texts: Stateful function pointer for passing C++ capturing lambdas / std::functions to C style callbacks

texts:
#include <functional>

template<typename return_type, typename... argument_types>
struct stateful_function_pointer
{
  using function_type         = std::function<return_type(argument_types...)>;
  using function_pointer_type = return_type (*) (argument_types..., void*);

  function_pointer_type callback ()
  {
    return [ ] (argument_types... arguments, void* user_data)
    {
      return (*static_cast<function_type*>(user_data))(arguments...);
    };
  }
  void*                 user_data()
  {
    return static_cast<void*>(&function);
  }

  function_type function;
};

The C style callback must be providing a void* user data as its final parameter (which is a de-facto standard). It may be possible to pass additional user data other than the function state, but I do not see the point as the lambda can already capture user state.
An eccentricity: It is instantiated as e.g. stateful_function_pointer<void, int, char*> instead of stateful_function_pointer<void(int, char*)>.
Example usage as requested (wrapping a HDF5 C function in C++):
class link_access_property_list : public property_list
{
public:
  using function_pointer_type = stateful_function_pointer<herr_t, const char*, const char*, const char*, const char*, unsigned*, hid_t>;
  using callback_type = function_pointer_type::function_type;

  bool set_external_link_callback(const callback_type& callback)
  {
    function_pointer_.function = callback;
    return H5Pset_elink_cb(id_, function_pointer_.callback(), function_pointer_.user_data()) >= 0;
  }

protected:
  function_pointer_type function_pointer_;
};

Then I could:
lapl.set_external_link_callback(
  [CAPTURE_WHATEVER_YOU_WANT]
  (const char*, const char*, const char*, const char*, unsigned*, hid_t)
  {
    USE_WHATEVER_YOU_WANT
    return herr_t(0);
  });


texts:
I have written this code for crawling and scraping search results from Google. But it's super slow when I run it.

What it does: read a pandas column, search values in Google and take the first result link then extract the siret number in link
Ex.

  https://www.infogreffe.fr/entreprise-societe/380760702-entreprise-de-decoration-et-d-innovation-sarl-340591B001420000.html
  the siret is 380760702. In every iteration I save this number in found_results.

To do that, there are three functions:

rechercher_google() to get the html
parse_results() to parse the url where the digit is
recherche_google() to wrap to these two functions above.

Could it be less greedy in complexity or be better?

# Function pour recupere la html
USER_AGENT = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}

def rechercher_google(search_term, number_results, language_code):
    '''
    input: Nom de l'entreprise à siretiser, le nombre de page et la langue
    output: La page resultat dde google en html stocker au format raw html
    '''
    assert isinstance(search_term, str), 'Il doit etre en string'
    assert isinstance(number_results, int), 'DOit etre en chiffre'
    escaped_search_term = search_term.replace(' ', '+')

    g_url = 'https://www.google.fr/search?q={}&num={}&hl={}'.format(escaped_search_term, number_results, language_code)
    response = requests.get(g_url, headers = USER_AGENT)
    response.raise_for_status()

    return response.text, search_term

# function pour recuperer ce qu'on a besoin dans la page
def parse_results(html, keyword):
    '''
    Input: la sortie de la fortion fetch_results()
    output: le nom de l'entreprise et le siret
    '''
    soup = bs(html, 'html.parser')

    found_results = []
    rank = 1
    result_block = soup.find_all('div', attrs={'class': 'g'}) # g indique q'on est bien dans un resultat normal
    for result in result_block:
        link = result.find('a', href=True)
        title = result.find('h3')
        if link and title:
            link = link['href']
            title = title.get_text()
            if link != '#':
                try:
                    found_results.append({'siret':link.split('/')[4].split('-')[0]})
                except Exception as list_error:
                    print('error in fund_results {}'.format(list_error))

                rank += 1
    return found_results

# wrap up, le tout dans un global function qui appelle les deux premiere.
def scrape_google(search_term, number_results, language_code):
    '''
    input: il mange les deux premier functions
    output: une liste de dict des nom d'entreprise avec leur siret et club
    '''
    try:
        html, keyword = rechercher_google(search_term, number_results, language_code)
        results = parse_results(html, keyword)
        return results
    except AssertionError:
        raise Exception("Probleme d'argument")
    except requests.HTTPError:
        raise Exception(" :/ Google a bloqué le ip")
    except requests.RequestException:
        raise Exception(" :/ Probleme de connexion/proxy")

To run it

# Siret à partir de google
start_time = time.time()
data = []
for keyword in liste_partenaire.Partenaire:
    keyword = keyword+ ' ' + 'infogreffe Montpellier'
    name.append(keyword)
    try:
        results = scrape_google(keyword, 1, "fr")
        for result in results:
            data.append(results[0]['siret'])
    except Exception as e:
        print(' :( Error in results:: [ {} ]'. format(e))
    finally:
        time.sleep(11)
print("--- %s seconds d'éxecution ---" % (time.time() - start_time)) # 48 minutes
# save


texts: Car Showroom Database: Taking user inputs and manipulating arrays

texts:
I've been learning C# for around 2 weeks and I'm feeling a bit more confident. I wrote this for general practice and am quite proud but hoping to make it faster and more efficient as I progress and learn more.

This program allows the user to input car data i.e. "Model and Price" and then search for the stored data.
(Next step is to add more values to the arrays).

class Program
{
    static void Main(string[] args)
    {

        Console.WriteLine("How many cars are in the workshop?");
        int amountofcars = int.Parse(Console.ReadLine());

        int[] cars = new int[amountofcars];
        double[] carprice = new double[amountofcars];
        string[] models = new string[amountofcars];

        for(int i = 0; i < amountofcars; i++)
        {
            Console.WriteLine("List the model of car #{0}", i + 1);
            string carmodels = Console.ReadLine();
            models[i] = carmodels;
            Console.WriteLine("Input car price");
            double price = double.Parse(Console.ReadLine());
            carprice[i] = price;

        }

            Console.WriteLine("Data stored");

            Console.WriteLine();
            Console.WriteLine("What do you want to do next?");
            Console.WriteLine("Type \"Search\" to start a new search or any key to leave program");
            string responce = Console.ReadLine();
            char searchagain = 'Y';

        do
        {
            if (responce == "Search")
            {
                bool contains = false;
                Console.WriteLine("What car did you want to search for?");
                string modelsearch = Console.ReadLine();

                for (int i = 0; i < amountofcars; i++)
                {
                    if (modelsearch == models[i])
                    {
                        contains = true;
                        Console.WriteLine("{0} {1} ", models[i], carprice[i]);
                        Console.WriteLine();
                        Console.WriteLine("What do you want to do next?");
                        Console.WriteLine("Search again? \"Y\" or any key to exit");
                        searchagain = char.Parse(Console.ReadLine());

                    }
                    if (modelsearch == "All")
                    {
                        for (i = 0; i < amountofcars; i++)
                        {
                            contains = true;
                            Console.WriteLine("{0} {1} ", models[i] , carprice[i]);
                            Console.WriteLine();
                        }
                        Console.WriteLine("What do you want to do next?");
                        Console.WriteLine("Search again? \"Y\" or any key to exit");
                        searchagain = char.Parse(Console.ReadLine());
                    }

                }

            }

        } while (searchagain == 'Y');
    }
}


texts: C++ implementation of Hackerrank's "Maximum Element in a Stack"

texts:
I just attempted the Maximum Element Challenge on Hackerrank. This question has been posted before in swift Swift Hackerrank Maximum Element in a Stack but it has attracted low views/no answers. Moving forward, based on the requirements of finding the maximum element, I used a vector<int> as my underlying data structure as opposed to using Stack as I can't iterate through a stack. This exercise is meant to be a simple one but the time limit gets exceeded for larger input.

How do I improve the performance? Please feel free to criticise my approach as I'm new to C++ with 5 days of experience.

  You have an empty sequence, and you will be given \$N\$ queries. Each
  query is one of these three types:

  1 x  -Push the element x into the stack
  2    -Delete the element present at the top of the stack
  3    -Print the maximum element in the stack

  Input Format

  The first line of input contains an integer, \$N\$ . The next \$N\$
  lines each contain an above mentioned query. (It is guaranteed that
  each query is valid.)

  Constraints

  \$1 \leq N \leq 10^5 \$
  \$1 \leq x \leq 10^9 \$
  \$1 \leq \text{type} \leq 3 \$

  Output Format

  For each type \$3\$ query, print the maximum element in the stack on a
  new line.

  Sample Input

10
1 97
2
1 20
2
1 26
1 20
2
3
1 91
3

  Sample Output

26
91

#include <vector>
#include <iostream>
#include <algorithm>

//using namespace std;
bool compareValues(int i, int j) { return i<j; }

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int N;
    int queryType;
    int element;
     std::vector<int> stackOfNumbers;

    std::cin >> N;
    for(int i =0; i < N ; i++){
        std::cin >> queryType;

        switch(queryType) {
      case 1 :
            std::cin >> element;
            stackOfNumbers.push_back(element);
         break;
      case 2 :
            stackOfNumbers.erase(stackOfNumbers.end()-1);
            break;
      case 3 :
           std::cout<< *std::max_element(std::begin(stackOfNumbers), std::end(stackOfNumbers),compareValues ) << std::endl;
         break;
      default :
        std::cout << "Invalid queryType" << std::endl;
   }

    }
    return 0;
}


texts:
Is this image uploading script safe? I have spent my day researching this and it would be very much appreciated if you could point out any errors or ways to make it safer.

<?php

$max_file_size = 1048576; // expressed in bytes
                          // 10240 = 10 KB
                          // 102400 = 100 KB
                          // 1048576 = 1 MB
                          // 10485760 = 10 MB

$upload_errors = array(
  // http://www.php.net/manual/en/features.file-upload.errors.php
  UPLOAD_ERR_OK         => "No Errors",
  UPLOAD_ERR_INI_SIZE   => "Larger than upload_max_filesize",
  UPLOAD_ERR_FORM_SIZE  => "Larger than form MAX_FILE_SIZE",
  UPLOAD_ERR_PARTIAL    => "Partial upload",
  UPLOAD_ERR_NO_FILE    => "No file",
  UPLOAD_ERR_NO_TMP_DIR => "No temporary directory",
  UPLOAD_ERR_CANT_WRITE => "Can't write to disk",
  UPLOAD_ERR_EXTENSION  => "File upload stopped by extension"
  );

$image_types = array (
  IMAGETYPE_GIF         => "gif",
  IMAGETYPE_JPEG        => "jpg",
  IMAGETYPE_PNG         => "png"
  );

$image_whitelist = array(IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF);

$message = "";
if (isset($_POST['submit'])) {

  // This would store the actual user id
  $userId = 1;

  // store uploaded file's temp path.
  $tmp_file = $_FILES['file_upload']['tmp_name'];

  if($_FILES['file_upload']['error'] > 0){
    $error = $_FILES['file_upload']['error'];
    die($upload_errors[$error]);
  }

  // check to see if file is an image, if not die.
  if(!getimagesize($tmp_file)) {
    die('Please ensure you are uploading an image.');
  }

  // check to see if image is a valid type, if not die.
  if (!in_array(exif_imagetype($tmp_file), $image_whitelist)) {
    die('Please upload a valid image. (.jpg, .png or .gif)');
  }

  $target_file = md5($userId . date('U')) . "." . $image_types[exif_imagetype($tmp_file)];
  $upload_dir = "uploaded";

  // check to see if file already exsits if it does die.
  if (file_exists($upload_dir."/".$target_file)) {
    die('file already exists');
  }

  //move_uploaded file will return false if $tmp_file is not a valid upload file
  // or if it cannot be moved for any other reason
  if (move_uploaded_file($tmp_file, $upload_dir."/".$target_file)) {
    $message = "File uploaded successfully.";
  } else {
    die("move_uploaded_file() error.");
  }
}
?>

<html>
<head>
  <title>File Upload</title>
</head>
<body>
  <?php if(!empty($message)) { echo "<p>{$message}</p>"; } ?>
  <form action="fileupload.php" enctype="multipart/form-data" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>">
    <input type="file" name="file_upload">
    <input type="submit" name="submit" value="Upload">
  </form>
</body>
</html>

Many Thanks


texts: More efficient way of removing line indices?

texts:
After profiling my current script I've found that nearly 100% of the run time (and I'm not surprised) comes from the following function:

def rem_asc_by_pos(xmlFile, fileOut,removeIndices):
fileIn = xmlFile.replace('.xml', '.asc')
with open(fileIn, 'r') as fin:
    with open(fileOut, 'w') as fout:
        #remove indices from each line and write to new file
        if len(removeIndices) > 0:
            for line in fin:
                lineList = list(line)
                checkLine = ''
                newLine = []
                for ind,char in enumerate(lineList):
                    if ind not in removeIndices:
                        newLine.append(char)
                lineOut = ''.join(newLine)
                fout.write(lineOut)

The files themselves can have anywhere from a 15 thousand lines to 2.5 million at the most, each line is usually from 300-600 characters.

I was thinking that the write operation may be causing an increase in run-time so I could write multiple lines at a time but wouldn't know a good way to determine when it should write the lines (so as to not run out of memory).

Is there anything obvious that I might be able to change to decrease the overall run-time? To go through all the files currently it takes about 20 hours and any decrease from that is appreciated!

edit: Adding an example of input and expected output!

Input:
I have a bunch of data files that look similar to this:

511111 12  1.000000  1.000000  1.000000   .750000
511112 12  1.000000   .666667   .500000   .555556

The removeIndicies list contains the indicies to remove from each line, for this example we want to remove the first three and indicies 19-28.

Expected output:

111 12  1.000000  1.000000   .750000
112 12  1.000000   .500000   .555556


texts: Make pinging faster while looking for a Windows PC

texts:
This code pings 1 time every IP while using TTL to identify if it's a Windows PC. If so, it outputs it. It's very slow, so is there any way to make it go faster (1-255 in 12 min)?

@echo off
echo running, it will take a long time to scan
(
  FOR /L %%N in (1 1 254) DO (
      FOR /f "tokens=1,3 delims=: " %%A IN ('ping -n 1 192.168.250.%%N ^| find "TTL=128"') DO ECHO %%B

  )
) >ip.txt

echo done
get_info.bat


texts: Is there a better way to thread this class function?

texts:
I have a class bar that keeps track of N instances of class foo in a std::map (so N = map.size()).
When I call bar::func I want to have N threads that call foo::foo_func.

foo::foo_func requires multiple arguments though, namely the instance of bar that it's related to.

I was thinking of doing something like:

void * _threaded_foo_func(void *);

struct box {
  bar * the_bar;
  foo * the_foo;
};

class bar {
  class sub_bar {
    // stuff
  };

  map<foo*, sub_bar*> foo_mappings;

  void func() {
    pthread_t threads[ foo_mappings.size() ];
    map<foo*, sub_bar*>::iterator it = foo_mappings.begin();
    int i=0;
    for(it; it != foo_mappings.end() && i < foo_mappings.size(); ++it, ++i) {
      box * args = new args();
      args->the_bar = this;
      args->the_foo = it->first;
      pthread_create( &threads[i], NULL, _threaded_foo_func, (void*) args);
    }

    for(int i=0; i<bar_mappings.size(); ++i) {
      pthread_join(threads[i], NULL);
    }

  }

};

void * _threaded_foo_func(void * args) {
  box * b = (box*) args;
  bar * the_bar = b->the_bar;
  foo * the_foo = b->the_foo;
  the_foo->foo_func(the_bar);
  return NULL;
}

My questions are:

Is there a better way to do this? Cleaner? Thoughts on using
fork()?
Does this look like a poor design of the relationship
between foo & bar?

To make this fun, you're only allowed to use pthread.h, no C++11 stuff :)


texts: Avoiding object slicing within abstractions and their derivations

texts:
I've created a rudimentary example of the issue I'm inquiring about: Object slicing. I followed a post on Stack Overflow which provided a similar template - and for all intents and purposes, this works. I was just wondering if this would get me into a trouble longer down the line? Is there anything here that jumps out at you as dangerous and/or wrong?

The heart of the logic is in main(). I'm pushing a Circle object into a Shapes* vector, then push the new Shapes* element into a Circle vector. The issue I had WITHOUT the assignment operators, was that the compiler couldn't decide how to convert Shape* to Circle.

Please let me know if there are any glaringly obvious improvements.

class Shape {
public:
    virtual Shape& operator=(const Shape& s) {
        assign(s);
        return *this;
    }

    virtual std::string getName() = 0;
    virtual         int getEdges() = 0;

protected:
    std::string name;
    int         edges;

    void assign(const Shape& s) {
        this->name = s.name;
        this->edges = s.edges;
    }
};

class Circle : public Shape {
private:
    int radius;
public:
    Circle() { name = "Circle"; edges = 1; }
    Circle(int rad) { name = "Circle"; edges = 1; radius = rad; }

    virtual Circle& operator=(const Shape& s) {
        if (const Circle* c = dynamic_cast<const Circle*>(&s))
            assign(*c);
        else{
            std::cout << "BAD ASSIGNMENT IN CIRCLE.";
                    //THROW ERROR HERE INSTEAD OF THE ABOVE COUT
            }
        return *this;
    }

    std::string getName() { return name; }
            int getEdges() { return edges; }
            int getRadius() { return radius; }
           void setRadius(int r) { radius = r; }

protected:
    void assign(const Circle& c) {
        Shape::assign(c);
        this->radius = c.radius;
    }

};

int main() {
    std::vector<Shape*> shapes;
    std::vector<Circle> circs;
    Circle c2(5); //Creates a circle with 5 for the radius.

    shapes.push_back(&c2); //Pushing the 5-radius circle into the Shapes* vector
    Circle c3; //Creates a circle with default constructor (which does NOT define radius)
    c3 = *shapes[0]; //Now, the overloaded assignment operator. Look at Circle::assign(const Shape&) function
    circs.push_back(c3); //We push our newly assigned circle to our Circle vector
    std::cout << "c3 radius: " << circs[0].getRadius(); //This will be 5!
}


texts: API using NodeJS to recive data from client and send it to a server

texts:
Hello I have a NodeJS which act like an interface it connects the client(mobile app) to the actual server
My node JS API receives data from the client to verify it and send it to the server.

I want to know does this code looks good?
Is that how API should be written in NodeJS?
Does this code violate any of the SOLID principles?
How can I improve this code?

const axios = require("axios")
require("express-async-errors")
const bodyParser = require("body-parser")
const express = require("express")

const LOLTrackingSystem = require("../methods/onlineGamesTracking/LOLTracking")
const getUserData = require("../methods/leagueOfLegends/getUserData")
//======[Gizmo Operator Settings]=======

// userId = token

//========[Gizmo API URL]==========
apiRoute = (api) => {
  api.use(bodyParser.json())
  // api.use(bodyParser.urlencoded({ extended: false }));
  // api.use(express.json());

  api.post("/api/auth", (req, res) => {
    const clientAuth = {
      username: req.body.username,
      password: req.body.password
    }

    const loginValidationURL = `http://${process.env.HOST}/api/users/${clientAuth.username}/${clientAuth.password}/valid`

    axios
      .get(loginValidationURL, { headers: { Authorization: process.env.AUTH } })
      .then((response) => {
        let token = response.data.result.identity.userId
        response.data.result.result == 0
          ? res.json({ status: "Authenticated", result: 1, token: hash })
          : res.json({ status: "Wrong Username or Password", result: 0 })
      })
      .catch((error) => {
        console.log("error " + error)
        res.json({
          status: `Couldn't reach Arena Gaming Server. Try again later`,
          result: 404
        })
      })
  })

  api.post("/api/memberProfile", (req, res) => {
    var token = req.headers["authorization"]
    // bcrypt.compare(token, hash).then(function(res) {
    //     // res == true
    // });
    const memberProfileURL = `http://${process.env.HOST}/api/users/${encryptedId}`

    axios
      .get(memberProfileURL, { headers: { Authorization: process.env.AUTH } })
      .then((response) => {
        response.data
      })
      .catch((error) => {
        console.log("error " + error)
        res.json({
          status: `Couldn't reach Arena Gaming Server. Try again later`,
          result: 404
        })
      })
  })
  //=============================================================================
  // Gizmo Related API
  //=============================================================================
  // MemberState Get The UserId & HostId when member login or logout of Gizmo
  api.post("/api/gizmo/memberState/:userId/:host/:state", async (req, res) => {
    const member = {
      state: req.params.state,
      userId: req.params.userId,
      hostComputer: req.params.host
    }
    if (Number(member.state)) {
      console.log(
        "[Logged In] Member with userId: " +
          member.userId +
          " To HostId: " +
          member.hostComputer +
          "[Sent From GizmoServer]"
      )
      await getUserData(member.userId, async (subscribed) => {
        // Check if the user is subscribed to the tracking system or not
        //*TODO* Add a list of currently tracking members that we can see
        if (subscribed) {
          LOLTrackingSystem(member.userId) // Start tracking that member
          res.json("[Started] Member " + member.userId + " Tracking")
        } else {
          res.json(
            "[Started] Member " +
              member.userId +
              " is not subscribed to the tracking system"
          )
        }
      })
    } else {
      console.log(
        "[Logged Out] Member with userId: " +
          member.userId +
          " From HostId: " +
          member.hostComputer +
          "[Sent From GizmoServer]"
      )
    }
  })
}

module.exports = apiRoute

Thanks


texts: How could I have approached this responsive image gallery differently?

texts:
This gallery uses the Orbit gallery from the Foundation framework (version 3). I've set it up so that on smaller screens it appears as an accordion.

It works just fine, but is there a more concise way this could've been written? Perhaps in an object oriented way?

The script:

function activateSlider() {
    if (window.Foundation && window.matchMedia) {

      // Establishing media check
      widthCheck = window.matchMedia("(max-width: 767px)");
      if (widthCheck.matches) {
        $('.orbit-container').after($('.orbit-timer'));
        $('#slider, #slider li').attr('style', '');
        $('#slider').removeClass('orbit-slides-container').removeAttr('data-orbit').addClass('accordion-container');
        $('#slider li').removeAttr('data-orbit-slide').removeClass('active');
        $('.orbit-container > a, #slider li .slider-content').hide();
        $('#slider li:not(.active) .slider-content').css('display', 'none');

      //Init accordion click functions
        $('#slider li').unbind().bind('click', function(){
            $(this).toggleClass('active').siblings().removeAttr('class');
            $(this).siblings().find('.slider-content').slideUp();
          $(this).find('.slider-content').slideToggle();
        });
  }
  else
  {
    //If accordion styles are present, clean it up
    var OrbitStyles = ($('.accordion-container').length === 0);
    if (!OrbitStyles) {
        $('.orbit-container > a').show();
        $('#slider').removeClass('accordion-container');
        $('#slider').addClass('orbit-slides-container');
        $('#slider').attr('data-orbit', '');
        $('.orbit-bullets-container').before($('.orbit-timer'));
        $('.orbit-timer').removeClass('paused');
    }
   //Then set it up for the slider
      $('.slider-content').show();
      $('#slider li:first-child').addClass('active').siblings().removeAttr('class');
  }
 }
}

//Run the script
$(function(){
    activateSlider();
});

//Run the script on resize
if (window.addEventListener) {
   window.addEventListener('resize', debounce(function () {
    activateSearch();
    //fade in the slider while loading to prevent that second of ugly formatting
    if ($('#slider').length > 0) {
        $('#slider').delay(700).animate({ opacity: 1 }, 500);
    }
  }, 250));
} else {
    window.attachEvent('resize', debounce(function () {
      activateSearch();
      //fade in the slider while loading to prevent that second of ugly formatting
      if ($('#slider').length > 0) {
         $('#slider').delay(700).animate({ opacity: 1 }, 500);
      }
    }, 250));
}

And the html markup:

        Oh got walrus

More hence euphemistic oriole let tediously dear repeatedly.

          Read More

        Overslept wiped yikes

Much supreme quick rakishly tamarin

           Read More


texts: Faster track to recognizing patterns in looping through nested sequences

texts:
I frequently have patterns as below, usually not this simple, which require me to first code a working solution for a single test case, and then to refactor the code to make it more concise. See the first incarnation below, then the final code. I'm looking to see what other techniques some use to skip the initial step, other than suddenly being able to see the solution with experience. Or if you would approach the example below in an entirely different fashion.

Initial code:

# 4.) A Tic-tac-toe game (see http://en.wikipedia.org/wiki/Tic-tac-toe) can be
# simulated by a computer using a 3 x 3 matrix of strings. Each string has one
# of three possible values, 'X', 'O' or '' (an empty block). Moreover,
# individual move of a player can be simulated with a tuple, containing three
# values: the x-coordinate (0..2), the y-coordinate (0..2) and a string
# containing the mark of the player ('X' or 'O'). Write a procedure
# insertMoves(board, listOfMoves), which has two parameters: a 3 x 3 matrix
# board and a list of players moves as tuples. The procedure then inserts all
# moves in a list to the game board.
def insertMoves(board, list_of_moves):
    for move in list_of_moves:
        if move[0] == 0:
            if move[1] == 0:
                (board[0])[0] = move[2]
            if move[1] == 1:
                (board[1])[0] = move[2]
            if move[1] == 2:
                (board[2])[0] = move[2]
        elif move[0] == 1:
            if move[1] == 0:
                (board[0])[1] = move[2]
            if move[1] == 1:
                (board[1])[1] = move[2]
            if move[1] == 2:
                (board[2])[1] = move[2]
        elif move[0] == 2:
            if move[1] == 0:
                (board[0])[2] = move[2]
            if move[1] == 1:
                (board[1])[2] = move[2]
            if move[1] == 2:
                (board[2])[2] = move[2]
    return board

row = [''] * 3
board = [row, row[:], row[:]]
moves = [(0, 0, 'A'), (0, 1, 'B'), (0, 2, 'C'), (1, 0, 'D'), (1, 1, 'E'),
         (1, 2, 'F'), (2, 0, 'G'), (2, 1, 'H'), (2, 2, 'I')]
final_board = insertMoves(board, moves)
for row in final_board:
    print row

And the final function definition:

def insertMoves(board, list_of_moves):
    for move in list_of_moves:
        for i in range(0, 3):
            if move[0] == i:
                for j in range(0, 3):
                    if move[1] == j:
                        (board[j])[i] = move[2]
    return board


texts: Finding the number of occurrences of a string in another string

texts:
I have written a program, in which I have to find the number of occurrences (overlapping + non-overlapping) of a string in another string.

// variable to keep track of word
int i=0;
for(vector<string>::iterator it = p.begin(); it!=p.end(); it++){
    frequency[i]=0;
    int start=0;
    while(true){
        start = s.find(*it, start);

        if(start==-1){  // not found
            break;
        } else{
            frequency[i]++;
            start++;
        }
    }

    i++;
}

I am finding the starting index start of the match, and then again searching for the string starting from 'start+1' this time, and so on. The length of the string s, in which searching has to be performed is 50,00,000. And total number of keywords (stored in vector p here) is 500 (each having length of 5000).


texts:
Due to being unable to ask a C programming language expert or advanced user in person, I'm posting this simple question about my C code. Today I was refreshing my C with exercise 5.4 of the C programming Language 2nd Edition by K&R, which is a very simple exercise:

Do you think that my way of handling pointers is 'very good' or 'world class'?

I know the example is short/simple but that question comes to my mind because I want to know the opinion from other knowledgeable people about the subject, if you want to critique my code please do so. I'm always trying to push my current C knowledge to the next level.

/*----------------------------------------------------*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*
  Exercise 5-4.
  Write the function strend(s,t)
  which returns 1 if the string t occurs at the
  end of the string s, and zero otherwise.
*/
int strend(char *s, char *t);

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

  if ( rt = strend("Unix Powered", "red"))
     printf("occurs\n");

 return EXIT_SUCCESS;
}

/*
  find if 't' occurs at the end of 's'
*/
int
strend(char *s, char *t)
{
   while (*s)
      s++;
   if ( strlen(s) < strlen(t))
      return 0;
   s -= strlen(t);
   for (; *t ; s++, t++) {
      if ( *s != *t)
         return 0;
   }
 return 1;
}
/*----------------------------------------------------*/


texts: Picking from a list of individuals based on their fitness values

texts:
I have this method that takes a list of my individuals (class has public field fitnessValue). I sum all fitnessValue and then draw a random value between 0 and sum of fitnessValue. In the end, I check for each individual where cumulative sum of fitnessValue passes the point I counted before and return the one which passed first.

public Individual pickRandomIndividual(List<Individual> pool) {
    Double totalScore = 0d;
    Double runningScore = 0d;
    for (Individual ind : pool) {
        totalScore += ind.fitnessValue;
    }

    Double rnd = Math.random() * totalScore;

    for (Individual ind : pool) {
        if (rnd >= runningScore &&
                rnd <= runningScore + ind.fitnessValue) {
            return ind;
        }
        runningScore += ind.fitnessValue;
    }
    return null;
}

I want to refactor this function with Java 8 streams. Any idea how can I achieve that?

I changed it a bit, into:

Double fitnessSum = genePool.stream()
                .mapToDouble(individual -> individual.fitnessValue)
                .sum();
Double runningScore = 0d;

Double rnd = random() * fitnessSum;

for (Individual g : genePool) {
    if (rnd >= runningScore && rnd <= runningScore + g.fitnessValue) {
            return g;
    }
    runningScore += g.fitnessValue;
}
return null;

Still, I do not know how to change cumulative sum part into a stream. Maybe entire logic is poorly implemented? I just want to draw one Individual from the list depending on how large the Individual's fitnessValue is.


texts: Java and stacks: correct implementation?

texts:
I created this very simple stack concept's implementation.
Could you tell me if it is correct and clean? Do you see any bad coding habits?

public class MyStack
{
    private static final int MAXELEMENTS = 10;
    private int[] elements;
    private int numElements;

    public MyStack()
    {
        numElements = 0;
        elements = new int[MAXELEMENTS];
    }

    public boolean isEmpty()
    {
        return (numElements == 0);
    }

    public boolean isFull()
    {
        return (numElements == MAXELEMENTS);
    }

    public void push(int e)
    {
        if (!isFull())
            elements[numElements++] = e;
    }

    public int top()
    {
        if (!isEmpty())
            return elements[numElements - 1];
        else
            return -1;
    }

    public void pop()
    {
        if (!isEmpty())
            numElements--;
    }
}

You can use it with the following code:

class MyStackTestDrive
{
    public static void main(String[] args)
    {
        MyStack s1 = new MyStack();
        MyStack s2 = new MyStack();
        s1.push(2);
        s2.push(4);
        System.out.println(s1.top());
        System.out.println(s2.top());
    }
}


texts: My first build.gradle for a 3D space graphics program

texts:
I'm writing a 3D space graphics program and I just changed the build system to using gradle. This is my first gradle project. It works but I'm sure there is room for improvement.

apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'eclipse'
apply plugin: 'idea'

mainClassName = 'spaceworld.UFOSpaceWorld'

repositories {
    jcenter()
}

ext.jmeVersion = "[3.1,)"

project(":assets") {
    apply plugin: "java"

    buildDir = rootProject.file("build/assets")

    sourceSets {
        main {
            resources {
                srcDir '.'
            }
        }
    }
}
repositories {
    mavenCentral()
    maven {
        url "https://mvnrepository.com/artifact/cz.advel.jbullet/jbullet"

    }
    maven {
        url 'http://nifty-gui.sourceforge.net/nifty-maven-repo'
    }

}

dependencies {

    compile "org.jmonkeyengine:jme3-core:$jmeVersion"
    compile "org.jmonkeyengine:jme3-desktop:$jmeVersion"
    compile "org.jmonkeyengine:jme3-lwjgl:$jmeVersion"
    compile "org.jmonkeyengine:jme3-blender:$jmeVersion"
    compile "org.jmonkeyengine:jme3-bullet:$jmeVersion"
    compile "org.jmonkeyengine:jme3-plugins:$jmeVersion"
    compile "org.jmonkeyengine:jme3-networking:$jmeVersion"
    compile 'lessvoid:nifty:1.4.1'
    compile 'lessvoid:nifty-default-controls:1.4.1'
    compile 'lessvoid:nifty-style-black:1.4.1'
    compile group: "cz.advel.jbullet", name: "jbullet", version: "20101010"
    compile files('libs/cai-nmgen-0.2.0.jar')
    compile files('libs/ext.bundle.opengl.jmonkey-1.1.3.jar')
    runtime project(':assets')
}

task wrapper(type: Wrapper) {
}

task createDirs << {

    def pkg = 'spaceworld'
    def dirs = [
            file("./src/main/java/$pkg"),
            file("./src/main/resources"),
            file("./assets/Interface"),
            file("./assets/MatDefs"),
            file("./assets/Materials"),
            file("./assets/Effects"),
            file("./assets/Textures"),
            file("./assets/Models"),
            file("./assets/Scenes"),
            file("./assets/Shaders"),
            file("./assets/Sounds"),
            file("./assets/Textures"),
    ]

    dirs.each {
        if (!it.exists()) {
            println "Creating " + it
            it.mkdirs()
        }
        if (it.listFiles().length == 0) {
            def stub = new File(it, 'removeme.txt')
            println "Creating stub file to allow git checkin, file:$stub"
            stub.text = "Remove me when there are files here."
        }
    }
}


texts:
Here is my first project that I made with JavaScript and jQuery with a little bit of HTML and CSS:

var currentTurn = "X"; //X or O
var turnNumber = 0;

function generateFields() {
  var y = 1;
  var top = 50;
  for (var i = 0; i < 9; i++) {
    var x = $("#board").append(
      "

"
    );
    var fieldI = $("#nr" + i);

    if (i == 0 || i == 3 || i == 6) {
      fieldI.css("margin-left", "5px");
    }
    if (i >= 3 && i <= 8) {
      fieldI.css("margin-top", "15px");
    }

    fieldI.click(chooseField);
  }
}

$(generateFields());

/*
How table looks like:
    var fieldsOnBoard =
    ["nr0", "nr1", "nr2",
    "nr3", "nr4", "nr5",
    "nr6", "nr7", "nr8",];
 */

function chooseField() {
  if (currentTurn == "X") {
    $(this).html(
      ""
    );
    currentTurn = "O";
  } else if (currentTurn == "O") {
    $(this).html(
      ""
    );
    currentTurn = "X";
  }

  $(this).css({ opacity: 0, scale: 0 });
  $(this).removeClass("hover-field");
  $(this).transition({ opacity: 1, scale: 1 }, "in-out");

  turnNumber++;

  $(".flipper").toggleClass("flipped");

  $(this).off("click");
  if (checkIfWin() != null) {
    endOfGame(checkIfWin());
  }
}

function checkIfWin() {
  var winConditions = [
    ["nr0", "nr1", "nr2"],
    ["nr3", "nr4", "nr5"],
    ["nr6", "nr7", "nr8"],
    ["nr0", "nr3", "nr6"],
    ["nr1", "nr4", "nr7"],
    ["nr2", "nr5", "nr8"],
    ["nr0", "nr4", "nr8"],
    ["nr2", "nr4", "nr6"]
  ];
  for (var x in winConditions) {
    // $("#" + winConditions[x][0] + "> img").attr("class");
    //console.log($("#" + winConditions[x][0] + "> img").attr("class") + " " + $("#" + winConditions[x][0] + "> img").attr("class") + " " + $("#" + winConditions[x][0] + "> img").attr("class"));

    var field1 = $("#" + winConditions[x][0] + "> img").attr("class");
    var field2 = $("#" + winConditions[x][1] + "> img").attr("class");
    var field3 = $("#" + winConditions[x][2] + "> img").attr("class");
    //console.log(`pierwsza = ${field1} druga = ${field2} trzecia = ${field3}`);
    if (field1 != undefined && field2 != undefined && field3 != undefined) {
      if (field1 === field2 && field2 === field3 && field1 === field3) {
        return field1;
      }
    }
  }

  var fieldsOnBoard = [
    "nr0",
    "nr1",
    "nr2",
    "nr3",
    "nr4",
    "nr5",
    "nr6",
    "nr7",
    "nr8"
  ];
  for (var z in fieldsOnBoard) {
    var full = false;

    if ($("#" + fieldsOnBoard[z] + "> img").attr("class") == undefined) {
      break;
    }
    full = true;
  }
  if (full) {
    return "draw";
  }

  return null;
}

function endOfGame(x) {
  console.log(x);

  $("." + x)
    .first()
    .clone()
    .removeClass(".field, " + x)
    .attr("id", "winned")
    .appendTo("#board");
  $(".field, #lines").hide();
  $("#winned").transition({ height: "100px", width: "100px" });
  $("#winned").transition({
    height: "200px",
    width: "200px",
    color: "#e74c3c"
  });
  if (x != "draw") {
    $("#board").append("
HAS WON!
");
  } else {
    $("#board").append("
DRAW
");
    setTimeout(() => resetBoard(), 2000);
  }
  $("#winned").click(() => {
    resetBoard();
  });

  function resetBoard() {
    $(".field, #lines").show();
    $("#board").transition({ scale: 0, rotate: "-90deg" });
    $("#board")
      .children("[id != 'lines']")
      .remove();
    generateFields();
    $("#board").transition({ scale: 1, rotate: "0deg" });
  }
}

Codepen (with HTML and CSS)


texts:
Multiple  AFNetworking calls In a view controller.
The code is very wield.

I think , to negotiate with the server , and combine those into one url, instead of many urls.

@interface HomeViewController ()

#pragma mark - init user info
- (void) initUserData
{
    [self get_userInfo];// user login info about
    [self getRule];// get ship rule
    [self getAppSystem];
    [self getPunchCardInfo]; // get work register stauts
    [CardTypePickerView updateCardTypes:nil]; //  get id type
    [self getProblemTypes];
    [self getFetch_ad];/ get ad
    [self updateSMSCount];// update small messages
    [CGAreaData updateAddressList:NO failure:^(NSString *failure) {}];// update province , city , district
}

#pragma mark -- user login info about
- (void)get_userInfo
{
    __block UserInfoModel *userInfo = [UserInfoModel getUserInfoModel];
    [NetWorkManager info_userSuccess:^(id result, NSString *message) {
        userInfo = [UserInfoModel getUserInfoModel];
        if ([UiUtil checkIsNull:result] == NO) {
            [userInfo setValuesForKeysWithDictionary:result];
            [userInfo saveUserInfoModel];
            [self.headerTaskView setName:userInfo.realName];
        }
    } failure:nil];
    [self.headerTaskView setName:userInfo.realName];
}

#pragma mark --  get ship rule
- (void)getRule
{
    [NetWorkManager getBillRuleWithSuccess:^(NSDictionary *dict) {
        if (![UiUtil checkIsNull:dict]) {
            [[EGOCache globalCache] setObject:dict forKey:EGO_BAR_RULE];
        }

    } failure:^(NSString *errmsg) {
    }];
}

#pragma mark -- get app version
- (void)getAppSystem
{
    [NetWorkManager app_systemWithSuccess:^(NSDictionary *result, NSString *message) {
        if (![UiUtil checkIsNull:result]) {
            [[EGOCache globalCache] setObject:result forKey:EGO_APP_SYSTEM_RULE];
            // check if new version exists
            [VersionCheck versionCheckComplete:result[@"VERSION_IOS"]];

        }

    } failure:^(NSString *errmsg) {

       // check if new version exists
    }];
}

......
// network request info etc

Under the hood,  those functions all use AFNetworking

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];

Any suggestion to optimize these batch requests?

What is the harm of code like this? I think it is the battery consuming.


texts:
So I've been working on a generator for Pascal's triangle in Python. Now, I wouldn't call myself a Python god, so my program is a lot longer than the very confusing ones on the internet. It's more of a logical approach to creating the triangle.

Here's the program:

def double_chunker(lst):
  leng = len(lst)
  for i in range(leng):
    if i == 0:
      yield [lst[0]]
    elif i == 1:
      yield [lst[0], lst[1]]
    elif i == leng:
      yield [lst[-1]]
    else:
      yield [lst[i-1], lst[i]]
  yield [lst[-1]]

def chunk_adder(lst):
  for i in lst:
    if len(i) == 1:
      yield i[0]
    else:
      yield sum(i)

def pascal_next(lst):
  return list(chunk_adder(double_chunker(lst)))

def pascal_triangle(rows):
  end = [[1]]
  for i in range(rows):
    end.append(pascal_next(end[-1]))
  return end

A simple go-through of how it works:

double_chunker() splits up a row of Pascal's triangle into the pairs of numbers you would use when adding up to determine the numbers in the next row. This algorithm is little jerry-rigged - I had to add some special exceptions for some numbers on the end of the row to make it work properly.
chunk_adder() adds together a list of chunks generated by double_chunker to determine the next row in the Pascal sequence.
pascal_next()combines both double_chunker() and chunk_adder() to, when given one row in Pascal's triangle, determine the next row in the triangle.
pascal_triangle() iteratively creates rows of Pascal's triangle using pascal_next().

So, here are some of my questions:

Is there anything in my program that seems redundant, repetitive, or can be shortened?
Is there any better code practices I should be employing and am not?

And obviously, as always, feel free to provide any other feedback you may have. Thanks in advance!


texts:
Building on a previous answer and an attempt to write a comprehensive XMLHttpRequest example that covers all kinds of possible errors and return them to caller gracefully instead of a crash.

function Remote() {}

Remote.upload = function(formData, progressHandler) {
    return new Promise(function(resolve, reject){
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "http://localhost:3000");
        xhr.setRequestHeader("Accept", "application/json");
        xhr.addEventListener("error", function(event){
            reject({code: 0, message: "A network error occurred.", event: event});
        });
        xhr.upload.addEventListener("progress", progressHandler);
        xhr.addEventListener("readystatechange", function() {
            if(xhr.readyState == 4 && xhr.status != 0) { // exclude status 0
                try {
                    xhr.status == 200 ? resolve(JSON.parse(xhr.response)) : reject(JSON.parse(xhr.response));
                } catch(error) {
                    reject({code: 0, message: "JSON parsing error.", body: xhr.response});
                }
            }
        });
        xhr.send(formData);
    });
};

function progressHandler(event) {
    if(event.lengthComputable) {
        console.log((event.loaded / event.total * 100 | 0));
    }
}

Here in this example, I've added a check in the readystatechange not to handle status 0 errors since event handler can be triggered with all sorts of those errors, whether invalid certificate, offline or request getting suppressed. (Limitation: Can't figure out the exact error scenario hence the generic Network error message.

200 status is success as suggested by the REST contract so it's hard coded.
JSON parsing error is also a possibility to handle any issues.
Code is meant to be backward compatible for older browsers.

Hope the code is comprehensive and takes care of all corners.


texts:
Please let me know your feedback around handling ADO.NET connection and transaction, especially when it comes the catch block. Any way I could improve?

public static bool FileBulkLoad(string filePath, string tableName, string fieldSeparator, int numberOfSourceColumns)
{
    using (var connection = new SqlConnection(GetConnectionString()))
    {
        connection.Open();
        using (var transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted))
        {
            try
            {
                foreach (var fileData in Helpers.StreamFile(filePath, tableName, fieldSeparator, numberOfSourceColumns))
                {
                    // BulkInsert uses SqlBulkCopy to insert data.
                    Helpers.BulkInsert(fileData.Data, tableName, connection, transaction);
                }

                transaction.Commit();
                return true;
            }
            catch (Exception)
            {
                transaction.Rollback();
                return false;
            }
        }
    }
}


texts: React-Router, render multiple components

texts:
This works but it doesn't really seem ideal. Is there a better way to write this using react-router? Initialization and pagination are just React containers holding logic. DisplaySaves is a component that renders some stuff to the screen.

<div>
  <BrowserRouter>
    <Route path="/authorize_callback" exact component={Initialization} />
    <Route path="/authorize_callback" exact component={Pagination} />
    <Route path="/authorize_callback" exact component={DisplaySaves} />
  </BrowserRouter>
</div>


texts:
I wrote this console rock-paper-scissors game. I'm new to C++. I'd appreciate any suggestions to improve the code below. Thanks.

RPSCore.h

#ifndef RPS_CORE_H
#define RPS_CORE_H

class RPSCore
{
public:
    static int rpsWinner(char& playerChoice, char& computerChoice);
    static char getComputerChoice();
};

#endif // !RPS_CORE_H

RPSCore.cc

#include <random>
#include <chrono>
#include <cstdint>
#include <map>
#include <sstream>
#include <string>
#include <algorithm>

#include "RPSCore.h"

// private helper function
char getValueIfKeyExists(std::map<std::string, char>& dict, std::string& key)
{
    char ret = '\0';
    for (std::map<std::string, char>::iterator it = dict.begin(); it != dict.end(); it++)
    {
        if (it->first.compare(key) == 0)
        {
            ret = it->second;
            break;
        }
    }
    return ret;
}

int RPSCore::rpsWinner(char& playerChoice, char& computerChoice)
{
    std::map<std::string, char> rules = { {"rs", 'r'}, {"rp", 'p'}, {"sp", 's'} };
    std::stringstream ss;
    ss << playerChoice << computerChoice;
    std::string combination = ss.str();
    std::string combinationCopy{ combination };
    std::reverse(combinationCopy.begin(), combinationCopy.end());
    char p = getValueIfKeyExists(rules, combination) == '\0' ? getValueIfKeyExists(rules, combinationCopy) : getValueIfKeyExists(rules, combination);
    return p == playerChoice && p != computerChoice ? 1 : p == computerChoice && p != playerChoice ? 2 : -1; // 1-> player wins, 2-> computer wins, -1-> draw
}

char RPSCore::getComputerChoice()
{
    std::string options = "rps";
    uint32_t seed = static_cast<uint32_t>(std::chrono::system_clock::now().time_since_epoch().count());
    std::minstd_rand0 range(seed);
    std::uniform_int_distribution<std::minstd_rand0::result_type> dist(0, 2);
    return options[dist(range)];
}

main.cc

#include <iostream>
#include <string>
#include <cctype>

#include "RPSCore.h"

std::string input(std::string prompt="")
{
    std::string temp;
    std::cout << prompt;
    std::getline(std::cin, temp);
    return temp;
}

int main(int argc, char* argv[])
{
    char playerChoice = []() {
        std::string ret = "";
        do
        {
            ret = input("Your weapon >>> ");
            if (std::tolower(ret[0]) == 'r' || std::tolower(ret[0]) == 'p' || std::tolower(ret[0]) == 's') break;
        } while (1);
        return ret[0];
    }();
    char computerChoice = RPSCore::getComputerChoice();
    int winner = RPSCore::rpsWinner(playerChoice, computerChoice);
    std::cout << "Your choice: " << (playerChoice == 'r' ? "Rock" : playerChoice == 'p' ? "Paper" : "Scissors")  << " Computer's choice: " << (computerChoice == 'r' ? "Rock" : computerChoice == 'p' ? "Paper" : "Scissors") << " And " << (winner == 1 ? "You WIN!!!" : winner == 2 ? "Computer Wins :(" : "It's a draw :)");
    std::cin.get();
    return 0;
}


texts:
I have a working code, but it has a lot of flaws.

The main project is to get a value from a website. I need to complete this action million of times, so i download the webpage returned from the class method, and parse it afterwards. In case the page is already downloaded i just open that one up.

This code is working, however even with the multiple except socket.error i do sometimes get socket errors when running it in parallel.

Also i am kinda new to programming, so any advice would be really appreciated. (I know this code is kinda too long)

class Uniprot:
    """
    Gets the UNIPROT XML or HTML, very bad code.... Cant come up with a better one yet :(
    """

    def __init__(self, uniid):
        """
        Initialize stuff
        :param uniid: Same as in parent class
        :return:
        """
        self.uniid = uniid.upper()
        self.soup = ""

    def xml(self):
        """
        returns the full XML file
        :return:
        """
        xmlpage = urllib2.urlopen("http://www.uniprot.org/uniprot/%s.xml" % self.uniid, timeout=2)
        if xmlpage.getcode() != 200:
            return
        self.soup = BeautifulSoup(xmlpage)
        return self.soup.get_text

    def web(self):
        """
        Returns the full HTML file
        :return:
        """
        webpage = urllib2.urlopen("http://www.uniprot.org/uniprot/%s" % self.uniid, timeout=2)
        # UNIPROT error handler
        if webpage.getcode() != 200:
            return
        websoup = BeautifulSoup(webpage)
        return websoup.get_text

def uniprotannotation():
    """
    Chaos, and anarchy right again, same with the errors, plus its an HTML variable instead of an XML
    :return: Annotation score from UNIPROT
    """
    uniprotxml = ""
    soup = ""
    # Check if the folder is present
    if not os.path.isdir("%s/%s/UNIPROT" % (DATA_DIR, FASTA_OBJECT.organism())):
        os.makedirs("%s/%s/UNIPROT" % (DATA_DIR, FASTA_OBJECT.organism()))
    # Check if the file is present, if not create it
    try:
        f = open("%s/%s/UNIPROT/%s.html" % (DATA_DIR,
                                            FASTA_OBJECT.organism(), FASTA_OBJECT.accession()), "r")
        for i in f:
            uniprotxml += i
        f.close()
        # Check if the file is empty
        if os.stat("%s/%s/UNIPROT/%s.html" % (DATA_DIR,
                                              FASTA_OBJECT.organism(), FASTA_OBJECT.accession())).st_size == 0:
            os.remove("%s/%s/UNIPROT/%s.html" % (DATA_DIR,
                                                 FASTA_OBJECT.organism(), FASTA_OBJECT.accession()))
            sys.stderr.write(
                    "%s, removed empty html, running it again\n" % sys.argv[1])
            uniprotannotation()
        soup = BeautifulSoup(uniprotxml)
    except IOError:
        try:
            soup = BeautifulSoup(str(FASTA_OBJECT.Uniprot(sys.argv[1]).web()))
        except socket.timeout:
            sys.stderr.write(
                    "%s, HTML socket timeout, trying again\n" % sys.argv[1])
            uniprotannotation()
        except socket.error:
            sys.stderr.write(
                    "%s, HTML socket error, trying again\n" % sys.argv[1])
            uniprotannotation()
        f = open("%s/%s/UNIPROT/%s.html" % (DATA_DIR,
                                            FASTA_OBJECT.organism(), FASTA_OBJECT.accession()), "w")
        f.write(str(FASTA_OBJECT.Uniprot(sys.argv[1]).web()))
        f.close()
    if not soup:
        return "-"
    result = re.search("Annotation score: \d out of \d", str(soup.get_text))
    if not result:
        return "-"
    return re.search("\d", str(result.group())).group()[0]


texts:
I recently created Argyle, a small library for parsing command-line arguments in Scala. I'd be happy for anyone to take a look and provide general feedback on it. But there is also one specific issue that sparked some discussion when I posted on reddit, so I would be interested to hear the thoughts of folks here also. Basically, I have the following trait:

trait Arg[+A] {
  def parse(xs: List[String], mode: ArgMode): Try[A]
  def flatMap[B](f: A => Try[B]): Arg[B]
}

The idea is that an Arg[A] handles parsing (and potentially failing to parse) a list of strings into an A. The issue is over the name of the flatMap method. It's a useful method, for instance, converting an Arg[String] to Arg[Int] by .flatMap(s => Try(s.toInt)). But it's not a valid FP Monad flatMap since the parameter type is A => Try[B] and not A => Arg[B].

If you view Arg as a function List[String] => Try[A], then it is actually pretty identical to .andThen(_.flatMap(f)). But I don't know if there's a canonical FP name for an operation like this.

In my mind, pros of naming it flatMap:

Similar enough to other flatMap methods that it gives some immediate understanding of how it should function
Enables for-comprehension with chains of Trys and such, that work as expected

Cons:

Confusing for those who expect flatMap always implies monad, since Arg is not a monad.
Potentially confusing that for-comprehensions can't use chains of Args, but that seems nonsensical anyway, and probably shouldn't be allowed.

Any other thoughts, or suggestions for a better name? There is also a map method to deal with.


texts:
I've been thinking about it for a while and, after asking a question on vi.stackexchange, I decided to write a small plugin myself and put it on GitHub; basically it offers a mapping to activate a kind of "window movement" mode where Vim waits for inputs that it appends to Ctrl+w, so that one does not have to press this combination before every window-related movement or action; hitting Esc exits this mode.
It's mostly just one main function and one mapping, so I will copy them below.

The mapping plus some things I copied from scratch.vim which seemed reasonable:

" plugin/winzoz.vim

if (exists('g:winzoz_disable') && g:winzoz_disable) || &compatible
  finish
endif

nnoremap <silent> <Plug>(go-zoz-navigation) :call winzoz#goZoZ()<cr>

if !exists('g:winzoz_no_mappings')
  nmap <silent> <leader>w <Plug>(go-zoz-navigation)
endif

The function with the logic (plus a helper function for coloring the command line while the functionality is active)

" autoload/winzoz.vim

function! winzoz#goZoZ()
  redrawstatus!
  echohl Search
  echo s:make_status_line()
  echohl None
  let l:key = ''
  while l:key !=? "\<Esc>"
    let l:key = nr2char(getchar())
    execute "normal! \<c-w>" . l:key
    redrawstatus!
  endw
  echo ''
  redrawstatus!
endfunction

" drawing function
function! s:make_status_line()
  let l:text = 'Go WinZoZ'
  let l:text .= repeat(' ', (&columns - len(l:text))/2)
  return repeat(' ', &columns - len(l:text) - 1) .  l:text
endfunction

I'd like some feedback in general, but also on the following points.

As regards the logic, I'm not checking that the input is correct (with a :try-:catch-:finally), because I'm not inventing any functionality, but only forwarding the keys to the already existing functionality of Ctrl+w+whatever.
I'm using echohl Search + echo to print a colored command line to make apparent when the mode is active; is this a good way of doing it?

Regarding this part, I had to make a trick (the - 1 in the second to last line of code above) in order to have one character left for the blinking cursor. I really don't like this, but I don't know what else I could do...

There are some Ctrl+w-commands that take two key strokes, but my plugin cannot deal with them :( ... I'll fix when I have time.
Do you like it?
Do you think it could be useful?

(I also plan to add some documentation to it, fwiw :/ )


texts:
This is a program for converting Roman numerals to their decimal equivalents. There must be a better way of distinguishing between, for example, 'IV' and 'VI', than what I have currently written.

#include <iostream>
#include <string>
using namespace std;

class romanType{
public:
    romanType();
    romanType(string s);
    ~romanType();

        void setRoman(string); //Set the Roman numeral from user entries.
        int romanToDecimal(); //Convert the Roman numeral(string) to Decimal value.
        void printDecimal(); //Display the decimal value.
        void printRoman(); //Display the Roman numeral value.
private:
    string romanNum;
    int decimalNum = 0;

};

romanType::romanType()
{
    romanNum = 1;
}

romanType::~romanType()
{
}

void romanType::setRoman(string troll)
{
    romanNum = troll;
}

int romanType::romanToDecimal()
{
    for (int i = 0; i < romanNum.length(); i++)
    {
        if (romanNum[i] == 'I')
            decimalNum++;
        if (romanNum[i] == 'V')
        {
            if (i > 0 && romanNum[i - 1] == 'I')
                decimalNum -= 2;
            decimalNum += 5;
        }
        if (romanNum[i] == 'X')
        {
            if (i > 0 && romanNum[i - 1] == 'I')
                decimalNum -= 2;
            decimalNum += 10;
        }
        if (romanNum[i] == 'L')
        {
            if (i > 0 && romanNum[i - 1] == 'X')
                decimalNum -= 20;
            decimalNum += 50;
        }
    }
    cout << decimalNum << endl;
    return decimalNum;
}

int main()
{
    string numerals;
    do{
        cout << "Enter roman numerals: ";
        cin >> numerals;

        romanType Rom;
        Rom.setRoman(numerals);
        Rom.romanToDecimal();

    } while (true);
    system("PAUSE");

}

Sample output:

Enter roman numerals: IX
9
Enter roman numerals: XI
11
Enter roman numerals: XIX
19
Enter roman numerals: XX
20
Enter roman numerals: LVIII
58
Enter roman numerals: LXXXVIII
88
Enter roman numerals: LXVI
66
Enter roman numerals: LXIV
64
Enter roman numerals:


texts:
I have fairly simple Python 3 code that creates a DFA from a string.

It works great, but I believe it can be made more efficient. There are a total of 3 loops:

First iterates over the string
Second iterates the alphabet the string can be composed from. In this scenario it is always length 26. The standard English alphabet.
Third iterates over the string again

From what I believe, I can only break out of the third loop and only if a prefixed string is found.

My comments provide a good explanation of what I am doing in the code.

def create_from_text(self, text):
    """
        Create/edit the DFA from the provided text
    """

    # We start by editing the first state to accept the first character in
    # the text provided. After that we check the next character and create
    # a new state that goes to the 2nd character. Here we check if a
    # character that does not go to the 2nd character will create a prefix
    # of the text in combination with an any number of characters preceeding
    # it that . e.g. (oopoops)
    #       oo -> o     We want a `p` but got `o`.
    #                   But we check if, starting with 2nd character, `o`,
    #                   any combination after that, appended with the bad
    #                   character creates a prefix of the text. The first
    #                   found will always be the best match.
    #                   `oo` is a prefix of `oopoops` so we can start back
    #                   at index 2 since `oo` is of length 2. We mark the
    #                   state we are on with that state at that character.

    self.states[0].transitions[text[0]] = 1
    for i in range(len(text)):
        if i == 0:
            continue
        new_state = State(i)
        for j in self.alphabet:
            if j == text[i]:
                # Easiest part, just set the transition to the next state
                new_state.addTransition(i + 1, j)
            else:
                # Now do that check we spoke of earlier
                found = False
                for k in range(len(text)):
                    if k == 0:
                        continue
                    try:
                        if text.index(text[k:i] + j) == 0 and k <= i:
                            new_state.addTransition(len(text[k:i] + j), j)
                            found = True
                            break
                    except ValueError:
                        pass

                if not found:
                    new_state.addTransition(0, j)

        self.states.append(new_state)

    # Make every transition in the last state point to itself
    last_state = State(len(self.states))
    for j in self.alphabet:
        last_state.addTransition(len(self.states), j)
    self.states.append(last_state)

A sample output for string oopoops:

Number of states: 1
Accepting states: 0
Alphabet: abcdefghijklmnopqrstuvwxyz
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 3 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 6 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 7 0 0 0 0 0 0 0
7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7

Run time on a string of 2048 characters was about 5 minutes.


texts:
I am currently working on implementing some data structures as a way to learn C++. I'm coming mostly from a Java background so I was hoping to get some feedback regarding this implementation of a singly linked list in C++ using templates. This singly linked list will only support insertions at the head and tail positions and deletions from the head position. The plan is to use this as a base to build further data structures. I would like to create a rather complete library of data structures, so I was hoping to make them as extensible and reusable as possible.

Below follows the class definition.

#ifndef LINKEDLISTS_SINGLYLINKEDLIST_H_
#define LINKEDLISTS_SINGLYLINKEDLIST_H_

#include <cstddef>
#include <iostream>

template <typename E>
class SinglyLinkedList {

private:

    /** BEGIN NESTED NODE CLASS **/
    class Node {

    private:
        E data; //Should this be a reference?
        Node* next;

    public:
        Node(Node* n, const E& d) : data(d), next(n) {};

        Node* getNext() const { return next; }

        E& getData() { return data; }

        void setNext(Node* n) { next = n; }

    }; /** END NESTED NODE CLASS **/

    /** Begin fields of SinglyLinkedList class **/
    Node* head;
    Node* tail;
    int listSize;
    /** End fields of SinglyLinkedList class **/

public:

    SinglyLinkedList();
    ~SinglyLinkedList();

    //Accessor methods
    bool isEmpty() const;
    int size() const;
    const E& first() const;
    const E& last() const;

    //Update methods
    void addFirst(const E&);
    void addLast(const E&);
    E* removeFirst();

    void print() const;

}; /** END SINGLYLINKEDLIST CLASS HEADER **/

#include "SinglyLinkedList.tpp" //Include implementations of template code.

#endif /* LINKEDLISTS_SINGLYLINKEDLIST_H_ */

The implementations of the functions follow below:

/*
 * SinglyLinkedList.tpp
 *
 *  Created on: Jan 5, 2020
 *      Author: dii
 */

/** Constructor **/
template<typename E>SinglyLinkedList<E>::SinglyLinkedList() : head(nullptr), tail(nullptr), listSize(0) {}

/** Destructor **/
template<typename E>SinglyLinkedList<E>::~SinglyLinkedList() {
    while(!isEmpty()) {
        delete removeFirst();
    }
}

/** Begin functions **/

template<typename E> bool SinglyLinkedList<E>::isEmpty() const { return listSize == 0; }

template<typename E> int SinglyLinkedList<E>::size() const { return listSize; }

template<typename E> const E& SinglyLinkedList<E>::first() const { return head->getData(); }

template<typename E> const E& SinglyLinkedList<E>::last() const { return tail->getData(); }

template<typename E> void SinglyLinkedList<E>::addFirst(const E& d) {

    Node* temp = new Node(head->getNext(), d); //Create a new node.
    head = temp; // Set the head pointer to point to this object.
    listSize++; // Increase size of list by 1.

}

template<typename E> void SinglyLinkedList<E>::addLast(const E& d) {

    Node* temp = new Node(nullptr, d);
    if(isEmpty()) {
        head = temp;
        tail = temp;
    } else {
        tail->setNext(temp);
        tail = temp;
    }

    listSize++;

}

template<typename E> E* SinglyLinkedList<E>::removeFirst() {

    if(isEmpty()) {
        return nullptr;
    }

    E* temp = &(head->getData());
    head = head->getNext();
    listSize--;

    return temp;

}

template<typename E> void SinglyLinkedList<E>::print() const {
    Node* walk = head;
    while(walk != nullptr) {
        std::cout << walk->getData() << std::endl;
        walk = walk->getNext();
    }
}

I have a feeling that the destructor is not implemented as well as it could be. I am also still not entirely sure about when to use references, e.g., should the data field of the Node class be of type E& or is just E ok?


texts: Creating two dictionaries to lookup values into an array

texts:
In my attempt to help improve Using Array to store calculations in VBA, I figured a good way to do it would be to create two dictionaries of values to lookup.

So this was my attempt at creating two dictionaries from two sheets and then gathering data from a third sheet into an array and looking up the items in the array based on a condition as to which dictionary to use.

My sample is pretty small and the last line of printing was just to see it worked. I actually struggled with this for a little while, so I'm thinking there are some improvements to be made. Also - is this sufficiently made to be scaled up to millions of data points? What about more than one dictionary - should that be refactored? What if there are more criteria needed for the lookup?

Option Explicit

Public Sub ArrayLookupAndPopulate()
    Dim firstTable As Object
    Set firstTable = CreateObject("Scripting.Dictionary")
    Dim secondTable As Object
    Set secondTable = CreateObject("Scripting.Dictionary")
    Dim rowNumber As Long
    Dim myKey As String
    Dim lookupArray As Variant
    Dim myIndex As Long

    For rowNumber = 1 To 10
        firstTable.Add CStr(Sheet1.Cells(rowNumber, 1)), Sheet1.Cells(rowNumber, 3)
        secondTable.Add CStr(Sheet2.Cells(rowNumber, 1)), Sheet2.Cells(rowNumber, 3)
    Next

    Dim lastRow As Long
    lastRow = Sheet3.Cells(Rows.Count, "A").End(xlUp).Row
    Dim lastColumn As Long
    lastColumn = Sheet3.Cells(1, Columns.Count).End(xlToLeft).Column + 1

    ReDim lookupArray(1 To lastRow, 1 To lastColumn)
    lookupArray = Sheet3.Range(Cells(1, 1), Cells(lastRow, lastColumn))

    For myIndex = 1 To 9
        myKey = lookupArray(myIndex, 2)
        If lookupArray(myIndex, 1) = "First" Then lookupArray(myIndex, 3) = firstTable.Item(myKey)
        If lookupArray(myIndex, 1) = "Second" Then lookupArray(myIndex, 3) = secondTable.Item(myKey)
    Next

    Sheet3.Range("F1:H9") = lookupArray

End Sub

I don't want to edit the code, but I just realized I don't need to redim.


texts:
Following is a chunk of code from my class which generates PDF documents. I am refactoring my code and in the process I have created short methods. But I have to pass 'table i.e PdfPTable' to my methods again and again. How can I avoid this?

PdfPTable orgTable = new PdfPTable(2);
PdfPCell cell = null;
string orgName = dr["OrganizationName"].ToString();
cell = new PdfPCell(new Phrase(orgName, Heading1)) {Colspan = 2, BackgroundColor = BckColor, HorizontalAlignment = Element.ALIGN_CENTER };
orgTable.AddCell(cell);

AddOrganizationProfile(document, dr, orgTable);
OrganizationHeadOffice(document, dr, orgTable);
OrganizationContacts(document, orgTable, orgId);

private void OrganizationHeadOffice(Document document, DataRow dr, PdfPTable table)
{
    AddTitle("Office Contact & Information:", table);

    // How to avoid passing table variable again and again here.
    AddLegend("Address:", table);
    AddDataValue(dr["address"].ToString(), table);
    AddLegend("Contact Number:", table);
    AddDataValue(phone1, table);
}

private void AddTitle(string title, PdfPTable table)
{
    table.AddCell(new PdfPCell(new Phrase(title, TableFontCaption)) { Colspan = 2, BackgroundColor = BckColor });
}

private void AddLegend(string legend, PdfPTable table)
{
    table.AddCell(new PdfPCell() { Border = Rectangle.NO_BORDER, Phrase = new Phrase(legend, TableFontCaption) });
}

private void AddDataValue(string dataValue, PdfPTable table)
{
    table.AddCell(new PdfPCell() { Border = Rectangle.NO_BORDER, Phrase = new Phrase(dataValue, TableFont) });
}


texts:
Working from a CSV of about 14.000 lines, I need to match dates in the CSV against some API. I'm reading the CSV using Pandas (for various other reasons). Most often, the date is just a year, i.e. an integer, which Pandas converts to a float. Other date formats also occur (see main in the code below). 12-10-1887 is the 12th of October, not the 10th of December.

The API also returns date strings, often also incomplete, for example when only year but not month and/or day of birth are known. Single-digit days and months do get a leading zero, and format is as close to ISO-date as possible, e.g. March 1675 will be "1675-03".

I think my best bet is not to convert to type datetime, but to try to match strings.

EDIT: because this way I can let the API do more work.

http://baseURL/name:Gupta,Anil&date:1956

Without the date, I get all Anil Gupta's. With it, I get all Anil Gupta's with either born year (most likely), death year, of year of activity 1956. All in all, this is MUCH less work than writing dateconverters for fields that are empty in 90% of the cases. In general, name + exact date of birth is a pretty unique identifier.

So I wrote this dateclean.py (Python 3.7):

import re
from datetime import datetime as dt

def cleanup(date):
    patterns = [# 0) 1-12-1963
                r'(\d{1,2})-(\d{1,2})-(\d{4})$',
                # 1) 1789-7-14
                r'(\d{4})-(\d{1,2})-(\d{1,2})$',
                # 2) '1945-2'
                r'(\d{4})-(\d{1,2})$',
                # 3) 2-1883
                r'(\d{1,2})-(\d{4})$'
                ]

    try:
        return str(int(date))
    except ValueError:
        pass

    for pat in patterns:
        q = re.match(pat, date)
        if q:
            if pat == patterns[0]:
                year = re.sub(patterns[0], r'\3', date)
                month = re.sub(patterns[0], r'\2', date)
                day = re.sub(patterns[0],  r'\1', date)
                return '{0}-{1:0>2}-{2:0>2}'.format(year, month, day)
            if pat == patterns[1]:
                year = re.sub(patterns[1], r'\1', date)
                month = re.sub(patterns[1], r'\2', date)
                day = re.sub(patterns[1],  r'\3', date)
                return '{0}-{1:0>2}-{2:0>2}'.format(year, month, day)
            if pat == patterns[2]:
                year = re.sub(patterns[2], r'\1', date)
                month = re.sub(patterns[2], r'\2', date)
                return '{0}-{1:0>2}'.format(year, month)
            if pat == patterns[3]:
                year = re.sub(patterns[3], r'\2', date)
                month = re.sub(patterns[3], r'\1', date)
                return '{0}-{1:0>2}'.format(year, month)
            else:
                return date

def main():
    dates = 1858.0, '1-12-1963', '1945-2', '7-2018', '1789-7-14',
    for date in dates:
        print('in: {}  out: {}'.format(date, cleanup(date)))

if __name__ == "__main__":
    main()

The list dates in main() contains all formats known until now. On the plus side, by using this method, adding new formats is easy.

There are a lot of patterns[x], which is not at all DRY, yet I don't see how I can avoid that: I have to split each input string into year, month and day, if any (using r'\1' etc.)

Also, I know flat is better than nested, but I don't see how I can improve on that. I do try to return as early as possible.

Readability is more important to me than performance, because the API is a bottleneck anyway. Then again, serious slowing-downers should be avoided.


texts: Datagrid not refreshing correctly with Async Ping VB .Net

texts:
I have an application coded in VB.NET that has a bunch of servers in a DataGridView and does a continuous asynchronous ping.  If all the servers are up it refreshes great, but if one goes down and starts to time out it takes about 5-10 seconds before the program starts responding again.  This program needs to ping all the servers at the same time.
I need help with improving the performance of this code.

Private Sub cmdStartPing_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStartPing.Click

    Dim rc, myic As Integer
    Dim sname As String
    'Dim preply As PingReply

    pinging = 1
    cmdStopPing.Select()
    rc = DGV1.RowCount - 1

    If rc > -1 Then

        bCancel = False

        Do Until bCancel = True

            For myic = 0 To rc

                Application.DoEvents()

                If bCancel Then
                    bCancel = True
                    DGV1.BackgroundColor = Color.White
                    MsgBox("Pinging Stopped")
                    Exit For

                End If

                Try
                    sname = DGV1.Item(0, myic).Value

                    PingHost(sname)

                    If pingresults = "Success" Then
                        DGV1.Rows(myic).Cells(1).Value = "Success"
                        DGV1.Rows(myic).Cells(2).Value = roundtriptime
                        DGV1.Rows(myic).DefaultCellStyle.BackColor = Color.YellowGreen
                        DGV1.Refresh()
                    Else
                        DGV1.Rows(myic).Cells(1).Value = "No Reply"
                        DGV1.Rows(myic).Cells(2).Value = "Timed Out"
                        DGV1.Rows(myic).Cells(3).Value = currentdt
                        DGV1.Rows(myic).DefaultCellStyle.BackColor = Color.Red
                        DGV1.Refresh()
                    End If

                Catch ex As Exception
                    DGV1.Rows(myic).Cells(1).Value = "No Reply"
                    DGV1.Rows(myic).Cells(2).Value = "Timed Out"
                    DGV1.Rows(myic).Cells(3).Value = currentdt
                    DGV1.Rows(myic).DefaultCellStyle.BackColor = Color.Red
                    DGV1.Refresh()

                End Try

            Next

        Loop

    Else
        MsgBox("Please add at least one host to the datagrid to ping.")
    End If

End Sub

Stop ping:

Private Sub cmdStopPing_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStopPing.Click
    bCancel = True
    pinging = 0
End Sub

Uses this function to ping:

Imports System.Net.NetworkInformation
Module AsyncPingHost
'Function PingIPAdress(ByVal IPAdress As String)
Function PingHost(ByVal host As String)
    Dim ping As Ping
    Dim preply As PingReply
    ping = New Ping

    Try
        preply = ping.Send(host)
        roundtriptime = preply.RoundtripTime
        If preply.Status = IPStatus.Success Then
            pingresults = "Success"
        Else
            pingresults = "Failed"

        End If
    Catch ex As Exception
        pingresults = ex.Message
    End Try

End Function


texts:
I've written some jQuery for my navbar, but it's super sloppy and I'm always trying to write better code.

$(function(){
    $(window).scroll(function(){
    var sT = $(this).scrollTop();
    if (sT >= 70) {
        $('.navbar').addClass('navbar-switch')
        $('.navbar .scroll-link').addClass('navbar-link-switch')
        $('.navbar .logo').addClass('logo-adjust')
        $('.navbar hr').addClass('hide')
        $('.navbar .navbar-collapse').addClass('border')
    } else {
        $('.navbar').removeClass('navbar-switch')
        $('.navbar .scroll-link').removeClass('navbar-link-switch')
        $('.navbar .logo').removeClass('logo-adjust')
        $('.navbar hr').removeClass('hide')
        $('.navbar .navbar-collapse').removeClass('border')
    }
    })
})

My goal is that, when the user scrolls pass a certain limit, my navbar removes certain classes and adds certain classes.


texts: Condense multiple if statements with or operators?

texts:
I created a weather widget in JavaScript that requests the current weather from Yahoo. The weather request returns a code which corresponds with a current weather image. I don't like Yahoo's images, so I use my own CSS classes that correspond with my own images. Consequently, the following code returns the correct CSS class which I then deal with later:

function returnClass(c) {
    if (c === "0" || c === "19" || c === "23" || c === "24") {
        return ["basecloud", "wind"];
    } else if (c === "1" || c === "2") {
        return ["basecloud", "rain"];
    } else if (c === "3" || c === "4" || c === "37" || c === "38" || c === "39" || c === "45" || c === "47") {
        return ["basecloud", "thunder"];
    } else if (c === "5" || c === "6" || c === "7" || c === "8" || c === "10" || c === "18") {
        return ["basecloud", "sleet"];
    } else if (c === "9") {
        return ["basecloud", "drizzle"];
    } else if (c === "11" || c === "12" || c === "40") {
        return ["basecloud", "rain"];
    } else if (c === "13" || c === "14" || c === "15" || c === "16" || c === "41" || c === "42" || c === "43" || c === "46") {
        return ["basecloud", "snow"];
    } else if (c === "17" || c === "35") {
        return ["basecloud", "hail"];
    } else if (c === "20" || c === "21" || c === "22") {
        return ["mist"];
    } else if (c === "25") {
        return ["basecloud", "frost"];
    } else if (c === "26" || c === "27" || c === "29" || c === "33" || c === "28" || c === "30" || c === "34" || c === "44") {
        return ["cloud"];
    } else if (c === "31") {
        return ["moon"];
    } else if (c === "32" || c === "36") {
        return ["sun"];
    } else if (c === "3200") {
        return ["none"];
    }
}

Is there any way to simplify the above code? As you can tell, multiple codes can represent the same CSS class, which is why I have so many or operators. The only requirement is that it returns the correct array depending on the code.


texts:
My starting point is a file like so:

# Default environment to run the app locally.
# In production, the app will probably run on NginX,
# which will act as a reverse proxy
export NODE_ENV='development'
export APPNAME='gigsnet'
export DBHOST='192.168.1.13'
export DBNAME='gigsnet-development'
export IPADDRESS='localhost'
export PORT='8080'

This is a simple bash file that sets and exports some environment variables.
I want some nodeJs scripts to use the same file to set the same variables. The idea is to require this file, and have process.env magically enriched.

So, I wrote this:

var fs = require('fs')
var p = require('path')

fs.readFileSync(p.join(__dirname, 'localEnv.sh')).toString().split('\n').forEach(line => {
  var tokens = line.split(' ')
  if (tokens[0] === 'export') {
    var [ name, value ] = tokens[1].split('=')
    process.env[name] = value.match(/["'](.*?)["']/)[1]
  }
})

Problems I have:

That first line is way too long for my own likings
The variable token could and should have a better name

Looks clunky.

How would you improve it?


texts: ArrayBlockingQueue in which queue head is removed if the queue is full while adding an element

texts:
I am trying to write a simple queue like ArrayBlockingQueue in which the head of the queue will be removed if the queue is full while adding an element. The class should just have the below public methods

To get the size of the Queue
To get an element from the head of the queue
To add an element at the tail of the queue

Can someone review the below code and let me know if there is a better way of doing this?

public class CircularArrayNonBlockingQueue<E> {
    private ArrayBlockingQueue<E> blockingQueue;

    public CircularArrayNonBlockingQueue(int size) {
        blockingQueue = new ArrayBlockingQueue<>(size);
    }

    public synchronized int size() {
        return blockingQueue.size();
    }

    public synchronized void add(E element) {
        if(blockingQueue.remainingCapacity() <= 0) {
            blockingQueue.poll();
        }
        blockingQueue.add(element);
    }

    public synchronized E poll() {
        return blockingQueue.poll();
    }
}


texts:
I was trying to solve one of the hackerrank practice questions. Could anyone please let me know how can I make this code much effective, in terms of time and space complexity?

  The Super Bowl Lottery is about to commence, and there are several
  lottery tickets being sold, and each ticket is identified with a
  ticket ID. In one of the many winning scenarios in the Superbowl
  lottery, a winning pair of tickets is:

  Concatenation of the two ticket IDs in the pair, in any order,
  contains each digit from 0 to 9 at least once.

  For example, if there are 2 distinct tickets with ticket ID 12930455 and 56789, (129300455, 56789) is a winning pair.

  NOTE: The ticket IDs can be concantenated in any order. Digits in the
  ticket ID can occur in any order.

  Your task is to find the number of winning pairs of distinct tickets,
  such that concatenation of their ticket IDs (in any order) makes for a
  winning scenario. Complete the function winningLotteryTicket which
  takes a string array of ticket IDs as input, and return the number of
  winning pairs.

  Input Format

  The first line contains n denoting the total number of lottery tickets
  in the Super Bowl. Each of the next n lines contains a string, where
  string on a ith line denotes the ticket id of the ith ticket.

  Constraints

  [1 ≤ pretty much everything  input ≤ 10⁶]
  Each ticket id consists of digits from [0, 9]

  Output Format

  Print the number of pairs in a new line.

  Sample Input

5
129300455
5559948277
012334556
56789
123456879

  Sample Output

5

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    static Long winningLotteryTicket(String[] tickets) {
        int count = 0;
        for(int i = 0 ; i < tickets.length-1 ; i++) {
            for(int j = i+1 ; j < tickets.length ;j++ ){
               if(!(tickets[i]).equals(tickets[j]) && getStatus(tickets[i],tickets[j])){
                   count++;
               }
            }
        }
        return Long.valueOf(count);
    }

    public static boolean getStatus(String a, String b){
        String c = a+b;
        if(c.length() < 10){
            return false;
        }
        Set<Character> charSet = new HashSet<>();
        char[] arr = c.toCharArray();
        for(int i = 0; i < arr.length; i++){
            charSet.add(arr[i]);
        }

        if (charSet.size() == 10){
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        String[] tickets = new String[n];
        for(int tickets_i = 0; tickets_i < n; tickets_i++){
            tickets[tickets_i] = in.next();
        }
        Long result = winningLotteryTicket(tickets);
        System.out.println(result);
        in.close();
    }
}


texts: replace digit at some positions in number

texts:
I'm trying to write function, that replace digits at some positions in number.

For example f 91521 [3,4] -> [91001,91111,91221,91331,91441,91551,91661,91771,91881,91991]

It's behavior like 91**1 -> ..., so I named it as a 'whitemask'.

Question 1: is "whitemask" a normal and adequately name for that function?

After that I've formulated that 'whitemask' function.

sublists :: (Eq a) => [a] -> [[a]]
sublists list = [x | x <- subsequences list, x /= []]

numbers :: [Int]
numbers =  take 10 [0..]

numLength :: Integer -> Int
numLength = length . show

decreaseList :: Num a => [a] -> a -> [a]
decreaseList = (\a b c -> map (a c) b) (flip (-))

listToNum :: [Int] -> Integer
listToNum digits = toInteger $ foldl1 (\x y -> x*10 + y) digits

numToList :: Integer -> [Int]
numToList x = map digitToInt $ show x

remove :: [Int] -> [Int] -> [[Int]]
remove [] x = [x]
remove (x:xs) list = putted : remove (decreaseList xs x) unputted
    where [putted,unputted] = (\(x,y) -> [init x,y]) $ splitAt x list

sew :: [[a]] -> a -> [a]
sew list sewer = foldr1 (\x y -> x ++ [sewer] ++ y) list

whitemask :: Integer -> [Int] -> [Integer]
whitemask num places =  filter (\x -> numLength x == numLength num ) $ map (listToNum . sew (remove places (numToList num))) numbers

But in context of all problem where that function might be used I figured out, that I need only fix-length answers. For examples, it works like

> whitemask 75148 [1,3,4]
[15118,25228,35338,45448,55558,65668,75778,85888,95998]

and answer isn't contain '5008' element.

Question 2: is that fix-length filtering 'whitemask' function's business? Or it would be better to return all possible variants and filtering them if it really needed?

When I've started to use that function in complicated iterates ways I figured out that it's might do some unnecessary and superfluous calculations.

Question 3: how can I refactor 'whitemask' function with less-usage folds maps and recursions?

Any cosmetics and style advices are appreciated.

ps: did I select the right place to asking for? (question could be migrated to SO actually)

UPD:
I figured out that sew can be written much easier.

sew list sewer = concat $ intersperse [sewer] list


texts: Calculating relative strength index over a period

texts:
I'm looking for a review on my code. I am also looking for ways to transform this function into something more Pythonic. I'm fairly new to Python, so any advice would be appreciated.

def get_rsi(self, period):
    rsi = []

    for i in xrange(1, len(self.hist_d) - period + 1):
        gains = 0.0
        losses = 0.0

        for j in xrange(i, i + period):
            diff = self.hist_d[j][2] - self.hist_d[j - 1][2]

            if diff > 0:
                gains += diff
            elif diff < 0:
                losses += abs(diff)

        rsi.append(round(100 - (100 / (1 + gains / losses)), 2))

    return rsi


texts: generating stochastic coloured noise for many oscillators

texts:
I have a system of n oscillators which oscillate with time. To each of these oscillators I am adding a fluctuating coloured noise term with a different seed for each oscillator. Here is my code for the generation of this noise:
#include <math.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <iostream>
#include <random>

using namespace std;

double dt = 0.01;

static normal_distribution<double> n_dist(0 , sqrt(dt));
static random_device rd;
static default_random_engine generator(rd());

static double dW ( double dt ) {
    return n_dist(generator);
}

void exp_noise(double gamma, int steps, double c_sigma, float X[])
{
    X[0] = 1;

    for (int i = 0; i < steps; i++ ){
        X[i+1] = (1 - gamma) * X[i] + c_sigma * sqrt(2*gamma) * dW(1);
    }
}

int main()
{
    int n = 256;
    constexpr int steps = 1000;

    float X[n*steps];
    for( int i=0 ; i<n ; ++i ){
        float X_i[steps];
        memset(X_i, 0.0, sizeof X_i);
        exp_noise(0.4, steps, 1, X_i);
        for( int j=0 ; j<steps ; ++j ){cout << X_i[j] << '\n';}
        memcpy( X + i*steps, X_i, sizeof( X_i ) );
    }

    cout << "total vector is" << '\n';
    for( int i=0 ; i<n*steps ; ++i ){cout << X[i] << '\n';}

    return 0;
}

Essentially my code is producing something similar to an array of noise for each oscillator, and then appending all of those arrays together. The intention is to apply to above code to my oscillators in the following way.
for (int h = 0; h < steps; ++h){
    for( int i=0 ; i<n ; ++i ){
        oscillator[i] = stoch_runge_kutta( oscillator[i], X[ h + i*steps ], ... )
    }
}

This code seems to work well for a small number of steps. This code unfortunately breaks down however for values of n * steps > 2500000 with a stack overflow error. So my first question would be whether the code can be made more stable to the value of n*steps with some minor changes, or whether I need to change everything by using vectors instead? I would also be interested in knowing whether the code would be faster or more elegant if I completely redesigned the code in some other way, for example by not creating an array of arrays, and doing something else instead? How would these things be done? It's not essential, but it's preferable to have the noise as an array so that it can be reused to for other things.
Any help would be greatly appreciated.


texts:
This is my second script in my first language so I'm trying to get oriented and better foundations. I noticed in the while loop I got really messy but I couldn't google my way to a better solution that I could understand. With that, I'd appreciate any feedback that makes my code more "pythonic" or clean.

import random

def card_deck():
    card_faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
    card_suits = ['♠', '♦', '♥', '♣']
    deck = []
    for i in card_suits:
        for j in card_faces:
            deck.append(j + ' ' +  i)
    return deck

def card_draw(deck):
    random.shuffle(deck)
    deck = deck.pop()
    return deck

def card_value(card):
    card = str(card)
    if card[0] == 'J':
        return 10
    elif card[0] == 'Q':
        return 12
    elif card[0] == 'K':
        return 13
    elif card[0] == 'A':
        return 14
    else:
        card = int(card[0:2])
        return card

correct_guesses = 0
deck = card_deck()
card = card_draw(deck)

while True:
    card_points = card_value(card)
    if not deck:
        print("You've done it! You've won with", correct_guesses, "correct guesses!")
        break
    next_card = card_draw(deck)
    next_card_points = card_value(next_card)
    print("\nYou're card is: ", card)
    user_guess = input('\n(H)igher, (L)ower, or (S)ame?:\t')
    user_guess = user_guess.lower()
    if user_guess not in ('h', 'l', 's'):
        break
    if card_points < next_card_points and user_guess == 'h':
        print("Correct!")
        correct_guesses += 1
        card = next_card
        continue
    elif card_points > next_card_points and user_guess == 'l':
        print("Correct!")
        correct_guesses += 1
        card = next_card
        continue
    elif card_points == next_card_points and user_guess == 's':
        print("Correct!")
        correct_guesses += 1
        card = next_card
        continue
    else:
        print('You lose the next card was ', next_card)
        print('You had', correct_guesses, 'correct guesses.')
        break
```


texts: Checking if any permutation of a string can make it palindrome

texts:
I was writing code to check if any permutation of a string can make it palindrome and came up with the following logic:

anagram = [ x for x in input() ]
count_alphabets = [ anagram.count(x) for x in set(anagram) ]
middle_element = [x for x in count_alphabets if x % 2 == 1]
print("YES") if len(middle_element) == 0 or len(middle_element) == 1 else print("NO")

The logic is to count the number of times each character appears. ONLY one or none of the characters can appear odd number of times.

The above logic works fine and passes all test cases. Is there a better logic for this?


texts:
I've decided to code Perlin noise generator in Java. It works pretty well, I just want to know If I am doing everything right and if it is a valid implementation!

PS : The metaVector2f and metaVector2i are just 2D vector classes

public float[][] generate(long seed, metaVector2i size, metaVector2i gridSize) {
    Random rand = new Random(seed);
    metaVector2f[][] gvectors = new metaVector2f[gridSize.x][gridSize.y];

    for (int y = 0; y < gridSize.y; y++)
        for (int x = 0; x < gridSize.x; x++)
            gvectors[x][y] = new metaVector2f(rand.nextFloat(),rand.nextFloat());

    float[][] data = new float[size.x][size.y];

    for (int y = 0; y < size.y; y++)
        for (int x = 0; x < size.x; x++) {
            data[x][y] = perlinPoint(new metaVector2f(x/(float)(size.x/gridSize.x),y/(float)(size.y/gridSize.y)), gvectors);
        }

    return data;
}

private float perlinPoint(metaVector2f position, metaVector2f[][] gvectors) {

    int x0 = (int)position.x;
    int y0 = (int)position.y;
    int x1 = (int)position.x+1;
    int y1 = (int)position.y+1;

    float dx0 = position.x-x0;
    float dy0 = position.y-y0;

    float dx1 = position.x-x1;
    float dy1 = position.y-y1;

    float h1 = dotProduct(new metaVector2f(dx0, dy0), gvectors[x0%gvectors.length][y0%gvectors[0].length]);
    float h2 = dotProduct(new metaVector2f(dx1, dy0), gvectors[x1%gvectors.length][y0%gvectors[0].length]);
    float fin1 = lerp(h1, h2, dx0);

    float v1 = dotProduct(new metaVector2f(dx0, dy1), gvectors[x0%gvectors.length][y1%gvectors[0].length]);
    float v2 = dotProduct(new metaVector2f(dx1, dy1), gvectors[x1%gvectors.length][y1%gvectors[0].length]);
    float fin2 = lerp(v1, v2, dx0);

    return lerp(fin1,fin2,dy0);

}

private float lerp(float x, float y, float t) {
    return (1.0f - t)*x + t*y;
}

private float dotProduct(metaVector2f vec, metaVector2f grad) {
    return vec.x*grad.x+vec.y*grad.y;
}

Here is the output (value/2+0.5f) :


texts:
We've developed an ESLint rule to determine if a tag name used inside the Protractor's by.tagName() locator is valid.

  A Tag Name is considered valid when:

  It can contain alphanumeric characters.
  It can contain the dash(-) symbol.
  It cannot start with dash or a number.
  It cannot end with dash.

The Code:

'use strict'

var isTagName = /^[A-Za-z][A-Za-z0-9-]*$/

module.exports = {
  meta: {
    schema: []
  },

  create: function (context) {
    return {
      'CallExpression': function (node) {
        var object = node.callee.object
        var property = node.callee.property

        var insideByTagName = object && property && object.name === 'by' && property.name === 'tagName'
        var argumentExists = node.arguments && node.arguments.length && node.arguments[0].value

        if (insideByTagName && argumentExists) {
          var tagName = node.arguments[0].value
          if (!tagName.match(isTagName) || tagName.endsWith('-')) {
            context.report({
              node: node,
              message: 'Invalid TagName value: "' + tagName + '"'
            })
          }
        }
      }
    }
  }
}

Is it possible to decrease nested-ness and improve on readability?

FYI, using standard JS code style.


texts: Image Compression Using the Singular Value Decomposition (SVD) with MATLAB

texts:
I'm new to both linear algebra and MATLAB.
I need help with this code with the objective of compressing image using the Singular Value Decomposition (SVD).
The code is currently working, if I run with e.g sigma_threshold = 10, I get a blurry picture, if I set it to 100 it's even more blurry etc.

I have searched all over the web and found a lot of similiar examples that I have used to improve this code with, but still I know I can do it a lot more elegant.

One problem is that I dont fully understand the math behind what I'm doing, and thus I don't know really know what to do, particularly with the matrices U and V in [U S V] = svd(A).

Wondered if someone could give me a hint how to improve the sections under the comments
"%Find the first index smaller than sigma_threshold" and "%Compose the red, green and blue channel again until the sigma value"

function svd_exercise(imagename,sigma_threshold)

image = imread(imagename);
image = im2double(image);

%Decompose the image in rgb values
R = image(:, :, 1);
G = image(:, :, 2);
B = image(:, :, 3);

%Compute the Single Value decomposition for each channel
[U_R, S_R, V_R] = svd(R);
[U_G, S_G, V_G] = svd(G);
[U_B, S_B, V_B] = svd(B);

%Find the first index smaller than sigma_threshold
[red_j, ~] = find(S_R > 0 & S_R < sigma_threshold, 1);
[green_j, ~] = find(S_G > 0 & S_G < sigma_threshold, 1);
[blue_j, ~] = find(S_B > 0 & S_B < sigma_threshold, 1);

%Compose the red, green and blue channel again until the sigma value
R_K = U_R(:, 1:red_j) * S_R(1:red_j, 1:red_j) * V_R(:, 1:red_j)';
G_K = U_G(:, 1:green_j) * S_G(1:green_j, 1:green_j) * V_G(:, 1:green_j)';
B_K = U_B(:, 1:blue_j) * S_B(1:blue_j, 1:blue_j) * V_B(:, 1:blue_j)';

AK = zeros(size(image));
AK(:,:,1) = R_K;
AK(:,:,2) = G_K;
AK(:,:,3) = B_K;