texts: PHP - Transforming text content according to rules then persisting to database

texts:
I have a web application where my users can upload text documents and emails into what I call Streams. A stream is like a "stack", that holds all emails / documents.

My users can then add fields to the stream, and field_rules. This means, that every time a new document or email is added, the text content of the document/email, will be parsed according to the rules, and then the final parsing result is then stored in the database.

My current code works, to some degree, however, it feels a bit "hackish" as well as not very "Laravel like".

My progress so far

Whenever a new document (or email) is added, it will be handled by a queue:

public function handle(DocumentHandlingFinished $event)
{
    $stream = Stream::find($event->document->stream_id);
    $ParsingRules = new ApplyParsingRules($stream, $event->document);

    $event->document->storeResults($ParsingRules->parse());

    return true;
}

OK, so in above I start off by getting the "Stream" that the document was uploaded to.

Then I instanciate the ParsingRule class, that will perform the various rules on the content of the document.

Finally, I save the parsed results to the database.

Below you can see my ApplyParsingRule class:

public function __construct(Stream $stream, Document $document)
{
    $this->data = $document;
    $this->content = $document->content;
    $this->stream = $stream;
    $this->fields = $this->stream->documentfields()->with('rules')->get();
}

//Iterate through each rule and parse through the content.
public function parse() : object
{
    $content = $this->content;
    $results = collect([]);
    foreach ($this->fields as $field) {
        foreach ($field->rules as $fieldrule) {

            $content = doSomething($content); //Minified for simplicity.
            $results[] = [
                'field_rule_id' => $fieldrule->id,
                'content' => $content
            ];

        }
    }

    return $results;
}

Now as you can see in my handle message, I call the parse() function and then saves the results:

$event->document->storeResults($ParsingRules->parse());

In my Document model, I have the storeResults() function:

Document.php

//Persist the parsed content to the database.
public function storeResults(object $results) : object
{
    //If the document was already parsed before, delete old records.
    if ($this->results->count() > 0) {
        $this->results()->delete($this->results);
    }

    //Use ->last() because we only want to insert the last parsed text result.
    return $this->results()->create($results->last());
}

So above flow works as long as the $results array contains information.

I was wondering if above code can be refactored / improved even further?

Another concern I have is, If the $results array from the ApplyParsingRule class is empty, then the create() method will fail.


texts: Find the sum of the digits of a given number

texts:
I need to find the sum of the digits of the given number and repeat the process until the value lies between 1 to 9.

e.g
if the input is 72457 then,

7+2+4+5+7 = 25

2+5 = 7

so , the function should return 7.

Also, if the input is a negative number like -72457 the function should return -7.

Here's what i tried,

int digitSum(int input1){

int flag=0;

if(input1<0)
     flag=1;

 int rem,sum=0;
 int x=abs(input1);

 while(x>0){
    rem=x%10;
    sum+=rem;
    x=x/10;

    }

 int value = sum%9;

 if(value==0){

    if(flag==1)
     return -9;

    else
     return 9;
 }

 else{

  if(flag==1)
   return -value;

   else
    return value;

 }

}


texts: Minimum element in a sorted rotated array

texts:
A sorted array [0,1,2,3,4,5] when rotated n times (3 times in this case) becomes [3,4,5,0,1,2], meaning elements in the front move to the end. The code below finds the minimum element in this array, which is the pivot point of rotation.

function findminimum(a, start, end){
    if(start>end || start == end || a[start]<a[end])
        return a[start];

    var mid = start + Math.floor((end-start)/2);

    //check if mid is the minimum element - also if mid is greater than start
    if(mid>start && a[mid]<a[mid-1])
        return a[mid];

    //check if mid+1 is the minimum element - also if mid is less than end
    if(mid<end && a[mid]>a[mid+1])
        return a[mid+1];

    //handles duplicate elements case
    if(a[start]==a[mid] && a[mid]==a[end]){
        //search both sides and get the minimum
        return Math.min(findminimum(a, start, mid-1), findminimum(a, mid+1,    end));
    }
    //left half is sorted or every element is same, search right half
    if(a[start]<=a[mid])
        return findminimum(a, mid+1, end);
    return findminimum(a, start, mid-1); //search left half
}
var a = [3,4,5,0,1,2];
//original array [0,5,5,5,5] rotated 2 times
//var a = [5,5,5,0,5];
console.log(findminimum(a, 0, a.length-1));

Code also handles duplicates. Any comments or suggestions on improving this code will be helpful.


texts: User class implemented with PHP 7.4 using Active Record

texts:
I need some constructive feedback for the working OOPs project which I created to introduce to Object Oriented Programming in a class. Hence is for beginners, I did not include interfaces or abstract functions nor singleton or factories. Can you give me some feedback on the code style, some possible anti patterns? Thanks

<?php

declare(strict_types=1);

namespace MidoriKocak;

use function array_key_exists;

/**
 *
 */
final class User
{

    /**
     * @var Database
     */
    private Database $db;
    /**
     * @var string
     */
    private ?string $id = null;

    /**
     * @var string
     */
    private string $email;
    /**
     * @var string
     */
    private string $username;
    /**
     * @var string
     */
    private string $password;

    /**
     *
     */
    public function __construct(Database $db)
    {
        $this->db = $db;
    }

    /**
     * @param  string  $password
     *
     * @return void
     */
    public function setPassword(string $password): void
    {
        $this->password = password_hash($password, PASSWORD_DEFAULT);
    }

    public function getPassword(): string
    {
        return $this->password;
    }

    /**
     * @param  string  $email
     *
     * @return void
     */
    public function setEmail(string $email): void
    {
        $this->email = $email;
    }

    /**
     * @param  string  $username
     *
     * @return void
     */
    public function setUsername(string $username): void
    {
        $this->username = $username;
    }

    /**
     * @return void
     */
    public function save()
    {
        if ($this->id) {
            $this->db->update($this->id, $this->toArray(), 'users');
        } else {
            $this->db->insert($this->toArray(), 'users');
            $this->id = $this->db->lastInsertId();
        }
    }

    /**
     * @return array
     */
    public function toArray(): array
    {
        return [
            'username' => $this->username,
            'email' => $this->email,
            'password' => $this->password
        ];
    }

    /**
     * @param  array  $data
     *
     * @return void
     */
    public function fromArray(array $data): void
    {
        if (array_key_exists('id', $data)) {
            $this->id = (string)$data['id'];
        }

        $this->setEmail($data['email']);
        $this->setUsername($data['username']);
        $this->setPassword($data['password']);
    }
}

Thank you for your feedback.

(P.S. Please be harsh as possible.)


texts:
I am building a doctor appointment app with Django and Django Rest Framework. The app will have the functionality for secretaries to add appointments to a Doctor's calendar, and each Doctor may have more than one clinic (and multiple secretaries).
I built this Calendar Model to store the availability information of a doctor, which needs to basically inform:

on a given day, at what time the doctor starts and finishes work
on a given day, at what time the doctor starts and finishes their break time (if they do).

Is this the optimal way to do it?
class Calendar(models.Model):
    doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE, related_name="appointments")
    clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE, related_name="appointments")
    monday_start =  models.TimeField()
    monday_end =  models.TimeField()
    monday_break_start =  models.TimeField()
    monday_break_end =  models.TimeField()
    # continues for every single day of the week


texts:
I've decided that I want to take a stab at test first programming. So, before I tackled writing an isPrime function, I wrote this unit test. It's my first and I'm not sure I'm doing this right.

I was thinking that I might want to extract the loops to just two methods that I would pass an array to. One for Assert.IsTrue and one for Assert.IsFalse, but I wasn't sure if that was a good idea in a unit test.

Am I covering my bases here?
What other cases am I missing?
What would you do differently?

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Challenges;
using System.Numerics;

namespace ChallengesTest
{
    [TestClass]
    public class PrimeTest
    {
        [TestMethod]
        public void SmallPrimes()
        {
            int[] numbers = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };

            for (var i = 0; i < numbers.Length; i++)
            {
                Assert.IsTrue(Numbers.isPrime(numbers[i]));
            }

        }

        [TestMethod]
        public void Negatives()
        {
            int[] numbers = { -2, -3, -5, -7, -11, -13, -17, -19, -23, -29 };

            for (var i = 0; i < numbers.Length; i++)
            {
                Assert.IsFalse(Numbers.isPrime(numbers[i]));
            }
        }

        [TestMethod]
        public void PositiveNotPrime()
        {
            int[] numbers = { 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25 };

            for (var i = 0; i < numbers.Length; i++)
            {
                Assert.IsFalse(Numbers.isPrime(numbers[i]));
            }
        }

        [TestMethod]
        public void ZeroAndOne()
        {
            Assert.IsFalse(Numbers.isPrime(0));
            Assert.IsFalse(Numbers.isPrime(1));
        }

        [TestMethod]
        public void BigPrimes()
        {
            int[] numbers = {104677,104681, 104683, 104693, 104701, 104707, 104711, 104717, 104723, 104729 };

            for (var i = 0; i < numbers.Length; i++)
            {
                Assert.IsTrue(Numbers.isPrime(numbers[i]));
            }
        }
    }
}


texts: constexpr Precalculate size of serialized data with templates and C++20 concepts

texts:
Im writing a serializer that will do serialization/deserialization as fast as possible, and that uses templates so that i dont have to create a ton of functions for every data structure,
This is the part of it that pre-calculates the size of the data to be serialized
I have only tested this on MSVC and GCC
So this code has get_size_needed() which should get the total size (in bytes) needed to store the data for the arguments.
You should be able to put any container/arithmetic type (and any combination of those types) into it as a argument and it should calculate its size at compile time.
It should also support calculating the size of nested containers.
sorry if its messy, this is my first time dealing with templates and concepts (with some help from some people)
Serialization.h
#include <vector>
#include <cstdint>
#include <string>
#include <ranges>
#include <numeric>
#include <type_traits>

#ifdef _MSC_VER // vvv MSVC implementation vvv (MSVC does not support <ranges> nor templates with auto arguments)

// checks the requires size of a variable
template <typename T>
constexpr std::size_t get_size_needed_for_type(const T& value)
{
    // If the value is a bool/int/float then just get the size of it
    if constexpr (std::is_arithmetic_v<T>)
    {
        return sizeof(value);
    }

    // If the value is a container, then get the size of the container, and the size of its elements
    else if constexpr (std::is_class_v<T> || std::is_union_v<T>)
    {
        // Get the size of every element
        return std::accumulate(value.cbegin(), value.cend(), std::size_t{ 0 }, [](std::size_t acc, const auto& v)
        {
            return acc + get_size_needed_for_type(v);
        });
    }

    // I dont know what whould end up here, but its probably not something thats serializable
    else
    {
        static_assert(false, "Unsupported type for serialization!");
    }
}

#else // vvv GCC implementation vvv - ^^^ MSVC implementation ^^^

// Only accepts bool/int/float
template <typename T>
    requires std::integral<T> || std::floating_point<T>
constexpr std::size_t get_size_needed_for_type(const T& value)
{
    return sizeof(value); // return the size of it
}

// If the is a range, then its probably a container, then get the size of the container, and the size of its elements
constexpr std::size_t get_size_needed_for_type(const std::ranges::range auto& value)
{
    // Get the size of every element
    return std::accumulate(value.cbegin(), value.cend(), std::size_t{ 0 }, [](std::size_t acc, const auto& v)
    {
        return acc + get_size_needed_for_type(v);
    });
}

#endif // ^^^ GCC implementation ^^^

// Iterate through arguments, and accumulate the size of all of them
template <typename... Args>
constexpr std::size_t get_size_needed(const Args&... args) {
  return (... + get_size_needed_for_type(args));
}

Whould be nice to get thoughts / criticism / optimization tips on this


texts:
I'd like to know any ways of shortening this UI window for Maya, at the moment, because I couldn't find very detailed documentation and not very skilled with python, I have just built this UI with the knowledge that I have already, I know it's not the best way of doing it (using empty text elements to fill gaps etc)

Can someone provide me with an example on how to shorten this code or structure it properly?

import maya.cmds as cmds
class randomScatter():
    def __init__(self):
        if cmds.window("randSelection", exists=1): cmds.deleteUI("randSelection")
        cmds.window("randSelection", t="Scatter Objects - Shannon Hochkins", w=405, sizeable=0)
        cmds.rowColumnLayout(nc=3,cal=[(1,"right")], cw=[(1,100),(2,200),(3,105)])
        cmds.text(l="Prefix ")
        cmds.textField("prefix")
        cmds.text(l="")
        cmds.text(l="Instanced object(s) ")
        cmds.textField("sourceObj", editable=0)
        cmds.button("sourceButton", l="Select")
        cmds.text(l="Target ")
        cmds.textField("targetObj", editable=0)
        cmds.button("targetButton", l="Select")
        cmds.separator( height=20, style='in')
        cmds.separator( height=20, style='in')
        cmds.separator( height=20, style='in')
        cmds.text(l='Copy Options ')
        cmds.radioButtonGrp('copyOptions', labelArray2=['Duplicate', 'Instance'], numberOfRadioButtons=2, sl=2)
        cmds.text(l="")
        cmds.text(l="Rotation Options ")
        cmds.radioButtonGrp('orientation', labelArray2=['Follow Normals', 'Keep original'], numberOfRadioButtons=2, sl=1)
        cmds.text(l="")
        cmds.separator( height=20, style='in')
        cmds.separator( height=20, style='in')
        cmds.separator( height=20, style='in')
        cmds.text(l="")
        cmds.checkBox('copyCheck', l='Stick copies to target mesh.')
        cmds.text(l="")
        cmds.separator( height=20, style='in')
        cmds.separator( height=20, style='in')
        cmds.separator( height=20, style='in')
        cmds.text('maxNumber', l="Copies ")
        cmds.intFieldGrp("totalCopies", nf=1, v1=10, cw1=100)
        cmds.text(l="")
        cmds.separator( height=20, style='in')
        cmds.separator( height=20, style='in')
        cmds.separator( height=20, style='in')
        cmds.text(l='')
        cmds.text(l=" From                          To", align='left')
        cmds.text(l='')
        cmds.text(l="Random Rotation")
        cmds.floatFieldGrp("rotValues", nf=2, v1=0, v2=0, cw2=[100,100])
        cmds.text(l="")
        cmds.text(l="Random Scale")
        cmds.floatFieldGrp("scaleValues", nf=2, v1=0, v2=0, cw2=[100,100])
        cmds.text(l="")
        cmds.setParent("..")
        cmds.rowColumnLayout(w=405)
        cmds.separator( height=20, style='in')
        cmds.text("Progress", height=20)
        cmds.progressBar('buildGridProgBar', maxValue=100, width=250)
        cmds.separator( height=20, style='in')
        cmds.button("excute", l="Scatter Objects",  w=403, al="right")
        cmds.showWindow("randSelection")
randomScatter()


texts:
Look at the method setupCamera. I use it to reduce the size of the create method. As you can see, inside this method I instantiate camera and viewport, that are fields.
Is there any problem to do that, or exists  there any surer way to do that?

public class HudCameraSample extends ApplicationAdapter {

    private static final float SCREEN_WIDTH = 1280;
    private static final float SCREEN_HEIGHT = 720;
    private static final float SCENE_WIDTH = 12.8f;
    private static final float SCENE_HEIGHT = 7.2f;
    private static final float WORLD_TO_SCREEN = SCENE_HEIGHT / SCREEN_HEIGHT;

    private OrthographicCamera camera, hudCamera;
    private Viewport viewport, hudViewport;
    private SpriteBatch batch;

    @Override
    public void create() {
        setupCamera(camera, viewport, SCENE_WIDTH, SCENE_HEIGHT);
        setupCamera(hudCamera, hudViewport, SCREEN_WIDTH, SCREEN_HEIGHT);
    }

    private void setupCamera(Camera camera, Viewport viewport, float width, float height) {
        camera = new OrthographicCamera();
        viewport = new FillViewport(width, height, camera);
        camera.update();
    }

    @Override
    public void render() {

    }
}


texts:
I am new to Python (and to programming). I tried to implement this game in Python and took some help from the code reviews of similar questions posted on this website.

# rock paper scissors game

import random
import sys

choices = ["rock", "paper", "scissors"]

def check_victory(computer_choice, user_choice):
    if user_choice == computer_choice:
        return "tie"
    elif computer_choice == "rock" and user_choice == "paper":
        return "won"
    elif computer_choice == "paper" and user_choice == "scissors":
        return "won"
    elif computer_choice == "scissors" and user_choice == "rock":
        return "won"
    else:
        return "lost"

def play():
    # get input from user
    user_choice = None
    while user_choice not in choices:
        user_choice = input("Enter your choice: ")
        # check if user wants to quit
        if user_choice == "quit":
            sys.exit()

    computer_choice = random.choice(choices)

    # output result
    print(f"Computer choose: {computer_choice}")
    print("You " + check_victory(computer_choice, user_choice), end="\n\n")

if __name__ == "__main__":
    while True:
        play()
```


texts:
I have created an encryption algorithm for this app I am currently in the process of developing. I was wondering if my code looks "sharp", concise, and most importantly, succinct. I was also wondering if it is secure.

I know that 99% of the time, encryption algorithms that are invented are not secure, however I was wondering if this algorithm is in the 1% of the safe ones.

#Key Size: 128 bytes [recommended]

import random
import os
import time
import hashlib

def generate_key(key_size):
    key = os.urandom(key_size)
    return key;

def encrypt(_key, message):
    letter_ascii = []
    letter_ascii_final = []
    ascii_key_value = ''.join(str(ord(x)) for x in str(_key))
    for letter in message:
        letter_ascii.append(ord(letter))
    for _letter in letter_ascii:
        added = int(ascii_key_value) + int(_letter)
        letter_ascii_final.append(str(added))
    return letter_ascii_final;

def decrypt(_key, message):
    message_repieced = []
    ascii_key_value = ''.join(str(ord(x)) for x in str(_key))
    for item in message:
        _item = chr(int(item)-int(ascii_key_value))
        message_repieced.append(str(_item))
    return ''.join(message_repieced);


texts:
This question has a second part here:

Comparing columns from two CSV files - follow-up

I'm currently trying to compare two CSV files column by column but only when their indexes match.

Here is what I've done:

import sys

def get_column(columns, name):
    count = 0
    columns = columns.split(';')
    for column in columns:
        array = list(column)
        if(array[0] == '"'):
            array[0] = ''
        if(array[len(column) - 1] == '"'):
            array[len(column) - 1] = ''
        column = ''.join(array)
        if column != name:
            count += 1
        else:
            return(count)

def set_up_file(file, variable):
    columns = next(file)
    siren_pos = get_column(columns, 'INDEX1')
    nic_pos = get_column(columns, 'INDEX2')
    variable_pos = get_column(columns, variable)
    return(siren_pos, nic_pos, variable_pos)

def test_variable(variable):
    with open('source.csv', 'r') as source:
        sir_s, nic_s, comp_s = set_up_file(source, variable)
        with open('tested.csv', 'r') as tested:
            sir_t, nic_t, comp_t = set_up_file(tested, variable)
            correct = 0
            memory = 0
            for row_s in source:
                row_s = row_s.split(';')
                tested.seek(0, 0)
                count = 0
                for row_t in tested:
                    count += 1
                    if(count >= memory):
                        row_t = row_t.split(';')
                        if(row_s[sir_s] == row_t[sir_t] and row_s[nic_s] == row_t[nic_t]):
                            if(row_s[comp_s] == row_t[comp_t]):
                                correct += 1
                                memory = count
                            break
            tested.seek(0, 0)
            print(correct / sum(1 for line in tested) * 100)

def main():
    test_variable('VARIABLE_TO_COMPARE')

if(__name__ == "__main__"):
    main()

This script is running into some performance issue and I would like to know how to make it run faster / make it more readable.


texts:
I'm using Python to find fixed points of a given function and then draw a cobweb plot to visualize it. Thanks to this question, I have the core of the code written and can accomplish the task, but I have a number of questions about improving the functionality of the code.

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return 2*x*(1-x)

class fixpt(object):

    def __init__(self, x):
        self.x = x
        self.f = f

    def search(self, N = 1000, epsilon = 1.0E-100, store = False):
        x = self.x
        y = self.f(x)
        n = 0
        if store: values = [(x,y)]
        while abs(y-x) >= epsilon and n < N:
            x = f(x)
            n += 1
            y = f(x)
            if store: values.append((x,y))
        if store:
            return y, values
        else:
            if n >= N:
                return "No fixed point for given initial condition"
            else:
                return x, n, y
    def plot(self):
        res, points = self.search(store = True)
        xaxis = np.linspace(0,1,1000)
        plt.plot(xaxis, f(xaxis), 'b')
        plt.plot(xaxis, xaxis, 'r')

        for x, y in points:
            plt.plot([x, x], [x, y], 'g')
            plt.plot([x, y], [y, y], 'g')

        plt.show()

What I'm wondering is how I can:

Avoid the need to redefine the function f(x) when analyzing other functions (by, perhaps asking for user input)
Avoid the need to change the range of concern (i.e. the range in np.linspace) in a similar manner
Improve the structure of this code in general (I'm a Python noob and get the feeling I've created a class for little to no reason
Most importantly: use this code iteratively to scan for fixed points for all x in a given range


texts:
This is actually a question that bugged me for 8 years or so, but just swept it under the rug.

I have a project (big, old, zend 1, etc.) that contains a decent (not high but large enough) amount of logic in views. This implies existence of conditionals there. It does not have any template system (like smarty/twig) so php is used for that.

Now... my problem is how to indent (since current indentation just hurts my eyes).

Currently is like this:

  <?php if ($this->product->getType() == Product_Types::BOOK) {
       $bookAuthor = $this->product->getAuthor();
  ?>

<?php echo $bookAuthor; ?>

  <?php } ?>

Basically the indentation is correct, but totally useless since I can't easily see that Some output is actually inside the if statement.

Personally I prefer this approach (and used it for years, but now I decided I need a second opinion):

  <?php
     if ($this->product->getType() == Product_Types::BOOK) {
        $bookAuthor = $this->product->getAuthor();
        ?>

              <?php echo $bookAuthor; ?>

        <?php
     }
  ?>

This is not actually that correct since the <?php ?> tags don't open/close on same space. It basically creates an "pseodo-block" ?> <?php. BUT it helps me see exactly what's where. You can see from first glance that the div belongs in the if... and I think that is actually the purpose of indenting.

How do you guys think is better? (other variants are encouraged)


texts: Find next number whose sum of digits is N

texts:
This program takes two numbers M(<10k) and N (<100) and finds the smallest number greater than M whose sum of digits = N. Additionally, as per the question's requirements, it prints the number of digits in the printed number.

Example: M = 919
,         N = 34

Required number = 7999 as 7+9+9+9 = 34

   /**
     *Takes M and N , finds the number greater than M whose sum of digits = N
     */
    import java.util.*;
    class MtoN
    {
        static int sumOfdigits(int n)
        {
            int sum =0 ;
            while(n!=0)
            {
                sum = sum + n%10;
                n = n/10;
            }
            return sum;
        }

        static int numOfdigits(int n)
        {
            String str = Integer.toString(n);
            return str.length();
        }

        public static void main(String[] args)
        {
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter M (100 to 10000)");
            int M = sc.nextInt();
            System.out.println("Enter N (less than 100)");
            int N = sc.nextInt();
            if(N> 100 || M>10000 || M<100)
            {
                System.out.println("INVALID INPUT");
            }
            else
            {
                for(int i = M+1 ; ; i++)
                {
                    if(sumOfdigits(i) == N)
                    {
                        System.out.println("Required Number is: "+ i);
                        System.out.println("Number of digits in it "+ numOfdigits(i));
                        break;
                    }
                }
            }
        }
    }

It works fine for smaller number but takes TOO much time for numbers like: M = 9181 and N = 99. (In fact, it doesn't even print the result on my screen...)

How do I reduce this execution time?


texts: Merge sort in declarative style with JavaScript

texts:
ES6 syntax helps to write code in a declarative style, which is exactly what I am trying to achieve here. Any advice to make my code "more declarative" (and easier to read) is welcomed.

const middleIndex = xs => Math.floor(xs.length / 2);

const split = xs => {
    return {
        fst: xs.slice(0, middleIndex(xs)),
        snd: xs.slice(middleIndex(xs))
    };
};

const isSingleton = xs => xs.length === 1;

const any = xs => xs.length > 0;

const dropHead = xs => xs.shift();

const head = xs => xs[0];

// Arrow functions cannot be generators. Damn it!
const merge = function* (xs, ys) {
    while (any(xs) && any(ys)) {
        yield dropHead(head(xs) < head(ys) ? xs : ys);
    }

    while (any(xs)) {
        yield dropHead(xs);
    }

    while (any(ys)) {
        yield dropHead(ys);
    }
}

const sort = xs => {
    if (isSingleton(xs) || !any(xs)) {
        return xs;
    }

    const { fst, snd } = split(xs);

    return [...merge(sort(fst), sort(snd))];
}


texts:
So I'm making a strlen function and I thought I would use SIMD instructions for it. It runs fine but when comparing it to std::strlen(), it falls a lot behind. Any ideas on how to make it faster would be much appreciated.
inline size_t strlen(const char* data) {
        const __m128i terminationCharacters = _mm_setzero_si128();
        const __m128i* pointer = (const __m128i*)data;

        size_t length = 0;

        const int compareMode = _SIDD_UBYTE_OPS | _SIDD_LEAST_SIGNIFICANT | _SIDD_CMP_EQUAL_EACH;

        for (;; length += 16, ++pointer) {
            const __m128i comparingData = _mm_loadu_si128(pointer);

            size_t index = _mm_cmpistri(terminationCharacters, comparingData, compareMode);

            if (index < 16)
                return length + index;
        }
    }
```


texts: Save all HTML field names in Controller - it is bad or not bad idea?

texts:
I have sample controller InboxController in my Inbox app. I want control with field name from my controller. If I will control with fields name from controller will not be destroyed MVC rules?

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class InboxController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Field names in HTML form
    |--------------------------------------------------------------------------
    */

    /**
     * Recipient field name.
     *
     * @var string
     */

    public $recipient = 'recipient';

    /**
     * Sender field name.
     *
     * @var string
     */

    public $sender = 'sender';

    /**
     * Subject field name.
     *
     * @var string
     */
}

Html code:

<input type='text' name="{{ $sender }}">


texts:
Array.prototype.insertionSort = function(){
    for (var i=1, s,temp; i<this.length; i++){
         temp = this[s=i];
         while (s&&temp<this[s-1]) this[s] = this[--s];
         this[s] = temp;
    }
    return this
}

Array.prototype.bubbleSort = function(){
    var swapped = true;
    while (swapped) {
        swapped = false;
        for (var i = 0; i<this.length-1; i++) if (this[i]>this[i+1]) {
            var temp = this[i];
            this[i] = this[i+1];
            this[i+1] = temp;
            swapped = true;
        }
    }
    return this;
}

var array = [1,4,4,5,6,7,5,3,5,67,7,4,3,5,76,234,24,235,24,4,234,234,234,325,32,6246,8,89,689,7687,56,54,643,32,213,2134,235,346,45756,857,987,0790,89,57,5,32,423,54,6,765,65,745,4,34,543,43,3,3,3,34,3,63,63,35,7,537,35,75,754,7,23,234,43,6,247,35,54,745,767,5,3,2,2,6,7,32,3,56,346,4,32,32,3,4,45,5,34,45,43,43],

    iter = 10000000;

console.time("bubble x"+iter);
for (var i = iter; i--;) array.bubbleSort();
console.timeEnd("bubble x"+iter);

console.time("insertion x"+iter);
for (var i = iter; i--;) array.insertionSort();
console.timeEnd("insertion x"+iter);

The insertion sort should be quicker, right? Is there something wrong with an implementation of mine?

bubble x10000000: 3131ms
insertion x10000000: 4287ms

I didn't even apply the optimisation, to the bubble sort, that decrements the loop length every iteration.


texts: Nagios check to see if a certain IP appears in a trace route

texts:
I needed a test to know which firewall in out HA environment was currently active. We have a webFilter connected to our "primary" so if the firewall fails over the webfilter is taking out of path and internet access is completely open during that time.

I have a bash script that will feed two IP addresses. I am aware there is no data validation. This was done to reduce processing time. Run the trace using the first IP address and see if we can grep the second from the result. If the result is a non-zero string then return and OK result else return a Critical result. The exit codes are used by the Nagios Monitoring system to determine state and actions which is why there are custom error codes.

#!/usr/bin/env bash

# Nagios exit codes. These are used to determine state
nagiosStateOK=0
nagiosStateWarning=1
nagiosStateCritical=2
nagiosStateUnknown=3

# Initialize result
traceResult=''

# The address that we are going to run the tracert to
target="$1"
# Check for this address in the trace
locate="$2"

traceResult=$(traceroute -n -w 2 $target | grep $locate)

if [[ -n "$traceResult" ]];then
        echo "$locate found in path. Still running on primary"
        exit $nagiosStateOK
else
        echo "$locate not found in path. Probably failed over"
        exit $nagiosStateCritical
fi


texts:
I have created an api in php and I was hoping some clever individuals would mind reviewing it to see what I could do better. I have commented it heavily to explain my reasoning. please feel free to pick holes wherever you can!

    //On my page 'localhost/api'

    if (!$_POST) {
        die('No direct access allowed');
    }

    include('/api/gateway.php'); //Pull in my Gateway class

    try {
        $api = new Gateway($_POST);
    }
    catch (Exception $e) {
        //Catch any exceptions thrown in the api and return them as a bad request
        echo json_encode( array(
            'status'=> 400,
            'params'=> $_POST,
            'data'=> array(
                'message'=> $e->getMessage(),
                'file'=> $e->getFile(),
                'line'=> $e->getLine()
            )
        ));
    }

My Gateway class then deals with the api call.

class Gateway {

    function __construct($params) {
        $this->params = (isset($params) ? $params : array());

        if ( !isset($params['method']) ) {
            throw new Exception('No method passed to API');
        }

        $method = explode('.', $params['method']);

        if ( !class_exists($method[0]) ) {
            throw new Exception('No class by the name of ' . $method[0]);
        }
        if ( !method_exists($method[0], $method[1]) ) {
            throw new Exception('No method in ' . $method[0] . ' called ' . $method[1]);
        }

        //Call my class and method without instantiating it.
        $result = $method[0]::$method[1]($params);

        if (!$result) {
            //This shouldn't really fire as it should be handled in the method.
            $this->error();
        }
        else {
            $this->send(200, $result, $params);
        }

    }

    public $params; //$_POST parameters stored here to return if an error is thrown

    public function error($code = 400, $data = array(), $params = array()) {
        echo json_encode( array(
            'status'=> 400,
            'params'=> $this->$params,
            'data'=> $data
        ));
    }

    public function send($code = 200, $data = array(), $params = array()) {
        echo json_encode( array(
            'status'=> 200,
            'params'=> $this->params,
            'data'=> $data
        ));
    }
}

Example of my api classes. These are currently in the same file as my Gateway class. Eventually these will be moved into a separate folder and pulled in dynamically.

class Sites {
    public function getSites($params) {
        return array(
            'gotyou'=> 'message'
        );
    }
}


texts: Persist keyboard backlight color on Linux laptop

texts:
System76 sells laptops that come preloaded with their Ubuntu spinoff Pop_OS. The laptop keyboards have backlights that can change color and brightness, but so far I haven't found any way to keep the setting when I restart the machine; it goes back to bright white.
Here's someone else struggling with the same problem somewhat recently. The comments link to a useful python script, but it doesn't seem to be finished to the point where it would do what's wanted. (It's primary goal seems to be a GUI, with persistence on the wishlist.)
I finally got sick of it and implemented the behavior I wanted using systemd, which I'm using to call a Python script.
Since other people have asked the same questions as me in the past, I figured I'd share my solution, but the first step is to ask for feedback.
Is this a good solution to the problem? Are there mistakes or other reasons people shouldn't use it?
#!/usr/bin/env python3

import argparse as ag
import os.path as path
import re

print("Attempting to set system76 keyboard backlight color and brightness.")

"""
Partially cribbed from
https://github.com/ahoneybun/keyboard-color-chooser/blob/master/keyboard-color-switcher.py

Called by
/etc/systemd/system/system76-kb-backlight.service
as decribed here:
https://www.howtogeek.com/687970/how-to-run-a-linux-program-at-startup-with-systemd/

Example file /etc/systemd/system/system76-kb-backlight.service
``
[Unit]
Description=Set color and brightness of system-76 laptop keyboard backlight

[Service]
Type=simple
ExecStart=systemd-cat /path_to_this_executable/set_system76_kb_backlight -g 55 -r FF -B 150

[Install]
WantedBy=multi-user.target
``
(Don't forget to enable the service.)
"""

def color_fragment(string):
    if re.fullmatch(r'^[0-9A-F]{2}$', string):
        return string
    else:
        raise ag.ArgumentTypeError(f'"{string}" is not a two-digit hex value.')

def brightness_fragment(string):
    if re.fullmatch(r'^[0-9]{1,3}$', string) and 0 <= int(string) and 255 >= int(string):
        return string
    else:
        raise ag.ArgumentTypeError(f'"{string}" is not an integer 0-255.')

arg_parse = ag.ArgumentParser(description="Set the color and brightness of the system76 keyboard backlight.")
arg_parse.add_argument('-r', help="The red RGB value (00 to FF).", default="00", type=color_fragment)
arg_parse.add_argument('-g', help="The green RGB value (00 to FF).", default="00", type=color_fragment)
arg_parse.add_argument('-b', help="The blue RGB value (00 to FF).", default="00", type=color_fragment)
arg_parse.add_argument('-B', help="The brightness (0 to 255).", default="48", type=brightness_fragment)

args = arg_parse.parse_args()
red = args.r
green = args.g
blue = args.b
brightness = args.B
color = f'{red}{green}{blue}'

ledPath = "/" + path.join('sys', 'class', 'leds', 'system76_acpi::kbd_backlight') + '/'
if not path.exists(ledPath):
    ledPath = "/" + path.join('sys', 'class', 'leds', 'system76::kbd_backlight') + '/'

regions = ['left', 'center', 'right', 'extra']
region_paths = [ledPath + f'color_{r}' for r in regions]
brightness_path = ledPath + 'brightness'
settings = {brightness_path: brightness,
            **{rp: color for rp in region_paths}}

for (p,s) in settings.items():
    with open(p, 'w') as f:
        f.write(s)

print("Successfully set system76 keyboard backlight brightness.")
arg_parse.exit(0)


texts: Computing the integer square root of large numbers

texts:
The "integer square root" of a
non-negative integer \$ n \$ is defined as the largest integer not greater than
 \$ \sqrt{n} \$:
$$
 \operatorname{isqrt}(n) = \lfloor \sqrt{n} \rfloor
 = \max \{ k \in \Bbb N_0 \mid k^2 \le n \}
$$
It is for example needed in prime factorization, as an upper bound for the possible
factors.

A simple approach is to compute the floating point square root and truncate the result to an integer. In Swift that would be

func isqrt_simple(_ n: Int) -> Int {
    return Int(Double(n).squareRoot())
}

As observed in
Computing the square root of a 64-bit integer,
this can produce wrong results for large numbers, because an IEEE 64-bit floating point
number with its 53 bit significand cannot represent large integers exactly.
Here is an example:

let n = 9223371982334239233
let r = isqrt_simple(n)

print(r)           // 3037000491
print(r * r <= n)  // false

The correct result would be 3037000490, since
$$
  \sqrt{9223371982334239233} \approx 3037000490.9999996957524364127605120353
$$
(computed with PARI/GP).

The following implementation uses the ideas from
DarthGizka's answer
to the above mentioned question to implement a "correct" integer square root function in Swift 4:

func isqrt(_ n: Int) -> Int {
    precondition(n >= 0, "argument of isqrt() must be non-negative")

    var r = Int(Double(n).squareRoot()) // Initial approximation
    // Try to increase:
    while case let prod = r.multipliedReportingOverflow(by: r),
        !prod.overflow && prod.partialValue < n  {
            r += 1
    }
    // Decrease if necessary:
    while case let prod = r.multipliedReportingOverflow(by: r),
        prod.overflow || prod.partialValue > n  {
            r -= 1
    }
    return r
}

Example:

let n = 9223371982334239233
let r = isqrt(n)

print(r)                 // 3037000490
print(r * r <= n)        // true
print((r+1) * (r+1) > n) // true

Remarks:

I have chosen Int as argument and result type even if the square root is defined
only for non-negative integers. The reason is that Int is the prevalent integer
type in Swift and already used for quantities that can not be negative (e.g.
the count of an array, or the MemoryLayout<T>.size of a type).
Int can be a 32-bit or 64-bit quantity, therefore I cannot check against
a constant for overflow (as r < UINT32_MAX in
DarthGizka's C++ solution).
multipliedReportingOverflow() is used instead to check if squaring a candidate causes an overflow.

The code worked correctly in all my tests. Here are some tests which all succeed

func testSqrt(_ n: Int) {
    let r = isqrt(n)
    if r * r > n {
        print("Too large:", n, r)
    } else if (r+1) * (r+1) <= n {
        print("Too small:", n, r)
    }
}

testSqrt(4503599761588224)
testSqrt(4503599895805955)
testSqrt(4503600030023688)
testSqrt(4503600164241423)

testSqrt(9223371982334241080)
testSqrt(9223371982334239233)
testSqrt(9223372024852248003)
testSqrt(9223372024852247041)
testSqrt(9223372030926249000)
testSqrt(9223372030926247424)

These tests fail if isqrt_simple() is used instead.

All feedback is welcome, in particular suggestions how to improve the performance.


texts:
I know there is a better way to do the following but I havent had any luck trying to clean it up.

This is for a table of messages where the user can click a row, message-head, which will display the message-body-hidden to the user as well as change the class of message-head to message-head-active. It will also change the fontawesome icon. Along with that, any rows that are currently being displayed or are -active will be reverted back to their defaults.

How could I clean this up or more easily perform the same tasks?

$("table").on("click", "tr.message-head", function () {
    var active = $(this)
    active.toggleClass('message-head-active')

    if($("i",this).hasClass("fa-envelope-open")){
        $("i",this).removeClass("fa-envelope-open")
        $("i",this).addClass("fa-envelope")
    }else{
        $("i",this).removeClass("fa-envelope")
        $("i",this).addClass("fa-envelope-open")
    }

    var showMe = active.next().find('.message-body-hidden')
    showMe.toggle()

    $("tr.message-head-active").not(active).removeClass('message-head-active')
    $("tr.message-head-active").not(active).addClass('message-head')

    $("tr.message-head").not(active).find('i').removeClass("fa-envelope-open")
    $("tr.message-head").not(active).find('i').addClass("fa-envelope")

    $("td.message-body-hidden").not(showMe).hide()
})


texts: Check if a string has all unique characters

texts:
This is a question from the book "Cracking the Coding Interview".

  Implement an algorithm to determine if a string has all unique
  characters What if you can not use additional data structures?

I can use std::map but in interview they check logic. Suggest me some improvement for optimization.

#include <iostream>
#include <string>

class Strings
{
   static const int SIZE = 26;
   char alphabetL[SIZE] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                            'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                            'U', 'V', 'W', 'X', 'Y', 'Z'};

   char alphabetS[SIZE] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
                            'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
                            'u', 'v', 'w', 'x', 'y', 'z'};

  public:
    Strings()  = default;
    ~Strings() = default;

    bool isAllUnique(std::string&);

  private:
    std::string toLower(std::string&);
};

std::string Strings::toLower(std::string& str)
{
    for (int i = 0; i < str.length(); i++)
    {
        for (int j = 0; j < SIZE; j++)
        {
            if (str[i] == alphabetL[j])
            {
                str[i] = alphabetS[j];
            }
        }
    }
    return str;
}

bool Strings::isAllUnique(std::string& str)
{
    int count[SIZE];
    for (int k = 0; k < SIZE; k++)
    {
        count[k] = 0;
    }
    str = toLower(str);
    for (int i = 0; i < str.length(); i++)
    {
        for (int j = 0; j < SIZE; j++)
        {
            if (str[i] == alphabetS[j])
            {
                count[j] = count[j] + 1;
                if (count[j] > 1)
                {
                    return false;
                }
                break;
            }
        }
    }
    return true;
}

int main()
{
    Strings obj;
    std::string str;
    std::cout << "Enter String\n";
    std::getline(std::cin, str);
    bool res = obj.isAllUnique(str);
    if (res == true)
    {
        std::cout << "There are unique characters in string\n";
    }
    else
    {
        std::cout << "There are no unique characters in string\n";
    }
}


texts: Copying one dimensional array bottom to top

texts:
I want to convert a one dimensional array to a two dimensional array with the following conditions and have followed the code from this question - https://stackoverflow.com/questions/1817631/iterating-one-dimension-array-as-two-dimension-array. The 2-dimensional array has to be copied from the one dimensional array and written bottom to top. The second condition is that while the 1-dim array is being copied bottom to top the first row and the last column of the original 1-dimensional array must not appear in the two dimensional array if one were to visualize the 1-dim as a 2-dim array.

int maxrowIndex = rows-1;
for (int row = 0; row < rows; row++)
    {
        for (int column = 0; column < columns ; column++)
            {
               twodim[row][column] = onedim[maxrowIndex*columns+column];

            }
        maxrowIndex--;
    }

Here is the second code

int maxrowIndex = rows-1;
for (int row = 0; row < rows-1; row++)
    {
        for (int column = 0; column < columns-1 ; column++)
            {
               twodim[row][column] = onedim[maxrowIndex*columns+column];

            }
        maxrowIndex--;
    }

Did I get it right ? Is there any way I can improve the code ?


texts: Django template for "no more discount codes" and "expired discount code" situations

texts:
I have the following code in my Django template. It's a bit repetitive. I wonder if that's good the way I wrote it, or if you would combine these two 'if'-statements into one somehow?

{% elif discount.no_more_left %}

{{ discount.code }}

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            &times;
          </button>

{% trans "There are no more discount codes available. If you want to offer more, you can edit it and increase the available quantity." %}

          <button type="button" class="btn btn-secondary" data-dismiss="modal">{% trans "Close" %}</button>

{% elif discount.is_expired %}

{{ discount.code }}

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            &times;
          </button>

{% trans "This discount code is expired. If you want to extend it, you can edit it and change the expiration date." %}

          <button type="button" class="btn btn-secondary" data-dismiss="modal">{% trans "Close" %}</button>

{% endif %}


texts: Show/hide checkbox div on change and load

texts:
I'm working on a show/hide div with checkbox on change and on load.  I've come up with this so far:

jsFiddle

$(document).ready(function() {

var $cbtextbook = $('#in-product_category-14'),
    $cbimod = $('#in-product_category-15'),
    $mb1 = $('#mbtextbook'),
    $mb2 = $('#mbimod');

function tbmb() {
    if ($cbtextbook.is(":checked")) $mb1.show();
    else $mb1.hide();
}

function immb() {
    if ($cbimod.is(":checked")) $mb2.show();
    else $mb2.hide();
}
tbmb();
immb();

$cbtextbook.change(tbmb);
$cbimod.change(immb);

})

At the moment, I'm not worrying about dynamically changing elements (although I might in the future as I learn more).

Is there a much cleaner way to do this?  I did get pretty simple toggle to work, but that didn't take into account if the box was already checked on page load, and the div I wanted to show/hide could get off cycle (i.e. show when unclicked, hide when clicked) if it was already checked, so I came up with this overly verbose solution.  How can I pare this down?


texts:
Problem is to calculate median of numbers. My idea is :

Fill array of integer with numbers using Arraymake() function
copy the address into a pointer created in main() function
pass that array to Median() function and calculate that median

Code:

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

    int* Arraymake(size_t);//Function for creating array of numbers.
    void  Median(size_t ,int* );//Function for calculate the median.

    int main(int argc, char **argv)
    {
        size_t count;//Size of the list of numbers.
        puts("Size of the list:");
        scanf("%Iu",&count);
        int *ArResult=Arraymake(count);//Result of the first function
        Median(count,ArResult);
        free(ArResult);
        return 0;
    }

    int* Arraymake(size_t ln)   //ln~lenght
    {
        int* Array=(int*) malloc(ln*sizeof(int));
        int number ,i; //numbers filling the array

        puts("Please input numbers.\n");

        for(i=0;i<(ln);i++)
            {
                scanf("%i", &number);
                Array[i]=number;
            }
            return Array;
    }

    void  Median(size_t ln,int* Array)
    {
        float median;

        if((ln)%2==0)
            {
                    median= (Array[(ln)/2]+Array[(ln/2 )-1] )/2;
                    printf("%f",median);

            }
        else
            {
                    median= Array[((ln-1)/2)];
                    printf("%f",median);
            }
}

I want to find a way to optimize my variables and make my code more self-documented? How can I improve my code?


texts: Automatically indent a whole block of text into str.format

texts:
I wondered if there was any better way of doing so.

I had a hard time figuring it out (it seemed nobody else already tried to do so).

import re
import string

class BetterFormat(string.Formatter):
    """ Introduce better formatting """

    def parse(self, format_string):
        """ Receive the string to be transformed and split its elements to facilitate the actual replacing """

        # Automatically counts how many tabs are before the {} then automatically adds the new rule (defined in format_field)
        return [(before, identifiant, str(len(re.search('\t*$', before).group(0))) + '\t' + (param if param is not None else ''), modif) for before, identifiant, param, modif in super().parse(format_string)]

    def format_field(self, v, pattern):
        """ Receive the string to be transformed and the pattern according which it is supposed to be modified """

        # Hacky way to remove a dynamic sequence of characters ([0-9]+\t) and returning it

        sharedData = {'numberOfTabs': 0}

        def extractTabs(pattern):
            sharedData['numberOfTabs'] = int(pattern.group(0)[:-1]) # Save the data that will be erased
            return "" # This will erase it

        pattern = re.sub('[0-9]+\t', extractTabs, pattern)

        if sharedData['numberOfTabs']: # If there are tabs to be added
            v = (sharedData['numberOfTabs'] * '\t').join(v.splitlines(True))

        return super().format_field(v, pattern)

css = """
/* Some multi-lines CSS
All automatically indented */
"""

print(BetterFormat.format("""
<html>
    <head>
        <style type="text/css">
            {css}
        </style>
    </head>
    <body>
        <!-- Whatever -->
    </body>
</html>""",
    css=css
 ))

 # Output
 <html>
    <head>
        <style type="text/css">
            /* Some multi-line CSS
            All automatically indented */
        </style>
    </head>
    <body>
        <!-- Whatever -->
    </body>
</html>

Otherwise, previously I had to do this:

# […]

print(""" […]
            {css}
[…]""".format(css='\t\t\t'.join(css.splitlines(True)))
)

And just so you better understand, I first only implemented BetterFormat.format_field, then I was able to do that, but I was still required to count the number of tabulations myself:

# […]

print(""" […]
            {css:3\t}
[…]""".format(css=css)
)


texts:
Is the code below safe to create unique ids for objects?

I will create new yoga classes and need to have a unique id for each class. I made this small piece of code to generate the id numbers.

Regarding specifically the uniqueIdCreatorHandler method, would this solution incur in bad performance, or is it just far from elegant?

what would you say?

CodeSandBox here

The code is also presented as per below:

import React from "react";

export default class App extends React.Component {
  state = {
    id: "",
    ids: [{ id: 7 }, { id: 14 }]
  };

  uniqueIdCreatorHandler = () => {
    let ids = [...this.state.ids];
    let highestId = 0;
    if (ids.length > 0) {
      highestId = ids
        .map(value => {
          return value.id;
        })
        .reduce((a, b) => {
          return Math.max(a, b);
        });
    }
    let newId = highestId + 1;
    ids.push({ id: newId });
    this.setState({ ids: ids });
  };

  idDeleterHanlder = currIndex => {
    let ids = this.state.ids;
    ids.splice(currIndex, 1);
    this.setState({ ids: ids });
  };

  render() {
    let ids = this.state.ids.map((id, index) => {
      return (

 this.idDeleterHanlder(index)} key={id.id}>
          id:{id.id}

      );
    });

    return (

        <button onClick={this.uniqueIdCreatorHandler}>Push new id</button>

all ids below:

        {ids}

    );
  }
}


texts:
I am generating co-occurrence matrix (2000X2000) in Python.

Vocab is a list of the 2000 top words in corpus. It does not contain all words in corpus.
Corpus is a Pandas dataframe of 30000 (rows) sentences.
An example of a single row in the corpus:

  the energy classroom high the room filled scholars eager learn they embarking learning journey unlike no these scholars asked learn time rapidly changing technology communication as teacher job give tools successful our school special always looking ways give students best education possible my 4th grade students counting provide tools necessary success i want keep love learning alive giving students access technology critical success 21st century learning environment our school 1 3 ratio ipads kids we use variety apps allow kids collaborate build critical thinking skills even though ipads keyboard ipad cumbersome difficult kids use therefore i asking 15 keyboards plug ipads having wired keyboard allows kids practice keyboarding skills standard collaborate others effectively utilize technology accesskeyboards enhance collaboration choice critical thinkin

My code is currently taking 120s per iteration and 364 hours to complete run.
I am running this code in Google Colab with 25GB RAM.

The code works fine with small data like 10 row corpus and 5 word vocab.
Is there a better way to complete this task or speed up this process?

tqdm is required because if the code runs for longer than 12 hours, which it is, then it gets disconnected from Google Colab.

coocur_matrix = np.zeros((len(voca), len(voca)),np.float64)

#python
from tqdm import tqdm

window_size=5
corpus=corpu1
vocab = voca

for word1 in tqdm(vocab):
  for word2 in vocab:
    for sent in corpus:
      doc_tokens = []
      doc_tokens=sent.split()

      p1= [i for i in range(len(doc_tokens)) if doc_tokens[i] == word1]
      p2= [i for i in range(len(doc_tokens)) if doc_tokens[i] == word2]
      for k in p1:
        print(9)
        for l in p2:
          if (abs(l-k)<=window_size):
            if(word1!=word2):
              coocur_matrix[vocab.index(word1),vocab.index(word2)] += 1

print(coocur_matrix)


texts:
I have some buttons on an Excel report. 2 in particular are for posting all Budget numbers to the report and posting the Actual numbers. I currently have 2 separate subs, one assigned to each button.

Public Sub PostAllActual()
  Dim sheet As Worksheet
  Dim rFind As Range

  For Each sheet In ActiveWorkbook.Worksheets                       'Cycle through all of the sheets
    If sheet.Name <> "Index" Then                                   'Skip the Index sheet
      'Search for the Index row in Col A
      Set rFind = sheet.Cells.Find("Index", [H2], xlValues, xlWhole, xlByColumns, xlNext)
      If rFind Is Nothing Then                                      'Did we find the Index row?
        'Not Found - ORatio sheet
      Else                                                          'Found
        PostNumbers sheet, 37, "I"                                  'Procedure to copy numbers to the YTD
      End If
    End If
  Next sheet                                                        'Move to the next sheet
  Beep                                                              'Auditory notification of completed process
End Sub

Public Sub PostAllBudgets()
  Dim sheet As Worksheet
  Dim rFind As Range

  For Each sheet In ActiveWorkbook.Worksheets                       'Cycle through all of the sheets
    If sheet.Name <> "Index" Then                                   'Skip the Index Sheet
      'Search for the Index row in Col A
      Set rFind = sheet.Cells.Find("Index", [H2], xlValues, xlWhole, xlByColumns, xlNext)
      If rFind Is Nothing Then                                      'Did we find the Index row?
        'Not Found - ORatio sheet
      Else                                                          'Found
        PostNumbers sheet, 21, "H"                                  'Procedure to copy the numbers to the YTD
      End If
    End If
  Next sheet                                                        'Move to the next sheet
  Beep                                                              'Auditory notification of completed process
End Sub

Do I really save anything by reducing these to simple sub calls on the button click, and passing in the 2 parameters like this?

Public Sub PostAllBudgets()
  PostAllNumbers 21, "H"
End Sub

Public Sub PostAllActual()
  PostAllNumbers 37, "I"
End Sub

Public Sub PostAllNumbers(ByVal iRow as Integer, ByVal sCol as String)
  Dim sheet As Worksheet
  Dim rFind As Range

  For Each sheet In ActiveWorkbook.Worksheets                       'Cycle through all of the sheets
    If sheet.Name <> "Index" Then                                   'Skip the Index Sheet
      'Search for the Index row in Col A
      Set rFind = sheet.Cells.Find("Index", [H2], xlValues, xlWhole, xlByColumns, xlNext)
      If rFind Is Nothing Then                                      'Did we find the Index row?
        'Not Found - ORatio sheet
      Else                                                          'Found
        PostNumbers sheet, iRow, sCol                                  'Procedure to copy the numbers to the YTD
      End If
    End If
  Next sheet                                                        'Move to the next sheet
  Beep                                                              'Auditory notification of completed process
End Sub


texts:
Learn You a Haskell explains the unwords function.

  $unwords ["hey","there","mate"]
    "hey there mate"

Here's my implementation.

unwords' :: [String] -> String
unwords' [] = []
unwords' (x:xs)
  | null xs   = x
  | otherwise = x ++ " " ++ unwords' xs

Is there a possible implementation with fold? I tried the following, but the " " got appended to the end.

$foldr (\x acc -> x ++ " " ++ acc) [] ["hey", "there", "mate"]
"hey there mate "

Also, how can I append a String([Char]) to another String without ++?

Lastly, please critique in general.


texts: Finding products of all other members of an array

texts:
I had the following interview question: Given an array of integers, for each member of the array find the product of all the other members of the array.  So for instance, if you have this array:

{3, 1, 2, 0, 4}

you should end up with this:

{0 0 0 24 0}

I wrote this code which uses two loops, but I couldn't come up with a solution with just one loop.  Can anyone help me?

public int[] findProducts(int[] arr) {
    int[] products = new int[arr.length];

    for (int i = 0; i < arr.length; i++) {
        int product = 1;

        for (int j = 0; j < arr.length; j++) {
            if (i != j) {
                product *= arr[j];
            }
        }

        products[i] = product;
    }

    return products;
}


texts: On right click draw triangle to the canvas

texts:
This is a simple program that using easelJS adds functionality to the right click, when the right mouse button is clicked a triangle is drawn to the screen. I am just wanting to get the opinions of others on my coding style and how it could be improved.

body{
    margin: 0;
    background-color: #d3d3d3;
    font-family: Sans-Serif;
}

h1{
    font-weight: 100;
    text-align: center;
}

canvas{
    display: block;
    margin: auto;
    background-color: #ffffff;
    border: solid 1px #000000;
}
<!DOCTYPE html>

        <title>Draw Triangle</title>
        <link rel="stylesheet" href="styles.css"/>

Right click to draw a Triangle to the canvas

        <canvas id="myCanvas" width="900" height="700"></canvas>


texts:
This was just an experiment to see if it was possible to build a stateless builder in ES6. I was able to do it, but when I took it a step further I got stuck trying to DRY it out.

In this case, we have a MoveableBuilder and a ParticleBuilder. A Particle is a Moveable, so the ParticleBuilder could reuse a lot of the code from the MoveableBuilder. Unfortunately, I haven't been able to figure out how to combine the two functions in an elegant way.

function ParticleBuilder(coordinates = [], vector = [], lifespan = 255, decay = 1) {
  const self = this;

  this.at = (...coordinates) =>
    new self.constructor(coordinates, vector, lifespan, decay);

  this.facing = (...vector) =>
    new self.constructor(coordinates, vector, lifespan, decay);

  this.lifespan = (lifespan) =>
    new self.constructor(coordinates, vector, lifespan, decay);

  this.decay = (decay) =>
    new self.constructor(coordinates, vector, lifespan, decay);

  this.build = () => Object.freeze({
    coordinates: coordinates,
    vector: vector,
    lifespan: lifespan,
    decay: decay
  });
}

function MoveableBuilder(coordinates = [], vector = []) {
  const self = this;

  this.at = (...coordinates) => new self.constructor(coordinates, vector);

  this.facing = (...vector) => new self.constructor(coordinates, vector);

  this.build = () => Object.freeze({
    coordinates: coordinates,
    vector: vector
  });
}

console.info(new MoveableBuilder().at(1,1).facing(2,1).build());

console.info(new ParticleBuilder().at(1, 1).build());

What I had trouble with is how to reuse the at and facing methods within the ParticleBuilder. Granted, since the signatures of both builders is different, it might not be the correct thing to do. However, I figured I could elicit the community for feedback on this.


texts: Converting a string to a corresponding type in JavaScript

texts:
I need to convert a string value to its primitive type in JavaScript. Other values that are not of type String should just be returned.

Example:

String '34' should be converted to 34
String '34px' should be kept as '34px'
true should return true
'true' should return true

Here is a working example (please look at console).

I would like to know:

If there is any better way to write the same function, in term of performance.
If I missed some type or any other issues.

function convert(value) {
    var result = value;
    if (typeof value === 'string') {
        // check if it is a empty character
        value.trim();
        if (value.length > 0) {
            if (/\S/.test(value)) {
                if (value === 'true') {
                    result = true;
                } else if (value === 'false') {
                    result = false
                } else if (!isNaN(value)) {
                    result = new Number(value);
                }
            }
        }
    }
    return result;
}


texts:
I have 2 alternatives for executing recurring tasks in ASP.NET MVC.

We just need to add some code in Global.asax

First alternative:

private static void ThreadSendNextMail()
{
  while (true)
  {
    HostingEnvironment.QueueBackgroundWorkItem(async cancellationToken =>
    {
      using (var db = new EFDbContext())
      {
        try
        {
          //demo test for periodically tasks
          int paymentCount = await db.Payments.AsNoTracking().CountAsync();
          logger.Info(paymentCount);
        }
        catch (Exception ex)
        {
          logger.Error(ex.ToString());
        }
      }
    });
    Thread.Sleep(20000);
  }
}

private Thread mailThread { get; set; }

protected void Application_Start()
{
  //other code removed for clarity
  mailThread = new Thread(new ThreadStart(ThreadSendNextMail));
  mailThread.Start();
}

Second alternative:

private void AddTask(Action<string, object, CacheItemRemovedReason> target, int seconds)
{
  HttpRuntime.Cache.Insert(target.Method.Name + DateTime.Now.ToString(), seconds, null, DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, new CacheItemRemovedCallback(target));
}

public void SendNextMail(string key, object seconds, CacheItemRemovedReason reason)
{
  HostingEnvironment.QueueBackgroundWorkItem(async cancellationToken =>
  {
    using (var db = new EFDbContext())
    {
      try
      {
        //demo test for periodically tasks
        int paymentCount = await db.Payments.AsNoTracking().CountAsync();
        logger.Info(paymentCount);
      }
      catch (Exception ex)
      {
        logger.Error(ex.ToString());
      }
    }
  });

  AddTask(SendNextMail, Convert.ToInt32(seconds));
}

protected void Application_Start()
{
  //other code removed for clarity

  //Periodically tasks
  AddTask(SendNextMail, 20);
}

I use .NET 4.5.2 and MVC 5.2. For logging I use NLog.

Both methods work perfectly (You can check this by watch log time in log file). Which is more preferable and better for performance, if I have many recurring tasks in the same time?

Do you see any improvement / issue?


texts: Connection Pool in Java 8 using Strategy and Factory Pattern

texts:
How can I improve the following code and features?
It is based on active911's C++ connection pool.

The full code and unit tests are here : https://github.com/spakai/connection_pool

the README which explains the code is here : https://github.com/spakai/connection_pool/blob/master/README.md

This project uses Strategy and Factory Design Pattern. This allows ConnectionPool class to be generic. The type of database supported is determined by the type of Factory object that is injected during runtime. The specific factory creates required specific connection class that contains the actual connection to the database. So for example , if you need a MySQL connection pool, pass in a MySQLJDBConnectionFactory object.

package com.spakai;

import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

public class ConnectionPool {

  private final ConcurrentLinkedQueue<JdbConnection> pool = new ConcurrentLinkedQueue<>();

  private final Map<JdbConnection,Instant> borrowed = new ConcurrentHashMap<>();

  private final JdbConnectionFactory factory;

  private final long leaseTimeInMillis;

  /**
   * Creates connection objects and pushes it into queue.
   * @param factory Used to create JDBConnection implementations.
   * @param poolSize Number of JDBConnection implementations to create.
   * @param leaseTimeInMillis How long the client can use the connection before it expires.
   */

  public ConnectionPool(JdbConnectionFactory factory, int poolSize, long leaseTimeInMillis) {
    for (int i = 0; i < poolSize; i++) {
      pool.add(factory.create());
    }

    this.factory = factory;
    this.leaseTimeInMillis = leaseTimeInMillis;
  }

  /**
   * Get a JdbConnection object either by the ones available in the queue or replace
   * the first expired connection. When a connection is given to a client, it is tagged with
   * the current time. This enables us to check the duration it has been out and replace if
   * required.
   * @return JDBConnection This contains the actual jdbc connection object to db.
   * @throws ConnectionPoolException Throws if no available connections
   */

  public JdbConnection borrow() throws ConnectionPoolException {
    if (pool.size() > 0) {
      borrowed.put(pool.peek(),Instant.now());
      return pool.remove();
    } else {
      return createReplacementIfExpiredConnFound();
    }
  }

  /**
   * Return a JdbConnection object back to the pool.
   *
   * @param jdbConnection The object retrieved from the pool via borrow()
   * @throws ConnectionPoolException Throws if connection has already been
   *        returned or forced to expire
   */

  public void forfeit(JdbConnection jdbConnection) throws ConnectionPoolException {
    if (borrowed.containsKey(jdbConnection)) {
      borrowed.remove(jdbConnection);
      pool.add(jdbConnection);
    } else {
      throw new ConnectionPoolException("Connection already returned or forced to expire");
    }
  }

  private JdbConnection createReplacementIfExpiredConnFound() throws ConnectionPoolException {
    //check for the first expired connection , close it and create a replacement
    //throw exception if replacement is not possible

    Entry<JdbConnection, Instant> entry =
        borrowed.entrySet().stream()
                        .filter(e -> hasExpired(e.getValue()))
                        .findFirst()
                        .orElseThrow(() -> new ConnectionPoolException("No connections available"));

    entry.getKey().close();
    borrowed.remove(entry.getKey());
    JdbConnection newJdbConnection = factory.create();
    borrowed.put(newJdbConnection,Instant.now());
    return newJdbConnection;
  }

  private boolean hasExpired(Instant instant) {
    return (Duration.between(instant, Instant.now()).toMillis() > leaseTimeInMillis);
  }
}


texts:
I am new to async methods and am kinda confused how async is working so what i want for you to do is review this code and tell me does implementing async like this is meaningless
[Route("/Dev/ForceBufferUpdate")]
public async Task<IActionResult> BufferUpdate()
{
    bool isAdministrator = await Task.Run(() => {
        return Security.IsAdministrator(Request);
    });

    if(!isAdministrator)
            return View("Error", "You don't have permission!");

    await Task.Run(() => {
        LimitlessSoft.Buffer.Refresh();
    });

    return Redirect("/Dev");
}


texts: Finding the states with the three most populous counties

texts:
I just started to use Python and Pandas. My current solution to a problem looks ugly and inefficient. I would like to know how to improve it. Data file is Census 2010 can be viewed here

Question:

  Only looking at the three most populous counties for each state, what are the three most populous states (in order of highest population to lowest population)? Use CENSUS2010POP.
  This function should return a list of string values.

Current code

def answer_six():
    cdf = census_df[census_df['SUMLEV'] == 50]
    cdf = cdf.groupby('STNAME')
    cdf = cdf.apply(lambda x:x.sort_values('CENSUS2010POP', ascending=False)).reset_index(drop=True)
    cdf = cdf.groupby('STNAME').head(3)
    cdf = cdf.groupby('STNAME').sum()
    cdf = cdf.sort_values('CENSUS2010POP', axis=0, ascending=False).head(3)
    return list(cdf.index)


texts: Java game that generates and compares random numbers, looking for matches

texts:
I have written some Java code for a school assignment. It is a game, and it works as follows:

The game makes 4 random numbers, all different, as the users ticket.
It then generates 4 other random numbers, again all different, to compare it to. If they match, you win. If they don't match, then you lose.

A = random 0-9
B = random 0-9
C = random 0-9
D = random 0-9

A Cannot be equal to B / C / D
B Cannot be equal to A / C / D
C Cannot be equal to A / B / D
D Cannot be equal to A / B / C

Here is the code:

import java.util.Random;
import java.util.Scanner;

public class Lottery {

   public static void main(String[] args) {

      Scanner scan = new Scanner(System.in);

      System.out.println("Lottery Game");

      Random rand = new Random();
      // Creating the four individual balls
      int ball1 = 0;
      int ball2 = 0;
      int ball3 = 0;
      int ball4 = 0;
      int guess1 = 0;
      int guess2 = 0;
      int guess3 = 0;
      int guess4 = 0;

      // THIS IS THE USERS TICKET NUMBER

      System.out.println("Generating Ticket");

      guess1 = rand.nextInt(10);
      guess2 = rand.nextInt(10);
      guess3 = rand.nextInt(10);
      guess4 = rand.nextInt(10);

      do {

          guess1 = rand.nextInt(10);
          guess2 = rand.nextInt(10);
          guess3 = rand.nextInt(10);
          guess4 = rand.nextInt(10);

      if ( guess1 == guess2 || guess1 == guess3 || guess1 == guess4 ) {
          guess1 = rand.nextInt(10);
      }
      if ( guess2 == guess3 || guess2 == guess4 ) {
          guess2 = rand.nextInt(10);
      }
      if ( guess3 == guess4 ) {
          guess3 = rand.nextInt(10);
      }

      } while (guess1 == guess2 || guess2 == guess3 || guess3 == guess4 || guess4 == ball1);

      System.out.println(guess1 + " " + guess2 + " " + guess3 + " " + guess4);

      System.out.println("Are you happy with the selected numbers?");

      int confirmation = 0;

      System.out.println("Please Type '1' For 'YES' Or '2' For 'NO");

      confirmation = scan.nextInt();

      System.out.println(confirmation);

      if (confirmation == 1) {

          ball1 = rand.nextInt(10);
          ball2 = rand.nextInt(10);
          ball3 = rand.nextInt(10);
          ball4 = rand.nextInt(10);

          do {

              ball1 = rand.nextInt(10);
              ball2 = rand.nextInt(10);
              ball3 = rand.nextInt(10);
              ball4 = rand.nextInt(10);

          if ( ball1 == ball2 || ball1 == ball3 || ball1 == ball4 ) {
              ball1 = rand.nextInt(10);
          }
          if ( ball2 == ball3 || ball2 == ball4 ) {
              ball2 = rand.nextInt(10);
          }
          if ( ball3 == ball4 ) {
              ball3 = rand.nextInt(10);
          }

          } while (ball1 == ball2 || ball2 == ball3 || ball3 == ball4 || ball4 == ball1);

          System.out.println("The Winning Numbers Are As Follows...");
          System.out.println(ball1 + " " + ball2 + " " + ball3 + " " + ball4);

          if ( ball1 == guess1 &&  ball2 == guess2 &&  ball3 == guess3 &&  ball4 == guess4) {
              System.out.println("Congratulations! You've Won £1,000,000!");
              System.exit(0);
          }
          else {
              System.out.println("Unfortunately, You Did Not Win. Better Luck Next Time!");
              System.exit(0);
          }

      }
      else if (confirmation == 2) {
          System.out.println("Exiting Game, Thanks for playing!");
      }
      else {
          System.out.println("ERROR");
      }

      }

   }

Specifically, I would like to improve the algorithm that I've used here. I don't think it is very elegant, even though it does work.

I'm also interested in other ways that my code can be improved. I would appreciate any suggestions.


texts: Callback pattern for handling socket response

texts:
I am in the process of learning go and am coming from a PHP, JS, and Nodejs background.

I created a package that is a client which connects to a socket server and processes the data received from the server.  I am using a callback pattern and am wondering if this is frowned upon in the Go community.  Here are the relevant code snippets:

// SocketClient allows handles the socket connection to a server
type SocketClient struct {
    Host string
    Path string
    conn *websocket.Conn
}

// SocketResponse function callback for data from socket
type SocketResponse func(res []byte, err error)

// Connect create the connection with the host
func (sc SocketClient) Connect(cb SocketResponse) {
    interrupt := make(chan os.Signal, 1)
    signal.Notify(interrupt, os.Interrupt)

    u := url.URL{Scheme: "wss", Host: sc.Host, Path: sc.Path}

    var err error
    sc.conn, _, err = websocket.DefaultDialer.Dial(u.String(), nil)

    if err != nil {
        cb(nil, err)
    }

    defer sc.conn.Close()

    done := make(chan struct{})

    // anonymous function call
    go func() {
        defer sc.conn.Close()
        defer close(done)
        for {
            _, message, err := sc.conn.ReadMessage()
            if err != nil {
                cb(nil, err)
            }
            cb(message, nil)
        }
    }()

    // ...
}

And then in another file I actually initialize SocketClient and call Connect...

sc.Connect(func(res []byte, err error) {
    // handle the response
})


texts:
I'm making my first steps in ELisp programming and I want to know is there a better solution for this problem:

I have a file with two columns, that are separated by one or more spaces, ex.:

One 1
Two 2
Three 3
Four  4

I'd like to make some alignment (columns are separated by at least two spaces):

One    1
Two    2
Three  3
Four   4

My solution is:

(defun align-config-file ()
  "Align two-columned config file in a pretty manner"
  (interactive)
  (let* ((strings (split-string (buffer-string) "\n"))
         (data (mapcar (lambda (line) (split-string line " ")) strings))
         (first-col-lengths (mapcar (lambda (item) (length (car item))) data))
         (first-col-length (+ 2 (apply 'max first-col-lengths))))
    (erase-buffer)
    (while data
      (let* ((this-line (car data))
             (first-col (car this-line))
             (last-col (car (nthcdr (- (length this-line) 1) this-line)))
             (amount-of-spaces (- first-col-length (length first-col)))
             (spaces-inserted 0))
        (insert first-col)
        (while (< spaces-inserted amount-of-spaces)
          (insert " ")
          (set 'spaces-inserted (+ 1 spaces-inserted)))
        (insert last-col)
        (insert "\n"))
      (set 'data (cdr data)))))

It is not beautiful, but it works. Is it ok?


texts: Convert all dates in an array to date format

texts:
I'm returning an array containing dates (and other things) from an API, then looping through the array on the front end to convert them into dates

The backend uses Node.Js and queries a mySql database with the mySql module:

pool.getConnection(function(err, conn) {
  conn.query('SELECT * FROM myData’, function(err, result) {
    if (result) {
      res.json(result);
    }
    conn.release();
  });
});

An Angular.js front end accesses the Express API.

var _getCases = function() {
  return $http.get('/api/case');
};

But the dates are all strings.  Here’s an example of what's received in Angular:

[
  {
    id: 1,
    fruit: “apple”,
    createdOn: "2016-09-02T23:00:00.000Z"
  },
  {
    id: 2,
    fruit: “banana”,
    createdOn: "2016-09-11T23:00:00.000Z”
  },
  {
    id: 3,
    fruit: “cherry”,
    createdOn: "2016-09-13T23:00:00.000Z"
  },
]

I'm converting all the dates to strings in a loop but this seems inefficient.  Is there a better way?

var a = $http.get('/api/case');

for(var i in a){
  a[i].createdOn = new Date(a[i].createdOn);
};

return a;


texts: Is there some way of taking advantage of code reuse in this example?

texts:
I am implementing a set, using an array as the backend.

Here is how I declared it (and some method implementations):

public class Set {
            private int[] elementData;
            private int size;
               ....
          public void remove(int value) {
             for(int count = 0; count < size; count ++) {
                    if(elementData[count] == value) {
                        elementData[count] = elementData[size - 1];
                        size --;
                        break;
                    }
              }
           }
          public boolean contains(int value) {
             for(int count = 0; count < size; count ++) {
                 if(elementData[count] == value) {
                    return true;
                 }
            }
            return false;
        }
   }

I tested these methods with the JUnit testing framework and they both ran fine and worked. However I am trying to improve code reuse because I see the same iteration and a test condition in both methods, that is

for(int count = 0; count < size; count ++) {
            if(elementData[count] == value) {

But both methods perform different operations if they make it into a conditional block, one returns while the other moves elements and then breaks. Is there a way to reduce code redundancy here or is that not necessary?


texts:
I am trying to learn how to write clean HTML5 code and I came across a sidebar.

I need to get something like this:

My code:

Naujienos

2015-09-20

2013-10-30

Am I going in the right direction? Any feedback is appreciated.


texts: Removing duplicates without using a temporary buffer

texts:
This question is from Cracking the Coding Interview and in this question they have asked to solve without using temporary buffer.

I have used Iterator interface. Can I use it or need to re-implement it?

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;

public class WithoutExtraSpace {

    public static void main(String[] args) {

        LinkedList<Integer> list = new LinkedList<Integer>();
        list.add(9);
        list.add(1);
        list.add(3);
        list.add(2);
        list.add(5);
        list.add(7);
        list.add(8);
        list.add(3);
        list.add(1);
        list.add(8);
        System.out.println(list);
        Collections.sort(list);
        System.out.println(list);

        Iterator<Integer> itr = list.iterator();
        if (itr.hasNext()) {
            Integer previous = itr.next();
            while (itr.hasNext()) {
                Integer current = itr.next();
                if (previous.equals(current)) {
                    itr.remove();
                }
                previous = current;
            }
        }
        System.out.println(list);
    }
}


texts:
I want to display a table similar to this:

This table is generated from three tables depending on the student ID:

I don't want the table to depend on fixed values. For example, I should be able to add a subject or exam in the database and see the changes reflected in the table without touching the code. Any suggestions?

<?

$con = mysql_connect("localhost","root","123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
 }
mysql_select_db("test", $con);

////////////////////////

///////////////// Select the exams and put it in array
$ex = mysql_query("SELECT * FROM exams");
$dc=1;
while ($rowex= mysql_fetch_array($ex)){
$exn[$dc]=$rowex['Exam_Title'];
$exid[$dc]=$rowex['Exam_ID'];
$dc++;
}

/////////////////////////// Select the subjects and put it in array
$sj = mysql_query("SELECT * FROM subjects");
$dsj=1;
while ($rowsj= mysql_fetch_array($sj)){
$sjn[$dsj]=$rowsj['Subj_Title'];
$sjid[$dsj]=$rowsj['Subj_ID'];
$dsj++;
}

////////////////Select the student marks and put it in array with subject id and exam id

$result = mysql_query("SELECT * FROM stu_marks");
while ($row= mysql_fetch_array($result)){
$arr[$row['Subj_ID']][$row['Exam_ID']]=$row['Grade'];

}
/////////////////////// count the exams and the subjects to draw the table
$exc=count($exn);
 $sjc=count($sjn);
?>

   <?
///////// display subjects in table rows
for ($d=0;$d<=$sjc;$d++){

if ($d==0){
echo '-	';
}else{
echo '
'.$sjn[$d].'	';
}

///////// display exams in table head tds

for ($p=1;$p<=$exc;$p++){
if ($d==0){
 echo ' '.$exn[$p].'	';
}else{
?>

<?=$arr[$sjid[$d]][$exid[$p]]?>

 <?}
  }
  }?>


texts:
I'm coding a school project that involves MVC and threading.

This is my Main class. From there I launch the actual client.

public class Main {

    public static void main(String[] args) {

        Controller myController = new Controller();

        ScreenModel screenModel = new ScreenModel();

        ChessBoardModel chessBoardModel = new ChessBoardModel();

        ChessBoard chessBoardView = new ChessBoard(myController);

        View myView = new View(myController, chessBoardView);

        chessBoardModel.addObserver(chessBoardView);

        screenModel.addObserver(myView);

        myController.addModel(screenModel);

        myController.addChessBoardModel(chessBoardModel);

        myController.addView(myView);

    }

}

Is this too messy? I essentially have one model, the ScreenModel, that handles moving back and forth between screens and another model which handles the Chess Board. Here's my controller:

public class Controller {

    ScreenModel model;
    View view;
    User user = new User();
    ClientSocketManager csm;
    ChessBoardModel chessBoardModel;

    /**
     * Called when the user logs in.
     */

    public Controller() {

        csm  = new ClientSocketManager();

        csm.connect("localhost", 4444);

    }

    public void login() {

        //Create userdata object upon login.

        model.handleLogin();

    }

    /**
     * Called when the user creates a game (from the main menu or the join game/games in progress screens)
     */

    public void createGame() {

        model.handleCreateGame();

    }

    /**
     * Called when the user clicks on the Join Game button in the main menu.
     */

    public void joinGameButton() {

        model.handleJoinGameButton();

    }

    /**
     * Called when the user chooses a game clicks on the "join" button.
     */

    public void joinGame() {

        model.handleJoinGame();

    }

    /**
     * Called when the user clicks on the "My Games in Progress" button.
     */

    public void myGamesInProgress() {

        model.handleMyGamesInProgress();

    }

    /**
     * Called when user cancels joining a new game or joining a game in progress.
     */

    public void cancel() {

        model.handleCancel();

    }

    /**
     * Handles making a move from the chess board.
     * @param from   The non-empty from square.
     * @param to     The non-empty to square.
     */

    public void makeMove(Cell from, Cell to) {

        chessBoardModel.handleMakeMove(from,to);

    }

    /**
     * Methods related to the Chess Board game in progress
     */

    /**
     * Called when the user clicks on the "back" button inside the Chess Board screen.
     */

    public void back() {

        model.handleBack();

    }

    /**
     * Chess Board Screen methods below
     */

    public void offerDraw() {

        chessBoardModel.handleOfferDraw();

    }

    public void resign() {

        chessBoardModel.handleResign();

    }

    /**
     * Handles flipping the board from the Chess Board Screen
     */

    public void flipBoard() {

        chessBoardModel.handleFlipBoard();

    }

    /**
     * Methods for adding models and views.
     * @param m
     */

    public void addModel(ScreenModel m){

        this.model = m;
        m.setUser(user);

    }

    public void addChessBoardModel(ChessBoardModel c) {

        this.chessBoardModel = c;
        c.setUser(user);

    }

    public void addView(View v){

        this.view = v;

    }

}

Is the controller the appropriate place for the ClientSocketManager, or should it be placed inside the model? What do you think of the rest of my controller?


texts: Conditional aggregate whilst constructing array

texts:
I have the following snippet of code which gets a load of time intervals (every hour, every 2 hours etc), then groups the results for each of the intervals (e.g, the max value for each hour).  This data needs to go into an array (which will be sent to a Chart).

The user can select if they wish to group my Min, Max or Average.

At the moment I have a switch statement that has the same code in each branch except the Max/Min/Average bit at the end.

Can I avoid duplicating the code whilst still having the Min/Max/Average conditional?

The code as it is:

var vm = new MyViewModel();
var times = getTimeIntervals();
var results = getResults();

vm.GroupedData =
   times.Select(x =>
      new object[] {
         x.Start.ToInstant().Ticks,
         results.Data
             .Where(i => x.Intersects(i.Date))
             .Select(v => v)
             .DefaultIfEmpty()
             .Max(i => i == null ? 0m : decimal.Parse(i.Value))
             //.Min(i => i == null ? 0m : decimal.Parse(i.Value))
             //.Average(i => i == null ? 0m : decimal.Parse(i.Value))
   });

The code I'd like:

vm.GroupedData =
           times.Select(x =>
              new object[] {
                 x.Start.ToInstant().Ticks,
                 results.Data
                     .Where(i => x.Intersects(i.Date))
                     .Select(v => v)
                     .DefaultIfEmpty()
                     .If(Avg)
                         .Average(i => i == null ? 0m : decimal.Parse(i.Value))
                     .ElseIf(Max)
                         .Max(i => i == null ? 0m : decimal.Parse(i.Value))
                     .ElseIf(Min)
                         .Min(i => i == null ? 0m : decimal.Parse(i.Value))
           });


texts:
I've created a responsive nav but feel there's probably a more simpler way of doing it.

HTML

    toggle

Link

Link

Link

Link

Link

Link

Google

Link

Link

Link

CSS

ul {
    list-style: none;
    color: #000;
}

.main-nav ul li {
    display: inline;
    padding-left: 28px;
    float: right;
}

.menu-toggle {
    float: right;
}

.menu-side {
    background-color: #333;
    border-right: 1px solid black;
    color: white;
    position: fixed;
    top: 0;
    right: -231px;
    width: 210px;
    height: 100%;
    padding: 10px;
}

.menu {
    overflow-x: hidden;
    position: relative;
    right: 0;
}

.menu-open {
    right: 231px;
}

.menu-open .menu-side {
    right: 0;
}

.menu-side,
.menu {
    -webkit-transition: right 0.2s ease;
    -moz-transition: right 0.2s ease;
    transition: right 0.2s ease;
}

@media (min-width: 700px)  {
    .menu-side, .menu-toggle {
        display: none;
    }
}

    @media (max-width: 700px)  {

    .main-nav {
        display: none;
    }
}

There is some jQuery to action this but I'm not concerned with this at the moment. I'm aware that SASS may simplify this but I'm not comfortable with that yet.


texts:
I wrote a two player Noughts and Crosses game in Python 3, and came here to ask how I can improve this code.

import random
cell = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
board = '\n\t ' + cell[0] + ' | ' + cell[1] + ' | ' + cell[2] + '\n\t-----------\n\t ' + cell[3] + ' | ' + cell[4] + ' | ' + cell[5] + '\n\t-----------\n\t ' + cell[6] + ' | ' + cell[7] + ' | ' + cell[8]
def owin(cell):
    return cell[0] == cell[1] == cell[2] == 'O' or cell[3] == cell[4] == cell[5] == 'O' or cell[6] == cell[7] == cell[8] == 'O' or cell[0] == cell[3] == cell[6] == 'O' or cell[1] == cell[4] == cell[7] == 'O' or cell[2] == cell[5] == cell[8] == 'O' or cell[0] == cell[4] == cell[8] == 'O' or cell[2] == cell[4] == cell[6] == 'O'
def xwin(cell):
    return cell[0] == cell[1] == cell[2] == 'X' or cell[3] == cell[4] == cell[5] == 'X' or cell[6] == cell[7] == cell[8] == 'X' or cell[0] == cell[3] == cell[6] == 'X' or cell[1] == cell[4] == cell[7] == 'X' or cell[2] == cell[5] == cell[8] == 'X' or cell[0] == cell[4] == cell[8] == 'X' or cell[2] == cell[4] == cell[6] == 'X'
def tie(cell):
    return cell[0] in ('O', 'X') and cell[1] in ('O', 'X') and cell[2] in ('O', 'X') and cell[3] in ('O', 'X') and cell[4] in ('O', 'X') and cell[5] in ('O', 'X') and cell[6] in ('O', 'X') and cell[7] in ('O', 'X') and cell[8] in ('O', 'X')
print('\tNOUGHTS AND CROSSES\n\t\tBy Lewis Cornwall')
instructions = input('Would you like to read the instructions? (y/n)')
if instructions == 'y':
    print('\nEach player takes turns to place a peice on the following grid:\n\n\t 1 | 2 | 3\n\t-----------\n\t 4 | 5 | 6\n\t-----------\n\t 7 | 8 | 9\n\nBy inputing a vaule when prompted. The first to 3 peices in a row wins.')
player1 = input('Enter player 1\'s name: ')
player2 = input('Enter player 2\'s name: ')
print(player1 + ', you are O and ' + player2 + ', you are X.')
nextPlayer = player1
while not(owin(cell) or xwin(cell)) and not tie(cell):
    print('This is the board:\n' + board)
    if nextPlayer == player1:
        move = input('\n' + player1 + ', select a number (1 - 9) to place your peice: ')
        cell[int(move) - 1] = 'O'
        board = '\n\t ' + cell[0] + ' | ' + cell[1] + ' | ' + cell[2] + '\n\t-----------\n\t ' + cell[3] + ' | ' + cell[4] + ' | ' + cell[5] + '\n\t-----------\n\t ' + cell[6] + ' | ' + cell[7] + ' | ' + cell[8]
        nextPlayer = player2
    else:
        move = input('\n' + player2 + ', select a number (1 - 9) to place your peice: ')
        cell[int(move) - 1] = 'X'
        board = '\n\t ' + cell[0] + ' | ' + cell[1] + ' | ' + cell[2] + '\n\t-----------\n\t ' + cell[3] + ' | ' + cell[4] + ' | ' + cell[5] + '\n\t-----------\n\t ' + cell[6] + ' | ' + cell[7] + ' | ' + cell[8]
        nextPlayer = player1
if owin(cell):
    print('Well done, ' + player1 + ', you won!')
elif xwin(cell):
    print('Well done, ' + player2 + ', you won!')
else:
    print('Unfortunately, neither of you were able to win today.')
input('Press <enter> to quit.')


texts: Simple script to find the largest number palindrome

texts:
I have made a simple C# script that will find the largest palindrome made by the product of two numbers. These numbers will be between a minimum and maximum value, inputted by int.Parse(Console.ReadLine()). Is there a way to make this better?

It is brute force, however I tried to make it use fewer numbers if one combination gives a smaller palindrome. The numbers are generated in a for loop.

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

namespace ProjectEuler
{
    class Solution
    {
        static void Main( /*I am not sure what the point is for String args. If anybody can explain?*/ )
        {
            Console.Clear();
            Console.WriteLine("What would the maiximum value be for these numbers?");
            int max = int.Parse(Console.ReadLine());

            Console.WriteLine("\nWhat would the minimum value be for these numbers?");
            int min = int.Parse(Console.ReadLine());

            int largestNumb1 = 0;
            int largestNumb2 = 0;
            int generatedPalindrome = 0;

            for (int number1 = max; number1 >= min; number1--)
            {
                for (int number2 = max; number2 >= min; number2--)
                {
                    string generatedNumber = (number1 * number2).ToString();
                    if (IsPalindrome(generatedNumber))
                    {
                        if (int.Parse(generatedNumber) > generatedPalindrome)
                        {
                            generatedPalindrome = number1 * number2;
                            largestNumb1 = number1;
                            largestNumb2 = number2;
                            //This is mainly done to increase 'subtle' performance, by skipping numbers
                            //that will never give a larger number than the previous palindrome
                            number1--;
                            number2 = max;
                        }
                        else if (int.Parse(generatedNumber) < generatedPalindrome)
                        {
                            //This is mainly done to increase 'subtle' performance, by skipping numbers
                            //that will never give a larger number than the previous palindrome
                            number1--;
                            number2 = max;
                        }
                    }
                }
            }
            PrintAnswer(generatedPalindrome, largestNumb1, largestNumb2);
        }

        static bool IsPalindrome(string generatedNumber)
        {
            char[] answerChar = generatedNumber.ToCharArray();
            Array.Reverse(answerChar);
            string reversedString = new string(answerChar);

            if (generatedNumber == reversedString)
            {
                return true;
            }
            else
            {
                return false;
            }

        }

        static void PrintAnswer(int generatedPalindrome, int largestNumb1, int largestNumb2)
        {
            Console.Clear();
            if (generatedPalindrome != 0)
            {
                Console.WriteLine("Largest possible palindrome given limit: {0}\nNumbers used: {1} & {2}", generatedPalindrome, largestNumb1, largestNumb2);
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("Sorry, but no valid palindrome was generated given your values.\nWould you like to try again? (y)");
                if (Console.ReadLine() == "y")
                {
                    Main();
                }
                else
                {
                    return;
                }
            }
        }
    }
}