texts:
The script reads WLAN packets, looks for probe requests and then extracts SSID, MAC address and then stores them in a list if the MAC address/SSID combo is unique.

if p.haslayer(Dot11ProbeReq):
    if pc == 0:
      print O+'[+]'+W+' Got first packet! Many more to go...\n'
        if p.haslayer(Dot11Elt):
          pc +=1
          vali = 0
            if p.ID == 0:
              ssid = p.info
                if ssid != "":
                  for (i,j) in obs:
                    if (i,j) != (p.addr2,ssid):
                        vali += 1
                    else:
                        break
                    if vali == len(obs):
                        obs.append((p.addr2,ssid))
                        checkmac(p.addr2)
                        checknet(ssid)
                        count +=1
                        get_oui(p.addr2)
                        print str(count)+'>',p.addr2+' ('+G+macf+W+') <--Probing--> '+O+ssid+W
                        wr_log(p.addr2,ssid,macf)
                    else:
                            pass

What modifications can I make to make the code faster, specially the for block and the validation process? Any other optimizations or practices that I should be following?

This script is reliant on the scapy library. Here p is a packet that scapy intercepts. It could be any type of packet - management, data or control etc. and can be of any subtype - deauthentication, probe response, authentication, probe request etc. The function that I have mentioned above reads each packet p and processes it the way I desire. The code begins with intercepting any packet p from the air and checking if the packet is a probe request. A probe request is emitted by all wifi enabled devices when they are looking to connect to a wifi network if they can't find one or even if they are connected, then to find a backup network in case the currently connected network fails. These probe requests are automatic and the users don't get to choose anything about them. The devices will emit these requests broadcasting a list of known wireless networks to check if there is any of them available nearby. After the packet is confirmed to be a probe request, the packet counter (pc) checks if it is the first packet, if it is then it displays a message confirming that we are able to receive requests and the network is up. Then the function checks whether the packet has a Dot11Elt layer, which is the information element that contains all the info about the device and previously connected wireless networks. If it does have an information layer then the value in the first information layer, which happens to be the ssid of a previously connected network, is stored in a variable called ssid. the variable p.addr2 is the MAC address of the device that the packet came from. Each MAC/SSID pair found is stored in an orderly fashion inside the list obs. Each packet intercepted, as many can be duplicates, are checked against the ones already stored in obs and if unique against each pair already stored, then the value of the vali (validation counter) is incremented. Needless to say, if the value of vali is the same as the length of obs then the packet is unique and did not match any other (MAC/SSID) pair stored in obs and is hence, printed. Before printing, the unique (MAC/SSID) pair is appended to the list obs and the functions checkmac() and checknet() check whether the MAC address or the SSID is unique, if they are then a counter is incremented and that helps us to identify unique devices and unique networks after the script stops running. The function get_oui() gets the manufacturer name though the use of netaddr library for each and every MAC address we find and wr_log() writes the MAC address, SSID name and manufacturer info in a log file.


texts: Optimizing primes generating program in C++

texts:
I am writing a program to generate primes in range 1 upto 10^9 but it seems to be timing out.

It implements the Sieve of Atkin

I have tried optimizing my code using bitsets and pragmas.

Please are there any other ways i can optimize my code. Code below

#include<bitset>
#include<vector>
#include<iostream>
#include<algorithm>
#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
using namespace std;
#define int long long
const int LIM = 1e9;
bitset<100000000> sieve;
void compute(int limit)
{
    if (limit > 2)
        cout<<"2 ";
    if (limit > 3)
        cout<<"3 ";

    for (int x = 1; x * x < limit; x++) {
        for (int y = 1; y * y < limit; y++) {
            int n = (4 * x * x) + (y * y);
            if (n <= limit && (n % 12 == 1 || n % 12 == 5))
                sieve.flip(n);

            n = (3 * x * x) + (y * y);
            if (n <= limit && n % 12 == 7)
                sieve.flip(n);

            n = (3 * x * x) - (y * y);
            if (x > y && n <= limit && n % 12 == 11)
                sieve.flip(n);
        }
    }
    for (int r = 5; r * r < limit; r++) {
        if (sieve.test(r)) {
            for (int i = r * r; i < limit; i += r * r)
                sieve.reset(i);
        }
    }
    for(int i=sieve._Find_first();i< sieve.size();i = sieve._Find_next(i))
    {
        if(i==0||i==1)continue;
        cout<<i<<" ";
    }
    cout<<endl;
}
signed main()
{
    compute(LIM);
    return 0;
}

Thanks in advance.


texts:
I am working on angularjs, and I have created some directives with bunch of HTML elements within its templates. I have assigned a controller for those directives.  Below is my code snippet:

directives.directive('ngLd',function()
{
    return {
        restrict : "AE",
        templateUrl:'partials/ld.html',
        scope:{},
        link : function(scope,element,attr)
        {
            var lbutton = element.find("span[class='lb-lk-comm']");
            var dlbutton = element.find("span[class='lb-dlk-comm']");
            if(lbutton && dlbutton)
            {
                lbutton.bind('click',function(event)
                {
                    scope.likeAction(lbutton.hasClass("lb-voted-comm"),dlbutton.hasClass("lb-voted-comm"));
                    scope.$apply();
                });
                dlbutton.bind('click',function(event)
                {
                    scope.dislikeAction(lbutton.hasClass("lb-voted-comm"),dlbutton.hasClass("lb-voted-comm"));
                    scope.$apply();
                });
            }
        },
        controller : "MyController"
    };
});

In the above code, I have used a link function of bind the click event on required elements.
Another approach I could have followed to use the ngClick directive directly over the elements, but that is sort of exposing method to client end.

My question is, am I following a good approach by binding click event ? or should I use ngClick ?

I am using angular.bootstrap(document,"myApp"); to bootstrap the angular module to document, so I was wondering if I could have similar thing to dynamically bind those events (click, hover, change etc) to my HTML elements, without exposing them to HTML pages.


texts: Program to print the number as a sum of consecutives

texts:
We need the input number as the sum of consecutive natural numbers.

  Examples:

  For input 27, output should be:

  2 3 4 5 6 7

  8 9 10

  13 14

  For input 9, the output should be:

  4 5

  2 3 4

Here is my code. It works as it is expected to:

import java.util.*;
class Consecutives
{
    static void print()
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number: ");
        double n = sc.nextDouble();
        /*
         * Needed: Different Arithmetic progressions (APs) with common difference 1;
         * i(2a + (i-1)) = 2n // from formula for sum of AP, a indicates first term of progression
         * #implies -> a = n/i - (i-1)/2   // i indicates number of terms of AP possible
         * Now, a can't be negative so:
         * -> n/i > (i-1)/2
         * -> Range of i = [2, (int)(1+sqrt(1+8n))/2]
         */
        int max_i = (int)((1+Math.sqrt(1+8*n))/2);
        System.out.println("Max i = "+ max_i);
        double a;
        for(double i=2; i <= max_i ;i++)
        {
            a = n/i - (i-1)/2;
            if(a == Math.floor(a) && a>0)//i.e if a is an integer
            {

                if(i*(2*a+ (i-1))== 2*n)
                {
                    for(int j= (int)a ; j<=a + (i-1) ;j++)
                        System.out.print(j+ " ");
                    System.out.println();
                }
                else
                    break;
            }

        }
    }
}

Are my comments too messy? Is there any way to change them and still make the logic clear to the reader? What other improvements can I make to my program?


texts: Cancellable progress form using async/await

texts:
Introduction:

For a project I'm working on I used a BackGroundWorker to lift some heavy tasks away from the UI thread and report progress. For this I created some sort of modal dialog with a label and progress bar which were updated from the ProgressChanged method of the backgroundworker.

I read a very interesting article on async/await and I thought I might update my code, since the BackGroundWorker is, despite being handy, getting outdated anyway. After some more reading on this matter I found an article with code that had the backgroundworker instance inside the modal dialog form and not on the caller form.

This gave me the idea to do the same but using async/await instead. This is a first result, which is working, and I was wondering if I am doing things right. Any tips and/or improvements are much appreciated, certainly regarding scalability/extensibility and the use of async/await.

The form:

The code:

public partial class CancellableProgress : Form
{
    private readonly IEnumerable<KeyValuePair<string, Action>> _tasks;
    private CancellationTokenSource _cancelTokenSource;
    private bool _isTaskCompleted;

    public CancellableProgress(string message, Action action)
        : this(new[] { new KeyValuePair<string, Action>(message, action) })
    {
    }

    public CancellableProgress(IEnumerable<KeyValuePair<string, Action>> tasks)
    {
        InitializeComponent();
        Load += CancellableProgress_Load;
        _tasks = tasks;
    }

    private void CancellableProgress_Load(object sender, EventArgs e)
    {
        PerformTasks(_tasks);
    }

    private async void PerformTasks(IEnumerable<KeyValuePair<string, Action>> tasks)
    {
        _cancelTokenSource = new CancellationTokenSource();
        var token = _cancelTokenSource.Token;
        var progressHandler = new Progress<string>(value => MessageLabel.Text = value);
        var progress = progressHandler as IProgress<string>;

        try
        {
            await Task.Run(() =>
            {
                foreach (var task in tasks)
                {
                    if (token.IsCancellationRequested)
                    {
                        token.ThrowIfCancellationRequested();
                    }
                    progress.Report(task.Key);
                    task.Value();
                }
            }, token);
            _isTaskCompleted = true;
        }
        catch (OperationCanceledException)
        {
            MessageLabel.Text = @"Cancelled!";
        }
        catch (Exception ex)
        {
            MessageLabel.Text = ex.Message;
        }
        finally
        {
            _cancelTokenSource.Dispose();
            DialogResult = _isTaskCompleted ? DialogResult.OK : DialogResult.Cancel;
        }
    }

    private void btnCancel_Click(object sender, EventArgs e)
    {
        CancelTaskButton.Enabled = false;
        _cancelTokenSource.Cancel();
    }
}

Example usage:

This is some code on how I use the modal form.

private void TaskButton_Click(object sender, EventArgs e)
{
    var operations = new[]
    {
        new KeyValuePair<string, Action>("Operation 1", LongOperation),
        new KeyValuePair<string, Action>("Second operation", LongOperationTwo)
    };

    using (var progress = new CancellableProgress(operations))
    {
        progress.ShowDialog();
    }
}

private static void LongOperation()
{
    for (var i = 1; i <= 5; i++)
        System.Threading.Thread.Sleep(1000);
}

private static void LongOperationTwo()
{
    for (var i = 1; i <= 5; i++)
        System.Threading.Thread.Sleep(1000);
}


texts: Checking if any competitors have a non-empty name

texts:
Take this:

has_competitors:function(){
  var c = false;
  _.each(this.competitors, function(obj, index){ // lodash here
    if(obj.name && obj.name.trim() !== ''){
      c = true;
      return false; // to break the loop
    }
  });
  return c;
}

I don't like the form of this, but till now I didn't find a more concise way. Could you suggest a better way? :) I mean, less lines.


texts: If she floats then she is not a witch like we thought

texts:
Continuing my C++ saga, this is the third project for my CS1 class:

  Buoyancy is the ability of an object to float.  Archimedes' principle
  states that the buoyant force is equal to the weight of the fluid that
  is displaced by the submerged object.  The buoyant force can be
  computed by

  $$ F_b = V \cdot y $$

  where \$ F_b \$ is the buoyant force. \$ V \$ is the volume of the
  submerged object, and \$ y \$ is the specific weight of the fluid.  If
  \$ F_b \$ is greater than or equal to the weight of the object, then
  it will float, otherwise it will sink.

  Write a program that inputs the weight (in pounds) and radius (in
  feet) of a sphere and outputs whether the sphere will sink or float in
  water.  Use \$ y = 62.4 \dfrac{\text{lb}}{\text{ft}^3} \$ as the
  specific weight of water.  The volume of a sphere is computed by \$ \left( \dfrac{4}{3} \right) \pi r^3\$.

Additionally, I must have a loop in this program that allows the user to run it as many times as they want to. I have to ask the user each time whether they want to continue.

It is also supposed to be fully commented, which I think I have done within reason.

buoyancy.cpp:

/**
 * @file buoyancy.cpp
 * @brief Calculates if a sphere will sink or float in water given the weight and radius
 * @author syb0rg
 * @date 9/12/14
 */

#include <iostream>
#include <limits>
#include <math.h>

/**
 * Sphere
 * @var weight The weight of the sphere
 * @var radius The height of the sphere
 */
struct Sphere
{
    double weight = 0;
    double radius = 0;
};

/**
 * Resets the command line so we can input data again, and signals user to re-enter proper data
 */
void resetConsole()
{
    std::cin.clear(); // clear the error flag that was set so that future I/O operations will work correctly
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skips to the next newline
    std::cout << "Invalid input.  Please enter a positive number: ";
}

int main()
{
    constexpr double waterBuoyancy = 62.4;
    Sphere obj;
    char again = '\0';
    do
    {
        // get input for height, re-read input if not a positive number
        std::cout << "Enter the weight in pounds: ";
        while(!(std::cin >> obj.weight) || obj.weight < 0) resetConsole();

        // get input for radius, re-read input if not a positive number
        std::cout << "Enter the radius in inches: ";
        while(!(std::cin >> obj.radius) || obj.radius < 0) resetConsole();

        double volume = ((4/3) * M_PI * pow(obj.radius, 3));
        double bouyantForce = volume * waterBuoyancy;

        if (obj.weight <= bouyantForce) std::cout << "The object will float." << std::endl;
        else std::cout << "The object will sink." << std::endl;

        std::cout << "Run the program again (y/N): ";
        std::cin.get();  // absorb newline character from previous input
        std::cin.get(again);
        again = tolower(again);
        if ('\n' == again) again = 'n';
    } while (again == 'y');
}


texts: PHP API Query using CURL and return JSON

texts:
Fairly new to writing PHP. I want some PHP code to query an API with a post request, set specific headers and message body, and echo out the JSON response. This is the code I have come up with, which validates but I dont know if its optimal:

<?php
$url = 'http://api.local/rest/users';
$data = '{"4":"four","8":"eight"}';
$accesstoken = 'abc';
$apikey = 'abc';
$companyid = 'abc';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json', 'Content-Type: application/json', 'Authorization: Bearer $accesstoken', 'x-api-key: $apikey', 'x-proxy-global-company-id: $companyid']);
$result = curl_exec($ch);
?>


texts: Using promises to zoom to a project, then to a task or comment

texts:
How to beautify this part of code? (I mean usage of promise in promise) I really have no clue how this could've look like.

    function zoom(projectId) {
        Service.useZoomToProject(projectId).then(
            function (useZoomToTask) {
                if (useZoomToTask) {
                    CrmDataServices.getProjectTaskId(projectId).then(
                        function (taskId) {
                            zoomByTask(taskId);
                        });
                } else {
                    zoomByComment(projectId);
                }
            }
        );
    }


texts:
I am trying to code a sin wave with 5 sliders: frequency, amplitude, phase change, number of data points, and time. I am currently trying to link my phase change slider with my graph so that it updates it when I move the slider. I realize that my code is probably quite messy and could be more concise but I can adjust that later.
I think adding a phase change slider and length of time the function is plotted for would be good too, like the frequency and amplitude sliders (which do work).
For those who aren't familiar with the physics terms:
amplitude: height of the wave (in y-axis)

frequency: number of times a wave passes a certain point per unit time. 1 Hertz = 1 wave passing per second
Phase difference: the change in the starting position of the current wave where amplitude = 0 at t = 0. A 90-degree phase change would shift the function the left or right, then representing a cos function rather than sine.

Any advice for my current code would be much appreciated!
My code so far:
import tkinter
import numpy as np
from scipy import signal
from scipy.fft import fft, ifft as sc
from matplotlib import pyplot as p, animation
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
from matplotlib.widgets import Slider

root = tkinter.Tk()
root.wm_title("Embedding in Tk")
fig = Figure(figsize=(6, 5), dpi=100)
t = np.linspace(0, 5, 200)
f = 1
time = np.linspace(0, 100, 101)
y = np.sin(f*t)

fig.subplots_adjust(left=0.15, bottom=0.45)  # Adjust subplots region leaving room for the sliders
and buttons

canvas = FigureCanvasTkAgg(fig, master=root)  # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

def on_key_press(event):
    print("you pressed {}".format(event.key))
    key_press_handler(event, canvas, toolbar)

canvas.mpl_connect("key_press_event", on_key_press)

def _quit():
    root.quit()  # stops mainloop
    root.destroy()

button = tkinter.Button(master=root, text="Quit", command=_quit)
button.pack(side=tkinter.BOTTOM)

# Amplitude slider
initiala = 1  # starting value of amplitude on graph
asliderax = fig.add_axes([0.25, 0.15, 0.65, 0.03])  # setting amplitude slider position
aslider = Slider(asliderax, 'Amp', 0.1, 10.0, valinit=initiala)  # setting amplitude slider values

# Frequency slider
initialf = 1  # starting value of frequency on graph
fsliderax = fig.add_axes([0.25, 0.1, 0.65, 0.03])  # setting frequency slider position
fslider = Slider(fsliderax, 'Freq', 0.1, 3.0, valinit=initialf)  # setting frequency slider values

# Time slider
initialt = 1  # starting value of time on graph
tsliderax = fig.add_axes([0.25, 0.2, 0.65, 0.03])  # setting time slider position
tslider = Slider(tsliderax, 'Time', 0.1, 100.0, valinit=initialt)  # setting time slider values

# Number of Points slider
initialp = 99  # starting value of number of points on graph
psliderax = fig.add_axes([0.25, 0.25, 0.65, 0.03])  # setting points slider position
pslider = Slider(psliderax, 'Points', 3, 30.0, valinit=initialp)  # setting frequency points values

# Phase slider
initialph = 0  # starting value of number of points on graph
phsliderax = fig.add_axes([0.25, 0.3, 0.65, 0.03])  # setting points slider position
phslider = Slider(phsliderax, 'Phase Change', 0, np.pi*2, valinit=initialph)  # setting frequency
points values

def update(val):
    amp = aslider.val
    freq = fslider.val
    t = np.linspace(0, 5, 200)
    y.set_ydata(amp*np.sin(2*np.pi*freq*t))

fslider.on_changed(update)
aslider.on_changed(update)
tslider.on_changed(update)
pslider.on_changed(update)

tkinter.mainloop()


texts:
I am making my first object-oriented program in python and I am having trouble with the __str__ part of Board() class. I want it to be a visual representation of the tic-tac-toe board. I have achieved this but the code looks ridiculous and I know there must be a better way! Here is my project so far:

class Space(object):

    def __init__(self, state="x"):
        self.state = state

    state_names = ['empty', 'x', 'o']

    def __str__(self):

        return str(self.state)

    def change_state(self, string):
        if string == 'x':
            self.state = 'x'
        else:
            self.state = 'o'

class Board(object):

    def __init__(self):
        self.spaces = []
        for num in range(0,9):
            space = Space()
            self.spaces.append(space)
        board = self.spaces

    def __str__(self):
        res = []
        for space in self.spaces:
            res.append(str(space))
        return '   |   |'  + '\n ' + res[6] + ' | ' + res[7] + ' | ' + res[8] + '\n   |   |' + '\n-----------' + '\n   |   |' + '\n ' + res[3] + ' | ' + res[4] + ' | ' + res[5] + '\n   |   |' + '\n-----------' + '\n   |   |' + '\n ' + res[0] + ' | ' + res[1] + ' | ' + res[2] + '\n   |   |'

the default output should (and does) look like this:

   |   |
 x | x | x
   |   |
-----------
   |   |
 x | x | x
   |   |
-----------
   |   |
 x | x | x
   |   |


texts: Get percentage on the fly with AND and LIKE

texts:
Aim: Get percentage based on if field is blank or not

Issue: Unknown amount of variables based on search and thus speed

Solution: Dynamic SQL build up

Looking for: Tips to speed up even more/spot injection as required!

Notes: removed all but one vString SQL line for viewing purposes

  Dim vString As String = ""
        If Trim(sUPRN.Text) <> "" Then vString = "p.UPRN Like '%" & Trim(sUPRN.Text) & "%'"

    If vString <> "" Then
        vString = " and " & vString
    End If

Dim ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("mySQL").ToString()
'Count total lines of data and see if they have a certifacte then get percentage
        Try

        Using connection = New SqlConnection(ConnectionString)
            '######### VERY IMPORTANT --> DOCURL MUST BE NULL FOR THIS TO WORK! (not blank!!)
            Using command As New SqlCommand("Select count(d.docurl)  * 100.0 / sum(count(d.id)) over() From TblData   AS D  JOIN TBLPROPERTYLIST AS p ON d.UPRN = p.UPRN WHERE 1 = 1 " & vString & "", connection)
                connection.Open()
                lblCertOutput.Text = Math.Floor(command.ExecuteScalar())
            End Using

        End Using

    Catch ex As Exception
        lblCertOutput.Text = "N/A"
    End Try


texts:
I am making an application using Phonegap where users can select and share files. When the user selects it, even if it goes offline or closes the app, I should upload it back to the server, so I need to store the reference file path.

Steps I have used:

User selects/captures video or image using Camera.
File may not contain extension to name in Android every time and in iOS when selected from Gallery.
Get mimeType and then copy the file to myApp's folder with a new name and extension.
Then again get mimeType and return.

Is it correct to copy a file to another location whenever the user selects a media file?

 var obj = {
    destinationType: navigator.camera.DestinationType[fromCamera ? 'FILE_URI' : 'NATIVE_URI'],
    // If I use NATIVE_URI for when taking from Camera it returns null.
    sourceType: navigator.camera.PictureSourceType[fromCamera ? 'CAMERA' : 'PHOTOLIBRARY'],
    mediaType: navigator.camera.MediaType[image ? 'PICTURE' : 'VIDEO']
}, that = this;

if (image && fromCamera) {
    obj.correctOrientation = true;
    obj.quality = 40;
}

return new Promise(function (resolve, reject) {
    navigator.camera.getPicture(function (url) {
        var fail = function () {
            resolve(false);
        }
        window.setTimeout(function () {
            // mimeType uses window.resolveLocalFileSystemURL to get fileEntry
            that.mimeType(url).then(function (mimeObj) {
                /*
                    mimeObj contains object like below
                    {lastModified:'', fileType:'', fileExtension:'', name : ''}
                */
                if (mimeObj) {
                    // that.fileSystem() resolves fileSystem
                    that.fileSystem().then(function (fs) {
                        // dirName is where I want to store all myApp's media files.
                        var dirName = 'myApp/media/' + (image ? "images" : "videos") + '/';
                        that.getFile(url).then(function (fileEntry) {
                            // getFile uses window.resolveLocalFileSystemURL and returns fileEntry
                            that.moveTo(fs, fileEntry, dirName, mimeObj.name).then(function (entry) {
                                // MoveTo fill copy the same file to directory where I am manintaing files.
                                mimeObj.localURL = entry.nativeURL;
                                /*
                                    mimeObj is failing to find extension
                                    when user selects it from different albums. But not when user uses Camera.
                                    So I am making again mimeType call.
                                */
                                that.mimeType(mimeObj.localURL).then(function (mimeObj) {
                                    // This gives me exact mimeObj that I need.
                                    resolve(mimeObj);
                                });
                            }, fail);
                        }, fail);
                    }, fail);
                } else {
                    resolve(false);
                }
            });
        }, 0);

    }, function (fail_message) {
        window.setTimeout(function () {
            reject(fail_message);
        }, 0);
    }, obj);
});


texts: Removing a specific key of ModelState for a specific controller's method

texts:
I have a controller for Post and Put request for the same entity: MyModelDTO with some ModelState's attributes.

The users can make a Post request without the Id attribute, because it is being generated on server side, but for Put request the Id attribute is needed (And has to be different than an empty guid).

I want to allow get a Post request without the "Id" property, and still use the ModelState functionality, the best solution I've came across is overriding the OnActionExecuting and removing the specific key:

public class ExceptPropertiesAttribute : ActionFilterAttribute
{
    private IEnumerable<string> _propertiesKeys;

    public ExceptPropertiesAttribute(string commaSeperatedPropertiesKeys)
    {
        if (!string.IsNullOrEmpty(commaSeperatedPropertiesKeys))
        {
            this._propertiesKeys = commaSeperatedPropertiesKeys.Split(',');
        }
    }

    public override void OnActionExecuting(ActionExecutingContext actionContext)
    {
        if (this._propertiesKeys != null)
        {
            foreach (var propertyKey in this._propertiesKeys)
            {
                if (actionContext.ModelState.ContainsKey(propertyKey))
                {
                    actionContext.ModelState.Remove(propertyKey);
                }
            }
        }
    }
}

MyModelDTO class:

public class EventModelDTO : IBaseModel
{
    [IsNotEmpty(ErrorMessage = "Guid Id Is Empty")]
    public Guid Id { get; set; }
    [Required]
    public string Name { get; set; }
}

public class IsNotEmptyAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        if (value == null) return false;

        var valueType = value.GetType();
        var emptyField = valueType.GetField("Empty");

        if (emptyField == null) return true;

        var emptyValue = emptyField.GetValue(null);

        return !value.Equals(emptyValue);
    }
}

Usage:

[HttpPost]
[ExceptPropertiesAttribute("Id")]
public ActionResult Post([FromBody] MyModelDTO itemDTO = null)
{
    try
    {
        if (!ModelState.IsValid)
        {
            return BadRequest();
        }

        MyModel item = _mapper.Map<MyModel>(itemDTO);
        ResultService result = this._myService.Insert(item);
        if (result.Success)
        {
            return CreatedAtAction("Post", new { item.Id }, itemDTO);
        }
        else
        {
            return StatusCode(500, result.ErrorCode);
        }
    }
    catch (Exception ex)
    {
        return StatusCode(500, ErrorCode.Unknown);
    }
}

[HttpPut("{id}")]
public ActionResult Put([FromBody] MyModelDTO itemDTO)
{
    try
    {
        if (!ModelState.IsValid)
        {
            return BadRequest();
        }

        MyModel item = _mapper.Map<MyModel>(itemDTO);
        ResultService result = this._eventsService.Update(item);
        if (result.Success)
        {
            return Ok();
        }
        else
        {
            return StatusCode(500, result.ErrorCode);
        }
    }
    catch (Exception ex)
    {
        return StatusCode(500, ErrorCode.Unknown);
    }
}


texts: Fetching certain eventIDs from servers on network.

texts:
The PowerShell script below queries the Security event log on one or more servers for events with id 4663. When trying to retrieve all audit events for event id 4663 with the following code the computer throws the following exception: how can we to optimize this PowerShell?
So I just want to fetch security event log based on specific AD Users instead of all of users. Otherwise I want to retrieve what I need.

$server = "HOSTNAME"
$out = New-Object System.Text.StringBuilder
$out.AppendLine("ServerName,EventID,TimeCreated,UserName,File_or_Folder,AccessMask")
$ns = @{e = "http://schemas.microsoft.com/win/2004/08/events/event"}
foreach ($svr in $server)
    {    $evts = Get-WinEvent -computer $svr -FilterHashtable @{logname="security";id="4663"} -oldest

    foreach($evt in $evts)
        {
        $xml = [xml]$evt.ToXml()

        $SubjectUserName = Select-Xml -Xml $xml -Namespace $ns -XPath "//e:Data[@Name='SubjectUserName']/text()" | Select-Object -ExpandProperty Node | Select-Object -ExpandProperty Value

        $ObjectName = Select-Xml -Xml $xml -Namespace $ns -XPath "//e:Data[@Name='ObjectName']/text()" | Select-Object -ExpandProperty Node | Select-Object -ExpandProperty Value

        $AccessMask = Select-Xml -Xml $xml -Namespace $ns -XPath "//e:Data[@Name='AccessMask']/text()" | Select-Object -ExpandProperty Node | Select-Object -ExpandProperty Value

        $out.AppendLine("$($svr),$($evt.id),$($evt.TimeCreated),$SubjectUserName,$ObjectName,$AccessMask")

        Write-Host $svr
        Write-Host $evt.id,$evt.TimeCreated,$SubjectUserName,$ObjectName,$AccessMask

        }
    }
$out.ToString() | out-file -filepath C:\TEMP\4663Events.csv


texts:
Question:
Implement an autocomplete system. That is, given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix.
For example, given the query string de and the set of strings [dog, deer, deal], return [deer, deal].
Hint: Try preprocessing the dictionary into a more efficient data structure to speed up queries.
What I tried to do:
Implement prefix tree is way to go as researched from internet. So without looking at actual implementation code, I just grabbed the idea and wrote down the code to challenge myself. Of course code is a messy, but will be really appreciated if someone could advice on how it can be improved in terms of efficiency and simplicity.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define ALP_PREFIX 97 //for numeric value of alphabets

typedef struct stTree
{
    struct stTree *nLetter[26];
    bool isLastChar;
    char value;
} stTree;

stTree* createNode(void)
{
    stTree *node = malloc(sizeof *node);
    node->value = '\0';
    node->isLastChar = false;
    return node;
}

stTree* insertNode(stTree *currNode, char value, bool isLastChar)
{
    if (!currNode->nLetter[value - ALP_PREFIX])
    {
        stTree *node = malloc(sizeof *node);
        node->value = value;
        currNode->nLetter[value - ALP_PREFIX] = node;
    }

    currNode->nLetter[value - ALP_PREFIX]->isLastChar = isLastChar;
    return currNode->nLetter[value - ALP_PREFIX];
}

stTree* treeTraverse(char *chars, stTree *Node)
{
    stTree *nextNode = Node->nLetter[chars[0] - ALP_PREFIX];
    if (nextNode && chars[0] != '\0')
    {
        return treeTraverse(chars + 1, nextNode);
    }
    else
        return Node;
}

void autoComplete(stTree *Node)
{
    for (int i = 0; i < 26; i++)
    {
        if (Node->nLetter[i])
        {
            printf("%c", Node->nLetter[i]->value);
            if (Node->nLetter[i]->isLastChar)
                printf("]");
            autoComplete(Node->nLetter[i]);
        }
    }

    printf("\n");

}

int main(void)
{
    stTree *rootNode = createNode();

    insertNode(insertNode(insertNode(insertNode(rootNode, 'c', false), 'a', false), 'r', false), 't', true);
    insertNode(insertNode(insertNode(rootNode, 'c', false), 'a', false), 'r', true);
    insertNode(insertNode(insertNode(rootNode, 'c', false), 'a', false), 't', true);

    char a[] = "ca";
    printf("%c%c->\n", a[0], a[1]);

    stTree *lastNode = treeTraverse(a, rootNode);

    autoComplete(lastNode);

}

Output:
ca->

r]t]

t]

It means, autocompleted words are: car, cart, cat


texts:
This is a console version of the famous Rock Paper Scissors game part of The Odin Project curriculum. Please review this code and provide suggestions. Please comment whether the code is DRY and if it is simplified.

function computerPlay() {
    let choices = ['rock', 'paper', 'scissors'];
    return choices[Math.floor(Math.random() * choices.length)];
}

function playRound(playerSelection, computerSelection) {
    const capitalize = word => { return word.charAt(0).toUpperCase() + word.slice(1); }
    const winStatement = (winner, loser) => { return `You Win! ${capitalize(winner)} beats ${capitalize(loser)}`; }
    const loseStatement = (winner, loser) => { return `You Lose! ${capitalize(winner)} beats ${capitalize(loser)}`; }
    const winningChoice = {'rock': 'paper', 'paper': 'scissors', 'scissors': 'rock'};

    playerSelection = playerSelection.toLowerCase();

    if(playerSelection === computerSelection) return "Oh! It's a tie";
    else if(playerSelection === winningChoice[computerSelection]) return winStatement(playerSelection, computerSelection);
    else return loseStatement(computerSelection, playerSelection);
}

const playerSelection = 'rock';
const computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));


texts:
Do I still need to protect my code against SQL injection when I'm not using variables in SQL queries?

Is this code still vulnerable?:

$result = mysqli_query($connect,"SELECT subsubcat_name FROM subsubcategories WHERE subcat_ID = 4");
while ($row=mysqli_fetch_array($result)){
echo $row['subsubcat_name'];
echo '<br>';
}


texts:
I've been looking into empty abstract classes and from what I have read, they are generally bad practice. I intend to use them as the foundation for a small search application that I am writing. I would write the initial search provider and others would be allowed to create their own providers as well. My code's intent is enforce relationships between the classes for anyone who would like to implement them.

Can someone chime in and describe why or why not this is still a bad practice and what, if any, alternatives are available?

namespace Api.SearchProviders
{
public abstract class ListingSearchResult
{
    public abstract string GetResultsAsJSON();
}

 public abstract class SearchParameters
 {
 }

 public interface IListingSearchProvider
 {
     ListingSearchResult SearchListings(SearchParameters p);
 }
 }


texts:
I'm a beginner at C.
I'm currently implementing atof to build a raytracer, however I'm still learning how to efficiently write programs.
Assignement
Instructions
The program takes a scene description file as argument to generate objects. Some of these paramaters are float. Example of the file.

I'm parsing through the file. As I'm restricted in terms of lines allowed per function and I'm currently learning how double pointers work, I'm using a double char pointer. Example of one such function using lc_atof.
int    a_parsing(char *str, t_pars *data)
{
    if (*(str++) == 'A')
    {
        if (((data->a_ratio = lc_atof(&str)) >= 0.0) && data->a_ratio <= 1.0 && errno == 0)
        //
            if (((data->a_R = lc_atoi(&str)) >= 0) && data->a_R <= 255 && errno == 0)
                if (*(str++) = ',' && ((data->a_G = lc_atoi(&str)) >= 0) && data->a_G <= 255 && errno == 0)
                    if (*(str++) = ',' && ((data->a_B = lc_atoi(&str)) >= 0) && data->a_B <= 255 && errno == 0)
                        return (skip_space(&str));
    }
    return (0);
}

Current code to review:
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#include <float.h>

static float    conversion(char **str)
{
    double    d_nbr;
    double    power;

    d_nbr = 0.0;
    power = 10.0;
    while (isdigit(**str))
    {
        d_nbr = d_nbr * 10.0 + (**str - 48);
        if (d_nbr > FLT_MAX)
        {
            errno = EIO;
            return (-1);
        }
        (*str)++;
    }
    if (**str == '.')
    {
      (*str)++;
      if (isdigit(**str))
      {
        d_nbr = d_nbr * 10.0 + (**str - 48);
        if (d_nbr > FLT_MAX)
        {
            errno = EIO;
            return (-1);
        }
        (*str)++;
        return ((float)(d_nbr / power));
      }
    }
    errno = EIO;
    return (-1);
}

float            lc_atof(char **str)
{
    float    n;
    int        sign;

    n = 0.0;
    sign = 1.0;
    if (!str || !*str)
    {
        errno = EIO;
        return (-1);
    }
    while (isspace(**str))
        (*str)++;
    if (**str == '+' || **str == '-')
    {
        if (**str == '-')
            sign = -1.0;
        (*str)++;
    }
    if (!isdigit(**str))
    {
        errno = EIO;
        return (-1);
    }
    if ((n = conversion(str)) == 0 && errno != 0)
       return (-1);
    return (sign * n);
}

The only tweaks to the actual atof I've made is having a double char pointer as argument and returning -1 in case of errors.
Every input much appreciated.


texts: Replicate / Sync files from source to destination with powershell only

texts:
I have lots of live and disaster recovery servers, which should have the same files and folders. I searched on the web but could not find a Powershell script which has all of the functionality on the same script. So I have created one in the below function.
Please do not use it in Production without fully testing it!!!!!
This script replicates / synchronizes files and folders recursively from source location to destination location with the sync switch.
If you use -Sync $True then the script will remove all of the files and folders on destination location which do not exist in the source location.
Usage:

Sync-Files -SourceRoot "C:\Test" -DestinationRoot "\\Server\Test"
Sync-Files "C:\Test" "\\Server\Test"
Sync-Files -SourceRoot "C:\Test" -DestinationRoot "\\Server\Test" -Sync $true

Source:
    <#
    .Synopsis
    synchronies files between two location
    .DESCRIPTION
    This function is synchronising all files from source location to destination location.
    Script has ability to fully sync files by deleting the destination files if not exists in the source directory.

    if -Sync is set $true script will delete files which exists in the destination directory only.
    Please do not run this script before test in test/dev environment.

    .EXAMPLE
    Sync-Files C:\Test \\SERVER\Test
    .EXAMPLE
    Sync-Files -SourceRoot "C:\Source" -Destination "\\SERVER\DestinationDirectory\

    .EXAMPLE
    Sync-Files -SourceRoot "C:\Source" -Destination "\\SERVER\DestinationDirectory\ -Sync $True
    #>
    function Sync-Files
    {
    [CmdletBinding()]
    Param
    (

    [Parameter(Mandatory=$true,
               ValueFromPipelineByPropertyName=$true,
               Position=0)]
    $SourceRoot,

    [Parameter(Mandatory=$true,
               ValueFromPipelineByPropertyName=$true,
               Position=1)]
    $DestinationRoot,

    [Parameter(
               ValueFromPipelineByPropertyName=$true,
               Position=3)]
    [bool]$Sync

    )
    Begin
    {
    $SourceRootFiles = Get-ChildItem $SourceRoot -Recurse
    $DestinationRootFiles = Get-ChildItem $DestinationRoot -Recurse
    $CompareObjects = Compare-Object -ReferenceObject $SourceRootFiles -DifferenceObject $DestinationRootFiles -ErrorAction SilentlyContinue -IncludeEqual

    }
    Process
    {
    ForEach($CompareObject in $CompareObjects){

        $FinalPath = Join-Path $DestinationRoot $CompareObject.InputObject.FullName.Substring($SourceRoot.length)

        if($CompareObject.SideIndicator -eq "<="){

            if($CompareObject.InputObject.PSIsContainer){
                Copy-Item -Path $CompareObject.InputObject.FullName -Destination $FinalPath -Force
            }

            Elseif(!(Test-Path $FinalPath)){

                Copy-Item -Path $CompareObject.InputObject.FullName -Destination $FinalPath -Force

            }

        }

        if($CompareObject.SideIndicator -eq "=="){

            if((Get-FileHash $CompareObject.InputObject.FullName).Hash -ne (Get-FileHash $FinalPath).Hash){

                Copy-Item $CompareObject.InputObject.FullName $FinalPath -Force
            }

        }

        if($CompareObject.SideIndicator -eq "=>"){
            if($Sync -eq $true){
                if(Test-Path $CompareObject.InputObject.FullName){
                    Remove-Item $CompareObject.InputObject.FullName -Force -Recurse -Verbose
                }
            }

        }

    }
    }
    End
    {

    }
    }

    Sync-Files -SourceRoot "C:\Test" -DestinationRoot "\\Server\Test" -Sync $true


texts:
This is just a very simple version of the Game of Life made in Java. Please let me know how I could have improved this. I am also hoping for some feedback on how the formatting and conventions are because I would like my code to be readable and neat.

public class GameOfLife
{
    private boolean[][] board;
    private int maxRow, maxCol;

    public GameOfLife(boolean[][] board)
    {
        if(board != null)
            this.board = board;
        else
            this.board = new boolean[1][1];

        this.maxRow = this.board.length;
        this.maxCol = this.board[0].length;
    }

    public void calculateNextGeneration()
    {
        boolean[][] nextBoard = new boolean[maxRow][maxCol];

        for(int row = 0; row < maxRow; row++)
        {
            for(int col = 0; col < maxCol; col++)
            {
                nextBoard[row][col] = nextState(row, col);
            }
        }

        board = nextBoard;
    }

    public void print()
    {
        for(int row = 0; row < maxRow; row++)
        {
            for(int col = 0; col < maxCol; col++)
            {
                if(isAlive(row, col))
                    System.out.print("*");
                else
                    System.out.print(".");
            }
            System.out.println();
        }
    }

    public void setAlive(int row, int col, boolean isAlive)
    {
        if(inBounds(row, col))
            board[row][col] = isAlive;
    }

    public boolean isAlive(int row, int col)
    {
        if(inBounds(row, col))
            return board[row][col];
        else
            return false;
    }

    private boolean nextState(int rowPos, int colPos)
    {
        int alive = 0;

        for(int row = rowPos - 1; row <= rowPos + 1; row++)
        {
            for(int col = colPos - 1; col <= colPos + 1; col++)
            {
                if(!inBounds(row, col) || (row == rowPos && col == colPos))
                    continue;

                if(isAlive(row, col))
                    alive++;
            }
        }

        if(alive == 3)
            return true;
        else if(isAlive(rowPos, colPos) && alive == 2)
            return true;
        else
            return false;
    }

    private boolean inBounds(int row, int col)
    {
        if(row < 0 || row >= maxRow || col < 0 || col >= maxCol)
            return false;
        else
            return true;
    }
}


texts:
I have implemented a kind of thing that does event triggering in Golang. This is open-sourced here. Review and suggestions appreciated.

First thing I am trying to implement is adding event listeners to a trigger:

func (t *trigger) On(event string, task interface{}) error {
    if _, ok := t.functionMap[event]; ok {
        return errors.New("event already defined")
    }
    if reflect.ValueOf(task).Type().Kind() != reflect.Func {
        return errors.New("task is not a function")
    }
    t.mu.Lock()
    defer t.mu.Unlock()
    t.functionMap[event] = task
    return nil
 }

So that when Fire is called all the handler chain will be executed:

func (t *trigger) Fire(event string, params ...interface{}) ([]reflect.Value, error) {
    f, in, err := t.read(event, params...)
    if err != nil {
        return nil, err
    }
    result := f.Call(in)
    return result, nil
 }

But the thing is that don't want to maintain a whole param array for all the handlers' method parameters. How can it be done otherwise?


texts:
Write a function that a receives file name of a txt file, which contains unknown number of words of max length 10 each. Print the word with the most occurrences. Assume the input is correct and contains at least one word.

Code

#define MAX_CHARS 11

int mostFrequentWord(char* filename) {
  char ch;
  int i, j, k, occurrence, counter = 1, maximum = 0;
  char *index_max = NULL;
  char **arr;
  FILE *file = fopen(filename, "r");
  while((ch = fgetc(file)) != EOF) {
    if(ch == ' ') {
        counter++;
    }
  }
  rewind(file);
  arr = (char**) calloc(counter, sizeof(char*));
  for (k = 0; k < counter; k++) {
    arr[k] = (char*) calloc(MAX_CHARS, sizeof(char));
  }
  while ((ch = fgetc(file)) != EOF) {
    if (ch == ' '){
        i++;
        j = 0;
    } else {
        arr[i][j] = ch;
        j++;
    }
  }
  for (i= 0; i < counter; i++) {
    occurrence = 0;
    for (j = i; j < counter; j++) {
        if (!strcmp(*(arr + i), *(arr + j))){
            occurrence++;
        }
    }
    if (occurrence > maximum) {
        maximum = occurrence;
        index_max = *(arr+i);
    }
  }
  if (index_max != NULL){
    printf("The most frequent word is \"%s\" with %d occurrences.\n", index_max, maximum);
  }
  for ( i = 0; i < counter; i++ ) {
    free(arr[i]);
  }
  free(arr);
  return 0;
}

Example

Input (test.txt):

test one two test three test

Output:

The most frequent word is "test" with 3 occurrences.

One thing I think I'm missing (and not sure what's the way to do it) is to check the success of calling functions that use system resources.

Any review is appreciated.


texts: Tampermonkey script to check and replace youtube's subscriptions to show all videos

texts:
Just wanted a general review of the code to make sure I'm doing it properly/efficently. New to JS and don't use RegEx too often.
// ==UserScript==
// @name         Youtube Subscriptions Redirect
// @namespace    https://github.com/spacegIider
// @version      1.0
// @license      MIT
// @description  Shows all subscribed videos in subscription feed.
// @author       Spaceglider
// @match        *://www.youtube.com/feed/subscriptions
// @grant        none
// @homepageURL  https://github.com/spacegIider/Youtube-Subscriptions-Redirect
// @supportURL   https://github.com/spacegIider/Youtube-Subscriptions-Redirect/issues
// @downloadURL  https://raw.githubusercontent.com/spacegIider/Youtube-Subscriptions-Redirect/redirect.js
// @updateURL    https://raw.githubusercontent.com/spacegIider/Youtube-Subscriptions-Redirect/redirect.js
// ==/UserScript==

var BadDumbYoutubeURL = window.location.pathname;

if ( ! /\?flow=1$/.test (BadDumbYoutubeURL) ) {
    var ActuallySeeAllVideosURL = window.location.protocol + "//"
                                + window.location.host
                                + BadDumbYoutubeURL + "?flow=1"
                                +window.location.search
                                +window.location.hash
                                ;

    window.location.replace (ActuallySeeAllVideosURL);
}


texts:
3 elements forms arithmetic sequence, when difference between any two consecutives of them is the same.

In our task we are given array A. Any pair of integers in this array is called slice (eg. (B,C)), when 0 <= B < C< N, where N is an array length (0<=N<=60).

A slice (B,C) is called arithmetic, when the sequence:
A[B],A[B+1],...,A[C-1],A[C] is arithmetic and B+1 < C.

My method should return the number of arithmetic slices in array.
Time complexity should be linear. When result exceeds 1000000000 method should return -1.
Is my solution correct?

public int computeNumberOfArithmeticSlices(int[] A) {
    int front = 0, total = 0;
    int result = 0;
    List list;
    for (int back = 0; back < A.length && front < A.length; ) {
        list = new ArrayList();
        front = back + 2;
        total = A[front - 1] - A[back];
        list.add(back);
        list.add(front - 1);
        int i = 0;
        boolean ok = false;
        while (front < A.length && A[front] - A[front - 1] == total) {
            ok = true;
            i++;
            list.add(front);
            back = front;
            front++;
            result += i;
            if (result > 1000000000)
                return -1;
        }
        if (!ok)
            back++;
    }
    return result;
}


texts:
I'm receiving an language string out of an PHP file which returns an array like this:

DIR_LANG\en\home.php:

return array(

    'welcome_string'    => 'welcome @ home! '

);

And my Lang class:

<?php

class Lang
{

    private static $langArray = array();
    private static $lang = DEFAULT_LANG;

    public static function get($langString)
    {
        if (isset(self::$langArray[self::$lang]) && isset(self::$langArray[self::$lang][$langString])) {
            return self::$langArray[self::$lang][$langString];
        } else {
            $langUsed = self::$lang;
            self::receiveLang($langString);

            if (!isset(self::$langArray[$langUsed][$langString])) {
                if ($langUsed != DEFAULT_LANG) {
                    $langUsed = DEFAULT_LANG;
                    self::receiveLanguage($langString, DEFAULT_LANG);
                } else {
                    $langUsed = FALLBACK_LANG;
                    self::receiveLanguage($langString, FALLBACK_LANG);
                }
            }
            return (isset(self::$langArray[$langUsed][$langString]) ? self::$langArray[$langUsed][$langString] : $langString);
        }
    }

    private static function receiveLang($langString)
    {
        $langStringExp = explode('.', $langString);
        $usedLang = self::$lang;
        $langFile = DIR_LANG . $usedLang . '/' . $langStringExp[0] . '.php';

        if (!file_exists($langFile)) {
            $usedLang = ($usedLang != DEFAULT_LANG) ? DEFAULT_LANG : FALLBACK_LANG;
            $langFile = DIR_LANG . $usedLang . '/' . $langStringExp[0] . '.php';

            if (!file_exists($langFile)) {
                return;
            }
        }
        $langFileContents = require_once $langFile;

        foreach ($langFileContents as $key => $value) {
            self::$langArray[$usedLang][$langStringExp[0] . '.' . $key] = $value;
        }
    }

    private static function receiveLanguage($langString, $language)
    {
        $langStringExp = explode('.', $langString);
        $langFile = DIR_LANG . $language . '/' . $langStringExp[0] . '.php';

        if (!file_exists($langFile)) {
            return;
        }

        $langFileContents = require_once $langFile;

        foreach ($langFileContents as $key => $value) {
            self::$langArray[$language][$langStringExp[0] . '.' . $key] = $value;
        }
    }

    public static function setLang($newLang)
    {
        self::$lang = $newLang;
    }
}

And somewhere in my view, I receive the language like this:

echo Lang::get('home.welcome_string');

The constants are defined in an config.php. Here's an stripdown of it:

define('DIR_LANG', 'app/language/');
define('DEFAULT_LANG', 'nl');
define('FALLBACK_LANG', 'en');

Although this do work, it feels a bit bloated. What could I do to improve this, or is this the best way (I can't believe it)


texts: Stack implementation in C++ using linked list

texts:
I am learning C++ and I made a simple stack class using a (reversed) linked-list to test my knowledge.

Are there any problems with the following code, or any suggestions to improve it?

I want to make sure I am getting things correct in the beginning so I don't make the same mistakes again in the future - especially memory management and avoiding leaks.

One thing to point out is that I included the implementation in the header file... I wouldn't normally do this but apparently there are problems when implementing methods with templates in .cpp files.

#ifndef TEST_STACK_H
#define TEST_STACK_H

#include <stdexcept>

template <class T>
class stack {

    struct node {
        T data;
        node* previous;

        node(T data, node *previous) : data(data), previous(previous) {}
    };

    node* head = nullptr;

    int size = 0;
    int max = -1; // -1 so isFull() == false when default constructor used

public:
    stack() = default;

    stack(int max) {
        if (max <= 0) throw std::out_of_range("stack size must be > 0");
        this->max = max;
    }

    ~stack() {
        node* n = head;

        while (n != nullptr) {
            node* previous = n->previous;
            delete n;

            n = previous;
        }
    }

    void push(const T &object) {
        if (isFull()) throw std::overflow_error("cannot push to a full stack");

        head = new node(object, head);
        ++size;
    }

    T pop() {
        if (head == nullptr) throw std::underflow_error("cannot get item from empty stack");

        T item = head->data;
        head = head->previous;

        --size;

        delete head;
        return item;
    }

    T peek() {
        if (head == nullptr) throw std::underflow_error("cannot get item from empty stack");
        return head->data;
    }

    int getSize() {
        return size;
    }

    bool isFull() {
        return size == max;
    }

    bool isEmpty() {
        return head == nullptr;
    }
};

#endif


texts: Extract subarray of elements that appear after the last occurrence of "4"

texts:
I am doing some challenges, and in one challenge given a non-empty array of int, I am to return a new array containing the elements from the original array that come after the last 4 in the original array. The original array will contain at least one 4.

E.g:

  post4([2, 4, 1, 2]) → [1, 2]
  post4([4, 1, 4, 2]) → [2]
  post4([4, 4, 1, 2, 3]) → [1, 2, 3]

As such, I have written code that works but it is far too complicated and unprofessional, at least it feels this way.

public static int[] post4(int[] nums) {

    int startPoint = nums.length - 1;
    int[] newArray;
    int amtOfElements = 0;
    int stopIndex = 0;

    for (int i = startPoint; i >= 0; i--) {

        if (nums[i] == 4) {
            stopIndex = i;
            i = 0;
        } else {
            amtOfElements++;
        }
    }

    newArray = new int[amtOfElements];

    for (int i = 0, j = stopIndex; i < amtOfElements; i++, j++) {
        newArray[i] = nums[j + 1];
    }

    return newArray;
}

As such, this looks nasty to me.
How can I shorten this to a single for-loop?


texts:
This code is meant to do a binary search of a sorted list containing integers.

I'm doing this to improve my style and to improve my knowledge of fundamental algorithms/data structures for an upcoming coding interview.

def bin_search(a, item):
    first = 0
    last = len(a) - 1
    found = False

    while first <= last and not found:
        mid = (first + last) // 2
        if a[mid] == item:
            found = True
        else:
            if item < a[mid]:
                last = mid - 1
            else:
                first = mid + 1

    return found


texts: Extracting watermark from a video using Python

texts:
I'm extracting a few frames from a video:

Comparing the similarity or equality of pixel color (from first two images)
Saving to a new image
Comparing the new image (conjunction of first two images) and the next image, etc.

Can you review my codes for efficiency and best coding practices?

Code

import sys
import os
import numpy as np
from PIL import Image, ImageDraw

def main(obr1,obr2):
    img1= Image.open("%s" %(obr1))
    img2= Image.open("%s" %(obr2))
    im1 = img1.convert("RGBA")
    im2 = img2.convert("RGBA")
    pix1 = im1.load()
    pix2 = im2.load()
    im = Image.new("RGBA", (im1.width, im1.height), (0, 0, 0, 0))
    draw = ImageDraw.Draw(im)
    x = 0
    y = 0
    while y != im1.height-1 or x != im1.width-1:
        if pix1[x,y] == pix2[x,y]:
            draw.point((x,y),fill=pix1[x,y])
        else:
            p1 = np.array([(pix1[x,y][0]),(pix1[x,y][1]),(pix1[x,y][2])])
            p2 = np.array([(pix2[x,y][0]),(pix1[x,y][1]),(pix1[x,y][2])])
            squared_dist = np.sum(p1**2 + p2**2, axis=0)
            dist = np.sqrt(squared_dist)
            if dist < 200 and pix1[x,y] !=(0,0,0,0) and pix2[x,y] != (0,0,0,0):
                color = (round(pix1[x,y][0]+pix2[x,y][0]/2), round(pix1[x,y][1]+pix2[x,y][1]/2), round(pix1[x,y][2]+pix2[x,y][2]/2), round(pix1[x,y][3]+pix2[x,y][3]/2))
                #color=pix1[x,y]
                draw.point((x,y),fill=color)
            else:
                draw.point((x,y),fill=(0,0,0,0))
        if x == im1.width-1:
            x=0
            y=y+1
        else:
            x=x+1
    im.save('test%s.png' %(z), 'PNG')
    print("Zapisano obraz test%s.png" %(z))

imglist = sys.argv[1:]
z=0
while imglist != []:
    exists = os.path.isfile("./test%s.png" % (z-1))
    if exists:
        obr1="test%s.png" % (z-1)
        obr2=imglist.pop()
        print("Porównywanie obraza %s i %s" % (obr1,obr2))
        main(obr1,obr2)
        print("Analiza skończona")
        z=z+1
    else:
        obr1=imglist.pop()
        obr2=imglist.pop()
        print("Porównywanie obraza %s i %s" % (obr1,obr2))
        main(obr1,obr2)
        print("Analiza skończona")
        z=z+1


texts:
I have time-series data (t) that I want to loop through each t and take the difference of the previous five lags t-1 ... t-5.

This code works, but is inefficient. I'm not sure how to increase the performance and efficiency of the code.

Sample data

import pandas as pd
import numpy.random as nr

dat = pd.DataFrame({'t': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'rnum': nr.rand(10)})

Function

def diff_n(idat):
    # Get t from group
    i = idat['t'].iat[0]

    # If one, nothing to difference
    if i == 1:
        return None

    # Get value to loop through and diff
    h1 = idat.groupby('t')['rnum'].mean().values

    # Subset dat (outside fn)
    h2 = dat[(dat.t < i ) & (dat.t >= i - 5)]

    # Combine data for return
    retdat = pd.DataFrame()

    # Loop through t-1 to last obs
    for j in range(max(h2.t), min(h2.t), -1):

        # Get value to difference from h1
        h3 = h2[h2.t == j].groupby('t')['rnum'].mean().values

        # Difference
        ndiff = (h3 - h1)

        # Build df and concat
        indat = pd.DataFrame({'t': [i], 'lag': i - j, 'diff': ndiff})
        retdat = pd.concat([retdat, indat])
    return retdat

Groupby and apply the function to each t

dat.groupby('t').apply(lambda x: diff_n(x))

Output

>>> dat.groupby('t').apply(lambda x: diff_n(x))
      t  lag      diff
t
2  0   2    1  0.440644
3  0   3    1 -0.284075
   0   3    2  0.156569
4  0   4    1  0.439154
   0   4    2  0.155079
   0   4    3  0.595723
5  0   5    1 -0.095552
   0   5    2  0.343602
   0   5    3  0.059527
   0   5    4  0.500171
6  0   6    1  0.296337
   0   6    2  0.200784
   0   6    3  0.639939
   0   6    4  0.355864
   0   6    5  0.796507
7  0   7    1 -0.749913
   0   7    2 -0.453576
   0   7    3 -0.549128
   0   7    4 -0.109974
   0   7    5 -0.394049
8  0   8    1  0.506379
   0   8    2 -0.243534
   0   8    3  0.052803
   0   8    4 -0.042749
   0   8    5  0.396405
9  0   9    1 -0.021761
   0   9    2  0.484618
   0   9    3 -0.265295
   0   9    4  0.031042
   0   9    5 -0.064510
10 0  10    1  0.409118
   0  10    2  0.387357
   0  10    3  0.893736
   0  10    4  0.143823
   0  10    5  0.440160


texts:
I am using JPA for my database work and I need to create a database entity superclass which all of my table entities will extend.

Every database entity will have a primary key named id (which in some cases is an int and in some a String) and also a lastUpdate field which stores the time at which the database row was last updated (set from within the code).

DatabaseEntity superclass:

import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
public class DatabaseEntity <T> {
    @Id
    @Basic(optional = false)
    @Column(name = "id")
    private T _id;

    @Basic(optional = false)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "last_update")
    private Date _lastUpdate;

    public T getId() {
        return _id;
    }

    public void setId(T id) {
        _id = id;
    }

    public Date getLastUpdate() {
        return _lastUpdate;
    }

    public void setLastUpdate() {
        _lastUpdate = new Date();
    }
}

Anything that I am doing wrong or that I should add in the superclass?


texts: Multiple jQuery statements in one function

texts:
I've been working with jQuery for a few days now and starting to get the hang of it (it does the thing that I want to do).

I've made an accordion, and the header of each accordion item has an arrow that points up (for being open) or down (for being closed). This code works fine, does what it has to do. When I wrote it, it felt very ugly.

When I press a header of an item in the accordion, function gets called like this:

The function itself:

function leftActive(e, b) {
  $('.active').removeClass('active');
  $('.relative').eq(e).addClass('active');

  $('.arrowUp').addClass('arrowDown');
  $('.arrowUp').removeClass('arrowUp');
  $('.arrowDown', b).addClass('arrowUp');
  $('.arrowDown', b).removeClass('arrowDown');
}

HTML structure:

 Transport logistics

      <?php require 'templates/dummyBedrijven.php'; ?>

 Real Estate

      <?php require 'templates/dummyBedrijven.php'; ?>

 Salt trade Winter Maintenance

      <?php require 'templates/dummyBedrijven.php'; ?>

 Human Resources Solutions

      <?php require 'templates/dummyBedrijven.php'; ?>


texts: Split string by substring without using String.Split()

texts:
The Aim

Since I very rarely write code to do things other than business logic anymore I've set myself a challenge:

Split a string into a list of substrings by splitting on a matching string, without using string.Split() or similar methods of string (substring, indexof, etc) or LINQ methods (edit or regex /edit).

The method must also accept a parameter stating whether the return list is allowed to contain empty strings (only excludes string.Empty, not whitespace).

The Code

private static IList<string> SplitString(string toSplit, string splitOn, bool allowEmptyResults = true)
{
    int cursorPosition = 0;
    int innerCursor = 0;
    var strings = new List<string>();

    while (cursorPosition < toSplit.Length)
    {
        bool match = false;

        for (int i = 0; i < splitOn.Length ; i++)
        {
            match = toSplit[innerCursor] == splitOn[i];

            if ((i < splitOn.Length - 1 && innerCursor == toSplit.Length - 1) || !match)
            {
                match = false;
                break;
            }

            innerCursor++;
        }

        if (match)
        {
            var result = StringFromCursor(toSplit, cursorPosition, innerCursor - splitOn.Length);

            if (result != string.Empty || allowEmptyResults)
            {
                strings.Add(result);
            }

            cursorPosition = innerCursor;
        }
        else
        {
            if (innerCursor < toSplit.Length - 1)
            {
                innerCursor++;
            }
            else
            {
                var result = StringFromCursor(toSplit, cursorPosition, toSplit.Length);

                if (result != string.Empty || allowEmptyResults)
                {
                    strings.Add(result);
                }

                break;
            }
        }
    }

    return strings;
}

private static string StringFromCursor(string toSplit, int cursorPosition, int matchStart)
{
    string result = string.Empty;

    for (int i = cursorPosition; i < matchStart; i++)
    {
        result += toSplit[i].ToString();
    }

    return result;
}

The Problem

This seems hopelessly complicated and prone to "off by 1" errors, I'm more interested in the cleaner logic for accomplishing this task rather than making it cleaner by refactoring into smaller methods.

Also I'm not too concerned about style (inconsistent use of var for example).

The code spends a large number of characters trying to deal with tricky behaviour at the end of a string but seems to work for the following test cases:

var result = SplitString("thetgonceupon the time there was a thing there", "the");
var result = SplitString("thetgonceupon the time there was a thing thereth", "the");
var result = SplitString("thetgonceupon the time there was a thing therethe", "the");


texts:
My application's structure looks like this:

Solution: MySolution

Projects in MySolution: Host, Business, Server.

References between the projects looks like this:

Host <-- Business --> Server

(Business references Host and Server but Host does not reference Server and vice versa because this causes a circular-)

So, I have some Database stuff in Server. I have a property, DBConnectionString - which should contain the connection string. What I want to do is to set this property from the Host but I want to keep all methods that have anything to do with the database in the Server project.

Keeping interfaces in mind - so that I can also at a later stage just create an web application.

I have some code and it's working but I don't know if this is the right way.

I have this interface in Library (connection between the other two projects):

    public interface IDBUtils
    {
        string DBConnectionString { get; set; }

        bool OpenConnection();

        bool CloseConnection();

        bool ExecuteSQL(string sql);

        bool CreateDatabase(string servername, string databaseName, string databaseDataPath);

        bool CreateDatabaseUser(string servername, string username, string password);
    }

Then the class in Library that has the code for the interface:

public string DBConnectionString
{
    get
    {
        return DBService.DB.DBUtils.DBConnectionString;
    }
    set
    {
        DBService.DB.DBUtils.DBConnectionString = value;
    }
}

public bool OpenConnection()
{
    return DBService.DB.DBUtils.OpenConnection();
}

public bool CloseConnection()
{
    return DBService.DB.DBUtils.CloseConnection();
}

public bool ExecuteSQL(string sql)
{
    return DBService.DB.DBUtils.ExecuteSQL(sql);
}

public bool CreateDatabase(string servername, string databaseName, string databaseDataPath)
{
    return DBService.DB.DBUtils.CreateDatabase(servername, databaseName, databaseDataPath);
}

public bool CreateDatabaseUser(string servername, string username, string password)
{
    return DBService.DB.DBUtils.CreateDatabaseUser(servername, username, password);
}

I'm only going to show the property and one method on the server otherwise this is going to get too long.

On the Server:
Property:

public static string DBConnectionString { get; set; }

The OpenCOnnection() Method:

        public static bool OpenConnection()
        {
            bool success = false;
            try
            {
                if (DBConnectionString.Length > 0)
                {
                    conn = new SqlConnection(DBConnectionString);
                    conn.Open();
                    success = true;
                }
            }
            catch { /* Do nothing... */ }
            return success;
        }

To set the property from Host on Server:

It uses the interface on Library:

iDBUtils.DBConnectionString = connectionString.ToString();

To execute a method from Host on Server:

iDBUtils.OpenConnection();

So as you can see, Library is the "Middle Man".


texts:
I'm trying to use Moq to mock a rather large set of interfaces in an object. I'm trying to capture the behavior of retaining a dirty flag when properties are set and I'm hoping there is a cleaner way to do this because I have many properties that need this setup.

    public static void SetupDirtyProperty<T, TProp>(this Mock<T> mock, Expression<Func<T, TProp>> getterExpression, Action<T> setterExpression, ref bool isDirty)
    {
        TProp p = default(TProp);

        mock.SetupGet(getterExpression).Returns(() => p);
        mock.SetupSet(setterExpression).Callback((TProp value) =>
        {
            if (p != value)
            {
                p = value;
                isDirty = true;
            }
        });
    }

and to use it it's called like this:

        bool isDirty = false;
        var product = new Mock<IProduct>();

        product.As<ISku>().SetupDirtyProperty(x => x.Price, x => x.Price= It.IsAny<decimal?>(), () => isDirty = true);

The things I would like to simplify about this approach are:

I have to specify a property getter and setter, but it seems like I should be able to invert the property getter expression into a setter with It.IsAny<TProp> that will work correctly with Moq.
I have to specify the closure around the isDirty flag every time.

It'd be nice if I could set this up in a way that is easy to apply this to dozens of properties, and it'd be really nice if it was something like SetupAllProperties where it would just handle all the properties automatically.


texts:
Not really an issue I am stuck on (the code works) but I just really don't like some code I wrote, if you're bored in lockdown maybe you might like to help.

Context:
I am import some data from a spreadsheet, it contains data about retail stores (grocery stores). As the data comes in from the spreadsheet, each row is stored as a StoreData object. Each store has upto five tills (point of sale devices) and I want the StoreData class to be able to return an array of information about each till. Here is the class showing the code relevant to the tills (the class is much bigger).

How can I clean up the function getTills()?

class StoreData
{
    private $spreadsheetData;

    private $tillModel;
    private $tillVersion;
    private $tillOneName;
    private $tillOneIpAddress;
    private $tillTwoName;
    private $tillTwoIpAddress;
    private $tillThreeName;
    private $tillThreeIpAddress;
    private $tillFourName;
    private $tillFourIpAddress;
    private $tillFiveName;
    private $tillFiveIpAddress;

    public function __construct($spreadsheetData, String $storeStatus)
    {
        $this->spreadsheetData = $spreadsheetData;
        $this->setStoreProperties();
    }

    private function setStoreProperties()
    {
        $this->tillModel = $this->spreadsheetData[17];
        $this->tillVersion = $this->spreadsheetData[7];
        $this->tillOneName = $this->spreadsheetData[40];
        $this->tillOneIpAddress = $this->spreadsheetData[41];
        $this->tillTwoName = $this->spreadsheetData[42];
        $this->tillTwoIpAddress = $this->spreadsheetData[43];
        $this->tillThreeName = $this->spreadsheetData[44];
        $this->tillThreeIpAddress = $this->spreadsheetData[45];
        $this->tillFourName = $this->spreadsheetData[46];
        $this->tillFourIpAddress = $this->spreadsheetData[47];
        $this->tillFiveName = $this->spreadsheetData[48];
        $this->tillFiveIpAddress = $this->spreadsheetData[49];
    }

    public function getTills()
    {
        $tillList = [];

        if ($this->tillOneName !== null)
        {
            $tillList[] = [
                'model' => $this->tillModel,
                'name' => $this->tillOneName,
                'ip_address' => $this->tillOneIpAddress,
                'version' => $this->tillVersion,
            ];
        }
        if ($this->tillTwoName !== null)
        {
            $tillList[] = [
                'model' => $this->tillModel,
                'name' => $this->tillTwoName,
                'ip_address' => $this->tillTwoIpAddress,
                'version' => $this->tillVersion,
            ];
        }
        if ($this->tillThreeName !== null)
        {
            $tillList[] = [
                'model' => $this->tillModel,
                'name' => $this->tillThreeName,
                'ip_address' => $this->tillThreeIpAddress,
                'version' => $this->tillVersion,
            ];
        }
        if ($this->tillFourName !== null)
        {
            $tillList[] = [
                'model' => $this->tillModel,
                'name' => $this->tillFourName,
                'ip_address' => $this->tillFourIpAddress,
                'version' => $this->tillVersion,
            ];
        }
        if ($this->tillFiveName !== null)
        {
            $tillList[] = [
                'model' => $this->tillModel,
                'name' => $this->tillFiveName,
                'ip_address' => $this->tillFiveIpAddress,
                'version' => $this->tillVersion,
            ];
        }
        return $tillList;
    }
}

For info, this is used to populate an eloquent model on a controller:

           foreach($storeData->getTills() as $till)
            {
                $store->tills()->create($till);
            }


texts:
I created a program to find the largest prime factor for a given number. The program works but unfortunately takes very long time to compute a huge number like 600851475143.

How can I optimise this program to run faster?

I don't know what does this multicore thing is, but I think it is a possible way to improve this program.

// A program to find the largest prime factor for a given number

#include <iostream>
#include <math.h>

using namespace std;

bool IsPrime (int n) {
   if (n < 2)      return false;
   if (n < 4)      return true;
   if (n % 2 == 0) return false;

   for (int i = 3; i <= int(sqrt(n)) + 1; i += 2)
       if (n % i == 0)
               return false;
   return true;
}

int main () {

    long long x;
    int lpf = 0; //Largest Prime Factor

    cin >> x;

    for (int n = 0; n <= x; n++)
        if (IsPrime(n) && x % n == 0)
            lpf = n;

    cout << lpf;
}


texts:
To practice my JavaScript for future employment, I've decided to take up the challenge of writing a javascript sudoku verifier. This code only verify's one of the nine 3x3 blocks there are. I would like feedback on this portion of the code, so I can continue my development with more knowledge and more efficient code. Also, any feedback on my HTML/CSS is warmly welcome. I'm using a fullscreen chrome browser for development, so the #middle centers the box on my screen, but it might not on yours.

You will have to click on full page -> to view the CSS correctly.

function checkAnswer() {

 //reset each time button is clicked
 document.getElementById('correct').style.display = 'none';
 document.getElementById('incorrect').style.display = 'none';

 //add each input into 2D array
 let first_row = document.getElementsByClassName('row1');
 let second_row = document.getElementsByClassName('row2');
 let third_row = document.getElementsByClassName('row3');
 let sudoku = [
  [first_row[0].value, first_row[1].value, first_row[2].value],
  [second_row[0].value, second_row[1].value, second_row[2].value],
  [third_row[0].value, third_row[1].value, third_row[2].value]
 ]

 //check if each number is unique in the 2D array
 for (let i = 0; i < sudoku.length; i++) {
  for (let j = 0; j < sudoku[i].length; j++) {
   if(!isUnique(sudoku[i][j], sudoku)) {
    document.getElementById('incorrect').style.display = 'block';
    return;
   }
  }
 }
 document.getElementById('correct').style.display = 'block';
}

function isUnique(num, arr) {
 let count = 0;
 //check entire array
 for(let i = 0; i < arr.length; i++) {
  for(let j = 0; j < arr[i].length; j++) {
   if(arr[i][j] == num) {
    count++;
   }
  }
 }
 return count == 1;
}
body {
 background-color: pink;
}
input {
 width: 50px;
 height: 50px;
 font-size: 20px;
 text-align: center;
}
button {
 width: 100px;
 height: 50px;
 font-size: 15px;
 margin-left: 40px;
}

#middle {
 margin-left: 900px;
 margin-top: 300px;
}
<!DOCTYPE html>

  <meta charset='UTF-8'>
  <title>Sudoku</title>
  <link rel="stylesheet" type="text/css" href="style.css">

     <input type="text" class="row1" maxlength="1" value="3">
     <input type="text" class="row1" maxlength="1">
     <input type="text" class="row1" maxlength="1">

     <input type="text" class="row2" maxlength="1">
     <input type="text" class="row2" maxlength="1" value="2">
     <input type="text" class="row2" maxlength="1">

     <input type="text" class="row3" maxlength="1" value="7">
     <input type="text" class="row3" maxlength="1">
     <input type="text" class="row3" maxlength="1">

   <button type="button" onclick="checkAnswer()">Check</button>

Incorrect Entry!

Correct Entry!


texts:
I am working on a Java project for college that involves us setting up a TCP Server and Client. I have that part working and now to add more of a feel to my project I want to add a GUI.

We have not begun learning about GUI's in Java yet. However I want to try as I think it would be a useful exercise. I have a very basic GUI set up and the appropriate ActionListener set for the button. My next problem is positioning my panels so they look neat and tidy on the Frame...

At the moment I have all the components in one panel as seen below:

public ClientGUI(){

    //Initialise Frame
    frame = new JFrame("TCP Client");

    //Initialise Panel 1 & Components
    p1 = new JPanel();

    //Set Layout
    p1.setLayout(new GridLayout(1,2));

    //Label 1 - For TextArea
    l1 = new JLabel("Chat Log");
    p1.add(l1);

    //TextArea - To display conversation
    t1 = new JTextArea(10,10);
    p1.add(t1);

    //Label 2 - For TextField
    l2 = new JLabel("Message");
    p1.add(l2);

    //Message Box - For user input
    t2 = new JTextField(10);
    p1.add(t2);

    //Button 1 - To send message
    b1 = new JButton("Send");
    p1.add(b1);

    //Add panels to frame
    frame.add(p1);

    //Frame properties...
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400,400);
    frame.setVisible(true);

    //Add Event listener to button
    b1.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ev){
            //do something
            t1.setText(t2.getText());
        }
    });

I have a wireframe drawn up of what I'd like it to look like but unfortunately I cannot upload as my reputation is not high enough. Basically something like this...

Label on top of a TextArea.
Label and TextField below.
Button below.

I'd appreciate any feedback anyone might have! Thanks very much.


texts:
Problem
I'm trying to get into Python and get a bit familiar with it, so I found a problem online to train. The problem was to find the shortest path around some points, given a set of nodes which constitute the path and a set of points it must go around
I took the problem from here, but it's all in Czech so I don't know to what extent this will be helpful: https://kasiopea.matfyz.cz/soutez/F/
Algorithm
Since the providen set of edges isn't too large (<300) I iterate through all edges and check if all points are on just one side of the edge (since the shape must obviously be convex). Once I found all the edges I would run them against the Floyd Warshall algorithm to find out the shortest path length from one start node to itself.
Code
from itertools import combinations
from math import sqrt

INF = float("inf")

def floyd_warshall(graph):
    N = len(graph)
    dist = [[col for col in row] for row in graph]
    for k in range(N):
        for i in range(N):
            for j in range(N):
                dist[i][j] = min(dist[i][k] + dist[k][j], dist[i][j])
    return dist

def vector(u, w):
    return (w[0] - u[0], w[1] - u[1])

with open("input.txt") as f:
    T = int(f.readline())
    for _ in range(T):
        N = int(f.readline())
        M = int(f.readline())

        hedges = []
        bombs = []

        for _ in range(N):
            p = f.readline().split()
            x, y = int(p[0]), int(p[1])
            hedges.append((x, y))

        for _ in range(M):
            p = f.readline().split()
            x, y = int(p[0]), int(p[1])
            bombs.append((x, y))

        graph = [[INF] * len(hedges) for i in range(len(hedges))]
        for (ui, u), (wi, w) in combinations(enumerate(hedges), 2):
            edge = vector(u, w)
            side = None
            for bomb in bombs:
                point = vector(u, bomb)
                cross = edge[0]*point[1] - edge[1]*point[0]
                if cross == 0:
                    break
                if side == None:
                    side = cross > 0
                elif side != (cross > 0):
                    break
            else:
                if side != None:
                    dist = sqrt(edge[0]**2 + edge[1]**2)
                    if side:
                        graph[ui][wi] = dist
                    else:
                        graph[wi][ui] = dist

        solved = floyd_warshall(graph)
        cir = INF
        for i in range(len(hedges)):
            cir = min(solved[i][i], cir)

        if cir == INF:
            print(-1)
        else:
            print(cir)

Please don't mind the naming, the problem was presented a bit differently so I used the names for that instead.
Example input
1
4
1
1 1
4 1
4 4
1 4
2 2

Example output
10.24264068711928

I was wondering if there could be a faster solution for this problem and given the fact I'm coming from Java, if there are any things that could be more "pythonic", things I should avoid or stuff that could generally be better. Also I want to point out my solution is working, I'm just wondering if there's a better way to do it.


texts: Changing height of an UI panel using Array content

texts:
I've created following code which works just fine:

GraphBar1.GetComponent<RectTransform> ().sizeDelta = new Vector2 (50, oScript.reactionTimeArray [0] * 1000);
GraphBar2.GetComponent<RectTransform> ().sizeDelta = new Vector2 (50, oScript.reactionTimeArray [1] * 1000);
GraphBar3.GetComponent<RectTransform> ().sizeDelta = new Vector2 (50, oScript.reactionTimeArray [2] * 1000);
GraphBar4.GetComponent<RectTransform> ().sizeDelta = new Vector2 (50, oScript.reactionTimeArray [3] * 1000);
GraphBar5.GetComponent<RectTransform> ().sizeDelta = new Vector2 (50, oScript.reactionTimeArray [4] * 1000);
GraphBar6.GetComponent<RectTransform> ().sizeDelta = new Vector2 (50, oScript.reactionTimeArray [5] * 1000);
GraphBar7.GetComponent<RectTransform> ().sizeDelta = new Vector2 (50, oScript.reactionTimeArray [6] * 1000);
GraphBar8.GetComponent<RectTransform> ().sizeDelta = new Vector2 (50, oScript.reactionTimeArray [7] * 1000);
GraphBar9.GetComponent<RectTransform> ().sizeDelta = new Vector2 (50, oScript.reactionTimeArray [8] * 1000);
GraphBar10.GetComponent<RectTransform> ().sizeDelta = new Vector2 (50, oScript.reactionTimeArray [9] * 1000);

As I'm re-writing almost the same code so many times, I'm convinced this can be done using less code, even though I'm confused on how to do it with the Array properties being present.


texts: for of loop that stops at last object of array

texts:
I have a for of loop, for each item in the childElements HTMLCollection I want to subtract the height of the elements from the parent height.

let height = element[0].clientHeight;
const childElements = <[HTMLElement]>element[0].children;
let i = 0;
for (const childElement of childElements) {
    if (i !== childElements.length - 1) {
        height -= Math.ceil(childElement.clientHeight);
    }
    i++;
}
return height;

But I want to exclude the last HTMLElement in the collection from the for loop. I've now created a i variable that is checked against the length of the collection minus 1. If that's not the case the height of the element is subtracted and i is increased.

This works fine, but it feels like I'm doing two things (for of loop and while loop). Any suggestions?


texts:
I'm attempting to correctly convert a synchronous controller method to asynchronous, given that the operation it performs is CPU-intensive.

private MyDbContext db = new MyDbContext();
public async Task<ActionResult> Index()
{
    List<DashboardItemViewModel> viewModels = new List<DashboardItemViewModel>();
    List<ProductModel> products = db.Products.ToList();
    await Task.Run(() =>
    {
        foreach (ClientModel client in db.Clients)
        {
            // Constructor uses lots of logic, mostly looping through the list
            //   many times
            viewModels.Add(new DashboardItemViewModel(client, products));
        }
    });
    return View(viewModels);
}


texts: Code to find value into a table by 2 criteria (x,y)

texts:
My code finds the value that corresponds to two values in a table. It works fine, but I'd like to know what you might do differently.

Table sample:

Input:

=findval(3200,100)

Output:

4,6

Code:

Function findval(x As String, y As String)

Dim LastRow As Long
Dim LastCol As Integer
Dim x_rgn As Range
Dim y_rgn As Range
    With ActiveSheet
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With
    With ActiveSheet
        LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    End With

Set x_rgn = Range(Cells(1, 1), Cells(1, LastCol))
Set y_rgn = Range(Cells(1, 1), Cells(LastRow, 1))

With x_rgn
    Set val_x = .Find(What:=x, _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlFormulas, _
                        LookAt:=xlWhole, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
    val_x = val_x.Address
    val_x = Range(val_x).Column
End With
With y_rgn
    Set val_y = .Find(What:=y, _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlFormulas, _
                        LookAt:=xlWhole, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
    val_y = val_y.Address
    val_y = Range(val_y).Row
End With
findval = Cells(val_y, val_x).Value
End Function


texts:
Context

As an exercise for myself (I'm learning clojure). I wanted to implement the  Depth-first search algorithm.

How I did it

Using recursion

(def graph
  {:s {:a 3 :d 4}
   :a {:s 3 :d 5 :b 4}
   :b {:a 4 :e 5 :c 4}
   :c {:b 4}
   :d {:s 4 :a 5 :e 2}
   :e {:d 2 :b 5 :f 4}
   :f {:e 4 :g 1}})

(def stack [[:s]])

(def goal :g)

(defn cost [Graph start goal]
  (goal (start Graph)))

(defn hasloop? [path]
  (not (= (count path) (count (set path)))))

(defn atgoal? [path]
  (= goal (last path)))

(defn solved? [stack]
  (some true? (map atgoal? stack)))

(defn addtopath [path node]
    (conj path node))

(defn pop* [stack]
    (last stack))

(defn findpath [stack]
    (if (not (solved? stack))
        (let [first* (pop* stack) l (last first*) ]
                (findpath (drop-last
                    (remove hasloop?  (lazy-cat
                                            (map #(addtopath first* %)
                                            (keys (l graph))) stack)))))
        [(first stack)]))

How to use

(findpath stack)

Question

I'm really really interested in how this code can be improved. Both in readability, efficiency and performance.


texts: Indentation and formatting for chained jQuery methods

texts:
Below I have some jQuery code that handles footnotes. My question is actually about the formatting and indentation of the code, so I won't bother trying to explain what the code does beyond that.

I'd like to know what patterns of indentation are considered the most maintainable and readable when chaining jQuery function calls of the form: $(foo).foo(bar).foo(function(){ bar; }).foo(function(){ bar; });

Here is my specific code and the formatting/indentation that I've come up with:

$('.footnote[id^="ret_"]')
  .removeAttr('title')
  .removeAttr('alt')
  .mouseenter(function(e) {
    var footnote = $('#footnote_cont_' + this.id.substring(4)).html();

    $footnoteTooltip.stop(true, false);
    //only completely hide and change text/position if we are hovering over a different footnote
    if($footnoteTooltip.html() != footnote)
      $footnoteTooltip.hide().html(footnote).css({ left: e.pageX + 10, top: e.pageY + 15});

    $footnoteTooltip.fadeTo(fadeTime, opacity);
  })
  .mouseleave(function() {
    $footnoteTooltip.delay(fadeTime).fadeOut(fadeTime);
  })
;

Is there a more readable way of indenting this?


texts: Fixed-size array-based implementation of a queue

texts:
For my computer science class, I've implemented a Java version of a queue and would like to know if there's anything wrong with it. After my tests, it seems to work fine, but maybe somebody can point out what can be improved or if something is wrong.

public class Queue<E> implements IQueue<E> {

private E[] internalQueue;
private int currIndex;

public Queue(int size) {
    internalQueue = (E[]) new Object[size];
    currIndex = 0;
}

@Override
public void push(E input) {
    internalQueue[currIndex] = input;
    currIndex++;
}

public E[] getQueueDebug() {
    return this.internalQueue;
}

@Override
public E pop() {
    if (currIndex != 0) {
        E toReturn = internalQueue[0];

        for (int i = 1; i <= internalQueue.length - 1; i++) {
            internalQueue[i - 1] = internalQueue[i];
            internalQueue[i] = null;
        }

        currIndex--;
        return toReturn;
    }

    return null;
}

@Override
public E top() {
    if (currIndex != 0)
        return internalQueue[0];

    return null;
}

@Override
public boolean empty() {
    return (currIndex == 0);
}

}


texts: C++ application calling C# Dll marshalling strings

texts:
The code appears to work fine. The values are returned as expected from  the DLL and the values are added correctly to the DLL.

Will the way I am passing the string to C# cause a memory leak?

Also, I have to return a string from C# as type LPSTR to add to a char pointer, how could I change it so I could use the string type for the return value.

Also, I assume its related to the .Net garbage collector not kicking in yet but here is the values in TaskManager at different points:

First Line Of C Code          =  1,424k
Just After Create Instance    =  6,752k
Just Before Calling EndString =  26,264k
After EndString               =  26,276k
After CoUninit                =  26,320k

I would have expected the values to drop back down? Or do we have to wait for the garbage collector?

Here is the sample code I put together in Visual Studio 6.0:

#include "stdafx.h"
#include <string>
using namespace std;

#import "C:\\Documents and Settings\\Administrator\\My Documents\\Visual Studio 2008\\Projects\\COMCallable\\COMCallable\\bin\\Release\\COMCallable.tlb" raw_interfaces_only
using namespace COMCallable;

MyNetInterfacePtr pComObject;

string RetString();

void AddValue(long i);

void AddValue2(long i);

int main(int argc, char* argv[])
{
    HRESULT hr = S_OK;

    hr = CoInitialize(NULL);

    if(pComObject == NULL)
    {
        pComObject.CreateInstance(__uuidof(MyNETClass));
    }

    pComObject->StartString();

    for(long i = 1; i <= 100000; i++)
    {
        printf("Value %ld: %s\r\n", i, RetString().c_str());

        AddValue(i);
    }

    pComObject->EndString();

    pComObject->Release();

    CoUninitialize();

    while(true)
    {
        Sleep(1000);
    }

    return 0;
}

string RetString()
{
    char *c = NULL;

    if(pComObject != NULL)
    {
        pComObject->TestMethodString(&c);
    }

    if(c != NULL)
    {
        return c;
    }
    else
    {
        return "";
    }
}

void AddValue(long i)
{
    char numstr[21] = {0}; // enough to hold all numbers up to 64-bits
    sprintf(numstr, "%ld", i);

    string s = string("Some String Here ") + string(numstr);

    if(pComObject != NULL)
    {
        pComObject->AddString((char *)s.c_str());
    }
}

And here is the .NET code:

Interface:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace COMCallable
{
    [ComVisible(true)]
    public interface MyNetInterface
    {

        [return: MarshalAs(UnmanagedType.LPStr)]
        string TestMethodString();

        void StartString();

        void AddString([MarshalAs(UnmanagedType.LPStr)]string s);

        void EndString();
    }
}

Class

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;
using System.Diagnostics;

namespace COMCallable
{
    [ComVisible(true)]
    public class MyNETClass : MyNetInterface
    {
        private StringBuilder sb = new StringBuilder();

        public string TestMethodString()
        {
            return "Some String ";
        }

        public void StartString()
        {
            sb = null;
            sb = new StringBuilder();
        }

        public void AddString(string s)
        {
            if (sb == null)
            {
                sb = new StringBuilder();
            }

            sb.Append(s);
        }

        public void EndString()
        {
            sb = null;
        }
    }
}


texts:
I am writing color model logic in C++. I ask review in  defining limits for the color model, by saying Limits I mean this.
Consider a struct which represents RGB color model.
template<typename T>
struct RGB {
   T r,g,b;
};

So I declared a type RGB<T> where T can be any arithmetic type (the assertion is done, don't worry). So now I can create types using RGB_Float = RGB<flaot> or using RGB_888 = RGB<unsigned char> and so on.
As you already guessed I am doing image processing and sometimes there comes a time where I want a type RGB<float> where each component limits are [0-1] and sometimes I want same RGB<float> with the limits [10-20] (An example) . Also I need each type to know its limits, at compile time. Syntax is like RGB_Float::Limits::max() \\Returns max RGB_Float and RGB_Float::Limits::min() \\ Returns min RGB_Float. So I need to change my struct RGB<T> this way.
template<typename T, typename LIMITS>
struct RGB {
    using Limits = LIMITS;
    T r,g,b;

}

And before declaring any RGB<T,LIMITS> type I need to create a struct like
RGB_FloatLimits {
     static RGB<float,RGB_FloatLimits> max( return {1.0f,1.0f,1.0f};
     ... // min implementation too.
}

And then using RGB_Float = RGB<float,RGB_FloatLimits>;
I know that this is a bad solution but I think it's the only if you use C++17. I spent a week trying to pass the limits as a template argument to a color model. Please review this solution and I am 90% sure that there is a better way to do this. Thx in advance.
Note In any implementation of the limits sizeof the color model must remain the same.(So we must store the max and min statically)


texts: Calculating ordered differences between elements in vector

texts:
Input
I start with a vector of integers or floats, e.g.:
[10, 100, 20, 5, 50]

Output
I want to return a list of differences or "deltas" between elements of the sorted version of this vector. Differences are then presented in the same order as the items from the original, unsorted vector.
The above example vector would return, for instance:
[5, 50, 10, 5, 30]

Procedure
The procedure I have is to:

Order the input vector, e.g.,:

[5, 10, 20, 50, 100]

Calculate the differences between each pair of elements in the sorted vector (using the first element as-is; i.e., the difference between that value and zero):

[5, 5, 10, 30, 50]

Reorder differences by the original index of elements from the input vector:

[5, 50, 10, 5, 30]

Function
I am working in Javascript. This is the code I have written so far:
/**
 * Remap input vector into a vector of state-sorted delta scores
 *
 * @param {Array} 1d array of numbers
 * @returns {Array} 1d array of per-element differences sorted by input index indices
 */
remapVectorToIndexSortedDiffs(vector) {
  const l = vector.length;
  const indices = [...Array(l).keys()];
  const vals = indices
    .sort((a, b) => vector[a] < vector[b] ? -1 : vector[a] > vector[b] ? 1 : 0 )
    .map((d, i) => { const k = indices[i]; const v = vector[k]; return { i:k , d:v }; });
  const deltas = new Array(l);
  deltas[0] = vals[0];
  for (let idx = 1; idx < l; idx++) deltas[idx] = { i : vals[idx].i, d : vals[idx].d - vals[idx - 1].d };
  return deltas
    .sort((a, b) => (a.i > b.i) ? 1 : -1)
    .map((d) => d.d);
}

I'm working with a large 2D matrix of such vectors and would like to optimize this function as much as possible, for both memory and speed (though speed is higher priority).
Are there ways I can improve this function in Javascript?