texts: Idiomatic way to implement `tail -f` in clojure

texts:
Disclaimer: This is just an educational task to learn how to program in clojure and switch brain to immutable state-way of developing (the provided snipped has some unused variables which I didn't clean up since they will be used soon and are easy to understand).

The current milestone: to implement a solution that reads all lines from a file, if reaching file end - sleep and reopen a file, then continue trying reading the file from the same place.

This code is ugly without doubts. What makes me worrying is that it uses recursion in an ugly manner to maintain state. I think my next iteration will be to try using atoms to maintain mutable state instead of recursions, but not sure yet if it will be any better.

The main function currently for testing purposes just reads 3 lines from the channel.

(ns log-multiline-join.tailer
  (:use [clojure.core.async :only (>!! >! <!! thread chan timeout alt!)])
  (:import [java.io RandomAccessFile])
  (:gen-class))

(defn create-rac [filename]
  (RandomAccessFile. filename "r"))

(defn read-lines [rac position out stop]
  (.seek rac position)
  (if-let [line (.readLine rac)]
    (do
      (>!! out line)
      (recur rac (.getFilePointer rac) out stop))
    (.getFilePointer rac)))

(defn read-file-recur [filename position out]
  (let [rac (create-rac filename)
        position (read-lines rac position out 2)]

    (println "sleep")
    (Thread/sleep 1000)
    (recur filename position out)))

(defn tailer [filename out]
  (read-file-recur filename 0 out))

(defn -main []
  (let [out (chan)]

    (thread (tailer "/tmp/file" out))

    (println (<!! out))
    (println (<!! out))
    (println (<!! out))

    ))

UPD: this is the latest revision for the same code, it looks a bit better I suppose: https://www.refheap.com/93412


texts: Improvements with caesar cipher encryption

texts:
I have wanna learn more of ways to improve my code and also, make it look different. I want to see different approach but have the same result.

def text():
    print('What message(s) are you trying to encrypt?')
    return input()

def shift():
    key = 0;
    while True:
        print('Enter the key number (1-%s)' % (keymax))
        key = int(input())
        if (key >= 1 and key <= keymax):
            return key

def encrypt(string, shift):
    hidden = ''
    for char in string:
        if char.isalpha() == False:
            hidden = hidden + char
        elif  char.isupper():
            hidden = hidden + chr((ord(char) + shift - 65) % 26 + 65)
        else:
            hidden = hidden + chr((ord(char) + shift - 97) % 26 + 97)

    return hidden

text = text()
s = shift()

print("original string: ", text)
print("after encryption: ", encrypt(text, s))

It would be gladly appreciated if anyone could lend a hand or help out! :)


texts: Mongoose query using conditional formatting and regex

texts:
I this the function createQuery is fully functionally, but I would like a review on it. I'm pretty sure this can be shorten and most important (improve performance). Any ideas?

const express = require("express");
const router = express.Router();
const CompanyPart = require("../models/parts");

router.post("/search", (req, res) => {
  function createQuery(bodyFieldName, mongodbFieldName) {
    if (bodyFieldName !== undefined && bodyFieldName !== "") {
      const trimmedString = bodyFieldName.trim();
      if (
        trimmedString.charAt(0) !== "*" &&
        trimmedString.charAt(trimmedString.length - 1) !== "*"
      ) {
        // screw
        return (query[mongodbFieldName] = new RegExp(
          "^" + trimmedString + "$",
          "i"
        ));
      } else if (
        trimmedString.charAt(0) === "*" &&
        trimmedString.charAt(trimmedString.length - 1) === "*"
      ) {
        // *screw*
        return (query[mongodbFieldName] = new RegExp(
          trimmedString.replace(/[*]/g, ""),
          "i"
        ));
      } else if (
        trimmedString.charAt(0) !== "*" &&
        trimmedString.charAt(trimmedString.length - 1) === "*"
      ) {
        // screw*
        return (query[mongodbFieldName] = new RegExp(
          "^" + trimmedString.replace(/[*]/g, ""),
          "i"
        ));
      } else if (
        trimmedString.charAt(0) === "*" &&
        trimmedString.charAt(trimmedString.length - 1) !== "*"
      ) {
        // *screw
        return (query[mongodbFieldName] = new RegExp(
          trimmedString.replace(/[*]/g, "") + "$",
          "i"
        ));
      }
    }
  }

  console.log("req.body", req.body);
  let query = {};

  createQuery(req.body.partNumber, "itemNumber");
  createQuery(req.body.partName, "partName");
  createQuery(req.body.customsTariff, "customsTariff");
  console.log("query", query);

  CompanyPart.find(query)
    .sort({
      itemNumber: 1
    })
    .exec((err, parts) => {
      if (err) {
        res.status(500).json(err);
        return;
      }
      res.status(200).json({ parts });
    });
});

module.exports = router;


texts:
I have around 150 lines of code that I managed to optimize.

But, because my two methods and the six if-statements almost are identical, could there be room for improvement?  Maybe it could be done with only one button and one listbox?

As I'm out of ideas and could learn more myself, I'd like to know what could be done to improve this code.

public Form1()
    {
      InitializeComponent();
      timer1.Interval = 100;
      timer1.Start();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
      lblClock.Text = DateTime.Now.ToString("HH:mm:ss");
    }
        // ADD values BUTTON
    private void button8_Click(object sender, EventArgs e)
    {
        AddValues();
    }

        // REMOVE values BUTTON
    private void button7_Click(object sender, EventArgs e)
    {
        RemoveValues();
    }

    private void AddValues()
    {
            // ADD hours
        if (!box_Hour.Items.Contains(DateTime.Now.Hour))
        {
            box_Hour.Items.Add(DateTime.Now.Hour);
        }
            // ADD minutes
        if (!box_Minute.Items.Contains(DateTime.Now.Minute))
        {
            box_Minute.Items.Add(DateTime.Now.Minute);
        }
            // ADD seconds
        if (!box_Second.Items.Contains(DateTime.Now.Second))
        {
            box_Second.Items.Add(DateTime.Now.Second);
        }

    }

    private void RemoveValues()
    {
            // REMOVE hours
        if (box_Hour.Items.Contains(DateTime.Now.Hour))
        {
            box_Hour.Items.Remove(DateTime.Now.Hour);
        }
            // REMOVE minutes
        if (box_Minute.Items.Contains(DateTime.Now.Minute))
        {
            box_Minute.Items.Remove(DateTime.Now.Minute);
        }
            // REMOVE seconds
        if (box_Second.Items.Contains(DateTime.Now.Second))
        {
            box_Second.Items.Remove(DateTime.Now.Second);
        }
    }


texts:
I coded this, which is working but I think there is a better way to do this.. I have a form where the user can check from checkboxes. For each checkbox I have multiple info that I want to send to my servlet, so I thought to create manually a JSON...

<input name="warehouse"
       value="{ 'version':'<%=b.getVersion()%>',
                'product':'<%=b.getProduct()%>',
                'productionDate':'<%=b.getProductionDate()%>',
                'order':'<%=b.getOrder()%>'
               }"
       type="checkbox">

Then in my servlet, I read the checkboxes...

 String[] product = request.getParameterValues("warehouse");

I replace the " with '

product.replace("'","\"");

and then I convert every String in JSON by:

ObjectMapper mapper = new ObjectMapper();
Box box = mapper.readValue(product, Box.class);

Is there a better way than the above to send the all these info to my servlet?


texts: Single price grid component (HTML & CSS Project)

texts:
I would appreciate some feedback on this single price grid component project completed using HTML and CSS.
I am trying to recreate the content shown by this image: https://res.cloudinary.com/practicaldev/image/fetch/s--FzGw2rbZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/3y0bhisv135j7979dk3m.jpg
HTML file

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>Price Grid</title>

Join our community

30-day, hassle-free money back guarantee

Gain access to our full library of tutorials along with expert code reviews.

Perfect for any developers who are serious about honing their skills.

Monthly Subscription

$29 per month

Full access for less than $1 a day

            <button>Sign up</button>

Why us?

Tutorials by industry experts

Peer & expert code review

Coding exercises

Access to our GitHub repos

Community forum

Flashcard decks

New videos every week

CSS File
html {
    margin: 0;
    padding: 0;
    font-family: 'Abel', sans-serif;
}

body {
    background-color: rgb(230, 230, 230);
}

.container {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 800px;
    height: 500px;
    border: 20px solid rgb(20, 148, 20);
    border-radius: 25px;
}

.description {
    padding: 20px;
    text-align: left;
    background-color: rgb(255, 255, 255);
}

.pricing {
    position: relative;
    float: left;
    top: 5.5%;
    height: 55%;
    width: 50%;
    color: white;
    background-color: rgb(43, 179, 177);
    text-align: center;
}

.featuredContent {
    position: relative;
    float: right;
    top: 5.45%;
    color: rgb(255, 255, 255);
    background-color: rgb(74, 190, 189);
    height: 55%;
    width: 50%;
}

.featuredContent h2 {
    text-align: center;
}

.featuredContent ul {
    position: relative;
    list-style: none;
    left: 20%;
}


texts:
I've written a model for an app that generates math facts kids have to solve by evaluating the operation and the difficulty you pass to it at initialization.

I don't like how I am repeating the code that performs the operations. For instance, performAddition() and performMultiplication() both perform the same thing. How can I make this model better?

import UIKit

class QuestionGenerator: NSObject {

    enum BinaryOperation {
        case Addition
        case Subtraction
        case Multiplication
        case Division
    }

    enum Difficulty {
        case Easy
        case Intermediate
        case Difficult
    }

    struct Settings {
        var binaryOperation: BinaryOperation
        var difficulty: Difficulty
    }

    private var brain: Settings
    var number1: Int = 0
    var number2: Int = 0
    var answer: Int = 0

    init(operation: BinaryOperation, difficulty: Difficulty) {
        brain = Settings(binaryOperation: operation, difficulty: difficulty)
        super.init()
    }

    func newQuestion() {
        switch brain.binaryOperation {
        case .Addition:
            performAddition()
            break
        case .Multiplication:
            performMultiplication()
            break
        default: break
            // operation not implemented yet
        }
    }

    private func performAddition() {
        switch brain.difficulty {
        case .Easy:
            number1 = Int.random(1...10)
            number2 = Int.random(1...10)
        case .Intermediate:
            number1 = Int.random(10...100)
            number2 = Int.random(10...100)
        case .Difficult:
            number1 = Int.random(109...999)
            number2 = Int.random(109...999)
        }
        answer = number1 + number2
    }

    private func performMultiplication() {
        switch brain.difficulty {
        case .Easy:
            number1 = Int.random(1...10)
            number2 = Int.random(2...4)
        case .Intermediate:
            number1 = Int.random(1...50)
            number2 = Int.random(3...7)
        case .Difficult:
            number1 = Int.random(10...100)
            number2 = Int.random(4...15)
        }
        answer = number1 * number2
    }
}


texts:
I am working on a fairly complex (at least it feels complex to me at the moment) search program and am looking to possibly increase the performance. Everything works exactly how I want it to, but I'm just wondering if there are any slight performance increases I could benefit from. In this code, even minor performance increases are essential.  This is due to the extensive amount of operations being performed.

// Split search into multiple terms and check the {x} longest terms against the cache.
string[] word = searchTerm.Split(' ');
Array.Sort(word, (x, y) => y.Length.CompareTo(x.Length));
for (int i = 0; i < word.Length; i++)
{
    string searchValue = word[i];
    if (i <= MAX_WORD_ITERATIONS && (xmlsearchResults == BLANK_SEARCH_XML_SCHEMA || xmlsearchResults == string.Empty))
    {
        xmlsearchResults = GetCachedRecord(thisSearch, searchValue);
    }
    if (xmlsearchResults != BLANK_SEARCH_XML_SCHEMA && xmlsearchResults != string.Empty)
    {
        thisSearch.Value = searchValue;
        ignoreCache = true;
        break;
    }
}

xmlString.Append(string.Format(@"<{0}>", xmlHeader));
int objcount = 0;
string prevResultName = string.Empty;
try
{
    if (searchResults.hitCount > 0)
    {
        List<SearchItem> SearchResults = new List<SearchItem>();
        foreach (Node ResultNode in Results.Nodes)
        {
            string code = ResultNode.code.ToString();
            string result = ResultNode.id.ToString();
            string name = ResultNode.name_l.ToString();
            string image = string.Empty;

            if (!code.ToLower().Contains("ccb") && code.Length <= MAX_CODE_LENGTH &&
                name != prevResultName && objcount < maxResults)
            {
                Boolean addResult = true;
                if (thisSearch.FilterDescription)
                {
                    if (!name.ToLower().Contains(thisSearch.Value.ToLower()))
                    {
                        addResult = false;
                    }
                }
                if (addResult)
                {
                    SearchItem oSearch = new SearchItem(name, code);
                    SearchResults.Add(oSearch);
                    prevResultName = name;
                }
            }
        }
        var SortedSearchResults = SearchResults.OrderByDescending(s => s.Downloads).ToList();
        for (int i = 0; i < SortedSearchResults.Count(); i++)
        {
            if ((objcount < maxResults))
            {
                string te = string.Format("<ResultName>{0}</ResultName>", SortedSearchResults[i].Description);
                if (!xmlString.ToString().Contains(te))
                {
                    xmlString.Append(SortedSearchResults[i].GetXMLString());
                    objcount += 1;
                }
            }
        }
    }
}
xmlString.Append(string.Format(@"</{0}>", xmlHeader));
return objcount;


texts:
this post is sort of a continuation of my answer on the following question: Fast Algorithm to Factorize All Numbers Up to a Given Number. As this post explains - We need to factorize all the numbers up to a large N.
At first I gave a python solution which was pretty slow (since - you know, python), than I decided to write it in C++. I am not that good with C++ and I would like to have a code review about that answer:
#include <math.h>
#include <unistd.h>
#include <list>
#include <vector>
#include <ctime>
#include <thread>
#include <iostream>
#include <atomic>

#ifndef MAX
#define MAX 200000000
#define TIME 10
#endif

std::atomic<bool> exit_thread_flag{false};

void timer(int *i_ptr) {
    for (int i = 1; !exit_thread_flag; i++) {
        sleep(TIME);
        if (exit_thread_flag) {
            break;
        }
        std::cout << "i = " << *i_ptr << std::endl;
        std::cout << "Time elapsed since start: "
                  << i * TIME
                  << " Seconds" << std::endl;
    }
}

int main(int argc, char const *argv[])
{
    int i, upper_bound, j;
    std::time_t start_time;
    std::thread timer_thread;
    std::vector< std::list< int > > factors;

    std::cout << "Initiallizating" << std::endl;
    start_time = std::time(nullptr);
    timer_thread = std::thread(timer, &i);
    factors.resize(MAX);
    std::cout << "Initiallization took "
              << std::time(nullptr) - start_time
              << " Seconds" << std::endl;

    std::cout << "Starting calculation" << std::endl;
    start_time = std::time(nullptr);
    upper_bound = sqrt(MAX) + 1;
    for (i = 2; i < upper_bound; ++i)
    {
        if (factors[i].empty())
        {
            for (j = i * 2; j < MAX; j += i)
            {
                factors[j].push_back(i);
            }
        }
    }
    std::cout << "Calculation took "
              << std::time(nullptr) - start_time
              << " Seconds" << std::endl;

    // Closing timer thread
    exit_thread_flag = true;

    std::cout << "Validating results" << std::endl;
    for (i = 2; i < 20; ++i)
    {
        std::cout << i << ": ";
        if (factors[i].empty()) {
            std::cout << "Is prime";
        } else {
            for (int v : factors[i]) {
                std::cout << v << ", ";
            }
        }
        std::cout << std::endl;
    }

    timer_thread.join();
    return 0;
}

I would especially like a review about my usage of threads (I am afraid it might slow down the code). The performance are reaching 6619 which is the 855th (out of 1662 primes up to 14140 ~ square root of 200000000) in 1.386111 hours, if you find any way to make it faster I will be amazing! A more semantic review is also very welcome (Like #include order?).
Just for fun and a point of reference if you are trying to run the code yourself:

Where X is time and Y is the prime reached (i). The orange tradeline is y = 13 * 1.00124982852632 ^ x. The graph is exponential since indeed the inner loop time is getting shorter.
The orange tradeline says I will reach 14107 (The highest prime before the square root) at x ≈ 5595.842803197861 seconds which is 1.554 hours!


texts:
Is this efficient?

"""
merge sort algorithm in python
"""

def merge_sort(array):
    if len(array) == 1 or len(array) < 1:  # base case
        return array

    int_mid = len(array) / 2

    left = merge_sort(array[:int_mid])
    right = merge_sort(array[int_mid:])

    return merge_arrays(left, right)

def merge_arrays(left, right):
    left_index = 0
    right_index = 0
    new_array = []
    size = (len(left) + len(right))

    for i in range(size):
        if left[left_index] <= right[right_index]:
            new_array.append(left[left_index])
            left_index += 1
        else:
            new_array.append(right[right_index])
            right_index += 1

        if right_index >= len(right):
            for i in range(left_index, len(left)):
                new_array.append(left[i])
            break
        elif left_index >= len(left):
            for i in range(right_index, len(right)):
                new_array.append(right[i])
            break
    return new_array

if __name__ == '__main__':
    print merge_sort([8, 5, 3, 4, 6])
    print merge_sort([10, 9, 8, 7, 6, 5, 4])
    print merge_sort([1, 2, 3, 4, 5])
    print merge_sort(['b', 'c', 'a'])
    print merge_sort([54, 26, 93, 17, 77, 31, 44, 55, 20])
    print merge_sort([])


texts:
I wrote a script for reading a CSV, parsing it and saving data to MongoDB. I would love some input on how I'm handling errors and dealing with callbacks. I wrote it with nested without using async and the nesting wasn't too bad, but I tried this way thinking it might be better practice. It's a one-off script.

var fs = require('fs');
var parse = require('csv').parse;
var db = require('../models');
var async = require('async');

// take file path argument from command line (absolute or relative path)
// or default to the file path I used
var airportCSVPath = process.argv[2] || '../public/files/airports.csv';

// Read in airport data from csv file and write it to database.
async.waterfall([
    async.apply(readCSV, airportCSVPath),
    parseCSV,
    saveAirports
], function(err){
    if(err){
        console.log(err);
        return;
    }
    console.log('airports saved to db');
    process.exit(0);
});

// read in airports csv
function readCSV(filePath, cb){
    fs.readFile(filePath, function (err, data) {
        if (err) {
            return cb(err);
        }
        return cb(null, data);
    });
}

// parse airports csv
function parseCSV(data, cb){
    parse(data, function (err, parsedData) {
        if (err) {
            return cb(err);
        }
        return cb(null, parsedData);
    });
}

// Create objects for airports in the US with scheduled service and save them to the DB.
// Includes heliports, seaplane bases, balloonports, and airports of all sizes.
function saveAirports(data, cb){
    var count = 0;
    var q = async.queue(function (data, callback) {
        var airport = new db.Airport(data);
        airport.save(function (err) {
            if (err) {
                return callback(err);
            }
            return callback(null, data);
        })
    }, 5);

    for (var i = 1; i < data.length; i++) {
        var country = data[i][8];
        var scheduledService = data[i][11];
        var status = data[i][2];
        if(country === 'US' && scheduledService === 'yes' && status !== 'closed'){
            var airportObj = createAirportObj(data[i]);

            q.push(airportObj, function (err) {
                if (err) {
                    fs.appendFile('../logs/create-db-errors.txt', err.toString(), function (writeErr) {
                        if (writeErr) {
                            console.log('error writing to error log', writeErr);
                        }
                    });
                }
                count++;
            });
        }
    }

    // quick way to check successfully saved records from command line against
    // expected value
    q.drain = function(){
        console.log(count);
        cb(null);
    }
}

// I like this here to cut down on the function size of saveAirports
function createAirportObj(row) {
    var airportObj = {
                        id: Number(row[0]) || 0,
                        ident: row[1] || null,
                        type: row[2] || null,
                        name: row[3] || null,
                        latitude: Number(row[4]) || 0, // latitude in degrees
                        longitude: Number(row[5]) || 0, // longitude in degrees
                        eleveation: Number(row[6]) || 0, // elevation in feet
                        continent: row[7] || null,
                        iso_country: row[8] || null,
                        iso_region: row[9] || null,
                        city: row[10] || null, // because why not? space is cheap
                        scheduled: row[11] || null,
                        gps_code: row[12] || null,
                        iata: row[13] || null,
                        local_code: row[14] || null,
                        home_link: row[15] || null,
                        wikipedia_link: row[16] || null,
                        keywords: row[17] || null
                    };

    return airportObj;
}


texts:
$elements is an array, which may contain 'x' or 'y' keys, I want to check if they exist, otherwise assign a 0. I'm looking for a clean way to validate it. I'm new to PHP, so I want to make sure my code is created according to PHP best practices.

Input array:

Array
(
    [0] => Array
        (
        )

    [1] => Array
        (
            [x] => 123
        )

    [2] => Array
        (
            [x] => 123
            [y] => 456
        )

    [3] => Array
        (
            [y] => 456
        )

)

Code:

foreach ($elements as $element) {
    $element_x = $element_y = 0;
    if (isset($element['x']))
        $element_x = $element['x'];
    if (isset($element['y']))
        $element_y = $element['y'];
    $results[] = sprintf('(%d,%d)', $element_x, $element_y);
}

Is there a cleaner way to do it?


texts: TLE in APS - Amazing Prime Sequence in Python at Spoj

texts:
This series is similar to Fibonacci Series defined as : a[0] = a[1] = 0  and For n > 1, a[n] = a[n - 1] + f(n), where f(n) is smallest prime factor of n.
for N in (1 < N < 10^7). Spoj Link for this problem .

I have solved this problem in c & Python. But due to long range, I am getting Time Limit Exceeded in Python. For small range this is working fine. Is there any alternative way do this in Python or can this be more optimized.

lst = []
lst.append(0)
lst.append(0)
i = 2
while i <10000000 :
    t = 2
    while t <= i :
        if i % t == 0 :
            break
        t +=1
    lst.append(lst[i-1]+t)
    i +=1
for _ in range(int(input())):
    print(lst[int(input())])


texts:
Looking for the best way to speed up or maybe move from FFMpegConverter to another application for converting video to GIF, because it takes much time, will be much appreciate for code review and suggestions to improve converting performance.

   public static byte[] ConvertToGif(string url, string watermarkImagePath, string documentsPath)
        {
            try
            {
                const double height = 340;
                const double width = 600;
                double minimizedHeight, minimizedWidth;

                var converter = new FFMpegConverter();
                var ffProbe = new FFProbe();

                var videoInfo = ffProbe.GetMediaInfo(url);
                var videoStream = videoInfo.Streams.First(x => (x.Width != -1 && x.Height != -1));

                var ratio = (double)videoStream.Height / (double)videoStream.Width;
                if (videoStream.Tags.Any(x => x.Key == "rotate"))
                {
                    ratio = (double)videoStream.Width / (double)videoStream.Height;
                    if (videoStream.Height > videoStream.Width)
                    {
                        minimizedWidth = width;
                        minimizedHeight = minimizedWidth * ratio;
                    }
                    else
                    {
                        minimizedHeight = height;
                        minimizedWidth = minimizedHeight / ratio;
                    }
                }
                else
                {
                    if (videoStream.Height > videoStream.Width)
                    {
                        minimizedHeight = height;
                        minimizedWidth = minimizedHeight / ratio;
                    }
                    else
                    {
                        minimizedWidth = width;
                        minimizedHeight = minimizedWidth * ratio;
                    }
                }
                var identity = Guid.NewGuid().ToString();
                converter.Invoke($"-i {url}" +//input file
                    $" -i {watermarkImagePath}" +//input image
                    " -filter_complex \"overlay = (main_w - overlay_w) / 2:(main_h - overlay_h) / 2\" " +//image place params
                    $"-s {(int)minimizedWidth}x{(int)minimizedHeight} -t 6 -r 8" +//size, time and framerate
                    $" {documentsPath}\\output_{identity}.gif");//output file

                var returnedBytes = File.ReadAllBytes($"{documentsPath}\\output_{identity}.gif");
                File.Delete($"{documentsPath}\\output_{identity}.gif");
                return returnedBytes;
            }
            catch (Exception ex)
            {
                Log.Error($"Video url: {url} " + ex.ToString());
                throw;
            }
        }


texts: Inserting a Java object into a MySQL database

texts:
I'm writing a method to insert objects into a MySQL database and while everything runs fine I feel my code is bulky and inefficient.  What steps would you take to make this code more pleasant to look at and more efficient?

public void addAuthorization(Authorization authorization) {
    try {
        // Builds the query, lastHeader is used to prevent a trailing comma
        query = "INSERT into authorizations (";
        for(int i = 0; i < authorizationsHeaders.size() - 1; i++) {
            query += authorizationsHeaders.get(i) + ", ";
            questionMarks += "?, ";
        }
        String lastHeader = authorizationsHeaders.get(authorizationsHeaders.size() - 1);
        query += lastHeader + ") values(" + questionMarks + "?)";

        openConnection();
        ps = con.prepareStatement(query);
        ps.setString(1,  authorization.getCompany());
        ps.setString(2,  authorization.getPromoType());
        ps.setString(3,  authorization.getPromoDescription());
        ps.setString(4,  authorization.getStartDate());
        ps.setString(5,  authorization.getEndDate());
        ps.setString(6,  authorization.getVlMarketingNum());
        ps.setString(7,  authorization.getMarketingNum());
        ps.setString(8,  authorization.getStatus());
        ps.setDouble(9,  authorization.getForecast());
        ps.setDouble(10, authorization.getActual());

        ps.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        closeConnection();
    }
}


texts: Kotlin program to summarize git commits by regex match

texts:
I am trying to learn Kotlin. I am coming from some background in Java. As a learning exercise, I wrote this simple program to summarize occurrences of a string by author email in a list of git repositories.

I am curious if I am approaching things in an idiomatic Kotlin way. Extension functions are awesome but I suspect it's something that I should not overuse.

I plan to make this a command line application and maybe use recursion to get the git repositories from the source directory without explicitly providing them. Before I get too far though I would like to see how I can improve what I have.

Any feedback is appreciated!

import java.io.File
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
import java.util.concurrent.TimeUnit
import java.util.regex.Pattern
import kotlin.concurrent.thread

data class CommitSummary(
        var author: String,
        var regexString: String,
        var count: Int)

data class Commit(
        var commit: String = "",
        var author: String = "",
        var date: OffsetDateTime? = null,
        var message: String = "")

fun main(args: Array<String>) {

    val cmd = "git log --all --branches=* --remotes=*"
    val matchStr = "d'{0,1}oh" //case-insensitive
    val gitDir = "C:\\dev\\git\\"

    arrayListOf("repo-1", "repo-2")
            .forEach { repo ->
                thread {
                    val log = cmd.run(File(gitDir + repo), createTempFile())
                    val commits = log.parseGitLog()
                    val summaries = commits.summarizeGitMessages(matchStr)
                    summaries.forEach { author, summary ->
                        println(String.format("repo: %s, author: %s, %s count: %s", repo, author, summary.regexString, summary.count))
                    }
                }
            }
}

fun File.parseGitLog(): ArrayList<Commit> {
    return this.readLines().fold(arrayListOf()) { accumulated, current ->

        val startingWord = current.split("\\s".toRegex())[0]

        when (startingWord) {
            "commit" -> accumulated.add(Commit(current.split("\\s".toRegex())[1]))
            "Author:" -> accumulated.last().author = current.substring(current.indexOf("<") + 1, current.indexOf(">"))
            "Date:" -> accumulated.last().date = current.split("Date:")[1].trim().parseGitDateString()
            else -> accumulated.last().message += current.trim()
        }

        return@fold accumulated
    }
}

fun ArrayList<Commit>.summarizeGitMessages(regexString: String): MutableMap<String, CommitSummary> {
    val pattern = Pattern.compile(regexString, Pattern.MULTILINE or Pattern.CASE_INSENSITIVE)

    return this.fold(mutableMapOf()) { acc, commit ->
        val summary: CommitSummary = acc.getOrPut(commit.author) { CommitSummary(commit.author, regexString, 0) }
        val match = pattern.matcher(commit.message)
        while (match.find()) {
            summary.count = summary.count.plus(1)
        }
        return@fold acc
    }
}

// string extensions
fun String.run(workingDir: File, targetFile: File = File("C:\\dev\\tmpFile")): File {

    if (targetFile.exists()) {
        targetFile.delete()
    }

    ProcessBuilder(*split(" ").toTypedArray())
            .directory(workingDir)
            .redirectOutput(ProcessBuilder.Redirect.appendTo(targetFile))
            .redirectError(ProcessBuilder.Redirect.INHERIT)
            .start()
            .waitFor(60, TimeUnit.MINUTES)

    return targetFile
}

fun String.parseGitDateString(format: DateTimeFormatter = DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss yyyy Z")): OffsetDateTime {
    return OffsetDateTime.parse(this, format)
}


texts:
I wrote this C++ code for Tic-tac-toe for an interview (The basic skeleton was pre-provided) and got rejected because the code was too complex and inefficient. I'm not an expert programmer so I'd like some ideas about how to better my code to make it more efficient. The code is as follows:

#include <iostream>

const int N = 3; // Square NxN board, win with N consecutive

int board[N][N];

class TicTacToe {

 public:

int MakeMove(int player, int row_location, int col_location){

  if(player == 1){

    if(board[row_location][col_location]==0){

      board[row_location][col_location]=1;
    /*std::cout << "Player: "<< player << "\nCurrent board:\n";
    for(int i=0;i<N;i++){
    for(int j=0;j<N;j++){
    std::cout << board[i][j];
    }
  }*/
}
else{

  std::cout<<"Invalid entry\n";
}
  }
  else if(player == 2){

if(board[row_location][col_location]==0){
  board[row_location][col_location]=2;
/*std::cout << "Player: "<< player << "\nCurrent board:\n";
for(int i=0;i<N;i++){
    for(int j=0;j<N;j++){
        std::cout << board[i][j];
      }
  }*/
}
else{
  std::cout<<"Invalid entry\n";
}
  }

  int result = check_board(board);

  //std::cout << "\nResult of checkboard is: " << result << std::endl;

  return result;
}

private:

  int check_board(int board[N][N]){

bool flag = 0;
//std::cout << "\nInside checkboard function: \n";

if(flag==0)
{
for(int i=0;i<N;i++){      //Horizontal check
  for(int j=1;j<N-1;j++){
    if(board[i][j-1]==1 && board[i][j]==1 && board[i][j+1]==1){
      return 1;
      flag=1;
    break;
    }

    else if(board[i][j-1]==2 && board[i][j]==2 && board[i][j+1]==2){
      return 2;
      flag=1;
    break;
    }
  }
}
}

if(flag==0)
{

for(int j=0;j<N;j++){        //Vertical check
  for(int i=1;i<N-1;i++){

    if(board[i-1][j]==1 && board[i][j]==1 && board[i+1][j]==1){
      return 1;
      flag=1;
    break;
    }

    else if(board[i-1][j]==2 && board[i][j]==2 && board[i+1][j]==2){
      return 2;
      flag=1;
    break;
    }
  }
}
}

if(flag==0){

for(int i=1;i<N-1;i++){       //Leading diagonal check
  for(int j=i;j<N-1;j++){

    if(board[i-1][j-1]==1 && board[i][j]==1 && board[i+1][j+1]==1){
      return 1;
      flag=1;
    break;
    }

    else if(board[i-1][j-1]==2 && board[i][j]==2 && board[i+1][j+1]==2){
      return 2;
      flag=1;
      break;
    }
  }
}
}

if(flag==0){

 for(int i=N-1;i>1;i--){       //Opposite diagonal check

  for(int j=1;j<N-1;j++){

    //std::cout<<"In opposite diagonal loop\n "<<board[i+1][j-1]<<board[i][j]<<board[i-1][j+1];
    if(board[i+1][j-1]==1 && board[i][j]==1 && board[i-1][j+1]==1){

      return 1;
      flag=1;
    break;
    }

    else if(board[i+1][j-1]==2 && board[i][j]==2 && board[i-1][j+1]==2){

      return 2;
      flag=1;
      break;
    }
  }
}
}
return 0;
}
};

int main(int argc, char** argv) {

  int result;

  TicTacToe ttt;

  std::cout << "Starting test!" << std::endl;

  result = ttt.MakeMove(1,1,0);

  result = ttt.MakeMove(1,1,1);

  result = ttt.MakeMove(1,1,2);

  std::cout << "Winning Player is: " << result << std::endl;

 return 0;

}


texts: Select row based on another table row index

texts:
I have 2 tables. One holds only first column of my "data table" rest is stored in another table, that is placed right to first. What I need to do is to get all the data from specific row to pass it to jqplot.

My tables look like this. My code basically works, but I think it can be improved.

$('table#baseTable  > tbody > tr > td').click(function() {
    var rowIndex = $(this).parent().index();
    $('div#log').html(rowIndex);

    var myData = [];

    $('#dataTable tbody tr:eq(' + rowIndex + ')').map(function() {
            return $(this.cells).get();
        }).each(function() {
    var headerVal = $(this).closest("table").find("thead > tr > th").eq($(this).index()).html();
    myData.push([headerVal, $(this).html()]);
})

    alert(myData);
    console.log(myData);
});

I'm using this code in ASP page, so that every time I use UpdatePanel I must call my functions again.

This is my plot function:

function plot() {
    var $plot;
    var dataTableRows = $('#Grid3_br tbody tr');

    $('td.akcje').on('click', function() {
        var $newTitle = $(this).next().text();
        var myData = [],
            element = $(this),
            rowIndex = element.parent().index();

        $(dataTableRows[rowIndex]).map(function() {
            return $(this.cells).get();
        }).each(function(index, value) {
            myData.push(['M' + index, parseFloat($(this).html())]);
        })
        $('#wykres1').empty();//clears old plot. Don't know why re-plotting don't work for me
        $plot = $.jqplot('wykres1', [myData], {
            title: $newTitle,
            axes: {
                xaxis: {
                    renderer: $.jqplot.CategoryAxisRenderer,
                    tickOptions: {
                        formatString: '%s'
                    }
                },
                yaxis: {
                    tickOptions: {
                        formatString: '%.2f zł'
                    }
                }
            },
            highlighter: {
                show: true,
                sizeAdjust: 7.5,
                tooltipAxes: 'y'
            },
            cursor: {
                show: false
            }
        });

        $(window).resize(function() {
            $plot.replot({
                resetAxes: true
            });
        });
    });
}


texts:
Any feedback is welcome:

public class HexToDecimal {

    static String hexRep = "0123456789ABCDEF";

    public static void main(String[] args) {
        System.out.println(HexToDecimal.hexToDecimal("AB"));
    }

    public static int hexToDecimal(String hex) {

        int counter = hex.length()-1;
        int sum = 0;

        for (char c:hex.toCharArray()) {
            int i = hexRep.indexOf(c);
            sum = (int) (sum + (Math.pow(16,counter))*i);
            counter--;
        }

        return sum;
    }

}


texts: Parallax animation, running well on Chrome but slow on Safari

texts:
I have the following script to create a parallax effect on the page using request animation frame, it runs well on Chrome, but on Safari is lagging, I think because I run too many calculations on each rAF.

  $('.parallax').each(function () {
    var section = $(this),
        elements = section.find('[data-parallax-ratio]');

    elements.data('parallax-current', 0);

    function animation() {
      var scrollPos = $(window).scrollTop(),
          offsetY = section.offset().top - 60;

      for (var i = 0; i < elements.length; i++) {
        var el = $(elements[i]),
        ratio = el.data('parallax-ratio'),
        current = el.data('parallax-current');

        var newPos = (offsetY - scrollPos) * ratio;

        var pos = current - ((current - newPos) * 0.08);

        el.css('transform', 'translateY(' + pos + 'px)');

        el.data('parallax-current', pos);
      }

      window.requestAnimationFrame(animation);
    }

    animation();

  });


texts: Finding and pasting images into a specific cell

texts:
The below macro finds and pastes images into column A. While the macro works, it starts to slow down when running 500+ images. I am not too familiar with the VBA language, does anyone have any suggestions to make this code quicker and/or more elegant?

My existing Macro is as follows:

    Sub Picture() 'This Sub Looks for Image names posted in column B
            'in the file folder and then resizes the images and pastes them
            'in Column A

     'Opens File Dialog Box to select File Folder
     With Application.FileDialog(msoFileDialogFolderPicker)
    .InitialFileName = Application.DefaultFilePath & "\"
    .Title = "Select the folder containing the Image/PDF files."
    .Show
    If .SelectedItems.Count = 0 Then
        Exit Sub
    Else
        FldrName = .SelectedItems(1)
    End If
    End With

    Dim PicName As String

    Dim pasteAt As Integer
    Dim lThisRow As Long

    Application.ScreenUpdating = False

    lThisRow = 2

    Do While (Cells(lThisRow, 2) <> "Please Check Data Sheet")

    pasteAt = lThisRow
    Cells(pasteAt, 1).Select 'This is where picture will be inserted

    PicName = Cells(lThisRow, 2) 'This is the picture name

    present = Dir(FldrName & "\" & PicName & ".jpg")

    If present <> "" Then

        ActiveSheet.Pictures.Insert(FldrName & "\" & PicName & ".jpg").Select 'Path to where pictures are stored
        '''''''''''''''''''''''''''''''''''''''''''''''''''''''
        ' This resizes the picture
        '''''''''''''''''''''''''''''''''''''''''''''''''''''''
        With Selection
            .ShapeRange.LockAspectRatio = msoFalse
            .Height = ActiveCell.Height
            .Width = ActiveCell.Width
            .Top = ActiveCell.Top
            .Left = ActiveCell.Left
            .Placement = xlMoveAndSize
        End With

    Else
        Cells(pasteAt, 1) = "No Picture Found"
    End If

       lThisRow = lThisRow + 1
Loop

Range("A10").Select
Application.ScreenUpdating = True

Exit Sub

ErrNoPhoto:
MsgBox "Unable to Find Photo" 'Shows message box if picture not found
Exit Sub
Range("B20").Select

End Sub


texts:
This code is about manipulating each value in a 2D array. My method below is called based on how I want the values in the array to be manipulated (process).

For the first method in the switch statement - as an example, I am calling AllCaps() method to manipulate the value.

What I am trying to avoid is repeating statements when I can put it in a method instead and just call it when needed. With my code below, though, it seems like I am making the program work too hard by performing a check on each iteration - which could be in the thousands.

Is it effective to call a method for processing each 2D array value inside the nested for loop? Or call the method first and perform the nested for loop inside each method?

private void ProcessSelectedRange(string process)
{
    selectedRange = GetSelectedRange();

    // initialize and populate 2d array with values from selected range
    curValue = new object[,] { };
    curValue = selectedRange.Value;

    // possibly more statements

    // loop through curValue 2d array
    for (int i = 1; i <= curValue.GetLength(0); i++)
    {
        for (int j = 1; j <= curValue.GetLength(1); j++)
        {
            string str = string.Empty;

            // continue if curValue[i, j] is null or empty
            try
            {
                str = curValue[i, j].ToString();
                if (string.IsNullOrEmpty(str)) continue;
            }
            catch { continue; }

            //********************************************************************

            // call method depending on what we want to do with the value
            switch (process)
            {
                case "AllCaps": AllCaps(str); break;
                case "Process2": Process2(str); break;
                case "Process3": Process3(str); break;
                case "Process4": Process4(str); break;
                // possibly more methods
                default: Process5(str); break;
            }

            //********************************************************************
        }
    }
}


texts:
From SICP:

  Exercise 2.66.  Implement the lookup
  procedure for the case where the set
  of records is structured as a binary
  tree, ordered by the numerical values
  of the keys.

I wrote the following:

(define key car)
(define make-record cons)
(define value cadar)

(define (lookup given-key set-of-records)
  (cond ((null? set-of-records) false)
        ((equal? given-key (key (car set-of-records)))
         (car set-of-records))
        ((< given-key (key (car set-of-records))) (lookup given-key (left-branch set-of-records)))
        (else (lookup given-key (right-branch set-of-records)))))

(The following part is from the book)

(define (entry tree) (car tree))
(define (left-branch tree) (cadr tree))
(define (right-branch tree) (caddr tree))
(define (make-tree entry left right)
  (list entry left right))

(define (list->tree elements)
  (car (partial-tree elements (length elements))))

(define (partial-tree elts n)
  (if (= n 0)
      (cons '() elts)
      (let ((left-size (quotient (- n 1) 2)))
        (let ((left-result (partial-tree elts left-size)))
          (let ((left-tree (car left-result))
                (non-left-elts (cdr left-result))
                (right-size (- n (+ left-size 1))))
            (let ((this-entry (car non-left-elts))
                  (right-result (partial-tree (cdr non-left-elts)
                                              right-size)))
              (let ((right-tree (car right-result))
                    (remaining-elts (cdr right-result)))
                (cons (make-tree this-entry left-tree right-tree)
                      remaining-elts))))))))

How can my answer be improved?


texts: C++ reimplementation of Python's threading.Event

texts:
I've reimplemented in C++ the basic interface implemented by Python's threading.Event class using a mutex and condition variable. I've inlined functions rather than pasted both the header and source file. My reimplementation also skips the timeout argument to wait since I don't need it. The code appears to work through basic testing (test shown below reimplementation), but I'm particularly concerned about thread safety -- is using a mutex to protect isSet_ enough, or is there a way for a thread to get stuck waiting for an event that's already been set? Are there any other improvements I need to make?
Reimplementation:
#include <mutex>
#include <condition_variable>

class Event {
private:
    std::mutex isSetLock;
    bool isSet_ = false;
    std::mutex setTriggerLock;
    std::condition_variable setTrigger;
public:
    bool isSet () {
        isSetLock.lock ();
        bool isSetRet (isSet_);
        isSetLock.unlock ();
        return isSetRet;
    };
    void set () {
        isSetLock.lock ();
        isSet_ = true;
        isSetLock.unlock ();
        setTrigger.notify_all ();
    };
    void clear () {
        isSetLock.lock ();
        isSet_ = false;
        isSetLock.unlock ();
    };
    void wait () {
        if (!isSet ()) {
            std::unique_lock <std::mutex> setTriggerUniqueLock (setTriggerLock);
            setTrigger.wait (setTriggerUniqueLock);
        }
    };
};

Basic test:
#include "Event.hpp"
#include <thread>

class Test {
    Event event;
    void thread_ () {
        event.wait ();
    };
public:
    Test () {
        std::thread thread (&Test::thread_, this);
        event.set ();
        thread.join ();
    };
};
int main () {
    Test test;
    // Should exit immediately
};


texts: Simplify this function which finds the coordinates of the neighbors of an isometric cell

texts:
I would like to simplify and optimize this function which finds me the neighbors of a cell thanks to cartesian coordinates of a cell Id

const getNeighborsCellId = cellId => {
    const neighbors = []
    const {x, y} = getCoordinatesFromCellId(cellId)

    // LOL ->

    const isStaggered = y % 2
    if (isStaggered){

      neighbors.push(getCellIdFromCoordinates(x, y - 1))
      neighbors.push(getCellIdFromCoordinates(x, y - 2))
      neighbors.push(getCellIdFromCoordinates(x + 1, y - 1))
      neighbors.push(getCellIdFromCoordinates(x - 1, y))
      neighbors.push(getCellIdFromCoordinates(x + 1, y))
      neighbors.push(getCellIdFromCoordinates(x, y + 1))
      neighbors.push(getCellIdFromCoordinates(x, y + 2))
      neighbors.push(getCellIdFromCoordinates(x + 1, y + 1))

    }
    else {
      neighbors.push(getCellIdFromCoordinates(x - 1, y - 1))
      neighbors.push(getCellIdFromCoordinates(x, y - 2))
      neighbors.push(getCellIdFromCoordinates(x, y - 1))
      neighbors.push(getCellIdFromCoordinates(x - 1, y))
      neighbors.push(getCellIdFromCoordinates(x + 1, y))
      neighbors.push(getCellIdFromCoordinates(x - 1, y + 1))
      neighbors.push(getCellIdFromCoordinates(x, y + 2))
      neighbors.push(getCellIdFromCoordinates(x, y + 1))
    }

    return neighbors
}


texts:
This program asks the user for input three times, and based on that input, calculates the chmod. I have included comments with questions and clarifications in the code.

I would like to have these questions answered and help with making the if ... in ... part shorter, if that's possible.

'''
This program asks the user for input three times, and based on that input, calculates the chmod.
'''

'''
This is a simple function that prevents me from repeating myself.
Usage:
    whoCan('execute')
will return 'Who can execute?'
'''

def whoCan(doThis):
    '''
    If I use `print` instead of `return` here, this is the output:

     Who can read?
     None

    Why is that?
    '''
    return "Who can %s?" % doThis

'''
Ask the user for input in the form of 'ow', 'gr' and 'ot'.
FYI:
    ow = owner
    gr = group
    ot = other

chmod 777 would be  owgrot
                    owgrot
                    owgrot
'''

read = raw_input(whoCan('read'))
write = raw_input(whoCan('write'))
execute = raw_input(whoCan('execute'))

'''
I didn't have any success with
    readValue, writeValue, executeValue = int()
Why?
'''

readValue = 0
writeValue = 0
executeValue = 0

# There must be a shorter way to write this...

if 'ow' in read:
    readValue += 4
if 'gr' in read:
    readValue += 2
if 'ot' in read:
    readValue += 1

if 'ow' in write:
    writeValue += 4
if 'gr' in write:
    writeValue += 2
if 'ot' in write:
    writeValue += 1

if 'ow' in execute:
    executeValue += 4
if 'gr' in execute:
    executeValue += 2
if 'ot' in execute:
    executeValue += 1

# And print the chmod

print readValue, writeValue, executeValue


texts: Ensuring file handle is closed in case of an exception

texts:
fun readLines(path: String): Stream<String> =
    try {
        Files.lines(Paths.get(path)).use { it }
    } catch (ex: Exception) {
        ex.printStackTrace()
        Stream.empty<String>()
    }

I added .use { it } to tack on try-with-resources like behaviour for autoclosing the file handle (?) in case of exceptions.

Is this required?
Are there better approaches?


texts: Does this one-line text-based terrain generator go against standards?

texts:
This isn't really much of an actual project, just something I threw together in about 5-10 minutes. I just want to know if it goes with the current Python standards, and if anything should be changed or fixed.

print(''.join([__import__('random').choice(['\033[7;1;32m  \033[0m','\033[7;32m  \033[0m','\033[7;1;33m  \033[0m','\033[7;34m  \033[0m']) for world in range(40)])); __import__('time').sleep(0.5)

Can anything be improved? What needs to be fixed?


texts: Find smallest index that is identical to the value in an array

texts:
The task is taken from LeetCode

  Given an array A of distinct integers sorted in ascending order,
  return the smallest index i that satisfies A[i] == i.  Return -1 if no
  such i exists.

  Example 1:

Input: [-10,-5,0,3,7]
Output: 3
Explanation:
// For the given array, A[0] = -10, A[1] = -5, A[2] = 0, A[3] = 3, thus the output is 3.

  Example 2:

Input: [0,2,5,8,17]
Output: 0
Explanation:
// A[0] = 0, thus the output is 0.

  Example 3:

Input: [-10,-5,3,4,7,9]
Output: -1
Explanation:
// There is no such i that A[i] = i, thus the output is -1.

  Note:

  1 <= A.length < 10^4

  -10^9 <= A[i] <= 10^9

My solution

has time complexity of \$O(n)\$ and space complexity of \$O(1)\$. I start to look from the start to the last element. If I find a value that is greater than i, then I can exit early (because there won't be an element that is equal to i anymore). If I find A[i] === i, then I have a result.

Is there a faster solution than the one provided?

/**
 * @param {number[]} A
 * @return {number}
 */
var fixedPoint = function(A) {
    for (let i = 0; i < A.length; i++) {
        if (A[i] > i) { return -1; }
        if (A[i] === i) { return i; }
    }
    return -1;
};


texts: How to exactly work with the JSON Object and jQuery, adding info to posts

texts:
I have been working with AJAX and JSON for quite some years now, but to be honest I still do not know exactly what all the functionality are, and how to create optimized code for jQuery.

So my first question: Does anyone know a good tutorial, or better even a cheatsheet where are the functionalities are explained. I have Googled and looked at the normal jQuery documentation for years now, but I still can't manage to think in optimized paterns, if that makes any sense at all.

Now to illustrate this with a relevant problem. Currently I am developing a small public plugin that adds various counters to posts, nothing special here.

&nbsp;

&nbsp;

&nbsp;

&nbsp;

&nbsp;

&nbsp;

Now this has to be filled. The best way I could make this work is with the following json sting:

{ "posts" :
    { "60" :
        { "x" : "100", "y" : "200" , "z" : "300" }
    },
    { "64" :
        { "x" : "400", "y" : "500" , "z" : "560" }
    }
}

Now as for the ajax there is a double loop:

    // AJAX blah blah blah above
success : function( data ){
    posts = data.posts;
    jQuery.each( posts, function( post_id, post_counts ) {
        jQuery.each( post_counts, function( item_name, item_count ) {
            jQuery( '#container-' + post_id + ' .counter-' + item_name ).text( item_count );
        });
    });
}

Now this works fine, but I bet there is a better way for doing this. Maybe change the json string to a more optimized version for doing things quicker.

jQuery has so many special functions.

Anyone have any suggestions.


texts: Making a lot of similar looking views in Android layouts

texts:
I'm getting started with Android development. Take a look at this Android layout file:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/wallpaper">
    <Button
        android:id="@+id/gameStartButton"
        android:text="Start"
        android:fontFamily="serif"
        android:textSize="30sp"
        android:textColor="@color/white"
        android:background="@color/metal"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:layout_height="@dimen/mainMenuItemWidth"
        android:onClick="chooseGameMode"/>
    <Button
        android:id="@+id/settingsButton"
        android:text="Settings"
        android:fontFamily="serif"
        android:textSize="30sp"
        android:textColor="@color/white"
        android:background="@color/metal"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:layout_height="@dimen/mainMenuItemWidth"
        android:onClick="openSettings"/>
    <Button
        android:id="@+id/exitButton"
        android:text="Quit"
        android:fontFamily="serif"
        android:textSize="30sp"
        android:textColor="@color/white"
        android:background="@color/metal"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:layout_height="@dimen/mainMenuItemWidth"
        android:onClick="closeApp"/>
</LinearLayout>

All three buttons have exactly the same dimensions, margins and color. As a result, this layout file appears needlessly verbose. Is is possible to extract this common information somewhere else so that it could be reused?

One way could be to subclass Button with specific features and use it instead of the stock button. Is there any other way? What I'm trying to achieve is simple attribute sharing and it shouldn't require dropping down to Java.


texts: Given a monetary amount, calculate the equivalent change

texts:
I have written a program that takes in some amount of money, and prints the equivalent change (starting at hundred dollars, to fifty, to twenty, down the pennies). Here is the code:

System.out.print("Enter amount of money: ");
Scanner scan = new Scanner(System.in);

double value = scan.nextDouble();
int valueIntegral = (int) value;
int valueFractional = (int) Math.round(100 * value - 100 * valueIntegral);

// Integral values

int hundred = valueIntegral / 100;

int fifty = (valueIntegral % 100) / 50;

int twenty = ((valueIntegral % 100) % 50) / 20;

int ten = (((valueIntegral % 100) % 50) % 20) / 10;

int five = ((((valueIntegral % 100) % 50) % 20) % 10) / 5;

int one = (((((valueIntegral % 100) % 50) % 20) % 10) % 5) / 1;

// Fractional values

int quarter = valueFractional / 25;

int dime = (valueFractional % 25) / 10;

int nickel = ((valueFractional % 25) % 10) / 5;

int penny = (((valueFractional % 25) % 10) % 5) / 1;

System.out.println(hundred + " hundred dollar bills\n" +
                   fifty + " fifty dollar bills\n" +
                   twenty + " twenty dollar bills\n" +
                   ten + " ten dollar bills\n" +
                   five + " five dollar bills\n" +
                   one + " one dollar bills\n" +
                   quarter + " quarters\n" +
                   dime + " dimes\n" +
                   nickel + " nickels\n" +
                   penny + " pennies");

What I want to know is that without using loops or any iterative structures is this an acceptable way to accomplish this task? What would be a more elegant way? (those chains of modulo division are ugly)


texts:
I wrote some compare-functions that I pass to other methods in javascript:

function equal(a, b) {
    if (a instanceof Date) return a.getTime() == b.getTime();
    return a == b;
}

function lessThan(a, b) {
    if (a instanceof Date) return a.getTime() < b.getTime();
    return a < b;
}

function greaterThan(a, b) {
    if (a instanceof Date) return a.getTime() > b.getTime();
    return a > b;
}

function lessOrEqual(a, b) {
    return equal(a, b) || lessThan(a, b);
}

function greaterOrEqual(a, b) {
    return equal(a, b) || greaterThan(a, b);
}

Is there a way to get this a bit more compact? If I want to add another comparable type I always have to modify the first three functions.


texts:
Recently, I found a way to generate specific blame for SmokeDetector. That was cool, so I decided to make a C++ program for it. I also have it on GitHub. This program is called Blame Bot.

Blame Bot does not need any flags to compile, so you can use make blame to compile it.

How it works:

Blame Bot takes an input of a number. This input is your chat id. This number is taken from your chat link. Mine would be: https://chat.stackexchange.com/users/301688/grant-garrison, and my number would be 301688. Then, the number is converted to base 7. A switch statement then outputs the characters. (Note: the characters must be in double quotes.)

#include <iostream>

int main(){
    int digit;
    std::string stringDigit, answer, instring;
    std::cin>>instring;
    int in = std::stoi(instring,nullptr);
    while (in != 0){
        digit = in % 7;
        if (digit < 10){
            stringDigit = '0' + digit;
        }else{
            stringDigit = digit - 10 + 'A';
        }
            answer = stringDigit + answer;
            in /= 7;
    }
    std::cout<<"!!/blame\u180E ";
    int i = 0;
    while(answer.length()>=i){
        switch (answer[i]-'0'){
            case 0: std::cout<<"\u180E";
                break;
            case 1: std::cout<<"\u200B";
                break;
            case 2: std::cout<<"\u200C";
                break;
            case 3: std::cout<<"\u200D";
                break;
            case 4: std::cout<<"\u2060";
                break;
            case 5: std::cout<<"\u2063";
                break;
            case 6: std::cout<<"\uFEFF";
                break;
        }
        i++;
    }
    std::cout<<"a\n";
}

What I'm looking for:

I'm looking for efficiency and syntax improvements. I know the program is fast already, but any extra computation cut out is a bonus. I do want to leave the { and } on the if statements though, as I think it improves readability for me. I also do not want to use any libraries.

What I think can be improved:

I think that switching back and forth from std::string and int is inefficient, and I'm sure there is a better way that doesn't need that. I also think that the base conversion algorithm might have a better replacement.


texts:
I have this fiddle http://jsfiddle.net/L7zuT/ where I'm working on a small part of a big event program. The functionality is ok, the part of the problem would be the large JavaScript lines needed with the full event program. Is there any way to implement it with DRY (don't repeat yourself) or a better approach for a simpler way?

    13:00-14:30
    18.AAL Solution Deployment Seminar
      9. Results of the AALIANCE Network: Roadmap and more
      7. From    actimetry to ADL ,in the framework of remote medical monitoring of elderly    from living labs to the nursing home
      8. Interoperability APIs and LivingLabs for AAL
      10. Large scale deployment of AAL solutions based on Open    Platform: Challenge and perspectives
    &nbsp;

    14:30-16:00
      1.    User Forum and workshop for exergames in AAL
    &nbsp;

        16:00-17.30
        19.Deployment event - matchmaking session
        &nbsp;

<input id="date_main01" name="date_main01" type="radio" value="01" />
<input id="date_main02" name="date_main01" type="radio" value="02" />
<input id="date_sub03" name="date_sub01" type="radio" value="03" />
<input id="date_sub04" name="date_sub02" type="radio" value="04" />
<input id="date_main05" name="date_main01" type="radio" value="05" />
<input id="date_main06" name="date_main01" type="radio" value="06" />
<input id="date_last07" name="date_last01" type="radio" value="07" />

CSS

tr {
    height: 1px;
}
td{
    height: 100%;
}
label{
    display: block;
    min-height: 100%; /* for the latest browsers which support min-height */
    height: auto !important; /* for newer IE versions */
    height: 100%; /* the only height-related attribute that IE6 does not ignore  */
}
label:hover {
    cursor:pointer;
}

JS

$(document).ready(function(){
    $("input[name='date_main01']").click(function() {
        var test = $(this).val();
        $("input[name='date_sub01']").prop('checked', false);
        $("input[name='date_sub02']").prop('checked', false);
        $("label[for*='date_main']").css("background", "none");
        $("label[for*='date_sub']").css("background", "none");
        $("label[for='date_main"+test+"']").css("background-color", "yellow");
    });
    $("input[name='date_sub01']").click(function() {
        var test = $(this).val();
        $("input[name$='date_main01']").prop('checked', false);
        $("label[for*='date_main']").css("background", "none");
        $("label[for='date_sub"+test+"']").css("background-color", "yellow");
    });
    $("input[name='date_sub02']").click(function() {
        var test = $(this).val();
        $("input[name$='date_main01']").prop('checked', false);
        $("label[for*='date_main']").css("background", "none");
        $("label[for='date_sub"+test+"']").css("background-color", "yellow");
    });
        $("input[name='date_last01']").click(function() {
        var test = $(this).val();
        $("label[for='date_last"+test+"']").css("background-color", "yellow");
    });
});


texts:
I'm building a small application in Spring and Spring Data JPA.
I need serval layer. I don't know if I'm doing well.

Here is an example:
POJO

@Entity
public class Product {
    @Id
    @GeneratedValue
    private long Id;
    @NotBlank
    private String name;
    @NotNull
    private int price;

    public long getId() {
        return Id;
    }

    public String getName() {
        return name;
    }

    public int getPrice() {
        return price;
    }

    public void setId(long id) {
        Id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Product{" +
                "Id=" + Id +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}

REPOSITORY

public interface ProductRepository extends CrudRepository<Product, Long> {
    Product findByName(String name);
    List<Product> getAllProducts();
    Product getProductById(String productId);
    void addProduct(Product product);
}

SERVICE

public interface ProductService  {

    List<Product> getAllProducts();
    Product getProductById(String productId);
    void addProduct(Product product);
}

REPOSITORY IMPLEMENTATION

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductRepository productRepository;

    @Override
    public List<Product> getAllProducts() {
        return productRepository.getAllProducts();
    }

    @Override
    public Product getProductById(String productId) {
        return productRepository.getProductById(productId);
    }

    @Override
    public void addProduct(Product product) {
        productRepository.addProduct(product);

    }

}

It is a good?
Unless How create communication with database in Spring?


texts:
The following is an a self-tutored attempt to take a leap into understanding simple usage of wait() and notify() methods.

The code is responsible for scanning a directory structure with each directory being scanned by a new thread, for the files present in it. All results to get accumulated in a data collection and displayed at the end. The problem is to detect the end, since this is a chain reaction type.

class MyThreadA implements Runnable {

    private String path;
    private static List<String> FILE_LIST;
    private static AtomicInteger ATOMIC_COUNTER;

    static {
        ATOMIC_COUNTER = new AtomicInteger(0);
        FILE_LIST = new LinkedList<>();
    }

    public MyThreadA(String path) {
        this.path = path;
    }

    @Override
    public void run() {
        try {
            int begin = ATOMIC_COUNTER.getAndIncrement();
            File filePath = new File(path);
            File[] listOfFiles = filePath.listFiles();
            synchronized (System.out) {
                for (File temp : listOfFiles) {
                    if (temp.isFile()) {
                        FILE_LIST.add(temp.getAbsolutePath());
                    } else if (temp.isDirectory()) {
                        Thread t = new Thread(new MyThreadA(temp.getPath()));
                        t.start();
                    }
                }
            }
            MyThreadA.decrementCounter();
            //if(begin == 0)
                try {
                    synchronized (FILE_LIST) {
                        FILE_LIST.wait();
                    }
                    printList();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void decrementCounter() {
        if (ATOMIC_COUNTER.decrementAndGet() == 0)
            synchronized(FILE_LIST){
                FILE_LIST.notifyAll();
            }
    }

    private static void printList(){
        for(String temp:FILE_LIST){
            System.out.println(temp);
        }
    }
}

Now, as you can see, all such spawned threads will wait to be notified. I can minimize this by letting the 1st thread only to wait, but that introduces one more critical section. I am looking for if there can be a better solution to this using wait() and notify() constructs only, with minimal concurrency tools.

I understand that there are better tools for solving this, but this is solely for learning purpose.


texts:
Edit 13 June:
I have made a new and improved version here.
Original Question
This is a very rudimentary lolcats translator (it only works on the phrase "Can I have a cheeseburger") in Haskell. This is my first ever attempt at Haskell (or any functional programming language). I am sure that my code is absolutely atrocious (the documentation was dismal) but it works.
Teh Codez
import Data.Strings
main = do
    putStrLn "Enter your text to translate"
    inputText <- getLine
    let capsText = strToUpper inputText
    let a = strReplace "HAVE" "HAS" capsText
    let b = strReplace "CAN I" "I CAN" a
    let c = strReplace "CHEESEBURGER" "CHEEZBURGER" b
    let d = strReplace " A " " " c
    putStrLn (d)
    getLine


texts: What is the optimal way to retrieve a list of sorted dates in a list of sorted periods in python?

texts:
Suppose I have a list with N sorted dates and M non-overlapping sorted periods with start date, end date (inclusive), and a tax rate for example. I have to make an efficient algorithm retrieve all tax rates for all dates. If there is not period including this date it should raise an error.

Given the brute-force approach I could have a O(N * M) with two nested loops. It is possible to break the inner loop when one date is found (maintains the code worst-case complexity). Another optimization would be to store the index of last period, since the lists are sorted, then I believe I got O(N + M). Is there a more optimal way of doing that? Maybe using other data structures?

Working code in Python:

import collections
import datetime
import sys
from typing import List

RatePeriod = collections.namedtuple("RatePeriod", ["start_date", "end_date", "rate"])

periods = [
    RatePeriod(datetime.datetime(2019, 1, 3), datetime.datetime(2019, 4, 1), 10.7),
    RatePeriod(datetime.datetime(2019, 4, 2), datetime.datetime(2019, 12, 2), 20.5),
    RatePeriod(datetime.datetime(2019, 12, 3), datetime.datetime(2020, 1, 2), 37.8),
]

def get_rates(dates: List[datetime.datetime]) -> List[float]:
    rates = []
    last_period = 0
    for idx, date in enumerate(dates, 1):
        for idx2 in range(last_period, len(periods)):
            period = periods[idx2]
            last_period = idx2
            if period.start_date <= date <= period.end_date:
                rates.append(period.rate)
                break
        if len(rates) < idx:
            sys.exit("No period found for date: {}".format(date))
    return rates

series = [
    datetime.datetime(2019, 2, 20),
    datetime.datetime(2019, 3, 6),
    datetime.datetime(2019, 12, 14),
]

result = get_rates(series)
expected = [10.7, 10.7, 37.8]
assert result == expected


texts:
I have implemented two genetic operators, which is really just a fancy way of mangling lists. In particular OX-1 (illustration) and displacement mutation.

I found it necessary to extract out the randomness from the algorithms in order to do unit testing with some known examples. Is that a decent way to go about it? Any comments on performance, structure, clarify and so forth is appreciated.

import           Control.Monad.Random
import qualified Data.Vector.Generic  as V

-- | Displacement Mutation:
-- A continous part of random length is taken out from a random position
-- and reinserted at a random position
displaceMutation :: (MonadRandom m, V.Vector v a) => v a -> m (v a)
displaceMutation genome = do
  let len = V.length genome
  idxs@(l, r) <- randIndices len
  insert_pos <- getRandomR (0, len-(r-l))
  return $ displaceMutationStat idxs insert_pos genome

-- | Displacement mutation with chosen 'slice indexes' and 'insert position'
displaceMutationStat :: (V.Vector v a) => (Int, Int) -> Int -> v a -> v a
displaceMutationStat (left, right) insert_pos genome = mutated
    where
  n = right - left
  part = V.slice left n genome -- O(1)
  leftovers = V.take left genome V.++ V.drop right genome -- O(m+n)
  mutated = V.take insert_pos leftovers V.++ part V.++ V.drop insert_pos leftovers -- O(m+n)

-- | Ordered crossover (OX-1) between two individuals
orderedCrossover :: (Eq a, MonadRandom m, V.Vector v a) => v a -> v a -> m (v a, v a)
orderedCrossover parent_a parent_b = do
  idxs <- randIndices (V.length parent_a)
  return (orderedCrossoverStat idxs parent_a parent_b)

-- | Ordered crossover with chosen 'slice indexes'
orderedCrossoverStat :: (Eq a, V.Vector v a) => (Int, Int) -> v a -> v a -> (v a, v a)
orderedCrossoverStat (left, right) parent_a parent_b = (child_a, child_b)
    where
      n = right - left
      -- Initialize a child with a slice from its parent
      c_a_mid = V.slice left n parent_a
      c_b_mid = V.slice left n parent_b
      -- Find missing genes from the opposite parents, in the order as they
      -- appear starting from the right of the slice looping around to the left
      c_a_miss = V.filter (`V.notElem` c_a_mid) (V.drop right parent_b V.++ V.take right parent_b)
      c_b_miss = V.filter (`V.notElem` c_b_mid) (V.drop right parent_a V.++ V.take right parent_a)
      splitpos = (V.length parent_a) - right
      (ra, la) = V.splitAt splitpos c_a_miss
      (rb, lb) = V.splitAt splitpos c_b_miss
      child_a = la V.++ c_a_mid V.++ ra
      child_b = lb V.++ c_b_mid V.++ rb

-- | Get two distinct 'Ints' in the interval 0 through 'len', with the lowest
-- number appearing first in the tuple
randIndices :: (MonadRandom m) => Int -> m (Int, Int)
randIndices len = do
  i_left <- getRandomR (0, len-1)
  i_right <- getRandomR (i_left+1, len)
  return (i_left, i_right)


texts: Quoting strings passed to an output stream

texts:
This class allows me to quote strings being sent to an output stream:

class Quote{
public:
    friend std::ostream& operator<<(std::ostream& os, const Quote& obj){
        obj.write(os);
      return os;
    }
    Quote() = delete;
    Quote(const string & text): text(text){}

    void write(ostream & os) const{
        os << default_quote_token << text << default_quote_token;
    }
private:
    const string & text;
};

Like this:

os << Quote(name);

It feels like a lot of work to avoid:

os << "\"" << name << "\"";

Is there a better solution?


texts: Game where two players take turns picking numbers until a target sum

texts:
Working on the problem of sum game. Suppose we have consecutive numbers from 1 to n, and an expected sum number, there are two players, and each player tries to select one number in turn (once a number is selected by one player, the other player cannot select it again), and the selected numbers are summed together. The player who first get a sum which is >= expected sum wins the game. The question is trying to find if first player has a force win solution (means no matter what numbers 2nd player will choose each time, the first player will always win).

For example, if we have numbers from 1 (inclusive) to 5 (inclusive) and expected sum is 7, if the first player select 1, no matter what the 2nd player select, in the final the first player will always win.

Here is my code and my idea is, each player tries to see if select the largest number can win -- if not then selecting the smallest available (means not having been selected) number -- which gives the current player max chance to win in the following plays, and give the opponent player minimal chance to win in the following plays.

I think the above strategy is optimum for player 1 and player 2, if in this strategy, player 2 cannot win, it means player 1 could force win.

I want to review the code, and also if my thought of the algorithm (strategy) to resolve the problem is correct?

def try_best_win(numbers, flags, current_sum, expected_sum, is_first_player):
    if current_sum + numbers[-1] >= expected_sum:
        return is_first_player == True
    else:
        for i in range(len(flags)):
            # find the next smallest number
            if flags[i] == False:
                flags[i] = True
                return try_best_win(numbers, flags, current_sum+numbers[i], expected_sum, not is_first_player)

if __name__ == "__main__":
    print try_best_win([1,2,3,4,5], [False]*5, 0, 6, True) #False
    print try_best_win([1,2,3,4,5], [False]*5, 0, 7, True) #True


texts: Amanda's Relationship Tips app, with scroll performance issues

texts:
I am having some major issues with scrolling in my active app "Amanda's Relationship Tips"

Under the User Advice tab:

I'm using the Parse Database as a backend to pull user data.  This lag is presenting a huge problem with Overall User Experience and I want to solve it, but I'm coming up short.  I think (90% sure) that it's totally related with pulling the user images from parse.  Here is the following code that is in the app currently:

//-------------------------------------------------------------------------------------------------------
- (PFTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object: (PFObject *)object
//-------------------------------------------------------------------------------------------------------
{
    static NSString *myWallTableIdentifier = @"UserPostsCell";
    WallCell *cell = [tableView dequeueReusableCellWithIdentifier:myWallTableIdentifier];
    if (cell == nil)
    {
        cell = [[WallCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:myWallTableIdentifier];
    }

    //////////////////////////CONFIGURE THE CELL//////////////////////////

    PFUser * user = object[@"User"];
    [user fetchIfNeeded];

    ////USER NAME//////////////////////////////////////
    UILabel *cUser = (UILabel*) [cell viewWithTag:105];
    cUser.text = [object objectForKey:@"Post_Author"];

    if (cUser.text == nil) {
        cUser.text = [NSString stringWithFormat:@"Anonymous User"];
    }

    //User's Profile Picture//
    profilePictureAttributes *thumbnailImageView = (profilePictureAttributes*)[cell viewWithTag:106];
    [AFDownload start:user[PF_USER_PICTUREURL] complete:^(NSString *path, NSError *error, BOOL network)
     {
         if (error == nil)
         {
             thumbnailImageView.image = [[UIImage alloc] initWithContentsOfFile:path];
             NSLog(@"No Error with PictureURL");
         }
         else
         {
             thumbnailImageView.file = user[PF_USER_PICTURE];
             [thumbnailImageView loadInBackground];
             NSLog(@"Error with PictureURL trying to pull Parse File");
         }
     }];

    ////DATE LABEL (WHEN CREATED)/////////////////////////
    UILabel *dateLabel = (UILabel*) [cell viewWithTag:102];
    NSDate *parseDate = object.createdAt;
    NSString *timeAgoFormattedDate = [parseDate formattedAsTimeAgo];
    [dateLabel setText:[NSString stringWithFormat:@"%@", timeAgoFormattedDate]];
    NSLog(@"%@", timeAgoFormattedDate);

    ////DESCRIPTION TEXT OF POST/////////////////////////////////
    UITextView *postLabel = (UITextView*) [cell viewWithTag:103];
    postLabel.text = [object objectForKey:@"body"];

    ////COMMENT BUTTON/////////////////////////////////////////////////////
    CommentButton *commentButton = (CommentButton*) [cell viewWithTag:222];
    commentButton.index = indexPath.row;
    [commentButton addTarget:self action:@selector(commentSegueWithButton:) forControlEvents:UIControlEventTouchUpInside];

    ////////////////////////////
    [cell configureCell:object];
    return cell;
}

I have been told before that using tags for my cell's is a terrible idea, and to be honest, that's the only way I know of how to reference the make-up of my cell.

I get the warning in the console that a long-running operation is being executed on the main thread. When I check instruments, the lag is 2999MS on the main thread.  I would greatly appreciate any help!


texts:
The previous code on codereview
I'm quite novice here so apologies for any silly mistake in advance
I've been writing a simple tic tac toe game which is a part of my course in udemy
Since this is my first project, I want to do my best in order to learn new things besides learning how to code better. Generally, I want to optimize my code as much as possible.
Can anyone help me with this?
# Tic Tac Toe
# 17 July 2020

import os

test_board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
player_input_num = 0    # numbers of inputs entered by player
player_num = 0
won = False
marker = 'X'

def clear_screen():
    os.system("clear")

def display_board(board_cords):
    '''
    display the board
    board_cords = list(left to right from top to bottom)
    '''
    line = '-'*40
    for counter in range(0, len(board_cords), 3):
        print("\t|\t\t|")
        print(
            f"{board_cords[counter]}\t|\t{board_cords[counter+1]}\t|\t{board_cords[counter+2]}")
        print(line)
        counter += 3    # go to next row

def check_player_input(number):
    if number < 10 and number >= 0:  # checking the range
        return True
    else:
        print('Sorry the input is not in range [0-9] .')
        return False

def player_input(player_in):
    global player_input_num  # access to player_input_num
    if player_input_num >= 2:
        # check if the position is free to use
        if check_capacity(test_board, player_in):
            result = place_marker(test_board, 'X', player_in)
            clear_screen()
            display_board(result)

            if check_win(test_board, marker):
                print("You Won!")
                global won
                won = True
        else:
            print("The current position is occupied.")
    else:
        if check_capacity(test_board, player_in):
            result = place_marker(test_board, 'X', player_in)
            clear_screen()
            display_board(result)
            player_input_num += 1
        else:
            print("The current position is occupied.")

def check_capacity(board, position):
    '''
    Check if the current position is free to use.
    '''
    return board[position] == ' '

def place_marker(board, marker, position):
    '''
    Replace the position with a marker
    '''
    board[position] = marker
    return board

def check_win(board, marker):
    '''
    Check if the current game is finished
    '''
    if board[0] == board[1] == board[2] == marker:
        return True
    if board[0] == board[3] == board[6] == marker:
        return True
    if board[0] == board[4] == board[8] == marker:
        return True
    if board[2] == board[5] == board[8] == marker:
        return True
    if board[6] == board[7] == board[8] == marker:
        return True
    if board[2] == board[4] == board[6] == marker:
        return True
    return False

def wanna_play():
    answer = input("Wanna play again? (Y or N)")
    return answer

# Main
display_board(test_board)
while True:
    while won == False:
        try:  # checking if input is int
            player_num = int(input("Enter a position: "))
        except:
            print("Input is not a number")
            continue

        if check_player_input(player_num):
            player_input(player_num)

    if wanna_play() in ['y', 'Y', 'n', 'N']:
        print("something")
    else:
        print("Invalid input.")
        # print("Thanks for playing :)")

Note that code is working, I just want to know other ways of doing it and optimize it overalls.


texts: Counting occurrences of "hi" in a string, except where followed by "x"

texts:
I already solved this one from CodingBat, but I'm unsatisfied with my solution and I feel I could have made it much shorter. Most of the other recursion tasks could be solved by a one line conditional for the base case and a one line return statement usually using ternary operator. So, could I have made this any shorter or more readable?

  Given a string, compute recursively the number of times lowercase "hi" appears in the string, however do not count "hi" that have an 'x' immedately before them.

public int countHi2(String str) {
  if (str.length() <= 1) {
    return 0;
  }

  if (str.startsWith("x") && str.charAt(1) != 'x') {
    return countHi2(str.substring(2));
  }
  else if (str.startsWith("hi")) {
    return 1 + countHi2(str.substring(2));
    }
  else {
    return countHi2(str.substring(1));
  }
}


texts:
I have such problem : find all png files to disk and rename them as I did:

static void DirSearch(string sDir)
{
    try
    {
        var images = Directory.GetFiles(sDir, "*.png");
        images.ToList().AsParallel().WithDegreeOfParallelism(100).ForAll(dd =>
       Rename(dd)
   );

    }
    catch { }

    try
    {
        foreach (string path in Directory.GetDirectories(sDir))
                DirSearch(path);
    }
    catch (System.Exception excpt)
    {
        Console.WriteLine(excpt.Message);
    }

}

Actually a question : whether it is optimized enough ? Need as quickly as possible to process all png files.


texts: Which swift screen handler approach is better for instantiating a utility class and then presenting a viewController?

texts:
1st approach:

let whatsNewHandler = WhatsNewHandler(buildNumber: buildNumber)
 whatsNewHandler.showWhatNewScreeen(completion: { whatsNewVC in

      self.present(whatsNewVC, animated: true, completion: nil)
 })

2nd approach, which looks a bit functional:

WhatsNewHandler(buildNumber: buildNumber).showWhatNewScreeen(completion: { whatsNewVC in

      self.present(whatsNewVC, animated: true, completion: nil)
})

While both allocate the same amount of memory. I like the functional approach, I just do something and that's really it. But the reason I'm asking is I haven't seen anyone write like this. I see things similar to it when you're using a singleton, but this isn't a singleton.

EDIT:

My WhatNewHandler class:

import Foundation
import UIKit

typealias WhatsNewCompletionHandler = (_ whatsNewViewController: WhatsNewViewController) -> ()

class WhatsNewHandler{

    let buildNumber : String
    lazy var route : Router = {
      return Router.whatsNew(buildNumber: self.buildNumber)
    }()

    init(buildNumber: String){
        self.buildNumber = buildNumber
    }

    func showWhatNewScreeen(completion: @escaping WhatsNewCompletionHandler){

        NetworkHandler.sharedInstance.request(route, success: { json,_  in

            guard let json = json else{
                writelog("what's new json was nil")
                return
            }
            if let releaseBuild = ReleaseBuild(json: json){
                let WhatsNewVC = WhatsNewViewController(releaseBuild: releaseBuild)
                WhatsNewVC.modalPresentationStyle = .overFullScreen

                // TEST ALPHA ON REAL DEVICE
                WhatsNewVC.view.backgroundColor = UIColor.black.withAlphaComponent(0.985)
                completion(WhatsNewVC)
            }
            }, failed: {_,_,_ in

        })
    }
}

As for my WhatsNewViewController, kindly assume it to be a Viewcontroller that shows a list of new features added to the app.


texts:
After studying from Introduction to Algorithm and taking help from internet I have written a program. I don't know much about C++11. Please help me to optimize this program with better functions and better runtime.

Note: I have used adjacency matrix instead of adjacency list and I don't know whether I have used it in correct way.

#include <iostream>
#include <vector>

class Graph
{
  int V; //no of Vertices
  enum class Color { WHITE, GRAY, BLACK };

  struct Vertex
  {
  char id;
  Color color;
  Vertex(char c, Color clr) : id(c), color(clr) {}
  };
  std::vector< std::vector<int> > adjMatrix; //adjacency Matrix
  std::vector<Vertex> vertices;

public:
  Graph(int);
  void addEdge(int, int);
  void DFS(int);
};

Graph::Graph(int v)
{
  V = v;
  adjMatrix.resize(V, std::vector<int>(V));
  for(int i = 0; i < V; i++)
  {
    vertices.push_back( Vertex('A'+i, Color::WHITE));
    for(int j = 0; j < V; j++)
    {
      adjMatrix[i][j] = 0;
    }
   }
}

void Graph::addEdge(int a, int b)
{
  adjMatrix[a][b] = 1;
}

void Graph::DFS(int u)
{
  vertices[u].color = Color::GRAY;
  std::cout << vertices[u].id <<" ";

  for(int i = u; i < V; i++)
  {
    for(int j = 0; j < V; j++)
    {
      if(adjMatrix[i][j] == 1)
      {
        if(vertices[j].color == Color::WHITE)
        DFS(j);
      }
    }
  }
  vertices[u].color = Color::BLACK; //blacken u, it is finished
}

int main()
{
  Graph grp(4);
  grp.addEdge(0, 1);
  grp.addEdge(1, 2);
  grp.addEdge(2, 3);
  grp.addEdge(2, 1);
  grp.addEdge(0, 3);

  grp.DFS(2);
  return 0;
}


texts:
I have seen one algorithmic task and I am not sure if my solution is fully efficient. As input to the method you are given positive integer N. And you should return the sum of values of the digits in a decimal representation of N!.

For example, given N = 6 the function should return 9, because N != 720 and sum of digits 7 + 2 + 0 = 9. Result cannot exceeds 100000000. N is higher or equal than 1 and less or equal than 2000.

Is this an efficient solution and the best optimized?

public int solution(int N) {
    long factorial = 1;
    for (int i = 1; i <= N; i++)
        factorial = factorial * i;
    long res = 0;

    while(factorial>0) {
        res+=factorial%10;
        factorial/=10;
    }
    if (res > 100000000)
        return -1;
    return (int) res;
}


texts: Code to initialize, set, or get node properties

texts:
I have this JavaScript excerpt, and I was wondering if this (primarily the usage of switch case) would be considered good practice. One item of note is that I have it separated into two similar parts to not evaluate the same boolean check over and over again when it is static the whole time.

if (strict) {
  for (var i = 0, len = node.properties.length; i < len; ++i) {
    var other = node.properties[i];
    if (other.key.name !== prop.key.name) continue;
    var otherKind = other.kind;
    switch (kind) { // used as a kind of goto
    case "init":
    case "get":
    case "set":
      if (otherKind === "get" ||
          otherKind === "set" ||
          otherKind === "init")
        raise(prop.key.start, "Redefinition of property");
  }
} else if (sawGetSet)) {
  loop:
  for (var i = 0, len = node.properties.length; i < len; ++i) {
    var other = node.properties[i];
    if (other.key.name !== prop.key.name) continue;
    var otherKind = other.kind;
    switch (kind) { // used as a kind of goto
    case "get":
    case "set":
      if (otherKind === "init") break;
    case "init":
      if (otherKind === "get" || otherKind === "set") break;

    default: continue loop; // skip the below portion, don't throw error
    }
    raise(prop.key.start, "Redefinition of property");
  }
}

Should I rewrite it like this, something else, or leave it as is? (Speed still is important.)

if (strict) {
  for (var i = 0, len = node.properties.length; i < len; ++i) {
    var other = node.properties[i];
    if (other.key.name !== prop.key.name) continue;
    var otherKind = other.kind;
    if ((kind === "init" ||
         kind === "get" ||
         kind === "set") &&
        (otherKind === "get" ||
         otherKind === "set" ||
         otherKind === "init")) {
      raise(prop.key.start, "Redefinition of property");
    }
  }
} else if (sawGetSet)) {
  for (var i = 0, len = node.properties.length; i < len; ++i) {
    var other = node.properties[i];
    if (other.key.name === prop.key.name) continue;
    var otherKind = other.kind;
    if ((kind === "get" ||
         kind === "set") &&
        (otherKind === "init" ||
         otherKind === "get" ||
         otherKind === "set")) {
      raise(prop.key.start, "Redefinition of property");
    } else if ((kind === "init") &&
               (otherKind === "get" ||
                otherKind === "set")) {
      raise(prop.key.start, "Redefinition of property");
    }
  }
}


texts:
I'm trying to implement signed URLs for short lived access to static files.
The idea is:

generate an URL with an expiration timestamp (e.g. https://example.com/file.png?download=false&expires=1586852158)
sign it with HMACSHA256 and a private key and append the signature at the end of URL (e.g. https://example.com/file.png?download=false&expires=1586852158&signature=6635ea14baeeaaffe71333cf6c7fa1f0af9f6cd1a17abb4e75ca275dec5906d1

When i receive the request on the server, I take out the signature parameter and verify that the rest of the URL signed with HMACSHA256 and the same private key results in the same signature.

The implementation is as follows:

    public static class URLSigner
    {
        private static string GetSignatureForUri(string uri, byte[] key)
        {
            var hmac = new HMACSHA256(key);
            var signature = hmac.ComputeHash(Encoding.UTF8.GetBytes(uri));
            var hexSignature = BitConverter.ToString(signature).Replace("-", string.Empty).ToLowerInvariant();
            return hexSignature;
        }

        public static string SignUri(string uri, byte[] key)
        {
            var hexSignature = GetSignatureForUri(uri, key);
            return QueryHelpers.AddQueryString(uri, new Dictionary<string, string> { { "signature", hexSignature }});
        }

        public static bool VerifyUri(string uri, byte[] key)
        {
            var signatureRegex = "[\\?&]signature=([a-z0-9]+)$";
            var signatureMatch = Regex.Match(uri, signatureRegex);
            if (!signatureMatch.Success || signatureMatch.Groups.Count != 2)
                return false;
            var parsedSignature = signatureMatch.Groups[1].Value;

            var originalUri = Regex.Replace(uri, signatureRegex, "");
            var hexSignature = GetSignatureForUri(originalUri, key);
            return hexSignature == parsedSignature;
        }
    }

and it's used like so:

var signedUri = URLSigner.SignUri("https://example.com/file.png?download=false", secretKey);
var isVerified = URLSigner.VerifyUri(signedUri, secretKey);

The timestamp is verified separately on the request handler.

Is this implementation of signed URLs reasonably secure?


texts: Given an array of Strings , check if they are anagrams are not

texts:
Two strings are anagrams if they are permutations of each other. Assuming we have an ASCII alphabet we can take 128 integer array to count the characters in the first string. Then decrement the count for the corresponding character in the second string. If all the character counts are zero then the strings are anagrams else they are not.

public class anagrams {
        public static boolean anagramsHelper(String[] words)
        {
            for(int i = 1 ; i < words.length ; i++)
            {
                if(!areAnagrams(words[0], words[i]))
                {
                    return false;
                }
            }
            return true;
        }
        public static boolean areAnagrams(String word1, String word2)
        {
            if(word1.length() != word2.length())
            {
                return false; // anagrams are strings with same length
            }
            int[] charCount = new int[128]; // 128 unique chars in ASCII
            //count the chars in word1
            for(int i = 0 ; i < word1.length() ; i++)
            {
                charCount[(int)word1.charAt(i)]++;
            }
            //decrement the char count for chars in word2
            for(int i = 0 ; i < word2.length() ; i++)
            {
                if(charCount[(int)word2.charAt(i)] == 0)
                {
                    return false;
                }
                charCount[(int)word2.charAt(i)]--;
            }
            //verify if any char count is non zero
            //for anagrams it should be zero else they are not anagrams
            for(int i  = 0 ; i < 128 ; i++)
            {
                if(charCount[i] != 0)
                {
                    return false;
                }
            }
            return true;
        }
        public static void main(String[] args) {
            String[] words = {"abc", "bca", "cab" , "myd"};
            System.out.println(anagramsHelper(words));
        }
    }