texts:
Const FOLDERPATH As String = "\ITSEASY"
Const DATAFOLDER As String = "\AS"
Const OLDDATAFOLDER As String = "\ABC"
Public Sub ExportData()
Application.ScreenUpdating = False
'GET DROPBOX PATH
Dim TheDropBoxPath As String
TheDropBoxPath = DropBoxPath.GetDBPath

Dim files() As Variant 'STARTS AT 1
files = FileStuff.listfiles(TheDropBoxPath & FOLDERPATH & DATAFOLDER)
Dim NumberOfFlies As Integer

On Error GoTo blob
NumberOfFlies = UBound(files)
On Error GoTo 0

'FILE FOR EXPORTED DATA
Dim ExportWB As Workbook
Set ExportWB = Workbooks.Open(TheDropBoxPath & FOLDERPATH & "\" &
"Pushed.xlsx")
Dim ExportWBLastRow As Long
ExportWB.Sheets(1).UsedRange.Clear

'FILE BEING READ
Dim DataWB As Workbook
Dim DataWBLastRow As Long

For i = 1 To UBound(files)
    'OPEN THE FILE
    Set DataWB = Workbooks.Open(TheDropBoxPath & FOLDERPATH & DATAFOLDER & "\" & files(i))
    DataWBLastRow = DataWB.Sheets(1).Cells(1, 1).End(xlDown).Row

    If i > 1 Then 'LAZY
    ExportWBLastRow = ExportWB.Sheets(1).Cells(1, 1).End(xlDown).Row + 1
    End If

    If i = 1 Then 'FOR HEADER ROW
    DataWB.Sheets(1).Range("1:1").Copy
    ExportWB.Sheets(1).Range("A1").PasteSpecial xlPasteValues
    ExportWBLastRow = 2
    End If

    'COPY PASTE CONTENT
    DataWB.Sheets(1).Range("2:" & DataWBLastRow).Copy
    ExportWB.Sheets(1).Range("A" & ExportWBLastRow).PasteSpecial xlPasteValues

    Application.DisplayAlerts = False
    DataWB.Close
    Application.DisplayAlerts = True

    'MOVE FILE TO OLD
    Call FileStuff.MoveFiles(TheDropBoxPath & FOLDERPATH & DATAFOLDER & "\" & files(i), TheDropBoxPath & FOLDERPATH & DATAFOLDER & "\AYE\" & files(i))
Next i

    ExportWB.Sheets(1).UsedRange.RemoveDuplicates Columns:=1, Header:=xlGuess
    ThisWorkbook.Save

    Application.DisplayAlerts = False
    ExportWB.Save
    ExportWB.Close
    Application.DisplayAlerts = True

Application.ScreenUpdating = True

MsgBox (NumberOfFlies & " dfghdfsgsfg tf " & Chr(34) & "FAKETEXT" & Chr(34) & "BLABLA")
Exit Sub

blob:     MsgBox ("FAKE MESSAGE  NUMBER 2 " & TheDropBoxPath & FOLDERPATH & DATAFOLDER): Exit Sub
End Sub

I'm looking for improvement on the way I deal with processing multiple files. Currently i'm using FSO, I feel like it's slow. Any better way to do that ?

Is there a way to copy the content of a sheet without having to open it ?

Self answer : ADODB does that


texts: Security of authentication check for a blog

texts:
I am currently making a very big blogging system for my Website where I want really neat code! So, I was wondering: is this method safe/does it have any problems with security? Yes, I'll be encrypting the password anyway. I also want to know if there is a better way to achieve the same idea. Also any tips on implementing high security and high performance?

<?php
class Users {
    protected $db;
    public $id;
    public $username;
    public $password;
    public $lastlogin;
    public $email;
    public $rank;
    public $creationdate;
    public $country;
    public $status;

    public function __construct() {
        $this->db = new mysqli('localhost', 'root', 'php123', 'ht');
    }

    public function login($username, $password) {
        $query = $this->db->prepare("SELECT username, password FROM blog_users WHERE username = ? AND password = ? LIMIT 1");
        $query->bind_param('ss', $username, $password);
        $query->execute();
        $query->bind_result($username, $password);
        $query->store_result();
        if($query->num_rows == 1) {
            while($query->fetch()) {
                $userData = getData($username);

                $this->id             =   $this->userData['id'];
                $this->username       =   $username;
                $this->password       =   $password;
                $this->lastlogin      =   time();
                $this->email          =   $this->userData['email'];
                $this->rank           =   $this->userData['rank'];
                $this->creationdate   =   $this->userData['creationdate'];
                $this->country        =   $this->userData['country'];
                $this->status         =   $this->userData['status'];

                $_SESSION['loggedin'] = 1;
                return true;
            }
        } else {
            return false;
        }
        $query->close();
        $query->free_result();
    }

    public function getData($username) {
        $query = $this->db->prepare("SELECT id, email, rank, creationdate, country, status FROM blog_users WHERE username = ?");
        $query->bind_param('s', $username);
        $query->execute();
        $query->bind_result($id, $email, $rank, $creationdate, $country, $status);
        $query->store_result();
        $userData = array(
            'id'           => $id,
            'email'        => $email,
            'rank'         => $rank,
            'creationdate' => $creationdate,
            'country'      => $country,
            'status'       => $status
        );
        return $userData;
        $query->close();
        $query->free_result;
    }

}
?>


texts:
Given three positive numbers A, B, and C. Find the number of positive
  integers less than D that are divisible by either of A, B or C.

  Input format

  The 1st argument given is an Integer A. The 2nd argument given is an
  Integer B. The 3rd argument given is an Integer C. The 4th argument
  given is an Integer D.

  Output Format

  Return an Integer X, the number of positive integers that are
  divisible by either of A, B, or C.

  Constraints

  1 <= A, B, C, D <= 1e9

  For Example

  Input:

  A = 2

  B = 3

  C = 4

  D = 10

  Output:

  6

  Explanation:

  positive numbers less than D that are divisible by either of A, B or C are    2, 3, 4, 6, 8, 9

My approach:

import java.math.BigInteger;

public class Solution {
    public int solve(int A, int B, int C, int D) {
        BigInteger numDivA = BigInteger.valueOf((D - 1)/A);

        BigInteger numDivB = BigInteger.valueOf((D - 1)/B);

        BigInteger numDivC = BigInteger.valueOf((D - 1)/C);

        BigInteger newA = BigInteger.valueOf(A);

        BigInteger newB = BigInteger.valueOf(B);

        BigInteger newC = BigInteger.valueOf(C);

        BigInteger newD = BigInteger.valueOf(D);

        BigInteger limit = new BigInteger("1000000000");

        BigInteger lcmAB = (newA.divide(hcf(newA, newB))).multiply(newB);

        BigInteger lcmAC = (newC.divide(hcf(newA, newC))).multiply(newA);

        BigInteger lcmBC = (newB.divide(hcf(newB, newC))).multiply(newC);

        BigInteger lcmABC = lcmAB.divide(hcf(lcmAB,newC)).multiply(newC);

        BigInteger numDivAB = newD.subtract(BigInteger.ONE).divide(lcmAB);

        BigInteger numDivBC = newD.subtract(BigInteger.ONE).divide(lcmBC);

        BigInteger numDivAC = newD.subtract(BigInteger.ONE).divide(lcmAC);

        BigInteger numDivABC = newD.subtract(BigInteger.ONE).divide(lcmABC);

        BigInteger numTotal = (((((numDivA.add(numDivB)).add(numDivC)).subtract(numDivAB)).subtract(numDivBC)).subtract(numDivAC)).add(numDivABC);

        return (numTotal.mod(limit)).intValue();
    }

    private BigInteger hcf (BigInteger a, BigInteger b) {

        BigInteger hcf = a.gcd(b);

        return hcf;
    }

}

I have the following questions with regards to the above code:

How can I further improve my approach?
Is there a better way to solve this question?
Are there any grave code violations that I have committed?
Can space and time complexity be further improved?
Have I gone too overboard by using BigInteger?

Reference


texts: Android: should I get network calls in viewmodel

texts:
I am using Retrofit to get data from API. I am doing it in view model like the following:
class RegisterShopViewModel : ViewModel() {
    private val client by lazy { WebServicesApi.getClient }

    private var isShopRegisterSuccessful = MutableLiveData<Pair<Boolean, List<String>>>()

    fun registerShop(shopModel: ShopModel): LiveData<Pair<Boolean, List<String>>> {
        client.registerShop(shopModel)
            .enqueue(object : Callback<RegisterResponseModel> {
                override fun onFailure(call: Call<RegisterResponseModel>, t: Throwable) {
                    TODO("Not yet implemented")
                }

                override fun onResponse(
                    call: Call<RegisterResponseModel>,
                    response: Response<RegisterResponseModel>
                ) {
                    response.body()?.let {
                        isShopRegisterSuccessful.value =
                            Pair(it.isSuccess, it.errorsList)
                    }
                }
            })
        return isShopRegisterSuccessful
    }

and in my view(Activity/Fragment), I am listening for changes like so
       val email = txtShopEmail.text.toString()
       val password = txtShopPassword.text.toString()
       val confirmPassword = txtShopConfirmPassword.text.toString()
       val name = txtShopName.text.toString()

       val shopModel = ShopModel(email, password, confirmPassword, name)

       registerShopViewModel.registerShop(shopModel).observe(this, Observer {
           registerShop(it)
       })
   }

   private fun registerShop(result: Pair<Boolean, List<String>>) {
       if (result.first)
           Toast.makeText(this, "Registered Successfully", Toast.LENGTH_SHORT).show()
       else
           Toast.makeText(this, "error ${result.second}", Toast.LENGTH_SHORT).show()
   }
}

my questions are:
1 - is it best practice to send the data in ViewModel's function?
2 - in cases of register/ login in which I send a request with data and wait for a response. Is LiveData useful?
if you have any suggestion to improve this code please share it


texts:
This was an exercise from cs50. The goal was to get the initials in upper letter of a name that we got from user. So for "barack obama" we would get "BO", input like "abc" should output "A" and so on. I am interested in knowing what I can do to simplify it or be more efficient.

Do I need the check against '\0' in the while loop? I ask because the way I see it, when a user inputs a name, there will always be a '\n'(right ?), so it gets out of the while loop when its position has '\n' and then out of for loop so '\0' is never actually checked. Let me know if logic is right. I kept it there just in case.

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

#define NAME_LEN 80 + 1

int main(void)
{
    char userName[NAME_LEN], userInitials[NAME_LEN];
    int i, pos = -1;

    // ask user for a name
    fgets(userName, NAME_LEN, stdin);
    for(i = 0; userName[i] != '\n' && userName[i] != '\0'; i++)
    {
        if (userName[i] >= 'a' && userName[i] <= 'z')
        {
            userInitials[++pos] = userName[i] - ('a' - 'A');
        }
        else
        {
            userInitials[++pos] = userName[i];
        }
        while ((!isblank(userName[i])) && (userName[i] != '\n') && (userName[i] != '\0'))
        {
            i++;
        }
    }
    userInitials[++pos] = '\0';
    printf("%s\n", userInitials);

}


texts:
Should my class pass parameters internally or reference class level scoped variables?

I'm not sure on the best approach or style for procedure calls that have parameters. Should I go with the class level scoped variables?

public class YouOweTheGovernment
{
    public float AmountToPay { get; private set; }
    public float ArbitraryTaxRate { get; private set; }
    public float Salary { get; private set; }

    public YouOweTheGovernment(float taxRate, float salary)
    {
        this.ArbitraryTaxRate = taxRate;
        this.Salary = salary;

        CalculateAmount();
    }

    private void CalculateAmount()
    {
        this.AmountToPay = (this.Salary * (this.ArbitraryTaxRate / 100));
    }
}

Or explicitly pass parameters into a procedure?

public class YouOweTheGovernment
{
    public float AmountToPay { get; private set; }
    public float ArbitraryTaxRate { get; private set; }
    public float Salary { get; private set; }

    public YouOweTheGovernment(float taxRate, float salary)
    {
        this.ArbitraryTaxRate = taxRate;
        this.Salary = salary;

        CalculateAmount(this.Salary, this.ArbitraryTaxRate);
    }

    private void CalculateAmount(float salary, float taxRate)
    {
        this.AmountToPay = (salary * (taxRate / 100));
    }
}

In my contrived example I think the first is clearer, but as a class grows in size and complexity it would make it harder to track what is coming from where.


texts: Given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix

texts:
Implement an autocomplete system. That is, given a query string s and
  a set of all possible query strings, return all strings in the set
  that have s as a prefix.

  For example, given the query string de and the set of strings [dog,
  deer, deal], return [deer, deal].

    class DailyCodingProble11 {

        public static void main(String args[]) {

            String[] words = { "dog", "deer", "deal" };
            Trie trie = new Trie();
            for (String word : words) {
                trie.insert(word);
            }
            trie.search("de", trie.root, 0).stream().forEach(word -> System.out.println(word));
            trie.search("do", trie.root, 0).stream().forEach(word -> System.out.println(word));
        }
    }

        class TrieNode {
            public Character content;
            public TrieNode[] children = new TrieNode[26];
            public boolean isWord;

            TrieNode(Character ch) {
                this.content = ch;
            }
        }

        class Trie {
            TrieNode root;

            Trie() {
                root = new TrieNode('*');
            }

            public void insert(String word) {
                TrieNode currentNode = root;
                for (int i = 0; i < word.length(); i++) {
                    Character ch = word.charAt(i);
                    if (currentNode.children[ch - 'a'] == null) {
                        currentNode.children[ch - 'a'] = new TrieNode(ch);
                    }
                    currentNode = currentNode.children[ch - 'a'];

                }
                currentNode.isWord = true;
            }

            public List<String> search(String searchTxt, TrieNode currentNode, int index) {
                List<String> results = new ArrayList<>();
                Character ch = searchTxt.charAt(index);
                if (currentNode.children[ch - 'a'] == null) {
                    return results;
                }
                currentNode = currentNode.children[ch - 'a'];
                if (index == searchTxt.length() - 1) {
                    findWords(currentNode, new StringBuilder(searchTxt), results);
                    return results;
                }
                return search(searchTxt, currentNode, ++index);
            }

            public void findWords(TrieNode currentNode, StringBuilder sb, List<String> results) {

                for (TrieNode child : currentNode.children) {
                    if (child != null) {
                        if (child.isWord == true) {
                            results.add(sb.append(child.content).toString());
                        }
                        findWords(child, new StringBuilder(sb).append(child.content), results);
                    }
                }
            }

 }

How can I improve my solution? Are there any code improvements?


texts: Simple parsing for string formatting (version 2)

texts:
This is my second attempt (version 1) at writing a string formatting utility which uses parsing. This time I more explicitly designed it as a finite state machine. I have very little experience with writing FSMs. As before, I'm not 100% sure that this code does not contain any critical flaws. In addition to pointing out any such oversights, I would appreciate advice on how this could be modified to make it either faster or more readable.

#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>
#include <stdexcept>
#include <utility>
#include <cctype>

using std::to_string;

template <class T>
std::string to_string(T&& item)
{
    return boost::lexical_cast<std::string>(std::forward<T>(item));
}

template <class... Args>
std::string format(const std::string& fmt, Args&&... args)
{
    std::string arg_strs[] = { to_string(std::forward<Args>(args))... };

    std::string output, index;
    output.reserve(fmt.length() * 2);

    enum { COPYING, OPEN_BRACE, READ_INDEX, CLOSE_BRACE } state = COPYING;

    for (const char c : fmt)
    {
        switch (state)
        {
            case COPYING:
                if (c == '{') state = OPEN_BRACE;
                else if (c == '}') state = CLOSE_BRACE;
                else output += c;
                break;

            case OPEN_BRACE:
                if (isdigit(c)) {
                    index += c;
                    state = READ_INDEX;
                }
                else if (c == '{') {
                    output += '{';
                    state = COPYING;
                }
                else goto fail;
                break;

            case READ_INDEX:
                if (isdigit(c)) index += c;
                else if (c == '}') {
                    size_t i = std::stoi(index);
                    if (i >= sizeof...(args)) {
                        throw std::out_of_range(
                            "argument index is out of range in format");
                    }
                    output += arg_strs[i];
                    index.clear();
                    state = COPYING;
                }
                else goto fail;
                break;

            case CLOSE_BRACE:
                if (c == '}') {
                    output += '}';
                    state = COPYING;
                }
                else goto fail;
                break;
        }
    }

    if (state != COPYING) goto fail;
    return output;

fail:
    throw std::invalid_argument("invalid format string");
}

template <class... Args>
void print(const std::string& fmt, Args&&... args)
{
    std::cout << format(fmt, std::forward<Args>(args)...);
}

int main()
{
    print("Hello, {0}! The answer is {1}.", "World", 42);
}

Here is a diagram of the FSM:

Now just for fun, I converted this to JavaScript with regex...

function format(fmt, ...args) {
    if (!fmt.match(/^(?:(?:(?:[^{}]|(?:\{\{)|(?:\}\}))+)|(?:\{[0-9]+\}))+$/)) {
        throw new Error('invalid format string.');
    }
    return fmt.replace(/((?:[^{}]|(?:\{\{)|(?:\}\}))+)|(?:\{([0-9]+)\})/g, (m, str, index) => {
        if (str) {
            return str.replace(/(?:{{)|(?:}})/g, m => m[0]);
        } else {
            if (index >= args.length) {
                throw new Error('argument index is out of range in format');
            }
            return args[index];
        }
    });
}

function print(fmt, ...args) {
    console.log(format(fmt, ...args));
}

print("Hello, {0}! The answer is {1}.", "World", 42);


texts: Checking that all occurrences of 'g' have another 'g' as a neighbor

texts:
We'll say that a lowercase 'g' in a string is "happy" if there is another 'g' immediately to its left or right. Return true if all the g's in the given string are happy.

gHappy("xxggxx") → true
gHappy("xxgxx") → false
gHappy("xxggyygxx") → false

This is my code so far, which I think is very messy.

  public boolean gHappy(String str)
  {
        for(int i=1;i<str.length()-1;i++)
           {
              if(str.charAt(i)=='g')
                 if(str.charAt(i-1)!='g'&&str.charAt(i+1)!='g')
                    return false;
  }
  if(str.length()==1)
      return false;
  if(str.equals(""))
      return true;
if(str.charAt(str.length()-1)=='g')
      if(str.charAt(str.length()-2)!='g')
        return false;

  return true;
}


texts: Accessing server side variables in views and JavaScript

texts:
I was a PHP developer and I started writing a product in C# without studying the basic structure. Now, I have around 100+ views with similar code. After 1 year into development, I now realize that something is not right.

How can I separate the server tags when they are so intertwined in the code? Is it okay to use server side variables like this?

PS: I am not using Razor in my product.

/Views/Emp/EditEmp.aspx

<% if(HttpContext.Current.User.IsInRole("Manager")) { %>

        Back to Emp Info

<% } %>

. ..... .. .. ...

<% if(Model != null && Model.Holidays != null) {
    foreach(EmpHoliday eh in Model.Holidays){ %>

<%= eh.Date.ToString("dd/MMM/yyyy") %>

<%= eh.Holiday %>

    <% } %>

<% } %>


texts: Making user login system secure with $_SESSION

texts:
I am hoping that someone can help me out here. I am creating a PHP web app that requires a user to login to view their data in the MySQL database.

I just want to know if this is a good approach and is it secure enough. I know that nothing is secure in PHP scripting but I need this fairly secure.

Here is what I am doing step by step. If you could point me in the right direction and tell me what is wrong that would be great!

User logs in with user and password.
PHP checks user and password against the database.
If OK, I store the $SESSION["username"] (their username) to the session.

On every request/page load I have a function (below) to check the session:

function check_session_valid(){ if(!isset($_SESSION['username'])||$_SESSION['username'] == ""){ header("Location: /login.php"); } }

Now is this safe or am I doing this all completely wrong?

Here is what I am thinking that the user could do to "hack" the app:

On the registration page, when the user enters there username it will let them know if the username is available.

Could the "hacker" not just find a username that is not available and then write a PHP script to set the $_SESSION["username"] in their browser, then navigate to the .index.php page and be logged into some other users account?

I am also using session_start() before I check_session_valid() on every request. Is that wrong?


texts:
I have a weighted BFS search in python for networkx that I want to optimize:

def bfs(graph, node, attribute, max = 10000):
    # cProfile shows this taking up the most time. Maybe I could use heapq directly? Or maybe I would get more of a benefit making it multithreaded?
    queue = Queue.PriorityQueue()
    num = 0
    done = set()
    for neighbor, attrs in graph[node].iteritems():
        # The third element is needed because we want to return the ajacent node towards the target, not the target itself.
        queue.put((attrs['weight'], neighbor, neighbor))
    while num <= max and not queue.empty():
        num += 1
        item = queue.get()
        if graph.node[item[1]].get(attribute, False):
            return item[2]
        for neighbor, attrs in graph[item[1]].iteritems():
            if neighbor not in done:
                queue.put((item[0] + attrs['weight'], neighbor, item[2]))
                done.add(neighbor)


texts:
I want to implement a method which, given some camelcased or underscored String, will return a list of separate words that make up this String.
Examples:

ISomeCamelCasedString -> {I, Some, Camel, Cased, String}
UNDERSCORED_STRING -> {UNDERSCORED, STRING}
camelCased_and_UNDERSCORED -> {camel, Cased, and, UNDERSCORED}

My approach to solve this is as follows: I add a space character between each two words that should be separated and then divide them into a list using StringTokenizer.

public static List<String> split(String string) {
    StringBuilder separatedWords = new StringBuilder();

    for (int i=0; i<string.length(); i++) {
        char c = string.charAt(i);

        if (i > 0) {
            char previousC = string.charAt(i-1);

            if ((!Character.isLowerCase(c) && !Character.isUpperCase(previousC)) //  UpperCamelCase, UPPER_DASHED
                    || !Character.isLetterOrDigit(previousC)                    // lower_dashed
                    || (i < string.length() - 1) && Character.isLowerCase(string.charAt(i+1))  && Character.isUpperCase(c)  ) // IAttribute
            {
                separatedWords.append(" ");
            }
        }
        if (Character.isLetterOrDigit(c)) {
            separatedWords.append(c);
        }
    }

    List<String> tokens = new ArrayList<String>();

    StringTokenizer tokenizer = new StringTokenizer(separatedWords.toString());

    while(tokenizer.hasMoreTokens()) {
        tokens.add(tokenizer.nextToken());
    }
    return tokens;
}

As you can see, it looks quite complicated. How can I improve this?


texts:
How can I make this code shorter?

function tblcheckboxes(){
    var a= 0;
    var b= 0;
    var c= 0;
    var d= 0;
    var e= 0;
    var f= 0;
    var g= 0;

    if ($('#tcbx1').is(":checked")) {
         a = parseFloat($("#tcbx1").val(), 10);
    }
    if ($('#tcbx2').is(":checked")) {
         b = parseFloat($("#tcbx2").val(), 10);
    }
    if ($('#tcbx3').is(":checked")) {
         c = parseFloat($("#tcbx3").val(), 10);
    }
    if ($('#tcbx4').is(":checked")) {
         d = parseFloat($("#tcbx4").val(), 10);
    }
    if ($('#tcbx5').is(":checked")) {
         e = parseFloat($("#tcbx5").val(), 10);
    }
    if ($('#tcbx6').is(":checked")) {
         f = parseFloat($("#tcbx6").val(), 10);
    }
    if ($('#tcbx7').is(":checked")) {
         g = parseFloat($("#tcbx7").val(), 10);
    }

    var total = a + b + c + d + e + f + g;
    $('.txt7').val(total.toFixed(2));
}

$(document).ready(function(){
        $('#tcbx1').click(function(){
                tblcheckboxes();
                grandtotal();
        });
        $('#tcbx2').click(function(){
                tblcheckboxes();
                grandtotal();
        });
        $('#tcbx3').click(function(){
                tblcheckboxes();
                grandtotal();
        });
        $('#tcbx4').click(function(){
                tblcheckboxes();
                grandtotal();
        });
        $('#tcbx5').click(function(){
                tblcheckboxes();
                grandtotal();
        });
        $('#tcbx6').click(function(){
                tblcheckboxes();
                grandtotal();
        });
        $('#tcbx7').click(function(){
                tblcheckboxes();
                grandtotal();
        });
});


texts:
I have 2 lists with varying length. Both lists contain data which has to be matched with entries from the other list. Currently I am iterating both lists with a nested for-loop.

List<MyClass1> list2 = myClass1dao.findUnmatchedEntries();
List<MyClass2> list1 = myClass2dao.findUnmatchedEntries();

for (MyClass2 list1entry : list1) {
    for (MyClass1 list2entry : list2) {
        if (list1entry.getName().equals(list2entry.getName())
            && list1entry.getID().equals(list2entry.getID())) {
            //update entries
            myClass2dao.update(list1entry);
            myClass1dao.update(list2entry);
            break;
        }
    }
}

I know that this takes exponentially longer the more elements each list has.

So my question is, how can this code be improved?

Note: I am on a java 7 code base so answers to java 7 are preferred, but java 8 is okay as well


texts:
I am writing a benchmarking tool from scratch in Python.
However I can't get the performance of other benchmarking tools like wrk or wrk2. Using wr2 I can make 42k requests/s while my code can only create up to 2200 reqs/s. I have tried multiple ways to parallelize the code execution. I have tried using multiprocessing and parallel computing libraries like Dask. But I can't get better performance. I understand wrk and wrk2 are written in C which can be one reason but still 42k vs 2200 seems like a very large difference.
I have tried with different number of workers and number_of_request, but the performance does not change much.
I am trying to understand if I am really hitting the upper limit or I am doing something wrong. The server is running on localhost and written in Java Spring.
This is my code using multiprocessing:
import time
import multiprocessing
from collections import Counter, defaultdict
import requests

# import multiprocessing as mp

num_workers = multiprocessing.cpu_count()

output = multiprocessing.Queue()
def runner(number_of_request):
    output=""
    for i in range(number_of_request):
        try:
            output+=str(requests.get("http://127.0.0.1:8000/").text)
        except:
            pass
        # print(output)

    return output

if __name__ == '__main__':
    number_of_request = 1000
    start = time.time()
    pool = multiprocessing.Pool(processes=num_workers)
    outputs = [pool.apply_async(runner, args = (number_of_request,)) for x in range(num_workers)]
    pool.close()
    pool.join()

    duration = time.time() - start
    req_s = (number_of_request*num_workers)/duration
    print("duration =", time.time() - start)
    print(req_s)


texts: Calling a method only once in an updateScore function in SpriteKit

texts:
This works fine, but obviously it's messy and I'm thinking there has to be a better way to do this. Having to constantly remember to flip the bool back is a pain, is there anything else I can do here?  I take it SpriteKit itself doesn't have any convenience method for calling something only once for example.

func updateScore() {

        // MARK: Increase Difficulty
        switch score {
        case 0:
            if !levelToggle {
                showLevelGraphic(1)
                levelToggle = true
            }
        case 1:
            levelToggle = false
        case 5:
            if !lighteningToggle {
                GameEffects.lightening(self, masterNode: worldNode, backgroundStringName: "background")
                GameEffects.lightening(self, masterNode: worldNode, backgroundStringName: "foreground")
                GameEffects.shakeScreen(worldNode)
                lighteningToggle = true
            }

            if !rainToggle {
                makeItRain()
                rainToggle = true
            }
            break
        case 6:
            lighteningToggle = false
        case 10:
            if !rotateToggle {
                GameEffects.rotateScreenAndHold(worldNode, finishAngle: 0.06, totalEffectDuration: 5.0)
                rotateToggle = true
            }
        case 15:
            rotateToggle = false
        case 16:
            if !rotateToggle {
                GameEffects.rotateScreenAndHold(worldNode, finishAngle: -0.06, totalEffectDuration: 5.0)
                rotateToggle = true
            }
             break
        case 17:
            rotateToggle = false
        case 20:
            stopRaining()
            rainToggle = false
        case 25:
            if !rotateToggle {
                GameEffects.rotateScreenAndHold(worldNode, finishAngle: -0.06, totalEffectDuration: 10.0)
                rotateToggle = true
            }
        case 26:
            rotateToggle = false
        case 45:
            break
        case 50:
            if !levelToggle {
                showLevelGraphic(2)
                levelToggle = true
            }
            kGroundSpeed = 200
            break
        case 55:
            if !zoomToggle {
                GameEffects.zoomIn(worldNode)
            }
        case 56:
            zoomToggle = false
        case 70:
            if !rotateToggle {
                GameEffects.rotateScreenAndHold(worldNode, finishAngle: 0.06, totalEffectDuration: 10.0)
                rotateToggle = true
            }


texts: Music collection with lyric songs and instrumental pieces

texts:
I have problems with dealing with derived classes that inherit from the same base class.

I have 2 types of songs:

Songs with lyrics that have: Title, Tags (sad, happy etc.), lyrics (one line), writer.
Instrumental song: Title, Tags (same as lyric songs), instrumentals (a string), performer, BPM.

I thought it would be a good idea to implement a base class Song, since Title and Tags are fields that are common to the both types of the songs. Then, implement the class LyricSong and InstrumentalSong that inherit from Song.

class Song
{

public:
    Song(std::string title, std::string tags);

    std::string getTitle() const { return this->_title; }
    std::string getTags() const { return this->_tags; }

    // Since i had the need in virtual functions and since all virtual functions have to be
    // implemented, i used default string and int to be returned.
    virtual std::string getLyrics() const { return std::string(); }
    virtual std::string getLyricsBy() const { return std::string(); }
    virtual std::string getInstruments() const { return std::string(); }
    virtual std::string getPerformer() const { return std::string(); }
    virtual int getBPM() const { return 0; }

    static songContainer readSongsFromFile(std::string songsFileName);

private:
    std::string _title;
    std::string _tags;

};

//---------------------------------------------------------------------------//

class LyricSong : public Song
{

public:
    LyricSong(std::string title, std::string tags, std::string lyrics, std::string lyricsBy);

    std::string getLyrics() const { return this->_lyrics; }
    std::string getLyricsBy() const { return this->_lyricsBy; }

private:
    std::string _lyrics;
    std::string _lyricsBy;
};

//---------------------------------------------------------------------------//
class InstrumentalSong : public Song
{

public:
    InstrumentalSong(std::string title, std::string tags,\
                     std::string instruments, std::string performer, int BPM);

    std::string getInstruments() const { return this->_instruments; }
    std::string getPerformer() const { return this->_performer; }
    int getBPM() const { return this->_BPM; }

private:
    std::string _instruments;
    std::string _performer;
    int _BPM;
};

Issues that have arisen:

The code is cumbersome and messy.
Every time I'll need to add new song types, it will force me to modify Song (add more functions and make them virtual - Polymorphic issues).
Will there be a way to know what type of Song I work with, in case of iterating over an array of Song pointer that point to various song types?

Are there any common design principles that can help me with this?


texts:
I've done a program and it works fine as I want to but I feel it could be better and more advanced so I want some master advice on my program which is going to take many numbers and return the number with the most prime divisors and the number of its divisors in front of the number like this 678 3 as the output
code :
list_of_inputs = []
for elements in range(5):
    list_of_inputs.append(int(input()))
list_of_inputs = list(set(list_of_inputs))

def _check_prime_sample_(n):
    if n < 2:
        return False
    for i in range(2, n):
        if n % i == 0:
            return False
    return True

def find_integer_with_most_divisors(input_list):
    from operator import itemgetter
    lis = []
    dic = {}
    for elements in input_list:
        sub_lis = []
        for items in range(1, elements):
            if elements % items == 0 and _check_prime_sample_(items) == True:
                sub_lis.append(items)
        lis.append(len(sub_lis))
        dic[elements] = len(sub_lis)
    tup = [(k, v) for k, v in dic.items()]
    sup = max(tup, key=itemgetter(1, 0))

    print('{} {}'.format((sup)[0], (sup)[1]))

find_integer_with_most_divisors(list_of_inputs)


texts:
I'd been using this form for a while now with the functional methods map, filter, reduce:

// For example...
$result = array_reduce(array_map(function($value) {
    return explode('-', $value);
}, $input), function($carry, $item) {
    return array_merge($carry, $item);
}, array());

The array_reduce() part, where I need to collapse depth in the result. So I was thinking about this, and this is what I came up with. It actually works as a callback to array_reduce() too:

/**
 * Flatten a multi-dimensional array to a single-level array,
 * sorting the entries in order to depth first.
 *
 * @param array $carry Array to initialize, will be the subject if the only argument passed.
 * @param mixed $subject Optional Array or value that has data in potential multi-dimensions.
 *
 * @return array
 */
function array_flatten(?array $carry = [], $subject = null): array
{
    return array_reduce((array) ($subject ?? $carry), function(array $carry, $item) {
        return is_array($item)
            ? array_flatten($carry, $item)
            : array_merge($carry, (array) $item);
    }, $subject !== null ? (array) $carry : []); // Don't merge onto the $subject...
}

https://3v4l.org/J1NeJ

Thing is, the way it works, I think it literally goes one level further than there are levels to traverse. The reason I think this is because the array_merge() is getting passed a "boxed" element. So the way I'm adding to the array is to box/unbox an array wrapper so it can be merged.

That seems like the most amount of extra effort for one little thing; it happens to every non-array it comes across. Questioning whether I should use it.

It can be called like array_reduce():

array_reduce([1,2,[3,[4]],5], 'array_flatten');

Or more likely:

array_flatten([1,2,[3,[4]],5]);

Is this something I should avoid?


texts:
I have a complex phone validation that does the following:

First, check if either a home phone, mobile phone or work phone is provided (there will be 3 text fields in form and at least one type of phone number is required).
Strip out any characters from the phone number that is not a digit except 'x' and '+', since those represent extensions and are valid.
Make sure that the phones that were provided actually pass the phone number regex test.

And this is how I implemented the 3 steps above:

  VALID_PHONE_FORMAT = /\A(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?\z/

  validate :phone_provided
  before_validation :clean_phone_numbers
  validates_format_of :phone_home, with: VALID_PHONE_FORMAT, if: :home_is_filled?
  validates_format_of :phone_mobile, with: VALID_PHONE_FORMAT, if: :mobile_is_filled?
  validates_format_of :phone_work, with: VALID_PHONE_FORMAT, if: :work_is_filled?
  validates_format_of :phone_fax, with: VALID_PHONE_FORMAT, if: :fax_is_filled?

 private

  def clean_phone_numbers
    if phone_home.present?
      self[:phone_home] = strip_bad_characters :phone_home
    end
    if phone_mobile.present?
      self[:phone_mobile] = strip_bad_characters :phone_mobile
    end
    if phone_work.present?
      self[:phone_work] = strip_bad_characters :phone_work
    end
    if phone_fax.present?
      self[:phone_fax] = strip_bad_characters :phone_fax
    end
  end

  def strip_bad_characters(attr)
    send("#{attr}_before_type_cast").gsub(/[^\d+!x]/,'')
  end

  def phone_provided
    if phone_home.blank? && phone_mobile.blank? && phone_work.blank?
      errors.add(:base, "Must provide a phone number")
    end
  end

  def home_is_filled?
    !phone_home.blank?
  end

  def mobile_is_filled?
    !phone_mobile.blank?
  end

  def work_is_filled?
    !phone_work.blank?
  end

  def fax_is_filled?
    !phone_fax.blank?
  end

I particularly don't like how I am calling 4 different methods in the if condition for validates_format_of. I would like to only use one method and be able to tell which attribute to call blank? on. How can I refactor this?


texts:
I have the following codes, which I created as extension for datatable in my project.
It actually worked. Just wonder if there is any optimization can be made through. Thanks. =)

<Extension()>
Public Function HasNull(ByVal dataTable As DataTable) As Boolean
    For Each column As DataColumn In dataTable.Columns
        If dataTable.Rows.OfType(Of DataRow)().Any(Function(r) r.IsNull(column)) Then
            Return True
        End If
    Next
    Return False
End Function

<Extension()>
Public Function SetDefaultForNull(ByVal dataTable As DataTable) As DataTable
    For Each row As DataRow In dataTable.Rows
        For Each col As DataColumn In dataTable.Columns
            Dim value As Object = row(col)
            If IsDBNull(value) Then
                Dim dataType As String = col.DataType.ToString

                Select Case dataType
                    Case "System.DateTime"
                        value = New DateTime
                    Case "System.Decimal", "System.Int16", "System.Int32", "System.Int64"
                        value = 0
                    Case "System.String"
                        value = String.Empty
                    Case "System.Boolean"
                        value = False
                    Case Else
                        value = 0
                End Select
                row(col) = value
            End If
        Next
    Next
    Return dataTable
End Function


texts:
I write my log messages in JTextArea. Each message should have a time added.
I created a following method:

public void log(String message) {
    logTextArea.append(String.format("%s : %s%n",DateFormatUtils.ISO_TIME_NO_T_FORMAT.format(new Date()), message));
}

It uses DateFormatUtils from Apache Commons Lang.
Each time log() method is invoked, it creates a new instance of Date.

Is this the most elegant method?


texts: Fetching and formatting content from a database

texts:
I've wrote this script to fetch and format content from my DB. It also counts how many result there are and separates them into pages. I'm barely learning PHP and MySQL so I don't know much about performance.

function fetch_content($section, $subsection, &$count, $page = 0){
    $section = substr($section, 0,8);
    $subsection = substr($subsection, 0,8);
    require_once("system/config.php");
    //Initiate connection
        $mysqli = new mysqli($db_host, $db_user, $db_password, $db_database);
        if ($mysqli->connect_error) {
            die('Connect Error (' . $mysqli->connect_errno . ') '. $mysqli->connect_error);
        }
    //Select page
        $limit = 2;
        $start = $page * $limit ;

    //select query
        if($section == 'home' || ($section != 'home' && $subsection == NULL)){
            $selection =  "WHERE section = ?";
            }
        else
            $selection = "WHERE section = ? AND subsection = ?";

    //Fetch data
        $stmt = $mysqli->stmt_init();
        $qry= "SELECT * FROM public
        $selection
        ORDER BY id DESC LIMIT ?,?";
        $stmt->prepare($qry);
        if($section == 'home' || ($section != 'home' && $subsection == NULL))
            $stmt->bind_param("sss", $section, $start , $limit);
        else
            $stmt->bind_param("ssss", $section, $subsection, $start , $limit);
        $stmt->execute();
        $result = $stmt->get_result();
    //Format the data
        while( $row =  $result->fetch_assoc()){
            format_home($row, $mysqli);
        }
        $stmt->close();
    //Count result
        $stmt = $mysqli->stmt_init();
        $qry= "SELECT COUNT(*) AS count FROM public  $selection";
        $stmt->prepare($qry);
        if($section == 'home' || ($section != 'home' && $subsection == NULL))
            $stmt->bind_param("s", $section);
        else
            $stmt->bind_param("ss", $section, $subsection);
        $stmt->execute();
        $result = $stmt->get_result();
        $count = $result->fetch_assoc();
        $count =  $count['count'];
        $stmt->close();
    //close connection
        $mysqli->close();
}


texts: A Twitter bot that fetches Forecast.io data and tweets out the current weather with text and emojis

texts:
This is my first attempt at creating a Ruby script. I set up a Cron job to run this script every hour. I'm requesting constructive critiques and suggestions for making this better.

Sidenote: I've hard coded the location to my hometown. I don't plan on changing it to another location.

Here's an example of the expected output/tweet.

#!/usr/bin/env ruby
require 'twitter'
require 'forecast_io'
require 'gemoji'

client = Twitter::REST::Client.new do |c|
  c.consumer_key        = 'CONSUMER_KEY'
  c.consumer_secret     = 'CONSUMER_SECRET'
  c.access_token        = 'ACCESS_TOKEN'
  c.access_token_secret = 'ACCESS_TOKEN_SECRET'
end

ForecastIO.api_key = 'FORECAST_API_SECRET'
location           = ForecastIO.forecast(27.770, -82.638)
current_weather    = location.currently

icon =
  case current_weather.icon
  when 'clear-day'           then Emoji.find_by_alias('sunny').raw
  when 'clear-night'         then Emoji.find_by_alias('milky-way').raw
  when 'rain'                then Emoji.find_by_alias('umbrella').raw
  when 'snow'                then Emoji.find_by_alias('snowflake').raw
  when 'sleet'               then Emoji.find_by_alias('snowman').raw
  when 'wind'                then Emoji.find_by_alias('cyclone').raw
  when 'fog'                 then Emoji.find_by_alias('foggy').raw
  when 'cloudy'              then Emoji.find_by_alias('cloud').raw
  when 'partly-cloudy-day'   then Emoji.find_by_alias('partly_sunny').raw
  when 'partly-cloudy-night' then Emoji.find_by_alias('partly_sunny').raw
  when 'hail'                then Emoji.find_by_alias('cat').raw
  when 'thunderstorm'        then Emoji.find_by_alias('zap').raw
  when 'tornado'             then Emoji.find_by_alias('bangbang').raw
  else Emoji.find_by_alias('sunny').raw
  end

tweet = "Currently in #StPete it's #{current_weather.temperature.round}° & #{current_weather.summary.downcase} #{icon}"

client.update(tweet)


texts:
I've been trying to figure out the best way to create a inventory system in Python. I like the way this one works but what I was wondering was if there was a better way to write it.

inv = ['Sword','Armor']
item_values = {'Sword':['Sword',5,1,15,2],
               'Armor':['Armor',0,10,25,5]}
print('Name\tAtk\tArm\tLb\tVal')
print(item_values[inv[0]][0],'\t',item_values[inv[0]][1],'\t',item_values[inv[0]][2],'\t',item_values[inv[0]][3],'\t',item_values[inv[0]][4])
print(item_values[inv[1]][0],'\t',item_values[inv[1]][1],'\t',item_values[inv[1]][2],'\t',item_values[inv[1]][3],'\t',item_values[inv[1]][4])


texts: React app that interacts with CoinMarketCap API

texts:
I've started to fill my GitHub profile with small applications to educate and showcase my skills. However, I feel like I'm missing something essential, while creating these projects.

Could you take a look at this component, and advice me on how to refactor it? Its purpose is to get Coin Data from an API, and display the chart if the data is present :

import React from 'react';
import {connect} from 'react-redux';

import {formatCrypto} from '../../common/formating';

import ChartContainer from './chartContainer';

class Liquidity extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            chartData: [],
            minmaxValues: {},
            isLinear: false,
        };
    };

    /***
     * @method getDerivedStateFromProps - defines if the chart should be updated, since useEffect
     * hook was giving a warning for async component rendering
     * @param props - nextProps of the app
     * @param state - nextState of the app
     * @return {null} - returns null when there is no updates for the current state
     */
    static getDerivedStateFromProps({coinsData}, state) {
        if (!coinsData) return null;

        let parsedChartData = [];

        if (coinsData) {
            parsedChartData = [{
                id: 'CoinMarketCap API response',
                data: [...coinsData.map((el) => {
                    return {
                        id: el.id,
                        name: el.name,
                        marketCap: '$' + formatCrypto(el.quote.USD.market_cap, 3),
                        volume: '$' + formatCrypto(el.quote.USD.volume_24h, 3),
                        priceChange: formatCrypto(Math.abs(el.quote.USD.percent_change_24h)) + '%',
                        x: el.quote.USD.market_cap,
                        y: el.quote.USD.volume_24h,
                        z: Math.abs(el.quote.USD.percent_change_24h)
                    }
                })]
            }];

        }

        return {chartData: parsedChartData};
    }

    swapChart = () => {
        this.setState((prevState) => ({isLinear: !prevState.isLinear}));
    };

    render() {
        const {chartData, isLinear} = this.state;

        return (
            <>

Liquidity

                    <button
                        className={'btn btn-primary'}
                        type="button"
                        onClick={() => this.swapChart()}
                    >
                        Switch to {isLinear ? 'logarithmic' : 'linear'}
                    </button>

                <ChartContainer chartData={chartData} isLinear={isLinear}/>
            </>
        )
    }
}

const mapStateToProps = (state) => {
    const {coinsData} = state.cmcListCallReducer;

    return {coinsData};
};
export default connect(mapStateToProps)(Liquidity);

This component is a part of the largest app I've created so far. The app repo is here, in case you might be interested in a big picture. I will appreciate any kind of critics related to the project in general, since maybe my structure sucks more, than code styling.


texts: Is there any flaw in the logic of this problem?

texts:
The problem is find the number of factors of (N!)^2.

This is the code, I wrote:

int prime[]={//list of primes <(10^6)};
int num_fac_of_factorial(int n, int x)
{
    int p=x, z=0;
    while(n/p>0)
    {
        z+=n/p;
        p*=x;
    }
    return z;
}

int count=78498;   //Count of prime numbers <10^6

int main()
{
    int n, x, first=0, m=1000007;
    long long sol=1;
    scanf("%d", &n);

    for(int i=0; prime[i]<=n && i<count; i++)
    {
        x=num_fac_of_factorial(n, prime[i]);
        x=2*x+1;
        sol=(sol*x)%m;
    }
    sol%=m;
    printf("%d\n", sol);
}


texts: Checking if a date was increased by date-constants

texts:
At the moment I have a Reminder Date. In the UI I have two fields to create the reminder date. The first field is an int and the second field is a combo box.

public int Frequency {get; set;}
public ReminderComboItems item {get; set;}

public enum ReminderComboItems
{
    Minutes, Hours, Days, Weeks, Months, Years
}

public static DateTime ReminderComboItem(ReminderComboItems item, DateTime activityDate, int frequency)
{
    switch (item)
    {
        case ReminderComboItems.Minutes:
            date = date.AddMinutes(frequency);
            return date;
        case ReminderComboItems.Hours:
            date = date.AddHours(frequency);
            return date;
        case ReminderComboItems.Days:
            date = date.AddDays(frequency);
            return date;
        case ReminderComboItems.Months:
            date = date.AddMonths(frequency);
            return date;
        case ReminderComboItems.Years:
            date = date.AddYears(frequency);
            return date;
        default:
            return date;
    }
}

Using the top function creates the Reminder Date, now I'm trying to do the reverse.

public static ReminderDTO ReverseAppointment(DateTime activityDate, DateTime reminderDate)
{
    for (int i = 0; i < 100; i++)
    {
        var incrementedDate = reminderDate.AddYears(-i);
        if (incrementedDate == activityDate)
            return new reminderDTO{ ReminderComboItem = ReminderComboItems.Years, i};
    }
    for (int i = 0; i < 100; i++)
    {
        var incrementedDate = reminderDate.AddMonths(-i);
        if (incrementedDate == activityDate)
            return new ReminderDTO{ ReminderComboItem = ReminderComboItems.Months, i};
    }

   ...
   iterative loop for weeks, days, hours, minutes
   ...

    //default
    var minutes = activityDate.Subtract(reminderDate).TotalMinutes
    return new ReminderDTO{ ReminderComboItem = ReminderComboItems.Months, minutes};
}

I'm trying to have something that's less iterative, the fact that years/months aren't static(diff month lengths and leap years) it makes it a bit difficult. May I get some thoughts/opinions on this please.


texts: Shopping List Application (Work in Progress)

texts:
I'm new around here and want to involve myself with fellow developers and hopefully improve my skills here while attempting to help in any way I can with the knowledge I have so far. I'm a new Python programmer, been on and off it for years but have stuck to it recently officially.

I plan on making a career off of developing with it, whether it's data science, cyber security etc.

I plan on implementing some OOP in there instead of just straight functions:

import os

#create shopping list with automatic calculation

def display_help():
    print('''
    =======> Help <=======
    'HELP' to display this menu
    'START' to start creating your shopping list
    'SHOW' to display your current items
    'QUIT' to exit the program
    ''')
#create a list with the items needed
#

def clear_screen():
    os.system("cls" if os.name == "nt" else "clear")

#Create function to change values of current items or update price of items in the cart

def shopping_list():
    clear_screen()
    print('It\'s time to go shopping!')
    #Convert all floating point numbers to max digits of 2 after the decimal
    clear_screen()
    item_dict = {}
    print('Enter HELP at any moment if you need help or EXIT to return to the main menu')
    cart = 0
    def show_items():
        for key, value in item_dict.items():
            print(key + '-' * 5 + str(value))
        print('Current cart total: ',sum(item_dict.values()))
    while True:
        shop = input('Please enter an item: ')
        if shop.upper() == 'HELP':
            display_help()
            continue
        elif shop.upper() == 'EXIT':
           #Show total with taxes (or without taxes) with all the items in cronological order
           #start without taxes first
           print("Goodbye")
           break
        elif shop.upper() == 'SHOW':
            show_items()
            continue
        print(f'You have added {shop} to your list\n')
        try:
            cost = float(input(f'Price of {shop}: '))
            item_dict[shop] = cost
            cart = sum(item_dict.values())
            print(f'You entered {cost} as the price of {shop}\n')
            print(f'You now have {len(item_dict)} items in your list.\n')
            print(f'The total currently on your cart is {cart}')
            add_more_items = input('Would you like to add more items?(Y/N) ')
            if add_more_items == 'Y'.lower():
                continue
            else:
                print(f'Here\'s your cart and your total: \n')
                raise KeyboardInterrupt('Goodbye')
                continue
        except ValueError:
            print('Please enter a number')

def begin_attempt():
    print('Here\'s a list of possible commands: HELP, SHOP, EXIT')
    print('Welcome! What would you like to do?')
    while True:
        choose = input('> ')
        if choose.upper() == 'SHOP':
            print('Shopping has begun\n')
            shopping_list()
        elif choose.upper() == 'HELP':
            display_help()
            continue
        elif choose.upper() == 'EXIT':
            print("Goodbye")
            break

begin_attempt()

I still would like to add a lot more things, such as entering a specific state (or city in this case since I don't want to look up the taxes of every state) to calculate taxes, if there are discounts anywhere (I don't think I'll be adding that anytime soon or at all, but just an idea).


texts: Using AJAX to secure sessions and save messages

texts:
I have been working with PHP sessions and login protected pages for some time, but I want to start using some AJAX for managing some actions inside login protected pages (easy way with jQuery).

Here is what I want to do:

The user logs in (classic no-AJAX method), and wants to submit a message. I make a request with AJAX to another page, where the session is checked and the message is saved.

Here is how the start page looks:

<?php
    session_name('NEWSESSION');
    session_start();
    session_regenerate_id(true);

    if(!$_SESSION['user_logged']){
            header("location: login.php");
    }

    $sessionTTL = time() - $_SESSION["timeout"];
    if ($sessionTTL > SES_LENGHT) {
            session_destroy();
            header("location: login.php");
    }
?>

<textarea id="message">TEST</textarea>
<input type="" id="submit" value="Submit message">

And this is save.php where I send the request (and sends a "msg saved" alert):

<?php
session_name('NEWSESSION');
session_start();
session_regenerate_id(true);

if(!$_SESSION['user_logged']){
    header("location: login.php");
}

$sessionTTL = time() - $_SESSION["timeout"];
if ($sessionTTL > SES_LENGHT) {
    session_destroy();
    header("location: login.php");
}

$username = $_SESSION['user_username'];

if($_POST["action"] == "save_message"){
    /* PHP code for saving message */
    echo "Message saved!";
}
?>

Is this the right way to do this? And how vulnerable is this (is it more vulnerable than to do it with classic PHP methods, with no fancy AJAX things)? All suggestions are welcome.


texts: Build a flat List from a Tree structure in Java

texts:
I have a Tree structure represented by a List, which I want to get it flattened.

I wrote the function below:

List<Entry> flatTree(List<Entry> toFlat, List<Entry> destination) {
    for (Entry entry : toFlat) {
        if (CollectionUtils.isNotEmpty(entry.getEntries())) {
            this.flatTree(entry.getEntries(), destination);
        } else {
            destination.add(entry);
        }
    }
    return destination;
}

used in this way:

List<Entry> flattenedEntries = this.flatTree(entries, new ArrayList<>());

with this kind of input (entries):

[
    {
        key: "level1.1",
        entries: []
    },
    {
        key: "level1.2",
        entries: [
            {
                key: "level2.1",
                entries: []
            }
        ]
    },
    {
        key: "level1.3",
        entries: [
            {
                key: "level2.2",
                entries: []
            },
            {
                key: "level2.3",
                entries: [
                    {
                        key: "level3.1",
                        entries: []
                    }
                ]
            }
        ]
    }
]

What I'm going to achieve is to have a list containing only objects with keys: level1.1, level2.1, level2.2, level3.1 or rather, all the elements that has no sub elements entries.

Each object has just 2 properties inside: key and entries.

It works, but I would like to avoid the side effect on the List<Entry> destination. Is there a better way to write it?


texts:
The Julia set is the set of complex numbers z that do not diverge under the following iteration:

$$ z = z^2 + c $$

Where c is a constant complex number.

Different values of z reach infinity at different rates. A colourful fractal is produced by colouring the complex plane based on the number of iterations required to reach infinity.

function colour = julia(c, total_iterations, image_size, limits)
%   Calculates julia set by iterating z = z^2 + c, where z and c are complex,
%   and recording when z reaches infinity.
%
%   Inputs:
%
%   c                   Fixed complex number, of form a + bi
%   total_iterations    Number of iterations of z = z^2 + c
%   image_size          2D vector with number of complex coordinates in
%                           x and y directions
%   limits              Vector with 4 elements: min x, max x, min y, max y
%
%   Outputs:
%
%   colour              Matrix of doubles, with size equal to image_size.
%                           Plotting this matrix will produce a julia set

im_step = (limits(4) - limits(3)) / (image_size(2) - 1);
re_step = (limits(2) - limits(1)) / (image_size(1) - 1);

reals = limits(1) : re_step : limits(2);            % Real numbers
imags = limits(3) : im_step : limits(4);            % Imaginary numbers
z = bsxfun(@plus, reals(:), (imags(:) * 1i)');      % Complex coordinates
colour = inf(size(z));                              % Colour of Julia set

for iteration = 1:total_iterations
    index = isinf(z);
    % Only perform calculation on the z values that are less than infinity
    z(~index) = z(~index).^2 + c;
    % Colour depends on number of iterations to reach infinity
    colour(index & isinf(colour)) = iteration;
end

colour = colour'; % Transpose so that plot will have reals on the x axis

end

Example:

image_size = [1000 1000];   % Image size
limits = [-1.5 1.5 -1 1];   % Real and imaginary limits
c = -0.4 + 0.6i;            % Fixed complex number
total_iterations = 300;

colour = julia(c, total_iterations, image_size, limits);

I = imagesc(colour);
colormap(hot)
myaa('publish')

Note: myaa is a 3rd party  anti-aliasing function.


texts: Mean of the squares of differences for a large matrix

texts:
I have tried to obtain speed gains by transferring Matlab calculations to C and call it using .mex. My goal is to operate on a matrix \$B\$  which has roughly the dimension 10000x1000

$$
\frac{1}{\text{size(B,1)}}\sum_{i=1}^{2+l*t} \text{mean}( (B(:,i)-B(:,i+1))^2)$$

for \$ l*t<\text{size(B,2) and chosen } t \in \mathbb{N}\$.

My matlab code is as follows:

A=randn(10000,1000);

tic
RVV_Da_path=ones(size(A,2)-1,1);
i=2;
j=1;
while i <= size(A,2)+1-t_step
   RVV_Da_path(j)=    sum(mean(diff((A(:,1:i)),1,2).^2,1));
   i=i+t_step;
   j=j+1;
end
RVV_Da_path(j)=    sum(mean(diff((A(:,1:end)),1,2).^2,1));
toc

My C code goes as follows:

#include <math.h>
#include "mex.h"

void mexFunction(int nlhs, double *plhs[], int nrhs, const mxArray *prhs[])
{

  // calculate 1/size(A,1)*sum_{i=1}^{2+l*t} mean(A(:,i)-A(:,i+1))^2, for l*t < size(A,2), t \in N

#define RV_Out  plhs[0]
#define A_In    prhs[0]
#define t_In    prhs[1]

  double *A,*RV,p,Num_Of_Rows;
  int M, N,Mt,t,i,j,m,k;

  A=mxGetPr(A_In);

  t=mxGetScalar(t_In);
  M=mxGetM(A_In);

  Num_Of_Rows=mxGetM(A_In);
  N=mxGetN(A_In);

  RV_Out=mxCreateDoubleMatrix(1, N, mxREAL); // init vektor to save the sum of squared first differences
  RV = mxGetPr(RV_Out);
  memset(RV, 1, N);

  i=0;
  k=0;
  while(i < N-t)
  {
    for(j=0;j<=i;j++)
    {
      for(m=0;m<M;m++)
      {
        RV[k]+=1/Num_Of_Rows*(pow(A[m + M * j]  -  A[m + M * (j+1)],2.0)) ; // calculate the sum of squared first differences until last possible step
      }
    }

    i+=t;
    k++;
  }

  for(j=0;j<N-1;j++)
  {
    for(m=0;m<M;m++)
    {
      RV[k]+=1/Num_Of_Rows*(pow(A[m + M * j]  -  A[m + M * (j+1)],2.0)) ; // calculate the sum of squared first differences until end
    }
  }

  for(i=k+1;i<N;i++) RV[i]=1;  // set the remaining entries equal to 1
  return;

}

Now when I translate the C code to a .mex file and compare the speed of the Matlab and the C code the C code is roughly 4-8 times slower for big \$ B\$'s. Why is this the case? Where is the bottleneck in my C-code and how can I work around it?


texts:
I'm willing to simplify the use of the ASP.NET cache.

I wrote this helper class:

public static class CacheHelper
{
    public static T GetCached<T>(string key, Func<T> initializer, DateTime absoluteExpiration)
    {
        return GetCached(key, initializer, Cache.NoSlidingExpiration, absoluteExpiration);
    }
    public static T GetCached<T>(string key, Func<T> initializer, TimeSpan slidingExpiration)
    {
        return GetCached(key, initializer, slidingExpiration, Cache.NoAbsoluteExpiration);
    }
    public static T GetCached<T>(string key, Func<T> initializer, TimeSpan slidingExpiration, DateTime absoluteExpiration)
    {
        var httpContext = HttpContext.Current;

        if (httpContext != null)
        {
            var obj = httpContext.Cache[key];
            if (obj == null)
            {
                obj = initializer();
                httpContext.Cache.Add(key, obj, null, absoluteExpiration, slidingExpiration, System.Web.Caching.CacheItemPriority.Default, null);
            }
            return (T)obj;
        }
        else
        {

            return initializer(); // no available cache
        }
    }
}

The idea is to let the developer write its method as usual, but wrapping it like this:

public MyClass GetSomeCachedData(){
            return CacheHelper.GetCached(
                "GetSomeCachedData, () =>
                {

                        return ComputeExpensiveResult();
                }
                }, TimeSpan.FromMinutes(1), Cache.NoAbsoluteExpiration);
}

Do you see any issues?  Can it be improved?

(I'm sticking to .NET 3.5)


texts:
I am writing a class that has a few std::string as a member. I can't find clear guidelines on how use them in a safe way. Are std::string any different then int when we are talking about class members? Do I initialize the strings in the correct way? (How) can I improve the constructor?

#include <string>
#include <iostream>

class Student {
public:
    std::string name;
    Student(std::string name) {
        this->name = name;
    }
};

int main() {
    std::string name1 = "john";
    Student student1(name1);
    name1 = "jenny";
    std::cout << student1.name << std::endl;
    {
        std::string name2 = "ashley";
        student1.name = name2;
        name2 = "remy";
    }
    std::cout << student1.name << std::endl;
    return 0;
}

Which gave the following output as intended:

  john
  ashley


texts:
This is a revised follow-up to this question.

I have implemented most of the suggestions in the accepted answer. I am interested to see what I could improve in my code and what I could do to make it better.

  I have implemented counting sort in C. This program takes its input as integers from command line arguments, sorts the integers with counting sort, then outputs the sorted array.

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

int max(int* arr, size_t len) {
    if (len < 1) {
        return 0;
    }
    int greatest = arr[0];
    for (size_t i = 0; i < len; i++)
        if (arr[i] > greatest)
            greatest = arr[i];
    return greatest;
}

void sort(int* inputs, int* outputs, size_t length) {
    // this is the size of the array of counts
    int greatest = max(inputs, length); // find the greatest number in the array

    // allocate the array of counts
    int* counts = calloc(greatest + 1, sizeof(int));
    if (counts == NULL) {
        fprintf(stderr, "Memory allocation error\n");
        exit(EXIT_FAILURE);
    }

    // count numbers in input array
    for (size_t i = 0; i < length; i++) {
        counts[inputs[i]]++;
    }

    size_t counter = 0; // keep track of where we are in output array

    // loop through all the counts
    for (int i = 0; i <= greatest; i++) {   // for every count in array
        for (int j = 0; j < counts[i]; j++) {   // loop that many times
            outputs[counter++] = i; // add the integer being counted to the output array
        }
    }
    free(counts);
}

int main(int argc, char** argv) {
    int *inputs, *outputs;
    size_t length = argc - 1;   // number of integers to sort

    if (argc < 2) {
        fprintf(stderr, "Not enough arguments given.\n");
        exit(EXIT_FAILURE);
    }

    inputs = calloc(length, sizeof(int));
    outputs = calloc(length, sizeof(int));

    if (inputs == NULL || outputs == NULL) {
        fprintf(stderr, "Memory allocation error\n");
        exit(EXIT_FAILURE);
    }

    for (int i = 1; i < argc; i++) {
        inputs[i - 1] = atoi(argv[i]);  // assign arguments to array
        if (inputs [i - 1] < 0) {
            fprintf(stderr, "Integer %d out of range [0, 2^31)\n", inputs[i - 1]);
            exit(EXIT_FAILURE);
        }
    }

    sort(inputs, outputs, length);

    for (size_t i = 0; i < length; i++) {
        printf("%d ", outputs[i]);  // print space separated sorted numbers
    }
    printf("\n");

    free(inputs);
    free(outputs);

    return EXIT_SUCCESS;
}


texts:
I just finished a fairly easy homework assignment. Basically all I had to do was add six JPanels that were just text boxes with color names as the text.  However, the color of the font had to match the text, so for instance, black had to be black, blue had to be blue, etc.  It works find but it just seems like I could have shortened this code up a little.

import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.*;

public class SixLabels extends JFrame
{
    public SixLabels()
    {
        // sets layout of square
        setLayout(new GridLayout(2,3));

        //set JLabel properties such as border, text, font, etc.
        Border line =  new LineBorder(Color.yellow, 4);
        Font TNR = new Font("Times New Roman", Font.BOLD, 20);
        JLabel black = new JLabel("Black", JLabel.CENTER);
        JLabel blue = new JLabel("Blue", JLabel.CENTER);
        JLabel cyan = new JLabel("Cyan", JLabel.CENTER);
        JLabel green = new JLabel("Green", JLabel.CENTER);
        JLabel magenta = new JLabel("Magenta", JLabel.CENTER);
        JLabel orange = new JLabel("Orange", JLabel.CENTER);

        // add set properties and add panel to JFrame
        black.setOpaque(true);
        black.setForeground(Color.black);
        black.setBackground(Color.white);
        black.setBorder(line);
        black.setFont(TNR);
        black.setToolTipText("This is Black");
        add(black);

        // add set properties and add panel to JFrame
        blue.setOpaque(true);
        blue.setForeground(Color.blue);
        blue.setBackground(Color.white);
        blue.setBorder(line);
        blue.setFont(TNR);
        blue.setToolTipText("This is Blue");
        add(blue);

        // add set properties and add panel to JFrame
        cyan.setOpaque(true);
        cyan.setForeground(Color.cyan);
        cyan.setBackground(Color.white);
        cyan.setBorder(line);
        cyan.setFont(TNR);
        cyan.setToolTipText("This is Cyan");
        add(cyan);

        // add set properties and add panel to JFrame
        green.setOpaque(true);
        green.setForeground(Color.green);
        green.setBackground(Color.white);
        green.setBorder(line);
        green.setFont(TNR);
        green.setToolTipText("This is Green");
        add(green);

        // add set properties and add panel to JFrame
        magenta.setOpaque(true);
        magenta.setForeground(Color.magenta);
        magenta.setBackground(Color.white);
        magenta.setBorder(line);
        magenta.setFont(TNR);
        magenta.setToolTipText("This is Magenta");
        add(magenta);

        // add set properties and add panel to JFrame
        orange.setOpaque(true);
        orange.setForeground(Color.orange);
        orange.setBackground(Color.white);
        orange.setBorder(line);
        orange.setFont(TNR);
        orange.setToolTipText("This is Orange");
        add(orange);

    }

    public static void main(String[] args)
    {
        SixLabels frame = new SixLabels(); // creates frame
        frame.setTitle("Chapter 12 Exercise 12.8"); // sets name on title bar
        frame.setSize(600, 400); // sets size of GUI frame
        frame.setLocationRelativeTo(null); // Centers GUI frame
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Stop/Close program on exit
        frame.setVisible(true); // Shows the frame, must be true

    }

}


texts: C++ Trie using std::map and std::unique_ptr

texts:
I'm learning C++ and whilst trying to write in modern C++, I've made an attempt to rewrite a trie implementation written in C found here: http://www.geeksforgeeks.org/trie-insert-and-search/

It uses arrays to hold the branches in each node and because it's C it was done using malloc() and no freeing of memory was done in the example.

Is this an efficient approach of representing a trie in C++11? what other ways can I store children in trie nodes?

#include <iostream>
#include <map>
#include <algorithm>
#include <memory>

class Trie {
    struct Node;
    typedef std::unique_ptr<Node> spNode;
    struct Node {
        std::map<char, spNode> children;
        bool isLeaf;
        Node() : isLeaf{false} {}
    };

    spNode root;
public:
    Trie();
    void insert(const std::string& str);
    bool search(const std::string& str);
};

Trie::Trie():root{nullptr}{}

void Trie::insert(const std::string& str) {
    if (root == nullptr) {
        std::unique_ptr<Node> node(new Node());
        root = std::move(node);
    }

    Node *temp = root.get();
    for (const char& c : str) {
        if (temp->children.find(c) == temp->children.end()) {//if char not in map
            std::unique_ptr<Node> node(new Node());
            temp->children[c] = std::move(node);
        }

        temp = temp->children[c].get();
    }

    temp->isLeaf = true;
}

bool Trie::search(const std::string &str) {
    if (root == nullptr) return false;

    Node *temp = root.get();
    for (const char& c : str) {
        if (temp->children.find(c) == temp->children.end())
            return false;
        temp = temp->children[c].get();
    }
    return (temp->isLeaf);
}

int main (void) {
    std::string words[] = { "Hello", "hi", "hey", "howdy", "ho"};
    Trie test;

    for (const auto& str : words) {
        test.insert(str);
    }

   if (test.search("Hello"))
       std::cout << " 'Hello' is found in the trie\n";
    else
       std::cout <<" 'Hello' is not found in the trie\n";

   if (test.search("yo"))
       std::cout << " 'yo' is found in the trie\n";
    else
       std::cout << " 'yo' is not found in the trie\n";

}


texts:
I initially posted this on StackOverflow, and was redirected here.
I have been playing around with Bouncy Castle (Java) for the last few days, and I've reached the point where I believe I can securely exchange secret keys with a Diffie-Hellman exchange.

Having read many posts underlining the difficulty of properly implementing a cryptographic exchange, I would like your honest opinion on my work.
All the underlying cipher operations are based on Bouncy Castle and may therefore be deemed reliable.

String message = "Hello World";

AESCipher aes_client = new AESCipher(256);
RSACipher rsa_server = new RSACipher(2048);

// (Public key sent over the wire)
RSACipher rsa_client = new RSACipher(rsa_server.getPublicKey().getModulus(),
                                     rsa_server.getPublicKey().getExponent());

// The client encodes his AES key with the RSA public key:
byte[] aes_key = rsa_client.encode(aes_client.getKeyBytes());
byte[] aes_iv = rsa_client.encode(aes_client.getInitializationVector());

// (Data sent back over the wire)
byte[] decoded_aes_key = rsa_server.decode(aes_key);
byte[] decoded_aes_iv = rsa_server.decode(aes_iv);

// The server creates an AES server which uses the client key:
AESCipher aes_server = new AESCipher(decoded_aes_key, decoded_aes_iv);

byte[] encoded_message = aes_client.encode(message.getBytes());
byte[] decoded_message = aes_server.decode(encoded_message);

System.out.println(new String(decoded_message));

Can this exchange be considered safe? Should I be sticking with SSL Sockets, eventhough it'd hurt to thrash my hard work?
Thanks in advance for your input!

(By the way, my Bouncy-Castle-Wrapping-Library is totally open-source, so just let me know if you want the repository's URL.)


texts: Appending unique data to a postgres table

texts:
I receive daily files (filename_%m_%d_%Y.csv) from a client and I read those in pandas, process them, and store them in Postgres. Sometimes there are delays and we do not get the data for a few days. The problem is that I have everything on a scheduled task and I do not want to manually check if the files exist or not before I run my code since I am using append mode on Postgres (and do not have constraints set up yet).

My approach here is to read the last few days of data from my existing database, and then find the max date in order to know where to start reading new data from. So if the max date is Jan 22, I will know that the start date for reading my new files is Jan 23 onward. Is this a decent approach?

central_time = dt.datetime.now(pytz.timezone('US/Central'))
start_date = central_time - pd.Timedelta(days = 7)
engine = sa.create_engine('postgresql://usr:pass@localhost:XXXX/db')
df = pd.read_sql(sa.text('SELECT * FROM table WHERE report_date > :date'), engine, params={'date': start_date}, parse_dates = ['report_date'])
latest_date = df.report_date.max() + pd.Timedelta(days = 1)

Up until this week I have been exclusively using .csv files. My approach here was to find the beginning of the month and read all files from the beginning of the month until the current date. This meant that everyday I would overwrite my file (So this month I would read Jan 1 - 27 daily files, and create a January file, then tomorrow I would read Jan 1 - 28 daily files and then overwrite my previous MTD file).

start_date = (central_time - pd.Timedelta(days = 0)) - pd.offsets.MonthBegin()
end_date = central_time
days = ((pd.Timestamp(end_date) - pd.Timestamp(start_date)) / np.timedelta64(1, 'D')).astype(int)

def last_n_days(filename, num_of_days, include_curr = False):
    f = '%m_%d_%Y'
    curr = end_date
    if include_curr:
        yield curr.strftime(f)
    for num in range(num_of_days):
        curr = curr - dt.timedelta(days = 1)
        yield curr.strftime(f)


texts:
I'm new to Java so I have given myself small projects to help myself learn the ropes of java. My project was to create a function that would summate an expression no matter how high the degree or value of n.
I ended up being able to complete it but I wanted someone who knew what they were doing to look over it and see if I was doing things the right way.
A goal was to use no pre-built packages but I ended up using the java.lang.Math.pow() function (I didn't import it).
Also, what recommendations do you have for learning for beginners? I do have some experience programming but I feel like I never learned the correct way...
Code:
package TestSpace;
public class MathClass {

/*
    Steps:
    1. Get array of any length and n
    2. Reverse list so highest degree coefficients are last
    3. Run for loop for each time n increases
    4.Run for loop inside of that for each entry in array
*/

    //args consists of the coefficients of x; must include all degrees of x counting down from the highest degree
    public static float sigma (int[] args, int n) {
        float value = 0;
        int length = args.length;
        //reverses list
        int[] reverselist = reverselist(args);

        for(int i = 1;i<n+1;i++) {

            for(int v = 0; v < length;v++) {
                // Multiplies coefficient by "x" raised to the power of its degree
                value += reverselist[v] * java.lang.Math.pow(i, v);
            }
        }
        return value;
    }

//Reverses the order of the given array so that highest degree is at the end
    public static int[] reverselist(int[] args) {
        int length = args.length;
        int[] newint = new int[length];
        for(int i = 0;i<length;i++) {
            newint[i] = args[length - (i+1)];
        }
        return newint;
    }

//Makes printing simple
    public static void print(Object obj) {
        try {
            System.out.println(obj);
        }catch(Exception e){
            System.out.println(e);
        }
    }

    //main function
    public static void main(String[] args) {
        print(sigma(new int[] {5,2,7,4},4));
    }
}


texts: Shank Transformation to Lebniez series to find Pi recursively

texts:
I found a simple series named the Lebniez series for finding Pi.
$$1 - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + \frac{1}{9} - \dots = \frac{\pi}{4}$$
I made this in Python. I then realised that because it is an infinite series, and it will give an approximation. Additionally the convergence rate is very slow.
Here is the program I made after learning about series acceleration through the Shank Transform:
def lebniez(n):
    pi = 0
    n = n + 1
    for i in range(1,n):
        if(i % 2 == 1):
            pi -= 1 / (2*i - 1)
        else:
            pi += 1/(2*i - 1)
    pi = abs(4 * pi)
    return pi

def accelrate(n,depth):
    if depth == 1:
        a = lebniez(n + 1)
        b = lebniez(n)
        c = lebniez(n-1)
        return (a*c - b*b)/(a + c - 2*b)
    a = accelrate(n + 1,depth - 1)
    b = accelrate(n,depth - 1)
    c = accelrate(n-1,depth - 1)
    return (a*c - b*b)/(a + c - 2*b)

I have applied the shank transformation and gotten a new series. After this I continuously apply it recursively. However using recursion has made it very slow. If I keep accelerating the function then after some depth the accuracy starts decreasing.


texts:
I am a Javascript/JQuery beginner working on my first ever project. Everything in this program is working as it should and I am happy with its performance. I have pieced it together from a variety of sources and lots of trial and error.

Because this is so new to me I wanted some experienced opinions on the way I have used the various Javascript/JQuery components in my project. The code I have included here has been edited and simplified for clarity but in its entirety it is a working program so I'm not necessarily looking to have it rewritten but more looking for feedback on what I have done to see where I can improve my programming skills.

In particular am I following good programming protocols with my structure and layout of various elements and functions etc.?
Should I change, combine or separate components etc. to simplify coding whilst still allowing me to increase functionality should I want to extend the program further?
Are there better ways through HTML or otherwise to more efficiently achieve the outcomes I have noted in comments?

   <video id="videoElement" ><source src="video.mp4" > </video>

 <button on="" onclick="playVid();">Start video</button>

Click video to respond


texts: Passing multiple parameters to an SQL query

texts:
I am trying to use this VBA code to pass a SQL stored procedure multiple values from an excel sheet.

In order to have the procedure run multiple times and insert multiple sets of information into the database, I copied and pasted the parameter section of the code each time I wanted to insert new data and hard coded which excel cell to pull data from.

Is there a way to consolidate the code so that I can reference cells A1:A10 for parameter 1, cells B1:B10 for parameter 2, cells C1:C10 for parameter 3 and so on without copying the code over again?

Sub Module2()
Dim cnSQL As ADODB.Connection
Dim sqlCommand As ADODB.Command
Dim prm As ADODB.Parameter

Set cnSQL = New ADODB.Connection
cnSQL.Open "Provider=SQLOLEDB.1; uid=test; Pwd=test; Initial Catalog = test; Data source=test"

Set sqlCommand = New ADODB.Command
sqlCommand.ActiveConnection = cnSQL
sqlCommand.CommandType = adCmdStoredProc
sqlCommand.CommandText = "EstimateInsertUpdate"

Set prm = sqlCommand.CreateParameter("CD", adVarChar, adParamInput, 10)
sqlCommand.Parameters.Append prm
sqlCommand.Parameters("CD").Value = Worksheets("Sheet1").Range("B5")

Set prm = sqlCommand.CreateParameter("Date", adDate, adParamInput)
sqlCommand.Parameters.Append prm
sqlCommand.Parameters("Date").Value = Worksheets("Sheet1").Range("F5")

Set prm = sqlCommand.CreateParameter("Test", adDecimal, adParamInput)
prm.Precision = 4
prm.NumericScale = 4
sqlCommand.Parameters.Append prm
sqlCommand.Parameters("Test").Value = Worksheets("Sheet1").Range("E5")

Set prm = sqlCommand.CreateParameter("EDtm", adDate, adParamInput)
sqlCommand.Parameters.Append prm
sqlCommand.Parameters("EDtm").Value = Worksheets("Sheet1").Range("D5")

Set prm = sqlCommand.CreateParameter("UserID", adVarChar, adParamInput, 10)
sqlCommand.Parameters.Append prm
sqlCommand.Parameters("UserID").Value = Worksheets("Sheet1").Range("G5")

sqlCommand.Execute

Set cnSQL = New ADODB.Connection
cnSQL.Open "Provider=SQLOLEDB.1; uid=test; Pwd=test; Initial Catalog = PMW; Data source=test"

Set sqlCommand = New ADODB.Command
sqlCommand.ActiveConnection = cnSQL
sqlCommand.CommandType = adCmdStoredProc
sqlCommand.CommandText = "EstimateInsertUpdate"

Set prm = sqlCommand.CreateParameter("CD", adVarChar, adParamInput, 10)
sqlCommand.Parameters.Append prm
sqlCommand.Parameters("CD").Value = Worksheets("Sheet1").Range("B6")

Set prm = sqlCommand.CreateParameter("Date", adDate, adParamInput)
sqlCommand.Parameters.Append prm
sqlCommand.Parameters("Date").Value = Worksheets("Sheet1").Range("F6")

Set prm = sqlCommand.CreateParameter("Test", adDecimal, adParamInput)
prm.Precision = 4
prm.NumericScale = 4
sqlCommand.Parameters.Append prm
sqlCommand.Parameters("Test").Value = Worksheets("Sheet1").Range("E6")

Set prm = sqlCommand.CreateParameter("EDtm", adDate, adParamInput)
sqlCommand.Parameters.Append prm
sqlCommand.Parameters("EDtm").Value = Worksheets("Sheet1").Range("D6")

Set prm = sqlCommand.CreateParameter("UserID", adVarChar, adParamInput, 10)
sqlCommand.Parameters.Append prm
sqlCommand.Parameters("UserID").Value = Worksheets("Sheet1").Range("G6")

sqlCommand.Execute

End Sub


texts:
I recently came across the need to allow consumers to prevent further execution of methods and I utilized an event driven system that allows the consumer to specify if the execution should cancel. I've tested it in a multi-threaded environment and everything is working as expected so as a simple solution it works as intended with no issues. However, I can't help but wonder where there are improvements that could be made as I've never dealt with event cancellations before.
Event Arguments Definition
public class CustomEventArgs {
    public bool Cancel { get; set; } = false;
}

I'm not sure that a default value for the Cancel property is a good idea here.
Object Definition
public class MyCustomObject {
    public void Count(int countTo) {
        if (ShouldCount()) {
            for (int i = 0; i < countTo;)
                Console.WriteLine(++i);
        } else
            Console.WriteLine("Counting process was cancelled by the consumer.");

        Console.WriteLine("The counting process has completed.");
    }
    public event EventHandler<CustomEventArgs> OnStarting;
    private bool ShouldCount()
    {
        Console.WriteLine("The counting process is starting.");
        CustomEventArgs args = new CustomEventArgs();
        OnStarting?.Invoke(this, args);
        return !args.Cancel;
    }
}

I believe that return !args.Cancel is a little confusing to read as negative logic. Perhaps it should be return args.Cancel and the method should be renamed to something like ShouldCancelCounting and check for if (!ShouldCancelCounting()) instead of if (ShouldCount())?
Consumption
private static bool CancelEvent = false;
private static void RunTest() {
    CancelEvent = false;
    MyCustomObject obj = new MyCustomObject();
    obj.OnStarting += CountStarting;
    obj.Count(100);

    CancelEvent = true;
    MyCustomObject obj = new MyCustomObject();
    obj.OnStarting += CountStarting;
    obj.Count(100);
}
private static void CountStarting(object sender, CustomEventArgs e) {
    e.Cancel = CancelEvent;
}

What are some areas that are harder to follow with this implementation? Is there anything confusing about it in any way? Is there any official Microsoft documentation on implementing event cancellations? What are some potential gotchas with my implementation?


texts: Map a range of integers to a 64-bit integer

texts:
Given a 64-bit integer x (which is always larger than 0), we wish to map it to an index so that:

when x is between 0..64, we map it to 0,
when x is between 65..128, we map it to 1,
when x is between 129..192, we map it to 2, etc.

Writing such a function get_index(x) is simple, consider say the following program:

#include <iostream>
#include <cstdint>
#include <cmath>
#include <cassert>

// For benchmarking
#include <vector>
#include <algorithm>

std::uint64_t get_index(std::uint64_t x)
{
    return std::ceil(x / 64.0) - 1;
}

int main()
{
    // To see the expected outcome.
    /*
    for (int i = 1; i <= 129; ++i)
    {
        std::int64_t idx = get_index(i);
        std::cout << "i : " << i << " = " << idx << "\n";
    }
    */

    // A small performance benchmark.
    // Just in case print something so that the compiler doesn't optimize things away.
    std::vector<std::uint64_t> dummy;
    const std::uint64_t MAX = 10000000;
    for (std::uint64_t i = 1; i <= MAX; ++i)
    {
        dummy.push_back(get_index(i));
    }

    std::cout << dummy.size() << " " << *max_element(dummy.begin(), dummy.end()) << "\n";
}

Is there a (much) faster implementation for get_index(x)? Likely one that completely avoids floating-point math, ceilings etc.

For instance, I know that dividing by 64 is the same thing as bit-shifting x to the right by 6, but I'm not much of a bit hack wizard to figure out the rest without resorting to things that seem messy.


texts:
I am trying to work around the problem Pass-through for IAsyncEnumerable. The best I have so far is to return IAsyncEnumerable<IAsyncEnumerable<T>> instead of IAsyncEnumerable<T>, then to flatten it. I'm not thrilled about it, so I'm asking here for suggestions.

The underlying goal is to allow one to get portions of one's IAsyncEnumerable from child methods without going insane. The Counting() method below is my attempt.

I don't think it would be much trouble to design a recursive object in order to allow deeper nesting. But I still don't think I would like it much.

public static class AsyncEnumerables
{
    public static async IAsyncEnumerable<T> Flatten<T>(IAsyncEnumerable<IAsyncEnumerable<T>> enumerables)
    {
        await foreach (var e in enumerables)
        {
            await foreach (var t in e)
            {
                yield return t;
            }
        }
    }

    public static async IAsyncEnumerable<T> Singleton<T>(T t)
    {
        await Task.CompletedTask;
        yield return t;
    }
}

public class AsyncEnumerableTests
{
    public async IAsyncEnumerable<int> Children()
    {
        yield return 1;
        await Task.Delay(1000);
        yield return 2;
    }

    public async IAsyncEnumerable<IAsyncEnumerable<int>> Counting()
    {
        yield return AsyncEnumerables.Singleton(0);
        await Task.Delay(100);
        yield return Children();
        yield return AsyncEnumerables.Singleton(3);
    }

    [Fact]
    public async Task Counting_Counts()
    {
        var numbers = new List<int>();
        await foreach (var n in AsyncEnumerables.Flatten(Counting())) {
            numbers.Add(n);
        }
        Assert.Equal(4, numbers.Count);
        for (int i=0; i<4; i++)
        {
            Assert.Equal(i, numbers[i]);
        }
    }
}


texts: Improving performance of A* search in PHP

texts:
I need to figure out what can be done to improve the performance of a A* search algorithm in PHP. The idea is to look for the shortest path, in number of hops, between two points in a "map". Actual distance is irrelevant.

This is a minimalistic functional version of what I'm doing:

<?php

    /*

        1 ____ 2 ____ 3 ___ 5
        | \            ____/|
        |  \    ______/     |
        |   4__/            |
        |  /                7
        | /
        6

    */

    $points = [
        1 => [2, 4, 6],
        2 => [1, 3],
        3 => [2, 5],
        4 => [1, 5, 6],
        5 => [3, 4, 7],
        6 => [1, 4],
        7 => [5]
    ];

    function points_pathfind($from, $to)
    {
        global $points;

        if (!isset($points[$from]) || !isset($points[$to]))
            return null;

        if ($from == $to)
            return [$from];

        $seen = [$from];  // improves peformance
        $queue = [];
        $step = [$from, null];
        for (;;)
        {
            if ($queue)
            {
                $step = array_shift($queue);
                if ($step[0] == $to)
                {
                    $result = [];
                    while ($step !== null)
                    {
                        $result[] = $step[0];
                        $step = $step[1];
                    }
                    return array_reverse($result);
                }
            }
            foreach ($points[$step[0]] as $point)
            {
                if (!in_array($point, $seen))
                {
                    $seen[]  = $point;
                    $queue[] = [$point, $step];
                }
            }

            if (!$queue)
                return null;
        }
    }

    echo implode(' -=> ', points_pathfind(1, 7));

Output:

  1 -=> 4 -=> 5 -=> 7

The actual code howover will deal with almost 8000 points with a total of over 15000 connections, in which it all become extremely slow to the point that mapping some paths can take a couple seconds. This is unacceptable to my application. I even considered caching all possibilities to a database (which I will have to do anyway) but it is so slow it would take days only to generate this cache. I'm sure its performance can be improved somehow, I just can't figure out how.


texts: Improve nested loop for bio-statistics calculation

texts:
I am doing a bio-statistics calculation and the following code works. However, can someone help to improve the messy nested loop?

for(int i=0; i<NN; i++) {
    for (int j=0; j<NN; j++) {
        if (i != j){
            thirdlayer = 0;
            for (int k=0; k<NN; k++) {
                fourthlayer = 0;
                for (int l=0; l<NN; l++) {
                    fourthlayer =  fourthlayer + V[j*NN+l]*V[NN+l]*J[k*NN+l];
                }
                thirdlayer = thirdlayer + V[k]*V[i*NN+k]*fourthlayer;
            }
            if(pi_cod[j] != 0)
                Transitions[i*NN +j] =  sqrt(pi_cod[i]*pi_cod[1]/(pi_cod[0]*pi_cod[j]))*Q[i*NN +j]*thirdlayer/Padt;
        }
    }
}


texts:
I have a small WPF application which I'm not exactly localizing, but not hard-coding resources either. I know WPF doesn't use .resx files for that purpose, but I exposed the resource strings as public ViewModel properties which the view's controls bind to:

using resx = MyApp.Properties.Resources;
...

public string InterferingProcessesText { get { return resx.InterferingProcessesText; } }
public string SettingsText { get { return resx.SettingsText; } }
public string ExecuteInstallerCommandText { get { return resx.ExecuteInstallerCommandText; } }
public string SaveSettingsCommandText { get { return resx.SaveSettingsCommandText; } }
public string RefreshProcessesCommandText { get { return resx.RefreshProcessesCommandText; } }
public string KillInterferingProcessesCommandText { get { return resx.KillInterferingProcessesCommandText; } }

And then if I ever decide to translate the strings I can copy my .resx file and rename it with a culture suffix just like I would have done in WinForms or in any other Web app.

I know I'm supposed to put x:Uid all over my XAML and localize my app the way WPF has it, but just how bad is that, and why?

Yes, it clutters up my ViewModels with public string properties (#region to the rescue!). But does it violate some MVVM principle that will come and bite me in the *** later?


texts: Scraping names and images of products from a webpage

texts:
I've written some code in python to scrape item names, category and the variety of images connected to each item from four different links out of a webpage. The main problem with which i had to hurdle is that each item may have one image or around five different images. Parsing those image links are no big deal but problem appears when it comes to save them in a local folder. Coder like me find it difficult cause few links contain single image and the rest contain several. It was hard for me to twitch the scraper in such a way so that all the images can be parsed and saved properly. I used four different links: two of which contain one image for each item and the rest contain five images for each item . However, my parser is running smoothly now. Here is what I did:

import requests
from lxml import html
import os

urls = [

    "http://www.floralart.com.au/products/39-melbourne-online-floristflorist-melbourne-flowers-delivery-funeral-flowers-free-online.aspx",
    "http://www.floralart.com.au/products/316-amore-mio-vase-arrangement.aspx",
    "http://www.floralart.com.au/products/90-wedding-florist-wedding-flowers-wedding-bouquet-bridal-flowers-flowers-for-weddings-artificial.aspx",
    "http://www.floralart.com.au/products/182-flowers-on-line-flower-bouquets-flower-deliveries-flowers-melbourne-cheap-flower-deliveries-mel.aspx",
]

def opening_link(link):

    response = requests.get(link)
    tree = html.fromstring(response.text)
    cat = tree.cssselect(".breadcrumb a")[1].text.strip()      #category name of the item

    for item in tree.cssselect(".product-details-page"):
        name = item.cssselect("h1.productname")[0].text.strip() if item.cssselect("h1.productname") else ""
        image_link = [img.attrib['src'] for img in item.cssselect(".picture a img")]             #for single image
        image_links = [img_link.attrib['src'] for img_link in item.cssselect(".overview a img") if '.jpeg' in img_link.attrib['src']]      #for list of images
        if image_links:
            saving_images(cat,name,image_links)
        else:
            saving_images(cat,name,image_link)

def saving_images(cat, item_name, item_links):

    for link in item_links:
        response = requests.get(link, stream = True)
        image_name = link.split('/')[-1]

        if response.status_code == 200:
            os.chdir(r"C:\Users\ar\Desktop\mth")
            with open(image_name, 'wb') as f:
                for chunk in response.iter_content(1024):
                    f.write(chunk)

    print(item_name, cat)

if __name__ == '__main__':
    for url in urls:
        opening_link(url)

Btw, if there are more than one image in a link then it is not necessary to make use of single image cause the list containing several images also contain the main image.