texts:
I am writing a GenericDeserializer for Apache Kafka. My class implements IDeserializer<T> from Confluent.Kafka.Net package. I need to supply a Deserialize method which has this signature, T Deserialize(ReadOnlySpan<byte> data, bool isNull, SerializationContext context). But I also need to use Deserializers class of Confluent because it implements some low level details such as decoding a big endian message from network as primitive types, as byte array, as UTF8 string etc. How can I simplify this method. One example of simplification may be removing the use of casts which I introduced to make the compiler happy.
My logic in this method is like this, use every supported type in already implemented Deserializers class. For other types that are not deserialized with the help of this class, use Json Serialization. Here is my code:
public class GenericDeserializer<T> : IDeserializer<T>
{
    public T Deserialize(ReadOnlySpan<byte> data, bool isNull, SerializationContext context)
    {
        var type = typeof(T);

        if (type == typeof(double))
        {
            var retVal = Deserializers.Double.Deserialize(data, isNull, context);

            return (T) (object) retVal;
        }
        if (type == typeof(float))
        {
            var retVal = Deserializers.Single.Deserialize(data, isNull, context);

            return (T) (object) retVal;
        }
        if (type == typeof(int))
        {
            var retVal = Deserializers.Int32.Deserialize(data, isNull, context);

            return (T) (object) retVal;
        }
        if (type == typeof(long))
        {
            var retVal = Deserializers.Int64.Deserialize(data, isNull, context);

            return (T) (object) retVal;
        }
        if (type == typeof(Null))
        {
            var retVal = Deserializers.Null.Deserialize(data, isNull, context);

            return (T) (object) retVal;
        }
        if (type == typeof(string))
        {
            var retVal = Deserializers.Utf8.Deserialize(data, isNull, context);

            return (T) (object) retVal;
        }
        if (type == typeof(byte[]))
        {
            var retVal = Deserializers.ByteArray.Deserialize(data, isNull, context);

            return (T) (object) retVal;
        }
        if (isNull)
        {
            return default;
        }

        return JsonSerializer.Deserialize<T>(data, new JsonSerializerOptions()
        {
            PropertyNameCaseInsensitive = true
        });
    }
}

Here is the source of Deserializers class from Confluent.Kafka
https://github.com/confluentinc/confluent-kafka-dotnet/blob/master/src/Confluent.Kafka/Deserializers.cs


texts:
I'm using this method and I would likely have a code review. Also, I have one concern and is that source.Count() is executing synchronously and I don't know how to make it async in this context.

public static class IQueryableExtensions
    {
        public static Task<PaginatedList<T>> ToPaginatedListAsync<T>(this IQueryable<T> source, int pageSize, int pageIndex = 1)
        {
            var count = source.Count();
            return
                source.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                .AsAsyncEnumerable()
                .Aggregate(new PaginatedList<T>(
                    totalCount: count,
                    pageSize : pageSize,
                    pageIndex: pageIndex), (list, x) => { list.Add(x); return list; });
        }

    }

    public class PaginatedList<T> : List<T>
    {
        private int pageIndex;
        private int pageSize;
        public PaginatedList(IEnumerable<T> collection, int totalCount, int pageSize, int pageIndex) : base(collection)
        {
            TotalCount = totalCount;
            PageSize = pageSize;
            PageIndex = pageIndex;
        }

        public PaginatedList(int totalCount, int pageSize, int pageIndex) : base()
        {
            TotalCount = totalCount;
            PageSize = pageSize;
            PageIndex = pageIndex;
        }

        public PaginatedList(int capacity, int totalCount, int pageSize, int pageIndex) : base(capacity)
        {
            TotalCount = totalCount;
            PageSize = pageSize;
            PageIndex = pageIndex;
        }

        public int PageIndex
        {
            get { return pageIndex; }
            private set
            {
                if (value <= 0) throw new ArgumentOutOfRangeException(nameof(PageIndex));
                pageIndex = value;
            }
        }

        public int PageSize
        {
            get { return pageSize; }
            private set
            {
                if (value <= 0) throw new ArgumentOutOfRangeException(nameof(PageSize));
                pageSize = value;
            }
        }

        public int TotalPages => (int)Math.Ceiling(TotalCount / (double)PageSize);

        public bool HasPreviousPage => PageIndex > 1;

        public bool HasNextPage => PageIndex < TotalPages;

        public int TotalCount { get; }
    }

This code and updates are available at: https://gist.github.com/Bartmax/5a55ff88413174d49301


texts: Cleanest way to write a callback that accepts a next sequence in javascript

texts:
I need to call multiple functions asynchronously before producing a result. In this case what are the possible improvements in the following code(also including other library like for promise etc.) ?

var k8Setup = function(userID ,next) {
  function createReplicationController(userID) {
  k8.ns(config.k8component.namespace).replicationcontrollers.get(userID, function(err, result) {
    if(err)
      k8.ns(config.k8component.namespace).replicationcontrollers.post({ body: k8component('replicationController', userID)}, function(err, result){
        if(err){
           console.log("Can't start replication controller for the user: " + userID);
           console.log(JSON.stringify(err, null, 2));
        }
        else
          getServicePort(userID);
        });
    else
      getServicePort(userID);
  });
}

function getServicePort(userID) {
  k8.ns(config.k8component.namespace).service.get(userID,function(err, result) {
    if(err){
      console.log("Can't find service for the user: " + userID);
      console.log(JSON.stringify(err, null, 2));
    }
    else
      console.log("Service for the user: " + userID + ' is running!!');
      next(result.spec.ports[0].nodePort);
    });
}

createReplicationController(userID);
}

k8Setup('user1', function(port){console.log('PORT:' +port);});


texts: Identify and extract URLs from text corpus

texts:
I'm working on a project that requires POS Tagging of paragraphs. The text contains lot of URLs which contain various punctuation marks such as . ?.  This affects the accuracy of the sentence tokenization.

So I decided to clean the data by removing/replacing all the URLs. And thought regular expressions would be handy in doing that. Remember, I want to match not just the domain name but the complete URL.

For example, in the below text,

Hey Mayur, We have successfully credited the cashback amount of INR 600 in your CITRUS wallet linked to mobile - 9130977755. Please download and rate our apps here - http://smarturl.it/ixigoapps Happy travelling! Team ixigo

I want the regex to match http://smarturl.it/ixigoapps

Here's what I came up with so far

https?:\/\/?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b[-a-zA-Z0-9@:%_\+.~#?&=\/]*

Right now, I'm not concerned about protocols other than http and https, but I would like to match URLs without http or https but start with www. Example: www.acttv.in

What do you think of my approach so far, and the regular expression?


texts: Generating lists of sequences of specified lengths

texts:
I'm writing a program that uses a Genetic Algorithm to "intelligently brute force" our schedule at work. We typically have issues with creating schedules, so I thought using my new GA library to tackle the problem would be a neat exercise.

One of the very first functions I wrote seems overly complex though. It works as intended, but I worry that it could be simplified by making use of higher-order looping constructs instead of a raw loop:

(defn cut-genes-into-day-blocks
  "Cuts the genes into blocks. Each block will have as many genes are there are shifts that day.
  shifts-per-day should be a list (whose length matches the period length) containing how many shifts exist for each day of the period.

  For example, if a period is 14 days, and there are 5 shifts on weekdays, and 2 shifts on weekends,
   shifts-per-day would be [5 5 5 5 5 2 2 5 5 5 5 5 2 2]."
  [genes shifts-per-day]
  (loop [rem-genes genes
         [n-shifts & rem-days] shifts-per-day
         acc []]

    (if n-shifts
      (let [[block rest-genes] (split-at n-shifts rem-genes)]
        (recur rest-genes
               rem-days
               (conj acc block)))

      acc)))

As the docs mention, the purpose of this function is to take a gene sequence, and cut it into blocks where each block has as many elements as there are shifts in that day. An example usage (using dummy genes created by range) is:

(let [shifts-per-day [5 5 5 5 5 2 2 5 5 5 5 5 2 2]
      total-shifts (reduce + 0 shifts-per-day)
      genes (vec (range total-shifts))]
  (cut-genes-into-day-blocks genes shifts-per-day))

[(0 1 2 3 4) ; <---- Each number represents a person working that day
 (5 6 7 8 9) ; <---- 5 different people/shifts on weekdays...
 (10 11 12 13 14)
 (15 16 17 18 19)
 (20 21 22 23 24)
 (25 26) ; <---- ... and 2 shifts on the weekends
 (27 28)
 (29 30 31 32 33)
 (34 35 36 37 38)
 (39 40 41 42 43)
 (44 45 46 47 48)
 (49 50 51 52 53)
 (54 55)
 (56 57)]

This function is overly chunky though and contains a few things that I've run into in the past that I'd like suggestions on:

The "deconstruct the head from tail, then check if the first element is valid" "pattern". I use it a lot in my code whenever I'm iterating over a list using loop. Use the rest operator to pop the first element off, then check if it's actually valid before using it.
The fact that the loop requires 3 "state variables" is unfortunate. It would be nice if the accumulator was implicit somehow. I know that using reduce over shifts-per-day would et rid of one of the bits of information needing to be maintained, but there are two accumulators in use here (acc and rem-genes), and I've found reducing when more than one accumulator is necessary to be very messy and not worth the trouble.
Any other tips that you think are worth mentioning would be appreciated.


texts:
Question

Recently I have tried to create a web scraping program to get data from google trends. It uses an RSS feed to do so. My question is as follows:

How can I improve my code such that it is more concise, efficient, and pleasing to a programmers eye? I would like to emphasise that I'm most concerned about if I've misused any functions, methods, or syntax in my code and if it could be 'cleaner'

Context

I'm not experienced at all. I'm doing this to learn.
Security isn't an issue since the program is running locally.

The code

"""Uses webscraping to retrieve html information from Google Trends for
parsing"""

# Imports

import time
import ssl
from requests import get
from bs4 import BeautifulSoup

# Url for request

url = "https://trends.google.com/trends/trendingsearches/daily/rss?geo=US"

# Used to create an unverified certificate.

ssl._create_default_https_context = ssl._create_unverified_context

class connection(object):

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

    def __call__(self):
        """Calculates the time taken to complete the request without any errors"""
        try:
            # Times the amount of time the function takes to complete
            global html
            start = time.time()
            html = get(url)
            self.f()
            end = time.time()
            time_taken = end - start
            result = print("the function {} took {} to connect".format(self.f.__name__, time_taken))
            return result
        except:
            print("function {} failed to connect".format(self.f.__name__))

@connection
def html_parser():
    """Parses the html into storable text"""
    html_unparsed = html.text
    soup = BeautifulSoup(html_unparsed, "html.parser")
    titles_unformatted = soup.find_all("title")
    traffic_unformatted = soup.find_all("ht:approx_traffic")
    # Indexes through list to make data readable
    titles = [x.text for x in titles_unformatted]
    traffic = []
    for x in traffic_unformatted:
        x = x.text
        x = x.replace("+","")
        x = x.replace(",", "")
        traffic.append(x)
    print(traffic, titles)
html_parser()

Output

['100000', '2000000', '2000000', '1000000', '1000000', '1000000',
'1000000', '500000', '500000', '500000', '200000', '200000', '200000',
'200000', '200000', '200000', '200000', '200000', '200000', '200000']
['Daily Search Trends', '23 and Me', 'NFL scores', 'Best Buy', 'Walmart
Supercenter', 'NFL', 'Saints', 'GameStop', 'JCPenney', 'Lion King 2019',
'Starbucks', 'Dollar General', 'Amazon Black Friday', 'Mike Posner',
'NFL games On Thanksgiving', 'McDonalds', 'Bath And Body Works Black
Friday', 'Old Navy Black Friday 2018', 'Kroger', 'NFL standings',
'Safeway']
the function html_parser took 1.0186748504638672 to connect

Concerns

Makes programmers cringe.

As someone relatively new to python and programming in general my worst fear is that this code gives someone else a headache or a laugh to look at. At the end of the day I just want to improve, so to reiterate: how can I make this code look better? Have I misused any functions?


texts:
I'm pretty new to Angular. I wrote a weather app and need my code reviewed. I especially need help on best practices for handling edge cases on the response from the JSON endpoint.

Here's the HTML:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <ion-pane>
        <ion-header-bar class="bar-calm">

Kansas City Weather

        </ion-header-bar>
        <ion-content>

                        Day {{ $index + 1 }}

                                {{ x.temp.day }} &#8451;

                                Max : {{ x.temp.max }} &#8451;

                                Min : {{ x.temp.min }} &#8451;

        </ion-content>
    </ion-pane>

Here's the app.js :

// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a  attribute in index.html)
// the 2nd parameter is an array of 'requires'
var app = angular.module('starter', ['ionic'])

    .run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar                  above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
    });
    })

      app.controller('apiController', function($scope, $http) {
    $http.get("http://api.openweathermap.org/data/2.5/forecast/daly?q=Kansas+City&mode=json&units=metric&cnt=10&appid=f6b7081abd94e66273817ed6b5ce95c7").then(function(response) {
        $scope.myData = response.data.list;
    });
});


texts:
I would like a more elegant solution for this problem, I think the FizzBuzzArrayBuilder class is not used properly. Also can those if statements be removed somehow?

Any suggestion on how to improve this by still using OOP is welcome.

Problem:

Given the array [1, 2, 3, 4, ... 100], print all the elements as follows:

if the element can be divided by 3 print: Fizz
if the element can be divided by 5 print: Buzz
if the element can be divided by both 3 and 5 print: FizzBuzz
else print the number

Output:
1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz ...

Solution:

class Fizz
  def output
    puts 'Fizz'
  end
end

class Buzz
  def output
    puts 'Buzz'
  end
end

class FizzBuzz
  def output
    puts 'FizzBuzz'
  end
end

class Element
  def initialize(value)
    @value = value
  end

  def output
    puts @value
  end
end

class FizzBuzzArrayBuilder
  def initialize(array)
    @array = array
  end

  def build
    result = []
    @array.each do |e|
      if e % 15 == 0
        result << FizzBuzz.new
      elsif e % 3 == 0
        result << Fizz.new
      elsif e % 5 == 0
        result << Buzz.new
      else
        result << Element.new(e)
      end
    end
    result
  end
end

class Counter
  def initialize(array)
    @fizz_buzz_array = FizzBuzzArrayBuilder.new(array).build
  end

  def output_array
    @fizz_buzz_array.map(&:output)
  end
end

array = (1..100).to_a
Counter.new(array).output_array


texts: Excel Import Data from Different Workbook Dynamic Headers

texts:
I have this code below that copies data into a master workbook, in sheets "Inputs1", by matching the column headers from the master workbook with the source workbook. If a column header matches, it will copy and paste that column to the related column in the master workbook.

The macro works great for smaller files, but once I run it on larger files it takes almost 2 minutes to run. I also noticed it runs slower when called from a userform instead of from the developer tab directly.

How can I improve this code to run more efficiently and quickly? I still get page flickers too.

Sub Import()

 Application.ScreenUpdating = False

EventState = Application.EnableEvents
Application.EnableEvents = False

CalcState = Application.Calculation
Application.Calculation = xlCalculationManual

PageBreakState = ActiveSheet.DisplayPageBreaks
ActiveSheet.DisplayPageBreaks = False

Dim wbSource As Workbook
Dim wbDest As Workbook
Dim TargetSheet As Worksheet
Dim c As Range
Dim rng As Range
Dim i As Integer
Dim MyRange As Range
Dim SourceSheet As Worksheet
Dim source As String
Dim dest As String
Dim r As Range
Dim msg As String

'Source and destination workbooks defined by cell value

source = Worksheets("Set-Up").Range("B11")
dest = Worksheets("Set-Up").Range("B8")

Set wbSource = Workbooks(source)
Set SourceSheet = wbSource.Worksheets("HFL01 Extract")

Set wbDest = Workbooks(dest)
Set TargetSheet = wbDest.Worksheets("INPUTS1")

With SourceSheet.Range("A1").CurrentRegion
    For Each r In TargetSheet.Range("A1:cc1")
        Set c = .Rows(1).Find(r.Value, , , xlWhole, , 0)
        If Not c Is Nothing Then
            .Columns(c.Column).Copy
            r.PasteSpecial xlPasteValues

        End If
    Next
    Application.CutCopyMode = False
End With

Set fileDialog = Nothing
Set wbSource = Nothing

End Sub


texts: Assigning values from a numerical array to an associative array

texts:
I have this function here:

<?php
public function assignData($data)
{
    $aSqlData['company'] = $data[0];
    $aSqlData['tx_trouserextend_contactperson'] = $data[1];
    $aSqlData['username'] = $data[2];
    $aSqlData['tx_trouserextend_commission'] = $data[3];
    $aSqlData['tx_trouserextend_wincap_version'] = $data[4];
    $aSqlData['tx_trouserextend_wincap_link'] = $data[5];
    $aSqlData['tx_trouserextend_contract_due'] = $data[6];
    $aSqlData['tx_trouserextend_pos_version'] = $data[7];
    $aSqlData['tx_trouserextend_pos_link'] = $data[8];
    $aSqlData['tx_trouserextend_quick_select_version'] = $data[9];
    $aSqlData['tx_trouserextend_quick_select_link'] = $data[10];
    $aSqlData['password'] = $data[11];

    $this->userdata = $aSqlData;
}

This goes on for like 10 more items with this way of assigning. Is there maybe a better way to iterate through it? For instance, just adding the indices and run assign every numerical index to the corresponding associative array-key?

Even though it works, it is not that nice to maintain, imho. Ideas how to improve this? As you can imagine, if the csv-file grows and gets more fields, I'd have to add a line of code for every new column. Thought there would/could be a better way.


texts:
I was messing around online at work the other day when our phone systems went down. I came across the R programming language. Now I'm not guru with programming by any means but I like to mess around with different languages here and there, I believe it helps me to become a better programmer. So I decided that I would try to solve the fizzbuzz challenge in R for those of you that don't know what fizzbuzz is:

  Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz"

This is the first thing I've ever written in R and I would like to have some critique done on what I've accomplished so far:

fizzBuzz = function(range, x, y){
    for (i in seq(1, range, by=1)){
        if (i %% x == 0 & i %% y == 0){
            print('FizzBuzz')
        }
        else if (i %% y ==0){
            print('Buzz')
        }
        else if (i %% x == 0){
            print('Fizz')
        }
        else{
            print(i)
        }
    }
}
fizzBuzz(100, 3, 5)

Some key things I'd like to focus on, per norm feel free to critique everything;

Is it a little bit over kill to put this all in a function, obviously I could do it simply without the function, but is this considered good practice in R to put your solutions inside of functions? I only ask because I looked around at peoples code and didn't see very many functions in it.
Are there easier ways to create the range? I feel like seq(from, to, by=1) is a little harder to understand then range(from, to)


texts: Prim's algorithm via Priority Queues to print the minimum spanning tree of an undirected graph

texts:
Here's my attempt, I believe the runtime is O(V*(ElogE + log E)) since the while loop runs V times and it takes ElogE + log E to do the priority queue operations inside the loop.
class Edge implements Comparable<Edge> {
  T source;
  T destination;
  int weight;

  public Edge(T source, T destination, int weight) {
     this.source = source;
     this.destination = destination;
     this.weight = weight;
  }

  public int compareTo(Edge other) {
    return this.weight - other.weight;
    }
}

public void printMSTPrims(Map<T, List<Edge> > adjacencyList) {
        // Records all visited destinations.
        Set<T> visited = new HashSet<>();
        Queue<Edge> edges = new PriorityQueue<>();
        T currentNode = adjacencyList.entrySet().iterator().next().getKey();
        visited.add(currentNode);
        // Run until we've visited all vertices
        while (visited.size() < adjacencyList.size()) {

            // Take all edges from current node and add to the PQ.
            for (Edge edge: adjacencyList.get(currentNode)) {
                edges.add(edge);
            }

            // Pick the smallest edge to a destination node not already visited.
            Edge edge = edges.remove();
            while (!edges.isEmpty() && visited.contains(edge.destination)) {
                edge = edges.remove();
            }

            // Found an eligible edge, print its contents. This edge does not have to necessarily start from the currentNode.
            System.out.println(edge.source + "--" + edge.weight + "--" + edge.destination);
            // Go next to this destination vertex.
            currentNode = edge.destination;

            //Now that you've reached this edge as a destination, record it.
            visited.add(currentNode);
        }

}

PS. I assume the graph does not have self-loops and double-edges.


texts: Scipy basinhopping custom step update and constrained looping

texts:
I am searching for the global minimum of a certain function and trying to use its gradient (here same as Jacobin) to guide the step counter. However, my x is fix and so is my gradient. I am also trying to retrieve the fastest way possible the first x for which f(x)<1, therefore I am using a constraint.

How can I update the x input and the Jacobin ?
My f(x)<1 is not being very effective, so is there any alternative to achieve my requirement?

This is my code (more or less):

class MyBounds(object):
    def __init__(self, xmax=[2*np.pi, 2*np.pi, 2*np.pi, 2*np.pi, 1.2, 1.2, 1.2, 1.2], xmin=[0, 0, 0, 0, 0, 0, 0, 0] ):
        self.xmax = np.array(xmax)
        self.xmin = np.array(xmin)

    def __call__(self, **kwargs):
        x    = kwargs["x_new"]
        tmax = bool(np.all(x <= self.xmax))
        tmin = bool(np.all(x >= self.xmin))
        return tmax and tmin

class MyTakeStep(object):
    def __init__(self, stepsize=1):
        self.stepsize = stepsize

    def compute_step(self, jacobi_matrix, x, i):
        if   jacobi_matrix[i] < 0: r = np.random.uniform(0,      2*np.pi-x[i])
        elif jacobi_matrix[i] > 0: r = np.random.uniform(0-x[i], 0)
        else                     : r = 0
        return r

    def __call__(self, x):
        print("ENTERING fROM CALL")
        print("THIS IS X: ", x)
        jacobi_matrix  = jacobian(x)
        print("x     : ", x)
        print("jacobi: ", jacobi_matrix)
        x[0] += self.compute_step(jacobi_matrix, x, 0)
        x[1] += self.compute_step(jacobi_matrix, x, 1)
        x[2] += self.compute_step(jacobi_matrix, x, 2)
        x[3] += self.compute_step(jacobi_matrix, x, 3)
        x[4] += self.compute_step(jacobi_matrix, x, 4)
        x[5] += self.compute_step(jacobi_matrix, x, 5)
        x[6] += self.compute_step(jacobi_matrix, x, 6)
        x[7] += self.compute_step(jacobi_matrix, x, 7)
        print("newx  : ", x)
        return x

def f(x):
    # objective function componenets
    result  = g1
    result += g2
    result += g3
    return result

def jacobian(x):
    print("input_list in Jacobi: ", x)

    # define full derivatives
    dG_dphi  = dg1_dphi + dg2_dphi + dg3_dphi
    dG_dr    = dg1_dr   + dg2_dr   + dg3_dr
    gradient = np.hstack((dG_dphi, dG_dr))

    print("G: ", gradient.shape, gradient, " \n")
    return gradient

def callback(x, f, accept):
    print("x: %65s | f: %5s | accept: %5s" % (str([round(e,3) for e in x]), str(round(f, 3)), accept))

def hopping_solver(min_f, min_x, input_excitation):
    # define bounds
    mybounds   = MyBounds()
    mytakestep = MyTakeStep()
    comb       = [deg2rad(phi) for phi in  input_excitation[:4]] + input_excitation[4:]
    print("comb: ", comb)
    min_f = 10
    tol   = 0
    cons = {'type':'ineq','fun': lambda x: 1-f(x)}
    k    = {"method":'Nelder-Mead', 'constraints': cons, 'jac': jacobian, 'tol': tol}
    optimal_c = optimize.basinhopping(f,
                                      x0               = comb,
                                      niter            = 1000000,
                                      T                = 8,
                                      stepsize         = 1,
                                      minimizer_kwargs = k,
                                      take_step        = mytakestep,
                                      accept_test      = mybounds,
                                      callback         = callback,
                                      interval         = 100000,
                                      disp             = True,
                                      niter_success    = None)
    print(optimal_c)
    min_x, min_f = optimal_c['x'], optimal_c['fun']
    comb         = min_x
    sol          = np.array(list([np.rad2deg(phi) for phi in list(optimal_c['x'][:4])]) + list(optimal_c['x'][4:]))
    min_x        = sol
    return min_x, min_f

Any help is much appreciated, thank you in advance.


texts: CSS/JS slider using just data-attributes and transform:translate

texts:
I needed to make a multi-page form, with slides, but without using too much js code like slick.js or the likes. So I tried to figure out how to make it really simple, but still cross-browser and responsive. I ended up with a small test using transform transitions. My question is: do you maybe see any relevant drawbacks on this technique?

The whole thing is based on 3 concepts:

If I use transforms, I'll not have scrollbars.
I can use data attributes to both track the current slide and style (move) the main strip with css
For this specific project, I can safely assume I won't never ever have more than 10 slides or so.

Notice that the demo slider does not loop. It's intentional, since for this specific project I don't want it to loop. Though, it would be fairly simple to make it loop, just change the current var accordingly.

Here is a link to the demo.

The code:

HTML

1

2

3

4

5

6

7

    <button type="button" class="prev-button">prev</button>
    <button type="button" class="next-button">next</button>

CSS (scss)

.main-box{
  max-width: 600px;
  margin: 0 auto;
}

.slide-box{
  overflow:hidden;
}

.slides{
  background-color: #656565;
  display: flex;
  flex-wrap: nowrap;
  transition: transform 300ms;

  @for $i from 1 through 20{ // assuming slides won't never be > 20
    &[data-current="#{$i}"]{ transform: translateX(-100% * ($i - 1)); }
  }

  .slide{
    height: 300px;
    min-width: 100%;
    background-color: #ffb0b0;

    &:nth-child(even){
      background-color: #ff8181;
    }
  }
}//slides

JS (jquery)

var slide_strip = $('.slides');
var slides = slide_strip.find('> *');

var next_button = $('.next-button');
var prev_button = $('.prev-button');

next_button.on('click', function(e){ goto('next'); });
prev_button.on('click', function(e){ goto('prev'); });

function goto(direction){
  var current = parseInt(slide_strip.attr('data-current'), 10);

  if(direction == 'next'){
    if(current >= slides.length) return;
    current++;
  } else {
    if(current <= 1) return;
    current--;
  }

  slide_strip.attr('data-current', current);
}


texts: Providing advice based on user's favourite YouTuber

texts:
I have written this code which provides advice based on user's favourite YouTuber. I wonder if there is a better way to do absolutely any of it. Also, if there is any way to optimise it or if there is a problem please also tell me preferably with fixed code as I am still sort of a beginner.
The code is below:

import random

def test():
    youtuber = input('Enter your favourite youtuber:  ')
    youtuber = youtuber.lower()
    favouriteYoutuber = ['Dr. Phil', 'Mr. Beast', 'T-Series', 'PewDiePie', '5 Minute Crafts', 'The Ellen Show']

    if youtuber == 'dr. phil':
        print('You are an awesome lad!')
    elif youtuber == 'james charles':
        print('Errmm. Ok...')
    elif youtuber == 'bloamz':
        print('Ok then.')
    elif youtuber == 'ali a':
        print('I mean. Thats old but ok...')
    elif youtuber == 'jacksepticeye':
        print('Thats kinda cool')
    elif youtuber == 'will smith':
        print('Thats different. I rate that')
    elif youtuber == 'jack black':
        print('you have good taste')
    elif youtuber == 'jack white':
        print('I like him as well')
    elif youtuber == 'dr. mike':
        print('so you like learning then')
    elif youtuber == 'morgz':
        print('I mean just leave now')
    else:
        print('I dont know that one. Ill check them out')

    print('my favourite youtuber is ' + random.choice(favouriteYoutuber))

def try_again():
    again = True
    while again:
        test()
        while True:
            try:
                print("")
                print("Would you like to try again?")
                maybe = input("Y/N ")
                maybe = maybe.lower()
            except ValueError:
                print("That is not a valid option")
                print("")
                continue
            if maybe in ('y','n'):
                if maybe == "n":
                    print("")
                    again = False
                elif maybe == "y":
                    print("")
                break

    else:
        print("Thank you for using this app!")
try_again()


texts:
I am creating a Trie class in Java, and am wondering what else can be done to make it even better. I am hoping to add concurrency to speed querying up.

public class Trie {
    private HashMap<Character, HashMap> root;
    private final Character END_CHARACTER = '$';

    public Trie() {
        initializeRoot();
    }

    public Trie(String s) {
        initializeRoot();
        add(s);
    }

    public Trie(Collection<String> collection) {
        initializeRoot();
        for (String s : collection) {
            add(s);
        }
    }

    private void initializeRoot() {
        root = new HashMap<>();
    }

    public void add(String s) {
        HashMap<Character, HashMap> node = root;
        for (int i = 0; i < s.length(); i++) {
            Character character = s.charAt(i);
            if (!node.containsKey(character)) {
                node.put(character, new HashMap<Character, HashMap>());
            }
            node = node.get(character);
        }
        node.put(END_CHARACTER, new HashMap<>());
    }

    public boolean contains(String s) {
        HashMap<Character, HashMap> node = root;
        for (int i = 0; i < s.length(); i++) {
            Character character = s.charAt(i);
            if (node.containsKey(character)) {
                node = node.get(character);
            } else {
                return false;
            }
        }
        return node.containsKey(END_CHARACTER);
    }
}


texts: Recomendations on where to set an object properties (Repository Pattern)

texts:
Simple question:

What would you rather do?

public class FooRepository
{
    public Foo GetById(int id)
    {
        Foo foo = null;
        using (IDataReader data = /* Get Foo's data */)
        {
            // Let the Foo object set it's own fields using the data object
            foo = new Foo(data);
        }
        return foo;
    }
}

Or...

public class FooRepository
{
    public Foo GetById(int id)
    {
        Foo foo = null;
        using (IDataReader data = /* Get Foo's data */)
        {
            // Let the Repository class set the Foo object fields
            foo = new Foo();
            foo.Id = Convert.ToInt32(data["FooID"]);
            foo.Name = data["Name"].ToString();
        }
        return foo;
    }
}

Assuming you can't use an ORM (NHibernate, L2S, EF) to handle this for you and that you will need to create Foo in other methods of the repository.

Any explanation will be welcome!


texts:
We've got the basic functionality of using my postscript interpreter, xpost, as a library. I'd like to solicit some feedback from the community on the API setup. This example program, called xpost_client.c illustrates the API to rasterize a small EPS into a 792x612 BGR buffer, which it then dumps to a file as an ASCII PPM file (so you can check it with a text editor).

/*
   This is a simple example of a client calling xpost as a library
   with a postscript program, desiring the raster data of the
   generated image.

TODO:
    define buffer interchange type
 */

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

#include "xpost.h"
#include "xpost_memory.h"
#include "xpost_object.h"
#include "xpost_context.h"
#include "xpost_interpreter.h"

char *prog =
    "%%BoundingBox: 200 300 400 500\n"
    "300 400 100 0 360 arc\n"
    "fill\n"
    "showpage\n";

int main() {
    void *buffer_type_object;
    xpost_init();
    xpost_create("bgr",
            XPOST_OUTPUT_BUFFEROUT,
            &buffer_type_object,
            XPOST_SHOWPAGE_RETURN,
            1);
    xpost_run(XPOST_INPUT_STRING, prog);
    {
        unsigned char *buffer = buffer_type_object;
        int i,j;
        FILE *fp = fopen("xpost_client_out.ppm", "w");
        fprintf(fp, "P3\n612 792\n255\n");
        for (i=0; i<792; i++) {
            for (j=0; j<612; j++) {
                unsigned int red, green, blue;
                red = *buffer++;
                green = *buffer++;
                blue = *buffer++;
                ++buffer;
                fprintf(fp, "%d ", red);
                fprintf(fp, "%d ", green);
                fprintf(fp, "%d ", blue);
                if ((j%20)==0)
                    fprintf(fp, "\n");
            }
            fprintf(fp, "\n");
        }
        fclose(fp);
    }
    xpost_destroy();
    free(buffer_type_object);
    xpost_quit();
    return 0;
}

Currently only the bgr device offers the OUTPUT_BUFFEROUT option. The C code assumes that the PS program contains a showpage to trigger the copying of the buffer. No showpage :: your buffer's a trash-pointer, dude.

I do plan to sweep-up the auxiliary headers into a single "xpost.h" header file. But that's the full list you currently need from the top-level.

One obvious flaw is that there's currently no way to set the geometry or resolution. It's 1-pt per pixel, and that's that. It's also currently hardcoded at letter dimensions, (sorry, rest of the world). Does anybody have ideas about the best way to interface
for that at the top level?

Any other options that a library user might want? Does the buffer-type struct need anything more than height, width and stride? Should stride count words or bytes?

In unixes, Cygwin and mingw, you can

hg clone https://luser.droog@code.google.com/p/xpost/

then read the INSTALL stuff, but the quick version is

./configure
make
sudo make install

then you can run

xpost_client

to produce a (buggy) rendering of a filled circle in xpost_client_out.ppm which loads ok for me in Gimp.

The program can also be browsed online at:

http://code.google.com/p/xpost/source/browse/src/bin/xpost_client.c
http://code.google.com/p/xpost/source/browse/src/lib/xpost.h
http://code.google.com/p/xpost/source/browse/src/lib/xpost_memory.h
http://code.google.com/p/xpost/source/browse/src/lib/xpost_object.h
http://code.google.com/p/xpost/source/browse/src/lib/xpost_context.h
http://code.google.com/p/xpost/source/browse/src/lib/xpost_interpreter.h

Note: I have also posted this code to comp.lang.postscript for a more discussion-type discussion.

Also note: The interpreter produces temporary files in the current directory named gmemXXXXXX lmemXXXXXX xdumpXXXXXX (where XXXXXX is a system-generated unique filename sequence) which may needlessly accumulate diskspace. They periodically must be manually removed. And be careful with code that may do an infinite series of pushes to the stack, lmemXXXXXX may grow very large to hold a huge stack.


texts:
This is a Leetcode problem -

  Let's play the Minesweeper game
  (Wikipedia,
  online game)!

  You are given a 2D char matrix representing the game board. 'M'
  represents an unrevealed mine, 'E' represents an
  unrevealed empty square, 'B' represents a revealed blank square that has no adjacent (above, below, left, right, and all 4
  diagonals) mines, digit (1 to 8) represents how many mines are
  adjacent to this revealed square, and finally 'X' represents a
  revealed mine.

  Now given the next click position (row and column indices) among all
  the unrevealed squares (M or E), return the board after
  revealing this position according to the following rules -

  If a mine (M) is revealed, then the game is over - change it to 'X'.
  If an empty square (E) with no adjacent mines is revealed, then change it to a revealed blank (B) and all of its adjacent
  unrevealed squares should be revealed recursively.
  If an empty square (E) with at least one adjacent mine is revealed, then change it to a digit (1 to 8) representing the
  number of adjacent mines.
  Return the board when no more squares will be revealed.

  Example 1 -

Input:

[['E', 'E', 'E', 'E', 'E'],
 ['E', 'E', 'M', 'E', 'E'],
 ['E', 'E', 'E', 'E', 'E'],
 ['E', 'E', 'E', 'E', 'E']]

Click : [3,0]

Output:

[['B', '1', 'E', '1', 'B'],
 ['B', '1', 'M', '1', 'B'],
 ['B', '1', '1', '1', 'B'],
 ['B', 'B', 'B', 'B', 'B']]

  Explanation -

  Example 2 -

Input:

[['B', '1', 'E', '1', 'B'],
 ['B', '1', 'M', '1', 'B'],
 ['B', '1', '1', '1', 'B'],
 ['B', 'B', 'B', 'B', 'B']]

Click : [1,2]

Output:

[['B', '1', 'E', '1', 'B'],
 ['B', '1', 'X', '1', 'B'],
 ['B', '1', '1', '1', 'B'],
 ['B', 'B', 'B', 'B', 'B']]

  Explanation -

  Note -

  The range of the input matrix's height and width is [1,50].
  The click position will only be an unrevealed square (M or E), which also means the input board contains at least one clickable
  square.
  The input board won't be a stage when the game is over (some mines have been revealed).
  For simplicity, not mentioned rules should be ignored in this problem. For example, you don't need to reveal all the unrevealed
  mines when the game is over, consider any cases that you will win the
  game or flag any squares.

Here is my solution to this challenge -

class Solution:

    directions = [(-1, 0), (-1, -1), (-1, 1), (0,-1), (0, 1), (1, -1), (1, 0), (1, 1)]

    def updateBoard(self, board, click):
        """
        :type board: List[List[str]]
        :type click: List[int]
        :rtype: List[List[str]]
        """
        return self.dfs(board, click)

    def dfs(self, board, click):
        stack = [(click[0], click[1])]
        m, n = len(board), len(board[0])
        while stack:
            r, c = stack.pop() # last inserted element

            if board[r][c] == 'M':
                board[r][c] = 'X'
                break

            # check for adjacent mines
            mines = 0
            for i, j in self.directions:
                dr = r + i
                dc = c + j
                if 0 <= dr < m and 0 <= dc < n and board[dr][dc] == 'M':
                    mines += 1
            board[r][c] = str(mines) if mines else 'B'

            # add neighbors
            for i, j in self.directions:
                dr = r + i
                dc = c + j
                if 0 <= dr < m and 0 <= dc < n and board[r][c] == 'B' and board[dr][dc] == 'E':
                    stack.append((dr, dc))

        return board

Here is my Leetcode result (54 test cases) -

So, I would like to know whether I could make this program shorter and more efficient.

Any help would be highly appreciated.


texts:
This is a bloom filter implementation in C++. To instantiate the BloomFilter class, supply it with the number of bool cells, and a HashFunction vector. The method addElement() adds a string to the set of strings the bloom filter test element membership against. The method searchElement() checks set membership against the aforementioned set.

#include <iostream>
#include <string>
#include <vector>
#include <iterator>

// bloom filter implementation

typedef unsigned int (*HashFunction)(std::string);

class BloomFilter {
    unsigned int numberOfCells;
    unsigned int numberOfFunctions;
    bool* cell;
    std::vector<HashFunction> hashFunctions;

public:

    BloomFilter(unsigned int numbCells, std::vector<HashFunction> funcs) : numberOfCells(numbCells), hashFunctions(funcs) {
        cell = (bool*)calloc(numbCells, sizeof(bool));
    }

    void addElement(std::string str) {
        for (std::vector<HashFunction>::iterator iter = hashFunctions.begin(); iter != hashFunctions.end(); iter++) {
            cell[(*iter)(str) % numberOfCells] = true;
        }
    }

    bool searchElement(std::string str) {
        bool strInSet = true;

        for (std::vector<HashFunction>::iterator iter = hashFunctions.begin(); iter != hashFunctions.end(); iter++) {
            if (cell[(*iter)(str) % numberOfCells] == false) {
                strInSet = false;
                break;
            }
        }

        return strInSet;
    }

    ~BloomFilter() {
        free(cell);
        cell = NULL;
    }
};

// implementing a couple of hash functions for testing

unsigned int djb2(std::string str) {
    unsigned int hash = 5381;

    for (std::string::iterator iter = str.begin(); iter != str.end(); iter++) {
        hash = ((hash << 5) + hash) + *iter;
    }

    return hash;
}

unsigned int sdbm(std::string str) {
    unsigned int hash = 0;

    for (std::string::iterator iter = str.begin(); iter != str.end(); iter++) {
        hash = ((hash << 6) + (hash << 16) - hash) + *iter;
    }

    return hash;
}

int main() {
    // create bloom filter
    std::vector<HashFunction> hashFunctions;
    hashFunctions.push_back(djb2);
    hashFunctions.push_back(sdbm);

    BloomFilter bf(1024, hashFunctions);

    // insert words into the filter
    std::vector<std::string> setOfStrings({
        "Hello World!",
        "sweet potato",
        "C++",
        "alpha",
        "beta",
        "gamma"
    });

    std::cout << "Bloom filter created." << std::endl;
    std::cout << "Bloom filter tests for the following set of strings:" << std::endl;

    for (std::vector<std::string>::iterator iter = setOfStrings.begin(); iter != setOfStrings.end(); iter++) {
        bf.addElement(*iter);
        std::cout << "\t" + *iter << std::endl;
    }

    // testing a set of strings against the bloom filter
    std::vector<std::string> testSetOfStrings({
        "Hello World!",
        "sweet potato",
        "C++",
        "alpha",
        "beta",
        "gamma",
        "delta",
        "where am i?",
        "foo",
        "bar"
    });

    std::cout << "Testing set inclusion for the following strings:" << std::endl;
    std::cout << std::boolalpha;

    for (std::vector<std::string>::iterator iter = testSetOfStrings.begin(); iter != testSetOfStrings.end(); iter++) {
        std::cout << "\t" + *iter + ": " << bf.searchElement(*iter) << std::endl;
    }

    getchar();
}


texts:
I whipped a reasonably fast brute-force perfect number finding function in Haskell, after seeing a similar thing in mathematica.

It works in under 3 seconds when I search up to 1000, but 10000 is too much.

isDivisor :: Integral a => a -> a -> Bool
isDivisor n a = mod n a == 0

sumDivisors :: Integral a => a -> a
sumDivisors a =
   foldr (\n -> if isDivisor a n then (+ n) else id) 0 [1..(a `div` 2)]

isPerfect :: Integral a => a -> Bool
isPerfect n = n == sumDivisors n

-- The main prime-finding function:
upUntil :: Integral a => a -> [a]
upUntil n = filter isPerfect [1..n]

It certainly isn't the fastest, or the most elegant, but I'm unsure how I can improve it.

I would like to concentrate on the isDivisor function in particular. Is there a more efficient way of checking for divisibility?


texts:
Project Euler problem 54 asks:

The file, poker.txt, contains one-thousand random hands dealt to two players. Each line of the file contains ten cards (separated by a single space): the first five are Player 1's cards and the last five are Player 2's cards. You can assume that all hands are valid (no invalid characters or repeated cards), each player's hand is in no specific order, and in each hand there is a clear winner.
How many hands does Player 1 win?

I wrote this program rather hastily, but I also tried to make use of Python features. Here are my questions:

Are the functions clear and does eval_hand return too much (or too little) info?
Would this benefit from rewriting with OOP?
Is the code easy to understand, and how can the code be shortened or clarified? Performance is not a concern.

value_dict = {'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14}

def eval_hand(hand):
    # Return ranking: high card = 0, ... royal flush = 9
    # Also return high card(s) of rank

    values = sorted([c[0] for c in hand])
    suits = [c[1] for c in hand]
    straight = (values == range(min(values), max(values)+1))
    flush = all(s == suits[0] for s in suits)

    # Should not occur (too rare)
    if straight and flush:
        if values[0] == 10:
            return 9, None
        else: return 8, max(values)

    pairs = []
    pair_present = False
    three_of_a_kind = False
    three_value = None
    for v in set(values):
        if values.count(v) == 4:
            return 7, v
        if values.count(v) == 3:
            three_of_a_kind = True
            three_value = v
        if values.count(v) == 2:
            pair_present = True
            pairs.append(v)

    if three_of_a_kind and pair_present: return 6, (three_value, pairs[0])
    if flush: return 5, None
    if straight: return 4, max(values)
    if three_of_a_kind: return 3, three_value
    if len(pairs) == 2: return 2, pairs
    if len(pairs) == 1: return 1, pairs[0]
    return 0, max(values)

def tiebreaker(hand1, hand2, hand1_info, hand2_info):
    # Return True if player 1 wins
    #print(hand1, hand1_info, hand2, hand2_info)
    assert(type(hand1_info) != list) # Shortcut, no identical Two Pairs
    assert(type(hand1_info) == int) # Flushes (None type) can't be compared
    if hand1_info != hand2_info:
        return (hand1_info > hand2_info)

    values1 = sorted((c[0] for c in hand1), reverse=True)
    values2 = sorted((c[0] for c in hand2), reverse=True)
    print(values1, values2, values1 > values2)
    return (values1 > values2)

player1_wins = 0
ranks1 = [0]*10
ranks2 = [0]*10
with open("p054_poker.txt") as f:
    for line in f:
        s = line.split(' ')
        line_pairs = []
        for card in s:
            try:
                value = int(card[0])
            except:
                value = value_dict[card[0]]

            line_pairs.append((value, card[1]))

        hand1 = line_pairs[:5]
        hand2 = line_pairs[5:]
        hand1_rank, hand1_info = eval_hand(hand1)
        hand2_rank, hand2_info = eval_hand(hand2)

        ranks1[hand1_rank] += 1
        ranks2[hand2_rank] += 1

        if hand1_rank > hand2_rank:
            player1_wins += 1

        elif hand1_rank == hand2_rank and tiebreaker(hand1, hand2, hand1_info, hand2_info):
            player1_wins += 1

#print(eval_hand([(2,'D'), (2,'D'), (1,'H'), (4,'D'), (2,'D')]))
print(ranks1)
print(ranks2)
print(player1_wins)


texts:
Is this good approach, to mock some domain object, for example javax.persistence.Entity, or DTO (data transfer object)? Below is simplified source code:

@Entity
public class Entity {
    @Id
    private int id;
    private String name;
    // getters and setters
}

//Spring repo for example
@Repository
public interface EntityRepo {
    Entity findOne(int id);
}

@Component
public class SomeProcessing {
    private EntityRepo entityRepo;

    public SomeProcessing(int id) {
        entityRepo.findOne(id);
        //some logic which would be tested
    }

}

@RunWith(MockitoJUnitRunner.class)
public class SomeProcessingTest {
    @Mock
    private EntityRepo entityRepoMock;
    @Mock
    private Entity entityMock; //it this ok? Or better not to mock it and use just "new Entity()" with getters/setters

    @Test(){
        given(entityMock.getName()).willReturn("text");
        given(entityRepoMock.findOne(anyInt())).willReturn(entityMock);

        //here is other testing stuff
    }
}

Is my understanding correct, that this is refer to Classical vs Mockist testing? Or, there is any other issues not to use mocked Entity or DTO objects?


texts: Parse webpage and save fetched images to a directory

texts:
I had a task for a programmer position which I failed. I am a newbie programmer and I accept that. The only problem is that employer never told me what the actual problem with the code is. So maybe community will be able to give few hints on how to improve it.

The task was to write code which would parse a given webpage, fetch all the images and save it to given directory. Webpage address and directory are command line parameters. Performance was a critical issue for this task.

require 'open-uri'
require 'nokogiri'

class Grab
    def runner(url, path)
        threads = []
        doc = Nokogiri::HTML(open("http://#{url}"))
        img_srcs = doc.css('img').map{ |i| i['src'] }.uniq
        img_srcs = rel_to_abs(url, img_srcs)
        img_srcs.each do |img_src|
            threads << Thread.new(img_src) do
                name = img_src.match(/^http:\/\/.*\/(.*)$/)[1]
                image = fetch img_src
                save(image, name, path)
            end
        end
        threads.each{ |thread| thread.join }
    end

    def fetch(img_src)
        puts "Fetching #{img_src}\n"
        image = open(img_src)
    end

    def save(image, name, path)
        File.open("#{path}/#{name}", "wb"){ |file| file.write(image.read) }
    end

    def rel_to_abs(url, img_srcs)
        img_srcs.each_with_index do |img_src, index|
          img_srcs[index] = "http://#{url}/#{img_src}" unless   img_src.match(/http:\/\//)
        end
        img_srcs
    end
end


texts: Generating vertices of the rectified hypercube

texts:
The following piece of code generates the vertices of the rectified hypercube in arbitrary dimensions. The 3D case of the rectified hypercube is a cuboctahedron with 12 vertices (±1,±1,0), (±1,0,±1), (0,±1,±1).

The code below works perfectly, I only want to know what optimizations should I consider and/or if faster approaches exist.

#include <array>
#include <vector>
#include <algorithm>

template <typename T, size_t N>
void generate_rectified_hypercube(std::vector<std::array<T, N>> &vertices)
{
    std::array<T, N> set;
    std::array<T, N> temp;

    // Initialize set { 2, 1, ..., 1 }

    set[0] = T(2);
    for (size_t i = 1; i < N; i++)
    {
        set[i] = T(1);
    }

    // Generate vertices

    for (size_t i = 0; i < N; i++)
    {
        // Modify set

        set[i] -= T(2);
        std::copy(set.begin(), set.end(), temp.begin());
        std::sort(temp.begin(), temp.end());

        // Add all possible permutations of current set

        do
        {
            vertices.push_back(temp);
        }
        while (std::next_permutation(temp.begin(), temp.end()));
    }
}


texts:
I'm using these 2 functions to handle file input/output and would like to know if there's anything that should be changed.

For content retrieval, enough space is allocated and the file content is copied. To make sure saving a file either saves all or nothing, I'm writing to a buffer then renaming it after all content is successfully written.

I'm particularly interested in knowing whether these functions are safe or not since tmpnam is considered dangerous. I read the main risk is a file with the name returned by tmpnam being created before we are able to do it, so I'm using wbxto make sure it doesn't happen. Is this enough or there are other security concerns that I'm not aware of?

files.h

#ifndef FILES_H
#define FILES_H

#include <stdlib.h>

#define FILE_SUCCESS 0
#define FILE_ERROR 1

void *file_get_content(const char *file_name, size_t *file_size_fill);

//Save all or nothing
int file_save_content(  const char *file_name,
                        const void *content,
                        size_t size             );

#endif

files.c

#include <stdio.h>
#include <sys/stat.h>
#include "files.h"

#define BYTE 1
#define READ_MODE "rb"

//Use the new "x" subspecifier so fopen will fail if a file with the name
//returned by tmpnam exists
#define SAFE_WRITE "wbx"

void *file_get_content(const char *file_name, size_t *file_size_fill)
{
    //Get file size, SEEK_END is not portable
    struct stat file_stat;
    if(stat(file_name, &file_stat) != 0)
        return NULL;

    //Check if the file actually contains anything, since malloc can return
    //values other than NULL for malloc(0)
    if(file_stat.st_size == 0)
        return NULL;

    //Space to save the contents
    void *content = malloc(file_stat.st_size);
    if(content == NULL)
        return NULL;

    //Open file
    FILE *file = fopen(file_name, READ_MODE);
    if(file == NULL){
        free(content);
        return NULL;
    }

    //Read it all
    if(fread(content, BYTE, file_stat.st_size, file) != file_stat.st_size){
        free(content);
        fclose(file);
        return NULL;
    }

    fclose(file);

    *file_size_fill = file_stat.st_size;
    return content;
}

//Save the file content safely, it either saves all or nothing
int file_save_content(  const char *file_name,
                        const void *content,
                        size_t size             )
{
    //Get a name for the temp file
    char temp_file_name[L_tmpnam];
    if(tmpnam(temp_file_name) == NULL)
        return FILE_ERROR;

    //Create it
    FILE *temp_file = fopen(temp_file_name, SAFE_WRITE);
    if(temp_file == NULL)
        return FILE_ERROR;

    //Write
    if(fwrite(content, BYTE, size, temp_file) != size){
        fclose(temp_file);
        remove(temp_file_name);
        return FILE_ERROR;
    }

    //Replace old file
    fclose(temp_file);
    if(rename(temp_file_name, file_name) != 0){
        remove(temp_file_name);
        return FILE_ERROR;
    }

    return FILE_SUCCESS;
}

file_save_content() after following the suggestions given by 200_success

int file_save_content(const char *file_name, const void *content, size_t size)
{
    /* Create temp file */
    char tmp[] = {'t','m','p','X','X','X','X','X','X', '\0'};
    int error;
    int fd = mkstemp(tmp);

    if(fd == -1)
        return FILE_ERROR;

    if(write(fd, content, size) != (ssize_t)size){
        error = errno;
        close(fd);
        errno = error;
        return FILE_ERROR;
    }

    /* Replace old file */
    if(rename(tmp, file_name) != 0){
        error = errno;
        unlink(tmp);
        close(fd);
        errno = error;
        return FILE_ERROR;
    }

    close(fd);

    return FILE_SUCCESS;
}


texts: Modelling a program with modules, symbols, and dependencies

texts:
My scenario is the following: I'm modelling a Program which has many Modules. Each Module has Symbols, some of which pointing at dependencies, which are other Modules. So a Module can be pointed to by many other Modules as a dependency.

Now I want to be able to modify a Module (typically, running an optimiser on its contents, removing unused dependencies, etc), and then any other Module which has it as a dependency should point to the "new" version.

I've tried two approaches:

Having a ModuleId for each Module, and have Modules point to their dependencies by their ModuleId. Then I can update the Module associated to a ModuleId and all links are still valid. One drawback is that there's no compile-time guarantee that I won't try to update a non-existing Module.
Using Rc<RefCell<Content>> to store the content to be updated, in which case I can update Content without any of the dependency links breaking. I find it suspicious that I have to use such advanced tools for this, and they're not risk free as RefCell is checked at run time.

I'm wondering if I missed another approach, and which one would be the most idiomatic.

Here is a link to a simplified playground with both approaches, and my code below:

mod with_module_id {
    use std::collections::hash_map::{Entry, HashMap};

    type Content = usize;

    #[derive(Debug)]
    struct Module {
        content: Content,
        dependency: Option<ModuleId>,
    }

    type ModuleId = String;

    #[derive(Debug)]
    struct Prog {
        modules: HashMap<ModuleId, Module>,
    }

    fn update_module(p: Prog, id: ModuleId, c: Content) -> Prog {
        let mut p = p;
        match p.modules.entry(id.clone()) {
            Entry::Occupied(mut m) => m.get_mut().content = c,
            _ => panic!("module id not found: {}", id),
        };
        p
    }

    pub fn run() {
        let m0 = Module {
            content: 42,
            dependency: None,
        };

        let m1 = Module {
            content: 43,
            dependency: Some(String::from("m0")),
        };

        let m2 = Module {
            content: 44,
            dependency: Some(String::from("m0")),
        };

        let p = Prog {
            modules: vec![
                (String::from("m0"), m0),
                (String::from("m1"), m1),
                (String::from("m2"), m2),
            ]
            .into_iter()
            .collect(),
        };

        println!("We start with this program:\n{:#?}\n", p);

        let p = update_module(p, String::from("m0"), 151);

        println!("We update module m0 to contain 151:\n{:#?}\n", p);

        println!("We try to update an unexisting module and boom...");
        let _p = update_module(p, String::from("invalid :("), 404);
    }
}

mod with_ref_cell {
    use std::rc::Rc;
    use std::cell::RefCell;

    type Content = usize;

    #[derive(Debug)]
    struct Module {
        content: Rc<RefCell<Content>>,
        dependency: Option<Rc<Module>>,
    }

    fn update_module(m: Rc<RefCell<Content>>, c: Content) {
        *m.borrow_mut() = c;
    }

    pub fn run() {

        let content0 = Rc::new(RefCell::new(42));

        let m0 = Module {
            content: Rc::clone(&content0),
            dependency: None,
        };

        let content1 = Rc::new(RefCell::new(43));

        let m0 = Rc::new(m0);

        let m1 = Module {
            content: Rc::clone(&content1),
            dependency: Some(Rc::clone(&m0)),
        };

        let content2 = Rc::new(RefCell::new(44));

        let m2 = Module {
            content: Rc::clone(&content2),
            dependency: Some(Rc::clone(&m0)),
        };

        println!("We start with this program:\n{:#?}\n\n{:#?}\n", m1, m2);

        update_module(content0, 151);

        println!("We update module m0 to contain 151:\n{:#?}\n\n{:#?}\n", m1, m2);
    }
}

fn main() {
    with_ref_cell::run();
    with_module_id::run();
}


texts: Go Lang custom convert array into string with two separators

texts:
This is my custom function to join strings from an array into one string.
We can provide normal separator and the last one. JoinStringsIntoArray(", ", " and ", words...)
func JoinStringsIntoArray(sep string, lastSep string, words ...string) string {
lastElementIndex := len(words) - 1
var joinedString string

for index, word := range words[0:lastElementIndex] {
    if index == lastElementIndex-1 {
        sep = lastSep
    }
    joinedString += word + sep
}

joinedString += words[lastElementIndex]

    return joinedString
}

Test for this function
func TestStringsJoinsWithCommas(t *testing.T) {
    var words []string
    words = append(words, "one", "two", "three")

    expectedResult := "one, two and three"
    result := JoinStringsIntoArray(", ", " and ", words...)

    if expectedResult != result {
        t.Errorf("Strings joiner is broken, it should be '%v', we got '%v'", expectedResult, result)
    }
}

What do you think about this, can this solution be improved? The function works fine but I'm not so sure it's written well.


texts:
I'm new to PHP and web development in general. Is this a good coding style for me as a beginner?  I don't care about password hashing.  I use MD5 which is, as far as I know, not a good encryption method, and I'm trying to create just the login for now.

connection.php:

<?php

try {
    $pdo = new PDO("mysql:host=localhost;dbname=akar","akar","raparen");
} catch (PDOException $e) {
    echo $e->getMessage();
}
?>

index.php:

<?php
session_start();
include "connection.php";

if(isset($_SESSION['logged_in']) == true){
    //Redirect the user to members
    header("Location: member.php");
    exit();

} else {
    ?>

    <?php
}
    if(isset($_POST['username']) && isset($_POST['password'])) {
        $username = $_POST['username'];
        $password = md5($_POST['password']);

        if(empty($username) or empty($password)) {
            //Display Errors
            $error = "All fields are required!";

        } else {
            //Verify the user
            $sql = "SELECT * FROM `users` WHERE user_name = ? AND user_password = ?";
            $query = $pdo->prepare($sql);
            $query->bindValue(1,$username);
            $query->bindValue(2,$password);
            $query->execute();

            if ($query->rowCount() > 0) {
                //User details right
                $_SESSION['logged_in'] = true;
                header("Location: member.php");
            } else {
                //User details wrong
                $error = "Wrong username or password";
            }
        }
    }

?>

<?php if (isset($error))  { ?>

    <?php echo $error; ?>

<?php } ?>

member.php:

<?php
session_start();

if($_SESSION['logged_in']) {
    echo "You're logged in";
} else {
    header("Location: index.php");
}

?>

Logout

logout.php

<?php
    session_start();

    session_destroy();
    header("Location: index.php");
?>

Here is my form:

 <form action="index.php" method="POST" autocomplete="off">
    <input type="text" name="username" placeholder="Username" />
    <input type="password" name="password" placeholder="Password" />
    <input type="submit" name="submit" value="Login" />
 </form>


texts: Java parsing and extract String from pattern String

texts:
I want to extract some string surrounded by certain patterns.

For Instance, the original String something like 1234@{78}dasdh@{1}fdsfs@{fdf}ad@{
and I want extract 78, 1, fdf from it.

Below is my code for the purpose

public class Test {

    // want to get "78", "1", "fdf"
    private static String targetStr = "1234@{78}dasdh@{1}fdsfs@{fdf}ad@{";

    public static void main (String[] args) throws Exception {

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

        Pattern open = Pattern.compile("@\\{");
        Matcher oMatcher = open.matcher(targetStr);

        Pattern close = Pattern.compile("}");
        Matcher cMatcher = close.matcher(targetStr);

        while(oMatcher.find()) {
            if(cMatcher.find())  parsed.add(targetStr.substring(oMatcher.start() + 2, cMatcher.start()));
        }
        System.out.println(parsed);
    }
}

Is there anyway to complete this task? Some how it feels unsafe since use 2 iterator without any validation.


texts: Prefix- and z-functions in C++ (string algorithms)

texts:
Let us define prefix-function(string)[i] as the length of the largest prefix of string, which is also a suffix of string[1..i], and z-function(string)[i] is the length of the largest prefix of string, which is also a prefix of string[i..].

Unfortunately, there is very little information on them in English, but I found a presentation on Knuth-Morris-Pratt algorithm containing description of prefix-function and an article on z-function.

Here is my implementation of prefix-function and z-function and conversions between them in linear time on the length of string using pure C++. Comments are appreciated! In particular, I'm interesting how to determine a string from z-function directly.

std::vector<int> prefix_function (const std::string& str) {
    std::vector<int> prefs (str.size(), 0);
    for (int i = 1; i < str.size(); ++i) {
        int pref = prefs[i-1];
        while (pref > 0 && str[i] != str[pref]) {
            pref = prefs[pref-1];
        }
        if (str[i] == str[pref]) {
            ++pref;
        }
        prefs[i] = pref;
    }
    return prefs;
}

std::vector<int> z_function(const std::string& str) {
    std::vector<int> zfunc (str.size(), 0);
    zfunc[0] = str.size();
    for (int i = 1, left = 0, right = 0; i < str.size(); ++i) {
        if (i <= right) {
            zfunc[i] = std::min (right - i + 1, zfunc[i - left]);
        }
        while (i + zfunc[i] < str.size() && str[zfunc[i]] == str[i + zfunc[i]]) {
            ++zfunc[i];
        }
        if (i + zfunc[i] - 1 > right) {
            left = i;
            right = i + zfunc[i] - 1;
        }
    }
    return zfunc;
}

std::string from_prefix_function(const std::vector<int>& prefs) {
    std::string str (prefs.size(), '.');
    char current_symbol = 'a';
    for (int i = 0; i < prefs.size(); ++i) {
        if (prefs[i] > 0) {
            str[i] = str[prefs[i] - 1];
        } else {
            str[i] = current_symbol++;
        }
    }
    return str;
}

std::vector<int> prefix_to_z(const std::vector<int>& prefs) {
    return z_function(from_prefix_function(prefs));
}

std::vector<int> z_to_prefix(const std::vector<int>& z_func) {
    std::vector<int> prefs (z_func.size(), 0);
    for (int i = 1; i < z_func.size(); ++i) {
        prefs[i + z_func[i] - 1] = std::max(prefs[i + z_func[i] - 1], z_func[i]);
    }
    for (int i = z_func.size() - 2; i >= 0; --i) {
        prefs[i] = std::max(prefs[i+1] - 1, prefs[i]);
    }
    return prefs;
}


texts: Perl hash mapping SVG elements to content elements


texts: More elegant solution to create a array of fake data

texts:
I am creating fake data using faker.js. Out of simplicity I created a for-loop.

const faker = require("faker")
const dataLength = 10
const productArr = []

for (var index = 0; index < dataLength; index++) {
  productArr.push({
    name: faker.commerce.productName(),
    category: faker.commerce.department(),
    price: faker.commerce.price(),
    description: faker.lorem.paragraph(),
  })
}

console.log(productArr.length)
console.log(JSON.stringify(productArr))

Is there a more elegant solution to iterate through an array that has a fixed length?


texts: Importing JPG, JPEG, and PNG images from a folder to an Excel worksheet

texts:
As I am a novice, I was keen to solve the task, so now I want to optimize the code.

Sub AddOlEObject()

    Dim mainWorkBook As Workbook

    Set mainWorkBook = ActiveWorkbook
    Sheets("SingleProfile").Activate
    Folderpath = "C:\Users\sandeep.hc\Pics"
    Set fso = CreateObject("Scripting.FileSystemObject")
    NoOfFiles = fso.GetFolder(Folderpath).Files.Count
    Set listfiles = fso.GetFolder(Folderpath).Files
    For Each fls In listfiles
       strCompFilePath = Folderpath & "\" & Trim(fls.Name)
        If strCompFilePath <> "" Then
            If (InStr(1, strCompFilePath, "jpg", vbTextCompare) > 1 _
            Or InStr(1, strCompFilePath, "jpeg", vbTextCompare) > 1 _
            Or InStr(1, strCompFilePath, "png", vbTextCompare) > 1) Then
                 counter = 29
                 counter1 = counter1 + 1

                Call insert(strCompFilePath, counter, counter1)
                'Sheets("SingleProfile").Activate
                counter1 = counter1 + 17
            End If
        End If
    Next
mainWorkBook.Save
End Sub

Function insert(PicPath, counter, counter1)
'MsgBox PicPath
    With ActiveSheet.Pictures.insert(PicPath)
        With .ShapeRange
            .LockAspectRatio = msoFalse
            .Width = 875
            .Height = 300
        End With
        .Left = ActiveSheet.Cells(counter, counter1).Left
        .Top = ActiveSheet.Cells(counter, counter1).Top
        .Placement = 1
        .PrintObject = True
    End With
End Function

Based on Comments Optimized code

Sub AddImage2()
Dim rgTarget As Range
Dim RowI As Long, ColumnI As Long

    Folderpath = "C:\Users\sandeep.hc\Pics"
    Set fso = CreateObject("Scripting.FileSystemObject")
    NoOfFiles = fso.GetFolder(Folderpath).Files.Count
    Set listfiles = fso.GetFolder(Folderpath).Files
    For Each fls In listfiles
       strCompFilePath = Folderpath & "\" & Trim(fls.Name)
        If strCompFilePath <> "" Then
            If (InStr(1, strCompFilePath, "jpg", vbTextCompare) > 1 _
            Or InStr(1, strCompFilePath, "jpeg", vbTextCompare) > 1 _
            Or InStr(1, strCompFilePath, "png", vbTextCompare) > 1) Then
    RowI = 29
    ColumnI = ColumnI + 1
    Set rgTarget = Cells(RowI, ColumnI)
    Application.ActiveSheet.Shapes.AddPicture strCompFilePath, False, True, rgTarget.Left, rgTarget.Top, 875, 400
    ColumnI = ColumnI + 17
    End If

End If
Next
End Sub


texts:
I have 5 different forms where I am disabling the submit button when a valid form is submitted so the form can only be submitted once. I am using a hidden field on each form to get the form Id.

function OnSubmit(buttonId) {
var disableButton = false;

if ($('#formType').val() == 1) {
    if ($('#CreateEntityName').val() != "" && $('#newAccountGroup').val() != "") {
        disableButton = true;
    }
}
if ($('#formType').val() == 2) {
    if ($('#newAccount').val() != "" && $('#lastName').val() != "") {
        disableButton = true;
    }
}
if ($('#formType').val() == 3) {
    if ($('#select2-entityId').val() != 0 && $('#contact').val() != "") {
        disableButton = true;
    }
}
if ($('#formType').val() == 4) {
    if ($('#select2-entityId').val() != 0 && $('#contact').val() != "" && $('#need').val() != "" && $('#candidates').val() != 0) {
        disableButton = true;
    }
}
if ($('#formType').val() == 5) {
    if ($('#newAccount').val() != "" && $('#country').val() != "") {
        disableButton = true;
    }
}
if (disableButton == true) {
    $('#' + buttonId + '').attr("disabled", true);
}
}

@Html.Hidden("formType", 5)


texts:
I've written a Python script to generate the closest square spiral matrix to a given number.

I'm new to code reviews as a practice, and I'm interested in ways to improve. Please suggest improvements to the code where you see fit, particularly in regards to:

Algorithm: Is there a faster/more elegant way to generate the matrix?
Style: I've tried to adhere to PEP8.

"""
Outputs the closest square spiral matrix of an input number
"""
from math import sqrt

def is_even_square(num):
    """True if an integer is even as well as a perfect square"""
    return sqrt(num).is_integer() and (num % 2 == 0)

def find_nearest_square(num):
    """Returns the nearest even perfect square to a given integer"""
    for i in range(num):
        if is_even_square(num - i):
            return num - i
        elif is_even_square(num + i):
            return num + i

def find_lower_squares(num):
    """Returns a list of even perfect squares less than a given integer"""
    squares = []
    for i in range(num, 3, -1):
        if is_even_square(i): squares.append(i)
    return squares

def nth_row(num, n):
    """Returns the nth row of the square spiral matrix"""
    edge = int(sqrt(num))
    squares = find_lower_squares(num)
    if n == 0:
        return list(range(num, num - edge, -1))
    elif n >= edge - 1:
        return list(range(num - 3*edge + 3, num - 2*edge + 3))
    elif n < edge // 2:
        return ([squares[1] + n] + nth_row(squares[1],n-1)
              + [num - edge - n + 1])
    else:
        return ([num - 3*edge + 4 + n - edge] + nth_row(squares[1],n-1)
              + [num - 2*edge + 1 - n + edge])

def generate_square_spiral(num):
    """Generates a square spiral matrix from a given integer"""
    edge = int(sqrt(num))
    square_spiral = [[None for x in range(edge)] for y in range(edge)]
    for row in range(edge): square_spiral[row] = nth_row(num, row)
    return square_spiral

def main ():
    num = None
    while not num:
        try:
            num = int(input('Input number: '))
        except ValueError:
            print('Invalid Number')
    nearest_square = find_nearest_square(num)
    matrix = generate_square_spiral(nearest_square)
    for row in range(len(matrix[0])):
        for col in range(len(matrix)):
            if matrix[row][col] < 10:
                print('  ',matrix[row][col],' ',sep='',end='')
            elif matrix[row][col] < 100:
                print(' ',matrix[row][col],' ',sep='',end='')
            else:
                print(matrix[row][col],' ',sep='',end='')
        print(2*"\n",end='')

if __name__ == '__main__':
    main()


texts:
I've been working on this challenge for a week:

  There are two sequences. The first sequence consists of digits "0" and "1", the second one consists of letters "A" and "B". The challenge is to determine whether it's possible to transform a given binary sequence into a string sequence using the  following rules:

  "0" can be transformed into non empty sequence of letters "A" ("A", "AA", "AAA" etc.)
  "1" can be transformed into non empty sequence of letters "A" ("A", "AA", "AAA" etc.) or to non empty sequence of letters "B" ("B", "BB",
  "BBB" etc) e.g.

  Examples:

1010 AAAAABBBBAAAA                -> Yes
00 AAAAAA                         -> Yes
01001110 AAAABAAABBBBBBAAAAAAA    -> Yes
1100110 BBAABABBA                 -> No

Here is the first small sample to feed the program and here is the second large sample.

I have 3 working solutions, but they're painfully slow.

My first idea was to build a regex for each test case, test if it matched and map Yes or No

puts IO.readlines(ARGV[0]).map { |l| l.chomp.split(' ') }.map { |a|
  index = 0
  a[1].match(a[0].chars.to_a.inject('^') { |result, digit|
    result + (digit == '1' ? '([A|B])\\' : '(A)\\') + "#{index += 1}{0,}"
  } + '$') ? 'Yes' : 'No'
}

It works fine with the small sample, but takes forever with the large one.

So I thought about backtracking and tried it

def check_char_number(char, number)
  (number == '0' && char == 'A') || number == '1'
end

def check(string, numbers, current_char)
  return true if string.empty? && numbers.empty?
  return false if string.empty?
  return false if current_char != string[0] && !check_char_number(string[0], numbers[0])

  if string[0] == current_char
    r = check(string[1..-1], numbers, current_char)
    return r if r
  end

  return check(string[1..-1], numbers[1..-1], string[0]) if check_char_number(string[0], numbers[0])
  return false
end

puts IO.readlines(ARGV[0]).map(&:chomp).map(&:split).map { |a|
  r = 0
  l1 = a[0].length
  l2 = a[1].length
  if l1 > l2 or l1 < 1 or l2 < 1
    r = 'No'
  else
    r = check(a[1], a[0], nil) ? 'Yes' : 'No'
    puts "finished: #{r}"
  end
  r
}

But it's still so slow

So I was getting desperate and started looking around on GitHub to see how other people did it, and found something interesting in python

I don't have any academic degree in CS I learned everything with books and MIT courses and I can't tell if what he's using is a known technique to solve this sort of problems. I feel like I barely understand it (spent a lot of time with the debugger to see what happens step by step) and I'd really love to know if a Wikipedia page could explain this better or if this is completely home-made.

I ported it ruby and my second question is: even though it is significantly faster than the previous two why is it sill five to seven times slower than his solution:

def check_number_with_partial_string(number, partial_string)
  #45% of runtime spent here!
  return !partial_string.include?('B') if number == '0'
  return !(partial_string.include?('A') && partial_string.include?('B')) if number == '1'
end

def check_matching(numbers, string, matching_matrix, row = 0, column = 0)
  return if matching_matrix[-1][-1] == true
  return if row >= matching_matrix.size or column >= matching_matrix[row].size
  return if matching_matrix[row][column]
  (column...string.length).each do |c|
    matching_matrix[row][c] = false
    if check_number_with_partial_string(numbers[row], string[column...(c + 1)])
      matching_matrix[row][c] = true
      check_matching(numbers, string, matching_matrix, row + 1, c + 1)
    end
  end
end

puts IO.readlines(ARGV[0]).map(&:chomp).map(&:split).map { |a|
  matrix = Array.new(a[0].length).map { |b| Array.new(a[1].length) }
  check_matching(a[0], a[1], matrix)
  matrix[-1][-1] ? 'Yes' : 'No'
}

I profiled it and it seems 45% of the time is spent in the first little method

Time profiler


texts: Making additional subclasses at any time should be as painless as possible

texts:
I'm writing a small text-based game in Java to learn the language. I'm concerned that I may be making some poor design decisions. I'll introduce 2 elements: A character and monsters. A singleton character should be able to fight a wide array of monsters.

Here is the monster class:

public abstract class Monster {

    protected static Random random = new Random();
    protected static int STATS_PER_LEVEL = 3;

    public int combatLvl;
    public int defense, strength, attack, hp;
    protected String name;

    protected Monster(int defense, int strength, int attack, int hp) {
        this.defense = defense;
        this.strength = strength;
        this.attack = attack;
        this.hp = hp;
        this.combatLvl = (int) (defense+strength+attack+Math.round((double)hp/10)-4)/STATS_PER_LEVEL;
    }

    public int attack() {
        //removed the body
    }

    public String toString(String name) {
        return this.name;
    }
}

Here's a subclass:

public class Bandit extends Monster {

    public static double averageLevelDouble = -1;
    public static String averageLevelString = "dummy";

    public static int minDefense = 1;
    public static int maxDefense = 1;
    public static int minStrength = 1;
    public static int maxStrength = 3;
    public static int minAttack = 1;
    public static int maxAttack = 3;
    public static int maxHp = 4;

    public Bandit() {
        super(random.nextInt(maxDefense-minDefense+1) + minDefense,
              random.nextInt(maxStrength-minStrength+1) + minStrength,
              random.nextInt(maxAttack-minAttack+1) + minAttack,
              random.nextInt(maxHp-minHp+1) + minHp);
        double min = minDefense+minStrength+minAttack+((double)minHp/10);
        double max = maxDefense+maxStrength+maxAttack+((double)maxHp/10);
        double avg = ((max+min)/2)-4;
        averageLevelDouble = (double)Math.round((avg/STATS_PER_LEVEL)*10)/10;
        averageLevelString = (Math.round(min)-4)/STATS_PER_LEVEL + "-" +
                     (Math.round(max)-4)/STATS_PER_LEVEL;
        name = "Bandit";
    }
}

My main concern is that I should be able to easily expand the game with arbitrarily many monsters. The way I'd do it now is to copy paste Bandit into a new class: Change the class name to f.i. Skeleton, initiate 'name' variable in the constructor, customize all the static ints. Is this a wrong approach?

Also a very obvious thing that comes to mind is that I should be able to display information on a particular monster without having to instantiate it. From a Swing.JComboBox I should be able to choose all monsters, display their information, and at the moment I decide to fight a monster it should be instantiated. I can't find a solution to represent monsters on a JList or JComboBox without having to manually add Bandit.name (pretend it's static) as a line of code in the JList/JComboBox class when I define the Bandit class.

I'm just assuming that I shouldn't be instantiating my subclasses. Again, that is the question: What am I doing wrong and right? I really don't how to ask but; What's wrong with my code?


texts: What is the best way to code an array that has same keys as another array's values

texts:
I have two arrays as follows:

public $headers = [
    'user_id',
    'timestamp',
    'value',
];

protected $args = array('user_id' => array('filter' => FILTER_VALIDATE_REGEXP,
                                                      'options' => array('regexp' => '/^[a-zA-Z0-9_]*$/'), ),
                        'timestamp' => array('filter' => FILTER_CALLBACK,
                                             'options' => "validateDate", ), ),
                        'value' => FILTER_VALIDATE_FLOAT, );

The keys in the array args are the same values of the array headers.
How to avoid repeating the values here ?


texts: Benchmarking inline vs normal functions in C++

texts:
I am currently learning C++ and have learnt about inline functions and how they can give a performance benefit.

How could this be improved?

#include <iostream>
#include <chrono>
#include <ctime>

long fibonacci(unsigned n) {
    if (n < 2) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

inline long fib(unsigned n) {
    if (n < 2) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

void timedFibonacci(unsigned n) {

    // Time vars
    std::chrono::time_point<std::chrono::system_clock> start, end;

    // Start time.
    start = std::chrono::system_clock::now();

    //std::cout << "Functional Fibonacci of " << n << " = " << fibonacci(n) << '\n';
    fibonacci(n);

    // End time.
    end = std::chrono::system_clock::now();

    // Time elapsed.
    std::chrono::duration<double> functionalTimeElapsed = end - start;

    // Start time.
    start = std::chrono::system_clock::now();

    //std::cout << "Inline Fibonacci of " << n << " = " << fib(n) << '\n';
    fib(n);

    // End time.
    end = std::chrono::system_clock::now();

    // Time elapsed.
    std::chrono::duration<double> inlineTimeElapsed = end - start;

    if (functionalTimeElapsed > inlineTimeElapsed) {
        std::cout << "n = " << n << "\tFunctional method was faster by " << ((functionalTimeElapsed - inlineTimeElapsed) / inlineTimeElapsed) * 100 << "%\n";
    } else if (functionalTimeElapsed < inlineTimeElapsed) {
        std::cout << "n = " << n << "\tInline method was faster by " << ((inlineTimeElapsed - functionalTimeElapsed) / functionalTimeElapsed) * 100 << "%\n";
    } else {
        std::cout << "n = " << n << "\tFunctional method and inline method took the same time.\n";
    }
}

int main() {

    for (int i = 5; i <=40 ; i++) {
        timedFibonacci(i);
    }

    cin.get();
}


texts:
I want to get the latest release of certain package. In order to do so I did this:

wget https://chromedriver.storage.googleapis.com/LATEST_RELEASE -O /tmp/chromedriver_release
wget http://chromedriver.storage.googleapis.com/`cat /tmp/chromedriver_release`/chromedriver_linux64.zip -O /tmp/chromedriver_linux64.zip

There's not a direct link to the latest version (at least none that I could find)
This instructions are part of a provisioning script, I don't have curl installed and I don't want to install it

I checked wget arguments and I didn't find anything that allows me to redirect the downloaded content to stdout. Will this be my best option?


texts: Working C code dealing with lists: problem with memory leak

texts:
I have written a working code that generates a simple linked list of dates and associated holidays. I realize that I have a problem with memory leaking as I copy lists repeatedly, so I wrote a freeList function. I am just having issues determining where to place this function.

//Creates a linked list of dates/holidays

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

typedef struct hashElem{
    char* date;
    char* holiday;
    struct hashElem* next;

}hashElem;

// Initialize list with input value
hashElem* createNode(char* input_date, char* input_holiday)
{
    hashElem* ptr = malloc(sizeof(*ptr));

    if (ptr == NULL)
    {
        perror("Error");
        return NULL;
    }

    ptr -> date = input_date;
    ptr -> holiday = input_holiday;
    ptr -> next = NULL;

    return ptr;
}

void freeList(hashElem* head)
{
    hashElem* ptr = head;
    while (head != NULL)
    {
        ptr = ptr->next;
        free(head);
        head = ptr;
    }
}

hashElem* addToTail(hashElem* head, char* input_date, char* input_holiday)
{
    hashElem* ptr = malloc(sizeof(*ptr));
    hashElem* temp = head;

    // If there is not yet a list, initialize the list with the input value
    if (head == NULL)
        return createNode(input_date, input_holiday);

    if (ptr == NULL)
        return NULL;
    else
    {
        ptr->date = input_date;
        ptr->holiday = input_holiday;
        ptr->next = NULL;

        // Find the last element of the list
        while (temp->next != NULL)
            temp = temp->next;

        // Add new node to the end of the list
        temp->next = ptr;
        ptr = head;

        //free(head);
        return ptr;
    }
}

hashElem* holidayList(void)
{
    hashElem* List = NULL;
    List = addToTail(List, "01/01/13", "New Years Day");
    List = addToTail(List, "14/02/13", "Valentine's Day");
    List = addToTail(List, "26/03/13", "Start of Passover");
    List = addToTail(List, "16/06/13", "Father's Day");
    List = addToTail(List, "31/10/13", "Halloween");
    List = addToTail(List, "28/11/13", "Thanksgiving");
    List = addToTail(List, "25/12/13", "Christmas");

    return List;
}

void printList(hashElem* head)
{
    hashElem* ptr = head;

    printf("------------------------------\n");
    printf("PRINTING LINKED LIST\n");
    while (ptr != NULL)
    {
        printf("Date: %s,  Holiday: %s\n", ptr->date, ptr->holiday);
        ptr = ptr->next;
    }

    printf("------------------------------\n");
}


texts: K&R Exercise 1-19. Reverse program input one line at a time

texts:
Intro

I'm going through the K&R book (2nd edition, ANSI C ver.) and want to get the most from it: learn (outdated) C and practice problem-solving at the same time. For that reason, I'm trying to solve the exercises "hardcore" - without using any knowledge from the "future". I'll catch-up with it after I finish the book.

I believe that the author's intention was to give the reader a good exercise, to make the reader think hard about what he can do with the tools introduced, and not to skip ahead to find an easier way. For that reason, I'm only using language features introduced up to this point in the book. That also means I'm using an old C standard.

Compiling with gcc -Wall -Wextra -Wconversion -pedantic -ansi.

K&R Exercise 1-19

Write a function reverse(s) that reverses the character string s. Use it to write a program that reverses its input a line at a time.

Solution

The task explicitly states how the function should look like. For that reason, I've coded it similarly to how the author made his copy function.

The 2nd part of the challenge is to reverse the program input a line at a time, but how long can the line be? It would be too easy to set a hard limit for line length, just loop line by line and return an error if it's exceeded. I can't use dynamic memory allocation to deal with arbitrary long lines since it hasn't been introduced yet so what's left? The book already introduced all the building blocks I need for recursion, so at this point it the only solution.

Code

/* Exercise 1-19. Write a function `reverse(s)` that reverses the
 * character string `s`. Use it to write a program that reverses its
 * input a line at a time. */

#include <stdio.h>
#define BUFSIZE 10 /* line buffer size */

int getline(char line[], int maxline);
void copy(char to[], char from[]);
void reverse(char s[]);
int reverseinput(char lastchar[]);

main()
{
    char lastchar[1];

    while (reverseinput(lastchar) != 0)
        if (lastchar[0] == '\n')
            putchar('\n');
    return 0;
}

/* reverseinput: read from input until end of line is reached and then
 * print the line in reverse */
int reverseinput(char lastchar[])
{
    int len;
    char line[BUFSIZE];
    int retval;

    if ((len = getline(line, BUFSIZE)) > 0) {
        if ((lastchar[0] = line[len-1]) == '\n') {
            line[len-1] = '\0';
            retval = 1;
        }
        else
            retval = reverseinput(lastchar);
        reverse(line);
        printf("%s", line);
    }
    else
        retval = 0;
    return retval;
}

/* getline: read a line into s, return length */
int getline(char s[],int lim)
{
    int c, i;

    for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
        s[i] = c;
    if (c == '\n') {
        s[i] = c;
        ++i;
    }
    s[i] = '\0';
    return i;
}

/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[])
{
    int i;

    i = 0;
    while ((to[i] = from[i]) != '\0')
        ++i;
}

/* reverse: reverse a '\0' terminated string */
void reverse(char s[])
{
    int tail;
    int head;
    char c;

    /* find the last character index */
    tail = 0;
    while (s[tail] != '\0')
        ++tail;
    if (tail > 0)
        --tail;
    /* reverse the string by swapping first and last elements */
    for (head = 0; head < tail; ++head && --tail) {
        c = s[head];
        s[head] = s[tail];
        s[tail] = c;
    }
}

Test

Running $ ./ch1-ex-1-19-01 <ch1-ex-1-19-01.c | ./ch1-ex-1-19-01 prints the program code :)


texts:
I have written this code to build a list by looking inside directory within deep to the level it finds a audio file and then move to the next level or next folder.

Can there be a more efficient way since a user can have any number of files? Do you think it can be achieved more robustly in terms of performance?

path = '/Users/ceaser/Music'

import os
allSongs = []
for folder in os.walk(path):
    for item in folder[-1]:
        name, ext = os.path.splitext(item)
        if ext in ['.mp3', '.wma', '.wav', '.ogg']:
            allSongs.append(name)


texts: Using a Subject to trigger a music list to reload

texts:
In my Android app I have a Service that is periodically polling a server for a music playlist XML. For certain occasions I also want to trigger a reload manually.

I am using Retrofit for the server communication and my Service exposes an Observable<Playlist> to which some other components of the app can subscribe. At the moment there are two such subscribers: One Fragment that contains the playback controls and one other Service that manages the actual audio streaming as well as the updates to the Notifications.

Now, I want all Subscribers to receive any new playlist info as soon as it becomes available. In particular this means that if I trigger a reload manually from the Fragment, the Service should also immediately receive the server response.

No matter how I turn it, all my solutions need a Subject. Here's the one I like best:

private Observable<MusicInfoResponse> mReloadingObservable;
private PublishSubject<Long> mManualRefreshesSubject = PublishSubject.<Long>create();

private void setupObservable() {

    Observable<Long> timer = Observable.timer(0, 15, TimeUnit.SECONDS);

    Observable<Long> pulses = Observable.merge(timer, mManualRefreshesSubject);

    mReloadingObservable = pulses
        .flatMap(new Func1<Long, Observable<MusicInfoResponse>>() {

            @Override
            public Observable<MusicInfoResponse> call(Long aLong) {
                Log.d(LOG_TAG, "reloading music info XML");
                return reloadMusicInfo();
            }
        })
        .share();
}

public Observable<MusicInfoResponse> subscribeToMusicInfo() {
    return mReloadingObservable;
}

public void triggerManualRefresh() {
    mManualRefreshesSubject.onNext(1l);
}

Since, it seems to me, one should generally avoid Subjects and try to use only normal Observables instead my question is: Is there any way to this that does not need Subjects? Is this a case where using Subjects is the way to go?

And also: What are the main drawbacks of Subjects in general?


texts:
I am a fairly new programmer, and I stumbled with a beginner practice project, a random dice number generator. The code works, but I would like to know if there is an efficient way compared to mine to write it.

#Random dice
import random

#returns a number (side of the dice)
def roll_dice():
  print (random.randint(1, 6))

print("""
Welcome to my python random dice program!
To start press enter!
Whenever you are over, type quit.
""")

flag = True
while flag:
   user_prompt = input(">")
   if user_prompt.lower() == "quit":
      flag = False
   else:
     print("Rolling dice...\nYour number is:")
     roll_dice()


texts: Write a function to determine whether an array contains consecutive numbers for at least N numbers

texts:
I am trying to write a function to determine whether an array contains consecutive numbers for at least N numbers. For example, the input is [1,5,3,4] and 3, it turns true because the array has 3 consecutive numbers, which is [3,4,5]

Here this function requires sorting beforehand and it is not the most eloquent solution in my opinion. Can someone take a look and suggest some improvements on this?

function hasConsecutiveNums(array, N) {
  if (array.length < N) return false;
  if (N === 0) return true;
  const sortedArray = array.slice().sort((a, b) => a - b);
  let count = 0;
  let prev = null;
  for (const num of sortedArray) {
    if (prev && num === prev + 1) {
      count++;
    } else {
      count = 1;
    }
    if (count === N) return true;
    prev = num;
  }

  return false;
}

console.log(hasConsecutiveNums([1, 4, 5, 6], 3)) // true
console.log(hasConsecutiveNums([1, 4, 5, 6], 4)) // false


texts:
I'm working on a program that aim to take sentences (currently in french) and compact them to a length of 38 characters while retaining as much information as possible.
You can find another part of this project here replacing words with their abbreviations

I've made a function that removes determiners from a string using an external config file containing said determiners. It is functionnal but I think there's a lot to improve.

Here it is:

# determiners is the config file below parsed by configparser, l1 is the string
def remove_determiners(determiners, l1):
    for key in determiners:
        it_l1 = 0

        # the goal is to obtain a string shorter than 38 char
        while(it_l1 < len(l1) and len(l1) > 38):

             # finds possible beginnig of words
             if(l1[it_l1] in ' -' or it_l1 == 0):
                 if(it_l1 == 0):
                      it_l1 = -1

                 # finds possible end of words
                 it_word = 0
                 while(it_word < len(key) and it_l1 + it_word + 1 < len(l1)
                 and l1[it_l1 + it_word + 1] == key[it_word].upper()):
                      it_word += 1
                 if(it_word == len(key) and (it_l1 + it_word + 1 == len(l1)
                 or l1[it_l1 + it_word + 1] in ' -.')):
                      if(it_l1 == -1):
                          it_l1 = 0

                      # cuts the determiner out
                      l1 = l1[:it_l1] + l1[it_l1 + it_word + 1:]

             it_l1 += 1
             if(it_l1 == 0):
                 it_l1 = 1
    return(l1)

Here is the configfile: (mostly french determiners)

[remove]
& = nope
A = nope
AND = nope
AU = nope
AUX = nope
D = nope
DE = nope
DES = nope
DU = nope
EN = nope
FOR = nope
ET = nope
L = nope
LA = nope
LE = nope
LEUR = nope
LEURS = nope
LES = nope
OF = nope
OU = nope
PAR = nope
POUR = nope
SA = nope
SON = nope
SUR = nope
THE = nope
UN = nope
UNE = nope

Here is how its parsed:

determiners = configparser.ConfigParser()
determiners.read('configuration//determiners.ini')

And here are some I/O examples:

'JE SUIS LA BAGUETTE.' --> 'JE SUIS BAGUETTE.'
'LES PILES DE LA TELECOMMANDE.' --> 'PILES TELECOMMANDE.'
'QU ELLE HEURE EST IL ?' --> 'QU ELLE HEURE EST IL ?'

You may note the strings have been formatted to remove special characters and to be all upcase