texts: Arrow key input to change selected row and column in a grid of HTML elements

texts:
Below is the working code but it can surely be simplified with some sort of changeCol() and changeRow() functions, or perhaps a single function?

$(document).ready(function(e){
    let keys = {};
    let selRow = 0;
    let selCol = 0;
    let rowCount = 5;
    let colCount = 5;

    //set initial highlits

    $('[data-row="0"]').addClass('hl');
    $('[data-col="0"]').addClass('hl');

    $(document).keydown(function(event){
        keys[event.which] = true;
    }).keyup(function(event){
        delete keys[event.which];
    });

        for (let row = 0; row < rowCount; row++) {
        for (let col = 0; col < colCount; col++) {
            let elPiece = $("<span>", {
                "class": 'piece',
                "data-col": col,
                "data-row": row,
                text: "O"
            });
            $('#board').append(elPiece)
        }
    }

    function gameLoop() {
        // w for north
        if (keys[87]) {
            shiftCol(selCol, -1);
        }
        //press s for south
        if (keys[83]) {
            shiftCol(selCol, 1);
        }

        //up arrow
        if (keys[38]) {
            $('[data-row="' + selRow + '"]').removeClass('hl');
            $('[data-col="' + selCol + '"]').addClass('hl');
            if (selRow === 0) {
                selRow = rowCount - 1;
            } else {
                selRow--;
            }
            $('[data-row="' + selRow + '"]').addClass('hl');
        }

        //down arrow
        if (keys[40]) {
            $('[data-row="' + selRow + '"]').removeClass('hl');
            $('[data-col="' + selCol + '"]').addClass('hl');
            if (selRow === rowCount - 1) {
                selRow = 0;
            } else {
                selRow++;
            }
            $('[data-row="' + selRow + '"]').addClass('hl');
        }

        //left arrow
        if (keys[37]) {
            $('[data-col="' + selCol + '"]').removeClass('hl');
            $('[data-row="' + selRow + '"]').addClass('hl');
            if (selCol === 0) {
                selCol = colCount - 1;
            } else {
                selCol--;
            }
            $('[data-col="' + selCol + '"]').addClass('hl');
        }

        //right arrow
        if (keys[39]) {
            $('[data-col="' + selCol + '"]').removeClass('hl');
            $('[data-row="' + selRow + '"]').addClass('hl');
            if (selCol === colCount - 1) {
                selCol = 0;
            } else {
                selCol++;
            }
            $('[data-col="' + selCol + '"]').addClass('hl');
        }
        // code to move objects and repaint canvas goes here

        setTimeout(gameLoop, 100);
    }
    gameLoop();
});
#board {
  width: 150px;
  height: 150px;
}

.piece {
  width: 30px;
  height: 30px;
  display: inline-block;
  background-color: black;
  color: white;
  text-align: center;
  line-height: 30px;
}

.hl {
  background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="board">

</div>


texts:
This copies the level graphics but uses a scale parameter. If the scale is 1, it copies a screen size segment. If it's 2, it copies a half-screen size piece and scales it to the screen size, etc.

How can I optimise this game level code or achieve the same outcome but simpler?

 public void render(Graphics g){

    int test = (screenwidth/2)-((screenwidth/2)/scale);
    int test2 = (screenheight/2)-((screenheight/2)/scale);

    int scaledstartx=test;
    int scaledstarty=test2;
    int scaledwidth=screenwidth-test;
    int scaledheight=screenheight-test2;
    int locationx=(wherex)+halfpwidth-(screenwidth/2);
    int locationy=(wherey)+halfpheight-(screenheight/2);

    g.drawImage(DrawnLevel,0,0,screenwidth,screenheight,
    scaledstartx+locationx,scaledstarty+locationy, scaledwidth+locationx,scaledheight+locationy, null );
 }


texts:
Is there a way to make this code shorter and more succinct? Thanks

My objective is to:

Take an array of objects (someArray)
Use get() to get one specific property of each of someArr's objects (which is also an object itself, as I am working with a json object)
And push this object to the 'tabs' array of the newly created object I am returning

function (someArray) {
    var resultObj = {};
    resultObj.tabs = [];
    someArray.map(function (obj) {
        resultObj.tabs.push(obj.get());   // get() gets the dataValues (Sequelize)
    });
    return resultObj;
}


texts: Counting words, letters, average word length, and letter frequency

texts:
I'm pretty sure my code is mostly correct.  I think I'm having formatting errors more than anything. I keep receiving warnings about "double to float and int to float,possible loss of data.  Here is what I am trying to accomplish exactly.

  Write a function that accepts a pointer to a C-
  string as an argument and calculates the number of
  words contained in the string as well as the number of letters in the string. Communicate (or send) both of these
  values back to the main function, but DO NOT use global variables
  (variables defined outside of a function).

  Write another function that accepts the number of letters and the number of words and sends the
  average number of letters per word (or average word
  size) back to the main function.

  Demonstrate the functions in a program that asks the user to input a string.
  First, store the input
  in a large array. The program should dynamically allocate just enough memory to store the
  contents of that array.
  Copy the contents of the large array into the dynamically allocated
  memory. Then the program should pass that new, dynamically allocated array to the first
  function.
  Both the number of words and the average word size should be displayed on the
  screen. Round the
  average word size to 2 decimal places.

  For instance, if the string argument is "Four score and seven years ago" the first function (word
  count) should calculate and send back a word count of 6 and a letter count of 25. The second
  function (average word size) should send back 4.17, or 25 / 6.

  Extra challenge: See if you can prevent the program from counting punctuation (such as quotes
  or periods) as part of the sentence. Also, see if you can prevent the program from counting extra
  spaces as new words. For in
  stance, 2 spaces will often follow a colon, such as the sentence:
  "There are 3 primary colors
  :
  red, blue, and green."
  In this example, the word count should be 9 (the number
  3
  does count as a 1-letter word), and the letter count should be 37, for an average of 4.11

#include<iostream>
#include<string>

using namespace std;

int CountWordsAndLetters(char* str, int& words, int& letters)
{
    words = 0;
    unsigned int i = 0;
    letters = 0;

    while (str[i] == ' ')
            i++;

    for (; str[i]; i++)
    {
            if (((str[i] >= 'a') && (str[i] <= 'z')) || ((str[i] >= 'A') && (str[i] <= 'Z')))
                    letters++;
            if (str[i] == ' ')
            {
                    words++;
                    while (1)
                            if (str[i] == ' ')
                                    i++;
                            else
                            {
                                    i--;
                                    break;
                            }

            }

    }
    words = words + 1;
    return (words);
}

float avg(float words, float letters)
{
    float a = (double)(letters / words);
    return a;
}

int main()
{
    char array[1000000];
    int words = 0;
    int letters = 0;

    cout << "enter the string\n\n";
    gets(array);
    int size;
    for (size = 0; array[size]; size++);
    char* str = new char[size];
    strcpy(str, array);
    CountWordsAndLetters(str, words, letters);

    cout << "\nword count= " << words << endl;
    cout << "\n letter count=" << letters << endl;
    cout << "\naverage number of letters per word=" << avg(words, letters);

    return 1;
}


texts: Fake closure to provide variable scoping in SASS

texts:
For some time I've wanted a way to provide private scope to variables, functions, etc. that needed to be used across multiple separate selections. As far as I'm aware there is no official solution for providing scope in this manner. However, it occurred to me that @at-root could help with this.

This isn't probably the most practical example, but let's say we wanted to create classes that would remove padding, borders, outlines, and margins.

$prefix: '.no'

#{$prefix}-outline
    outline: none

@each $region in margin, border, padding
    #{$prefix}-#{$region}
        #{$region}: 0 !important

    @each $position in top, right, bottom, left
        #{$prefix}-#{$region}-#{$position}
            #{$region}-#{$position}: 0 !important

The problem with this example is that $prefix will pollute the global scope. We could avoid this by nesting everything under @at-root.

@at-root
    $prefix: '.no'

    #{$prefix}-outline
        outline: none

    @each $region in margin, border, padding
        #{$prefix}-#{$region}
            #{$region}: 0 !important

        @each $position in top, right, bottom, left
            #{$prefix}-#{$region}-#{$position}
                #{$region}-#{$position}: 0 !important

What opinions are there about using @at-root in this manner? Is there a better way to accomplish this?


texts: Validating a list of dictionaries of names and tags

texts:
I created a Python function to check the types from a list and also check the keys inside an dictionary within that list.

I have the following data:

[
   dict(name='Frank', tags=['dog', 'cat']),
   dict(name='Manfred', tags=['cat', 'chicken'])
]

My function looks like this:

def _validate_data(self, data):
    if not isinstance(data, list):
        raise('not a list')
    else:
        for element in data:
            if not isinstance(element, dict):
                raise('not a dictionary')
            else:
                if not all(key in element for key in ('name', 'tags')):
                    raise('Keys not inside dictionary')

This works fine, but I don't like the structure and I also think there may be a smarter way to code this function. I hope someone could give me some nice and helpful hints.


texts: Asynchronous database lookups in Node.JS using Promises

texts:
Not confident enough if this would be the correct 'node way' of writing Promises:

Essentially, there are two async database calls, the result from both of these calls has to be collected and used in rendering the view:

Creating ...

exports.getIndustryById = function(industryId) {
   return new Promise(function(resolve, reject) {
    Industry.findOne({
      value: industryId
}, function(err, industry) {
  if (err) {
    return reject(err);
  }
  return resolve(industry);
});
})
}

exports.getCountryById = function(countryId) {
 return new Promise(function(resolve, reject) {
  Country.findOne({
   value: countryId
  }, function(err, country) {
  if (err) {
    return reject(err);
  }
   return resolve(country);
  });
 })
}

And using ...

  exports.renderEditProfile = function(req, res, next) {
  var i, c;
  ct.getIndustryById(req.user.industry)
    .then(function(industry) {
      i = industry;

      return ct.getCountryById(req.user.country);
    }).then(function(country) {
      c = country;

      res.render('profile_edit', {
        profile: req.user,
        industry: i,
        country: c
      });
    })
    .catch(function(err) {
      res.status(500).json({'message': err});
    });
};

This works, but am I getting Promises right?


texts: Creating a ModelBinder to Sanitize user input in HTML format

texts:
I have a custom model binder which takes user input in HTML format, sanitize the HTML input by removing any script or XSS threat and returns the sanitized HTML string:

public class AllowAndSanitizeHtmlBinder : IModelBinder
{

    private HtmlSanitizer _htmlSanitizer = HtmlSanitizerFactory.CreateInstance();

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var request = controllerContext.HttpContext.Request;
        var name = bindingContext.ModelName;

        // get the un-validated user input in HTML format
        var unsanitizedMessageHtmlString = request.Unvalidated[name];

        // removed script or any XSS threat from user input
        return _htmlSanitizer.Sanitize(unsanitizedMessageHtmlString);
    }
}

I am using HtmlSanitizer Nuget package to do this. I need to configure this object and tell it to add "nofollow" to all the links.

So I have created HtmlSanitizerFactory to do this configuration:

public static class HtmlSanitizerFactory
{
    public static HtmlSanitizer CreateInstance()
    {
        var sanitizer = new HtmlSanitizer();
        sanitizer.PostProcessNode += (s, e) =>  (e.Node as IHtmlAnchorElement)?.SetAttribute("rel", "nofollow noreferrer");
        return sanitizer;
    }
}

I am not entirely happy with this code. The reason is, in the future, a developer may forget that HtmlSanitizerFactory should be used for instantiating HtmlSanitizer... so he would create his new ModelBinder and initialize the object like:

HtmlSanitizer _htmlSanitizer = new HtmlSanitizer();

This would introduce a bug because links won't be converted to "nofollow"

I think DI would have worked much better here, but I don't know how to inject a class into a custom ModelBinder


texts: Bootstrap WordPress Carousel Recent Posts

texts:
This works, but I would like suggestions to improve it. For one I think the get posts shouldn't have to be repeated twice, but it only pulls the first two posts if I don't do it this way.

Also, I think
$incNum == 0 ? 'class="active"':'class' can be simplified, but if I take the second part out I get an error.

Most Recent Post

                    <?php
                    // Get posts (tweak args as needed)
                    $i=0;
                    $incNum = 0;
                    $args = array(
                        'post_type'        => 'post',
                        'posts_per_page'   => -1,
                        'orderby' => "date",
                        'order' => "desc"
                    );
                    $posts = get_posts( $args );
                ?>

                        <?php foreach (array_chunk($posts, 4, true) as $posts) :  ?>
                        <?php echo( '

');
                        $incNum++;
                        ?>

                    <?php endforeach; ?>

                               <?php
                    // Get posts (tweak args as needed)
                    $i=0;
                    $incNum = 0;
                    $args = array(
                        'post_type'        => 'post',
                        'posts_per_page'   => -1,
                        'orderby' => "date",
                        'order' => "desc"
                    );
                    $posts = get_posts( $args );
                ?>

                <?php foreach (array_chunk($posts, 4, true) as $posts) :  ?>
                <div class="item <?php if ($i==0){echo 'active';}?>">

                        <?php foreach( $posts as $post ) : setup_postdata($post); ?>

                                                <?php the_post_thumbnail( 'full' );  ?>

03 Dec 2014

<?php echo $i?>

<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?>

                                            John doe

<?php echo substr(get_the_excerpt(), 0,99).' [...]'; ?>

                        <?php $i++ ?>

                        <?php endforeach; ?>

                <?php endforeach; ?>


texts: Resx Translation Helper, V.2.0 Remove Files Window

texts:
Related to Resx Translation Helper, V.2.0

This is the code for the Remove Files window.  I was able to keep code out of the code-behind here, but I have a feeling I botched something else.

IDisplayOpenFiles.cs:

public interface IDisplayOpenFiles
{
    object DataContext { set; }

    event EventHandler Closed;

    void Show();
    void Close();
}

DisplayOpenFiles.xaml:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition Height="40" />
    </Grid.RowDefinitions>
    <DataGrid ItemsSource="{Binding OpenFiles}" AutoGenerateColumns="False"
              CanUserAddRows="False" CanUserDeleteRows="False" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
        <DataGrid.Columns>
            <DataGridCheckBoxColumn CanUserSort="True" IsReadOnly="False" Binding="{Binding Selected, Mode=TwoWay}" />
            <DataGridTextColumn CanUserSort="True" Binding="{Binding Value}" IsReadOnly="True" Width="600" />
        </DataGrid.Columns>
    </DataGrid>

    <Grid Grid.Row="1">
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Button Grid.Column="0" Content="{x:Static properties:Resources.RemoveFilesCancel}" Command="{Binding CancelRemoveFiles}" />
        <Button Grid.Column="1" Content="{x:Static properties:Resources.RemoveFilesRemove}" Command="{Binding RemoveSelectedFiles}" />
    </Grid>
</Grid>

DisplayOpenFilesVM.cs:

public class Files
{
    public string Value { get; private set; }
    public bool Selected { get; set; }

    public Files(string value, bool selected = false)
    {
        Value = value;
        Selected = selected;
    }
}

public class DisplayOpenFilesVM
{
    private readonly IDisplayOpenFiles _window;
    public ObservableCollection<Files> OpenFiles { get; set; }

    private ICommand _removeSelectedFiles;
    public ICommand RemoveSelectedFiles
    {
        get
        {
            return _removeSelectedFiles ?? (_removeSelectedFiles = new RelayCommand
            (
                param =>
                {
                    OnRemoveFiles(OpenFiles.Where(f => f.Selected).Select(f => f.Value));
                    _window.Close();
                }
            ));
        }
    }

    private ICommand _cancelRemoveFiles;
    public ICommand CancelRemoveFiles
    {
        get
        {
            return _cancelRemoveFiles ?? (_cancelRemoveFiles = new RelayCommand
            (
                param =>
                {
                    OnRemoveFiles(new List<string>());
                    _window.Close();
                }
            ));
        }
    }

    public DisplayOpenFilesVM(IDisplayOpenFiles window, IEnumerable<string> openFiles)
    {
        _window = window;
        OpenFiles = new ObservableCollection<Files>();
        foreach (var file in openFiles)
        {
            OpenFiles.Add(new Files(file));
        }

        _window.Closed += (s, e) =>
        {
            OnRemoveFiles(new List<string>());
        };

        window.DataContext = this;
    }

    public void Show()
    {
        _window.Show();
    }

    private bool _eventFired;
    public event EventHandler<IEnumerable<string>> FilesSelected;
    protected virtual void OnRemoveFiles(IEnumerable<string> selectedFiles)
    {
        var handler = FilesSelected;
        if (handler != null && !_eventFired)    // only fire once
        {
            _eventFired = true;
            handler(this, selectedFiles);
        }
    }
}


texts: Seeking improved Objective-C permutation algorithm

texts:
This algorithm seeks to find all of the possible permutations of a word:

-(void)permute:(NSMutableArray*)word position:(int)p length:(int)l{
    if(p==l){
     [self.allPermutations addObject:[word componentsJoinedByString:@""]];
    }
    else {
    for(int i = p;i<l;i++){
        NSString* t;
        t= word[p];
        word[p] = word[i];
        word[i] = t;
        [self permute:word position:p+1 length:l];
        t= word[p];
        word[p] = word[i];
        word[i] = t;
        }
    }
}

After that, I clean out the duplicates with this:

NSArray *cleanedArray = [[NSSet setWithArray:self.allPermutations] allObjects];

This starts to show a lag when the words get to 9 letters or greater. 9 letters is 362,880 loops. Any tips to get this down, or speed up this algorithm in a different way?


texts:
I have a List that I want to compare to an Enum.
If a.Value is found in the Enum we return true.
I feel that I should be able to make this a single line, but have struggled.
private bool IsFound(IEnumerable<SomeAttribute> attributes)
{
    foreach (AttributesInMethod option in Enum.GetValues(typeof(AttributesInMethod)))
    {
        if (attributes.Any(a => option.GetDisplayNameENUM().Contains(a.Value)))
        {
            return true;
        }
    }
    return false;
}


texts: Check for correct number of elements in exploded string

texts:
Let's say I've got this string:

$str = '1-2-3';

and I explode this like so:

$strSplit = explode('-', $str);

what would be the best way to check if I've got the correct number of elements and whether they are numeric (because the input can vary)?

Straightforward, I would say something like this:

if (isset($strSplit[0]) && is_numeric($strSplit[0]) && isset($strSplit[1]) && is_numeric($strSplit[1]) && isset($strSplit[2]) && is_numeric($strSplit[2]) {
    // some code
}

But you could also do:

if (count($strSplit) === 3 && is_numeric($strSplit[0]) && is_numeric($strSplit[1]) && is_numeric($strSplit[2])) {
    // some code
}

You can use some array functions to check for the is_numeric part, but that seems fussy, less readable and is probably slower. I could be wrong, though...


texts: Range class to represent limited values, like HP, Stamina and so on

texts:
I made a small script for Unity3D, meant to be use as GameComponent for GameObjects. It is supposed to represent values that have a max value, and an actual value. In games that would be the case, for instance, for the Health Points, the Stamina, Magic Points and so on. I would love to hear your feedback.

/////////////
//
// This is meant for things like Stamina, or HP. You have a max
// value, and an actual value.
//
// It inherits from MonoBehaviour because it is meant to be used
// as a Game Object Component
//
/////////////

using UnityEngine;
using UnityEngine.UI;

public class Range : MonoBehaviour {

    private int val, max;

    public Slider slider;

    // Is/Has/Can

    public bool IsDepleted() { return val == 0;    }
    public bool IsFull()     { return val == max; }

    public bool HasAtLeast(int _val) { return this.val >= _val; }

    // Actions

    public void Fill()    { val = max; }
    public void Deplete() { val = 0;   }

    public void Increase(int _val) { this.SetValue(this.val + _val); }
    public void Decrease(int _val) { this.SetValue(this.val - _val); }

    // Getters

    public int GetValue() { return this.val; }
    public int GetMax()   { return this.max; }

    // Setters

    public void SetValue(int amount) {
        if (amount > this.max) this.Fill();
        else if (amount < 0) this.Deplete();
        else this.val = amount;

        UpdateSlider();
    }

    public void SetMax(int amount) {
        this.max = amount;
        if (this.val > this.max) this.Fill();

        UpdateSlider();
    }

    private void UpdateSlider() {
        if (slider) {
            slider.maxValue = this.max;
            slider.value = val;
        }
    }
}


texts: Data structure to count occurrences of entries

texts:
I would love to hear any thoughtful suggestions on how to improve my programming style in order to be more understandable.

Listed below is a sample of my code which I wrote in Eclipse:

//Implement using a linked list
public class FrequencyBag<T>
{
// TO DO: Instance Variables
private Node firstNode;
private int numOfItems;

private class Node{
//Node Instance Variables

    private T data;
    private int frequency;
    private Node next;

    private Node(T Data, Node nextNode){
        data= Data;
        next=nextNode;
        frequency=1;
    }

    private void addF(){
        frequency++;
    }

    private int getF(){
        return frequency;
    }

}

/**
 * Constructor
 * Constructs an empty frequency bag.
 */
public FrequencyBag()
{
 firstNode=null;
 numOfItems =0;
}

/**
 * Adds new entry into this frequency bag.
 * @param aData the data to be added into this frequency bag.
 */
public void add(T aData)
{

  boolean found =false;
  Node currNode=firstNode;

  while(currNode !=null){
      if(currNode.data.equals(aData)){
          currNode.addF();
          found=true;
          break;
      }

      currNode= currNode.next;
  }

  if(!found){
      Node tempNode=firstNode;
      firstNode= new Node(aData,tempNode);

  }
  numOfItems++;

  }
/**
 * Gets the number of occurrences of aData in this frequency bag.
 * @param aData the data to be checked for its number of occurrences.
 * @return the number of occurrences of aData in this frequency bag.
 */
public int getFrequencyOf(T aData)
{
    Node currNode= firstNode;
    while(currNode!=null){
        if(currNode.data.equals(aData)){
            return currNode.getF();
        }
     currNode= currNode.next;
    }

    return 0;
}

/**
 * Gets the maximum number of occurrences in this frequency bag.
 * @return the maximum number of occurrences of an entry in this
 * frequency bag.
 */
public int getMaxFrequency()
{
    if(firstNode!=null){
    Node currNode= firstNode;
    Node maxNode= firstNode;
    while(currNode!=null){
        if(currNode.getF()>=maxNode.getF()){
            maxNode=currNode;
        }
        currNode=currNode.next;
    }
    return maxNode.getF();
    }
    else{
        return 0;
    }
}

/**
 * Gets the probability of aData
 * @param aData the specific data to get its probability.
 * @return the probability of aData
 */
public double getProbabilityOf(T aData)
{
  if(firstNode!=null){
    boolean flag=true;
    double dataF=0;
    double prob=0;
    Node currNode= firstNode;
    while(currNode!=null){
        if(currNode.data.equals(aData)){
             dataF=(double)currNode.getF();
             flag=false;
             break;
        }
     currNode= currNode.next;
    }
    if(!flag){
      prob= dataF/(double)numOfItems;
    }
    return prob;
  }
  else{
      return 0;
  }
}

/**
 * Empty this bag.
 */
public void clear()
{
    firstNode=null;
    numOfItems=0;
}

/**
 * Gets the number of entries in this bag.
 * @return the number of entries in this bag.
 */
public int size()
{
    return numOfItems;
}
}


texts:
I'm attempting to create a replacement shell for /bin/bash, that only permits commands defined by a read only config file. These commands will be run by absolute paths, and take no arguments. I'm not an experienced C programmer, so I kindly ask for your comments and feedback. I'm especially concerned with buffer overflows etc. Please note that the "re read" config file is by design, if the rules change I would like the sessions already running to adhere to these changes.

#include <stdio.h> /* fopen et al */
#include <string.h> /* strcmp, strlen */
#include <unistd.h> /* access */
#include <stdlib.h> /* system */
#define RULEFILE "/home/ole/wannabeshell/rules.conf"
#define PROMPT "$ "
#define BUFFER 512

// not really a shell - just executes commands
// thats given in the config file by absolute
// paths..

int main (int argc, char **argv) {
    // buffer size + 1 for \0 ending
    char sbuffer[BUFFER + 1], fbuffer[BUFFER + 1];

    // open the rulefile
    FILE *fh = fopen(RULEFILE, "r");

    // give up if unable to open it
    if (fh == NULL) {
        perror("unable to open rulefile");
        return(EXIT_FAILURE);
    }

    while (1) {
        // print prompt character
        printf(PROMPT);

        // force flush
        fflush(NULL);

        // make sure buffers does not contain data
        // from previous runs of the loop
        memset(sbuffer, 0, sizeof(sbuffer));
        memset(fbuffer, 0, sizeof(fbuffer));

        // read up to sizeof buffer, or \n
        if (fgets(sbuffer, sizeof(sbuffer), stdin) == NULL) {
            break;
        }

        // check for data up to NULL, must be atleast one !NULL
        // char for this test to be successful
        if (strlen(sbuffer) < 1) {
            break;
        }

        // find and replace \r and \n if exists
        sbuffer[strcspn(sbuffer, "\r\n")] = 0;

        // time to exit?
        if (strcmp(sbuffer, "exit") == 0 || strcmp(sbuffer, "quit") == 0) {
            break;
        }

        // seek to start of rulefile
        fseek(fh, 0, SEEK_SET);

        // read one line from rule file
        while (fgets(fbuffer, sizeof(fbuffer), fh) != NULL) {
            // strip \n and \r from line
            fbuffer[strcspn(fbuffer, "\r\n")] = 0;

            // if requested command equals rulefile line
            if (strlen(fbuffer) == strlen(sbuffer) && strcmp(fbuffer, sbuffer) == 0) {

                // make sure the command e.g. file exists
                // and is actually executable
                if (access(fbuffer, X_OK) == 0) {
                    // fork and execute fbuffer with /bin/sh -c
                    // system blocks till finished
                    system(fbuffer);
                    break;
                } else {
                    // not executable or does not exist
                    break;
                }
            }
        }
    }

    // close the rulefile
    fclose(fh);

    // indicate success
    return(0);
}

An initial attempt to overflow by perl -e 'print "\0"x50000;' did not reveal anything apparent. I've also tested that it runs as it should.

Example run

[ole@playground ~]$ ./strictshell
$ foo
$ \0
$ bar
$ /usr/bin/uptime
 15:14:44 up 157 days,  1:04, 23 users,  load average: 0.13, 0.15, 0.10
$ exit


texts: Is there a better way to retrieve variables from class method

texts:
Currently my code works but I wanted to know if I'm going about this the right way. I want to be able to individually call variables from method 'data_by_name' in 'otherfile.py' . At the moment I import 'otherfile.py' and put the elements into a list within 'main.py' and use tuple unpacking to give each element a variable name.

Could I go about this a better way?

otherfile.py

import requests
import json

API_KEY = "XXX"
PROJECT_TOKEN = "XXX"
RUN_TOKEN = "XXX"

class Data:
    def __init__(self, api_key, project_token):
        self.api_key = api_key
        self.project_token = project_token
        self.params = {"api_key":api_key}
        self.get_data()

    def get_data(self):
        r = requests.get('https://www.parsehub.com/api/v2/projects/PROJECT_TOKEN/last_ready_run/data', params={"api_key": API_KEY})
        self.data = json.loads(r.text)

    def data_by_name(self,country):

        data = self.data['country']
        for content in data:
            if content['Cname'].lower() == country.lower():
                print(content)
                name = content['Cname']
                pop = content['population']
                popRank = content['popRank']
                growth = content['growthRate']
                per = content['worldPer']
                area = content['area']
                capital = content['capital']
                region = content['region']
                gpd = content['gpd']
        return(name,pop,popRank,growth,per,area,capital,region,gpd)

if __name__ == '__main__':
    data = Data(API_KEY,PROJECT_TOKEN)
    data.data_by_name('Russia')

main.py

from ParsehubCode import Data,API_KEY,PROJECT_TOKEN

country = Data(API_KEY,PROJECT_TOKEN)
test = country.data_by_name("china")
list1 = []
for element in test:
    list1.append(element)
for x in list1:
    A,B,C,D,E,F,G,H,I = list1
print(A,B,C)

country.json

{
 "country": [
  {
   "Cname": "China",
   "name": "China Population 2020 (Live)",
   "population": "1,438,719,354",
   "popRank": "1",
   "growthRate": "0.39%",
   "worldPer": "18.47%",
   "area": "9,706,961 km²",
   "capital": "Beijing",
   "region": "Asia",
   "gpd": "$10,746.78"
  }
{


texts:
I'm on my way of understanding basic data structures and sorting algorithms through implementing them in c++. Post is followed of my implementation of Vector. I decided to weld the heap behaviour right into Vector class, although I'm not sure if it's a good solution/practice.
The heapSort method is not yet implemented. I'm not figuring out how I can build it based on already existing methods.
As at my office heavily criticising is an accepted practice, I'm asking for
rather hard, destructive critics and review.

#include "Vector.hpp"

Vector::Vector(int size):size(size) {
    array = new int[size]();
}

Vector::Vector(int vector[], int sizeT) {
    this->array = new int[sizeT]();
    this->size = sizeT;
    for(int i = 0; i < sizeT; ++i) {
        this->array[i] = vector[i];
    }
}

Vector::Vector(Vector* v1) {
    this->array = v1->array;
    this->size = v1->size;
}

Vector::~Vector() {
    delete[] array;
}

int Vector::length() {
    return this->size;
}

int Vector::getAt(int idx) {
    if(idx >= this->size) {
        throw "out of range";
    }
    return this->array[idx];
}

int& Vector::operator[](const int index){
    if(index >= this->size) {
        throw "out of range";
    }

    return this->array[index];
}

void Vector::deteleAt(int idx) {
    for(int i = idx; i < this->length() - 1; ++i) {
        this->array[i] = this->array[i+1];
    }
    --this->size;
}

//HEAP--------PRIORITY QUEUE
int Vector::parent(int idx) {
    if(idx >= 0 && idx <= 2) {
        return this->array[0];
    }

    return this->array[idx/2];
}

bool Vector::hasLeftChild(int idx) {
    return this->leftChild(idx) < this->size;
}

bool Vector::hasRightChild(int idx) {
    return this->rightChild(idx) < this->size;
}

void Vector::buildMaxHeap() {
    for(int i = this->size / 2; i >= 0; i--) {
        this->maxHeapify(i);
    }
}

void Vector::maxHeapify(int idx) {
    if(!this->hasRightChild(idx) && !this->hasLeftChild(idx)) {
        return;
    }

    int l = this->leftChild(idx), r = this->rightChild(idx);
    int largest = idx;

    if(l < this->size && this->array[l] > this->array[idx]) {
        largest = l;
    }

    if(r < this->size && this->array[r] > this->array[largest]) {
        largest = r;
    }

    if(largest != idx) {
        this->swap(idx, largest);
        this->maxHeapify(largest);
    }
}

void Vector::heapSort() {
    for(int i = this->heapSize; i >= 1; i--) {
        this->swap(0, i);
        this->heapSize--;
        this->maxHeapify(0);
    }
}

void Vector::swap(int firstIdx, int secondIdx) {
    int rotator = this->array[firstIdx];
    this->array[firstIdx] = this->array[secondIdx];
    this->array[secondIdx] = rotator;
}

int Vector::leftChild(int idx) {
    idx = idx * 2;
    return idx;
}

int Vector::rightChild(int idx) {
    idx = (idx * 2) + 1;

    return idx;
}

void Vector::print(){
    for(int i = 0; i < this->size; ++i) {
        std::cout<<this->array[i]<<" ";
    }
    std::cout<<"\n";
}

int Vector::popFront(){
    int firstElem = this->array[0];
    this->deteleAt(0);
    return firstElem;
}


texts:
I am wondering if this code will work in 10.1.

This video at 1:02 says not to create mxd based services. I think that just means not using IMapServerObjects3, but seems like IMapDocument should be OK.

#region IServerObjectExtension Members

private IPageLayout m_Layout = null;
public void Init(IServerObjectHelper pSOH)
{
    serverObjectHelper = pSOH;
    // open an mxd and grab the layout
    IMapDocument mapDoc = new MapDocumentClass();
    mapDoc.Open(@"\\sharedFolder\Mymapdocument.mxd");
    m_Layout = mapDoc.PageLayout;
    mapDoc.Close();
}

public void Shutdown()
{
    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(m_Layout);
}

#endregion

Edit: Here's a related question on GIS.stackexchange.


texts:
Tested on my TI-84 Plus CE.

Variables:

F: Stores the file listing's ID
N: Stores the current file's ID
I, J, L: Temporary variables
Str1: Used for input and output
Str2, Str3: Temporary variables
Str0: Used for storing the actual data
⌊DATA: Stores the start of the files

The DATA- programs are for storing files by ID#, the FILES- programs are used for storing files by name.

DATAADD (creates a new file, returns the file's ID)

augment(⌊DATA,{⌊DATA(dim(⌊DATA))})→⌊DATA
dim(⌊DATA)-1→N

DATAGET (gets the contents of the current file)

If ⌊DATA(N+1)-⌊DATA(N)
Then
sub(Str0,⌊DATA(N)+1,⌊DATA(N+1)-⌊DATA(N))→Str1
Else
" "→Str1
End
Str1

DATAINI (initializes/resets the files)

" "→Str0
{1}→⌊DATA

DATASET (sets the contents of a file)

length(Str1)-⌊DATA(N+1)+⌊DATA(N)→L
If length(Str0)-⌊DATA(N+1)>0
Then
sub(Str0,1,⌊DATA(N))+Str1+sub(Str0,⌊DATA(N+1),length(Str0)-⌊DATA(N+1))→Str0
Else
sub(Str0,1,⌊DATA(N))+Str1→Str0
End
For(I,N+1,dim(⌊DATA))
⌊DATA(I)+L→⌊DATA(I)
End

DATATEST (test program for the DATA- programs)

prgmDATAINI
prgmDATAADD
prgmDATAGET
Disp Str1
"ABC"→Str1
prgmDATASET
prgmDATAGET
Disp Str1
prgmDATAADD
prgmDATAGET
Disp Str1
1→N
prgmDATAGET
Disp Str1
2→N
"DEF"→Str1
prgmDATASET
prgmDATAGET
Disp Str1
1→N
prgmDATAGET
Disp Str1
"12"→Str1
prgmDATASET
prgmDATAGET
Disp Str1

FILES (semi-GUI file manager interface)

Lbl L
Menu("Choose an action","List files",LI,"Create file",CR,"Open file",OP,"View file",VI,"Edit file",ED,"View home screen",VH,"Advanced features...",AD,"Exit",E)
Lbl AD
Menu("Advanced features","Initialize/reset files",RF,"Initialize/reset all data",RD,"View current file ID",ID,"Back",L)
Lbl LI
prgmFILESLST
Pause Str1
Goto L
Lbl CR
Input "FILENAME: ",Str1
prgmFILESADD
Goto L
Lbl OP
Input "FILENAME: ",Str1
prgmFILESID
Goto L
Lbl VI
prgmDATAGET
Pause Str1
Goto L
Lbl ED
Input "NEW CONTENTS: ",Str1
prgmDATASET
Goto L
Lbl VH
Pause ""
Goto L
Lbl RF
prgmFILESINI
Goto L
Lbl RD
prgmDATAINI
Goto L
Lbl ID
Disp N
Goto L
Lbl E

FILESADD (creates a new file)

Str1→Str2
prgmDATAADD
N→I
F→N
prgmDATAGET
Str1+" "+Str2+" "+toString(I)→Str1
prgmDATASET

FILESID (gets the file's ID)

Str1→Str2
F→N
prgmDATAGET
Str1→Str3
3→I
While I and Str1≠Str2
Str3→Str1
I→J
inString(Str1," ",I)+1→I
If I
Then
sub(Str1,J,I-J)→Str1
Else
sub(Str1,J,length(Str1)-J)→Str1
End
End
inString(Str3," ",I)+1→I
inString(Str3," ",I)→J
If J
Then
sub(Str3,I,J-I)→Str1
Else
sub(Str3,I,length(Str3)-I+1)→Str1
End
expr(Str1)→N

FILESINI (initializes the file index)

prgmDATAADD
N→F

FILESLST (lists the files' names, space separated)

F→N
prgmDATAGET
" "→Str2
2→I
While I
inString(Str1," ",I+1)→J
If not(J)
Goto E
Str2+sub(Str1,I,J-I)→Str2
inString(Str1," ",J+1)→I
End
Lbl E
If length(Str2)<3
Then
""→Str1
Else
sub(Str2,3,length(Str2)-2)→Str1
End

FILESTST (test program for the FILE- programs)

prgmFILESINI
prgmFILESLST
Disp Str1
"ABC"→Str1
prgmFILESADD
prgmFILESLST
Disp Str1
"123"→Str1
prgmFILESADD
prgmFILESLST
Disp Str1


texts: Decorate instance method with (arbitrary) meta data in python

texts:
Requirements

What I need: attach meta information to methods, such that

it is 'easy' to retrieve all such methods for a given class instance
methods can still be called 'in a normal way', e.g. obj.method()
meta-data is accessible from the decorated method, e.g. obj.method.data
IDEs (PyCharm in particular) do not produce any warnings or errors (and, if possible, IDE support, e.g. auto-completion, should be able to handle the annotation)

Additionally, I would like the code to be readable/intuitive (not necessarily the super classes, though), generally robust and 'bug-free'. I accept the limitation that my decorators need to be the most 'outer' decorator for the automatic collection to take place.

From my point of view, overcoming function/method transformation while still exposing an arbitrary object type (not a function type -- thinking of this, maybe subclassing a FunctionType might be another idea?) is the hardest challenge.

What do you think of the following three solutions? Is there something I did miss?

Code

class MethodDecoratorWithIfInCall(object):
    def __init__(self):
        self._func = None

    def __call__(self, *args, **kwargs):
        if self._func is None:
            assert len(args) == 1 and len(kwargs) == 0
            self._func = args[0]
            return self
        else:
            return self._func(*args, **kwargs)

    def __get__(self, *args, **kwargs):
        # update func reference to method object
        self._func = self._func.__get__(*args, **kwargs)
        return self

class MacroWithIfInCall(MethodDecoratorWithIfInCall):
    def __init__(self, name):
        super(MacroWithIfInCall, self).__init__()
        self.name = name

class MethodDecoratorWithExplicitDecorate(object):
    def __init__(self, *args, **kwargs):
        # wildcard parameters to satisfy PyCharm
        self._func = None

    def __call__(self, *args, **kwargs):
        return self._func(*args, **kwargs)

    def __get__(self, *args, **kwargs):
        # update func reference to method object
        self._func = self._func.__get__(*args, **kwargs)
        return self

    def _decorate(self):
        def _set_func(func):
            self._func = func
            return self
        return _set_func

    @classmethod
    def decorate(cls, *args, **kwargs):
        obj = cls(*args, **kwargs)
        return obj._decorate()

class MacroWithExplicitDecorate(MethodDecoratorWithExplicitDecorate):
    def __init__(self, name):
        super(MacroWithExplicitDecorate, self).__init__()
        self.name = name

class MacroWithoutSuperclass(object):
    def __init__(self, func, name):
        self.func = func
        self.name = name

    def __get__(self, *args, **kwargs):
        # update func reference to method object
        self.func = self.func.__get__(*args, **kwargs)
        return self

    def __call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)

    @staticmethod
    def decorate(name):
        return lambda func: MacroWithoutSuperclass(func, name)

class Shell:
    def __init__(self):
        macros = [macro for macro in map(self.__getattribute__, dir(self))
                  if isinstance(macro, (MacroWithIfInCall, MacroWithExplicitDecorate, MacroWithoutSuperclass))]

        for macro in macros:
            print(macro.name, macro())

    @MacroWithIfInCall(name="macro-with-if-in-call")
    def macro_add_1(self):
        return "called"

    @MacroWithExplicitDecorate.decorate(name="macro-with-explicit-decorate")
    def macro_add_2(self):
        return "called"

    @MacroWithoutSuperclass.decorate(name="macro-without-superclass")
    def macro_add_3(self):
        return "called"

if __name__ == '__main__':
    shell = Shell()

Output

macro-with-if-in-call called
macro-with-explicit-decorate called
macro-without-superclass called


texts: Simplifying if statement in a StateT monad transformer

texts:
While learning the basics of Haskell I decided to challenge myself with seemingly simple task - write a program that would push the user input into a stack if it's not an empty string or pop the value from the stack and print it to user if the input is an empty string. the program would exit if it tries to pop from an empty stack.

Realising that I would have to combine functionality of input/output, stateful computations and failure handling got me looking into Monad Transformers. So here is the code that I ended up with:

import Control.Monad
import Control.Monad.Trans.Class
import Control.Monad.Trans.State
import Control.Monad.Trans.Maybe
import Control.Monad.IO.Class

type Stack = [String]

pop :: Stack -> (Maybe String, Stack)
pop (x:xs)  = (Just x, xs)
pop []      = (Nothing, [])

push :: String -> Stack -> ((), Stack)
push s xs = ((), s:xs)

mainLoop :: StateT Stack (MaybeT IO) ()
mainLoop = do
    input <- liftIO getLine
    if null input
         then do
             Just x <- state pop
             liftIO . putStrLn $ x
         else state $ push input
    mainLoop

main = runMaybeT (runStateT mainLoop [])

It works exactly how I wanted, but can someone please look into how I can simplify this code? Or if it's even possible to simplify it? Especially the then branch.


texts: Refactoring code to throw a single exception per function

texts:
One of my functions must throws 2 exceptions, but I understand 1 exception per function is preferred (at least according to my client's Sonar ruleset).  Can you suggest how I might refactor the following code to enable 1 or no exceptions on these functions?

Worth noting is that I have a global exception handler which wraps this class, so any thrown exception will be caught there.

public ResponseEntity postFooRequest(
        @RequestBody String body,
        @RequestParam(value = "action") String action,
        @RequestParam(value = "fooNumber") String fooNumber) throws UnsupportedEncodingException, InterruptedException {
    String sanitizedBody = inputSanitizer.sanitizeBody(body);
    FooRequest fooRequest = new FooRequest(sanitizedBody, action, fooNumber);
    return processFooRequest(fooRequest);
}

private ResponseEntity processFooRequest(FooRequest fooRequest) throws InterruptedException, UnsupportedEncodingException {
    FooRequest fooRequestResult = fooRequestDelegate.processFooRequest(fooRequest);
    return new ResponseEntity<>(decodeResponse(fooRequestResult.getBody()), httpHeaders, HttpStatus.OK);
}

private String decodeResponse(String body) throws UnsupportedEncodingException {
    return java.net.URLDecoder.decode(body, "UTF-8");
}


texts:
Since I did not get a satisfactory answer here (and I really needed to get it going on this weekend), I decided to implement my own Fisher–Yates shuffle, porting the code I found in other SO posts. I know my programming technique is far from optimal, so I decided to post this here.

What do you think? Can it be improved?

public static JSONArray shuffleJsonArray (JSONArray array) throws JSONException {
    // Implementing Fisher–Yates shuffle
        Random rnd = new Random();
        for (int i = array.length() - 1; i >= 0; i--)
        {
          int j = rnd.nextInt(i + 1);
          // Simple swap
          Object object = array.get(j);
          array.put(j, array.get(i));
          array.put(i, object);
        }
    return array;
}


texts:
I've written a small app using the kivy framework, which aims at reviewing your times tables. My major concern is about making this app easier to improve in the future. That is, how to organize the code to make it more clearer (by adding a User class that would store the data associated to the user, for instance). Since the code pretty straightforward, I've not added documentation to it.

The Python code:

# -*- coding: utf-8 -*-
from numpy.random import randint

import kivy
kivy.require('1.9.1-dev')
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.properties import StringProperty

Window.size = (200, 100)

class MyWidget(Widget):

    help_message = StringProperty()
    question = StringProperty()
    feedback = StringProperty()

    def __init__(self):
        super(MyWidget, self).__init__()
        self.help_message = "Your answer"
        self.question = ""
        self.answer = 0
        self.points = 0
        self.attempts = 1e-10
        self.feedback = ""
        self.set_question()

    def set_question(self):
        a, b = randint(1, 11, 2)
        self.question = "{} x {} =".format(a, b)
        self.answer = a * b

    def check_answer(self, user_input):
        try:
            if int(user_input) == self.answer:
                self.points += 1
                self.feedback = "right"
            else:
                self.feedback = "{} {}".format(self.question, self.answer)
            self.set_question()
            self.attempts += 1
        except:
            self.feedback = "invalid answer"

    def set_score(self):
        score = self.points / self.attempts * 100
        self.feedback = "{:3.0f}% of right answers".format(score)

class MyApp(App):
    def build(self):
        return MyWidget()

if __name__ == '__main__':
    MyApp().run()

The .kv one:

<MyWidget>:

    canvas:
        Color:
            rgba: .93, .93, .93, 1.
        Rectangle:
            pos: self.pos
            size: self.size

    TextInput:
        size: 130, 30
        pos: 70, 30
        text: root.help_message
        background: 1., 1., 1., 1.
        font_size: 14
        multiline: False
        on_text_validate: root.check_answer(self.text); self.text = ""

    Label:
        size: 200, 30
        pos: 0, 60
        text: root.feedback
        color: .0, .0, .0, 1.
        font_size: 14

    Label:
        size: 70, 30
        pos: 0, 30
        text: root.question
        color: .0, .0, .0, 1.
        font_size: 14

    Button:
        size: 200, 30
        pos: 0, 0
        text: "Stop"
        color: .0, .0, .0, 1.
        font_size: 14
        on_release: root.set_score()

[EDIT] Mentioned code reviewer here.


texts:
I was trying to solve Tennis-Refactoring-Kata. This seems quite hard at startup but, through use os OOP it can be deeply refactoring using just a single if.

My first understanding was about the fact that TennisGame (the main class) has a Score. Or at least should have one.

Furthermore score possibilities are just twenty (Love-All, Fifteen-All and so on...) and each one leads further Scores based on who is the last player who scores a point (e.g.: Love-All leads to Fifteen-Love if last point has been scored by first player, Love-Fifteen otherwise). From this observation I wrote 20 classes like this:

public class LoveAll implements IScore {

    public IScore Player1Scored() {
        return new FifteenLove();
    }

    public IScore Player2Scored() {
        return new LoveFifteen();
    }

    public String Label() {
        return "Love-All";
    }
}

This should seems a loss of time but this is not bad as it seems since each class is simple and concise. This give me the possibilities to write a TennisGame4 like this:

public class TennisGame4 implements TennisGame {
    private IScore score = null; // Composition here - TennisGame has a Score
    private String player1Name;
    private String player2Name;

    public TennisGame4(String player1Name, String player2Name) {
        this.player1Name = player1Name;
        this.player2Name = player2Name;
        score = new LoveAll();
    }

    public void wonPoint(String playerName) {
        if (playerName.equals("player1"))
            score = score.Player1Scored();
        else
            score = score.Player2Scored();
    }

    public String getScore() {
        return score.Label();
    }
}

Just a single if to distinguish who is the last player who score a point.
What do you think about this solution? Does this solution respect the kata constraint?

Consider that:

Code surely can be enhanced (Player should be an object too);
To stay in the Kata I have do everything in 90 minutes or so;


texts: Singly linked list implementation in Scala

texts:
What could be a better implementation, following the Scala way of doing it?

class Node(itemValue: Object, nextItem:Node){
  val value = itemValue
  val next = nextItem
}

class MyList() {
  var start: Node =null

  def add(value:Object){
    val cache = start
    this.start = new Node(value,cache)
  }

  def print:Unit  = {
    var n = start;
    println(n.value)
    while(n != null){
      println(n.value)
      n = n.next;
    }
  }

}


texts:
I've been tinkering with python for quite a while but have never taken on a challenge like this - I'm trying to write a collectd plugin to scrape metrics from prometheus endpoints.
My goals are to make it as stable as possible - i'd like to put this into production when i am happy with it. There are a couple of items that i haven't figured out yet (summary and histogram familytypes), so if anyone has any suggestions about how to do that, i would be very appreciative. As well as this, i am trying to be a pythonic as possible, but i am 100% self taught, so my code is probably all over the place.
I'm interested in any form of feedback, even if it means i need to go learn/un-learm some more stuff :)
import platform
import collectd
from prometheus_client.parser import text_string_to_metric_families
import requests

def config_func(config):
    endpoint_set = False
    endpoint_set = False
    interval = 60

    for node in config.children:
        key = node.key.lower()
        val = node.values[0]

        if key.lower() == 'endpoint':
            endpoint = val
            endpoint_set = True
        elif key.lower() == 'endpoint_name':
            endpoint_name = val
            endpoint_name_set = True
        elif key.lower() == 'interval':
            interval = val
        else:
            collectd.info(f'prometheus_scraper: Unknown config key "{key}"')

    if endpoint_set and endpoint_name_set:
        collectd.info(f'prometheus_scraper: python version {platform.python_version()}')
        collectd.info(f'prometheus_scraper: Using {endpoint} for {endpoint_name} on ')

        global ENDPOINT
        ENDPOINT = endpoint
        global ENDPOINT_NAME
        ENDPOINT_NAME = endpoint_name
        global INTERVAL
        INTERVAL = interval

def parse_func(metrics):

    for family in text_string_to_metric_families(metrics):
        for sample in family.samples:

            if family.type == 'summary':
                #print(family.type)
                pass
            elif family.type == 'histogram':
                #print(family.type)
                pass
            else:
                val = collectd.Values()
                val.plugin = ENDPOINT_NAME
                val.interval = INTERVAL
                val.type = family.type

                if len(sample.labels) > 0:
                    joined = ''.join(key + '_' + str(val) for key, val in sample.labels.items())
                    val.type_instance = sample.name + '.' + joined
                else:
                    val.type_instance = sample.name

                #print(f'type_instance: {val.type_instance}')

                val.values = [sample.value]
                val.dispatch()

def read_func():

    try:
        metrics = requests.get(url=ENDPOINT)
        metrics.raise_for_status()
        parse_func(metrics.text)
    except requests.exceptions.RequestException as e:
        collectd.error(f'failed to retrive metrics: {e}')

collectd.register_config(config_func)
collectd.register_read(read_func, INTERVAL)

https://github.com/mark-vandenbos/collectd_prometheus_scraper/


texts: Find words from dictionary method. Performance improvements

texts:
I've implemented a method to solve the following problem:

  Given a dictionary and a text string, find all words from the
  dictionary that are present in the text. One important point is
  that if the string is in double quotes, I should treat it a "single"
  value. If no matches found, the method should return 0.

So for this input:

const text = `Hi. I am a developer. A "Hello world" program was my first code.`;
const dictionary = "hi developer world";

I should get this:

hi
developer
hello
world

This is my current solution:

const fn = (text, dictionary) => {
    const knownWords = dictionary.toLowerCase().split(' ');
    const words = text.toLowerCase().match(/\w+|"[^"]+"/gi);

    const result = words.reduce((acc, word) => {
        if (word[0] == '"') {
            const wordsNoQuotes = word.replace(/"/g, "").split(' ');
            const shouldInclude = wordsNoQuotes.find(word => knownWords.includes(word));
            if (shouldInclude) {
                return acc.concat(wordsNoQuotes);
            }
        } else if (knownWords.includes(word)) {
            acc.push(word)
        }

        return acc;
    }, []);

    return result.length === 0 ? 0 : [...new Set(result)].join('\n');
}

It works ok, but I would like to get some performance related improvements. I am happy to change the code (i.e using indexOf over includes) and so on. Any suggestions are welcome! Thanks.


texts: Strongly connected component algorithm in Python 2.7

texts:
This is my implementation of Kosaraju's algorithm for detecting strongly connected components, post here for advice. Some special areas looking for advice,

Not sure if my current implementation for adjacent table of graph is efficient?
Any better ideas to reverse the graph to make it more efficient?
I use preVisited and visited to track what nodes are already reached by a strongly connected components, it there a better way?
Any other areas my code could improve, especially for performnace.

from collections import defaultdict
visitTimeCounter = 0

class GraphNode:
    def __init__(self, name):
        self.name=name
        self.connections = [] # list of GraphNode, directional
        self.visitTime = -1

    def DFS(self, visited):
        global visitTimeCounter
        if self.name in visited:
            return
        visited.append(self.name)

        for node in self.connections:
            if node.name in visited:
                pass
            else:
                node.DFS(visited)
        visitTimeCounter += 1
        self.visitTime = visitTimeCounter

if __name__ == "__main__":
    nodeA = GraphNode('A')
    nodeB = GraphNode('B')
    nodeC = GraphNode('C')
    nodeD = GraphNode('D')

    allNodes = [nodeA, nodeB, nodeC, nodeD]

    nodeA.connections.append(nodeB)
    nodeA.connections.append(nodeC)
    nodeB.connections.append(nodeA)
    nodeC.connections.append(nodeD)
    nodeD.connections.append(nodeC)

    visited = []

    for node in allNodes:
        if node.name not in visited:
            node.DFS(visited)

    for node in allNodes:
        print node.name, node.visitTime

    allNodesReverse=[]
    nodeIndex = defaultdict(GraphNode)
    # fork new nodes
    for node in allNodes:
        newNode=GraphNode(node.name)
        newNode.visitTime = node.visitTime
        allNodesReverse.append(newNode)
        nodeIndex[newNode.name]=newNode

    # build conections
    for node in allNodes:
        for neighbour in node.connections:
            nodeIndex[neighbour.name].connections.append(nodeIndex[node.name])

    # verify reverse connections
    for i in allNodesReverse:
        for j in i.connections:
            print i.name, '=>', j.name

    allNodesReverseOrdered = sorted(allNodesReverse, key=lambda x:x.visitTime, reverse=True)
    visited = []
    preVisited = []
    SCResults = []
    for node in allNodesReverseOrdered:
        if node.name not in visited:
            node.DFS(visited)
            # append to new SC
            sc = set()
            for node in allNodesReverseOrdered:
                if node.name in visited and not node.name in preVisited:
                    sc.add(node.name)
            for item in visited:
                preVisited.append(item)
            SCResults.append(sc)

    for sc in SCResults:
        print 'strongly connected component: '
        for i in sc:
            print i


texts: Why would I want to always have to explicitly call a "base" method if I just want to use base functionality?

texts:
I recently worked with an architect who structured his base class like this:

public abstract class Base<T>
{
    public abstract T Get(int id);

    internal T InternalGet(int id, IRepository<T> repository)
    {
       // Do more magic
       return repository.Get(id);
    }
}

And then in the derived class, if you just want to use the base functionality, you'd have to..

public class Derived : Base<T>
{
    private readonly IProductRepository _repository; // Implements IRepository<Product>

    // Ctor with dependency injection, this is good stuff!
    public DerivedClass(IProductRepository repository)
    {
       _repository = repository;
    }

    public override Product Get(int id)
    {
       // ... explicitly call base functionality - NOT a call to base though!
       return InternalGet(id, _repository);
    }
}

Why not just pass the repository to the base class, and override when you need to?

public abstract class Base<T>
{
   private readonly IRepository<T> _repository;

   protected Base<T>(IRepository<T> repository)
   {
      _repository = repository;
   }

   public virtual T Get(int id)
   {
      // Do magic
      return _repository.Get(id);
   }
}

And then in the derived class, if you don't want to use the base method, just override it.

public class Derived: Base<Product>
{
   private readonly IProductRepository _repo;

   public Derived(IProductRepository repo) : base(repo)
   {
      _repo = repo;
   }

   public override Get(int id)
   {
      if(! customerIsBeingNice)
         throw new GoAwayException();
      return _repo.Get(id);
   }
}

I think the architect was trying to avoid the call super code smell, but since we are not requiring a call to super - in fact it really should never happen, because if you override the method, you are supposed to implement the flow you want, whereas if you call super, you can't hook into the flow that easily.

Which of these is better/worse, and why? Any alternatives?


texts: Binary Search implementation: HackerRank - Climbing the Leaderboard

texts:
My code passes 11 out of 12 test cases. I was wondering where I can improve my code. NOTE: This code needs performance improvement, as it is working for most of the cases. To mu knowledge it would work for all the test cases where the size of arrays is smaller than 200.
Here is the question:

Alice is playing an arcade game and wants to climb to the top of the leaderboard and wants to track her ranking. The game uses Dense Ranking, so its leaderboard works like this:
The player with the highest score is ranked number 1 on the leaderboard.
Players who have equal scores receive the same ranking number, and the next player(s) receive the immediately following ranking number.
For example, the four players on the leaderboard have high scores of 100, 90, 90, and 80. Those players will have ranks 1, 2, 2, and 3, respectively. If Alice's scores are 70, 80 and 105, her rankings after each game are 4, 3 and 1.

And here is my code:
#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the climbingLeaderboard function below.
def binSearchMod(list1, value, start, end): #implemented for descending order
    mid = (start+end)//2
    #print('Looking for value: ', value, ' in ', start, end, mid , 'list :', list1)
    #conditions for element at start or end or mid
    if value==list1[start]:
        mid = start
    if value == list1[end]:
        mid = end
    if value == list1[mid]:
        return [True, mid]
    if end-start == 1: # if some element lies in between 2 numbers of array
        #print('Found between ', start, end)
        return [False, start]
    if value < list1[mid]:
        return binSearchMod(list1, value, mid, end)
    else:
        return binSearchMod(list1, value, start, mid)

def climbingLeaderboard(scores, alice): # O(log n), not really we have to go through all scores to determine their rank
    res=[]
    rank =1
    rankScores=[scores[0]]
    #ssign ranks to scores
    for score in range(1,len(scores)):
        if scores[score]!=scores[score-1]:
            rank+=1
            rankScores.append(scores[score])

    for ascore in alice:
        if ascore<scores[len(scores)-1]: # alice scores are smaller than all
            res.append(len(set(scores))+1)
        elif ascore > scores[0]: #alice score is greatest
            res.append(1)
        else: #alice score lies somewhere in between
            bsResult = binSearchMod(rankScores, ascore, 0 , len(rankScores)-1)
            #print(ascore, bsResult)
            if bsResult[0]:
                res.append(bsResult[1]+1)
            else:
                res.append(bsResult[1]+2)
    return res

I am guessing I'm trying to improve on test cases with length of arrays containing all scores and alice scores are > 200.


texts: Determining whether a string is transformable into another by repetitively increasing its prefixes alphabetically

texts:
Here's Alice and Strings, a programming challenge on hackerearth:

  Two strings \$A\$ and \$B\$ comprising of lower case English letters
  are compatible if they are equal or can be made equal by following
  this step any number of times:

  Select a prefix from the string \$A\$ (possibly empty), and increase the alphabetical value of all the characters in the prefix by the same
  valid amount. For example if the string is xyz and we select the
  prefix xy then we can convert it to yz by increasing the
  alphabetical value by 1. But if we select the prefix xyz then we
  cannot increase the alphabetical value.

  Your task is to determine if given strings \$A\$ and \$B\$ are
  compatible.

  Input format

  First line: String \$A\$

  Next line: String \$B\$

  Output format

  For each test case, print YES if string \$A\$ can be converted to
  string \$B\$, otherwise print NO.

  Constraints

  $$
  \DeclareMathOperator{\len}{len}
  1 \leq \len(A) \leq 1\,000\,000 \\
  1 \leq \len(B) \leq 1\,000\,000 \\
  $$

Can you please review my solution to it?  Please comment on any aspect to improve such as readability, comment usage, further improvements on speed/memory usage, etc.

/*
HackerEarth
https://www.hackerearth.com/practice/algorithms/string-algorithm/basics-of-string-manipulation/practice-problems/algorithm/aliceandstrings-9da62aa7/
*/

#include <iostream>

/*
Recusrsively checks if string A can be converted to B by incrementing the prefixes:

eg:
A = abaca B = cdbda
[step 1]bcbda (prefix abac incremented by 1)
[step 2]bc[b]da cd[b]da (don't take bcb as a prefix because b is already matched)
[step 3]cdbda -----> so convertible (incrementing prefix bc)
*/
bool transformable(std::string& A, std::string& B, int last_index)
{
    if (A.compare(0, last_index, B, 0, last_index) == 0)
    {
        return true;
    }
    else
    {
        if (A[last_index] == B[last_index])
        {
            return transformable(A, B, --last_index);
        }
        else
        {
            if (A[last_index] > B[last_index])
            {
                return false;
            }
            else
            {
                while(A[last_index] != B[last_index])
                {
                    for(int i = 0; i <= last_index; i++)
                    {
                        A[i] += ('b' - 'a');
                    }
                }

                return transformable(A, B, --last_index);
            }

        }

    }

}

int main()
{
    std::string A;
    std::string B;

    std::cin >> A >> B;

    if (A.length() != B.length())
    {
        std::cout << "NO" << std::endl;
        return 0;
    }

    if (transformable(A, B, A.length() - 1))
        std::cout << "YES" << std::endl;
    else
        std::cout << "NO" << std::endl;

    return 0;
}


texts:
I wrote a script for a timer. Is there any way to improve the code, with fewer number of lines?

JSBIN

var app = angular.module('app', []);
app.controller('main', function($scope, $interval) {

    $scope.timer = 0;
    var clickme = true,
        startfun;
    $scope.status = "Start";
    var foo = function() {
        $scope.timer += 1;
    };
    $scope.start = function() {
        if (clickme === true) {
            $scope.status = "Stop";
            clickme = false;
            startfun = $interval(foo, 1000);

        } else if (clickme === false) {
            clickme = true;
            $interval.cancel(startfun);
        }

    };
  $scope.reset=function(){

    $interval.cancel(startfun);
    $scope.timer = 0;
    $scope.status = "Start";
    clickme = true;
  };
});


texts: Number-guessing game in Python with a single level of abstraction

texts:
I've read about keeping functions to the same level of abstraction, and it seems to make sense in all the examples. However, when translating to non-contrived programming, I'm still very unsure of my decisions. I'm especially unsure of where it applies. I wrote this guessing game to try to work on it, but it ended up feeling really clunky and redundant. How far should I go out of my way to flatten code? I read loops should ideally only be one function call, but that seems extreme. Is that really standard practice? If so, how would I refactor my main without needing a bunch of globals or really long parameter lists?

from random import randrange

DEFAULT_LO   = 1
DEFAULT_HI   = 100
HOT_DISTANCE = 10

def main():
    answer    = randrange(DEFAULT_LO, DEFAULT_HI+1)
    tries     = 1
    lastGuess = 0
    guess     = 0
    wasHot    = False

    won = False
    isFirstTry = True
    while (not won):
        lastGuess = guess
        guess = promptGuess()

        if validGuess(guess):
            if guess != answer:
                newDistance = abs(answer-guess)
                oldDistance = abs(answer-lastGuess)
                displayResult(newDistance, oldDistance, isFirstTry)

            else:
                displayWin(tries)
                won = True

            tries += 1
            isFirstTry = False

def promptGuess(lo=DEFAULT_LO, hi=DEFAULT_HI):
    guess = input('Enter a number ({}-{}): '.format(lo, hi))
    guess = int(guess)
    return guess

def validGuess(num, lo=DEFAULT_LO, hi=DEFAULT_HI):
    return (num >= lo and num <= hi)

def displayResult(newDistance, oldDistance, firstGuess):
    wasHot = (oldDistance <= HOT_DISTANCE)
    isHot = (newDistance <= HOT_DISTANCE)

    if firstGuess:
        displayHotCold(newDistance)

    elif newDistance is oldDistance: # Can happen with new answer if equally
        print('Same temperature!')   # far on opposite side of answer

    elif isHot:
        displayHotHotterCooler(newDistance, oldDistance, wasHot)

    else:
        displayColdWarmerColder(newDistance, oldDistance, wasHot)

def displayHotCold(newDistance):
    if newDistance <= HOT_DISTANCE:
        print('HOT!')

    else:
        print('Cold')

def displayHotHotterCooler(newDistance, oldDistance, wasHot):
    if not wasHot:
        print('HOT!!')

    elif newDistance < oldDistance:
        print('HOTTER!!!')

    else:
        print('COOLER')

def displayColdWarmerColder(newDistance, oldDistance, wasHot):
    if wasHot:
        print('COLD')

    elif newDistance < oldDistance:
        print('Warmer!')

    else:
        print('Colder')

def displayWin(tries):
    if tries is 1:
        print('WOW!! You got it on your first try!')
    else:
        print('GOOD JOB! You got it in {} tries.'.format(tries))

main()


texts:
A few weeks ago, I developed a terminal game that increases your typing speed. The game is all about typing, providing difficulty levels from easy to hard. I feel like this terminal game won't become as popular as my others, so I need tips on how I could improve this code to make it shorter, easier to run, and more entertaining.
Here is the code developed by me, PYWPM:
import time
import random

logo = '''
  _____    __          _______  __  __
 |  __ \   \ \        / /  __ \|  \/  |
 | |__) |   \ \  /\  / /| |__) | \  / |
 |  ___/ | | \ \/  \/ / |  ___/| |\/| |
 | |   | |_| |\  /\  /  | |    | |  | |
 |_|    \__, | \/  \/   |_|    |_|  |_|
         __/ |
        |___/
'''
print(logo)
print(" ")
difficulty = input("Enter difficulty level (easy/hard): ")
if difficulty == "easy":
  openPlz = open('easywordbank.txt','r')
  readPlz = openPlz.read()
  wordBank = readPlz.split()
elif difficulty == "hard":
  openPlz = open('hardwordbank.txt','r')
  readPlz = openPlz.read()
  wordBank = readPlz.split()

open2 = open('highscore.txt','r+')
open2lst = open2.readlines()

stat = True
strike = 0
score = 0

def gameMain(wordBank):
    #Primary game loop. Returns a lst:
    #lst[0] = added points, lst[1] = added strikes
    lst = [0,0]
    start = time.time()
    wordQuiz = wordBank[random.randint(0,(len(wordBank)-1))]
    wordType = input('Enter the word, '+ wordQuiz + ' : ')
    if wordType == wordQuiz and time.time()-start < 3:
        lst[0] += 1
    elif time.time()-start >= 3:
        print('STRIKE! Too Slow! ')
        lst[1] += 1
    else:
        print('STRIKE! Watch your spelling. Be careful with strikes!')
        lst[1] += 1
    return lst

def highScore(name,score,highScoreLst,zFile):
    for line in highScoreLst:
        if score >= int(line[-3:-1]):
            highScoreLst.insert(highScoreLst.index(line),name+'-'+str(score)+'\n')
            highScoreLst.pop()
            zFile.seek(0,0)
            zFile.writelines(highScoreLst)
            break

def rsg():
    print('Ready?')
    time.sleep(1)
    print('Set?')
    time.sleep(1)
    print('Go!')
    time.sleep(1)

name = input('Enter a username for this session: ')
print("Type the word then press enter in under 3 seconds!")
time.sleep(2)
rsg()

#MainState

while stat == True:
    lst = gameMain(wordBank)
    score += lst[0]
    strike += lst[1]
    if strike == 3:
        time.sleep(.5)
        print('Game Over! The game has ended..!\n')
        time.sleep(2)
        print('Your Typing & Accuracy Score: ' + str(score))
        highScore(name,score,open2lst,open2)
        time.sleep(2)
        break
print('\nHighscores for PyWPM:')
time.sleep(2)
for line in open2lst:
    print(line, end='')
    time.sleep(1.5)
time.sleep(5)

openPlz.close()
open2.close()

Yes, this game includes a word bank that randomizes words.
The high scores aren't global.

How could I make this better?


texts:
Please see here for the general description.
Exercise 3: histogram :: [Integer] -> String
takes as input a list of Integers between 0 and 9 (inclusive),
and outputs a vertical histogram showing how many of each number
were in the input list.
histogram :: [Integer] -> String
histogram xs = let
  (a,m) = getCountOfElements xs
  unpadded = getStrings a
  padded = pad m unpadded
  transposed = transp ([], padded)
  in mkOutput transposed

mkOutput :: [String] -> String
mkOutput xss = let nums = "0123456789\n"
                    sep = "==========\n"
                    t = foldl (\a b -> b++"\n"++a) "" xss
                in t ++ sep ++ nums

pad :: Integer -> [String] -> [String]
pad _ [] = []
pad n (xs:xss) = (xs ++ (replicate (fromInteger n - length xs) ' ')) : (pad n xss)

getCountOfElements :: [Integer] -> ([Integer],Integer)
getCountOfElements ys =
  let arr = foldr (\e acc -> count e acc) (replicate 10 0) ys
        where
          count :: Integer -> [Integer] -> [Integer]
          count n xs = let idx = fromInteger n
                       in (take idx xs) ++ [(xs!!idx + 1)] ++ (drop (idx+1) xs)
      maxElt = maximum arr
  in (arr, maxElt)

getStrings :: [Integer] -> [String]
getStrings = map (\x -> replicate (fromInteger x) '*')

-- good, descriptive name is lacking...
f :: [[a]] -> ([a], [[a]])
f xss = foldr h ([],[]) xss where
  h [] (acc1, acc2) = (acc1, [])
  h (x:xs) (acc1, acc2) = (x:acc1, xs:acc2)

transp :: ([[a]],[[a]]) -> [[a]]
transp (xs:xss, [] ) = reverse xss
transp (xss, yss) = let (r, l) = f yss
               in transp ([r] ++ xss, l)


texts: Custom hook to have a featureList OBJ inside a useMemo()

texts:
In my React app, I had to build a system to check access based on roles and features.
To make code more efficient I should move the function which makes a list of an featureList OBJ of features inside a custom hook, to avoid in this way repeating of the code or redundant scripts.
The function where I have the fetureList I have to move
function doCheck(access, requirements, features = []) {
  const roles = access.roles || [];
  const actions = access.actions || [];

  const featureList = Object.entries(features)
    .filter(e => e[1])
    .map(e => e[0]);

  if (requirements.roles) {
    if (!requirements.roles.find(role => roles.includes(role))) {
      return false;
    }
  }

  if (!isEmpty(requirements.features)) {
    if (!requirements.features.find(feature => featureList.includes(feature))) {
      return false;
    }
  }

  if (requirements.actions) {
    if (!requirements.actions.find(action => actions.includes(action))) {
      return false;
    }
  }

  if (
    requirements.customCheck &&
    !requirements.customCheck(access, requirements.context)
  ) {
    return false;
  }

  return true;
}

From above the code I need to move is
const featureList = Object.entries(features)
        .filter(e => e[1])
        .map(e => e[0]);

And I need to move it inside this hook
function useFeatures(props) {
  const { data, loading } = useQuery(featureOptionsQuery, {
    variables: { studyId: props },
    skip: !Boolean(props),
  });

  const features = useMemo(
    () => ({
      recruitmentPortal: data?.featureOptions?.recruitmentPortal,
      engagementPortal: data?.featureOptions?.engagementPortal,
      consenteesPortal: data?.featureOptions?.consenteesPortal,
      analyticsPortal: data?.featureOptions?.analyticsPortal,
    }),
    [data],
  );

  if (loading) {
    return null;
  }

  return features;
}

As I understood inside the use memo I need to make an obj and use it to return the feature list but I don't know the way of doing it.
I was wondering to do
const featuresObj = {OBJ} and then use this to do the featureList thing to return but I don't know how to do this with useMemo()
I'm new to React and hooks and having some difficulties doing this refactor thing as required.


texts:
This code is a slot machine simulator that uses elements of both HTML and JavaScript. Please pardon the lack of comments.

<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>www.loseloselose.com</title>

Lucky Number Slots

<svg width="550" height="250" viewBox="0 0 1600 500">

<rect x="0" y="10" width="500" height="500" fill="black" stroke="white" stroke-width="10">
</rect>

<rect x="550" y="10" width="500" height="500" fill="black" stroke="white" stroke-width="10">
</rect>

<rect x="1100" y="10" width="500" height="500" fill="black" stroke="white" stroke-width="10">
</rect>

<text x="100" y="415" font-family="courier" font-size="500" fill="white">

</text>

<text x="650" y="415" font-family="courier" font-size="500" fill="white">

</text>

<text x="1200" y="415" font-family="courier" font-size="500" fill="white">

</text>
</svg>

<form>

<input type="button" value="Click Here To Spin" onClick="Refresh()">

</form>

Add Credit

0


texts:
Started working through Project Euler this weekend.

Project Euler 22

  Using names.txt (right click and 'Save Link/Target As...'), a 46K text
  file containing over five-thousand first names, begin by sorting it
  into alphabetical order. Then working out the alphabetical value for
  each name, multiply this value by its alphabetical position in the
  list to obtain a name score.

  For example, when the list is sorted into alphabetical order, COLIN,
  which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the
  list. So, COLIN would obtain a score of 938 × 53 = 49714.

  What is the total of all the name scores in the file?

#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <set>
#include <numeric>
#include "PunctFacet.h"

using ThorsAnvil::Util::PunctFacet;

long scoreName(std::string const& name)
{
    return std::accumulate(std::begin(name), std::end(name), 0L,
                           [](long v1, char x){return v1 + x - 'A' + 1;});
}

int main()
{
    // Open a file that considers " and , as space and thus ignores them
    std::ifstream   data;
    data.imbue(std::locale(std::locale(), new PunctFacet(std::locale(), "\",")));
    data.open("euler/e22.data");

    // read all the names in a set (its sorted)
    std::set<std::string> names{std::istream_iterator<std::string>(data),
                                std::istream_iterator<std::string>()};

    // Calculate the result
    long    score   = 0;
    long    loop    = 1;
    for(auto name: names) {
        score += (loop * scoreName(name));
        ++loop;
    }
    std::cout << score << "\n";
}

PunctFacet.h

#ifndef THORSANVIL_UTIL_PUNCT_FACET_H
#define THORSANVIL_UTIL_PUNCT_FACET_H

#include <locale>
#include <string>
#include <sstream>

namespace ThorsAnvil
{
    namespace Util
    {

// This is my facet that will treat the characters in `extraSpace`
// as space characters and thus ignore them with formatted input
class PunctFacet: public std::ctype<char>
{
    public:
        typedef std::ctype<char>    base;
        typedef base::char_type     char_type;

        PunctFacet(std::locale const& l, std::string const& extraSpace)
            : base(table)
        {
            std::ctype<char> const&  defaultCType  = std::use_facet<std::ctype<char> >(l);

            // Copy the default value from the provided locale
            static  char data[256];
            for(int loop = 0;loop < 256;++loop) { data[loop] = loop;}
            defaultCType.is(data, data+256, table);

            // Modifications to default to include extra space types.
            for(auto space: extraSpace) {
                table[space]  |= base::space;
            }
        }
    private:
        base::mask  table[256];
};

    }
}

#endif

Results

> g++ -O3 -std=c++14 euler/e22.cpp
> time ./a.out
871198282

real    0m0.018s
user    0m0.009s
sys     0m0.007s


texts: Find the smallest triangular number with more than 500 factors

texts:
I wrote a program about triangular numbers, which are derived from the sum of natural numbers one after the other. For example, the third triangular number is equal to: 1 + 2 + 3 = 6.
I want to find divisors of triangular numbers. for example the third triangular number have 4 divisors which equal to : 1,2,3,6.
Some triangular number with their divisors:

1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28

I want to find the smallest triangular number which has more than 500 divisors.  This program works, but is too slow to find the 500th.  How can I optimize my program?
    def triangular(n):
        a= []
        for i in range (2,n):
            if n % i == 0 :
            a.append(i)
        if len(a) > 498:
            return True
        else :
            a.clear()
            return False
    x=1
    n=x
    while x>0:
        if triangular(n):
            print(n)
            break
        else:
            n+=x+1
            x+=1


texts:
I would like you to take a look at this simple script I wrote that's supposed to emulate the Unix sort [FILE] | uniq -cd command. What's different about my script though is that it also lists line numbers telling the user where occurrences of duplicate lines are located in the file. Please, tell me what you think as well as what parts of the script, if any, you think I should rework to make it better.

################################################################################
# File name: uniq.awk
# ===================
#
# Find and report all occurrences of duplicate lines in a text file.
#
#
# Usage: awk -f uniq.awk [FILE]
#
################################################################################
{
    x = lines[$0]["count"]++; # Count the number of occurrences of a line
    lines[$0]["NR"][x] = NR;  # Also save the number lines

    # Find the length of the longest line to make it the column width
    if (x > 0) {
        if (length($0) > max) {
            max = length($0);
        }
    }
}
END {
    # If the file contains no lines to process, that is, it's empty,
    # return an exit status code of 1 to indicate the fact.
    if (!(NR > 0)) {
        exit 1;
    }

    # Prepare the format string
    # Column #1: number of occurrences of the line
    # Column #2: line itself
    # Column #3: line numbers where all the lines are located
    fmt_s = "%s: %" max "-s (%s)\n";

    for (i in lines) {
        if (lines[i]["count"] > 1) {
            for (j = 0; j < lines[i]["count"]; j++) {
                s = s lines[i]["NR"][j] ", ";
            }
            # Get rid of the trailing comma and space
            s = substr(s, 1, length(s) - 2);
            printf(fmt_s, lines[i]["count"], i, s);
            s = "";
        }
    }
}

Test:

$ cat > data
car
baby
car
man
woman
woman
key
woman
$
$ cat -n data
     1  car
     2  baby
     3  car
     4  man
     5  woman
     6  woman
     7  key
     8  woman
$
$ awk -f uniq.awk data
2: car   (1, 3)
3: woman (5, 6, 8)


texts: Computing logits for a vector and for all vectors in a set

texts:
I've had to write two different functions (shown below), but I want to combine the two functions into one. Is there a way to do this?

softmax_a_set() takes a list of numpy arrays, applies softmax() to each individual numpy array, and then returns a list of processed numpy arrays.

def softmax(a_vector):
    """Compute a logit for a vector."""
    denom = sum(numpy.exp(a_vector))
    logit = numpy.exp(a_vector)/denom
    return logit

def softmax_a_set(a_set):
    """computes logits for all vectors in a set"""
    softmax_set = numpy.zeros(a_set.shape)

    for x in range(0, len(a_set)):
        softmax_set[x] = softmax(a_set[x])

    return softmax_set


texts:
I used JS to re-populate the shipping address into the billing address when a checkbox is clicked. I'm wondering whether there is a more concise/better way to write the code below:

var checkBox = document.getElementById('order_use_billing');

var shipFirstName = document.getElementById('order_ship_address_attributes_firstname');
var billFirstName = document.getElementById('order_bill_address_attributes_firstname');
var shipLastName = document.getElementById('order_ship_address_attributes_lastname');
var billLastName = document.getElementById('order_bill_address_attributes_lastname');
var shipStreet = document.getElementById('order_ship_address_attributes_address1');
var billStreet = document.getElementById('order_bill_address_attributes_address1');
var shipStreetTwo = document.getElementById('order_ship_address_attributes_address2');
var billStreetTwo = document.getElementById('order_bill_address_attributes_address2');
var shipState = document.getElementById('order_ship_address_attributes_state_id');
var billState = document.getElementById('order_bill_address_attributes_state_id');
var shipCity = document.getElementById('order_ship_address_attributes_city');
var billCity = document.getElementById('order_bill_address_attributes_city');
var shipCountry = document.getElementById('order_ship_address_attributes_country_id');
var billCountry = document.getElementById('order_bill_address_attributes_country_id');
var shipZip = document.getElementById('order_ship_address_attributes_zipcode');
var billZip = document.getElementById('order_bill_address_attributes_zipcode');
var shipPhone = document.getElementById('order_ship_address_attributes_phone');
var billPhone = document.getElementById('order_bill_address_attributes_phone');

$(function(){
   $('input[type=checkbox]').prop("checked", false);
});

function filling(){

  if(checkBox.checked == true) {
    shipFirstName.value       = billFirstName.value;
    shipLastName.value        = billLastName.value
    shipStreet.value          = billStreet.value
    shipStreetTwo.value       = billStreetTwo.value
    shipCity.value            = billCity.value
    shipState.value           = billState.value
    shipCountry.value         = billCountry.value
    shipZip.value             = billZip.value
    shipPhone.value           = billPhone.value

  }
   if(checkBox.checked == false) {
    shipFirstName.value       = "";
    shipLastName.value        = "";
    shipStreet.value          = "";
    shipStreetTwo.value       = "";
    shipCity.value            = "";
    shipState.value           = "";
    shipCountry.value         = "";
    shipZip.value             = "";
    shipPhone.value           = "";

  }
};

$(function() {
    $('input[type="checkbox"]').on('change', function() {
         filling();
    });
});


texts: Viewing test scores from one of three CSV files

texts:
Is there any way I could tidy this code and make it look better and more appealing?

import csv
math_class = input ("Which math class would you like to see the results of?")
while math_class not in ['1','2','3']:
    math_class = input ("Which math class would you like to see the results of?")
sort = input ("How would you like to sort the results alphabetical, highest or average:\n")
while sort not in ["alphabetical","highest","average"]:
    sort = input ("How would you like to sort the results")
class_file_names = ['Class 1.csv', 'Class 2.csv', 'Class 3.csv']
scan = open(class_file_names[int(math_class)-1], 'r+')
rows = csv.reader(scan)
data = []
next(scan)

for row in rows:
    data.append(row)
scan.close()

if(sort == "alphabetical"):
    word = "- Highest Score on test:"
    sorted_= sorted(data, key=lambda name: name [0])
    field = 5

if(sort == "average"):
    word = "- Average Score"
    sorted_ = sorted(data, key=lambda average: average[4], reverse=True)
    field = 4

if(sort == "highest"):
    word = "- Highest Score on test:"
    sorted_ = sorted(data, key=lambda total: total[5], reverse=True)
    field = 5

for row in sorted_:
    print(str(row[0]), word, str(row[field]))
input ("Sort Complete, press any key to close the program.")

If there is no way I could clean up the code, then that's fine as it does what I want it to (it's just that I thought the code could look more appealing than it already is).


texts: Sampling words from randomly chosen text files

texts:
I've developed a script to randomly select 50 elements from a list of .txt files. This process is repeated 100 times. The script joins the randomly selected text files to one long string and then filters out the longest substring.

I want to run this script on a Droplet on Digital Ocean. The server, however, kills the script. When I randomly select only 3 elements, it works. Am I running out of memory? How can I tackle this problem?

Here are the files I randomly select items from. And this is my code:

# coding: utf-8

import glob
from collections import Counter
import pickle
import random

de_list_soz = pickle.load(open('de_list_soz.p', 'rb'))
str_seq_list = []

for str_seq in range(0,100):
    #creating random list
    random_list = []
    for item in range(0,50):
       list_item = random.choice(de_list_soz)
       random_list.append(list_item)

    #creating long string
    long_str = ''
    for de in random_list:

        input_file = open('txt_sr_de/txt_sr_de/' + de, 'r')
        text = input_file.read()
        text = text.replace('\n', ' ').replace('\xa0', '').replace('  ', '')
        #Removing these automated notifications
        text = text.replace('Wichtiger Hinweis:Diese Website wird in älteren Versionen von Netscape ohne graphische Elemente dargestellt. Die Funktionalität der Website ist aber trotzdem gewährleistet. Wenn Sie diese Website regelmässig benutzen, empfehlen wir Ihnen, auf Ihrem Computer einen aktuellen Browser zu installieren.Zurück zur Einstiegsseite Drucken Grössere Schrift', '')
        text = text.replace('Vorwärts ähnliche Leitentscheide suchenähnliche Urteile ab 2000 suchen Drucken nach oben', '')
        text = text.replace('Bundesgericht Tribunal fédéral Tribunale federale Tribunal federal', '')
        text = text.replace('Navigation Neue Suche Zurück zum Suchresultat Rang: Zurück 180', '')
        text = text.replace('Navigation Neue Suche Zurück zum Suchresultat Rang:1 ähnliche Leitentscheide suchenähnliche Urteile ab 2000 suchen Drucken nach oben', '')
        text = text.replace('  ', ' ')

        long_str = long_str + text

    times=3

    for n in range(1,int(len(long_str)/times+1)):
        substrings=[long_str[i:i+n] for i in range(len(long_str)-n+1)]
        freqs=Counter(substrings)
        if freqs.most_common(1)[0][1]<3:
            n-=1
            break
        else:
            seq=freqs.most_common(1)[0][0]

    str_seq_list.append(seq)

pickle.dump(str_seq_list, open('SOZIALRECHT_DE.p', 'wb'))


texts:
I've written an implementation for the Sherlock GCD HackerRank Challenge. As the running time of my algorithm is something like \$O(kn^2)\$, I reckon that there's a more efficient algorithm that could be used instead. Are there any improvements that can be made to my implementation to reduce the running time?

Problem statement (as shown on HackerRank)

  Sherlock is stuck while solving a problem: Given an array \$A={a1,a2,⋯,aN}\$, he wants to know if there exists a subset \$B\$ of this array which follows these statements:

  \$B\$ is a non-empty subset.
  There exists no integer \$x(x>1)\$ which divides all elements of \$B\$.
  There are no elements of \$B\$ which are equal to another.

  Print YES if such a subset exists; otherwise, print NO

Answer:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SherlockGCD {
    public static void main(String[] args) {
        try(BufferedReader input = new BufferedReader(new InputStreamReader(System.in))){
            int numTestCases = Integer.parseInt(input.readLine());

            for(int i = 0; i < numTestCases; i++){
                int N = Integer.parseInt(input.readLine());
                String[] array = input.readLine().split(" ");
                Set<Integer> distinctElements = new HashSet<>(N);
                for(int j = 0; j < N; j++){
                    distinctElements.add(Integer.valueOf(array[j]));
                }
                List<Integer> numbers = new ArrayList<>(distinctElements);
                System.out.println(doesSubsetExist(distinctElements, numbers));
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    /**
     * Determines whether a subset that satisfies the constraints in the problem statement exists.
     *
     * Looks for two elements that satisfy the conditions set out in the problem statement. If two such
     * elements exist, then there exists at least one subset that satisfies the conditions. Else, there doesn't exist a
     * subset.
     *
     * @param set        A set of distinct numbers. Passed in because .contains() is O(1) for a Set vs O(n) for an
     *                   ArrayList
     * @param numbers    A list of distinct numbers
     * @return "YES" if such a subset exists. "NO" if not.
     */
    private static String doesSubsetExist(Set<Integer> set, List<Integer> numbers){
        if(set.contains(1)){
            return "YES";
        }

        // If there's only one distinct element and that element isn't the integer 1, then the second constraint is not
        // satisfied.
        if(numbers.size() == 1){
            return "NO";
        }

        for(int i = 0; i < numbers.size(); i++){
            for(int j = i + 1; j < numbers.size(); j++){
                for(int k = 2; k <= Math.min(numbers.get(i), numbers.get(j)); k++){
                    if(numbers.get(i) % k == 0 && numbers.get(j) % k == 0){
                        break;
                    }

                    if(k == Math.min(numbers.get(i), numbers.get(j))){
                        return "YES";
                    }
                }
            }
        }
        return "NO";
    }
}


texts: Optimizing the performance of a nested for loop over millions of messages from SQLite Query - v2

texts:
I've posted and gotten help to optimize my code before here and here. Now I have implemented the following changes, after very helpful advice:

I have implemented a Dictionary instead of using list when looking into the extracted messages.
I have implemented index on the userid and unixtime tables in my database.

Both these changes combined has sped up this program a tenfold, but I still need to make it quicker.

I have a very large number (millions) of messages, each labeled with the unixtime it was sent in a SQLite database. Each message has its own userid, for the user that have sent it. I want to know what's the max number of messages that is sent within an 24hr timeslot for each user. The 24hr timeslot is defined as the time from one message to another. So if there are five messages, where the 5th one is sent 24 hours after the first one, 5 is the number I want.

After these changes the query time of my code is small compared to the total runtime of the program, so I think the biggest gains is in optimizing the algorithm itself.

con = lite.connect(databasepath)
    messageFrequency = []
    start = time.time()
    with con:
        cur = con.cursor()
        #Get all UserID
        distincttime = time.time()
        cur.execute('SELECT DISTINCT userid FROM MessageType1 limit 100000')
        deltadistincttime = time.time()-distincttime
        userID = cur.fetchall()
        userID = {index:x[0] for index,x in enumerate(userID)}
        #For each UserID
        for index in range(len(userID)):
            messageFrequency.append(0)
            #Get all MSG with UserID = UserID sorted by UNIXTIME
            cur.execute('SELECT unixtime FROM MessageType1 WHERE userID ='+str(userID[index])+' ORDER BY unixtime asc')
            AISmessages = cur.fetchall()
            AISmessages = {index:x[0] for index,x in enumerate(AISmessages)}
            #Loop through every MSG
            for messageIndex in range(len(AISmessages)):
                frequency = 0
                message = AISmessages[messageIndex]
                for nextMessageIndex in range(messageIndex+1, len(AISmessages)):
                #Loop through every message that is within 24 hours
                    nextmessage = AISmessages[nextMessageIndex]
                    if  nextmessage < message+(86400):
                    #Count the number of occurences
                        frequency += 1
                    else:
                        break
                #Add best benchmark for every message to a list that should be plotted.
                if messageFrequency[-1]<frequency:
                    messageFrequency[-1] = frequency

What I think can be done:

Instead of looping through every message in the third loop, I can implement some kind of binary-search to find the first message that is 24hours away.
Instead of looping through every message in the second loop, I can loop through every message that is \$x\$ seconds/minutes away; but maybe the gain is lost by trying to skip forward \$x\$ seconds?

When I run with 2000 userID's the total running time is 8.1 seconds, the cumulative time of the innermost loop is 6.9 seconds. Most optimal I will run this code with 80 000 userIDs and 200M messages.
I would love other suggestions on what to be done to bettering the performance of this code.