texts:
I have just started out learning C++ and I am trying to write out a simple bills' dispenser machine as an exercise.

Upon user input, the system is to check if it can pay out the amount but only in 20 and 50 bills, and it should return with the minimum number of bills.

I need someone to point out and tell me if the following code I have wrote if it is viable (it seems to be working when I tested it myself, but that is too one sided). What about the structure?

There are 2 parts that I did - the first code simply by extending the main function while the latter is done by introducing the functions.

#include <iostream>
using namespace std;

int main()
{
    int inputAmt;

    cout << "This machine only dispense in $20 and $50 bills only" << endl;
    cout << "Enter in the amount to be withdraw : " << endl;
    cin >> inputAmt;

    // Decides the number of $50 bills to be dispense
    int fiftyBill;
    fiftyBill = inputAmt/50;

    int remainderAmt;
    remainderAmt = inputAmt - (fiftyBill*50);

    // Test the Remainder Amount if it is even
    int remE;
    remE = remainderAmt % 20;

    if (remE >= 10 || remE <= 20 )
    {
        // If it is not, reduced $50 by 1 and add it to the remainder amount
        fiftyBill = fiftyBill - 1;
        remainderAmt = remainderAmt + 50;
    }

    // Decides the number of $20 bills to be dispense
    int twentyBill;
    twentyBill = remainderAmt / 20;

    // Output Message
    cout << "Number of $50 bills : " << fiftyBill << endl;
    cout << "Number of $20 bills : " << twentyBill << endl << endl;

    cout << "Number of bills dispensed is " << fiftyBill + twentyBill << endl;

    int leftoverAmt;
    leftoverAmt = inputAmt - (fiftyBill * 50) - (twentyBill * 20);
    if (leftoverAmt != 0)
    {
        cout << "There are a leftover of $" << leftoverAmt << " that cannot be dispensed." << endl;
    }
}

Lastly, I tried to integrate 2 functions bool dispense (int amt) (returns true if the amount indicated can be dispensed in combinations of 20 and 50 bills, false otherwise) and int dispenseFif (int amt) (returns the number of 50 bills to dispense that will results in least number of notes being dispensed).

#include <iostream>
using namespace std;

bool canDispense (unsigned int amount);
int dispense50s (unsigned int amount);

int main()
{
    int inputAmt;
    cout << "This machine only dispense in $20 and $50 bills only" << endl;
    cout << "Enter in the amount to be withdraw : " << endl;
    cin >> inputAmt;

    canDispense(inputAmt);
}

bool canDispense (unsigned int amount)
{
    int fifAmt = dispense50s(amount);
    int remainderAmt;
    remainderAmt = amount - (fifAmt*50);

    // Test the Remainder Amount if it is even
    int remE;
    remE = remainderAmt % 20;
    cout << "remE : " << remE << endl << endl;

    if (remE >= 10 || remE >= 20 )
    {
        fifAmt = fifAmt - 1;
        remainderAmt = remainderAmt + 50;
    }

    // Decides the number of $20 bills to be dispense
    int twentyBill;
    twentyBill = remainderAmt / 20;

    int leftoverAmt;
    leftoverAmt = amount - (fifAmt * 50) - (twentyBill * 20);

    if (leftoverAmt == 0)
        {
            // Output Message
            cout << "(2) Number of $50 bills : " << fifAmt << endl;
            cout << "(2) Number of $20 bills : " << twentyBill << endl;

            cout << "(2) Number of bills dispensed is " << fifAmt + twentyBill << endl;
            return true;
        }
    else
        {
        cout << "The amount is impossible! Please try again... " << endl;
        return false;
        }

}

int dispense50s (unsigned int amount)
{
    // Decides the number of $50 bills to be dispense
    int fiftyBill;
    fiftyBill = amount/50;
    return fiftyBill;
}


texts:
I am still uncomfortable and new with working with classes.

I have made a User class that will return stuff about the user.

<?

class User {
    public function age($id) {
        $birth = new DateTime("$id");
        $now = new DateTime();
        $age = $now->diff($birth)->format("%y");
        return $age;
    }
    public function avatar($id) {
        $connect = Database::factory();

        $id = $id;
        $getQuery = $connect->prepare("SELECT photo_thumb FROM users_profile WHERE uID =:id");
        $getQuery->bindValue(":id", $id);
        $getQuery->execute();
        $show = $getQuery->fetch();
        $photoName = ((empty($show['photo_thumb'])) ? '' : $show['photo_thumb']);
        return $photoName;
    }
    public function fullname($id, $full = 1) {
        $connect = Database::factory();
        $query = $connect->prepare("SELECT firstname, lastname FROM users WHERE id =:id");
        $query->bindValue(":id", $id);
        $query->execute();
        $row = $query->fetch();

        $full_name = $row["firstname"]." ".$row["lastname"];
        return $full_name;
    }
    public function firstname($id) {
        $connect = Database::factory();
        $query = $connect->prepare("SELECT firstname, lastname FROM users WHERE id = '$id'");
        $query->execute();
        $row = $query->fetch();
        $firstname = $row["firstname"];
        return $firstname;
    }
    public function sex($id) {
        $connect = Database::factory();

        $query = $connect->prepare("SELECT sex FROM users WHERE id=:id");
        $query->bindValue(":id", $id);
        $query->execute();
        $row = $query->fetch();
        return $row["sex"];
    }
}

If you look through it fast, you will notice how everything is like the same, apart from its grabbing another column name and sometimes from another table.

Otherwise it just execute, fetches and returns.

I wonder if I can improve this code any way, so it looks cleaner and not so copy+paste like now..


texts: Writing and saving scraped documents in several sheets in an Excel file

texts:
I've written some code in Python for the purpose of scraping names and URLs from several links found in the left sided bar in a webpage and populate the data in several sheets (also giving each sheet a new name taking a customized portion from URL) in an Excel workbook so that things do not get messy and the data can be located separately. I tried to do the whole thing accurately and found it working great. It would be very nice if I get any better idea other than what I did here.

Here is what I tried with:

import requests
from lxml import html
from pyexcel_ods3 import save_data

web_link = "http://www.wiseowl.co.uk/videos/"
main_url = "http://www.wiseowl.co.uk"

def get_links(page):

    response = requests.Session().get(page)
    tree = html.fromstring(response.text)
    data = {}
    titles = tree.xpath("//ul[@class='woMenuList']//li[@class='woMenuItem']/a/@href")
    for title in titles:
        if "author" not in title and "year" not in title:
            get_docs(data, main_url + title)

def get_docs(data, url):

    response = requests.Session().get(url)
    tree = html.fromstring(response.text)
    for item in tree.xpath("//p[@class='woVideoListDefaultSeriesTitle']"):
        title = item.findtext('.//a')
        link = item.xpath('.//a/@href')[0]
        sheetname = url.split("videos/")[1].split("/")[1].split(".")[0]
        if sheetname in data:
            data[sheetname].append([title, str(link)])
        else:
            data[sheetname] = [[title, str(link)]]
    save_data("documents.ods", data)

if __name__ == '__main__':
    get_links(web_link)


texts:
I have one container div which contains some children div members. From time to time, I need to run a custom blinking effects on some of the child div members. The effect steps are as follows:

Change font color to Yellow
Pause for 0.5 secs
Change background color to yellow and text color to black
Pause for 0.25 secs
Change font color to Yellow & background to black
Pause for 0.25 secs
Change background color to yellow and text color to black
Pause for 0.5 secs
Repeat step 1 to 8

Below is the JavaScript code that I came up using jQuery to achieve the above effect. The code is working perfectly fine, but somehow I feel that this is not an elegant solution and there may be possible issue with how I pass $elements var from one function to another.

Is there anything wrong with this approach?  How can this code be improved?

function startAnimation($container) {
    var $elements = $container.find(".animation");
    if ($elements.length) {
        $elements.switchClass("mc-ylw-blk", "mc-blk-ylw", 0).show(0).delay(500).promise().done(function () {
            $elements.switchClass("mc-blk-ylw", "mc-ylw-blk", 0).delay(250).promise().done(function () {
                $elements.switchClass("mc-ylw-blk", "mc-blk-ylw", 0).delay(250).promise().done(function () {
                    $elements.switchClass("mc-blk-ylw", "mc-ylw-blk", 0).delay(500).promise().done(function () {
                            startAnimation($container);   //Repeat
                    });
                });
            });
        });
    }

}


texts: Flexible multiple string comparision to determine variable value

texts:
I've a web form that allows users to create clusters of three sizes: small, medium and large. The form is sending a string of small, medium or large to a message queue, were job dispatcher determines how many jobs (cluster elements) it should build for a given cluster, like that:

# determine required cluster size
if cluster['size'] == 'small':
    jobs = 3
elif cluster['size'] == 'medium':
    jobs = 5
elif cluster['size'] == 'large':
    jobs = 8
else:
    raise ConfigError()

While it works, its very ugly and non flexible way of doing it - in case I'd want to have more gradual sizes, I'd increase number of elif's. I could send a number instead of string straight from the form, but I dont want to place the application logic in the web app. Is there a nicer and more flexible way of doing something like that?


texts: Passing a large amount of diverse information in JSON using Symfony 2.1 and Doctrine 2

texts:
For a project I need to give a load of diverseinformation in JSON format. All the information will be used on the same page so a single call would result in the least overhead. The information all concerns the same database object and is all nescessary on the page. It basically is a collection of counts of the amount of objects that are of one or more of a certain type (the types are all booleans) and we require to know a lot of different variations of this. I used the code below but my co-worker believes the way I put it in the JSON list is a bit clunky and the code could be far more performant. How could I improve this code?

public function getContactsStatisticsAction()
{
    $response = new Response();
    $json = array();
    $em = $this->getDoctrine()->getEntityManager();
    $cr = $em->getRepository('BlaCoreBundle:Company');

    $json['numberOfCompanies'] = $cr->numberOfCompanies();
    $json['numberOfAccounts'] = $cr->numberOfCompanies(array("typeAccount" => true));
    $json['numberOfCompetitors'] = $cr->numberOfCompanies(array("typeCompetitor" => true));
    $json['numberOfSuppliers'] = $cr->numberOfCompanies(array("typeSupplier" => true));
    $json['numberOfOthers'] = $cr->numberOfCompanies(array("typeOther" => true));
    $json['numberOfUnassigned'] = $cr->numberOfCompanies(array("typeAccount" => false, "typeCompetitor" => false,"typeSupplier" => false,"typeOther" => false));

    $json['numberOfJustAccounts'] = $cr->numberOfCompanies(array("typeAccount" => true, "typeCompetitor" => false, "typeSupplier" => false));
    $json['numberOfJustCompetitors'] = $cr->numberOfCompanies(array("typeAccount" => false, "typeCompetitor" => false, "typeSupplier" => false));
    $json['numberOfJustSuppliers'] = $cr->numberOfCompanies(array("typeAccount" => false, "typeCompetitor" => false, "typeSupplier" => false));

    $json['numberOfCompetitorAndAccounts'] = $cr->numberOfCompanies(array("typeAccount" => true, "typeCompetitor" => true, "typeSupplier" => false));
    $json['numberOfCompetitorAndSuppliers'] = $cr->numberOfCompanies(array("typeAccount" => false, "typeCompetitor" => true, "typeSupplier" => true));
    $json['numberOfSupplierAndAccounts'] = $cr->numberOfCompanies(array("typeAccount" => true, "typeCompetitor" => false, "typeSupplier" => true));
    $json['numberOfCompaniesAndAccountsAndSuppliers'] = $cr->numberOfCompanies(array("typeAccount" => true, "typeCompetitor" => true, "typeSupplier" => true));

    $response->setContent(json_encode($json));
    return $response;
}

public function numberOfCompanies($filters = array())
{
    $qb = $this->getEntityManager()->createQueryBuilder();
    $qb->select('count(c.id)');
    $qb->from('BlaCoreBundle:Company', 'c');
    $sizeFilters = count ($filters);
    $keys = array_keys($filters);
    if($sizeFilters >= 1){
        $qb->where('c.' . $keys[0] . ' = ' . (int) $filters[$keys[0]]);
    }
    for($i = 1; $i < $sizeFilters; $i++){
        $qb->andWhere('c.' . $keys[$i] . ' = ' . (int) $filters[$keys[$i]]);
    }
    return $qb->getQuery()->getSingleScalarResult();
}


texts:
Problem: Given a vector of strings, I want to print out all possible permutations where the strings may contain an OR operator (the | character, as in regular expressions).

Example Input: the strings race and car|horse

Example Output:

race car
race horse
car race
horse race

This code uses -std=c++17 and helper code from other programmers (if this makes it off topic, I will recode these parts).

This is faster than the Python version from one of my questions on a sibling site.

Code:

#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

// Begin helper function from https://stackoverflow.com/a/236803/10976976
template <typename Out>
void split(const std::string &s, char delim, Out result) {
    std::istringstream iss(s);
    std::string item;
    while (std::getline(iss, item, delim)) {
        *result++ = item;
    }
}

std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    split(s, delim, std::back_inserter(elems));
    return elems;
}
// End helper function from https://stackoverflow.com/a/236803/10976976

// Begin helper function from https://stackoverflow.com/a/17050528/10976976
std::vector<std::vector<std::string>> cart_product (const std::vector<std::vector<std::string>>& v) {
    std::vector<std::vector<std::string>> s = {{}};
    for (const auto& u : v) {
        std::vector<std::vector<std::string>> r;
        for (const auto& x : s) {
            for (const auto y : u) {
                r.push_back(x);
                r.back().push_back(y);
            }
        }
        s = std::move(r);
    }
    return s;
}
// End helper function from https://stackoverflow.com/a/17050528/10976976

int main() {
    std::vector vector_of_strings{"C++|Python|PHP", "Is|Is Not", "Good|Great|Excellent|Exceptional"};
    std::vector<std::vector<std::string>> vector_of_vector_of_strings;

    for (auto& word_possibilities_string : vector_of_strings) {
        auto word_possibilities = split(word_possibilities_string, '|');
        vector_of_vector_of_strings.push_back(word_possibilities);
    }

    // vector_of_vector_of_strings is now {{C++, Python, PHP}, {Is, Is Not}, {Good, Great, Excellent, Exceptional}}

    auto sentences = cart_product(vector_of_vector_of_strings);

    for (auto& sentence : sentences) {
        std::sort(sentence.begin(), sentence.end());

        do {
            const auto seperator = " ";
            const auto* sep = "";

            for (const auto& word : sentence) {
                std::cout << sep << word;
                sep = seperator;
            }

            std::cout << "\n";
        } while(std::next_permutation(sentence.begin(), sentence.end()));
    }
}

Output (I'm sure you'll agree with the statements below):

C++ Good Is
C++ Is Good
Good C++ Is
Good Is C++
Is C++ Good
Is Good C++
...
Exceptional Is Not PHP
Exceptional PHP Is Not
Is Not Exceptional PHP
Is Not PHP Exceptional
PHP Exceptional Is Not
PHP Is Not Exceptional

In the future, I will be reading in vector_of_strings from a file and passing in the starting permutation as arguments.

For example: ./permutation_generator words.txt PHP Exceptional "Is Not" will output:

PHP Exceptional Is Not
PHP Is Not Exceptional


texts:
I have a myCon=getUnusedConnection() method that gets a connection from Connection pool. I also have a releaseConnection(myCon) method to release Connection to the pool after finishing using it.

When coding, I need to select data from the database many times.  I also want to reuse my code.  I want to have many methods for a single action.

Example:

public static List<String[]> getData(){
    Connection myCon=null;
    PreparedStatement preparedStmt=null;
    try{
        myCon=getUnusedConnection();
        String sql="select ........";
        preparedStmt=myCon.prepareStatement(sql);
        ResultSet results=preparedStmt.executeQuery();
        String str="";
        if(results.next()){
             str=results.getString(1);
        }
        if(!str.equals("")){
             List<String[]> list=getData2(myCon, preparedStmt, str);
        }
        return list;
    }
    catch (SQLException ex) {
        while (ex != null) {
            System.out.println ("SQL Exception:  " +
                              ex.getMessage ());
            ex = ex.getNextException ();
        }
    }catch (java.lang.Exception e) {
        System.out.println("***ERROR-->" + e.toString());
    }
    finally{
        releaseConnection (myCon);
        closeStatement (preparedStmt);
    }
    return null;
}

public static List<String[]> getData2(Connection myCon, PreparedStatement preparedStmt, String str){

     try{
         List<String[]> list=new ArrayList<String[]>();
         String sql="c.......";
         preparedStmt=myCon.prepareStatement(sql);
         ResultSet results=preparedStmt.executeQuery();
         while(results.next()){
             list.add(results.getString(1));
         }
         return list;
     }catch (SQLException ex) {
        while (ex != null) {
            System.out.println ("SQL Exception:  " +
                              ex.getMessage ());
            ex = ex.getNextException ();
        }
    }catch (java.lang.Exception e) {
        System.out.println("***ERROR-->" + e.toString());
    }
    finally {

        closeStatement(preparedStmt);
        releaseConnection(myCon);
    }
    return null;
}

Do I need to include try - catch - finally in getData2, since I am passing myCon and prepareStatement around?  I am not sure if this the right way to code.

Is the way I'm coding considered standard?  If not, do you have something better in mind?


texts:
Short problem description:

  A sequence of numbers are antiarithemtic if there exists no three
  numbers a_i, a_j, a_k – where a_i preceeds a_j which then again
  preceeds a_k in the sequence – such that a_i - a_j = a_j - a_k.
  Example: (5, 0, -1, 3, 1) is not antiarithemtic, because 5-3 =
  3-1, wheras the sequence (1, 5, 3, 0, -1) is antiarithemtic.

Link to the Kattis page.

My attempt:

import sys

lines = sys.stdin.readlines()
lines = [x[:-1] for x in lines]
for line in lines:
    if len(line) > 1:
        line = line.split(':')
        found = False
        visited = {}
        curr = line[1].split()
        r = len(curr)
        for i in range(r):
            visited_2 = {}
            if curr[i] in visited:
                continue
            else:
                visited[curr[i]] = True
                for j in range(i+1, r):
                    if curr[j] in visited_2:
                        continue
                    else:
                        visited_2[curr[j]] = True
                        tmp = int(curr[i]) - int(curr[j])
                        for k in range(j+1, r):
                            if int(curr[j]) - int(curr[k]) == tmp:
                                print("no")
                                found = True
                                break
        if not found:
            print("yes")
    else:
        break

I believe my attempt solves the problem of finding out whether a sequence is antiarithmetic or not, as I've made my own extensive example-set to test that. My optimizing step so far has been to include dictionaries of visited "nodes" so as to not repeat searches for numbers that we already know do not result in an arithmetic sequence. However, it is not fast enough for Kattis, so I would much appreciate any suggestions on how to improve this.


texts: Alternatives for appending a div from a JS object

texts:
I've built my first "real" web app which uses both server-side and client side functions to populate a list of courses a user can register for. Currently, the client receives an Object with the following structure:

Object

{
  "date": "1/1/2018",
  "time": "14:30",
  "title": "String Title 1",
  "desc": "A long string description with information about the workshop.",
  "cat": "Category 1, Category 2",
  "seats": "20",
  "type": "In Person",
  "location" : "Building A",
  "lock": true,
  "code": "ABCD",
  "hash": "Str1ng",
  "who": "Teachers, Admin"
} ...

Then, the client adds div elements built from the Object. I'm using .append() and inserting object keys at the correct point. It works fine, but I'm feeling like this is a really inefficient and frankly, messy, way to add the content.

Client script

var data = JSON.parse(Object);

$("#list").append(
    "
\
       " + data[j].time + "\
       " + data[j].date + ", \
       <input type='checkbox' name='wkshp' value='" + data[j].hash + "'/>\
       " + data[j].title + "\
       " + data[j].desc + "\

         " + data[j].location + "\
         " + data[j].who + "\
         " + data[j].cat + "\
         " + data[j].type + "\
         Seats: " + data[j].seats + "\

\

\

Registration Code
\
         <input type='text' name='code' value='' />

"
);

What improvements can I make to the Object? Is there a better way to parse the object by the client?


texts: Secure/Bulletproof Image Upload Using PHP

texts:
Here is my code that check and upload an image to my website.
Is this code really secure against uploading of malicious codes?
Anything I have to add to this code to  make it more secure?
I have also blocked execution of PHP in images folder using php_flag engine off in .htaccess of images folder, I can also move images folder out of the public_html (root) folder.
    <?php
if(isset($_POST['submit'])){
    // permenant variabes for upload
    $target_dir = "./images/";
    $allowed = array('jpg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif');
    $maximumsize=5000000000;
    //variables form file
    $filetempname=$_FILES["image"]["tmp_name"];
    $fileinfo = new finfo(FILEINFO_MIME_TYPE);
    $filemime = $fileinfo->file($_FILES['image']['tmp_name']);
    //check if error is set
    if(!isset($_FILES['image']['error']) ){
        echo 'Invalid upload.';
        die();
    }
    // check formultiple uploads and block
    elseif(is_array($_FILES['image']['error'])){
        echo 'Only one file allowed.';
        die();
    }
    //check for any upload error
    elseif($_FILES['image']['error']===0){
        // check image size
        if($_FILES["image"]["size"] > $maximumsize){
            echo 'File size exceed maximum size.';
            die();
        }
        $ext = array_search($filemime, $allowed, true);
        if(false !== $ext){
            //upload file by giving new name
            $newfilename = md5(uniqid('', true));
            $newfilename= $newfilename.'.'.array_search($filemime, $allowed);
            $target_file = $target_dir .$newfilename;
            if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
                echo "uploaded.";
            }
            //upload failed message
            else{
                echo "upload failed";
                die();
            }
        }
        // if file format is wrong
        else{
            echo "invalid file format";
            die();
        }
    }
    // if there is any upload error
    else{
        echo "error in upload";
        die();
    }
}
else{
    echo "not submited form properly";
}
?>

Do you have any suggestions to make this more secure or can you spot any flaws in this script that could be used by hackers to upload shell or PHP scripts?


texts:
I'm making an image-downloading app that sets the image as the device wallpaper. For this I used the class:

ImageDownloader.java

This class has a function which accepts a URL and an ImageView. It downloads and assigns the image found at the URL to the ImageView using an AsyncTask class defined within.

I managed to implement it as intended and wanted to extend its use to helping me set the devices wallpaper. This turned out to be pretty complicated but I managed with the following code in my MainActivity.java:

public class MainActivity extends Activity {
private final ImageDownloader mDownload = new ImageDownloader();
public static Bitmap bima=null;
public static WallpaperManager wm;

in onCreate:

 wm = WallpaperManager.getInstance(getApplicationContext());
    mDownload.download(url,imageView);

method defined in the MainActivity.Java:

public static void setbima(Bitmap bimu) {

    try {wm.setBitmap(bimu);} catch (Exception e) {}
}

Then I used my function in the ImageDownloader class' AsyncTask's onPostExecute like this:

MainActivity.setbima(bitmap);

Making use of the bitmap that was being passed to there by the AsyncTask class.

With the WallpaperManager object I wanted to make use of that bitmap, because its function .setBitmap() accepts bitmaps and puts the system wallpaper to that bitmap.

I am just wondering if my way of achieving this is optimal or is there a simpler way to have achieved this? It seems a very far-fetched way of doing this and I wouldn't be surprised if it is as I am a beginner programmer.


texts: Is the way I'm handling deck (card) generation the wisest way to do it?

texts:
My Deck Class:

(In case it isn't clear, a Card is just an object with two enums, one for suit and one for value).

I'm particularly proud of the readability of this little bit if I do say so myself.

public class Deck {

    private static Random random = new Random();

    private List<Card> cards = new ArrayList<Card>();

    Deck () {
        // Create one of each card to populate deck with.
        for (Card.Suit suit : Card.Suit.values()) {
            for (Card.Value value : Card.Value.values()) {
                Card card = new Card(value, suit);
                cards.add(card);
            }
        }
        // Shuffle multiple times to ensure randomness...
        this.shuffle();
        this.shuffle();
        this.shuffle();
    }

    public void shuffle() {
        List<Card> temp = new ArrayList<Card>();
        while(!cards.isEmpty()) {
            int randInt = random.nextInt(cards.size());
            temp.add(cards.remove(randInt));
        }
        cards = temp;
    }

    public void addCard(Card card) {
        cards.add(card);
    }

    public Card getNextCard() {
        return cards.remove(0);
    }

}

EDIT:

I revised the drawCard() method. What do you guys think?

public Card drawCard() {
    if(cards.isEmpty()) {
        System.err.println("Can't draw from an empty deck!");
        System.exit(-1);
    }
    return cards.remove(cards.size() - 1);
}


texts: Simple Producer-consumer implementation in Python

texts:
I implemented a simple solution to the Producer–consumer problem
 that I'd love for you to take a look at.

The producer simply adds random numbers to a queue and the consumer (from a separate thread) pops numbers off the queue and prints them. I'd specifically like feedback on the concurrency aspects of this implementation. Thanks!

from collections import deque
import random
import threading

TIMES = 100

class SafeQueue:
  def __init__(self, capacity):
    self.capacity = capacity
    self.queue = deque([])
    self.remaining_space = threading.Semaphore(capacity)
    self.fill_count = threading.Semaphore(0)

  def append(self, item):
    self.remaining_space.acquire()
    self.queue.append(item)
    self.fill_count.release()

  def consume(self):
    self.fill_count.acquire()
    item = self.queue.popleft()
    self.remaining_space.release()
    return item

class Producer:
  def __init__(self, queue, times=TIMES):
    self.queue = queue
    self.times = times

  def run(self):
    for _ in range(self.times):
      self.queue.append(random.randint(0, 100))

class Consumer:
  def __init__(self, queue, times=TIMES):
    self.queue = queue
    self.times = times

  def run(self):
    for _ in range(self.times):
      print(self.queue.consume())

def main():
  queue = SafeQueue(10)

  producer = Producer(queue)
  producer_thread = threading.Thread(target=producer.run)
  consumer = Consumer(queue)
  consumer_thread = threading.Thread(target=consumer.run)

  producer_thread.start()
  consumer_thread.start()

  producer_thread.join()
  consumer_thread.join()

if __name__ == "__main__":
  main()


texts: Determine if an input is an integer, a double or a String

texts:
I created a method to test whether the specified input is a double, int or String and then pass it to a 3rd party library which has the methods doFoo which accepts either a String, double or int. This is the method that I would like feedback on:

public static void testString(String val) {
    System.out.print("Original '" + val + "'  ");
    String x = val.trim();
    try {
        int i = Integer.parseInt(x);
        System.out.println("It's an integer: " + i);
        doFoo(i);
    } catch (NumberFormatException e) {
        try {
            double d = Double.parseDouble(x);
            System.out.println("It's a double: " + d);
            doFoo(d);
        } catch (NumberFormatException e2) {
            System.out.println("It's a String: " + x);
            doFoo(x);
        }
    }
}

Is this good code? Could it be improved? I don't like the throwing and catching of Exceptions.

Some test code to prove it works:

testString("N/A");
testString("19.");
testString("19.0");
testString("19.4");
testString("  1 ");
testString(" 1");
testString("1 ");
testString("1");
testString("    ");

Results in:

Original 'N/A'  It's a String: N/A
Original '19.'  It's a double: 19.0
Original '19.0'  It's a double: 19.0
Original '19.4'  It's a double: 19.4
Original '  1 '  It's an integer: 1
Original ' 1'  It's an integer: 1
Original '1 '  It's an integer: 1
Original '1'  It's an integer: 1
Original '    '  It's a String:


texts:
I am interesting in the topic of finite automata, so I started over by implementing a parking machine from this video: Computers Without Memory - Computerphile to understand conceptions. Didn't do much of an error checking - have made a minimal working version.

Short description of the task, but for better understanding watch the video:

You have the parking machine which is implemented by the finite automaton.
The parking lot costs 25 pence. The machine takes only 5, 10, 20 pence coins. Thus, any combination of these coins can be used to pay for parking.
After a sum of coins has reached 25 pence, the ticket is issued.
The machine gobble up all extra money above the 25 pence, like 20 + 20 pence = the ticket only, no change are given.

Questions:

What do you think about my approach?
Is it optimal, extendable, suitable for real world applications or this technique has limiting factors and an another should be used?
How would you implement this machine? It will be good to see another solutions.

It is possible to do this by such way: Explicit state transition table, may be I will do this also. My target is to implement something more serious like a regex engine in the future, but I should read some books/articles before.

#!/usr/bin/python3

def get_coin(current_sum, *functions):
    print(f"Current sum = {current_sum} pence")
    coin = int(input("Insert coin\n"))
    if coin == 5:
        functions[0]()
    elif coin == 10:
        functions[1]()
    elif coin == 20:
        functions[2]()
    else:
        error(current_sum, functions)

def error(current_sum, functions):
    print("Error: only 5, 10, 20 pence coins are allowed\n")
    get_coin(current_sum, *functions)

def zero_pence():
    get_coin("0", five_pence, ten_pence, twenty_pence)

def five_pence():
    get_coin("5", ten_pence, fifteen_pence, twenty_five_pence)

def ten_pence():
    get_coin("10", fifteen_pence, twenty_pence, give_ticket)

def fifteen_pence():
    get_coin("15", twenty_pence, twenty_five_pence, give_ticket)

def twenty_pence():
    get_coin("20", twenty_five_pence, give_ticket, give_ticket)

def twenty_five_pence():
    input("Current sum = 25 pence, press the 'return' button to pay")
    give_ticket()

def give_ticket():
    print("""\nTake your ticket:

Date: 1 November 2019
Start time: \t20:21
End time: \t22:21\n
""")

def parking_machine():
    prompt = """\n\tThe parking machine.

Information:
1. The machine takes 5, 10, 20 coins.
2. The machine doesn't give a change.
3. The parking costs 25 pence.

Press 's' button to start inserting of coins.

"""
    prompt = '#' * 80 + prompt + '#' * 80 + '\n'

    while True:
        button = input(prompt)
        if button == 's':
            zero_pence()

parking_machine()


texts: Client wrapper for sending data to a downstream process

texts:
I am building a Python client for an alert process engine. The users can use this client to publish and clear the alerts.
The client  exposes two methods publish and clear to the users. These methods accept some parameters which would define the alerts from the users and enriches them with a few more fields and validates it. But so far there is no logical validation needed other than the type checking of the fields input by the users. The scripts also converts this data to a json fromat. The json data will be sent to the downstream process. Before sending, this data will be validated against a json schema which I haven't implemented yet.
The client will be packaged as a library eventually and made available to the users. This is how the current version of the main script looks like.

# -*- coding: utf-8 -*-

"""Main module."""

from enum import Enum
import json
import datetime

class AlertStatus(Enum):
    OPEN = 0
    CLOSED = 1

class AlertSeverity(Enum):
    EXCEPTION = 1
    WARNING = 2
    NOTIFICATION = 3

class AlertRequest:
    def __init__(self, run_date, application_id, data_process_key):
        self.param_dict = {"run_date": run_date,
                           "application_id": application_id,
                           "data_process_key": data_process_key}

    def _to_json(self, input_dict):
        return json.dumps(input_dict)

    def prepare_to_publish(self, severity, **kwargs):
        self.param_dict["status"] = AlertStatus.OPEN.name
        self.param_dict["severity"] = severity
        self.param_dict["owner"] = kwargs.get("owner", None)
        self.param_dict["data"] = kwargs.get("data", None)
        self.param_dict["alert_links"] = kwargs.get("alert_links", None)
        self.param_dict["event_date_time"] = datetime.datetime.now().isoformat()
        return self._to_json(self.param_dict)

    def prepare_to_clear(self):
        """Update the status of alert to closed"""
        self.param_dict["status"] = AlertStatus.CLOSED.name
        return self._to_json(self.param_dict)

def publish(run_date, application_id, data_process_key, severity="WARNING", **kwargs):
    """
    :param run_date: Run date of the data process in a sring format specified in the json schema
    :param application_id:
    :param data_process_key:
    :param severity:
    A number of optional keyword arguments may be specified

    Owner     Two types - 1. functional group (research group or data owner)
                          and 2 a set of functional groups a user is interested in (data rotation)
    Data      Custom dictionary to specify any additional attributes.

    Alert Links  List of links for action or sourcing debug data for display in custom views
    :return:
    """
    alert_req_obj = AlertRequest(run_date, application_id, data_process_key)
    req_payload = alert_req_obj.prepare_to_publish(severity, **kwargs)
    print(req_payload)
    return True

def clear(run_date, application_id, data_process_key):

    alert_req_obj = AlertRequest(run_date, application_id, data_process_key)
    req_payload = alert_req_obj.prepare_to_clear()
    print(req_payload)
    return True

if __name__ == "__main__":
    publish('2019-07-01', 1234, 'alert')
    clear('2019-07-01', 1234, 'alert')

This is the first time I am trying to make use of the enum class in Python. But so far I don't think they are actually making the code better if not complicating it.
I would really appreciate some constructive criticism on the structure, design, the methods implemented or the approach. Please let me know how can I make this better.
The downstream process would be a REST end point or a queue. But the process expects that data is a valid json format. Is there a type checking needed in this case to ensure that the json is valid?


texts:
I'm making some helper functions for the (fairly simple) UI framework I'm developing, among them, a helper to run app initialization tasks. Here's a helper class I've developed for oneshot tasks:

from threading import Lock

class Oneshot():
    _running = False
    _finished = False

    def __init__(self, func, *args, **kwargs):
        self.func = func
        self.args = args
        self.kwargs = kwargs

    def run(self):
        if self.running or self.finished:
            return
        self.active_lock.acquire()
        self._running = True
        self.active_lock.release()

        self.func(*self.args, **self.kwargs)

        self.active_lock.acquire()
        self._running = False
        self._finished = True
        self.active_lock.release()

    @property
    def running(self):
        self.active_lock.acquire()
        value = self._running
        self.active_lock.release()
        return value

    @property
    def finished(self):
        self.active_lock.acquire()
        value = self._finished
        self.active_lock.release()
        return value

Is it actually thread-safe, as I intend it to be? Any other thoughts on this?

I'd also like to add a reset() method. My idea is like this:

def reset(self):
    if self.running:
        raise Exception("Runner can't be reset while still running")
    self._finished = False

My only doubt is about whether raising an exception is the best course of action, but, since I have to signal the user that they are trying to perform an illegal action, and it's better to do it explicitly as the action user desired did not complete, I don't see a better way - do you?


texts:
I have a list of checkboxes styled using JQuery UI as buttons. Each have a data-price attributem containing a price in this format: data-price="40.00", data-price="25.00" etc.

When the user "checks" a box, I am adding it's data-price to the totalPrice var. Every time another box is clicked, it's own data-price is added to the total. If the user unchecks a boxm, that value is taken away. I have tried to prevent the value from going under 0.00 as well.

I then output the totalPrice into a div - totalBox.

I imagine there are some optimisations here - any thoughts?


texts: Slicing and dicing images for Google Play

texts:
Making an Android app involves making a lot of images of various sizes:

The app's launcher icon, in high/low/medium resolution
Buttons, menu buttons, if any, in high/low/medium resolution
Images for listing on Google Play: main icon, feature graphics

To simplify this, I use high-resolution source images
+ ImageMagick to cut to the various sizes
+ Makefile to only regenerate the images whose source image has changed.

For the feature graphics I cheat:
I just generate a transparent canvas with the required dimensions,
and overlay on top of it the app's icon, as big as it fits.

src_dir:=src
hdpi_dir:=res/drawable-hdpi
ldpi_dir:=res/drawable-ldpi
mdpi_dir:=res/drawable-mdpi

names:=$(patsubst $(src_dir)/%,%,$(wildcard $(src_dir)/*.png $(src_dir)/*.jpg))
hdpi_target:=$(patsubst %,$(hdpi_dir)/%,$(names))
ldpi_target:=$(patsubst %,$(ldpi_dir)/%,$(names))
mdpi_target:=$(patsubst %,$(mdpi_dir)/%,$(names))

appicon:=googleplay/appicon.png
feature:=googleplay/feature.png
canvas:=googleplay/canvas.png
work:=googleplay/work.png

default: all

hdpi: $(hdpi_dir) $(hdpi_target)

ldpi: $(ldpi_dir) $(ldpi_target)

mdpi: $(mdpi_dir) $(mdpi_target)

googleplay: $(appicon) $(feature)

all: hdpi ldpi mdpi googleplay

clean:
    rm $(hdpi_target) $(ldpi_target) $(mdpi_target) $(appicon) $(feature)

$(hdpi_dir):
    @mkdir -p $@

$(ldpi_dir):
    @mkdir -p $@

$(mdpi_dir):
    @mkdir -p $@

$(hdpi_dir)/btn_%.png: $(src_dir)/btn_%.png
    convert -geometry 48x $< $@
    identify $@

$(ldpi_dir)/btn_%.png: $(src_dir)/btn_%.png
    convert -geometry 24x $< $@
    identify $@

$(mdpi_dir)/btn_%.png: $(src_dir)/btn_%.png
    convert -geometry 36x $< $@
    identify $@

$(hdpi_dir)/launcher_%.png: $(src_dir)/launcher_%.png
    convert -geometry 72x $< $@
    identify $@

$(ldpi_dir)/launcher_%.png: $(src_dir)/launcher_%.png
    convert -geometry 36x $< $@
    identify $@

$(mdpi_dir)/launcher_%.png: $(src_dir)/launcher_%.png
    convert -geometry 48x $< $@
    identify $@

$(appicon): $(src_dir)/launcher_main.png
    @mkdir -p $(@D)
    convert -geometry 512x $< $@
    identify $@

$(feature): $(src_dir)/launcher_main.png
    @mkdir -p $(@D)
    convert -size 1024x500 xc:transparent $(canvas)
    convert -geometry 1024x500 $< $(work)
    convert -composite $(canvas) $(work) -gravity west $@
    identify $@

If you want to play with this,
save this script as Makefile,
put an image file in src/launcher_main.png,
and assuming you have ImageMagick installed,
simply run make to have the images of various sizes generated in the res directory.
In Android projects I have res pointing to the real resources directory of the project.

This works well, but it's a bit repetitive at some places.
I'm wondering if this can be more DRY,
or if there are other ways to improve.


texts: Textual representation of a C++ function

texts:
I need to create an instance of Show of a somewhat complicated type that represents a C++ function. The "serialization" gives me a Haskell interpretation of the said function.

It works as I wish but it looks utterly horrible, with the string concatenations, point-free conversions and nested let bindings.  How could I improve readability of the code?

instance Show Function where
    show (Function templateArgs returnT fname fArgs) =
        let toLowerIfPolymorphic argName =
               let lcArg = strToLower argName in
                    if lcArg `elem` (map snd templateArgs)
                    then lcArg
                    else id argName in
        concat [
            fname, " :: (",
            intercalate ", " (
                filter (/="") . map (
                \(concept, tIdent) ->
                    if not $ elem concept ["Any", "typename", "class"]
                    then concept ++ " " ++ strToLower tIdent
                    else ""
                ) $ templateArgs
            ), ") => ",
            intercalate " -> " (
                map toLowerIfPolymorphic . map (show . fst) $ fArgs
            ),
            (if not $ null fArgs then " -> " else ""),
            toLowerIfPolymorphic . show $ returnT
        ]

The Function is:

data Function = Function {
                    funcTemplateArgs :: [(Concept, Identifier)],
                    funcReturnT      :: CppType,
                    funcName         :: String,
                    funcArgs         :: [(CppType, Identifier)]
                }

CppType is basically a sum-type representing Scalar and Parameterzied types. Just synonyms for tuples. Concept / Identifier is a String synonym. Everything is an instance of Show.

Also I find the if condition then f else id very strange. "Do nothing if false" is somewhat silly.


texts: Computing the RPY tensor with C++/Eigen (linear algebra)

texts:
I'm mostly used to writing scientific code in MATLAB / Python / Julia and my experience with C++ is very limited. I've implemented a fairly simple computation of the Rotne-Prager-Yamakawa tensor in dimensionless form using the Eigen library in C++11 (currently using the Visual Studio toolchain).

#include <iostream>
#include <random>
#include <chrono>
#include <Eigen/Dense>

using namespace Eigen;
using namespace std;
using namespace std::chrono;

MatrixXd rotne_prager(Vector3d coords[], double r, const int p)
{
    MatrixXd rpy = MatrixXd::Zero(3 * (p + 1), 3 * (p + 1));
    Vector3d rvec;
    double Rij;
    double distance_ratio;
    for (int i = 0; i < p + 1; i++)
    {
        for (int j = 0; j < p + 1; j++)
        {
            rvec(0) = coords[j](0) - coords[i](0);
            rvec(1) = coords[j](1) - coords[i](1);
            rvec(2) = coords[j](2) - coords[i](2);
            Rij = sqrt(rvec(0)*rvec(0) + rvec(1)*rvec(1) + rvec(2)*rvec(2));
            distance_ratio = r / Rij;
            if (Rij > 2 * r)
            {
                rpy.block<3, 3>(3 * (i + 1) - 3, 3 * (j + 1) - 3) = 0.75 * distance_ratio * (1.0 - 2.0*distance_ratio * distance_ratio) * rvec * rvec.transpose();
                rpy.block<3, 3>(3 * (i + 1) - 3, 3 * (j + 1) - 3).diagonal().array() += 0.75 * distance_ratio * (1.0 + 2.0 / 3.0 * distance_ratio * distance_ratio);
            }
            else
            {
                rpy.block<3, 3>(3 * (i + 1) - 3, 3 * (j + 1) - 3) = 3.0 / 32.0 / distance_ratio * rvec*rvec.transpose();
                rpy.block<3, 3>(3 * (i + 1) - 3, 3 * (j + 1) - 3).diagonal().array() += 1.0 - 9.0 / 32.0 / distance_ratio;
            }
        }
    }
    return rpy;
}

int main()
{
    random_device rd;
    mt19937 gen(rd());
    uniform_real_distribution<> dis(0, 1);
    Eigen::setNbThreads(8);

    auto start = high_resolution_clock::now();

    const int p = 4000;
    Vector3d coords[p + 1];
    for (int i = 0; i < p + 1; i++)
    {
        coords[i](0) = dis(gen); coords[i](1) = dis(gen); coords[i](2) = dis(gen);
    }
    MatrixXd rpy = rotne_prager(coords, 0.01, p);
    auto end = high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
    cout << "p = " << p << ", time elapsed: " << duration << " ms" << endl;
}

The code produces correct results, but I'm sure it could have been written much better. I'd appreciate any performance optimization tips as well as any suggestions about writing more idiomatic (insofar as that term even applies in the C++ world) and concise code.


texts:
I have implemented a simple dynamic vector library in C. It is a header-only library.

Full library listing -
void_vector.h:

#ifndef VOID_VECTOR_H
#define VOID_VECTOR_H

typedef enum {
    VV_SUCCESS,
    VV_MALLOC_FAILURE
} vv_err;

typedef struct vv {
    size_t length;
    size_t size;
    void *data[];
} void_vector;

void_vector* new_void_vector(size_t size);
vv_err vv_push(void_vector **vv, void *el);
void *vv_pop(void_vector *vv);
const void* vv_read_index(void_vector *vv, size_t index);
void delete_void_vector(void_vector *vv, void (del_el)(void*));

#ifdef VOID_VECTOR_IMPL
#undef VOID_VECTOR_IMPL

#include <stdlib.h>

#define defualt_size 16ul

void_vector*
new_void_vector(size_t size)
{
    if (!size) size = defualt_size;
    void_vector* vv = malloc(sizeof(void_vector) + sizeof(void*) * size);
    if (vv) {
        vv->size = size;
        vv->length = 0;
    }
    return vv;
}

vv_err
vv_push(void_vector **vv, void *el)
{
    if ((*vv)->length >= (*vv)->size) {
        void_vector *new_vv = realloc((*vv), sizeof(void_vector)
                                            + sizeof(void*) * (*vv)->size * 2);
        if (!new_vv) return VV_MALLOC_FAILURE;
        (*vv) = new_vv;
        (*vv)->size *= 2;
    }
    (*vv)->data[(*vv)->length] = el;
    (*vv)->length++;
    return VV_SUCCESS;
}

void*
vv_pop(void_vector *vv)
{
    if(vv->length == 0) return NULL;
    vv->length--;
    return vv->data[vv->length];
}

const void*
vv_read_index(void_vector *vv, size_t index)
{
    if (index > vv->length) return NULL;
    return (vv->data[index]);
}

void
delete_void_vector(void_vector *vv, void (del_el)(void*))
{
    if (!del_el) del_el = &free;
    for (int i = vv->length; i; i--) {
        del_el(vv->data[i-1]);
    }
    free(vv);
}

#endif /* VOID_VECTOR_IMPL */
#endif /* VOID_VECTOR_H */

I am using this as test bench - void_vector_tb.c

#include <stdio.h>

#define VOID_VECTOR_IMPL
#include "void_vector.h"

int
main (int argc, char **argv)
{
    void_vector* vv = new_void_vector(4);

    char *strings[10];

    for (int i = 0; i < 10; i++) {
        strings[i] = malloc(32);
        snprintf(strings[i], 32, "This is String: %d", i);
    }

    for (int i = 0; i < 10; i++) {
        vv_push(&vv, strings[i]);
    }

    for (int i = 0; i < vv->length; i++) {
        printf("%d:\t%s\n", i+1, vv_read_index(vv, i));
    }

    char *s;
    while(s = (char*) vv_pop(vv)) {
        printf("%s\n", s);
    }

    for (int i = 0; i < 10; i++) {
        vv_push(&vv, strings[i]);
    }

    delete_void_vector(vv, NULL);
}

I am not using a make file. Compilation is performed by gcc -ggdb void_vector_tb.c -o void_vector_tb

I would greatly appreciate your time and any comments but I'm particularly interested in the following points:

Am I doing anything dangerous in this?
Is the code clear, what can I do to make it easier to follow?
Is there an obvious way to greatly improve the efficiency?
General style comments
I'm not overly concerned about the contents of void_vector_tb.c.

I ran this through valgrind and got the following output:

==7009== HEAP SUMMARY:
==7009==     in use at exit: 0 bytes in 0 blocks
==7009==   total heap usage: 14 allocs, 14 frees, 1,616 bytes allocated
==7009==
==7009== All heap blocks were freed -- no leaks are possible
==7009==
==7009== For counts of detected and suppressed errors, rerun with: -v
==7009== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

I am trying to minimize use of external libraries (although I don't think it would be possible to avoid stdlib.h).


texts: This program reads in integers until a sentinel number is read. And prints the largest integer read

texts:
I'm just looking for feedback on how I could improve this simple program. Whether it be comments for better understanding or better variable names. I try not to focus on memory consumption because I'm honestly not that knowledgeable as of yet. My main focus is getting a written solution on paper and then implement in syntax.

I was given the question to write a program that reads in integers one per line, once a sentinel integer is read end program, and display the largest integer. The way I solved it was with pen and paper first because I'm working on my pseudocode and algorithm design. If there are any books on the subject for recommendation. I would greatly appreciate.

/**
 * This program reads in integers until a sentinel number is read,
 * and prints the largest.
 *
 * @author shawn
 *
 */

//Import needed for Console Programs.
import acm.program.*;

public class LargestListValue extends ConsoleProgram {
    public void run() {

        /*Integer variables to track the current largest input
         * and current input.
         */
        int x, y;

        println("This program reads in integers until a sentinel number is read, ");
        println("and prints the largest.");

        while (true) { //Initial while to read in an initial integer.
            x = readInt(" ? "); //Initial read integer. Also current largest.
            if (x == SENTINEL_NUMBER) {
                println("No numbers?");
                break;
            }
            else {
                y = readInt(" ? "); //Next read integer.
                if (y == SENTINEL_NUMBER) {
                    println("Largest number is " + x + ".");
                    break;
                } else {
                    while (y <= x) { //While second read integer
                        y = readInt(" ? ");
                        if (y == SENTINEL_NUMBER) {
                            println("Largest number is " + x + ".");
                            break;
                        } else if (y >= x) {
                            while (y >= x) {
                                x = readInt(" ? ");
                                if (x == SENTINEL_NUMBER) {
                                    println("Largest number is " + y + ".");
                                    break;
                                } else if (y <= x) break;
                            }
                        }
                    }
                }
            }
            //Extra break added to the
            break;
        }
    }
    //Sentinel number to end reading integers and print largest.
    private static final int SENTINEL_NUMBER = 0;
}


texts: Python object-oriented pipe cooling simulations

texts:
Here is my code simulating liquid in a pipe cooling under different conditions. How did I do approaching this in an object orientated way? Is there any way I can improve this code?

import numpy as np
import scipy
from scipy.optimize import minimize
from matplotlib import pyplot as plt

class pipeSimulator:
    R_w = 0.654#  W/mk water heat loss ocefficient
    # R_w = 0.028# W/mk air heat loss ocefficient
    R_f = 0.042  #  W/mk pipe heat loss coefficient
    inner_radius = 0.2  #  m pipe radius
    T_0 = 50  #  C initial temperature
    T_a = 20  #  C ambiant temperature
    dx = 0.01  #  m differential distance
    Length = 25  # m length of pipe

    def heat_balance(self,T_1,T_2):
       heat_in = (T_1-T_2) * scipy.pi * self.inner_radius**2 * self.R_w
       heat_out = ( (T_1 + T_2) / 2 - self.T_a ) * 2 * self.inner_radius * scipy.pi * self.dx * self.R_f
       return abs(heat_in-heat_out)

    def simulation(self):
       T = [self.T_0]
       X = [0]
       for x in np.arange(self.dx,self.Length,self.dx):
         X.append(x)
         fun = lambda s: self.heat_balance(T[-1],s)
         T.append(float(minimize(fun,T[-1]-self.dx,method="SLSQP")['x']))
       return([T,X])

trial = pipeSimulator()
trial.Length = 30
diameters = [0.02,.2,1,3]
R_values = [100,400]
T_a_values = [20]
cols = ['red', 'blue', 'black', 'purple', 'brown']
mylines = ['-','--','-.',':']
i=0
labs = []
for rval in R_values:
    trial.R_f = 1.0/rval
    for dval in diameters:
         trial.inner_radius = dval/2.0
         for tval in T_a_values:
              trial.T_a = tval
              ans = trial.simulation()
              plt.plot(ans[1],ans[0],c=cols[i%len(cols)],ls=mylines[i%len(mylines)],lw=2*(i%len(mylines)+1))
              labs.append(str(rval)+' R-value (EU), '+str(dval)+' meter diameter, '+str(tval)+" degree C ambient")
              i+=1

plt.legend(fontsize=20,title='',labels=labs,prop={'size':12},loc=3)
plt.xlabel('Distance (m)',fontsize=20)
plt.ylabel('Average Temperature (C)',fontsize=20)
plt.show()


texts: function for PDO queries and return result - tested - any tips?

texts:
I write a function using PHP and MySQL, to get PDO connection, query and array of placeholders to execute query and return result.
I test this function and it has good response when result for SELECT has empty result or has error; do you see any problems, or have tips to say about this?
Do you have any tips about this to test or check?
Function and test code
function db_query_pdo( PDO $pd, $q,$ar )
    {

//      $pd Pdo connection object, $q query string ,  $ar array of placeholders
      try
       {
            $stmt = $pd->prepare($q);
            $x=$stmt->execute($ar);
            $rs=$stmt->fetchAll();

            if(!empty($rslt))
                return $rslt;
            else
                return $x;
        }
        catch (Exception $ex)
        {
            echo 'Query failed';
//            exit(); uncomment this lines if needed in future

//    echo $ex->getCode();
//    echo $ex->getMessage();
//    throw $ex;
        }

    }
// TEST CODE
$pdo_cnctn=db_con_pdo(); // is a pdo connection function that worked correctly and return connection object
    $id=133;
    $id2=77;

$query='SELECT * FROM `users` WHERE u_id=:uid OR u_id=:uid2;
';
$vals=[
    'uid' => $id,
    'uid2' => $id2
];

    $res= db_query_pdo($pdo_cnctn,$query,$vals);
//$res[] = $stmt->fetch();
    if(!is_bool($res))
    {
        var_dump($res);
    }
    else
    {
       // $$pdo_cnctn->rollBack();
        echo 'Not Found';
        goto  end_point;
    }

    //some codes
    end_point:


texts: C# enumerable property like .Any that accounts for nulls

texts:
Brief Description:

A generic extension method that performs the same function as IEnumerable.Any(), but does not throw an error when passed a parameter with a null value.

Explanation:

Often times I will come across code that performs two steps on a nullable collection to make sure it contains elements. The first step checks to make sure the collection is not null, then the second step looks to see that there are greater than zero elements.

For example, to make sure a List<T> meets these qualifications before working through each element, code might look like this:

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

if (
    intList != null &&
    intList.Any()
    )
{
    foreach (int intElement in intList)
    {
        // logic here
. . .

To reiterate, just using .Any() above would be insufficient for the situation where intList hasn't yet been initialized.

Because this is a common occurrence in the code I maintain, I've come up with a generic extension method that performs the same function as the above, in one method:

static class CLR
{
    public static bool Populated<TSource>(this IEnumerable<TSource> source)
    {
        return source != null && source.Any();
    }
. . .

... which renders the first block a little simpler:

if (intList.Populated())
{
    foreach (int intElement in intList)
    {
        // logic here
. . .

Are there suggestions for why this should not be implemented, or why it should be implemented in a different form?


texts:
Introduction

I've written a simple command line todo-list in Haskell.

The full code can be found here. However, given people's time constraints, I have selected three verbose functions for review.

Function One

program :: StateT TodoList IO ()
program = do
    StateT $ \xs -> do
        (choice,_) <- runStateT requestChoice xs
        (_,xs') <- runStateT (parseChoice choice) xs
        runStateT printList xs'
        runStateT program xs'

main = runStateT program []

Questions:

Am I repeating myself too much by extracting the monads using runStateT?
Is there a better way to structure the main program?

Function Two

parseChoice :: Text -> StateT TodoList IO ()
parseChoice choice
    | first == "add" = addItem $ TodoItem second third
    | first == "remove" = removeItem $ parseInt second
    | first == "save" = saveList second
    | first == "load" = loadList second
    | first == "quit" = StateT $ \_ -> exitSuccess
    | otherwise = invalidChoice first
    where   args =  split (=='|') (toLower choice)
        first = head args
        second = if length args > 1 then args !! 1 else ""
        third = if length args > 2 then args !! 2 else ""

Questions:

Am I using too many guards?

Function Three

removeItem :: Maybe Int -> StateT TodoList IO ()
removeItem mn = StateT remove
    where remove = \xs -> case mn of
        Just n -> if n <= length xs - 1
            then return ((),removeAt n xs)
            else do
                S.putStrLn "Index too large"
                return ((),xs)
        Nothing -> do
            S.putStrLn "Invalid index entered"
            return ((),xs)

General Questions

Which parts are un-idiomatic?
Which parts are superfluous?
Should I decompose these longer functions into smaller functions that do less?
How else can I improve this code?


texts:
Challenge

  Using the C++ language, have the function PentagonalNumber(num) read num which will be a positive integer and determine how many dots exist in a pentagonal shape around a center dot on the Nth iteration. For example, in the image below you can see that on the first iteration there is only a single dot, on the second iteration there are 6 dots, on the third there are 16 dots, and on the fourth there are 31 dots.

  Your program should return the number of dots that exist in the whole pentagon on the Nth iteration.

  Sample Test Cases

Input:2
Output:6

Input:5
Output:51

I found it weird that Coderbyte called this a hard challenge. It works, but is this the right approach?

Header File

#ifndef PentagonalNum_hpp
#define PentagonalNum_hpp

#include <stdio.h>

class PentagonalNum
{
public:
    PentagonalNum(int N);
    unsigned long long int num_Of_Dots();
private:
    int iteration;
};
#endif /* PentagonalNum_hpp */

CPP File

#include "PentagonalNum.hpp"

PentagonalNum::PentagonalNum(int N)
: iteration(N)
{
}

unsigned long long int PentagonalNum::num_Of_Dots()
{
    int result = 1;
    int num = 5;

    for (int i = 1; i < iteration; ++i)
    {
        result += num;
        num += 5;
    }
    return result;
}


texts: Define if post extract from a bilingual Facebook page are in English using Python

texts:
I am currently extracting post on a biligual page on Facebook. Therefore, I have the problem of splitting the post in French and english before starting analysing them. I have construct a function which permit me to filter the sentence in english from all my sentence.

However it is quite complex and not accurate..

### import enchant
import nltk
### nltk.download()
### from nltk.corpus import words
from nltk.corpus import brown
import pandas as pd
import numpy as np
import re
  ### pop is an example of posts...

pop = ['hi','say','bonjour mister','sauf','tu am      belle','I suis cool','Worst trip ever je deteste AirTransat! ce sont les pires']

### Defining my function

def Extract_sentence_english(list_of_sentence):

    ### Removing punctuation, numeric and whitespace at the same time
    list_of_sentence = [re.sub(r'[^A-Za-z]+', ' ', x) for x in list_of_sentence]
    ### To lower
    list_of_sentence = map(lambda x: x.lower(), list_of_sentence)

    ### Split the list into words (splitting on space)
    split_list = [y for x in list_of_sentence for y in x.split(' ')]
    ### Return a logical value (True if English, False if other)
    log = []
    for i in range(0,len(split_list)):
        k = split_list[i] in words.words()
        log.append(k)
    ### log contain the logical value for the words
    ### Number of words per sentence
    df=[]
    for entry in list_of_sentence:
        df.append(len(entry.split()))

    df = pd.DataFrame(df)
    df.columns = ['number_of_words']

    df['index'] = range(0,len(df))

    dat = pd.DataFrame(df.loc[np.repeat(df.index.values,df['number_of_words'])])
    dat['logical'] = log
    dat['log_num'] = dat['logical'].astype(int)

    df['English_words_freq'] = dat.groupby(['index'], as_index = False).sum()['log_num']/df['number_of_words']
    final = pd.DataFrame(list_of_sentence)
    final['logical'] = df['English_words_freq'] > 0.75
    return(final)

Extract_sentence_english(pop)

Does somebody know any better way of doing this ?


texts: T-SQL query Choose name of clients, concluded more than one loan agreement in 2010

texts:
QUESTION: Choose the name of clients,
concluded more than one loan agreement in 2010,
as the numbers and dates of issue of these contracts.
Sort by name of the client and date of issue of the loan.

My question: Is it the correct way of solving this task?
Sqlfiddle: http://www.sqlfiddle.com/#!18/c140c/1

DDL:

create table client(
    cl_id int primary key identity (1,1),
    cl_full_name nvarchar(100) not null,
);

create table deal(
    dl_id int primary key identity (1,1),
    dl_client_id int not null,
    dl_code nvarchar(100) not null,
    dl_valutation_date datetime not null,
    foreign key(dl_client_id) references client(cl_id)
);

QUERY:

SELECT  c.cl_full_name                      AS "ФИО Клиента",
        d2.dl_code                          AS "Номер договора",
        Cast(d2.dl_valutation_date AS DATE) AS "Дата выдачи"
FROM (
        SELECT d.dl_client_id
        FROM   deal AS d
        WHERE  Year(d.dl_valutation_date) = 2010
        GROUP  BY d.dl_client_id
        HAVING Count(*) > 1
) AS t1
INNER JOIN deal AS d2
        ON d2.dl_client_id = t1.dl_client_id
INNER JOIN client AS c
        ON c.cl_id = d2.dl_client_id
ORDER  BY c.cl_full_name,
        d2.dl_valutation_date


texts:
I have this method that will give a random prime for a given range (min inclusive an max not inclusive) all comments are welcome:

public static int randomPrime(int min, int max) {
    if (min < 0)
        throw new IllegalArgumentException("min must be positive.");
    if (min >= max)
        throw new IllegalArgumentException("min must be smaller the max.");
    if (!containsPrime(min,max))
        throw new IllegalArgumentException("no Primes in this interval.");
    if (rand == null) {
        rand = new Random();
    }
    int out = rand.nextInt(max - min) + min;
    while (!isPrime(out)) {
        out = rand.nextInt(max - min) + min;
    }
    return out;
}
    private static boolean containsPrime(int min, int max) {
    if (isPrime(min)||isPrime(max-1)){
        return true;
    }
    if(min%2==0){
        min +=1;
    }
    while (min<max){
        if (isPrime(min)){
            return true;
        }
        min +=2;
    }
    return false;
}


texts:
I'm wondering how to "beautify"/"simplify" this code:

function handleKeyDown (e) {
  if (e.key === 'Enter') {
    e.preventDefault()
    myCustomEvent(e)
    return
  }
  if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
    e.preventDefault()
    e.key === 'ArrowDown'
      ? document &&
        document.activeElement &&
        document.activeElement.nextElementSibling &&
        document.activeElement.nextElementSibling.focus()
      : document &&
        document.activeElement &&
        document.activeElement.previousElementSibling &&
        document.activeElement.previousElementSibling.focus()
  }
}

It seems too verbose to me. Is there something I'm doing wrong? How can I write it better?


texts: Deep copy linked list with arbitrary nodes

texts:
The original question can be found here.

I implemented method 2:

Please comment about style, unit testing, code complexity, time and memory space and complexity.

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

namespace ConsoleApplication2
{
    public class LinkedListArbitraryPointer
    {
        public ArbNode Root { get; set; }

        public ArbNode DeepCopyLinkedList(ArbNode root)
        {
            if(root ==null)
            {
              return null;
            }

            //1) Create the copy of node 1 and insert it between node 1 & node 2 in original Linked List, create the copy of 2 and insert it between 2 & 3..
            //Continue in this fashion, add the copy of N afte the Nth node
            ArbNode temp = root;
            while (temp != null)
            {
                ArbNode swap = temp.Next;
                temp.Next = new ArbNode(temp.Index);
                temp.Next.Next = swap;
                temp = temp.Next.Next;
            }

            // 2) Now copy the arbitrary link in this fashion
            //  original->next->arbitrary = original->arbitrary->next;  /*TRAVERSE TWO NODES*/

            temp = root;
            while (temp != null)
            {
                temp.Next.Arb = temp.Arb.Next;
                temp = temp.Next.Next;
            }

            //3) Now restore the original and copy linked lists in this fashion in a single loop.
            temp = root;
            ArbNode current = root.Next;
            ArbNode storeList = root.Next;
            while (temp != null)
            {
                temp.Next = temp.Next.Next;
                if (current.Next != null)
                {
                    current.Next = current.Next.Next;
                }
                temp = temp.Next;
                current = current.Next;
            }

            return storeList;
        }

    }

    public class ArbNode
    {
        public ArbNode(int index)
        {
            Index = index;
            Next = null;
            Arb = null;
        }

        public ArbNode()
        {
            Next = null;
            Arb = null;
        }
        public int Index { get; set; }
        public ArbNode Next { get; set; }
        public ArbNode Arb { get; set; }
    }
}

Unit Test

using System;
using System.Linq;
using ConsoleApplication2;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTests
{
    [TestClass]
    public class LinkedListArbPointerUnitTest
    {
        [TestMethod]
        public void TestMethod1()
        {
            LinkedListArbitraryPointer list = new LinkedListArbitraryPointer();

            list.Root = new ArbNode(1);

            list.Root.Next = new ArbNode(2);

            //2->1
            list.Root.Next.Arb = list.Root;

            list.Root.Next.Next = new ArbNode(3);

            //1 -> 3
            list.Root.Arb = list.Root.Next.Next;

            list.Root.Next.Next.Next = new ArbNode(4);

            //4->3
            list.Root.Next.Next.Next.Arb = list.Root.Next.Next;

            list.Root.Next.Next.Next.Next = new ArbNode(5);

            //5->2
            list.Root.Next.Next.Next.Next.Arb = list.Root.Next;

            //3->5
            list.Root.Next.Next.Arb = list.Root.Next.Next.Next.Next;
            //var res = list.DeepCopyLinkedListWithAuxArray(list.Root);
            var res = list.DeepCopyLinkedList(list.Root);
            Assert.AreEqual(1,res.Index);
            Assert.AreEqual(3, res.Arb.Index);
        }
    }
}


texts:
First I create a .tar of the root directory with all the file permissions saved and excluding all irrelevant directories (are these the right folders to be excluding?).

sudo tar -cvpzf /HDD/systemBackup/backup.tar.gz --one-file-system --exclude=/HDD --exclude=/NAS --exclude=/proc exclude=/tmp --exclude=/mnt --exclude=/dev --exclude=/sys /

Then the .tar is split into smaller files of 100mb for easier upload efficiency.

split -b 100MB /HDD/systemBackup/backup.tar.gz "/HDD/systemBackup/$date-"

Then I upload the parts to the Internet.

I am looking to optimise ease of restoration and speed efficiency (ignoring (to some extent) the speed of the upload to the Internet).

Will this method also work on both a Raspberry Pi and an Ubuntu system?

Is this a good method of backing up my Linux system to the web?


texts: Accessing fields in LINQ query for customers with overdue balances

texts:
Practicing my autodidactism using a free Kindle Unlimited book to get myself acquainted with the basics of C# in hopes of getting enough of a foundation to get into automation and I still feel a little wibbly on the best practices, etc and I just feel like I could've been a bit more elegant than what I enacted with the get; set; but I don't know what I don't know.

"C#: Learn C# in One Day and Learn it Well" in this instance. Which, I've exceeded a day by far... anyways, I've been challenging myself to use what I have learnt in prior chapters to unravel and actively enact theoretical applications in the book without any actual 'code-alongside' snippets when they rear their head.

I'm current learning about var and their usage in using LINQ queries which is fairly easy as I've prior experience in SQL but I feel like I've inelegantly accessed/set the values for what cust.Balance and cust.Name are pulling in the code with the get; set; in the snippet below and feel like there's some way to have accessed them without actively creating another set of public strings.

Is there a better way to have executed this?

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

    namespace LinqTut2
    {
        class Program
        {
            static void Main(string[] args)
            {
                List<Customer> customers = new List<Customer>();

                customers.Add(new Customer("Alan", "80911291", "ABC Street", 25.60m));
                customers.Add(new Customer("Bill", "19872131", "DEF Street", -32.10m));
                customers.Add(new Customer("Carl", "29812371", "GHI Street", -12.2m));
                customers.Add(new Customer("David", "78612312", "JKL Street", 12.6m));

                var overdue =
                    from cust in customers
                    where cust.Balance < 0
                    orderby cust.Balance ascending
                    select new { cust.Name, cust.Balance };

                foreach (var cust in overdue)
                    Console.WriteLine("Name = {0}, Balance = {1}", cust.Name, cust.Balance);
                Console.ReadLine();
            }
        }

        class Customer
        {
            private string CustName;
            private string CustPhone;
            private string CustAddress;
            private decimal CustBalance;

            public decimal Balance
            {
                get
                {
                    return CustBalance;
                }
                set
                {
                    CustBalance = value;
                }
            }
            public string Name
            {
                get
                {
                    return CustName;
                }
                set
                {
                    CustName = value;
                }
            }

            public Customer(string name, string phn, string addr, decimal         bal)
            {
                CustName = name;
                CustPhone = phn;
                CustAddress = addr;
                CustBalance = bal;
            }

        }
    }


texts:
I have created a custom web server control that will have a bool property 'RenderAsLabel' so that I can convert TextBoxes to Labels, for read-only forms. I was wondering if there is any reason why this code should not be safe, or work as intended. Upon initial testing it seems fine, but I just want to make sure I'm not doing something that will end up causing issues.

namespace OrmControlLibrary
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:OrmTextBox ID='' runat=server ></{0}:OrmTextBox>")]
    public class OrmTextBox : TextBox
    {
        private Label lbl;
        public virtual bool RenderAsLabel
        {
            get
            {
                if (ViewState["OrmTextBox"] == null)
                {
                    return false;
                }
                else
                {
                    return (bool)ViewState["OrmTextBox"];
                }
            }
            set
            {
                ViewState["OrmTextBox"] = value;
            }
        }

        protected override void Render(HtmlTextWriter w)
        {
            if (RenderAsLabel)
            {
                SetLabelProperties();
                lbl.RenderControl(w);
            }
            else
            {
                base.Render(w);
            }
        }

        private void SetLabelProperties()
        {
            lbl = new Label();
            lbl.ID = this.ID;
            lbl.CssClass = this.CssClass;
            lbl.Text = this.Text;
        }
    }
}


texts: A non-recursive tuple_element implementation

texts:
This is basically a non-recursive std::tuple_element implementation.

Note

To make this non-recursive, you must replace std::make_index_sequence with a non-recursive implementation. I left it with std::make_index_sequence in order to reduce the amount of unrelated code.

How it works

deduct has a specialization of deduct_impl that is generated from the index sequence template argument it receives. It is used in order to deduce the type at index in a variadic type template or tuple. It uses the itp_base and itp types.

itp<std::size_t> and itp<std::size_t, T> is an index-type-pair used to expand the variadic indices template with a type variadic template in order to match the generated specialization.

deducer puts it all together by specializing deduct and deduct_impl by using std::conditional_t to generate the correct specialization.

Basically, for std::tuple<void, int, char>, in order to get the type at index 1, it creates itp_base<0>, itp<1, int>, itp_base<2> and passes it to deduct and deduct_impl.

Source code

#include <utility>
#include <tuple>

template <std::size_t index>
struct itp_base {};

template <std::size_t index, typename T>
struct itp : itp_base<index> {};

template <std::size_t index, typename IndexSequence>
struct deduct;

template <std::size_t index, std::size_t... indices>
struct deduct<index, std::index_sequence<indices...>>
{
    template <typename Tuple>
    struct deduct_impl;

    template <typename T, typename... R>
    struct deduct_impl<std::tuple<itp_base<indices>..., itp<index, T>, R...>>
    {
        using type = T;
    };
};

template <std::size_t index, typename... Types>
class deducer
{
private:
    static_assert( index < sizeof...( Types ), "deducer::index out of bounds" );

    template <typename IndexSequence>
    struct deducer_impl;

    template <std::size_t... indices>
    struct deducer_impl<std::index_sequence<indices...>>
    {
        using type = typename deduct<index, std::make_index_sequence<index>
        >::template deduct_impl
        <
            std::tuple
            <
                std::conditional_t
                <
                    std::is_base_of<itp_base<indices>, itp<index, Types>>::value,
                    itp<index, Types>,
                    itp_base<indices>
                >...
            >
        >::type;
    };

public:
    using type = typename deducer_impl<
        std::make_index_sequence<sizeof...( Types )>>::type;
};

Convenience aliases

template <std::size_t index, typename Tuple>
struct tuple_element;

template <std::size_t index, typename... Types>
struct tuple_element<index, std::tuple<Types...>> : deducer<index, Types...> {};

template <std::size_t index, typename... Types>
using tuple_element_t = typename tuple_element<index, Types...>::type;

Test case

#include <iostream>
#include <string>

int main()
{
    using tuple_t = std::tuple<int, void, std::string>;
    static_assert( std::is_same<tuple_element_t<2, tuple_t>, std::string>::value, "!" );
}

Demo

http://coliru.stacked-crooked.com/a/16805356d2578d6d


texts:
I have an image cropper that crops the uploaded image, Before sending it to the server using PHP and AJAX.

Here is a live fiddle to preview a working cropping example.

Here is the code:

// Create cropped part.
function getRoundedCanvas(sourceCanvas) {
  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');
  var width = sourceCanvas.width;
  var height = sourceCanvas.height;
  canvas.width = width;
  canvas.height = height;
  context.imageSmoothingEnabled = true;
  context.drawImage(sourceCanvas, 0, 0, width, height);
  context.globalCompositeOperation = 'destination-in';
  context.beginPath();
  context.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, 2 * Math.PI, true);
  context.fill();
  return canvas;
}

// On uploading a file
$("#input").on("change", function(e) {
  var _URL = window.URL || window.webkitURL,
      file = this.files[0],
      image = new Image();
  image.src = _URL.createObjectURL(file);
  image.onload = function(e) {
    var image = document.getElementById('image'),
        button = document.getElementById('button');
    $('#image').attr('src',  _URL.createObjectURL(file));
    $('#image').show();
    $('#button').show();
    var cropper = new Cropper(image, {
      aspectRatio: 1,
      movable: false,
      cropBoxResizable: true,
      dragMode: 'move',
      ready: function () {
        croppable = true;
        button.onclick = function () {
          var croppedCanvas;
          var roundedCanvas;
          var roundedImage;
          if (!croppable) {
            return;
          }
          // Crop
          croppedCanvas = cropper.getCroppedCanvas();
          cropper.getCroppedCanvas({
            fillColor: '#fff',
            imageSmoothingEnabled: true,
            imageSmoothingQuality: 'high',
          });
          // Round
          roundedCanvas = getRoundedCanvas(croppedCanvas);
          // Show
          roundedImage = document.createElement('img');
          roundedImage.src = roundedCanvas.toDataURL();
          result.innerHTML = '';
          result.appendChild(roundedImage);

        }
      }
    });
  }
});
#image,
#button{
  display:none
}

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.1/cropper.min.css">

 <input type="file" id="input" name="image">

 <button type="button" id="button">Crop</button>

Upload an image and click crop, The cropped part would be displayed beneath it.

Then I use the following code to send a blob to PHP using Ajax:

cropper.getCroppedCanvas().toBlob(function (blob) {
  var formData = new FormData();
  formData.append('avatar', blob);
  // Use `jQuery.ajax` method
  $.ajax('upload.php', {
    method: "POST",
    data: formData,
    processData: false,
    contentType: false,
    success: function (response) {
    },
    error: function () {
    }
  });
});

In upload.php:

if( isset($_FILES['avatar']) and !$_FILES['avatar']['error'] ){
  file_put_contents( "uploads/image.png", file_get_contents($_FILES['avatar']['tmp_name']) );
}

Should I make some checks for security or just the dimensions and size checks?


texts:
I'm new to LXML, and parsing XML documents in general. I have written a small section of code that appears to do what I need it too do, but it feels like I have overly complicated it. Is there any way I can simplify this?

Method:

def importFromXML(self, filename):
    tree = etree.parse(filename)
    for child in tree.getroot():
        if child.tag != 'SLOT':
            print('Tag:', child.tag, ', Text', child.text)
        elif child.tag == 'SLOT':
            for slot, index in child.items():
                for attribute in child:
                    print('Slot Number =', index, ', Tag:', attribute.tag, ', Value:', attribute.text)

XML:

<?xml version="1.0" encoding="UTF-8"?>
<Item>
<ActiveState>drop</ActiveState>
<Location>Left Wrist</Location>
<Realm>All</Realm>
<ItemName>Band of the Dream Conqueror</ItemName>
<ItemQuality>100</ItemQuality>
<Equipped>1</Equipped>
<Level>50</Level>
<TYPE>Wrist</TYPE>
<SOURCE>Drop</SOURCE>
<DBSOURCE>kscraft</DBSOURCE>
<SLOT Number="0">
    <Type>Resist</Type>
    <Effect>Crush</Effect>
    <Amount>6</Amount>
</SLOT>
<SLOT Number="1">
    <Type>Resist</Type>
    <Effect>Thrust</Effect>
    <Amount>6</Amount>
</SLOT>
<SLOT Number="2">
    <Type>Resist</Type>
    <Effect>Slash</Effect>
    <Amount>6</Amount>
</SLOT>
</Item>

I just want to make sure I'm doing this right. I'm using Python 3.x. Eventually I will be doing more with the data I pull, but for right now I'm just trying to pull the information, and figure out the most optimized way of doing this.


texts: Best practice-creating a good PDO connection

texts:
I have this code for updating time of login failure.The other parts of the code are stripped and simplified because my question is related to PDO.Here I have a db_config.php and a function to update time.I want to know is this a best   practice for PDO connection and accessing variables in a function?

db_config.php

<?php
try
{
  $dbh =  new PDO('mysql:host=localhost;dbname=mark1',dbusername,dbpassword);
  $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
  echo 'ERROR: ' . $e->getMessage();
}
?>

Code for update time function.

<?php
require('db_config.php')

$login = strtolower($_POST['login']);

$sql = "SELECT * FROM members WHERE email=:email_db";
$result = $dbh->prepare($sql);
$result->bindParam(':email_db', $login);
$result->execute();
$row = $result->fetch(PDO::FETCH_ASSOC);

if($row > 0)
{
  if($row['user_failed_logins'] == 5 && $row['user_last_failed_login'] > (time() - 60) )// Blocks login attempt for 1 min.
  {
    UpdateLoginFailTime($login,$dbh);
  }
  else
  {
    //Do something...
  }

function($login,$dbh)
{
  $time = time();
  $sql_update_login_fail_fileds = "UPDATE members SET user_last_failed_login = :user_last_failed_login WHERE email = :email";
  $result_update_login_fail_fileds = $dbh->prepare($sql_update_login_fail_fileds);
  $result_update_login_fail_fileds->bindParam(':user_last_failed_login', $time);
  $result_update_login_fail_fileds->bindParam(':email', $login);
  $result_update_login_fail_fileds->execute();

  echo "You have been blocked.Please try login after 1 minute"));
}
?>


texts:
The demons had captured the princess (P) and imprisoned her in the
  bottom-right corner of a dungeon. The dungeon consists of M x N rooms
  laid out in a 2D grid. Our valiant knight (K) was initially positioned
  in the top-left room and must fight his way through the dungeon to
  rescue the princess.

  The knight has an initial health point represented by a positive
  integer. If at any point his health point drops to 0 or below, he dies
  immediately.

  Some of the rooms are guarded by demons, so the knight loses health
  (negative integers) upon entering these rooms; other rooms are either
  empty (0's) or contain magic orbs that increase the knight's health
  (positive integers).

  In order to reach the princess as quickly as possible, the knight
  decides to move only rightward or downward in each step.

  Write a function to determine the knight's minimum initial health so
  that he is able to rescue the princess.

  For example, given the dungeon below, the initial health of the knight
  must be at least 7 if he follows the optimal path RIGHT-> RIGHT ->
  DOWN -> DOWN.

  Notes:

  The knight's health has no upper bound.
  Any room can contain threats
  or power-ups, even the first room the knight enters and the
  bottom-right room where the princess is imprisoned.

I was tackling this problem and I ended up with code that is functional, but times out with really large input (meaning it's poorly optimized). I'm a beginner in programming and working out a functional algorithm was extremely hard for me. Now that I have to optimize it, I don't even know how to start.

Is there a way to optimize this code that doesn't change the fundamental underlying logic or is the approach I took doomed to be inefficient? If there is a way to optimize this, could you please provide some examples?

class Solution {
public:
int calculateMinimumHP(vector< vector<int> > &dungeon) {
    return 1 - actualFunction(dungeon, 0, 0, 0);
}
int actualFunction(vector< vector<int> > &dungeon, int roomCoordX, int roomCoordY, int shield){
    if(dungeon.size() == roomCoordX + 1 && dungeon[0].size() == roomCoordY + 1){
        if(shield + dungeon[roomCoordX][roomCoordY] < 0)
            return (dungeon[roomCoordX][roomCoordY] + shield);
        else
            return (0);
    }
    if(dungeon.size() == roomCoordX + 1){
         if(shield + dungeon[roomCoordX][roomCoordY] < 0)
            return (dungeon[roomCoordX][roomCoordY] + shield) + actualFunction(dungeon, roomCoordX, roomCoordY + 1, 0);
        else
            return 0 +  actualFunction(dungeon, roomCoordX, roomCoordY + 1, dungeon[roomCoordX][roomCoordY] + shield);
    }
    if(dungeon[0].size() == roomCoordY + 1){
         if(shield + dungeon[roomCoordX][roomCoordY] < 0)
            return (dungeon[roomCoordX][roomCoordY] + shield) + actualFunction(dungeon, roomCoordX + 1, roomCoordY, 0);
        else
            return 0 +  actualFunction(dungeon, roomCoordX + 1, roomCoordY, dungeon[roomCoordX][roomCoordY] + shield);
    }
        int temp1;
        int temp2;
    if(shield + dungeon[roomCoordX][roomCoordY] < 0){
        temp1 = actualFunction(dungeon, roomCoordX + 1, roomCoordY, 0);
        temp2 = actualFunction(dungeon, roomCoordX, roomCoordY + 1, 0);
        return(shield + dungeon[roomCoordX][roomCoordY]) + ((temp1 > temp2) ? temp1 : temp2);
    }
    else{
        temp1 = actualFunction(dungeon, roomCoordX + 1, roomCoordY, dungeon[roomCoordX][roomCoordY] + shield);
        temp2 = actualFunction(dungeon, roomCoordX, roomCoordY + 1, dungeon[roomCoordX][roomCoordY] + shield);
        return 0 + ((temp1 > temp2) ? temp1 : temp2);
    }
}
};


texts: Assign Names to Phone Numbers using text file

texts:
Assign all names to a phone number. Nothing much else to explain. I think there are a lot of improvements that can be done with this code. Not really sure what though.

here is the Name/Phone Number List

phone = open("Phone.txt", "r");

name_list = []
phone_list = []

append_data = "name"

iterate_first = True
for data in phone.readlines():
    if (data == '\n'):
        append_data = "phone"

    if (append_data == "name"):
        name_list.append(data.strip())
    else:
        if (iterate_first == False):
            phone_list.append(data.strip())
        else:
            iterate_first = False

for data in name_list:
    name_index = name_list.index(data)
    print("%s is associated with the phone number %s" % (data, phone_list[name_index]))


texts: Calculating sum of certain values in a list

texts:
I have two loops which I am using to create a file, if the clientID in the client loop is the same as the id in the valuation loop then create a row. Then if the month value is the same as the previous month value we need to add up the values.

This all works fine but i was wondering if anyone can think of a better way?

        for (Clients cl : clientList) {
            //in loop so use stringbuilder
            StringBuilder sb = new StringBuilder();
            sb.append(cl.getId());
            sb.append(",");
            sb.append(cl.getFirstName());
            sb.append(" ");
            sb.append(cl.getLastName());
            sb.append(",");
            row = sb.toString();
            for (Valuations vl : valList) {
                year = vl.getYear();
                    //if we are on a new month
                    if (!month.equals(vl.getMonth()) && !month.equals("")) {
                        //add row and reset values
                        if(!vl.isNanError()){
                        data.add(row + month + "," + year + ",£" + cash);
                        }
                        cash = 0;
                        month = "";
                        done = false;
                    }
                    if (cl.getId().equals(vl.getClientId())) {
                        if (!done) {
                            row = sb.toString();
                            cash = 0;
                            month = vl.getMonth();
                            done = true;
                        }
                    }
                    cash += vl.getValue();
            }
        }
        //add the last row after the loop breaks.
        data.add(row + month + "," + year + ",£" + cash);


texts: Sieve of Eratosthenes to print prime numbers in a given range

texts:
This is my implementation for Sieve of Eratosthenes in Java.Please let me know how can I further improve my code:

public static void main(String[] args) {

    ArrayList<Integer> numbers = new ArrayList<Integer>();

    for (int i = 2; i <= 120; i++) {
        numbers.add(i);
    }

    int digit = 2;
    while (digit <= numbers.size()) {
        for (int i = 0; i < numbers.size(); i++) {

            if (numbers.get(i) != digit && numbers.get(i) % digit == 0) {
                numbers.remove(i);
                i--;

            }

        }
        digit++;
    }

    for (int a : numbers)
        System.out.println(a);

}


texts: Adding conditional check to display information in Angular 8

texts:
I am displaying the following information in angular 8 application. I need to display only the partnerName if it exists.

Financial Game Plan
of {{ name }} and {{ partnerName }}  for {{ currentDateString }}

I have done the following. Could you let me know if it is correct?

TS

 this.name = factFindService.dataModel.client.firstName + ' ' + factFindService.dataModel.client.lastName;
      if(factFindService.dataModel.partner) {
        this.partnerName = factFindService.dataModel.partner.firstName + ' ' + factFindService.dataModel.partner.lastName;
      }

HTML

Financial Game Plan
of {{ name }}  and {{ partnerName }}   for {{ currentDateString }}


texts: Shorter, better way to write a "query" involving virtual attributes

texts:
I have this code in a model for an invoicing app. This virtual attribute current_invoice gets the only non-rescinded invoice associated with a contract. The code works but it seems really verbose. Can this be done in a prettier way?

  def current_invoice
    result = []
    invoices.each do |i|
      if i.current_status != "rescinded"
        result.push(i)
      else
        false
      end
    end
    if result.length > 1
      raise "Only one non-rescinded invoice association per contract"
    else
      result[0]
    end
  end

You might be wondering why not just do this...

invoices.where.not(current_status: "rescinded").first

...but current_status is a virtual attribute on invoice.


texts:
I'm adding db access to my go program, it looks like this:

package db_access

import (
    "database/sql"
    "fmt"
    "my_database"
)

type TheType struct {
    Name string
}

func LoadTheTypeFromDb(db *sql.DB, id uint) (*TheType, error) {
    query := fmt.Sprintf(
        "SELECT %s FROM %s WHERE %s = ?",
        my_database.NAME,
        my_database.TABLE,
        my_database.ID,
    )

    var theType TheType

    err := db.QueryRow(query, id).Scan(&theType.Name)

    switch {
    case err == sql.ErrNoRows:
        n := my_database.NewNotFoundError(err)
        return nil, &n
    case err != nil:
        return nil, err
    default:
        return &theType, nil
    }
}

And some part of the my_database package:

package my_database

import (
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

func GetDatabaseInstance(connectionString string) (*sql.DB, error) {
    db, err := sql.Open("mysql", connectionString)

    if err != nil {
        c := newConnectionError(err)
        return nil, &c
    }

    err = db.Ping()

    if err != nil {
        c := newConnectionError(err)
        return nil, &c
    }

    return db, nil
}

And the custom errors:

package my_database

import (
    "fmt"
    "reflect"
)

type ConnectionError struct {
    errorMessage string
}

func newConnectionError(err error) ConnectionError {
    return ConnectionError{fmt.Sprintf("Connection error %s %s", reflect.TypeOf(err), err)}
}

func (e *ConnectionError) Error() string {
    return e.errorMessage
}

type QueryError struct {
    errorMessage string
}

func newQueryError(err error) QueryError {
    return QueryError{fmt.Sprintf("Query error %s %s", reflect.TypeOf(err), err)}
}

func (e *QueryError) Error() string {
    return e.errorMessage
}

type NotFoundError struct {
    errorMessage string
}

func NewNotFoundError(err error) NotFoundError {
    return NotFoundError{fmt.Sprintf("Not found - %s", err)}
}

func (e *NotFoundError) Error() string {
    return e.errorMessage
}

I add a custom NotFound error, because when the row is not found, I don't want to leak sql.ErrNoRows outside, is that ok? I don't like that the constructor for NotFound error is public, unlike all other custom errors, furthermore, I think I would need to add that switch statement to every Load* method … also not so good.
The custom error code is very repetitive, is there a way to clean that up?
Any other comments are much appreciated.


texts:
Hello i'm coding a social site and I need to know how clean this code is. I read other answers people told me from my previous questions like this and used it as guidelines. So now I wanna know if anything could be improved. Thank you.
<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(-1);

include 'includes/header.php';

$userLoggedIn = $_SESSION['thesocial_username'];

$post_id = isset($_POST['cancel']) ? header("Location: settings.php") : '';

if(isset($_POST['close_account'])) {

    $close_query = $con->prepare('UPDATE users SET user_closed = "yes" WHERE username = ?');
    $close_query->bind_param("s", $userLoggedIn);
    $close_query->execute();

    session_destroy();
    header("Location: register.php");
}

?>

Close Account

    Are you sure you want to close your account ?

    Closing your account will hide your profile and activity from users.

    You can reopen your account at anytime by logging in.

    <form action="close_account.php" method="POST">

        <input type="submit" name="close_account" id="close_account" value="Yes, Close my account.">
        &nbsp;&nbsp;
        <input type="submit" name="cancel" id="update_details" value="Nevermind.">

    </form>


texts:
I have a shell script to mount different remote systems. While it does work, the area I struggle with (not being a programmer) is the logic of the script: it feels quite stilted and there seems to be some unnecessary duplication.

I would appreciate any comments as to how I could improve it - both in terms of the logic, but also any other tips about style or approach.

#!/bin/sh
# mount boxes by SSHFS

usage () {
    cat <<EOF
    sshmnt -[c,s,u,h]
      -c Box1
      -s Box2
      -u unmount
      -h print this message

EOF
}

mnt(){
    sshfs jason@"$host":/home/jason /media/"$dir" \
    -C -p "$port" \
    -o reconnect,IdentityFile=/home/jason/.ssh/id_rsa \
    && ls /media/"$dir"
}

umnt(){
    fusermount -u /media/"$dir"
}

# unmounting
if [ "$1" = "-u" ]; then
    box=$(mount | grep Box1)
    if [ -n "$box" ]; then
        dir=Box1
    else
        dir=Box2
    fi
    umnt && exit
fi

# check if on LAN
lan="$(ip addr | grep .102/)"

if [ -n "$lan" ]; then
    case "$1" in
      -c) int=100
          ;;
      -s) int=200
          ;;
    esac
    host="192.168.1.$int"
else
    host="XXX.XXX.XXX.XXX"
fi

# box specifics
case "$1" in
  -c) dir=Box1 port="XXXX"
      mnt
      ;;
  -s) dir=Box2  port="XXXX"
      mnt
      ;;
   *) usage && exit
       ;;
esac

I have obscured the relevant ports and hostnames.