texts:
As an answer to this problem:

  Exercise 1.29

  Simpson's Rule is a
  more accurate method of numerical
  integration than the method
  illustrated above. Using Simpson's
  Rule, the integral of a function f
  between a and b is approximated as
   (h / 3) * (y_0 + 4y_1 + 2y_2 + 4y_3 + 2y_4 + ... + 2y_(n-2) + 4y_(n-1) + y_n

  where h = (b - a)/n, for some even
  integer n, and yk = f(a + kh).
  (Increasing n increases the accuracy
  of the approximation.) Define a
  procedure that takes as arguments f,
  a, b, and n and returns the value of
  the integral, computed using Simpson's
  Rule. Use your procedure to integrate
  cube between 0 and 1 (with n = 100 and
  n = 1000), and compare the results to
  those of the integral procedure shown
  above.

I wrote the following solution:

(define (sum term a next b)
  (define (iter a result)
    (if (> a b)
        result
        (iter (next a) (+ (term a) result)))
    ) (iter a 0))

(define (simpsons-rule f a b n)
  (let ((h (/ (- b a) n)))
    (define (y_k k) (f (+ a (* k h))))
    (define (even n) (= (remainder n 2) 0))
    (define (term n) (* (if (even n) 2.0 4.0) (y_k n)))
    (define (next n) (+ n 1))
    (* (/ h 3.0) (+ (y_k 0.0) (sum term 0.0 next (- n 1.0)) (y_k n)))))

(define (cube x) (* x x x))

What do you think?


texts: Find palindromic substrings as efficiently as possible

texts:
I've written a function to calculate all the distinct substrings of a given string, that are palindromes. The string is passed as the argument to the function. For example, the string abba is a palindrome because reversed it is also abba. If the function takes the string aabaa it returns 5, because the distinct substrings are a, aa, aabaa, aba, b.

I've currently made use of two for loops for this to work, however, when the string gets big, it's very inefficient due to the fact it iterates one by one. Any suggestions as to how I can make this significantly more efficient? Recursion maybe?

The function:

function countPalindromesInString(s) {

    let subStrings = [];

    for (let i = 0; i < s.length; i++) {
      for(let j = 0; j < s.length - i; j++) {
        let subString = s.substring(j, j + i + 1);
        if(subString === subString.split('').reverse().join('') && !subStrings.includes(subString)) {
          subStrings.push(subString);
        }
      }
    }
    return subStrings.length;
}


texts: Print the frequency of characters as a horizontal histogram

texts:
Well, I've used some of the feedback from my last posting to improve how I wrote this program. Mainly using the void parameter in main, initializing my int array to zero without using a for-loop, and better naming of variables. If there are some issues that are going on with my code, or there's some things I can do better, please let me know.

Any feedback is welcome!

#include <stdio.h>

/* print histogram of the frequencies of different characters in its input */
int main(void)
{
  int histogram[95] = {0}; /* initialize 95 spaces for ASCII characters 32 - 127 */
  int c, i, j;

  while ((c = getchar()) != EOF) {
    ++histogram[c-' '];
  }

  for (i = 32; i < 127; ++i) {
    printf("%c ", i);
    ++histogram[c-' '];
    for (j = 0; j < histogram[i-' ']; ++j) {
      putchar('x');
    }
    putchar('\n');
  }
}


texts: React Animation example - accordion panel

texts:
I decided to study an animation in React and created a simple example of an collapsible panel using CSSTransitionGroup.
To make an animated collapsible, I added max-height: 0, overflow: hidden and a transition for the max-height property, to the panel class.
It works but I'm not sure that this is best way to create collapsible panel.
I will appreciate any advice about code.

const CSSTransitionGroup = React.addons.CSSTransitionGroup;

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = { visible: false }
  }
  onClick() {
    this.setState((prevState, props) => ({
      visible: !(prevState.visible)
    }))
  }
  render() {
    return (

Click me

          <CSSTransitionGroup
            transitionName='example'
            transitionEnterTimeout={300}
            transitionLeaveTimeout={300}>
            {this.state.visible ?

Hello!

              : null}
          </CSSTransitionGroup>

    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
.App {
  text-align: center;
  margin: 40px;
}

.content{
  background-color: #f1f1f1;
  overflow: hidden;
  height: 50px;
}

.example-enter {
  max-height: 0px;
}

.example-enter.example-enter-active {
  max-height: 50px;
  transition: max-height 300ms ease-in;
}

.example-leave {
  max-height: 50px;
}

.example-leave.example-leave-active {
  max-height: 0px;
  transition: max-height 300ms ease-in;
}


texts: Getting an element from RCU-protected list in kernel

texts:
I wrote a function, read_fox_rcu() for getting an element from RCU-protected list in a linux device driver. read_fox_rcu() reads the first element, converts it to string , stores it to tmp and stores the first pointer to ppfox.

I wonder that I used locks (rcu_read_lock(), synchronize_rcu(), etc), in an appropriate way.

static int read_fox_rcu(struct fox ** ppfox, char *tmp, size_t size){
    struct fox *f;
    rcu_read_lock();
    f = list_first_or_null_rcu(&fox_list_rcu, struct fox, list);
    if (f==NULL) {
        rcu_read_unlock();
        return -1;
    }
    snprintf(tmp, size, "%lu/%lu/%d\t",
            f->tail_length, f->weight, f->is_fantastic);
    *ppfox = f;
    rcu_read_unlock();
    return 0;
}

#define MAX_BUF_SIZE    1024
static ssize_t show_pop_fox_r(struct device *dev, struct device_attribute *attr, char *buf)
{
    int ret;
    struct fox * f;
    char tmp[MAX_BUF_SIZE];

    if (read_fox_rcu(&f, tmp, MAX_BUF_SIZE)) {
        ret = scnprintf(buf, PAGE_SIZE, "failure on read_fox_rcu()\n");
        return ret;
    }
    list_del_rcu(&f->list);
    synchronize_rcu();
    kfree(f);

    ret = scnprintf(buf, PAGE_SIZE, "%s\n", tmp);
    return ret;
}

static DEVICE_ATTR(pop_fox_r, S_IRUGO, show_pop_fox_r, NULL);

dev_attr_pop_fox_r.attr is declared by DEVICE_ATTR. And pop_fox_r is created, by calling sysfs_create_group() in the probe function.

fox_list_rcu and struct fox is defined like below.

struct fox {
    size_t tail_length;
    size_t weight;
    bool is_fantastic;
    struct list_head list;
};

static LIST_HEAD(fox_list_rcu);


texts:
I have written a shell script utility for deleting all merged local branches.

#!/usr/bin/env bash

# Remove references to remote branches that no longer exist.
git remote prune origin
# Create a file containing list of all merged branches.
git branch --merged > 5db3bb3c-718a-444c-b1ce-d90a5a0d1cb3.clc

nano 5db3bb3c-718a-444c-b1ce-d90a5a0d1cb3.clc
# Trim trailing and leading whitespace etc.
sed 's/^[ \t]*//;s/[ \t]*$//' < 5db3bb3c-718a-444c-b1ce-d90a5a0d1cb3.clc
# Soft delete all branches left in the file and then remove tmp file.
xargs git branch -d < 5db3bb3c-718a-444c-b1ce-d90a5a0d1cb3.clc
rm 5db3bb3c-718a-444c-b1ce-d90a5a0d1cb3.clc

Although I wrote this only for personal use, I will likely create a repository for it on my github account and I am not particularly familiar with shell script best practices.

(Edit: The script eventually ended up on github here)


texts: Print code-fenced sections of a Markdown document

texts:
Original code and demo at this gist.

Given a Markdown document like

Here is some text,
and some more text.
```javascript
const message = "This is JavaScript!";
```
More text follows, and then
```javascript
console.log(message);
```

I want to print out the sections in code fences, not including the code
fences, separated by a single blank line:

const message = "This is JavaScript!";

console.log(message);

I came up with the following AWK script, which seems to do the job
nicely:

#!/usr/bin/awk -f
BEGIN { in_code_block = 0 }
/^```/ {
    if (!in_code_block) {
        in_code_block = 1;
        first_line = 1;
    } else {
        in_code_block = 0;
        print "";
    }
}
{
    if (in_code_block && !first_line) {
        print;
    }
    first_line = 0;
}

A goal is for the script to be dependency-minimal. I don't want to have
to install an implementation of CommonMark or an Erlang environment. AWK
fits this bill well.

Correspondingly, a non-goal is for this script to be correct in all
cases: I’m happy to accept false positives on lines starting with
```inline code``` like this, and similar edge cases.

I’m mostly looking for critique of my AWK, with respect to which I am a
total newbie. But any comments are welcome!


texts: Returning JSON from GeoDjango QuerySet and Display using jQuery/AJAX

texts:
I have this query:

def floodhazard_tbl(request):
    if request.method == "GET":
        # create a list
        to_json = []

        # this code is results a messy JSON data that need underscore.js to manipulate
        # in order for us to use datatables
        getgeom1 = FloodHazard.objects.get(id=3).geom
        response_high = list(PolyStructures.objects.filter(geom__within=getgeom1).values(
            'brgy_locat', 'municipali').annotate(counthigh=Count('brgy_locat')))
        to_json.append(response_high)

        getgeom2 = FloodHazard.objects.get(id=2).geom
        response_medium = list(PolyStructures.objects.filter(geom__within=getgeom2).values(
            'brgy_locat', 'municipali').annotate(countmedium=Count('brgy_locat')))
        to_json.append(response_medium)

        getgeom3 = FloodHazard.objects.get(id=1).geom
        response_low = list(PolyStructures.objects.filter(geom__within=getgeom3).values(
            'brgy_locat', 'municipali').annotate(countlow=Count('brgy_locat')))
        to_json.append(response_low)

        return StreamingHttpResponse(list(json.dumps(to_json)), content_type='application/json')

Although it works, the respond is very slow and I wonder why.

Here's my model:

class PolyStructures(models.Model):
    bldg_name = models.CharField(max_length=100)
    block_name = models.CharField(max_length=75)
    bldg_type = models.CharField(max_length=50)
    brgy_locat = models.CharField(max_length=50)
    municipali = models.CharField(max_length=50)
    province = models.CharField(max_length=50)
    geom = models.MultiPolygonField(srid=32651, null=True, blank=True)
    objects = models.GeoManager()

    def __unicode__(self):
        return self.bldg_name

class FloodHazard(models.Model):
    hazard = models.CharField(max_length=6)
    date_field = models.DateTimeField(null=True, blank=True)
    geom = models.MultiPolygonField(srid=32651, null=True, blank=True)
    objects = models.GeoManager()

    def __unicode__(self):
        return self.hazard

Here's my JS function for displaying the result in my template:

function e() {
        $.ajax({
            url: "tbl/",
            dataType: "json",
            beforeSend: function () {
                $("#info_tbl").show().text("Getting data from server...Please wait.").addClass("getme")
            },
            success: function (e) {
                function t(e) {
                    return _.reduce(e, function (e, t) {
                        return e + parseFloat(t || 0)
                    }, 0)
                }
                $("#info_tbl").text("Successfully Loaded!").fadeOut(1e3).removeClass("getme"), $("#myErrorWrapper").hide(), $("#table_wrapper").show();
                var a = _.chain(e).flatten().groupBy("brgy_locat", "municipali").map(function (e, r) {
                    return {
                        municipality: _(e).chain().pluck("municipali").first(),
                        brgy: r,
                        low: t(_(e).chain().pluck("countlow").value()),
                        medium: t(_(e).chain().pluck("countmedium").value()),
                        high: t(_(e).chain().pluck("counthigh").value())
                    }
                }).value();
                r.fnClearTable();
                for (var o = 0; o < a.length; o++) r.fnAddData([a[o].municipality, a[o].brgy, a[o].low || 0, a[o].medium || 0, a[o].high || 0])
            },
            error: function () {
                e(), $("#myErrorWrapper").show()
            }
        })
    }

BTW, I'm using underscore.js and datatables plug-in.

The shapefile that I loaded in the PostgreSQL database has a size of 18mb and take up 3 rows in my table but before it was 28K+ rows, my co-worker "dissolved" it and make it in 3 (Low, Medium, High) rows.

I am using django-debug-toolbar to measure the query time.

Is there any way to make it fast? Or is it because of the shapefile size? or my query?


texts: Idiomatic catching of unchecked exceptions in ExecutorService.submit

texts:
OK, here's the problem space:
Lwjgl, a graphical library, has the ability to throw an unchecked LWJGLException on certain methods - like Display.create(). This becomes a problem when you have to off-load all work done by Display onto a single thread using an ExecutorService - that's what I'm doing, unfortunately, due to how Lwjgl works. ExecutorService.submit(Runnable) does not allow you to throw unchecked exceptions. ExecutorService.submit(Callable<V>) does, however, I still have to handle that exception.

My solution? I used the strategy pattern, like so.

private final ExecutorService executor;
private final ExceptionHandler exceptionHandler;

@Inject
public LwjglWindow(@Lwjgl ExecutorService executor, @Lwjgl ExceptionHandler exceptionHandler) {
    this.executor = executor;
    this.exceptionHandler = exceptionHandler;
}

public void start() {
    executor.submit(() -> {
        try {
            Display.create();
        } catch (LWJGLException ex) {
            exceptionHandler.onException(ex);
        }
    });
}

Using dependency injection, I inject an instance of ExceptionHandler to deal specifically with exceptions originating from Lwjgl. Should an exception occur from Lwjgl, well, then, this is called (from LwjglExceptionHandler):

@Override
public void onException(Exception exception) {
    logger.trace("lwjgl encountered an error", exception);
    systemShutdownStrategy.shutdown();
}

systemShutdownStrategy is an interface that is nothing more than a strategy pattern. This is injected into the instance of LwjglExceptionHandler, so it could be a stub and do nothing or it could shut down your program (which is, as the name of the field suggests, the intent). There's always room to implement some user-friendly error notification, rather than closing quietly, but this is just here for demonstration purposes.

The reason behind my choices here is that if a LwjglException occurs, the program is pretty much guaranteed to be unrecoverable. However, I'm concerned that I might be creating a code smell by the way I implement by start() method in LwjglWindow, given the side effects possible.

So, my question is, given that this is how I am handling my LwjglExceptions, is it a code smell, and what alternatives would you suggest in that case? (Also, a general review of my conventions would be appreciated if you'd like, as obviously just getting back into Java after 2 years in the .NETsphere)


texts:
I've always wondered what's the most elegant way of implementing PrintLn in C++. I have not yet come with perfect conclusion. This is my shot.

Shortcut for std::cout, std::cerr and std::clog "print line" version. So you can type
CoutLn << "Hello world!"; instead of std::cout << "Hello world!" << '\n';

CoutLn, CerrLn, ClogLn are implemented.

#include <iostream>
#include <typeinfo>
#include <mutex>

/* Template magic: determine if our type is printable. */
template<typename S, typename T, typename = void>
struct is_to_stream_writable : std::false_type {};
template<typename S, typename T>
struct is_to_stream_writable<S, T, std::void_t<decltype(std::declval<S&>()<<std::declval<T>())>> : std::true_type {};

/* Since std::cout, std::cerr etc. are all different instances of the same type,
 * let's define dummy classes for detecting different instances. */
class Cout{};
class Cerr{};
class Clog{};

template<class Stream = Cout>
class PrintLn {
  private:
    static std::ostream* stream;
    static std::mutex m;
  public:
    PrintLn() {
      if constexpr (std::is_same<Stream, Cout>::value) stream = &std::cout;
      else if constexpr (std::is_same<Stream, Cerr>::value) stream = &std::cerr;
      else if constexpr (std::is_same<Stream, Clog>::value) stream = &std::clog;
    }
    template<class T>
    PrintLn& operator<<(const T& msg) {
      static_assert(is_to_stream_writable<std::ostream, T>::value, "your type is not printable");
      std::lock_guard<std::mutex>(PrintLn<Stream>::m);
      *stream << msg;
      return *this;
    }
    ~PrintLn() {
      std::lock_guard<std::mutex>(PrintLn<Stream>::m);
      *stream << '\n';
    }
};

/* Declare static variables. */
template<class Stream>
typename::std::mutex PrintLn<Stream>::m;

template<class Stream>
typename::std::ostream* PrintLn<Stream>::stream;

using CoutLn = PrintLn<Cout>;
using CerrLn = PrintLn<Cerr>;
using ClogLn = PrintLn<Clog>;

/* Shorter syntax, for example: `CerrLn{} << "error";` -> `CerrLn << "error";`. */
#define CoutLn CoutLn{}
#define CerrLn CerrLn{}
#define ClogLn ClogLn{}


texts:
I've been working on this pong game for the last 10 days, and I'd like to know of your opinions about it, what could I change to make my code better?

 #include <stdio.h>
#include <allegro5/allegro.h>
#include "allegro5/allegro.h"
#include "allegro5/allegro_image.h"
#include <allegro5/allegro_native_dialog.h>
#include <allegro5/allegro_primitives.h>
#include <allegro5/color.h>
#include <allegro5/allegro_color.h>
#include <allegro5/allegro5.h>
#include <allegro5/color.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>
#include <iostream>
int p1score = 0;
int p2score=0;

ALLEGRO_EVENT ev;
int main(){
srand (time(NULL));
int d = 200;
int f = 200;
int x = 700;
int y = 100;
int a = 100;
int b = 100;
int ballx = 200;
int bally = 200;
int ballXSpeed = 10;
int ballYSpeed = 5;
bool ballmoving = true;
al_init_image_addon();
ALLEGRO_BITMAP *Player1;
ALLEGRO_BITMAP *Player2;
ALLEGRO_BITMAP *ball;
ALLEGRO_DISPLAY *display = NULL;

ALLEGRO_EVENT_QUEUE *eventqueue = NULL;
ALLEGRO_TIMER *timer = NULL;

bool playing = true;
al_init();
al_init_primitives_addon();
display = al_create_display(800, 600);
al_install_keyboard();
eventqueue = al_create_event_queue();
timer = al_create_timer(1.0 / 60.0);
al_register_event_source(eventqueue, al_get_keyboard_event_source());
al_register_event_source(eventqueue, al_get_display_event_source(display));
al_register_event_source(eventqueue, al_get_timer_event_source(timer));
Player1 = al_load_bitmap("brick.png");
Player2 = al_load_bitmap("brick.png");
int P1W = al_get_bitmap_width(Player1);
int P1H = al_get_bitmap_height(Player1);
int P2W = al_get_bitmap_width(Player2);
int P2H = al_get_bitmap_height(Player2);

ball = al_load_bitmap("ball.png");
int ballw = al_get_bitmap_width(ball);
int ballh = al_get_bitmap_height(ball);
while (playing){
    ballYSpeed = rand() % 7;

    al_clear_to_color(al_map_rgb(255, 255, 0));
    al_wait_for_event(eventqueue, &ev);
    al_start_timer(timer);
    if (ev.type == ALLEGRO_EVENT_TIMER){

        ballx = ballx + ballXSpeed;
        bally = bally + ballYSpeed;
        if (ballx < x+P1W && ballx+ballw>x &&bally<y+P1H && ballx+ballh>y){
            ballXSpeed = ballXSpeed * -1;
            ballYSpeed = ballYSpeed*-1;
        }
        if (ballx < a + P2W && ballx+ballw>a && bally <b + P2H &&bally+ballh>b){
            ballXSpeed = ballXSpeed*-1;
            ballYSpeed = ballYSpeed*-1;
        }
        if (ballx > 800 || bally > 600){
            ballx = 400;
            bally = 400;
            p2score++;
            std::cout << "P2 :  " << p2score << std::endl;
        }
        if (ballx<-1 || bally<-1){
            ballx = 400;
            bally = 400;
            p1score++;
            std::cout << "P1:   " << p1score << std::endl;
        }
    }
        if (ev.type = ALLEGRO_EVENT_KEY_DOWN){
            switch (ev.keyboard.keycode){
            case ALLEGRO_KEY_UP:
                y -= 20;
                break;
            case ALLEGRO_KEY_DOWN:
                y += 20;
                break;
            case ALLEGRO_KEY_W:
                b -= 20;
                break;
            case ALLEGRO_KEY_S:
                b += 20;
                break;

            }
        }

        al_draw_bitmap(Player1, x, y, 0);
        al_draw_bitmap(Player2, a, b, 0);
        al_draw_bitmap(ball, ballx, bally, 0);
        al_flip_display();
    }

al_flip_display();
al_rest(5);
}


texts: Shell POSIX OpenSSL file decryption script

texts:
Tonight, I tried to write a Bash OpenSSL file decryption script. Encryption script will follow in highly similar manner, so I think it's not necessary now.

Let's suppose we have an encrypted large file using:

openssl enc -aes-256-cbc -salt -in somefile -out somefile.enc

You correctly noticed I always add .enc to the file name.

The meaning of the script is:

take one, and only one, argument as a file
ask user for password
decrypt that file with openssl with a shown progress
save it without the .enc extension, or if it didn't have that extension, give it .dec extension
not to overwrite existing files

Though I wrote it with maximum effort, a review is more than welcome.

The script follows:

#!/bin/bash

if [ "$#" -ne 1 ] || [ ! -f "$1" ]
then
    echo "A single existing file needs to be given as an argument. Exiting."
else
    input_filename="$1"
    filepath=$(dirname "$1")
    filename_extracted_from_path=$(basename "$1")
    filename_without_enc_extension="${filename_extracted_from_path%.enc}"

    if [[ "$filename_extracted_from_path" == "$filename_without_enc_extension" ]]
    then
        output_filename="$filepath/$filename_extracted_from_path".dec
    else
        output_filename="$filepath/$filename_without_enc_extension"
    fi

    if [ -f "$output_filename" ]
    then
        echo "Destination file exists. Exiting."
    else
        pv "$input_filename" | openssl enc -aes-256-cbc -d -salt -out "$output_filename"
    fi
fi

EDIT1:

I decided to put the script on GitHub (when done), therefore it must be POSIX compliant, so I have made minor changes.
I found out, the script lacks destination directory writable check, so I integrated it.
Also, it now checks if it is run as root (or with sudo).

But the structure remains and new version of the script follows:

#!/bin/sh

if [ "$#" -ne 1 ] || [ ! -f "$1" ]
then
    echo "A single existing file needs to be given as an argument. Exiting."
else
    input_filename="$1"
    filepath=$(dirname "$1")
    filename_extracted_from_path=$(basename "$1")
    filename_without_enc_extension="${filename_extracted_from_path%.enc}"

    if [ "$filename_extracted_from_path" = "$filename_without_enc_extension" ]
    then
        output_filename="$filepath/$filename_extracted_from_path".dec
    else
        output_filename="$filepath/$filename_without_enc_extension"
    fi

    if [ -f "$output_filename" ]
    then
        echo "Destination file exists. Exiting."
    else
        if [ ! -w "$filepath" ] && [ "$(id -u)" -ne 0 ]
        then
            echo "Destination directory is not writable. Exiting."
        else
            pv --wait "$input_filename" | openssl enc -aes-256-cbc -d -salt -out "$output_filename"
        fi
    fi
fi

Uploaded on GitHub: https://git.io/fxslm


texts: Use weather API to get information in JavaScript + jQuery

texts:
Please can any code experts review and improve my code?

HTML

<!DOCTYPE html>

    <title>API</title>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link rel="stylesheet" href="//fonts.googleapis.com/css?family=font1|font2|etc" type="text/css">
    <link rel="stylesheet" type="text/css" href="style.css">

Description:

Temperature:

That's the HTML. It is just mostly tags with id to output info.

JavaScript

var ask = prompt("Type in your city or town that you want the weather for. Please make sure you write the first letter as capital letter and you spell it right.");
$.getJSON("https://api.openweathermap.org/data/2.5/weather?q="+ask+"&units=metric&appid=32b8cd17f2ff5d84d72342dd7408bab2", function(data) {
    console.log(data);
    var icon = "https://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
    var weather = data.weather[0].main;
    var desc = data.weather[0].description;
    var temp = data.main.temp;
    var temp1 = temp + "℃"
    $("#icon").attr("src", icon);
    document.getElementById('weather').innerHTML = weather;
    document.getElementById('desc').innerHTML = desc;
    document.getElementById('temp').innerHTML = temp1;
});

If there is any other language than jQquery that I can use to get JSON files from API, please let me know because I find jQuery quite confusing.


texts: Get the common values between two text files

texts:
I'm just trying to get the common values from two distinct files called file1.txt and file2.txt where I'm using Python's set method to get the results and this works.

However, I'm looking forward to see if there is better way to do this.

#!/grid/common/pkgs/python/v3.6.1/bin/python3
def common_member():
    a_set = dataset1
    b_set = dataset2
    if (a_set & b_set):
        print(a_set & b_set)
    else:
        print("No common elements")

with open('file1.txt', 'r') as a:
        dataset1 = set(a)
with open('file2.txt', 'r') as b:
    dataset2 = set(b)

common_member()

file1.txt

teraform101
azure233
teraform221
teraform223
teraform224

file2.txt

teraform101
azure109
teraform223
teraform226
teraform225
azure233

Result:

{ 'teraform101\n', 'azure233\n', 'teraform223\n' }


texts:
I have designed a proxy server which has the feature to manage miniature separate networks. Each network has space to have up to 500 nodes or 500 IPs. The code for getting a new virtual IP is based on a bit flag based approach. I have used an array of DWORD (Blocks) so as to skip entire 32 IP chunks, if the block is fully set. I have also divided the DWORD further into byte based checking. so as to forgo checking of all 32 bits as much as possible. The code also skips any addresses with the lower octet being 0 or 1. The code only gets the lower two octets while the higher two octets are fixed to 10.0.

I know the problem with this approach is that the higher the IP, the slower it gets found. So how can I diminish the slow down? Should I go higher towards LongWORD for one block? Should I check the Block byte by byte or in smaller/bigger chunks? Or just abandon this and find some other algorithm?

The limit to be 500 is more of a marketing move than a technical one. We currently have to manage 1800 such networks. These networks are academic in nature and have very anomalous behavior patterns, as such that we are seeing almost 10000 requests per second in peak times.

---

var
  fIPPool : array [0..15] of DWORD;

---

constructor xxxx;
begin

  fIPPool [0]  := $00000003; // Skips 0.0 and 0.1
  fIPPool [7]  := $80000000; // Skips 0.255
  fIPPool [8]  := $00000003; // Skips 1.0 and 1.1
  fIPPool [15] := $FE000000; // Skips 1.249-1.255

end;

---

function GetIP: DWORD;
var
  Block, Cell : Byte;
  Mask : DWORD

  function GetCell ( const ABlock: DWORD; var AMask: DWORD; const ACell : Byte )
                   : Byte; inline;
  begin
    Result := ACell;
    while ( ABlock and AMask ) <> 0 do
    begin
      Result := Result + 1;
      AMask := AMask shl 1;
    end;
  end;

begin

  Result := 0;
  for Block := 0 to 15 do
  begin

    if fIPPool [Block] <> $FFFFFFFF then
    begin

      if ( fIPPool [Block] and $000000FF ) < $000000FF then
      begin
        Mask := $00000001;
        Cell := GetCell ( fIPPool [Block], Mask, 0 )
      end
      else if ( fIPPool [Block] and $0000FFFF ) < $0000FFFF then
      begin
        Mask := $00000100;
        Cell := GetCell ( fIPPool [Block], Mask, 8 )
      end
      else if ( fIPPool [Block] and $00FFFFFF ) < $00FFFFFF then
      begin
        Mask := $00010000;
        Cell := GetCell ( fIPPool [Block], Mask, 16 );
      end
      else
      begin
        Mask := $01000000;
        Cell := GetCell ( fIPPool [Block], Mask, 24 );
      end;

      Result := ( Block * 32 ) + Cell;
      fIPPool [Block] := fIPPool [Block] or Mask;
      break;

    end;

  end;

end;

// one can use the following line to get the IPs if run in a for-loop for 500 times
Memo1.Lines.Add
( IntToStr ( ( IP and $FF00 ) shr 8 ) +'.'+ IntToStr ( IP and $00FF ));


texts:
I generally like to be Rubocop-clean, but it seems like breaking up the first case statement will only make things harder to read. Any suggestions?

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.provider 'virtualbox' do |vb|
    vb.customize ['modifyvm', :id, '--memory', host_hardware[:memory],
                  '--cpus', host_hardware[:cpus], '--ioapic', 'on']
  end

  private

  # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
  def host_hardware
    case RUBY_PLATFORM
    when /linux/
      cpus = `nproc`.to_i
      memory = `sed -n -e '/^MemTotal/s/^[^0-9]*//p' /proc/meminfo`.to_i / 1024
    when /darwin/ # OS X
      cpus = `sysctl -n hw.ncpu`.to_i
      memory = `sysctl -n hw.memsize`.to_i / 1024 / 1024
    when /cygwin|mswin|mingw|bccwin|wince|emx/ # Windows
      cpus = `wmic computersystem get numberofprocessors`.split("\n")[2].to_i
      memory = `wmic OS get TotalVisibleMemorySize`.split("\n")[2].to_i / 1024
    else
      cpus = 2
      memory = 2048
    end
    { cpus: cpus, memory: reasonable_memory(memory) }
  end
  # rubocop:enable Metrics/AbcSize, Metrics/MethodLength

  def reasonable_memory(memory)
    half_of_memory = memory / 2
    case
    when half_of_memory < 1024
      1024
    when half_of_memory > 4096
      4096
    else
      half_of_memory
    end
  end
end


texts:
This is my second Ruby coding attempt. Also - this is my first OOP usage in Ruby.

I'm using if __FILE__ == $0 form here - same as it is in Python because it's really comfortably as for me. Is there is any objections/restrictions for such usage?

Any other tips/links about this code appreciated as well.

Script intended to create Consul raft-database backup before run destroy.rb from my previous review, or restore database after provisioning.

#!/usr/bin/env ruby

require 'net/ssh'

$me = File.basename(__FILE__)

class CheckIn

    USER = 'knife';
    RSA_KEY = 'ssh/id_rsa';

    def initialize(host)

        @@host = host;

        if File.exist?(RSA_KEY) then
            File.chmod(0600, RSA_KEY);
        else
            abort "[#{$me}] ERROR: no RSA file #{RSA_KEY} found. Exit.\n";
        end

    end
end

class BackupRestore < CheckIn

    def backup()

        _consul_raft_db = '/opt/consul/data/raft/raft.db'
        _root_backup_dir = '/root/vaul_devops_kdbx/backups'
        _raft_backup_file = "#{Time.now.strftime("%H_%M_%S_%d_%m_%y")}_bkp_raft.db"

        Net::SSH.start(@@host, USER, :keys => RSA_KEY) do |ssh|

            backuped = ssh.exec!("

            if test -e #{_consul_raft_db}; then
                echo \"\"
                echo \"OK: Consul DB found - #{_consul_raft_db}.\"
                echo \"\"
            else
                echo \"ERROR: no #{_consul_raft_db} file found. Exit.\"
                exit 1
            fi

            if sudo [ -d #{_root_backup_dir} ]; then
                echo \"OK: #{_root_backup_dir} found.\"
                echo \"\"
            else
                echo \"ERROR: no #{_root_backup_dir} directory found. Exit.\"
                exit 1
            fi

            if sudo cp #{_consul_raft_db} #{_root_backup_dir}/#{_raft_backup_file}; then
                echo \"OK: backup created:\"
                echo \"\"
                sudo ls -l #{_root_backup_dir}/#{_raft_backup_file}
                echo \"\"
                echo \"All backups present on the #{@@host} in the #{_root_backup_dir}:\"
                echo \"\"
                sudo ls -l #{_root_backup_dir}
                echo \"\"
            else
                echo \"\"
                echo \"ERROR: can not complete backup from #{_consul_raft_db} to #{_root_backup_dir}/#{_raft_backup_file}. Exit.\"
                exit 1
            fi

            ")

            puts backuped

        end
    end

    def restore()

        puts "\nRestore will be here\n\n"

    end

end

if __FILE__ == $0

    puts "\n[#{$me}] Consul backup/restore started.\n"

    if ARGV.length == 2 and (ARGV[1] == 'backup' or ARGV[1] == 'restore')
        _host = ARGV[0]
        _mode = ARGV[1]

        puts "\n[#{$me}] Working on the #{_host} in #{_mode} mode.";

        run = BackupRestore.new(_host)
        run.send(_mode)
    else
        abort "\n[#{$me}] ERROR: HOST must be specified as first argument and MODE (backup or restore) - as second one. Exit..\n"
    end

    puts "[#{$me}] Consul backup/restore finished.\n\n"

end

And it's execution - backup:

$ ./scripts/backup.rb setevoy.vault.local backup

[backup.rb] Consul backup/restore started.

[backup.rb] Working on the setevoy.vault.local in backup mode.

OK: Consul DB found - /opt/consul/data/raft/raft.db.

OK: /root/vaul_devops_kdbx/backups found.

OK: backup created:

-rw------- 1 root root 2097152 Feb 17 16:11 /root/vaul_devops_kdbx/backups/16_11_57_17_02_16_bkp_raft.db

All backups present on the setevoy.vault.local in the /root/vaul_devops_kdbx/backups:

total 20248
-rw------- 1 root root 1048576 Feb 17 14:21 14_21_50_17_02_16_bkp_raft.db
[...[
-rw------- 1 root root 2097152 Feb 17 16:11 16_11_57_17_02_16_bkp_raft.db

[backup.rb] Consul backup/restore finished.

and "restore":

$ ./scripts/backup.rb setevoy.vault.local restore

[backup.rb] Consul backup/restore started.

[backup.rb] Working on the setevoy.vault.local in restore mode.

Restore will be here

[backup.rb] Consul backup/restore finished.


texts:
I have such method and have a hard time optimizing it to run better. It takes roughly 1 sec with 100 units to get between NSLog(@"Debug2") and NSLog(@"Debug3"). And 2 sec on iPhone.

Method idea:

Input:

NSMutableArray times - containing times (2012-12-12, 2013-01-19) and etc
NSMutableArray objectArray - contains LogUnit objects.

Output: Array of computed views.

Main idea: a view for each time with objects from objectArray whose time is the same.

I have made it faster by showing a small proportion of objects (see counted in code and _breakPlease), yet it's still not fast enough.

- (NSMutableArray*) sortViews: (NSMutableArray *)times and:(NSMutableArray *)objectArray
{
    NSLog(@"debug2");
    NSMutableArray *views = [[NSMutableArray alloc] initWithCapacity:times.count];

    NSString *number = [NSString stringWithFormat:@"SortLog%i ",[[NSUserDefaults standardUserDefaults] stringForKey:@"ObjectNumber"].intValue];

    NSString *comp = [[NSUserDefaults standardUserDefaults] stringForKey:number];

    LogUnit *unit;

    int counted = 0;
    for(int x = 0; x != times.count; x++)
    {
        @autoreleasepool {

        UIView *foo = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 400)];
        foo.backgroundColor = [UIColor clearColor];

        int f = 0;
        int h = 0;

        NSString *attributeName = @"realTime";
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K IN %@", attributeName, [times objectAtIndex:x]];
        // Filter the objectArray by the time, so we don't have to run through all the objects in objectArray, and check if time is right.
        NSArray *filtered  = [objectArray filteredArrayUsingPredicate:predicate];

        for(int i = 0; i != filtered.count; i++)
        {
                unit = [filtered objectAtIndex:i];

                // Filter units by user choice (comp). Like comp = Warnings or comp = Errors and etc.
                if([[unit status] isEqualToString:comp] || [comp isEqualToString:NULL] || comp == NULL)
                {
                     // testing if the unit is correct to use
                    if([unit getEvent] != NULL)
                    {
                    // below is some computation for frames, to get them to proper position
                        unit.view.frame = CGRectMake(unit.view.frame.origin.x, f * unit.view.frame.size.height + 30, unit.view.frame.size.width, unit.view.frame.size.height);
                        [foo addSubview:unit.view];
                        counted++;
                        f++;
                        h = unit.view.frame.size.height * f;
                    }
                }
        }

        UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
        myLabel.backgroundColor = [UIColor clearColor];
        myLabel.font = [UIFont boldSystemFontOfSize:20];
        myLabel.textColor = [UIColor colorWithRed:88 green:154 blue:251 alpha:1];
        myLabel.textAlignment = UITextAlignmentCenter;
        myLabel.text = [times objectAtIndex:x];
        // Just adding a label with "2012-12-30" or etc on top of the view.
        [foo addSubview:myLabel];

        foo.frame = CGRectMake(0,0, 320, h + 30 );
        h = 0;
        [views addObject:foo];

        // counting added views for performance, if more than 30, return, and show only small portion of whole units, user has the option to show all the units if he wants to, but that takes a time to load..
        if(counted > 30 && filtered.count != counted)
        {
            if(_breakPlease == false)
            {
                _broken = true;
                break;
            }
        }
       }
    }
    NSLog(@"debug3");
    return views;
}


texts: Filter leading zeroes from numbers using only character operations for input and output

texts:
Problem:  to eliminate initial zeroes from numbers besides those followed by '.' or alone.  For example if we input a-000123+bc+0000.0008-0000+0001.07 , we will get a-123+bc+0.0008-0+1.07).

Using putchar and getchar only. No strings and pointers involved. I have working code, but I think it's confusing and overloaded. Can someone suggest how it might be simplified or an easier algorithm?

char curr_char = 0, prev_char = 0,flag=0;
while ((curr_char = getchar()) != '&')
{

    if (isdigit(curr_char) && !(isdigit(prev_char)))
        flag = 1;
    if (flag)
    {
        while (true)
        {
            if (curr_char=='0'); else break;
            curr_char = getchar();
        }

        if (curr_char == '.')putchar('0');

        while (true)
        {
            if (isdigit(curr_char))putchar(curr_char); else break;
            curr_char = getchar();
        }

        if (curr_char == '.')
        {
            putchar('.');
            while (isdigit(curr_char = getchar()))putchar(curr_char);
        }
        flag = 0;
    }
    else putchar(curr_char);
    prev_char = curr_char;
}


texts: Optimization of comparing two collections and get the changes

texts:
I use the following code to get the changes between two collections. Objects are "joined" using a primary key. Any tips on performance issues or other optimizations appreciated.

/// <summary>
/// Gets the changes [Deleted, changed, inserted] comparing this collection to another.
/// </summary>
/// <param name="local">The source collection.</param>
/// <param name="remote">The remote collection to comare agains.</param>
/// <param name="keySelector">The primary key selector function</param>
/// <returns></returns>
public static ChangeResult<TSource> CompareTo<TSource, TKey>(this IEnumerable<TSource> local, IEnumerable<TSource> remote, Func<TSource, TKey> keySelector)
{
    if (local == null)
        throw new ArgumentNullException("local");
    if (remote == null)
        throw new ArgumentNullException("remote");
    if (keySelector == null)
        throw new ArgumentNullException("keySelector");

    var remoteKeyValues = remote.ToDictionary(keySelector);

    var deleted = new List<TSource>();
    var changed = new List<TSource>();
    var localKeys = new HashSet<TKey>();

    foreach (var localItem in local)
    {
        var localKey = keySelector(localItem);
        localKeys.Add(localKey);

        /* Check if primary key exists in both local and remote
         * and if so check if changed, if not it has been deleted
         */
        TSource changeCandidate;
        if (remoteKeyValues.TryGetValue(localKey, out changeCandidate))
        {
            if (!changeCandidate.Equals(localItem))
                changed.Add(changeCandidate);
        }
        else
        {
            deleted.Add(localItem);
        }
    }
    var inserted = remoteKeyValues
                    .Where(x => !localKeys.Contains(x.Key))
                    .Select(x => x.Value)
                    .ToList();

    return new ChangeResult<TSource>(deleted, changed, inserted);
}

/// <summary>
/// Immutable class containing changes
/// </summary>
public class ChangeResult<T>
{
    public ChangeResult(IList<T> deleted, IList<T> changed, IList<T> inserted)
    {
        Deleted = new ReadOnlyCollection<T>(deleted);
        Changed = new ReadOnlyCollection<T>(changed);
        Inserted = new ReadOnlyCollection<T>(inserted);
    }

    public IList<T> Deleted { get; private set; }
    public IList<T> Changed { get; private set; }
    public IList<T> Inserted { get; private set; }
}

Usage

var changes = Col1.CompareTo(Col2, x => x.UniqueId);


texts: RXJS and Ionic- Sequencial Subscriptions Waiting on User Action

texts:
In an Ionic App a user can open a new browser via "inAppBrowser". I'm trying to get the stats of the user before they go into to the inAppBrowser, get the stats again when browser closes, and then run a function to compare the before and after.

What I have right now is working but I feel like I'm not doing it the proper RXJS way and I want to make sure I do this right. Is this a case for using MergeMap or is that making it needlessly complicated? Do I need to worry about possible race conditions?

Code Snippet:

let previousStats = []

    this.reloadStats(user)
      .pipe(
        first(), // getting only the first because I dont want this to update
        tap(val => {
          previousStats = val //setting the stats before the user leaves
        })
      )
      .subscribe()

    const browser = this.inAppBrowser.create(user.url) //user opens a browser

    this.subscriptionUserUrl = browser.on('exit') // user closes the browser
      .switchMap(() => this.reloadStats(user)) // get the most latest stats
      .subscribe(currentStats =>{
        this.handleBrowserExit(previousStats, currentStats) // do the comparison
      })


texts: Delete all occurrences of an item in linked list

texts:
This code takes an item as an argument and deletes all occurrences of the item in the linked list. It works well with my testing. Is there anything that I am missing? Can this code be improved further?

void
LinkedList::DeleteAllOccurences(int key) {
   Node *temp = head;
   Node *prev = head;
   while(temp!=NULL) {
      if(temp->item == key){
         if(temp == head) {
            head = temp->next;
            delete temp;
            temp = head;
         } else {
            prev->next = temp->next;
            delete temp;
            temp = prev->next;
         }
      } else {
         prev = temp;
         temp = temp->next;
      }
   }
   return;
}


texts:
The following code will be used for educational purposes. It is to demonstrate various way that the box-shadow property can be used. Any feedback on areas where I have not used best practices would be great.

Working example

HTML:

<!DOCTYPE HTML>

    <title>Box Shadow</title>
    <link rel="stylesheet" type="text/css" href="boxshadow.css">

CSS:

body{
        background: #ccc;
        margin: 0;
}
.container{
    padding: 20px 50px;
    overflow: hidden;
}
.box{
    background-color: #fff;
    width: 500px;
    height: 200px;
}
.left{
    float: left;
}
.right{
    float: right;
}
/* Basic Shadow */
.shadow1{
    box-shadow: 5px 5px 0 rgba(150,150,150,0.5);
}
/* Inset Shadow and blur radius Variety */
.shadow2{
    box-shadow: inset 0 0 10px black;
}
/* Inset Shadow and blur radius */
.shadow3{
  background: #F2F2F2;
  box-shadow: inset 3px 3px 3px #BFBFBF, inset -3px -3px 3px #8C8C8C;
  border-radius: 10px;
}
/* Spread radius Shadow */
.shadow4{
    box-shadow: 0 20px 10px -10px rgba(150,150,150,0.8);
}
/* Curved Shadows */
.shadow5{
    position: relative;
    overflow:hidden;
}
.shadow5:before{
    content: "";
    position: absolute;
    z-index: 1;
    width: 96%;
    top: -15px;
    height: 15px;
    left: 2%;
    border-radius: 100px / 5px;
    box-shadow: 0 0 39px rgba(0,0,0,0.6);
}
.shadow5:after{
    content: "";
    position: absolute;
    z-index: 1;
    width: 96%;
    bottom: -15px;
    height: 15px;
    left: 2%;
    border-radius: 100px / 5px;
    box-shadow: 0 0 39px rgba(0,0,0,0.6);
}
.shadow6{
    position: relative;
    overflow:hidden;
}
.shadow6:before{
  content: "";
  position:absolute;
  z-index: 1;
  width:10px;
  top: 5%;
  height: 90%;
  left: -10px;
  border-radius: 5px / 100px;
  box-shadow:0 0 13px rgba(0,0,0,0.6);
}
.shadow6:after{
  content: "";
  position:absolute;
  z-index: 1;
  width:15px;
  top: 5%;
  height: 96%;
  right: -15px;
  border-radius: 5px / 100px;
  box-shadow:0 0 13px rgba(0,0,0,0.6);
}


texts: Graph implementation for solving graph problems (java)

texts:
I've currently started solving some competitive programming Graph questions. But Started using adjacency list as HashMap<Integer,ArrayList<Integer>> list . But in some problems, this doesn't work. so I decided to implement class Graph other than this HashMap.
I would like a review of efficiency and general code quality. Please let me know if this follow standard adjacency list implementation and best and worst-case scenarios.
Node class
class Node
{
    public int id;
    public boolean visited;
    public List<Node> adjecent;
    Node(int id)
    {
        this.id =id;
        adjecent = new ArrayList<>();
    }
}

Graph
class Graph
{
   private List<Node> nodes;
    Graph()
    {
       nodes = new ArrayList<>();
    }
    boolean check(int id)
    {
        boolean flag = false;
        for(Node temp:nodes)
        {
            if(temp.id == id)
                flag =true;
        }

        return flag;
    }
    Node getNode(int id)
    {
        for(Node temp:nodes)
        {
            if(temp.id == id)
                return temp;
        }
        return null;
    }
    void addEdge(int src,int dest)
    {

        Node s = check(src) ? getNode(src):new Node(src);
        Node d = check(dest) ? getNode(dest):new Node(dest);
        s.adjecent.add(d);
        d.adjecent.add(s);

        if(!check(src)) nodes.add(s);
        if(!check(dest)) nodes.add(d);
    }

    void print()
    {
        for(Node temp : nodes)
        {
            System.out.print(temp.id+" -> ");
             temp.adjecent.forEach(e->System.out.print(e.id+" "));
            System.out.println();
        }
    }
    void dfs(Node root)
    {
        if(root == null) return;
        System.out.print(root.id+" ");
        root.visited = true;
        for(Node t : root.adjecent)
        {
            if(!t.visited)
                dfs(t);
        }
    }
    void refresh()
    {
        for(Node temp : nodes)
        {
            temp.visited =false;
        }
    }
    void bfs(Node root)
    {
        Queue<Node> q =new LinkedList<>();
        root.visited =true;
        q.add(root);
        while(!q.isEmpty())
        {
            Node temp = q.poll();
            System.out.print(temp.id+" ");
            for(Node n:temp.adjecent)
            {
                if(!n.visited)
                    {
                        n.visited=true;
                        q.add(n);
                    }
            }
        }
    }

    public static void main(String[] args) {
        Graph g = new Graph();
        /*
         *                0
         *             /  |  \
         *            1   2   3
         *           / \   \   \
         *          4  5    6   7
         */
        g.addEdge(0, 1);
        g.addEdge(0, 2);
        g.addEdge(0, 3);
        g.addEdge(1, 4);
        g.addEdge(1, 5);
        g.addEdge(2, 6);
        g.addEdge(3, 7);
        g.print();
        System.out.println(g.nodes.size());
        g.dfs(g.getNode(0));
        System.out.println();
        g.refresh();
        g.bfs(g.getNode(0));

    }
}

Any suggestions to make this code leverage to better efficiency is appreciated.


texts:
I have script which plays audio, shows/hides elements:

   var audio = new Audio("audio/test.mp3");

    audio.addEventListener("ended", function(){
             element.fadeIn(0);
             setTimeout(function() {
                element2.fadeIn(0);
                setTimeout(function() {
                    element3.fadeIn();
                    sprite.play(); // a one lib for playing sprites
                },1000)
             },1000)
        });

// this is just event and we look for the last frame
sprite.on("frame", function(){
        if(this.frame === this.frames - 1)
        {
            this.pause();
            setTimeout(function() {
                //here we show some another elements and play another audio
            },1000)
        }
    });

audio.play();

As you can see there are a lot of setTimeout and spaghetti code. This is very short version, I have more than 5 audio files and a lot of elements which I have to show and hide, and, it's very difficult to understand the order audio files playing and showing/hiding elements in the end. May be you know how to organize this flow, some libraries? I am a noob at promises, is it good idea here?


texts:
I want to get just the first line of a big string. Currently, here's how I do it:

def getFirstParagraph(txt: String) = {
    val newLineIdx = txt.indexOf("\n") match {
        case i: Int if i > 0 => i
        case _               => txt.length
    }

    txt.substring(0, newLineIdx)
}

But my friend sees some downfall: if txt is null, there will be an exception. His suggestion involved using var:

def getFirstParagraph(txt: String) = {
    var result = txt
    scala.util.control.Exception.ignoring(classOf[Exception]) {
        result = result.substring(0, result.indexOf("\n"))
    }
    result
}

Which will handle the null value fine. Thing is, I'm quite uncomfortable using var. How can I handle this case without using var (aka the Scala / functional way)?


texts:
I am doing a project where I am analyzing a group of Tweets.

What I need to do is find the occurrence of each individual word. I am fairly new to Redis, so I am not quite sure that my solution is optimal. I am storing a key value pair for each word. The key is a word, and the value is the occurrence count. I then use a list to keep track of every word that goes into the cache.

$cache = new Redis;
$words = array('foo', 'bar', 'baz');

foreach ($words as $word) {
    if ($cache->exists($word) {
        $cache->incr($word);
    } else {
        $cache->put($word, 1);
        $cache->lpush('words', $word);
    }
}

$data = array();
$list = $cache->lrange('words', 0, -1);

foreach ($list as $word) {
    $data[$word] = $cache->get($word);
}

asort($data);


texts:
I found a function online that tests if a tree is a binary search tree:

private boolean isBST(Node node) {
  if (node==null) return(true);

  // do the subtrees contain values that do not
  // agree with the node?
  if (node.left!=null && maxValue(node.left) > node.data) return(false);
  if (node.right!=null && minValue(node.right) <= node.data) return(false);

  // check that the subtrees themselves are ok
  return( isBST(node.left) && isBST(node.right) );
}

I don't quite understand why maxValue and minValue are being used.

Here is the code for both functions:

private int minValue(Node node) {
  Node current = node;
  while (current.left != null) {
    current = current.left;
  }

  return(current.data);
}

private int maxValue(Node node) {
  Node current = node;
  while (current.right != null) {
    current = current.right;
  }

  return(current.data);
}

I made some edits to the isBST1 in my own way, but I'm not sure if there are any flaws in it or not.

static boolean isBST1(BinaryTreeNode root) {
    if (root == null) {
        return true;
    }
    if (root.left != null && root.left.value > root.value) {
        return false;
    }
    if (root.right != null && root.right.value < root.value) {
        return false;
    }
    return isBST1(root.left) && isBST1(root.right);

}

I am wondering if there is any sort of logic I am missing.


texts: Is my logic correct checking for a newer remote file?

texts:
String slm = status.getHeader("last-modified");
        SimpleDateFormat sdf = new SimpleDateFormat(
                "EEE, dd MMM yyy HH:mm:ss zzz");

        Date serverLastMod = null;
        try {
            serverLastMod = sdf.parse(slm);
        } catch (ParseException e) {
            Log.e("SAC XML last-modified", e.getMessage());
        }
        Date fileLastFetched = status.getTime();

        Log.e("DATE1", serverLastMod.toGMTString());
        Log.e("DATE2", fileLastFetched.toGMTString());

        //if the server date is before my file date, update it, else dont

        if (serverLastMod.after(fileLastFetched)) {
            Log.e("DS", "YES! Getting ROSE");

            XmlDom r = xml.tag("reportrose");
            roseUrl = r.tag("img").attr("src").trim();
            aq.download(roseUrl, file, new AjaxCallback<File>() {

                public void callback(String url, File file, AjaxStatus status) {
                    String s = status.getMessage();
                    int i = status.getCode();
                    String e = s + " | Status Code: " + i;

                    if (file != null) {
                        getInfo();
                    } else {
                        Log.e("ACR SAC Widget Error", e);
                    }
                }

            });
        } else {
            Log.e("DS", "NO! Don't do anything... Wait until next check...");
        }


texts: Count sub-sequences of an array having median lying in that subsequence itself

texts:
We need to calculate the number of sub-sequences of an array having its median lying in the sub-sequence itself. My code is -

#include <bits/stdc++.h>
using namespace std;

#define MOD 1000000007
#define fori0n for(int i=0;i<n;i++)
#define inputLoop for(int j=0;j<t;j++)

// FAST SCANNING ..
template<typename T> void scan(T &x)
{
     x = 0;
     bool neg = 0;
     register T c = getchar();

     if (c == '-')
     neg = 1, c = getchar();

     while ((c < 48) || (c > 57))
     c = getchar();

     for ( ; c < 48||c > 57 ; c = getchar());

     for ( ; c > 47 && c < 58; c = getchar() )
             x= (x << 3) + ( x << 1 ) + ( c & 15 );

      if (neg) x *= -1;
}

// FAST PRINTING..
template<typename T> void print(T n)
{
     bool neg = 0;

     if (n < 0)
     n *= -1, neg = 1;

     char snum[65];
     int i = 0;
     do
     {
          snum[i++] = n % 10 + '0';
          n /= 10;
     }

     while (n);
     --i;

     if (neg)
       putchar('-');

     while (i >= 0)
         putchar(snum[i--]);

     putchar('\n');
}

float median(vector<int> new_array, int num){
       sort(new_array.begin(), new_array.end());
       float median = (num % 2 != 0) ? (new_array[((num+1)/2)-1]) : (float)(new_array[(num/2)-1] + new_array[num/2]) / 2;
      return median;
}

void subsetsUtil(vector<int>& A, vector<vector<int> >& res,
            vector<int>& subset, int index)
{
for (int i = index; i < A.size(); i++) {

    // include the A[i] in subset.
    subset.push_back(A[i]);
    res.push_back(subset);

    // move onto the next element.
    subsetsUtil(A, res, subset, i + 1);

    subset.pop_back();
}

return;
}

vector<vector<int> > subsets(vector<int>& A)
{
    vector<int> subset;
    vector<vector<int> > res;

    // include the null element in the set.
    //res.push_back(subset);

    // keeps track of current element in vector A;
    int index = 0;
    subsetsUtil(A, res, subset, index);

   return res;
}

int main()
{

//ios_base::sync_with_stdio(false);
//cin.tie(NULL);

int t;
scan(t);
//cin>>t;
inputLoop {
int n;
scan(n);
//cin>>n;

// find the subsets of below vector.
vector<int> arr;

int input;
fori0n {
    //cin>>input;
    scan(input);
    arr.push_back(input);
}

vector<vector<int> > res = subsets(arr);
int goodMedian = 0;
// Print result
for (int i = 0; i < res.size(); i++) {

    //cout<<"Sub set : "<<i<<" _ With Size :  "<<res[i].size()<<" == ";

    // if size == 1 or 3
    if(res[i].size() % 2 != 0) {
        // there will always be a good median
        //cout<<"GOOD MEDIAN ";
        goodMedian++;
    }
    else if(res[i].size() == 2) {
        if(median(res[i], 2) == res[i][0] || median(res[i], 2) == res[i][1]) {
            //cout<<"GOOD MEDIAN ";
            goodMedian++;
        }
    }
    else if(res[i].size() % 2 == 0) {
        int size = res[i].size();
        if(median(res[i], res[i].size()) == res[i][size / 2] || median(res[i], res[i].size()) == res[i][(size - 1)/2]) {
            //cout<<"GOOD MEDIAN ";
            goodMedian++;
        }
    }

    //for (int j = 0; j < res[i].size(); j++)
    //  cout << res[i][j] << " ";
    //cout << endl;

}
      print(goodMedian % MOD);
    }
   return 0;
}

Can anyone suggest any better algorithm for this problem ?


texts:
I just coded method for loading data from SqLite 3 database, it is working and in test run it was successfully checked for no memory leaks:

template<typename T>
inline std::vector<T> Database::fill_from_table(const std::string& table_name, const std::vector<std::pair<std::string, void(*)(T &, char *)>>& setters, int64_t limit)
{
    if(!is_open_) throw SQLException("No sql connection");

    typedef void(*setter_t)(T& , char *);

    struct callback_data {
        std::vector<T>& result_vec;
        const std::vector<std::pair<std::string, void(*)(T &, char *)>>& setters;
    };
    callback_data data { std::vector<T>(), setters };

    data.result_vec.reserve(limit == -1 ? row_count(table_name) : limit);

    auto names = column_names(table_name);
    std::stringstream queried_cols;
    for (auto& it = setters.cbegin(); it < setters.cend() - 1; ++it)
    {
        if(std::find(names.cbegin(), names.cend(), it->first) == names.cend())
            throw SQLException("No such column \""+ it->first + "\" in table " + table_name);
        queried_cols << it->first << ", ";
    }
    queried_cols << setters.back().first;

    char *err_msg = nullptr;
    auto query = "SELECT " + queried_cols.str() +" FROM " + table_name + " LIMIT " + std::to_string(limit) + ";";

    auto result = sqlite3_exec(db, query.c_str(), [](void *in_cd, int c, char **col_data, char **n) {
        auto& cd = (*static_cast<callback_data*>(in_cd));
        T item;
        for (int i = 0; i < cd.setters.size(); i++) cd.setters[i].second(item, col_data[i]);
        cd.result.push_back(item);
        return 0; }, &data, &err_msg);

    if (result != SQLITE_OK) {
        std::string tmp(err_msg);
        sqlite3_free(err_msg);
        throw SQLException(tmp.c_str());
    }

    return data.result_vec;
}

where the relevant signatures(implementations can be assumed correct) are:

//SQLException.h
class SQLException : public std::runtime_error { ... }
//database.h
class Database
{
private:
    sqlite3 *db;
    bool is_open_;

public:
    const std::vector<std::string> column_names(const std::string& table_name);
    int64_t row_count(const std::string& table_name);

    template<typename T>
    std::vector<T> fill_from_table(const std::string& table_name, const std::vector<std::pair<std::string, void(*)(T &, char *)>>& setters, int64_t limit = -1);
};

Firstly, I am concerned about correctness of const-ness and (reference) types - arguments, local variables and especially the struct callback_data and return type. Regarding struct callback_data, there is also question about design - because I was unable to capture local variables to sqlite3_exec callback I chose to add this struct.
Also I am not-so-sure about correctness of interaction of custom error handling and SqlLite error handling. The performance is also concern and overall design  involving lambdas be can incorrect(?) because of this.
What is not important? Sql security(not type safety!) and functionality improvements - i.e. WHERE clause is omitted on purpose.
...and of-course, I am always looking to improve my C++ skills, so if you see any errors in parts I did not mention feel free to comment/answer.

usage example:

struct TimeStampValue {
    double value, time;
};

auto data = database.fill_from_table<TimeStampValue>("measuredvalues", {
    { "date_time", [](TimeStampValue& i, char* v) { i.time = utils::days_since_1900_ISO_ext(v); } },
    { "value" ,    [](TimeStampValue& i, char* v) { i.value = v ? std::stod(v) : -1.0; } }}
);


texts:
I wrote a little function to create a sorted-map with vectors of coordinates as keys and an empty map as a default value:

(defn empty-board [rows cols]
  (into (sorted-map)
        (for [x (range cols) y (range rows)]
            [[x y] {}])))

Is there is a more idiomatic way of achieving this?


texts: Refactor PHP | Laravel Code, Optimisation needed to make code clean

texts:
I have made some notification preferences in which there are 4 major preferences

SMS
PUSH
FAX
EMAIL

And then there are some specific templates such as booking-accepted and within booking accepted there are again these 4 notifications.

So what I have to do I need to check 1st priority notification preferences first that if SMS is on then I have to check regarding specific templates that SMS is on in booking-accepted and then I'll send the notification or will just unset the recipient.

The object on notification preferences is as follows

{
    "sendSms": "1",
    "sendFax": "1",
    "sendEmail": "1",
    "sendPush": "0",
    "specific-templates": [
        {
            "update-video-physical-address": [
                {
                    "sendPush": "1",
                    "sendSms": "0",
                    "sendEmail": "0"
                }
            ],
            "booking-denied": [
                {
                    "sendPush": "1",
                    "sendSms": "0"
                }
            ]
        }
    ],
}

And The code I did for this is given below which is bit messy and unclean.

 foreach ($recipients as $recipient) {
            $user = $userRepository->findByParams([
                'email' => $recipient->getUser()->email
            ]);
            if (!is_null($user->userNotificationPreference) && array_key_exists($sendMethod, $user->userNotificationPreference->preferences)
                && $user->userNotificationPreference->preferences[$sendMethod] == true) {
                if (array_key_exists($notification->getTemplateCode(), $user->userNotificationPreference->preferences['specific-templates'][0])) {
                    if (array_key_exists($notification->getTemplateCode(), $user->userNotificationPreference->preferences['specific-templates'][0])
                        && array_key_exists($sendMethod, $user->userNotificationPreference->preferences['specific-templates'][0][$notification->getTemplateCode()][0])) {
                        if ($user->userNotificationPreference->preferences['specific-templates'][0][$notification->getTemplateCode()][0][$sendMethod] == false) {
                            $key = array_search($recipient, $recipients->toArray());
                            unset($recipients[$key]);
                        }
                    }
                }
            } elseif (!is_null($user->userNotificationPreference) && array_key_exists($sendMethod, $user->userNotificationPreference->preferences)
                && $user->userNotificationPreference->preferences[$sendMethod] == false) {

                $key = array_search($recipient, $recipients->toArray());
                unset($recipients[$key]);

            }
        }

        return $recipients;

getTemplateCode() will return the template code i.e booking-accepted
$sendMethod is method i.e sendSms, sendPush

Please help me with writing this mode more clean and efficient way such as reducing IFs and any other approach


texts:
I just wanted some review and opinions. Any better implementations or suggestions would be great.

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

var sequence = [1,2]

var index = 1
var sum = 0

repeat {
    sequence.append(sequence[index-1] + sequence[index])
    index = index + 1
} while sequence[sequence.endIndex - 1] < 4000000

sequence.popLast()

for numbers in sequence {
    if (numbers % 2 == 0) {
        sum += numbers
    }
}
print(sum)


texts: Python decorator for optional arguments decorator

texts:
I want my Python decorators to have optional arguments and not be called when not necessary.

The accepted answer in here doesn't accept named arguments, and I don't want to add boilerplate code inside decorators, so I came up with an alternative decorator:

import inspect

def decorator_defaults(**defined_defaults):
    def decorator(f):
        args_names = inspect.getargspec(f)[0]

        def wrapper(*new_args, **new_kwargs):
            defaults = dict(defined_defaults, **new_kwargs)
            if len(new_args) == 0:
                return f(**defaults)
            elif len(new_args) == 1 and callable(new_args[0]):
                return f(**defaults)(new_args[0])
            else:
                too_many_args = False
                if len(new_args) > len(args_names):
                    too_many_args = True
                else:
                    for i in range(len(new_args)):
                        arg = new_args[i]
                        arg_name = args_names[i]
                        defaults[arg_name] = arg
                if len(defaults) > len(args_names):
                    too_many_args = True
                if not too_many_args:
                    final_defaults = []
                    for name in args_names:
                        final_defaults.append(defaults[name])
                    return f(*final_defaults)
                if too_many_args:
                    raise TypeError("{0}() takes {1} argument(s) "
                                    "but {2} were given".
                                    format(f.__name__,
                                           len(args_names),
                                           len(defaults)))
        return wrapper
    return decorator

Two sample decorators:

from functools import wraps

@decorator_defaults(start_val="-=[", end_val="]=-")
def my_text_decorator(start_val, end_val):
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            return "".join([f.__name__, ' ', start_val,
                            f(*args, **kwargs), end_val])
        return wrapper
    return decorator

@decorator_defaults(end_val="]=-")
def my_text_decorator2(start_val, end_val):
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            return "".join([f.__name__, ' ', start_val,
                            f(*args, **kwargs), end_val])
        return wrapper
    return decorator

And usage of sample text decorators:

@my_text_decorator
def func1a(value):
    return value

@my_text_decorator()
def func2a(value):
    return value

@my_text_decorator2("-=[")
def func2b(value):
    return value

@my_text_decorator(end_val=" ...")
def func3a(value):
    return value

@my_text_decorator2("-=[", end_val=" ...")
def func3b(value):
    return value

@my_text_decorator("|> ", " <|")
def func4a(value):
    return value

@my_text_decorator2("|> ", " <|")
def func4b(value):
    return value

@my_text_decorator(end_val=" ...", start_val="|> ")
def func5a(value):
    return value

@my_text_decorator2("|> ", end_val=" ...")
def func5b(value):
    return value

print(func1a('My sample text'))  # func1a -=[My sample text]=-
print(func2a('My sample text'))  # func2a -=[My sample text]=-
print(func2b('My sample text'))  # func2b -=[My sample text]=-
print(func3a('My sample text'))  # func3a -=[My sample text ...
print(func3b('My sample text'))  # func3b -=[My sample text ...
print(func4a('My sample text'))  # func4a |> My sample text <|
print(func4b('My sample text'))  # func4b |> My sample text <|
print(func5a('My sample text'))  # func5a |> My sample text ...
print(func5b('My sample text'))  # func5b |> My sample text ...

decorator_defaults works, but I believe it could be written better.
I'm not that experienced in Python, so I would like to hear some ideas/comments on how to improve it.


texts: Upgrade script for MediaWiki website with one external addon (wave 1)

texts:
I have a MediaWiki 1.33.0 website with only one external addon installed (external extension), which is ContactPage.
I have created the following script with that logic:

  if there is an upgrade to either MediaWiki core OR ContactPage these will be upgraded respectively;
  else, the script keeps the original state (that is, the state before the upgrade attempt). Successful upgrading might
  require further manual changes although I didn't have a case of
  needing to make manual changes.

I tested the script and it seems to work as expected; if no new version was released, the current ones are kept.

The script:

# Declare MediaWiki download variables (ensure latest versions are downloaded because as of 08/10/19 there aren't version-agnostic download links):

latest_mediawiki_core="https://releases.wikimedia.org/mediawiki/1.33/mediawiki-1.33.0.tar.gz"
latest_contactpage_extension="https://extdist.wmflabs.org/dist/extensions/ContactPage-REL1_33-abdcab9.tar.gz"

# Declare other important variables:

current_date="$(date +%Y-%m-%d-%H-%M-%S)"
war="$HOME/public_html" # Web Application Root # Change to your Web Application Root if needed
domain="example.com" # Change to relevant domain
db-username_and_db-name="DB_CREDENTIALS" # Change to relevant DB credentials

# Create backup directories:

mkdir -p "${war}/mediawiki_general_backups"
mkdir -p "${war}/mediawiki_specific_backups"

# General backups:

zip -r "${war}/mediawiki_general_backups/${domain}-directory-backup-${current_date}.zip" "${war}/${domain}"
mysqldump \
-u "${db-username_and_db-name}" \
-p "${db-username_and_db-name}" \
> "${war}/mediawiki_general_backups/${db-username_and_db-name}-${current_date}.sql"

# Specific backups:

rm "${war}"/mediawiki_specific_backups/*
rm "${war}"/mediawiki_specific_backups/.* # If I won't run this, a specific backup of .htaccess, in that directory, won't get deleted;

cp "${war}/${domain}"/.htaccess*                  "${war}/mediawiki_specific_backups"/.htaccess*
cp "${war}/${domain}"/LocalSettings.php           "${war}/mediawiki_specific_backups"/LocalSettings.php
cp "${war}/${domain}"/robots.txt                  "${war}/mediawiki_specific_backups"/robots.txt
cp "${war}/${domain}"/${domain}.png               "${war}/mediawiki_specific_backups"/${domain}.png
cp "${war}/${domain}"/googlec69e044fede13fdc.html "${war}/mediawiki_specific_backups"/googlec69e044fede13fdc.html

# Downloads and configurations:

rm -rf "${war}/${domain}"
mkdir "${war}/${domain}"
wget "${latest_mediawiki_core}" -O - | tar -xzv --strip-components 1 -C "${war}/${domain}"
wget "${latest_contactpage_extension}" -O - | tar -xzv -C "${war}/${domain}"/extensions/
cp -a "${war}/mediawiki_specific_backups"/* "${war}/${domain}"

# Create a new sitemap:

mkdir -p "${war}/${domain}/sitemap"
php "${war}/${domain}"/maintenance/generateSitemap.php \
--memory-limit=50M \
--fspath=/"${war}/${domain}/sitemap" \
--identifier="${domain}" \
--urlpath=/sitemap/  \
--server=https://"${domain}" \
--compress=yes

# Update DB (One might need to change LocalSettings.php before doing so):
php "${war}/${domain}"/maintenance/update.php


texts: Auditing a complex mix of reasonably small tables

texts:
I plan to use the following approach to audit the tables that represent user-editable configuration of an automated system (over the course of system's life these will be inevitably extended in their numbers and stuffed with more columns). This approach will not be applied to main data tables as those are automatically updated.

SQL Server 2005+, based on this. Suggestions?

CREATE TABLE [dbo].[audit] (
      [id] [bigint] IDENTITY(1,1) NOT NULL,
      [time] [datetime] NOT NULL,
      [username] [nvarchar](128) NOT NULL,
      [useraddress] [nvarchar](48) NULL,
      [tablename] [nvarchar](128) NULL,
      [operation]  AS (case when [oldvalue] IS NULL then 'I' when [newvalue] IS NULL then 'D' else 'U' end),
      [oldvalue] [xml] NULL,
      [newvalue] [xml] NULL
)
GO

ALTER TABLE [dbo].[audit] ADD CONSTRAINT [DF_audit_time] DEFAULT (sysutcdatetime()) FOR [time]
GO

CREATE PROCEDURE [dbo].[save_audit]
      @old_values xml,
      @new_values xml,
      @tablename nvarchar(128)
AS
BEGIN
      SET NOCOUNT ON;

      IF @old_values IS NOT NULL OR @new_values IS NOT NULL
      BEGIN
            DECLARE
                  @username nvarchar(128),
                  @useraddress varchar(48)

            SELECT @username = original_login_name FROM sys.dm_exec_sessions WHERE session_id = @@SPID
            SELECT @useraddress = client_net_address FROM sys.dm_exec_connections WHERE session_id = @@SPID

            INSERT INTO audit (username, useraddress, tablename, oldvalue, newvalue)
            VALUES (@username, @useraddress, @tablename, @old_values, @new_values)
      END
END
GO

CREATE TRIGGER [dbo].[audit_tablename] ON [dbo].[tablename]
    AFTER INSERT,DELETE,UPDATE
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @i xml, @d xml, @t nvarchar(128)
    SET @i = (SELECT * FROM inserted FOR XML AUTO)
    SET @d = (SELECT * FROM deleted FOR XML AUTO)
    SET @t = (SELECT OBJECT_NAME(parent_object_id) FROM sys.objects WHERE object_id = @@PROCID)
    EXEC save_audit @d, @i, @t
END

EDIT: Table name detection was found unreliable on 2005, fixed.

EDIT2: Not all versions of SQL Server 2005 have original_login_name column in sys.dm_exec_sessions (it was added with SP2, apparently), will have to use login_name if targeting all versions (the meaning is different, though).


texts: Arguments in constructors matching fields

texts:
What is your opinion in arguments in constructors matching members as in the following example

public Join(final int parent, final TIntHashSet children) {
  this.parent = parent;
  this.children = children;
}

I find this annoying since I have to use this. and also some code review applications generate warnings.


texts: Running arbitrary number of mongo queries in nodejs

texts:
I am faced yet again with a callback headache:

Simply I need to return to the client the results of multiple mongo queries, the number of which I don't know in advance.
In short:

fetch the first document in a collection
if the document has some
fields with alphabetic values, fetch all distinct values

Since I can only do the next query in the result callback of the previous one, that's what am doing keeping track of how many fields I have queried so far:

function getFieldsFromCollection (collection, socket) {
  MongoClient.connect(MAIN_DB, function (err, db) {
    if (err) {
      return console.log(err)
    }
    var c = db.collection(collection)
    c.findOne({}, {}, function (err, doc) {
      if (err) {
        return log(err)
      }
      if (!doc) {
        return log('document is null')
      } else {
        var alphaFields = []
        Object.keys(doc).forEach(function (key) {
          if (/^[A-Z]/.test(doc[key])) {
            alphaFields.push(key)
          }
        })
        // prepare the response
        var reply = {
          alphaFields: alphaFields,
          alphaFieldsValues: {}
        }
        fetchDistinctValues(c, alphaFields, 0, reply, socket)
      }
    })
  })
}

function fetchDistinctValues(collection, fields, index, reply, socket) {
  if (index < fields.length) {
    collection.distinct(fields[index], function (err, docs) {
      reply.alphaFieldsValues[fields[index]] = docs
      fetchDistinctValues(collection, fields, ++index, reply, socket)
    })
  } else {
    socket.emit('getFieldsFromCollectionReply', reply)
  }
}

Needless to say this feels very hackysh..
I've looked into some libraries or promises but they seem to offer solution for when one knows exactly how many queries have to be made.
Please tell me there is a better way


texts: Extension Method for Creating Types from Regular Expression Match Groups

texts:
I've been doing some parsing with regular expression named capture groups and decided it might make sense to write an extension to handle this.

The code below will create an instance of a specified type and attempt to match the property names to the capture group names and then set the values.  It also attempts to cast between compatible types.

Any suggestions for improving this code? Is it ok as an extension?

 public static class RegularExpressionExtension
{
    public static T CreateType<T>(this Regex regEx, string matchString) where T : new()
    {
        MatchCollection matchCollection = regEx.Matches(matchString);
        T obj = new T();
        Type type = typeof(T);
        PropertyInfo[] properties = type.GetProperties();

        IEnumerable<string> groupNames = regEx.GetGroupNames().Skip(1); //First Group is always 0
        if (matchCollection.Count >= 1)
        {
            SetPropertyValuesFromGroupMatches<T>(groupNames, regEx, obj, matchCollection[0].Groups, properties);
        }
        return obj;
    }

    public static IEnumerable<T> CreateTypeCollection<T>(this Regex regEx, string matchString) where T : new()
    {
        MatchCollection matchCollection = regEx.Matches(matchString);
        IEnumerable<string> groupNames = regEx.GetGroupNames().Skip(1); //First Group is always 0
        Type type = typeof(T);
        PropertyInfo[] properties = type.GetProperties();

        foreach (Match match in matchCollection)
        {
            T obj = new T();
            SetPropertyValuesFromGroupMatches<T>(groupNames, regEx, obj, match.Groups, properties);
            yield return obj;
        }
    }

    private static void SetPropertyValuesFromGroupMatches<T>(IEnumerable<string> groupNames, Regex regEx, T typeToPopulate, GroupCollection groupCollection, PropertyInfo[] properties)
    {
        Type type = typeof(T);

        foreach (string group in groupNames)
        {
            var foundProperty = properties.SingleOrDefault(p => p.Name.Equals(group,StringComparison.CurrentCultureIgnoreCase));
            if (foundProperty != null)
            {
                var matchValue = groupCollection[group].Value;
                object convertedValue = System.ComponentModel.TypeDescriptor.GetConverter(foundProperty.PropertyType).ConvertFrom(matchValue);
                foundProperty.SetValue(typeToPopulate, convertedValue, null);
            }
        }
    }
}


texts: null/undefined checking for checking seats

texts:
This looks pretty messy (need to reduce nesting I feel).  I need a check an input for a seat, but I can't guarantee it has a value (one may not be chosen for example). If the seats aren't in a certain color it goes to seat basic (1), otherwise seat premium (2).

 var seat = $("input[id*=" + seatPrefix + "]");
    if (seat != 'undefined') {
        seat = seat[0].value;
        if (seat != "") {
            if (seat != "red" && seat != "blue" && seat != "silver" && seat != "gold") {
                chooseSeat(seat, "2");
            }
            else {
                chooseSeat(seat, "1");
            }
        }
    }


texts: Identify the Length of the Longest Substring Without Repeating Characters

texts:
Length of Longest Substring Without Repeating Characters

Problem (from Leetcode)

  Given a string, find the length of the longest substring without repeating characters.

Examples

Given abcabcbb, the answer is abc, which the length is 3.

bbbbb, the answer is b, with the length of 1.

Given pwwkew, the answer is wke, with the length of 3. Note that the answer must be a substring, pwke is a subsequence and not a substring.

Discussion

Approach

Keep track of the substring characters in a Set.
Keep track of the evaluated ("seen") characters in a Queue.
Iterate through the characters in the input String.

If the substring characters include the current character

Iterate through the head of the seen characters Queue until you find a match in the Queue.
For each non-matching character from the Queue, remove it from the Queue and remove it from the Set.
Once you find a matching character, remove it from the head of the Queue and add it to the tail of the Queue.

Else

Add the current character to the Set
Add the current character to the tail of the Queue.

If the size of the Set is greater than the current longest substring length, replace the current longest substring length with the Set size.

General Questions

Naming sucks - open to a better name - there's gotta be something better than LongestSubstringWithoutRepeatingCharactersLengthIdentifier...right?
Is there a cleaner implementation that uses other data structures?

Implementation

import java.util.HashSet;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;

public class LongestSubstringWithoutRepeatingCharactersLengthIdentifier {
    public static int identify(String s) {
        int longestSubstringLength = 0;
        Set<Character> substringCharacters = new HashSet<>();
        Queue<Character> seenCharacters = new LinkedBlockingQueue<>();

        for (char currentCharacter : s.toCharArray()) {
            if (substringCharacters.contains(currentCharacter)) {
                while (seenCharacters.peek() != currentCharacter) {
                    substringCharacters.remove(seenCharacters.poll());
                }
                seenCharacters.poll();
            } else {
                substringCharacters.add(currentCharacter);
            }

            seenCharacters.add(currentCharacter);

            if (substringCharacters.size() > longestSubstringLength) {
                longestSubstringLength = substringCharacters.size();
            }
        }
        return longestSubstringLength;
    }
}


texts: DeepPtr: a deep-copying unique_ptr wrapper in C++

texts:
When using the pimple idiom it is necessary to represent your "impl" as a forward declared pointer in the header file.  This necessitates a lot of boilerplate code to implement the rule of five.

Instead, I want to wrap std::unique_ptr with a template class DeepPtr which automatically deep copies on copy construction, assignment, and "deep" swaps on move construction and move assignment.  The resulting class could also be convenient for "value-like" objects that need to be passed by handle due to polymorphism.

Areas of concern are:

Correct use of the swap idiom (should the local swap function be private/public or done some other way)?
Const correctness of the dereferencing operator overloads
Signature of the assignment operator function (const DeepPtr& other) which uses this const ref only to copy to temp.  This seems strange, but correct.
Any other pitfalls that could be caused by this class.

#pragma once
#include <iostream>
#include <memory>

template <typename T>
class DeepPtr
{
public:
    DeepPtr() :myPtr( nullptr ) {}

    DeepPtr( const T& value ) :myPtr( new T{ value } ) {}

    DeepPtr( const DeepPtr& other )
    :myPtr( nullptr )
    {
        if ( other )
        {
            myPtr = std::unique_ptr<T>{ new T{ *other } };
        }
    }

    DeepPtr( DeepPtr&& other )
    :myPtr( nullptr )
    {
        if ( other )
        {
            myPtr = std::unique_ptr<T>{ new T{ *other } };
        }
    }

    DeepPtr& operator=( const DeepPtr& other )
    {
        DeepPtr temp{ other };
        swap( *this, temp );
        return *this;
    }

    DeepPtr& operator=( DeepPtr&& other )
    {
        swap( *this, other );
        return *this;
    }

    static void swap( DeepPtr& left, DeepPtr& right ) { std::swap( left.myPtr, right.myPtr ); }

    T& operator*() { return *myPtr; }

    const T& operator*() const { return *myPtr; }

    T* const operator->() { return myPtr.operator->(); }

    const T* const operator->() const { return myPtr.operator->(); }

    const T* const get() const { return myPtr.get(); }

    operator bool() const { return (bool)myPtr; }

private:
    std::unique_ptr<T> myPtr;
};


texts: Calculator for calculating price per feet amounts

texts:
So I have a customers site I am remaking into an mvc3 app and they have an existing JavaScript pricing calculator.  Is this safe and efficient?  I am no JavaScript guy, but it looks pretty solid to me.

And here is the form.

<form name="carpet" action="#">

        Cost Estimate

        <input class="inp" type="text" />
        : Enter Square Footage

        <input class="inp" type="text" value="$0" readonly="readonly" />
        : Estimated Cost For Carpet

    <input class="inp" type="text" value="$0" readonly="readonly" />
    : Estimated Cost For Tile

    <input class="inp" type="text" value="$0" readonly="readonly" />
    : Estimated Cost For VCT and Wood

    <input class="inp" type="text" value="$0" readonly="readonly" />
    : Estimated Cost For Travertine Tile

    <input type="reset" />

</form>

I am worried this is old and outdated. Could I do this more effectively with C# in the app?


texts: How to overcome static referencing errors in Java/basic programming?

texts:
Someone posted a question on http://math.stackexchange.com earlier because their program to tranpose a matrix wasn't working. I copied the code they posted (which was just the transpose method) and added the code necessary to check if it worked on their example matrix and it does, so there's obviously a problem elsewhere in their code. I've posted my code below.

I don't have much programming experience and I suspect my style is unconventional. I implement most of the main program in the constructor, because every time I try to do it in the main method, I get lots of errors because I'm referencing non-static variables and methods from a static context. Maybe there are good reasons for using the static keyword, but I just wanted to write quickly a program to check whether the other person's method was correct and it seemed like the fact that the main method was static was getting in the way, so I just transferred most of the program to the constructor. I have 9 questions (question 8 is actually 2 questions), but question 8 is the most important:

Is my program ok?
Could it be better and if so, why?
What would be the conventional way to write the program?
How would the program be written with the main method in the main method rather than the constructor?
How does having the main method static help?
Someone wrote 'It is good to move code into on or more classes instead of having everything in the main method!'. If I do this, it seems like I get lot of errors because I'm referencing a static variable from a non-static context (since I must at least instantiate one class in the static main method). How would I best overcome this?
Someone else suggested changing everything to static, but that can't be normal, can it?
I know that's a lot of questions. I think the following 2 questions could pin down what I want to find out: where would printMatrix() be in a conventional program (presumably not in the constructor like it is in mine)? If there wouldn't even be such a method in a conventional program, how would the printing of the matrix and its transpose be implemented?

public class Matrix {
    double[][] M = new double[3][3];
    static int mat_size=3;
    public Matrix() {
        M[0][0]=1;
        M[0][1]=0;
        M[0][2]=0;
        M[1][0]=5;
        M[1][1]=1;
        M[1][2]=0;
        M[2][0]=6;
        M[2][1]=5;
        M[2][2]=1;
        System.out.println("M");
        printMatrix();
        transpose();
        System.out.println("M'");
        printMatrix();
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new Matrix();
    }

    public void transpose() {

        System.out.println();

        for(int i = 0; i < mat_size; ++i) {
            for(int j = 0; j < i ; ++j) {
                double tmpJI = get(j, i);
                put(j, i, get(i, j));
                put(i, j, tmpJI);
            }
        }
    }

    public void printMatrix() {
        System.out.println();

        for(int i = 0; i < mat_size; ++i) {
            for(int j = 0; j < mat_size ; ++j) {
                System.out.print((int)get(i,j)+" ");
            }
            System.out.println();
        }

    }

    private void put(int i, int j, double d) {
        // TODO Auto-generated method stub
        M[i][j]=d;
    }

    private double get(int i, int j) {
        // TODO Auto-generated method stub
        return M[i][j];
    }
}


texts:
I have to do a program in PHP that reads IGC files like this IGC file and gets records about the glider.
For now I came up with something like this:
<?php

        class Pilot {
            public $name;
            public $gliderType;
            public $competitionId;
            public $gpsDatuml;
            public $competitionClass;
            public $startPoint;
            public $endPoint;
        }
        $pilot = new Pilot();
        $myFile = new SplFileObject("https://xcportal.pl/sites/default/files/tracks/2020-06-09/069daro396091568.igc", 'r', 10);
        for($i=0; $i < 10; $i++) {
            $information =  $myFile->fgets();
            if(($pos = strpos($information, "PILOT")) !== FALSE){
                $pilot->name = substr($information, $pos+7);
            }
            if(($pos = strpos($information, "GLIDERTYPE")) !== FALSE){
                $pilot->gliderType = substr($information, $pos+12);
            }
            if(($pos = strpos($information, "COMPETITIONID")) !== FALSE){
                $pilot->competitionId = substr($information, $pos+15);
            }
            if(($pos = strpos($information, "GPSDATUM")) !== FALSE){
                $pilot->gpsDatuml = substr($information, $pos+10);
            }
            if(($pos = strpos($information, "CLASS")) !== FALSE){
                $pilot->competitionClass = substr($information, $pos+7);
            }
            // echo strpbrk($information, "PILOT");
            // echo substr($information, 10);
        }
        echo $pilot->name;
        echo $pilot->gliderType;
        echo $pilot->competitionId;
        echo $pilot->gpsDatuml;
        echo $pilot->competitionClass;

        $myFile = null;
    ?>

but I wonder if there is anyway to do it better that I haven't figured out already.
Also is it good practice to keep properties of the class as a private field or can I leave them as public if any other class doesn't use that property?


texts: Infinite Continued Fraction - iterative and recursive

texts:
Given the following exercise:

  Exercise 1.37.  a. An infinite
  continued fraction is an expression of
  the form

  As an example, one can show that the
  infinite continued fraction expansion
  with the Ni and the Di all equal to 1
  produces 1/, where is the golden ratio
  (described in section 1.2.2). One way
  to approximate an infinite continued
  fraction is to truncate the expansion
  after a given number of terms. Such a
  truncation -- a so-called k-term
  finite continued fraction -- has the
  form

  Suppose that n and d are procedures of
  one argument (the term index i) that
  return the Ni and Di of the terms of
  the continued fraction. Define a
  procedure cont-frac such that
  evaluating (cont-frac n d k) computes
  the value of the k-term finite
  continued fraction. Check your
  procedure by approximating 1/ using

(cont-frac (lambda (i) 1.0)
           (lambda (i) 1.0)
           k)

  for successive values of k. How large
  must you make k in order to get an
  approximation that is accurate to 4
  decimal places?

  b. If your cont-frac procedure
  generates a recursive process, write
  one that generates an iterative
  process. If it generates an iterative
  process, write one that generates a
  recursive process.

I wrote the following two functions:

Recursive:

(define (cont-frac n_i d_i k)
  (define (recurse n)
    (define (next n) (+ n 1))
    (if (= n k) (/ (n_i k) (d_i k))
        (/ (n_i n) (+ (d_i n) (recurse (next n))))))
  (recurse 1))

Iterative:

(define (i-cont-frac n_i d_i k)
  (define (iterate result n)
    (define (next n) (- n 1))
    (if (= n 1) (/ (n_i n) result)
        (iterate (+ (d_i (next n))
                    (/ (n_i n) result)) (next n))))
  (iterate (d_i k) k))

What do you think of my solution?


texts:
I'm using the flutter_simple_permissions plugin to request permission to read contacts on my flutter application. I want the app to quit when a user denies the permission, and need to show them a custom Dialog.

 Future<bool> getContactsPermission() async{
    bool hasPermission =  await SimplePermissions.checkPermission(Permission.ReadContacts);
      if(!hasPermission){
        await showDialog(context: context, builder: (context) {
          return new AlertDialog(
            title: Text('Requires Contacts Permission'),
            content: SingleChildScrollView(
              child: ListBody(
                children: <Widget>[
                  Text('This application requires access to your contacts'),
                  Text('Please allow access'),
                ],
              ),
            ),
            actions: <Widget>[
              FlatButton(
                child: Text('Allow'),
                onPressed:() async {
                  final response = await SimplePermissions.requestPermission(Permission.ReadContacts);
                  if(response != PermissionStatus.authorized){
                    return false;
                  }
                  Navigator.of(context).pop();
                },
              ),
              FlatButton(
                child: Text('Exit App'),
                onPressed: () {
                  exit(0);
                },
              ),
            ],
          );
        });
    }

    return true;
  }

  refreshContacts() async {
    bool hasPermission = false;
    while(!hasPermission){
      hasPermission = await getContactsPermission();
    }

    var contacts = await ContactsService.getContacts();
    print("GOT CONTACTS!");
    setState(() {
      _contacts = contacts;
    });

  }

Whenever I call refreshContacts() the popup shows up if the user had no permission.

The code is working great, but I feel it could have been much simpler using FutureBuilder maybe?


texts: Project Euler 3: Getting the largest prime factor of a number

texts:
I'm looking for some general feedback on my solution to Project Euler challenge 3

  The prime factors of 13195 are 5, 7, 13 and 29. What is the largest
  prime factor of the number 600851475143 ?

let p3 () =
    let rec primeFactors n i primes =
        if i > n/2L then n::primes else
            let quotient, remainder = Math.DivRem(n, i)
            if remainder = 0L then primeFactors quotient 2L (i::primes)
            else primeFactors n (i + 1L) primes
    primeFactors 600851475143L 2L []


texts: Check if two strings are permutations of each other

texts:
Description:

Given two strings check if those two are permutation of each other. Its expected that input string can contain ASCII characters.

Code:

class Main {
  public static boolean isPermutation(String s1, String s2) {
    if (s1 == null || s2 == null) {
      throw new IllegalArgumentException("Input string cannot be null");
    }
    if (s1.length() != s2.length()) {
      return false;
    }
    int[] count = new int[256];
    for (int i = 0; i < s1.length(); i++) {
      int index = s1.charAt(i) - '0';
      count[index] += 1;
    }
    for (int i = 0; i < s2.length(); i++) {
      int index = s2.charAt(i) - '0';
      count[index] -= 1;
    }
    for (int i = 0; i < count.length; i++) {
      if (count[i] != 0) return false;
    }
    return true;
  }

  public static void main(String[] args) {
    //System.out.println(isPermutation(null, null) == true);
    System.out.println(isPermutation("", "") == true);
    System.out.println(isPermutation("a", "") == false);
    System.out.println(isPermutation("", "b") == false);
    System.out.println(isPermutation("a", "a") == true);
    System.out.println(isPermutation("a", "b") == false);
    System.out.println(isPermutation("foo", "bar") == false);
    System.out.println(isPermutation("eat", "ate") == true);
    System.out.println(isPermutation("1010", "1100") == true);
  }
}

Questions:

From interview point of view are the test cases sufficient?
am I using Java features correctly?
I think I can merge the two for loops but I did above coding in time
bounded fashion, can it raise red flag from interviewer perspective?

PS: According to me I can use map if the input string can contain unicode characters.


texts: Should I use atexit to close db connection?

texts:
I just realized that I could turn:

import MySQLdb

def main():
    db = MySQLdb.connect( .. )
    try:
        while True:
           do_thingy()
    finally:
        db.close()

into:

import MySQLdb, atexit

def main():
    db = MySQLdb.connect( .. )
    atexit.register( db.close )
    while True:
        do_thingy()

Which lets me keep the code for closing the database next to the opening, and saves me a line of code and an indentation level, which I like. Is there a reason why I shouldn't do this?