texts: Finding customer searches and graphing their items

texts:
One of the reports I am working on requires me to locate searches a customer makes, and graph them in certain manners.

I have one query I'm particularly concerned about. This one takes the most amount of time (relative to the batch) and seems quite ugly to me.

Essentially, this should graph the search results by the day of the week and give me: the total number of searches, the average searches per week day, the number of searches that had no returned results, and the percent of searches that have no results.

SELECT
    DATENAME(WEEKDAY, [AtDateTime]) AS [Day of Week]
    ,COUNT(*) AS [Number of Searches]
    ,CAST(CAST(COUNT(*) AS DECIMAL(10, 2)) / COUNT(DISTINCT CONVERT(DATE, [AtDateTime])) AS DECIMAL(10, 2)) AS [Average Searches per Day]
    ,SUM(CASE WHEN [NumFound] = 0 THEN 1 ELSE 0 END) AS [Number of Searches with no Results]
    ,CAST(CAST(SUM(CASE WHEN [NumFound] = 0 THEN 1 ELSE 0 END) AS DECIMAL(10, 2)) / COUNT(*) AS DECIMAL(10, 4)) AS [Percent of Searches with no Results]
FROM [DB].[dbo].[SearchHistory]
WHERE NOT EXISTS
(
    SELECT 1 FROM [DB].[dbo].[CustomerExclusions]
    WHERE [CustomerNumber] = [SearchHistory].[CustomerNumber]
    AND [ExcludeFromSearch] = 1
)
GROUP BY DATENAME(WEEKDAY, [AtDateTime]), DATEPART(WEEKDAY, [AtDateTime])
ORDER BY DATEPART(WEEKDAY, [AtDateTime])

Any advice/critique is welcome.

DDL for the SearchHistory table:

CREATE TABLE [dbo].[SearchHistory](
    [CustomerNumber] [char](8) NOT NULL,
    [Username] [varchar](16) NOT NULL,
    [AtDateTime] [datetime2](7) NOT NULL,
    [Terms] [varchar](128) NOT NULL,
    [NumFound] [int] NOT NULL,
    [NumInStock] [int] NOT NULL
) ON [PRIMARY]
ALTER TABLE [dbo].[SearchHistory] ADD  CONSTRAINT [DF_SearchHistory_AtDateTime]  DEFAULT (sysdatetime()) FOR [AtDateTime]
GO

DDL for the CustomerExclusions table:

CREATE TABLE [dbo].[CustomerExclusions](
    [CustomerNumber] [char](8) NOT NULL,
    [ExcludeFromSearch] [bit] NOT NULL,
    [ExcludeFromErrors] [bit] NOT NULL,
    [ExcludeFromPageHits] [bit] NOT NULL,
 CONSTRAINT [PK_CustomerExclusions] PRIMARY KEY CLUSTERED
(
    [CustomerNumber] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

The indexes on SearchHistory are as follows:

CREATE NONCLUSTERED INDEX [IX_SearchHistory_CustomerNumber_Username_AtDateTime_Terms] ON [dbo].[SearchHistory]
(
    [CustomerNumber] ASC,
    [Username] ASC,
    [AtDateTime] ASC,
    [Terms] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_SearchHistory_NumFound] ON [dbo].[SearchHistory]
(
    [NumFound] ASC
)
INCLUDE (   [CustomerNumber],
    [Terms]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_SearchHistory_NumFound_CustomerNumber] ON [dbo].[SearchHistory]
(
    [NumFound] ASC,
    [CustomerNumber] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

The CustomerExclusions table has no indexes on it, apart from the PK.

This is for SQL Server 2012.

There are two records in CustomerExclusions, and almost 22k records in SearchHistory. When both filters are applied, both records in CustomerExclusions match ExcludeFromSearch = 1, and ~17k records in SearchHistory are returned when the CustomerExclusions filter is applied.


texts:
There are different methods to get data from server in Angular application:

Get Observable from the service and subscribe to it at component
Create Subject at the service and subscribe to the Subject at component

Both of this methods work for me but I can't understand which should I use.

First method. Get Observable from the service and subscribe to it at component:

article.service.ts

import { Injectable } from '@angular/core';
import { Article } from '../models/article';
import { AngularFirestore } from '@angular/fire/firestore';
import { map, take } from 'rxjs/operators';
import { Observable, Subject } from 'rxjs';

@Injectable({
  providedIn: "root"
})
export class ArticleService {
  public articlesChanged: Subject<Article[]> = new Subject<Article[]>();
  articles: Article[];

  constructor(private db: AngularFirestore) {}

  get() {
    return this.db.collection('articles').valueChanges({ idField: 'id' });
  }
}

home.component.ts

import { Component, OnInit } from '@angular/core';
import { ArticleService } from 'src/app/services/article.service';
import { Observable, Subscription } from 'rxjs';
import { Article } from 'src/app/models/article';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})

export class HomeComponent implements OnInit {
  articles: Article[];

  constructor(private articlesService: ArticleService) { }

  ngOnInit() {
    this.articlesService.get().subscribe(articles => this.articles = articles as Article[]);
  }
}

Second method. Create Subject at the service and subscribe to the Subject at component:

article.service.ts

import { Injectable } from '@angular/core';
import { Article } from '../models/article';
import { AngularFirestore } from '@angular/fire/firestore';
import { map, take } from 'rxjs/operators';
import { Observable, Subject } from 'rxjs';

@Injectable({
  providedIn: "root"
})
export class ArticleService {
  public articlesChanged: Subject<Article[]> = new Subject<Article[]>();
  articles: Article[];

  constructor(private db: AngularFirestore) {}

  get(): void {
    this.db
      .collection('articles')
      .valueChanges({ idField: 'id' }).subscribe(articles => {
        this.articles = articles as Article[];
        this.articlesChanged.next(this.articles);
      });
  }
}

home.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ArticleService } from 'src/app/services/article.service';
import { Observable, Subscription } from 'rxjs';
import { Article } from 'src/app/models/article';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})

export class HomeComponent implements OnInit, OnDestroy {
  articlesSubscription: Subscription;
  articles: Article[];

  constructor(private articlesService: ArticleService) { }

  ngOnInit() {
    this.articlesSubscription = this.articlesService.articlesChanged.subscribe(articles => this.articles = articles);
    this.articlesService.get();
  }

  ngOnDestroy(): void {
    this.articlesSubscription.unsubscribe();
  }
}

Is there a best practice which I should use?


texts:
The code below is an implementation of purely recursive solution to find a powerset of any given set. The input set is  a string, and the output - array of strings. Both of them are wrapped into a structure for convenience. The underlying algorithm is pretty common one. The recursive function executes exactly 2^n - 1 times.
I've intentionally removed all memory allocation error checking to make the snippet shorter.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct set {
    char* data;
    int size;
} Set;

typedef struct pset {
    char **data;
    int size;
} PSet;

Set *initSet(char *str) {
    Set *set;
    set = malloc(sizeof(Set));

    set->data = calloc(strlen(str) + 1, 1);
    strcpy(set->data, str);
    set->size = strlen(str);

    return set;
}

PSet *initPSet(const Set* sset) {
    // wrapper for recursive function getPSet
    void getPSet(PSet *pset, const Set *inputStr, int buffer, int index);

    PSet *pset = malloc(sizeof(PSet));

    pset->data = malloc (sizeof(char *) * (1 << sset->size));

    // empty set is a subset of any set
    pset->data[pset->size] = calloc(2, 1);

    strcpy(pset->data[pset->size], "");
    pset->size = 1;

    // in case the input set is empty return a set with just one element
    if (sset->size != 0)
        getPSet(pset, sset, 0, 0);

    return pset;
}

void getPSet(PSet *pset, const Set *set, int buffer, int index) {
    //allocating place for a new subset
    pset->data[pset->size] = calloc(strlen(pset->data[buffer]) + 2, sizeof(char));

    strcpy(pset->data[pset->size], pset->data[buffer]);
    pset->data[pset->size][strlen(pset->data[buffer])] = set->data[index];
    pset->size++;

    // local variable pos keeps track of a position of a prefix stored in pset for future recurrent calls
    int pos = pset->size - 1;

    index++;

    if (index >= set->size) return;

    getPSet(pset, set, buffer, index);
    getPSet(pset, set, pos, index);
}

int main () {

    Set *sset = initSet("abcd");
    PSet *pset;

    pset = initPSet(sset);

    for (int i = 0; i < pset->size; ++i) {
        printf("{%s}\n", pset->data[i]);
    }

    return 0;
}


texts: Coin Change Algorithm - coding challenge

texts:
Recently I came across a coding problem where I have to find the least positive value which is not possible to make using the coins present in the coin denomination array(array values can be used only once).
suppose that

if the input is 3 5 7, the answer is 1

if the input is 1 2 4, the answer is 8

if the input is 1 3 4, the answer is 2

I have written a solution using recursion but it has a time complexity of \$O(n!)\$.
It is given that the size of the array cannot be greater than 25 and no individual value being greater than 100,000.

    public class Test {
        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            int coins = scan.nextByte(); // max 25
            int maxPossible = 0;
            Integer[] coinsDenominationarray = new Integer[coins];
            for (int i = 0; i < coins; i++) {
                coinsDenominationarray[i] = scan.nextInt(); // max 1,00,000
                maxPossible += coinsDenominationarray[i];
            }
            Arrays.sort(coinsDenominationarray);
        /*
         * +1 because the coins will not be able to make 1 more than sum of all the coins.
         * Using this value for the upper limit for the for-loop.
         * In case the recursion is not able to find any value not possible to make
           using any combination of coins. This will be the final answer.
        */
            System.out.println(solve(maxPossible+1, coinsDenominationarray));
        }

        public static int solve(Integer maxNotPossible, Integer[] arr) {
            for (int num = 1; num < maxNotPossible; num++) {
                if (isPresent(num, arr)) {
                    continue;
                }
                if (!isPossible(num, 0, possibleDenominations(num, arr))) {
                    return num;
                }
            }
            return maxNotPossible;
        }

        public static boolean isPossible(int toMake, int sum, Integer[] arr) {
            if (toMake < sum) {
                return false;
            }
            for (int num : arr) {
                int currentSum = sum + num;
                if (currentSum == toMake) {
                    return true;
                } else if (currentSum > toMake) {
                    return false;
                } else if (isPossible(toMake, currentSum, removeAndReturn(num, arr))) {
                    return true;
                }
            }
            return false;
        }

        public static Integer[] removeAndReturn(Integer num, Integer[] arr) {
            List<Integer> list = new LinkedList<Integer>(Arrays.asList(arr));
            list.remove(num);
            return list.toArray(new Integer[list.size()]);
        }

        public static Integer[] possibleDenominations(Integer maxNum, Integer[] arr) {
            List<Integer> list = new ArrayList<>();
            for (int num : arr) {
                if (num >= maxNum) {
                    break;
                }
                list.add(num);
            }
            return list.toArray(new Integer[list.size()]);
        }

        public static boolean isPresent(int num, Integer[] arr) {
            List<Integer> list = Arrays.asList(arr);
            return list.contains(num);
        }

    }

link to the original challenge:
https://www.techgig.com/challenge/IG_Graduate_Programme_2018

Unfortunately, this is not an open challenge.


texts: How can I make this better? Python Web scraping

texts:
I am 12 days old into Python and web scraping and managed to write my first ever automation script. Please review my code and point out blunders If any.

What do I want to achieve?

I want to scrape all chapters of each Novel in each category and post it on a WordPress blog to test. Please point out anything that I missed, and is mandatory to run this script on the WordPress blog.

from requests import get
from bs4 import BeautifulSoup
import re

r = get(site,
        headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"})
soup = BeautifulSoup(r.text, "lxml")
category = soup.findAll(class_="search-by-genre")

# Getting all categories
categories = []
for link in soup.findAll(href=re.compile(r'/category/\w+$')):
    print("Category:", link.text)
    category_link = link['href']
    categories.append(category_link)

# Getting all Novel Headers
for category in categories:
    r = get(category_link,
            headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"})
    soup = BeautifulSoup(r.text, "lxml")
    Novels_header = soup.findAll(class_="top-novel-header")

    # Getting Novels' Title and Link
    for Novel_names in Novels_header:
        print("Novel:", Novel_names.text.strip())

        Novel_link = Novel_names.find('a')['href']

        # Getting Novel's Info
        r = get(Novel_link, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"})
        soup = BeautifulSoup(r.text, "lxml")
        Novel_divs = soup.findAll(class_="chapter-chs")

        # Novel Chapters
        for articles in Novel_divs:
            article_ch = articles.findAll("a")
            for chapters in article_ch:
                ch = chapters["href"]

                # Getting article
                r = get(ch, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"})
                soup = BeautifulSoup(r.content, "lxml")
                title = soup.find(class_="block-title")
                print(title.text.strip())
                full_article = soup.find("div", {"class": "desc"})

                # remove ads inside the text:
                for ads in full_article.select('center, small, a'):
                    ads.extract()

                print(full_article.get_text(strip=True, separator='\n'))


texts: Plain C implementation of 'Cumulative All' operation for R

texts:
I want to implement a cumulative all through R's C interface. I was able to hack something together that produces the correct results, but I have little idea what idiomatic C should look like. The code should be easy to understand, even if you don't know about R.

Description

The cumulative all takes a LGLSXP (logical S-expression) input. The function should output a LGLSXP of the same length as the input, where each element represents whether all values up to this point were true.

The three valued logic works like this:
(true & false) -> false, (true & na) -> na, (false & na) -> false

LGLSXP

A LGLSXP is a pointer to a struct that contains an int array that represents 3 valued logic with 0 as false, INT_MIN as NA and 1 as true. This array can be accessed with LOGICAL(). You can read about SEXPs here.

Code

#include <R.h>
#include <Rinternals.h>

SEXP cumall_impl(SEXP x) {
  SEXP res = PROTECT(allocVector(LGLSXP, XLENGTH(x)));
  R_xlen_t n = XLENGTH(x);

  if (n == 0){
    UNPROTECT(1);
    return(res);
  } else {
    memset(LOGICAL(res), 0, n * sizeof(int));
  }

  int *p_x = LOGICAL(x);
  int *p_res = LOGICAL(res);
  p_res[0] = p_x[0];

  for (R_xlen_t i = 1; i < n; i++) {
    if (p_x[i] == TRUE)
      p_res[i] = p_res[i - 1];
    else if (p_x[i] == NA_LOGICAL)
      p_res[i] = NA_LOGICAL;
    else
      break;
  }

  UNPROTECT(1);
  return res;
}

Remarks

PROTECT() and UNPROTECT() are necessary to prevent R's garbage collector from interfering
LOGICAL() accesses the underlying array of a LGLSXP
TRUE, NA_LOGICAL etc are provided by the headers.

Headers

The most important definitions are in Rinternals.h and R.h.
The NA_LOGICAL is defined in Arith.h and arithmetic.c
I am not sure where/how TRUE and FALSE are really defined. Likely sources are Boolean.h and Rdefines.h

I am thankful for all suggestions, be it coding style, variable naming or critique to how I formulated my question


texts:
I have written code in C++ 11 and check output with Project Euler site, and it is correct. I am not showing output, just to keep it secret, at least from my end.

Please review my C++ 11 code.

#include <fstream>
#include <string>
#include <algorithm>
#include <iostream>
#include <vector>
#include <sstream>

using namespace std;

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

    ifstream file("E:\\names.txt");

    if (!file.is_open())
    {
        cout << "Unable to open file";
        return -1;
    }

    /* Get all file data with ',' delimiter*/
    vector<string> words;
    string token;

    while (getline(file, token, ','))
    {
        words.push_back(token);
    }

    //sort all the words
    sort(words.begin(), words.end());

    int counter = 0;
    unsigned int grand_total = 0;

    //get total of each word and multiply with it's position
    for (auto it = words.begin(); it != words.end(); it++)
    {
        counter++;
        //copy word from token excluding " "
        string word((*it).begin() + 1, (*it).end() - 1);

        int sub_total = 0;
        for (string::iterator it = word.begin(); it != word.end(); it++)
        {
            //ascii value of A is 65
            //A is 1, B is 2, so *it - 64
            sub_total += *it - 64;
        }

        //grand total will be final answer
        grand_total += sub_total*counter;
    }

    return 0;
}


texts:
The general idea is is a progress bar that updates the totals and percentage continually.

This just gets a bit choppy when I trigger a few of these independently on the same page. I'm doing a bit of math at every step, and wonder if there is a better way to accomplish this.

$bar.animate({width:percent+"%"}, {
    duration : o.time,
    easing   : 'swing',
    complete : function() {
        $amount.text('$'+amount.toFixed(2));
        $diff.text('$'+(o.max - amount).toFixed(2));
        $percent.text(Math.floor(percent));
    },
    step : function(now, fx) {
        var actual_amount = (now / 100) * o.max;
        $percent.text(Math.floor(now));
        $amount.text('$'+actual_amount.toFixed(2));
        $diff.text('$'+(o.max - actual_amount).toFixed(2));
        if (o.warning.warning !== 0) {
            if (now > o.warning.alert) {
                $bar.css("background-color", o.alert_color);
            }
            else if (now > o.warning.warning) {
                $bar.css("background-color", o.warning_color);
            }
            else {
                $bar.css("background-color", beginning_color);
            }
        }
    },
});


texts: Get the first positive value that does not exist in array

texts:
function solution(A) {
    var len = A.length;
    if(len > 1){
        let max = Math.max.apply(null, A);
        let range = Array.from(Array(max).keys());
        for(let i = 0; i < range.length; i++){
            if(A.includes(range[i]) === false){
                if(range[i] > 0){
                    return range[i];
                }
                continue;
            }
            continue;
        }
        return max + 1;
    }else if(len == 1 && (A[0] < 1 || A[0] > 1)){
        return 1;
    }else if((len == 1) && (A[0] == 1)){
        return 2;
    }
    return 1;
}

This is mainly used to get the first positive value that does not exist in sequence of integers in an array.

There is a time complexity of O(N ** 2).

Can it be better than this?

If there is no better complexity, can we optimize the for loop better than that?


texts: Change text and styling of a form control when a slider value changes

texts:
Having a hard time to achieve what I'm looking for. I was thinking of using arrays but don't know where to start. Code below is what I want to shorten to get rid of multiple if statement using jQuery.

$("input#communication").on("slide", function(slideEvt) {
    if(slideEvt.value == 1) {
        $('#slider-val1').css('color', '#D0011B');
        $('.slider-label').not('#slider-val1').css('color', '#ccc');
        $('.slider-handle').css({
            'border': '5px solid #fff',
            'box-shadow': '0 0 0 2px #D0011B'
         })
        $("#desc").text('Amir is a terrible communicator.');
    }

    if(slideEvt.value == 2) {
        $('#slider-val2').css('color', '#D0011B');
        $('.slider-label').not('#slider-val2').css('color', '#ccc');
        $("#desc").text('Amir struggles, needs a lot of help to improve communication skills.');
    }

    if(slideEvt.value == 3) {
        $('.slider-handle').css({
            'border': '5px solid #fff',
            'box-shadow': '0 0 0 2px #D0011B'
        })
        $('.slider-handle').css('background', '#D0011B');
        $('.slider-selection').css('background', '#D0011B');
        $('#slider-val3').css('color', '#D0011B');
        $('.slider-label').not('#slider-val3').css('color', '#ccc');
        $("#desc").text('Amir needs some help to improve communication skills.');
    }

    if(slideEvt.value == 4) {
        $('.slider-handle').css('background', '#F47621');
        $('.slider-selection').css('background', '#F47621');
        $('#slider-val4').css('color', '#F47621');
        $('.slider-handle').css({
            'border': '5px solid #fff',
            'box-shadow': '0 0 0 2px #F47621'
        })
        $('.slider-label').not('#slider-val4').css('color', '#ccc');
        $("#desc").text('Amir has below average communication skills.');
    }

    if(slideEvt.value == 5) {
        $('#slider-val5').css('color', '#F47621');
        $('.slider-label').not('#slider-val5').css('color', '#ccc');
        $("#desc").text('Amir has adequate communications skills.');
    }
});

The code above use to change the $('#desc') text and CSS every time the slider is slide. Now, I'm looking for a good way on how to shorten thisif else statements.


texts:
Working on a C programming question where I have to write a function which will determine how many words are in a given string. Assume that one or more consecutive white spaces is a delimiter between words, and that the string you pass to your function is null terminated.

Have to use pointers and only the #include(stdio.h) library. Wondering how this can be improved upon or if there are any possible errors. Here it is:

#include <stdio.h>
int word_counter(char string[])
{
  //We start with first word unless we have a empty string then we have no words
  int count;
  if(*string!='\0'){
    count=1;
}
  else{
    count=0;
    return 0;
  }
  //while we dont reach the end of the string
  while(*string!='\0'){
    //if we detect a whitespace
    if(*string==' '){
      //get previous character
      string--;
      // If previous character is not a space we increase the count
      // Otherwise we dont since we already counted a word
      if(*string!=' '){
        count++;
      }
      //return pointer to current character
      string++;
    }
    // set pointer to next character
    string++;
  }
  return count;
}

//just to test if it works
int main(void)
{
    char str[] = "Hello World!";
    printf("How many words? = %i\n", word_counter(str));
    return 0;
}


texts:
I'm writing a simple function that applies a Sepia filter to an image. My function works, but I'm a beginner gopher. So I would like to know if there is a way to improve the code. I usually code in Javascript, so I have troubles with a strong typed language such as go.

// Sepia apply a sepia filter to Image.
func Sepia(pic image.Image) (output *image.RGBA) {

    bounds := pic.Bounds()
    w, h := bounds.Max.X, bounds.Max.Y
    rect := image.Rect(0, 0, w, h)
    output = image.NewRGBA(rect)

    for x := bounds.Min.X; x <= w; x++ {
        for y := bounds.Min.Y; y <= h; y++ {
            r, g, b, a := pic.At(x, y).RGBA()
// Part to improve from HERE
            r >>= 8
            g >>= 8
            b >>= 8
            a >>= 8

            r = uint32(math.Min(.393*float64(r)+.769*float64(g)+.189*float64(b), 255))
            g = uint32(math.Min(.349*float64(r)+.686*float64(g)+.168*float64(b), 255))
            b = uint32(math.Min(.272*float64(r)+.534*float64(g)+.131*float64(b), 255))

            newColor := color.RGBA{
                uint8(r),
                uint8(g),
                uint8(b),
                uint8(a),
            }
// to HERE
            output.Set(x, y, newColor)
        }
    }
    return
}


texts: Addition of defaults to components in AngularJS

texts:
I wrote a small module in typescript that augments the angularjs registerComponent function to provide a new way of default values for the component controller.

This module was written to solve the problem of not having a nice non-biolerplatey way of providing default values for components. Another problem it attempts to solve is to prevent the default value not applying if a value was provided trough bindings but the value is undefined or null.

The module works by using a static property on the component controller called $defaults. Getter functions are also supported to provide dynamic defaults for each component instance.

I wrote it with dynamic getters in mind. Because it is a function you could do anything in the function body (for example call an API).

I am looking for some feedback on the code and its purpose. The source code is available.

(function() {
type Dict<T = any> = { [key: number]: T, [key: string]: T };

angular.module('ng-sane-defaults', []).config([
    '$compileProvider',
    function configure($compileProvider: angular.ICompileProvider) {
        // get the original `registerComponent` function
        const registerComponent = $compileProvider.component;

        // override the original function
        $compileProvider.component = component;

        /**
         *
         * @param nameOrDict name or Dictionary of component names and their options
         * @param options options for the component if the first parameter is the name
         */
        function component(this: angular.ICompileProvider, nameOrDict: string|Dict<angular.IComponentOptions>, options?: angular.IComponentOptions) {
            // make sure the function signature is correct, if not pass it trough to the original function to handle errors
            if (typeof nameOrDict === 'string' && typeof options !== 'object')
                return registerComponent.call(this, nameOrDict, options as any);
            if (typeof nameOrDict !== 'string' && typeof nameOrDict !== 'object')
                return registerComponent.call(this, nameOrDict, options as any);

            // create the dictionary call signature as it is easier to work with
            const components: Dict<angular.IComponentOptions> = (typeof nameOrDict === 'string') ? { [nameOrDict]: options! } : nameOrDict;

            for (const key in components) {
                const options = components[key];

                // check if it has a controller function
                if (typeof options.controller !== 'function')
                    continue;

                // check if it has a `static $defaults` property, use `getOwnPropertyNames` to check for a getter function without invoking it
                if (Object.getOwnPropertyNames(options.controller).indexOf('$defaults') === -1)
                    continue;

                // get the original `$onInit` function or undefined if there was none
                const onInit: Function|undefined = options.controller.prototype.$onInit;

                // patch the `$onInit` function
                options.controller.prototype.$onInit = function $onInit() {
                    const defaults = (options.controller as Dict).$defaults;

                    if (typeof defaults === 'object') {
                        for (const prop in defaults) {
                            if (this[prop] == null) {
                                this[prop] = defaults[prop];
                            }
                        }
                    }

                    // call the lifecycle hook if it existed
                    return (typeof onInit === 'function') ? onInit.call(this) : void 0;
                };
            }

            return registerComponent.call(this, components);
        }
    }
]);
})();

You can check this plunkr to see it in action


texts:
I have the following code:

private ScatterViewItem FindScatterViewOfSourceFile(SourceFile find)
{
   foreach (ScatterViewItem svi in classScatterViews)
   {
      if ((svi.Tag as SourceFile).Equals(find))
      {
         return svi;
      }
   }
   return null;
}

Now I'm asking myself if this is valid or if I should better use:

private ScatterViewItem FindScatterViewOfSourceFile(SourceFile find)
{
   ScatterViewItem result = null;
   foreach (ScatterViewItem svi in classScatterViews)
   {
      if ((svi.Tag as SourceFile).Equals(find))
      {
         result = svi;
         break;
      }
   }
   return result;
}

Is there any common practive which one to use? And are both loops doing the same?


texts:
I wrote as an exercise in Test-Driven Development a piece of Python code that contains two functions:

roman2dec(roman), that converts a roman number (string) into a decimal number (int)
dec2roman(dec), that converts a decimal number (int) into a roman number (string)

I'd like to read your comments on this code, if there are bad practices, if you would sign it for shipping or if you'd change anything.

import re
import math

# Regular expression used to validate and parse Roman numbers
roman_re = re.compile("""^
   ([M]{0,9})   # thousands
   ([DCM]*)     # hundreds
   ([XLC]*)     # tens
   ([IVX]*)     # units
   $""", re.VERBOSE)

# This array contains valid groups of digits and encodes their values.
# The first row is for units, the second for tens and the third for
# hundreds. For example, the sixth element of the tens row yields the
# value 50, as the first is 0.
d2r_table = [
    ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'],
    ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'],
    ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM']]

def roman2dec(roman):
    """Converts a roman number, encoded in a string, to a decimal number."""
    roman = roman.upper()
    match = roman_re.match(roman)

    if not match:
        raise ValueError

    thousands, hundreds, tens, units = match.groups()
    result = 1000 * len(thousands)
    result += d2r_table[2].index(hundreds) * 100
    result += d2r_table[1].index(tens) * 10
    result += d2r_table[0].index(units)

    return result

def dec2roman(dec):
"""Converts a positive decimal integer to a roman number."""
    if dec == 0:
        return ''

    digit = 0
    rem = dec
    result = ''

    # Length in digits of the number dec
    dec_len = int(math.ceil(math.log10(dec)) + 1)

    # Scan the number digit-by-digit, starting from the MSD (most-significant
    # digit)
    while dec_len > 0:
        # Let's take the current digit
        factor = 10 ** (dec_len - 1)
        digit = rem / factor

        # And remove it from the number
        rem = rem - digit * factor

        if dec_len >= 4:
            # Thousands
            result = result + digit * 'M'
        else:
            # Look in the look-up table
            result = result + d2r_table[dec_len - 1][digit]

        dec_len -= 1

    return result

EDIT: Here is the test suite for dec2roman:

class DecToRoman(unittest.TestCase):
    def testZeroIsEmpty(self):
        self.checkString(0, "")

    def testSingleDigits(self):
        self.checkString(1, "I")
        self.checkString(10, "X")
        self.checkString(50, "L")
        self.checkString(100, "C")
        self.checkString(500, "D")
        self.checkString(1000, "M")

    def testSimpleRepeats(self):
        self.checkString(1, "I")
        self.checkString(2, "II")
        self.checkString(3, "III")
        self.checkString(10, "X")
        self.checkString(20, "XX")
        self.checkString(30, "XXX")

    def testSubtraction(self):
        self.checkString(4, "IV")
        self.checkString(9, "IX")
        self.checkString(40, "XL")
        self.checkString(90, "XC")

    def testOther(self):
        self.checkString(89, "LXXXIX")
        self.checkString(145, "CXLV")
        self.checkString(691, "DCXCI")
        self.checkString(1983, "MCMLXXXIII")
        self.checkString(2412, "MMCDXII")
        self.checkString(3309, "MMMCCCIX")

    def checkString(self, decimal, expected_string):
        self.assertEqual(expected_string, new_dec2roman(decimal))


texts: Gradient descent algorithm for solving localization problem in 3-dimensional space

texts:
Task
This code accomplishes the Time Difference of Arrival (TDoA) multilateration problem (see) using gradient descent (known otherwise as steepest descent).
Goal
I'm looking to:
a) Improve speed:
In practice, the algorithm will need to accomplish localizations 'on the fly'. Currently, it takes about a minute or so to perform one, whereas I'd like to perform thousands to hundreds of thousands in a reasonable time frame (unfortunately, I cannot put a number on that right now).
b) Improve readability: The code will need to be read many times over, and every ounce counts. The code should be as brief as possible (without sacrificing readability, of course) and easy to follow.
And, of course, if I've overlooked some edge case, etc, that's important as well.
import random
import math
from dataclasses import dataclass

@dataclass
class Vector:
    """Simple vector class to avoid dependencies, could
    easily be replaced with Numpy array, e.g."""

    x: float
    y: float
    z: float

    def __add__(self, operand):
        return Vector(self.x + operand.x,
                      self.y + operand.y, self.z + operand.z)

    def __sub__(self, operand):
        return Vector(self.x - operand.x, self.y - operand.y, self.z - operand.z)

    def __rmul__(self, scalar):
        return Vector(self.x * scalar, self.y * scalar,
                      self.z * scalar)

    def __truediv__(self, scalar):
        return Vector(self.x / scalar, self.y / scalar,
                      self.z / scalar)

    def __abs__(self):
        return math.sqrt(pow(self.x, 2) + pow(self.y, 2) + pow(self.z, 2))

@dataclass
class Localize:
    """Newton-Raphson localization class."""

    a: Vector
    b: Vector
    c: Vector
    d: Vector

    @staticmethod
    def tend(y, q, dxq):
        dyq = abs(y - q)
        return (dxq - dyq) * (y - q) / dyq

    def find(self, dxa, dxb, dxc, dxd, gamma=1e-3, precision=1e-10, max=int(1e+10)):

        y = Vector(0, 0, 0)

        for i in range(max):

            f = self.tend(y, self.a, dxa) + self.tend(y, self.b, dxb) + self.tend(y, self.c, dxc) + self.tend(y, self.d,
                                                                                dxd)
            y += gamma * f

            if abs(f) <= precision:
                return y

        raise Exception('Max. iterations insufficient.')

def random_point():
    return Vector(random.random(), random.random(), random.random())

def test_error():
    a = random_point()
    b = random_point()
    c = random_point()
    d = random_point()

    x = random_point()

    localize = Localize(a, b, c, d)

    y = localize.find(abs(x - a), abs(x - b), abs(x - c), abs(x - d))

    return abs(x - y)

print(test_error())


texts: Find the highest prime factor for given number

texts:
My code works for some smaller inputs but larger numbers causes it to hang (when running with node)

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

function factorsOf(n) {
    var factors = [];
    for (var i = 1; i <= n; i++) {
        if (n % i === 0) {
        factors.push(i);
        }
    }
   return factors;
}

function isPrime(number) {
    for (var i=2; i < number; i++) {
    if (number % i === 0) {
        return false;
    }
  }
  return number > 1;
}

function primes(factors) {
    var primes = [];
    for (var i=1; i<factors.length; i++) {
    if (isPrime(factors[i])) {
        primes.push(factors[i]);
    }
  }
  return primes;
}

var factors = factorsOf(13195);
var arr = primes(factors);
console.log(arr[arr.length-1]);


texts: Best way to find the largest sorted suffix in a list - USACO Sleepy Cow Sorting Python

texts:
Solving this problem.
Right now, my solution entails finding the largest sorted sublist, starting from the beginning, all the way to the end. However, I feel like the way I wrote the sorted_sublist function can definitely be improved. Besides that, I'm looking for any way to improve the way I write my code.
My code:
with open("sleepy.in", "r") as fin:
  n = int(next(fin))
  nums = [int(i) for i in fin.readline().split()]

def sorted_sublist(n, nums):
  for i in range(n):
    sublist = nums[i:n]
    if sublist == sorted(sublist):
      return sublist

def main(n, nums):
 x = sorted_sublist(n, nums)
 return n - len(x)

with open("sleepy.out", "w+") as fout:
 print(main(n, nums), file=fout)

Problem synopsis:
Given a list of numbers, find the number of steps it would take to sort this list by repeatedly placing the first element of this list into another slot, provided that you do this in an optimal fashion.
Example:
Input:
4
4 3 2 1

Step 1. Place the 4 to the back of the list: 3, 2, 1, 4
Step 2. Place the 3 to the third index of the list: 2, 1, 3, 4
Step 3. Place the 2 to the second index of the list: 1, 2, 3, 4
Output: 3, as it took three optimal steps to reach a sorted list


texts: Find the next number with all different digits, and no 0 or 2

texts:
Task
Input - integer number (year)
Print one number - the next year, in which all digits are pairwise different, and there are no digits 2 and 0. If there will never be such a year, print -1.
My solution (correct)
Could you please recommend time / space complexity optimizations?
vector<char> toVec(int n) {
    vector<char> res;
    while (n > 0) {
        res.push_back((n % 10) + '0');
        n /= 10;
    }
    return res;
}

int main(){
    int year;
    cin >> year;
    for (int i = year + 1; i < pow(10, 8); ++i) {
        vector<char> v = toVec(i);
        if (find(begin(v), end(v), '2') == v.end() and
            find(begin(v), end(v), '0') == v.end()) {
            set<char> temp(v.begin(), v.end());
            if (v.size() == temp.size()) {
                cout << i;
                return 0;
            }
        }
    }
    cout << -1;

}


texts:
I made this code for simple leveling game.

I think this code may have some issues with security. Also, are there some way to make this code more efficient and reliable?

For level scaling I will use this method. Should I make lvl, xp and nxtlevel variables to array or is that a bad idea?

class LevelingSystem
{

  private $_lvl;
  private $_xp;
  private $_nxtlevel;

  function __construct($lvl=1,$xp=0,$nxtlevel=30)
  {

    $this->_lvl=$lvl;
    $this->_xp=$xp;
    $this->_nxtlevel=$nxtlevel;
  }

  function setxp($setxp)
  {
    global $db;
    $stmt = $db->prepare("UPDATE user_atri SET totalxp =totalxp+".$setxp." WHERE id=1");
    $updatexp=$stmt->execute();
    return $updatexp;
  }

  private function getxp()
  {
    global $db;
    $query = $db->prepare("SELECT totalxp FROM user_atri where id=1");
    $query->execute();
    $totalxp=$query->fetch(PDO::FETCH_ASSOC);
    $this->_xp=$totalxp["totalxp"];
    return $totalxp["totalxp"];
  }

  function lvl()
  {

    $this->getxp();
    while ($this->_xp>=$this->_nxtlevel)
    {
        $this->_lvl+=1;
        $this->_xp =$this->_xp - $this->_nxtlevel;
        $this->_nxtlevel = round($this->_nxtlevel * 1.6);
    }

    //$levelprint=sprintf("Youre level is: %s ",$this->_lvl);
    //echo $this->_xp;
    //echo "<br>";
    //return $levelprint;
    return $this->_lvl;

  }

}


texts: Python Elasticserch DSL integration with Django

texts:
There is a big Pull Request in django-elasticsearch-dsl. Can anyone take some time and review the pull request?
We are changing from python MetaClass to a decorator @registry.register_document. Will it be a good approach?

It will be something like this

        @registry.register_document
        class CarDocumentDSlBaseField(DocType):
            position = GeoPoint()

            class Django:
                model = Car
                fields = ['name', 'price']

            class Index:
                name = 'car_index'


texts:
To learn more about OOP, @nhgrif challenged me to implement a Shape abstract class (more details in code remarks below. Here is how I did it. Any and all advice appreciated!

Shape.java

/* nhgrif says:
 * Phrancis ready for inheritance/polymorphism?
 * Given the following abstract class:
 *
 *  public abstract class Shape {
 *      public abstract double area();
 *      public abstract double perimeter();
 *  }
 *
 * Implement a Circle, Triangle, and Rectangle class which extend the class Shape.
 * Ex: public class Circle extends Shape ... etc
 */

public abstract class Shape {
    public abstract double area();
    public abstract double perimeter();
}

Rectangle.java

public class Rectangle extends Shape {
    private final double width, length; //sides

    public Rectangle() {
        this(1,1);
    }
    public Rectangle(double width, double length) {
        this.width = width;
        this.length = length;
    }

    @Override
    public double area() {
        // A = w * l
        return width * length;
    }

    @Override
    public double perimeter() {
        // P = 2(w + l)
        return 2 * (width + length);
    }

}

Circle.java

public class Circle extends Shape {
    private final double radius;
    final double pi = Math.PI;

    public Circle() {
        this(1);
    }
    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public double area() {
        // A = π r^2
        return pi * Math.pow(radius, 2);
    }

    public double perimeter() {
        // P = 2πr
        return 2 * pi * radius;
    }
}

Triangle.java

public class Triangle extends Shape {
    private final double a, b, c; // sides

    public Triangle() {
        this(1,1,1);
    }
    public Triangle(double a, double b, double c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    @Override
    public double area() {
        // Heron's formula:
        // A = SquareRoot(s * (s - a) * (s - b) * (s - c))
        // where s = (a + b + c) / 2, or 1/2 of the perimeter of the triangle
        double s = (a + b + c) / 2;
        return Math.sqrt(s * (s - a) * (s - b) * (s - c));
    }

    @Override
    public double perimeter() {
        // P = a + b + c
        return a + b + c;
    }
}

And this is what I used to test it all, which it all works as intended:

TestShape.java

public class TestShape {
    public static void main(String[] args) {

        // Rectangle test
        double width = 5, length = 7;
        Shape rectangle = new Rectangle(width, length);
        System.out.println("Rectangle width: " + width + " and length: " + length
                + "\nResulting area: " + rectangle.area()
                + "\nResulting perimeter: " + rectangle.perimeter() + "\n");

        // Circle test
        double radius = 5;
        Shape circle = new Circle(radius);
        System.out.println("Circle radius: " + radius
            + "\nResulting Area: " + circle.area()
            + "\nResulting Perimeter: " + circle.perimeter() + "\n");

        // Triangle test
        double a = 5, b = 3, c = 4;
        Shape triangle = new Triangle(a,b,c);
        System.out.println("Triangle sides lengths: " + a + ", " + b + ", " + c
                + "\nResulting Area: " + triangle.area()
                + "\nResulting Perimeter: " + triangle.perimeter() + "\n");
    }
}


texts: Notify one of hundreds of viewmodels with MVVM Light messenger

texts:
Assume a viewmodel for hosting a collection of item viewmodels. There can be some hundreds of items in the collection. The items are part of the business model and have an id and a name. The name for a specific item can be changed somewhere in the application and the viewmodel in the collection needs to be notified to refresh the property:

public interface IItem
{
    Guid Id { get; }
    string Name { get; }
}

public class ItemModel : ViewModelBase
{
    private IItem _item;

    public ItemModel(IItem item)
    {
        _item = item;
    }

    public void Refresh()
    {
        RaisePropertyChanged(nameof(Name));
    }

    public Guid Id { get { return _item.Id; } }

    public string Name { get { return _item.Name; } }

    private bool _isSelected;

    public bool IsSelected
    {
        get { return _isSelected; }
        set { Set(ref _isSelected, value); }
    }
}

public class ListModel : ViewModelBase
{
    public ListModel(IEnumerable<ItemModel> items)
    {
        Items = new ObservableCollection<ItemModel>(items);
    }

    public ObservableCollection<ItemModel> Items { get; }
}

I have tried the following solutions, but i am not sure what the best one is:

register every item at creation and let the messenger always notify them all

public class ItemModel : ViewModelBase
{
    public ItemModel(IItem item)
    {
        _item = item;

        MessengerInstance.Register<NotificationMessage>(this, (msg) => {
            if (msg.Notification == "REFRESH" && IsSelected)
            {
                Refresh();
            }
        });
    }

    [...]

register / unregister messenger on selection, so there will be only one viewmodel be registered

public class ItemModel : ViewModelBase
{
    [...]

    public bool IsSelected
    {
        get { return _isSelected; }
        set
        {
            if (Set(ref _isSelected, value))
            {
                if (value)
                {
                    MessengerInstance.Register<NotificationMessage>(this, (msg) => {
                        if (msg.Notification == "REFRESH")
                        {
                            Refresh();
                        }
                    });
                }
                else
                {
                    MessengerInstance.Unregister<NotificationMessage>(this);
                }
            };
        }
    }
}

register the hostig viewmodel and iterate over the items, so there wil be only one registration too

    public ListModel(IEnumerable<ItemModel> items)
    {
        [...]

        MessengerInstance.Register<NotificationMessage<Guid>>(this, (msg) => {
            if (msg.Notification == "REFRESH")
            {
                var item = Items.Single<ItemModel>(x => x.IsSelected);
                item.Refresh();
            }
        });
    }

which solution would you prefer? register and unregister on every selection or having hundereds of viewmodels registered to the messenger or itereate the items yourself? maybe there is also a better solution?


texts: SOXXY: a daemon stated IRC client project

texts:
This script is basically a proxy service; except it doesn't require an active client connection. In fact it expects the client connection to connect before, and disconnect after every transaction. Once running the proxy will buffer all incoming bytes, and will dump those bytes to the client upon request. Before I go any further and begin working on the IRC client intended to be used with this, I am posting here to persuade any feedback regarding the project in its current state from readers here:

soxxy.py

#! /usr/bin/python3

from socket import socket
from threading import Thread as thread
from sys import getdefaultencoding as enc
from sys import byteorder
from sys import argv

enc = enc()
CNCT, SEND, RECV, DISC, STAT = 0, 1, 2, 3, 4

class sox:
        def recv_t(self, s):
                while self.run:
                        try: self.buff += s.recv(8192)
                        except: continue
        def process(self, lo):
                try: bs = lo[0].recv(8192)
                except: return
                op, data = bs[0], bs[1:]
                if op is CNCT:
                        data = str(data, enc)
                        host, port = data.split(":")
                        self.sock = socket()
                        self.sock.connect((host, int(port)))
                        self.run = True
                        thread(target=self.recv_t, args=(self.sock, )).start()
                elif op is SEND: self.sock.send(data)
                elif op is RECV: lo[0].send(self.buff); self.buff = bytes()
                elif op is DISC: self.run = False; self.sock.close()
                elif op is STAT: bytes("error: %s" % (str(self.serr), ), enc)
        def server(self, port, host):
                ss = socket()
                ss.bind((host, int(port)))
                while True:
                        ss.listen(1)
                        self.process(ss.accept())
        def __init__(self, argv):
                self.sock = None
                self.buff = bytes()
                self.serr = False
                self.server(argv[1], argv[2])

if __name__ == "__main__":
        sox([argv + ["127.0.0.1", ], argv][len(argv) == 3])

IRC

#! /usr/bin/python3

from soxxy import *

lo_host = None
lo_port = None
remote_host = None
remote_port = None

def send(bs):
        s = socket()
        s.connect((lo_host, int(lo_port)))
        s.send(bs)
        x = s.recv(8192)
        s.close()
        return x

if __name__ == "__main__":
        lo_host, lo_port, remote_host, remote_port = argv[1:]
        send(bytes([CNCT, ] + [ord(c) for c in remote_host + ":" + remote_port]))
        from time import sleep
        sleep(8)
        print(str(send(bytes([RECV, ])), enc))
        send(bytes([DISC, ]))

Test case

$ cat test.sh
./soxxy.py 8000 & sleep 2 && \
./irc 127.0.0.1 8000 irc.gnu.org 6667
$ sh test.sh
:morgan.freenode.net NOTICE * :*** Looking up your hostname...
:morgan.freenode.net NOTICE * :*** Checking Ident
:morgan.freenode.net NOTICE * :*** Found your hostname
:morgan.freenode.net NOTICE * :*** No Ident response


texts: How to refract a while loop with a necessary initial setting?

texts:
I put the readable version into the gist file -> link

Please ignore the print and comment in the following code.

I often have to write this sort of logic: init the conditions, and deep into loop condition, get the variables in each iteration and break when the condition meets.

As you can see, I get the first line in a region and then loop until the region ends.

The exit condition is while True and (beginning_spaces - start_beginning_spaces).

Are there any better practices in my case?

 def get_exception_region(self, except_region, max_lines_in_exception=100):
        '''
        # get current line number
        row, _ = self.view.rowcol(except_region.a)
        # get next line's starting point
        next_row_starting = self.view.text_point(row + 1, 0)
        # get the whole next line
        next_row_region = self.view.full_line(next_row_starting)
        print(self.view.substr(next_row_region))
        '''

        # Init first setting
        try:

            row, _ = self.view.rowcol(except_region.a)
            next_line_text, next_line_region = self.get_next_line__text_and_region(row)
            prev_line_text, prev_line_region  = next_line_text, next_line_region
            beginning_spaces = self.count_the_beginning_spaces(next_line_text)
            start_row, start_beginning_spaces = row, beginning_spaces

            print "=================Start================="
            print row, beginning_spaces, next_line_text.strip()

            while True and (beginning_spaces - start_beginning_spaces) < max_lines_in_exception :
                row = row + 1
                next_line_text , next_line_region = self.get_next_line__text_and_region(row)
                beginning_spaces = self.count_the_beginning_spaces(next_line_text)
                print row, beginning_spaces, next_line_text.strip()
                if beginning_spaces > 1 and beginning_spaces != start_beginning_spaces:
                    print "=================Exit================="
                    break
                prev_line_text, prev_line_region  = next_line_text, next_line_region
            return row, prev_line_text, prev_line_region

            pass

        except Exception as e:
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print("[Error]\n", exc_type, fname, exc_tb.tb_lineno)

            raise e
            sys.exit(e)
            #EndOfExcept


texts:
I have the following solution for the Trip problem from Skiena's and Revilla's Programming Challenges (full problem description here).

//#include "stdafx.h"
#include <iostream>
#include <string> //Always import <string> if piping std input to a string in .net
#include<algorithm>
#include<math.h>
#include<fstream>
using namespace std;
int main()
{
    //ofstream myfile;
    //myfile.open("example.txt");

    int n; //number of students sharing trip costs.
    while (cin >> n) {
        if (n == 0) {
            return 0;
        }

        double *ammounts_spent = new double[n];
        double total_spent = 0;
        for (int i = 0; i < n; i++) {
            cin >> ammounts_spent[i];
            total_spent += ammounts_spent[i];
        }
        double ammount_exchanged = 0;
        double ammount_exchanged_below = 0;
        double ammount_exchanged_above = 0;

        double average_spent = total_spent / n;
        double rounded_down_average_spent =(double)((int)(average_spent * 100)/(double)100);
        double rounded_up_average_spent = rounded_down_average_spent + 0.01;
        if (rounded_down_average_spent - average_spent < 0) {
            for (int i = 0; i < n; i++) {
                if (average_spent > ammounts_spent[i]) {
                    ammount_exchanged_below += rounded_down_average_spent - ammounts_spent[i];
                }
                else {
                    ammount_exchanged_above += ammounts_spent[i] - rounded_up_average_spent;
                }
            }

        }
        else {
            for (int i = 0; i < n; i++) {
                if (average_spent > ammounts_spent[i]) {
                    ammount_exchanged_below += average_spent - ammounts_spent[i];
                }
                else {
                    ammount_exchanged_above += ammounts_spent[i] -average_spent;
                }
            }

        }

        ammount_exchanged = max(ammount_exchanged_above, ammount_exchanged_below);
        if (ammount_exchanged == floor(ammount_exchanged)) {
            cout << "$" << ammount_exchanged << ".00\n";

        }
        else {
            cout << "$" << ammount_exchanged << "\n";
        }
    }
}

It works for all debug input given on udebug and even for tricky instances such as

> 4
> 1.01
> 1.01
> 1.00
> 1.00

Where the amount exchanged is $0.00. Yet the UVA online judge is giving me a verdict of wrong answer.


texts:
I am saving data into a MongoDB. The data will be saved into 3 Mongoose models that are hierarchical. A User model contains an Activity model array. An Activity model contains an array of Data models. Are the following model definitions correct (or does an explicit reference to the parent model need to be declared)?

I will add any additional details if need be.

User

var userSchema = new mongoose.Schema({
    googleId: {type: String, unique: true, required: true},
    name: {type: String, required: true},
    data: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Activity' }]
});

module.exports = mongoose.model('User', userSchema);

Activity

module.exports = mongoose.model('Activity', {

    name: String,
    data: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Data' }]
});

Data

module.exports = mongoose.model('Data', {

    date: String,
    time: {type: Number, default: 0},
    timestamp: {type: Number, default: 0}
});


texts: Read .csv files and convert the rows into dict for looping

texts:
This script tries to parse .csv files and returns an iterable object to fetch one row at a time to do some process. It works fine but I think it needs improvements to make it efficient.

    import os
    from csv import DictReader

    class CSVHandler:
        DELIMIT = ','  # delimiter for csv
        FIELDS = set(list(['foo', 'bar']))  # fields that I want

        def __init__(self, file_path: str):
            self.file_path = file_path
            self.file_obj = None
            self.reader = DictReader([])

        def read_file(self):
            if self._is_file_ok:
                try:
                    self.file_obj = open(self.file_path, newline='')
                    self.reader = DictReader(self.file_obj)
                    unmatched = self._is_fields_ok
                    if isinstance(unmatched, set):
                        print(f"Warning : field set's unmatched! {unmatched}")
                except IOError:
                    print(f'Unable to open/read file : "{self.file_path}"')
            else:
                print(f'Invalid file : "{self.file_path}"')
            return self

        @property
        def _is_file_ok(self):
            if os.path.isfile(self.file_path):
                if os.path.exists(self.file_path):
                    if self.file_path.endswith('.csv'):
                        return True
            return False

        @property
        def _is_fields_ok(self):
            if self.reader or not self.FIELDS:
                return self.FIELDS - set(self.reader.fieldnames)
            return False

        def _trim_row(self, row: dict):
            trimmed_row = dict.fromkeys(self.FIELDS, None)
            for field in self.FIELDS:
                if field in row:
                     trimmed_row[field] = row[field]
            return trimmed_row

        def __enter__(self):
            return self

        def __iter__(self):
            return (self._trim_row(dict(row)) for row in self.reader)

        def __next__(self):
            return self._trim_row(dict(next(self.reader)))

        def __len__(self):
            return len(list(self.reader))

        def __exit__(self, exc_type, exc_val, exc_tb):
            if self.file_obj is not None:
                self.file_obj.close()

    if __name__ == '__main__':
        with CSVHandler('file_name.csv').read_file() as csv_h:
            for rows in csv_h:
                pass
```


texts: Presenting modal dialogs from XIB in Cocoa: best/shortest pattern?

texts:
Below is my typical WindowController module for presenting a modal dialog (could be settings, asking username/password, etc) loaded from a XIB. It seems a bit too complex for something like this. Any ideas how this can be done better/with less code?

Never mind that it's asking for a password, it could be anything. What frustrates me most is that I repeat the same pattern in each and every of my XIB-based modal window modules. Which of course means I could define a custom window controller class, but before doing that I need to make sure this is really the best way of doing things.

#import "MyPasswordWindowController.h"

static MyPasswordWindowController* windowController;

@interface MyPasswordWindowController ()
@property (weak) IBOutlet NSSecureTextField *passwordField;
@end

@implementation MyPasswordWindowController
{
    NSInteger _dialogCode;
}

- (id)init
{
    return [super initWithWindowNibName:@"MyPassword"];
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self.window center];
}

- (void)windowWillClose:(NSNotification*)notification
{
    [NSApp stopModalWithCode:_dialogCode];
    _dialogCode = 0;
}

- (IBAction)okButtonAction:(NSButton *)sender
{
    _dialogCode = 1;
    [self.window close];
}

- (IBAction)cancelButtonAction:(NSButton *)sender
{
    [self.window close];
}

+ (NSString*)run
{
    if (!windowController)
        windowController = [MyPasswordWindowController new];
    [windowController loadWindow];
    windowController.passwordField.stringValue = @"";
    if ([NSApp runModalForWindow:windowController.window])
        return windowController.passwordField.stringValue;
    return nil;
}

The application calls [MyPasswordWindowController run], so from the point of view of the user of this module it looks simple, but not so much when you look inside.


texts:
I have a functional class WordAnalyzer that uses espeak to grab the IPA phonetics of a word & uses that information to find rhymes & print the number of syllables:

from difflib import SequenceMatcher
from subprocess import check_output

class AnalyzeWord:
    """
    Uses espeak's output to get a word's phonetics & syllables.
    """
    def __init__(self, arg):
        super(AnalyzeWord, self).__init__()
        self.arg = arg
        self.word = arg
        ipa_vowels = ['ɐ', 'i', 'ɪ', 'e', 'ɛ', 'æ', 'a', 'ə', 'ɑ', 'ɒ', 'ɔ', 'ʌ', 'ɚ', 'o', 'ʊ', 'u', 'eɪ', 'aɪ']
        self.phon = list(check_output(['espeak', \
                             '-q', '-v', 'en-us', '--ipa',\
                             self.arg]).decode('UTF-8').strip())
        for i, x in enumerate(self.phon):
            if self.phon[i] == 'ɪ' and self.phon[i-1] in ipa_vowels:
                    self.phon[i-1:i+1] = [''.join(self.phon[i-1:i+1])]
        self.syll = len([l for l in self.phon if l in ipa_vowels])
    def check_rhyme(self, word):
        word = AnalyzeWord(word)
        sm = SequenceMatcher(None, self.phon, word.phon)
        perc = int(sm.ratio() * 100)
        print("Good rhyme - " + str(perc) + "%") \
                if perc > 50 else print("Not a good rhyme - " + str(perc) + "%")

test1 = AnalyzeWord('steed')
test1.check_rhyme("speed")

I think the class itself isn't as 'pythonic' as it ought to be. In particular, I'd love some help cleaning up the self.phon declaration & the following for loop.

EDIT: If there's a better way to store every IPA vowel character / combination I'd love to hear it!


texts: How do I write my multithreading code correctly so that it is faster than a single thread?

texts:
I have the following code that I am trying to optimize. I am running it on a Linux machine with 24 cores. I thought I could use multithreading to make it faster, but it's somehow making it way slower than the single thread. I believe it is because of cache misses but I am not sure how to structure this code to avoid them.

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

#include "mex.h"
#include "string.h"
#include "pthread.h"

/* NOT sure why multi-threading is worse than single thread */
#define NTHREADS 1

/* An argument list structure */
struct argList{
    double *X;
    double *p;
    int cycles;
    int N1;
    int N2;
};
typedef struct argList aList;

long int bino_rand(double p, double n)
{
  long int    x = 0;
  int i;
  for (i=0; i<n; i++)
    if (((double)rand())/RAND_MAX < p) x++;

  return(x);
}

void *bino_process(void* arglist){
    double* X   = ((aList*)arglist)->X;
    double* p   = ((aList*)arglist)->p;
    int cycles  = ((aList*)arglist)->cycles;
    int N1      = ((aList*)arglist)->N1;
    int N2      = ((aList*)arglist)->N2;
    int i,j;

/* mexPrintf("N1=%d, N2=%d, cycles=%d\n", N1, N2, cycles); */

for(i = N1;i<N2;i++){
    double tmp = X[i];
    double tmp_p = p[i];
    for(j=0;j<cycles;j++){
        tmp = tmp + bino_rand(tmp_p,tmp);
    }
    X[i] = tmp;
}
}

void mexFunction( int nlhs, mxArray *plhs[],
              int nrhs, const mxArray *prhs[])
{
double* n;              /* input scalar */
double* p;
int cycles;
mwSize N;               /* size of matrix */
double *X;              /* output matrix */
int i;

pthread_t threadA[NTHREADS];
int iterA[NTHREADS];
aList arglistA[NTHREADS];

int N1[NTHREADS];
int N2[NTHREADS];

/* get the value of the scalar input  */
n = mxGetPr(prhs[0]);
p = mxGetPr(prhs[1]);
cycles = (int)mxGetScalar(prhs[2]);

N = mxGetM(prhs[0]);

/* create the output matrix */
plhs[0] = mxCreateDoubleMatrix(N,1,mxREAL);

/* get a pointer to the real data in the output matrix */
X = mxGetPr(plhs[0]);

memcpy(X,n,N*sizeof(double));

for(i=0;i<NTHREADS;i++){
    N1[i] = i*(N/NTHREADS);
    N2[i] = (i+1)*(N/NTHREADS);
    arglistA[i].X = X;
    arglistA[i].p = p;
    arglistA[i].cycles = cycles;

    arglistA[i].X = (double*)mxCalloc(N2[i]-N1[i],sizeof(double));
    memcpy(arglistA[i].X, &X[N1[i]], (N2[i]-N1[i])*sizeof(double));

    arglistA[i].N2 = N2[i]-N1[i];
    arglistA[i].N1 = 0;

}

/* Spawn the threads */
for(i=0;i<NTHREADS;i++){
    iterA[i] = pthread_create(&threadA[i],NULL,bino_process,(void*)&arglistA[i]);
}

/* Join back the threads */
for(i=0;i<NTHREADS;i++){
    pthread_join(threadA[i],NULL);
}

/* Copy back the data from the chunks into X */
for(i=0;i<NTHREADS;i++){
    memcpy(&X[N1[i]], arglistA[i].X, (N2[i]-N1[i])*sizeof(double));
}

for(i=0;i<NTHREADS;i++){
    mxFree(arglistA[i].X);
}

}


texts: PHP include page index.php?page=GET safety preg_replace

texts:
I found a lot of working codes to include page in page on Internet but I could not find a safe code. So I decided to create one myself. The pages will be only stored in folder /pages/ and whitelist seems to be a good option.

Is the follow code safe?

<?php
$unsafe = $_GET['pagename'];
$page = preg_replace('/[^A-Za-z0-9\-]/', '', $unsafe);
if (empty($page)){
include('pages/default.php');
}
$pages = array('default', 'pageone', 'pagetwo', 'another', 'last');
if (isset($pages[$page])) {
    include('pages/' . $page . '.php');
} else {
include('pages/error-404.php');
}
?>


texts: Find the number of swaps that has taken place. New Year Chaos. Hackerrank

texts:
I am trying to solve the following Hackerrank Problem.

I have written the code for the problem. However, it runs for some of the test cases while for others it doesn't. It shows the message : "Your code did not execute within the time limits"

I know that bubble sort is not required for the problem. However, I have seen many people doing it using bubble sort.

I want to do the problem by employing bubble sort. Please tell me what changes do I need to make in the code in order to do so. Thanks for helping.

int N = 0 ,I = 0;
        int flag = 0;

        int n = q.length;
        int temp = 0;
        int noOfSwaps = 0;

        for(int i = 0 ; i < q.length ; i++)
        {
            N = q[i];
            I = i;
            if((N-I)>3)
            {
                flag = 1;
                break;
            }
        }

        if(flag == 1)
        {
            System.out.println("Too chaotic");
        }
        else if(flag == 0)
        {
            //System.out.println("Find Exchanges");

         for(int i=0; i < n; i++){
                 for(int j=1; j < (n-i); j++){
                          if(q[j-1] > q[j]){
                                 //swap elements
                                 temp = q[j-1];
                                 q[j-1] = q[j];
                                 q[j] = temp;

                                 noOfSwaps++;
                         }

                 }
         }

         System.out.println(noOfSwaps);

        }


texts: Rotate a N by N matrix by 90 degrees clockwise

texts:
The task:

  Given an N by N matrix, rotate it by 90 degrees clockwise.

  For example, given the following matrix:

  [[1, 2, 3],  [4, 5, 6],  [7, 8, 9]] you should return:

  [[7, 4, 1],  [8, 5, 2],  [9, 6, 3]]

  Follow-up: What if you couldn't use any extra space?

const mtx = [[1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]];

My imperative solution:

function transpose(matrix){
  const size = matrix[0].length;
  const newMatrix = JSON.parse(JSON.stringify(matrix));
  for (let rowIndex = 0; rowIndex < size; rowIndex++) {
    const row = matrix[rowIndex];
    for (let colIndex = 0; colIndex < size; colIndex++) {
      const newRowIndex = colIndex;
      const newColIndex = size - 1 - rowIndex;
      newMatrix[newRowIndex][newColIndex] = row[colIndex];
    }
  }
  return newMatrix;
};

console.log(transpose(mtx));

My declarative solution:

const transpose2 = matrix => {
  const size = matrix[0].length;
  const newMatrix = JSON.parse(JSON.stringify(matrix));
  matrix.forEach((row, rowIndex) => {
    row.forEach((val, colIndex) => {
      const newRowIndex = colIndex;
      const newColIndex = size - 1 - rowIndex;
      newMatrix[newRowIndex][newColIndex] = val;
    });
  });
  return newMatrix;
};

console.log(transpose2(mtx));

My solution to the Follow Up question:

Didn't really understand the part with "no extra space". The only solution that came to my mind was to overwrite the existing matrix with the new values and at the end clean it up by deleting the old values. ...but appending new values to old values requires extra space, doesn't it?

const transposeNoSpace = matrix => {
  const size = matrix[0].length;
  matrix.forEach((row, rowIndex) => {
    row.forEach((val, colIndex) => {
      const newRowIndex = colIndex;
      const newColIndex = size - 1 - rowIndex;
      const newVal = val[1] ? val[0] : val;
      matrix[newRowIndex][newColIndex] = [matrix[newRowIndex][newColIndex], newVal];
    });
  });
  return matrix.map(row => row.map(col => col[1]));
};

console.log(transposeNoSpace(mtx));

I'd also be interested in a pure functional solution


texts: Ubuntu kernel update and removal automation script

texts:
This is my first bigger than a few lines bash script.

It automates kernel updating and removing on Ubuntu through ukuu (Ubuntu kernel update utility).

I'm not yet familiar with all the bells and whistles of GNU utilities and want to strive for clarity. The only thing I know now is grep -P and everything seems like a nail if you have a hammer. Also this is mostly stitched from examples on StackExchange.

What would you change to make the code more readable or perhaps better in some other ways?

#!/bin/bash

updateInstalledKernels () { # TODO (low priority) modify to not double-count kernels which have two "Installed" records in ukuu --list
    while read I
    do
        INSTALLED_KERNELS=( "${INSTALLED_KERNELS[@]}" "$I" )
    done < <(printf "$AVAILABLE_KERNELS" | grep -oP 'v\d+\.\d+((\.\d+)|(-\w+))*(?=\s+[0-9.]*\s+(Installed|Running)\s*?\z)')
}
containsElement () { # usage: containsElement string element1 element2 ...
  local e match="$1"
  shift
  for e; do [[ "$e" == "$match" ]] && return 0; done
  return 1
}

FALLBACK_KERNELS=( 'v4.15.0-33.36' 'v4.15.0-30.32' ) # array of kernels for fallback
echo "fallback kernels: ${FALLBACK_KERNELS[@]}"
# TODO variable which chooses the number of latest kernels to keep

AVAILABLE_KERNELS=$(ukuu --list)
if ! echo "$AVAILABLE_KERNELS" | grep -oPzq 'Available Kernels.*?\n=+\n\K.*?(Installed|Running).*?\n';
then
    ukuu --install-latest
else
    LATEST_KERNEL=$(echo "$AVAILABLE_KERNELS" | grep -oPz 'Available Kernels.*?\n=+\n\Kv.+?(?=\s.*?\n)')
    echo "Latest kernel ${LATEST_KERNEL} installed. Removing old kernels apart from ${FALLBACK_KERNELS[@]}."
    declare -a INSTALLED_KERNELS
    updateInstalledKernels
    echo "Installed kernels: ${INSTALLED_KERNELS[@]}."
    for INSTALLED_KERNEL in "${INSTALLED_KERNELS[@]}"
    do
            echo "$INSTALLED_KERNEL"
        if ! containsElement "$INSTALLED_KERNEL" "${FALLBACK_KERNELS[@]}"
        then
            if ! echo "$INSTALLED_KERNEL" | grep -q "$LATEST_KERNEL"
            then
                echo "${INSTALLED_KERNEL} is not fallback, nor latest. Removing it..."
                ukuu --remove "$INSTALLED_KERNEL"
            fi
        fi
    done <<< "$INSTALLED_KERNELS"
fi


texts: Reorganizing a PHP array structure (arrays within arrays)

texts:
I have this array within array which contains a lot of values:

  183 =>
    array (size=3)
      0 => string 'DE' (length=2)
      1 => string '2015-06-09' (length=10)
      2 => string 'GK' (length=2)
  184 =>
    array (size=3)
      0 => string 'DE' (length=2)
      1 => string '2015-06-08' (length=10)
      2 => string 'GL' (length=2)
  185 =>
    array (size=3)
      0 => string 'FR' (length=2)
      1 => string '2015-06-09' (length=10)
      2 => string 'GN' (length=2)
  186 =>
    array (size=3)
      0 => string 'FR' (length=2)
      1 => string '2015-09-08' (length=10)
      2 => string 'GO' (length=2)

0 is the country code. 1 is a date. 2 is a column on an Excel file.

I want to organize it in this way:

2015-06-09 =>
  array (size=3)
    DE =>
      array (size=2)
        column => GK
        download => 666
    FR =>
      array (size=2)
        column => GN
        download => 777

2015-06-08 =>
  array (size=3)
    DE =>
      array (size=2)
        column => GL
        download => 666
    FR =>
      array (size=2)
        column => GO
        download => 777

So the same date can show up more than once. if it gets to an array value with the same date - it inserts in it the country code with and its' column.

if it has more than 1 country - it adds a new country. (with the 'download' and column values).

I have this function:

function get_cols_to_array_by_date($array) {

    $mainarr = array();

    $last_in_arr = count($array);

    for ($i=0; $i<$last_in_arr; $i++){

            $mainarr[$array[$i][1]] = array( $array[$i][0]=> array('downloads'=> 666, 'col'=>$array[$i][2]) );

    }

    return $mainarr;

}

which outputs an array that runs over the country when it gets to the same date and doesn't give me an array of countries.

What part am I missing in my code?
Is there a simpler way to do it? ( PHP syntax shortcuts ;) )


texts:
I started Python 3 days ago. This user login code is the first project I completed, not following along with a tutorial. The idea is that you can create a user and login with it. I am wondering if there are ways to make this code much more efficient or shorter. If it needs anything, I'd love to learn new things.
def choices():
    print("Please choose what you would like to do.")
    choice = int(input("For Signing Up Type 1 and For Signing In Type 2: "))
    if choice == 1:
        print("Please Provide")
        username = str(input("Username: "))
        f = open("usernames.txt", 'r')
        info = f.read()
        if username in info:
            print("Username unavailable. Please Try Again.")
            return print(choices())
        f.close()
        password = str(input("Password: "))
        f = open("passwords.txt", 'r')
        info1 = f.read()
        f.close()
        f = open("usernames.txt", 'w')
        info = info + " " + username
        f.write(info)
        f.close()
        f = open("passwords.txt", 'w')
        info1 = info1 + " " + password
        f.write(info1)
        f.close()
        print("Congratulations! You have successfully created an account. You may now login in.")
        return print(choices())
    elif choice == 2:
        print("Please Provide")
        username = str(input("Username: "))
        f = open("usernames.txt", 'r')
        info = f.read()
        if username in info:
            password = str(input("Password: "))
            f = open("passwords.txt", 'r')
            info1 = f.read()
            if password in info1:
                print("Welcome Back " + username + "!")
            else:
                print("Your password is incorrect. Please try again.")
                return print(choices())
        else:
            print("Your username is either incorrect or nonexistent. You can either try again or create a new account.")
            return print(choices())
    else:
        raise TypeError

print(choices())


texts: A recursive_count Function For Various Type Arbitrary Nested Iterable Implementation in C++

texts:
This is a follow-up question for A Summation Function For Arbitrary Nested Vector Implementation In C++ and A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++. Besides the summation result, I am trying to get the element count in arbitrary nested iterable things. For example, there are three elements in std::vector<int> test_vector = { 1, 2, 3 };, so the element count of test_vector is 3. The experimental implementation of recursive_count is as below.
size_t recursive_count()
{
    return 0;
}

template<class T> requires (!is_elements_iterable<T> && !is_iterable<T>)
size_t recursive_count(const T& input)
{
    return 1;
}

template<class T> requires (!is_elements_iterable<T> && is_iterable<T>)
size_t recursive_count(const T& input)
{
    return input.size();
}

template<class T> requires (is_elements_iterable<T> && is_iterable<T>)
size_t recursive_count(const T& input)
{
    size_t output{};
    for (auto &element : input)
    {
        output += recursive_count(element);
    }
    return output;
}

Some test cases of this recursive_count template function.
//  std::vector<int> case
std::vector<int> test_vector = {
    1, 2, 3
};
auto recursive_count_result1 = recursive_count(test_vector);
std::cout << recursive_count_result1 << std::endl;

//  std::vector<std::vector<int>> case
std::vector<decltype(test_vector)> test_vector2 = {
    test_vector, test_vector, test_vector
};
auto recursive_count_result2 = recursive_count(test_vector2);
std::cout << recursive_count_result2 << std::endl;

// std::deque<int> case
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(1);
test_deque.push_back(1);
auto recursive_count_result3 = recursive_count(test_deque);
std::cout << recursive_count_result3 << std::endl;

// std::deque<std::deque<int>> case
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
auto recursive_count_result4 = recursive_count(test_deque2);
std::cout << recursive_count_result4 << std::endl;

A Godbolt link is here.
All suggestions are welcome.
The summary information:

Which question it is a follow-up to?
A Summation Function For Arbitrary Nested Vector Implementation In C++ and
A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++

What changes has been made in the code since last question?
The previous questions are focused on summation operation, and I am trying to implement a recursive_count template function here.

Why a new review is being asked for?
In my opinion, I am not sure the name of this function is good or not. I know there is a function std::count in STL which purpose is to count the elements that are equal to given specific value. If there is any better naming suggestion, please let me know.


texts: Python script to extract columns from a CSV file

texts:
I have a very basic python script that reads a CSV file. I'm importing the csv module setting some empty list variables and getting the data I want. The problem is that I know there is a much more efficient way to get the data I just don't know how to do it and I feel very redundant in creating a reader object multiple times.
The goal of the script is to read the csv and extract fields (header) and column cells under it.
What I'm doing to accomplish this is creating multiple reader objects and looping each object to extract the data.
The csv file is simple and will have more columns in the future:
routers,servers
192.168.1.1,10.0.1.1
192.168.1.2,10.0.1.2

The code is simple:
import csv
filename='Book2.csv'
fields=[]
rows=[]

with open(filename, 'r') as csvfile_field:
    csvreader_group = csv.reader(csvfile_field)
    fields=next(csvreader_group)
    group1=fields[0]
    group2=fields[1]

 with open(filename, newline='') as csvfile_row1:
    csvreader_server = csv.DictReader(csvfile_row1)
    #print(str(group))
    print(group1)
    for row1 in csvreader_server:
        server1 = row1[group1]
        print(server1)

 print('\n')
 with open(filename, newline='') as csvfile_row2:
    csvreader_server = csv.DictReader(csvfile_row2)
    print(group2)
    for row2 in csvreader_server:
        server2 = row2[group2]
        print(server2)

The results are:
routers
192.168.1.1
192.168.1.2

servers
10.0.1.1
10.0.1.2

Can someone review this and suggest a more efficient way to extract the data without the opening of the same file multiple times with the same results?


texts: Ruby Exercise: Implement your own "#group_by" method

texts:
Task:

"Implement a method 'gruppiere', in a way that it can be invoked on all enumerable objects (Enumerable). The method receives a block and returns a hash. The items of the enumerable a grouped within the hash according to the return-value of the block."

What they like to have is an own implementation of Ruby's "#group_by"-method: Ruby-Docs Enumerable

My solution:

module Enumerable
    def gruppiere()
        ret = {}

        self.each { |item|
            key = yield item

            if ret[key] == nil
                tmp = []
                tmp << item
                ret[key] = tmp
            else
                ret[key] << item
            end
        }

        ret
    end
end

puts [1, 2, 3, 4].gruppiere { |i| i % 2 == 0 } # Result: {false=>[1, 3], true=>[2, 4]}

Works well. But I'm sure it could be done better.

Is there a less verbose way to solve the task?

Is my code written in a good way and manner? What could be improved?


texts:
I'm new to HTML coding and have created a basic webpage structure for a basic website with 5 pages.

Can anyone suggest any improvements that could help with the structure, layout and design for the pages?

Code for one of the pages is below (all the same except for the names):

<!DOCTYPE html>

    <title>Fellows and Fullwood LTD</title>
    <meta Charset="utf-8"/>
    <link rel="stylesheet" type="text/css" href="styles.css" />

Fellows and Fullwood

            <u1>
Home

About Us

News

Careers

Contact Us

            </u1>

Contact us
<form  action="" method="POST" enctype="multipart/form-data">

                <input type="hidden" name="action" value="submit"/>

Your name:

              <input name="name" type="text" value="" size="30"/>

                Your email:

                <input name="email" type="text" value="" size="30"/>

 Your message:

                <textarea name="message" rows="7" cols="30"> </textarea>

<input type="submit" value="Send email"/>

          </form>

lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here lots and lots of text here

Sidebar

            <u1>

Home

About Us

News

Careers

Contact Us

          </u1>

&copy;Copyright Fellows and Fullwood 2014.


texts:
I wrote a set data structure with some useful functions. I'm not sure if it is a good implementation and if there are other essential functions that a set should support.

class CustomSet

  def initialize(list=[])
    @cs =[]
    list.each do |n|
      put(n)
    end
  end

  def size
    @cs.size
  end

  def each(&blk)
    @cs.each do |n|
      blk.call(n)
    end
  end

  def index(n)
    @cs.index { |x| x.eql?(n) }
  end

  def ==(other_object)
    return false unless other_object.class == self.class
    return false unless other_object.size ==self.size
    other_object.each do |n|
      return false unless index(n)
    end
    true
  end

  def eql?(other)
    self == other
  end

  def hash
    @cs.reduce(:+){ |n| n.hash }
  end

  def delete(n)
    @cs.delete(n) if index(n)
    self
  end

  def difference(other)
    CustomSet.new(@cs.select { |n| other.index(n).nil? })
  end

  def disjoint?(other)
    union(other).size == self.size + other.size
  end

  def intersection(other)
    CustomSet.new(@cs.select { |n| other.index(n) })
  end

  def subset?(other)
    self.size >= other.size && intersection(other) == other
  end

  def union(other)
    u = CustomSet.new(@cs)
    other.each { |n| u.put(n) }
    u
  end

  def member?(n)
    index(n)
  end

  def put(n)
    @cs << n unless index(n)
    self
  end

  def empty
    @cs = []
    self
  end

  def to_list
    @cs
  end

end

Set treats integers and decimals as distinct elements:

irb(main):019:0> Set.new([1,2,3]) == Set.new([1,2.0,3])
=> false
irb(main):020:0> Set.new([1,2,3]) == Set.new([1,2,3])
=> true
irb(main):021:0> 2 == 2.0
=> true
irb(main):022:0> [2] == [2.0]
=> true
irb(main):023:0> Set.new([1,2,3]) == Set.new([1,3,2])
=> true

Set accepts a range, so the initialize has to copy elements manually unless there is another way.

irb(main):029:0> Set.new(1..3) == Set.new([1,3,2])
=> true


texts:
So here is my input

\\?\usb#vid_04d9&pid_1702#6&12e3c9ed&0&2#{a5dcbf10-6530-11d2-901f-00c04fb951ed}

I need to extract 04d9 and 1702 from this string. Instead of copying the values I just point my pointer to their respective locations.

And here is my horrible code

#DEFINE FIRST_STRING 1
#DEFINE SECOND_STRING 2
#DEFINE THIRD_STRING 3

VOID
StringDelimiterReplace(
    PCHAR string,
    INT delimiter,
    INT replace
)
/*
Description:
    Replaces the delimiter in the string with the replace value specified
*/
{
    size_t stringLen = strlen(string);
    for (size_t size = 0; size < stringLen; size++) {
        if (string[size] == delimiter) string[size] = replace;
    }
}

VOID
GenericStringSplit(
    PCHAR string,
    INT delimiter,
    PCHAR *dest,
    INT tokenNum,
    INT replace
)
/*
Description:
    A generic string splitting function which returns the string at token number
    specified,
    Also provision to replace the delimiter with string
*/
{
    int i = 1;
    size_t size;
    if( delimiter != replace) StringDelimiterReplace(string, delimiter, replace);
    if (tokenNum == 1) *dest = string;
    for (size = 0; ; size++) {
        if (string[size] != replace) continue;
        if (i == tokenNum - 1) break;
        if (i > tokenNum - 1) return;
        i++;
    }
    *dest = &string[++size];
}

//main
GenericStringSplit(string, '#', &dest, SECOND_STRING, '\0');
GenericStringSplit(dest, '&', &vendorId, FIRST_STRING, '\0');
GenericStringSplit(dest, '\0', &productId, SECOND_STRING, '\0');
GenericStringSplit(vendorId, '_', &vendorId, SECOND_STRING, '\0');
GenericStringSplit(productId, '_', &productId, SECOND_STRING, '\0');


texts: Simple IPv4 and port validation for chat client

texts:
This is part of my chat client's code.  It works fine but it looks messy.  Any ideas?

//IP Validation
private void textBox3_Leave(object sender, EventArgs e)
{
    IPAddress ip;
    bool ValidateIP = IPAddress.TryParse(textBox3.Text, out ip);
    if (ValidateIP)
    {
        button2.Enabled = true;
        button3.Enabled = true;
    }
    else
    {
        //Disables buttons and locks into text box
        textBox3.Text = "Invalid IPv4 address!!";
        textBox3.Select();
        button2.Enabled = false;
        button3.Enabled = false;
    }
}

//Port Validation
private void textBox4_Leave(object sender, EventArgs e)
{
    bool ValidatePort;
    int porttest = 0;
    try
    {
        porttest = Convert.ToInt32(textBox4.Text);
    }
    catch (Exception)
    {
    }

    if (porttest > 1 && porttest < 65535)
    {
        ValidatePort = true;
    }
    else
    {
        ValidatePort = false;
    }

    if (ValidatePort)
    {
        button2.Enabled = true;
        button3.Enabled = true;
    }
    else
    {
        //Disables buttons and locks into text box
        textBox4.Text = "Invalid Port";
        textBox4.Select();
        button2.Enabled = false;
        button3.Enabled = false;
    }
}


texts: Given an ASCII string, replace all ASCII chars with their Cyrillic equivalents

texts:
The objective of the following PHP function is simple: given an ASCII string, replace all ASCII chars with their Cyrillic equivalents.

As can be seen, certain ASCII chars have two possible equivalents.

For example: if the function is fed the string "dvigatel" it should get you "двигател".

The problem: if I pass "dvigat", the function will finish its execution in a fairly reasonable amount of time.

But, if I pass "dvigatel", which is only a couple letters longer, the execution time exceeds my 30 second PHP execution time limit.

Could anybody give me a few pointers here, what's wrong with this function, why does it run so slow with an 8-char string?

function transliterate($query) {
        $map=array(
            "a" => array("а", "ъ"),
            "b" => "б",
            "c" => array("с", "ц"),
            "d" => "д",
            "e" => "е",
            "f" => "ф",
            "g" => array("г", "ж"),
            "h" => "х",
            "i" => array("и", "й"),
            "j" => array("дж", "й"),
            "k" => "к",
            "l" => "л",
            "m" => "м",
            "n" => "н",
            "o" => "о",
            "p" => "п",
            "q" => "я",
            "r" => "р",
            "s" => "с",
            "t" => "т",
            "u" => array("ъ", "ю", "у"),
            "v" => array("в", "ж"),
            "w" => "в",
            "x" => array("кс", "х"),
            "y" => array("ъ", "у"),
            "z" => "з"
        );
        $query_array = preg_split('/(?<!^)(?!$)/u', $query );

        $en_letters=array_keys($map);

        $this->processed[]=$query;

        foreach ($query_array as $letter) {
            if (in_array($letter, $en_letters)) {

                if (!is_array($map[$letter])) {
                    $query_translit=str_replace($letter, $map[$letter], $query);
                } else {
                        foreach ($map[$letter] as $bg_letter) {
                            $query_translit=str_replace($letter, $bg_letter, $query);

                            if (!in_array($query_translit, $this->transliterations)) $this->transliterations[]=$query_translit;
                        }
                    }

            } else {
                $query_translit=$query;
            }

            if (!in_array($query_translit, $this->transliterations)) $this->transliterations[]=$query_translit;
        }

        foreach ($this->transliterations as $transliteration) {
            if (!in_array($transliteration, $this->processed)) {
                if (!preg_match("/[a-zA-Z]/", $transliteration)) {
                    return;
                } else {
                    $this->transliterate($transliteration);
                }
            }
        }
    }


texts: Conditionally creating new variables for data manipulation

texts:
My problem is related to data manipulation: on the basis of the existing variables in a given data set, I would like to create new ones. Bonus points for performance as well as code readability.

Let's consider a reproducible example for the famous "iris" data set. My goal is to create a new variable, which can be described by the following set of conditions:

if species="setosa" or species="virginica" and sepal.length < 5 then
    new variable = "Species1",
if (species="setosa" or species="virginica") and 5<= sepal.length <
10 then new variable = "Species2",
if (species="setosa" or species="virginica") and sepal.length >= 10
then new variable = "Species3",
otherwise, new variable = species (in this case "versicolor").

In order to achieve this, I have written the following conditional instructions:

iris$Speciec2 <- ifelse(iris$Species %in% c("setosa", "virginica"),
                       ifelse(iris$Sepal.Length < 5, "Species1",
                              ifelse(iris$Sepal.Length >= 5 & iris$Sepal.Length < 7,
                                     "Species2", "Species3")), as.character(iris$Species))

and it's really hard to read. I wonder if there are any better solutions.


texts:
I have a jsonArray.js file
const jsonArray = [
  {"click": "clearValue", "alt": "clearValueIcon",
  "src" : "https://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/128/Actions-edit-clear-icon.png",
  "style": "grid-column:1/2;grid-row: 2/3;"},
  {"click": "negativePositive", "alt": "negativePositiveIcon",
  "src" : "https://image.flaticon.com/icons/svg/1777/1777560.svg",
  "style":"grid-column:2/3;grid-row: 2/3"},
  {"click": "percentage", "alt": "percentageIcon",
  "src" : "https://image.flaticon.com/icons/svg/69/69839.svg",
  "style":"grid-column:3/4;grid-row: 2/3;"}
]

In my App.vue file I import it and give the value to imagesData
 beforeMount() {
    this.imagesData = JsonArray;
  }

Then I use a for loop to populate my img tags
<img
          v-for="img in imagesData"
          :key="img.alt"
          @click="getFunction(img.click)"
          :alt="img.alt"
          :src="img.src"
          :style="img.style"
        />

The only way I have been able to get the click to work is with a giant switch statement that evaluates the string and calls the method.
 getFunction: function(fn) {
      switch (fn) {
        case "clearValue":
          this.clearValue();
          break;
        case "negativePositive":
          this.negativePositive();
          break;
}}

I am thinking there is a better way, but cannot think of one.


texts: Functions like std::stoi for unsigned and shorter types using __gnu_cxx::__stoa

texts:
C++11 introduced the new standard library function std::stoi, unfortunately there is no equivalent function to convert an unsigned number inside an std::string to its numeric value. Moreover, there is no direct way to convert a string to a signed/unsigned short and char.

The standard library from GNU uses the function __gnu_cxx::__stoa to implement std::stoi. Although not portable, this can be used to implement these functions:

namespace gnu_np {

inline int
stoi(const string& __str, size_t* __idx = 0, int __base = 10)
{ return __gnu_cxx::__stoa<long, int>(&std::strtol, "stoi", __str.c_str(),
                  __idx, __base); }

inline short
stos(const string& __str, size_t* __idx = 0, int __base = 10)
{ return __gnu_cxx::__stoa<long, short>(&std::strtol, "stos", __str.c_str(),
                  __idx, __base); }

inline char
stoc(const string& __str, size_t* __idx = 0, int __base = 10)
{ return __gnu_cxx::__stoa<long, char>(&std::strtol, "stoc", __str.c_str(),
                  __idx, __base); }

inline unsigned
stou(const string& __str, size_t* __idx = 0, int __base = 10)
{ return __gnu_cxx::__stoa<unsigned long, unsigned>(&std::strtoul, "stou", __str.c_str(),
                  __idx, __base); }

inline unsigned short
stous(const string& __str, size_t* __idx = 0, int __base = 10)
{ return __gnu_cxx::__stoa<unsigned long, unsigned short>(&std::strtoul, "stous", __str.c_str(),
                  __idx, __base); }

inline unsigned char
stouc(const string& __str, size_t* __idx = 0, int __base = 10)
{ return __gnu_cxx::__stoa<unsigned long, unsigned char>(&std::strtoul, "stouc", __str.c_str(),
                  __idx, __base); }

} // namespace gnu_np

Besides not being portable, it seems to work.

Do you see any reason why one or more of these functions should not work?

There is a simpler portable way to implement these functions?

Should we expect __gnu_cxx::__stoa remain stable in future glibc versions?


texts:
I have created a simple ConfigManager in C# that loads each line of a file. If the line contains = then it gets the before = (the key) and the after = (the value).

For example, my config file would look something like this:

# Comment here
MyConfigKey1=MyValue1
MyConfigKey2=MyValue2
MyConfigKey3=MyValue3

Obviously my config file wouldn't be that, but that's the layout of it. If the file is unreadable or is not found then the defaults are used.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace Sirius.Core.Config
{
    internal sealed class ConfigManager
    {
        private readonly Dictionary<string, string> _configItems;

        public ConfigManager(string configFile)
        {
            _configItems = new Dictionary<string, string>();

            var logManager = Sirius.GetServer().GetLogManager();
            var stopwatch = Stopwatch.StartNew();

            try
            {
                if (File.Exists(configFile) && Sirius.GetServer().GetUtility().IsFileLocked(new FileInfo(configFile)))
                {
                    _configItems = File.ReadLines(configFile)
                        .Where(IsConfigurationLine)
                        .Select(line => line.Split('='))
                        .ToDictionary(line => line[0], line => line[1]);

                }
                else
                {
                    _configItems.Add("database.host", "localhost");
                    _configItems.Add("database.username", "root");
                    _configItems.Add("database.password", "");
                    _configItems.Add("database.name", "database");
                    _configItems.Add("database.port", "3306");
                    _configItems.Add("database.max_connections", "10000");
                    _configItems.Add("sockets.port", "30000");
                    _configItems.Add("sockets.backlog", "50");

                    logManager.Warn("Using the default configuration.");
                }
            }
            catch (Exception exception)
            {
                logManager.Error(exception.Message, exception);
            }
            finally
            {
                logManager.Information("Loaded Config Data [" + stopwatch.ElapsedMilliseconds + "ms]");
                stopwatch.Stop();
            }
        }

        private static bool IsConfigurationLine(string line)
        {
            return !line.StartsWith("#") && line.Contains("=");
        }

        public string GetConfigElement(string key)
        {
            string value;

            if (!_configItems.TryGetValue(key, out value))
            {
                Sirius.GetServer().GetLogManager().Error("Missing configuration key `" + key + "`");
            }

            return value;
        }
    }
}