texts: Load content from files (and sometimes parse) in Sapper

texts:
I am making my first Sapper app and the pages are all in routes. I am now extracting the content into a separate directory and unsure if I'm doing anything right.

Here is an excerpt from my directory structure:

content
|- index.md
|- services.txt
|- about
   |- index.md
   |- technologies.html
routes
|- index.html
|- services.html
|- section-[section].json.js
|- about
   |- index.html
   |- technologies.html

I've made JSON interface section-[section].json.js that is used to request content. The content of sectionX can be in file content/sectionX.ext with whatever extension and the content is also parsed through marked if it's a .md file.

This is how I am loading the content in my routes/services.html:

<script>
export default {
    preload() {
        return this.fetch('section-services.json').then(r => r.json()).then(section => {
            return {section};
        });
    }
}
</script>

Nested files are requested using dot notation, i.e. about.technologies could be resolved either to file content/about/technologies.ext or content/about/technologies/index.ext (similar to how sapper resolves URIs to files).

The part that I would like to have reviewed is my routes/section-[section].json.js. This is the file that receives a section name (with slashes replaced by dots) and returns the content, parsed if it's markdown.

import fs from 'fs'
import path from 'path'
import marked from 'marked'

function getFileFromDir(file, directory)
{
    const filesInDir = fs.readdirSync('content/'+directory, {withFileTypes: true})
                        .filter(f => f.isFile() && file == path.parse(f.name).name)

    if (filesInDir.length)
    {
        let fileName = 'content/'

        if (directory.length)
            fileName += directory + '/'

        fileName += filesInDir[0].name

        return fileName
    }

    return null
}

function getFile(path)
{
    path = path.split('.')

    // First try to get the named file
    let file = getFileFromDir(path[path.length-1], path.slice(0,-1).join('/'))
    if (file)
        return file

    // Assume that path is a directory and look for index
    file = getFileFromDir('index', path.join('/'))
    if (file)
        return file

    return null
}

export function get(req, res) {
    let file = getFile(req.params.section)

    if (!file)
        return 'Failed to fetch content of section ' + req.params.section

    let content = fs.readFileSync(file, 'utf8')

    if ('.md' == path.extname(file))
        content = marked(content)

    res.writeHead(200, {
        'Content-Type': 'application/json',
        'Cache-Control': `max-age=${30 * 60 * 1e3}`
    })

    content = JSON.stringify({content})

    res.end(content)
}

My experience with Node is also fairly limited, all tips are appreciated!


texts:
After posting my original address book program I took the responses and edited my code. I have used every suggestion given, the code works great, and now I am looking for further review and suggestions from the Code Review community.

Parent class (Person):

//parent class
#ifndef PERSON
#define PERSON
#pragma once

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

class Person
{
public:
    //input person variable
    std::istream& read(std::istream&, Person &p1);
    //output person variable
    std::ostream& print(std::ostream& os, const Person &p1);
    //comparison operator
    bool operator<(const Person&) const;
private:
    std::string name;
    std::string address;
};

#endif

Person member functions:

#include "Person.h"

//input for address book person element
std::istream& Person::read(std::istream& in, Person &p1) {
    std::cin >> p1.name;
    std::cin.ignore();
    std::getline(std::cin, p1.address);
    return in;
}

//operator for address book person element
std::ostream& Person::print(std::ostream& os, const Person &p1) {
    os << "Name: " << p1.name << "\nAddress: " << p1.address << "\n\n";
    return os;
}

bool Person::operator<(const Person& other) const {
    return name < other.name;
}

Child class (Address Book):

//child class
#ifndef ADDRESS_BOOK
#define ADDRESS_BOOK
#pragma once

#include "Person.h"

class Address_book : public Person
{
    friend std::istream& operator>>(std::istream&, Address_book&);
    friend std::ostream& operator<<(std::ostream&, Address_book&);
public:
    //set vector size to match appropriate number of entries
    void num_of_ent(int, Address_book&);
    void Address_book::sort(Address_book&,int);

private:
    std::vector<Person> add_book;
};

#endif

Address book member functions:

#include "Address_book.h"

//sets vector size, creates person elements of vector
void Address_book::num_of_ent(int entries, Address_book& abook) {
    for (int i = 0; i < entries; ++i) {
            Person p;
        abook.add_book.push_back(p);
    }
}

//fills address book
std::istream& operator>>(std::istream& in, Address_book& abook) {
    for (int i = 0; i < abook.add_book.size(); ++i) {
        abook.add_book[i].read(in, abook.add_book[i]);
    }
    return in;
}

//sort address book
void Address_book::sort(Address_book& abook) {
    std::sort(abook.add_book.begin(), abook.add_book.end());
}
//prints contents of address book
std::ostream& operator<<(std::ostream& os, Address_book& abook) {
    for (int i = 0; i < abook.add_book.size(); ++i) {
        abook.add_book[i].print(os, abook.add_book[i]);
    }
    return os;
}

Main:

#include <iostream>
#include <vector>
#include <string>
#include "Address_book.h"
#include "Person.h"

void pause();

int main() {

    int entries = 0;

    std::cout << "Enter number of entries to go in addressbook: ";
    std::cin >> entries;

    Address_book abook1;
    abook1.num_of_ent(entries, abook1);

    //input into addressbook
    std::cout << "Enter the name, followed by the address:\n";
    std::cin >> abook1;
    //sort addressbook
    abook1.sort(abook1, entries);

    //output addressbook
    std::cout << "\n";
    std::cout << abook1;

    pause();
}

void pause() {
    std::string pause;
    std::cout << "Press any key followed by enter to continue...";
    std::cin >> pause;
}


texts: Find the longest connect cells region per color

texts:
I have been studying graphs/BFS/DFS. working on wrapping my head around the following problem

  Given a grid [m,n] where each cell has a value denotes a color, find the longest connected region that shares the same color (color is an int)

I was able to come up with the following algorithm that uses a (BFS) Breadth Search First mechanism. I would appreciate your feedback.

I also wanted to try and craft a solution using DFS. I know I might run into a stack overflow issues if the graph is too big. However, I would appreciate any feedback on how to construct my algo using DFS ( I couldn't wrap my head around DFS with different colors at play)

The initialization method:

/// <summary>
/// Finds the longest connect region per color.
/// </summary>
/// <returns>Returns a pair that has the color and the count of the connected cells</returns>
public static Tuple<int,int> FindLongestConnectedColor()
{
    int[,] graph = {
                        {1, 1, 1, 2,2,3},
                        {1, 1, 1, 2,2,3},
                        {1, 1, 1, 2,2,3}
                    };

    var graphRowsCount = graph.GetLength(0);
    var graphColumnsCount = graph.GetLength(1);

    var visitedCellsPerColor = new Dictionary<int, HashSet<Tuple<int, int>>>();

    // first int represents the color, second int represents the region cells' count
    var longestRegion = new Tuple<int, int>(-1, -1);

    for (int row = 0; row < graphRowsCount; row++)
    {
        for (int column = 0; column < graphColumnsCount; column++)
        {
            var color = graph[row, column];

            if (!visitedCellsPerColor.ContainsKey(color))
            {
                visitedCellsPerColor.Add(color, new HashSet<Tuple<int, int>>());
            }

            if (!visitedCellsPerColor[color].Contains(new Tuple<int, int>(row, column)))
            {
                var length = GetConnectedRegionLength(row, column, graph, visitedCellsPerColor);
                if (longestRegion.Item2 < length)
                {
                    longestRegion = new Tuple<int, int>(color, length);
                }
            }
        }
    }

    return longestRegion;
}

My BFS logic

I am using two queues to avoid boxing/unboxing performance hit
I only consider cells that are of the same color
I only consider unvisited cells if they belong to the same color

Code:

private static int GetConnectedRegionLength(int row, int column, int[,] graph, Dictionary<int, HashSet<Tuple<int, int>>> visited)
{
    var directionRow = new List<int> { -1, +1, 0, 0 };
    var directionColumn = new List<int> { 0, 0, +1, -1 };
    var graphRowsCount = graph.GetLength(0);
    var graphColumnsCount = graph.GetLength(1);

    var connectedCellsCount = 0;

    var color = graph[row, column];

    var q1 = new Queue<int>();
    var q2 = new Queue<int>();

    q1.Enqueue(row);
    q2.Enqueue(column);
    visited[color].Add(new Tuple<int, int>(row, column));
    connectedCellsCount++;

    while (q1.Any())
    {
        // current Row
        var cr = q1.Dequeue();
        // Current Column
        var cc = q2.Dequeue();

        for (int a = 0; a < directionRow.Count; a++)
        {
            var newRow = cr + directionRow[a];
            var newColumn = cc + directionColumn[a];

            if (newRow < 0 || newColumn < 0) continue;
            if (newRow >= graphRowsCount  || newColumn >= graphColumnsCount ) continue;
            if (graph[newRow, newColumn] != color) continue;
            if (visited[color].Contains(new Tuple<int, int>(newRow, newColumn))) continue;

            q1.Enqueue(newRow);
            q2.Enqueue(newColumn);
            visited[color].Add(new Tuple<int, int>(newRow, newColumn));
            connectedCellsCount++;
        }
    }

    return connectedCellsCount;
}


texts: C++ Data-Oriented Modules using namespaces and extern

texts:
I have been coding in a certain style for some time now, where I try to avoid classes and stick to pure data structures whenever possible. Basically every module of my program has its own namespace in which all the data structures and functions are declared.

I started doing this because I wanted to focus on the actual data that gets processed and wanted to abstract data as little as possible. Performance is very important to me and I would like to develop a minimal, cache- and compiler-friendly style and I need someone to help me understand what I actually do by structuring my code like this.

So this is how I would structure the functionality of loading 3D meshes into my program for example. The actual code is very abbreviated because right now I would like to only focus on the structure with the namespace and the external declarations.

The header Mesh.h

#include "OpenGL.h" //a higher level namespace containing context information
namespace OpenGL{
    namespace Mesh{

struct Vertex{
    vec3 pos;
    vec3 normal;
    vec2 uv;
};

struct Material{
    vec3 amb;
    vec3 diff;
    vec3 spec;
    float shininess;
};
struct Mesh{
    unsigned int indexOffset;
    unsigned int indexCount;
    unsigned int materialIndex;
};
extern vector<Vertex> allVertices;
extern vector<unsigned int> allIndices;
extern vector<Material> allMaterials;
extern vector<Mesh> allMeshes;

extern string MESH_DIR;
extern vector<string> meshNames; //find mesh index by name

void setMeshDirectory(string pDirectory);

void loadAllMeshes();
Mesh loadMesh(string pFilename);
void addMesh(string pFileName);
    }
}

The code file

#include "Mesh.h"
#define DEFAULT_MESH_DIR "..//assets//meshes//"
//define all external variables
vector<Vertex> allVertices = {};
vector<unsigned int> allIndices = {};
vector<Material> allMaterials = {};
vector<Mesh> allMeshes = {};

string MESH_DIR = DEFAULT_MESH_DIR;
vector<string> meshNames = {};

void OpenGL::Mesh::setMeshDirectory(string pDirectory){
    MESH_DIR = pDirectory;
}

void OpenGL::Mesh::addMesh(string pFileName){
    auto it = find(meshNames.begin(), meshNames.end(), pFileName);
    if(it == meshNames.end()){
        meshNames.push_back(pFileName);
    }else{
    //error
    }
}

void OpenGL::Mesh::loadAllMeshes(){
    allMeshes.resize(meshNames.size()); //resize allMeshes array in advance
    for(unsigned int m = 0; 0 < meshNames.size(); ++m){
        allMeshes[m] = loadMesh(meshNames[m]);
    }
}

OpenGL::Mesh::Mesh OpenGL::Mesh::loadMesh(string pFilename){
    Mesh mesh;
    mesh.indexOffset = allIndices.size();
    unsigned int indexCount;
    unsigned int materialIndex;

    //use assimp to actually load the mesh from an .obj, .3DS, .fbx (etc) file
    //fill allMaterials, allVertices and allIndices with the data from this mesh

    mesh.indexCount = indexCount;
    mesh.materialIndex = materialIndex;
    return mesh;
}


texts: Computing features over the same dataframe

texts:
The following code computes three different features over the same dataset. I'm not sure if the filter_by_day_segment function can be made tidy or there's a more efficient/short but still readable way of refactor my code.

library(dplyr)

filter_by_day_segment <- function(data, day_segment){
  if(day_segment == "daily"){
    return(data %>% group_by(local_date))
  } else {
    return(data %>% filter(day_segment == local_day_segment) %>% group_by(local_date))
  }
}
compute_metric <- function(data, metric, day_segment){
  if(metric == "countscans"){
    data <- filter_by_day_segment(data, day_segment)
    return(data %>% summarise(!!paste("sensor", day_segment, metric, sep = "_") := n()))
  }else if(metric == "uniquedevices"){
    data <- filter_by_day_segment(data, day_segment)
    return(data %>% summarise(!!paste("sensor", day_segment, metric, sep = "_") := n_distinct(value)))
  }
  else if(metric == "countscansmostuniquedevice"){
    data <- data %>% group_by(value) %>%
      mutate(N=n()) %>%
      ungroup() %>%
      filter(N == max(N))
    data <- filter_by_day_segment(data, day_segment)
    return(data %>% summarise(!!paste("sensor", day_segment, metric, sep = "_") := n()))
  }

}

data <- read.csv("test.csv")

day_segment <- "daily"
metrics <-  c("countscans", "uniquedevices", "countscansmostuniquedevice")

features = data.frame()
for(metric in metrics){
  feature <- compute_metric(data, metric, day_segment)
  if(nrow(features) == 0){
    features <- feature
  } else{
    features <- merge(features, feature, by="local_date", all = TRUE)
  }
}

print(features)

A test CSV file

"local_date","value"
"2018-05-21","FC:44"
"2018-05-21","FC:58"
"2018-05-21","FF:7E"
"2018-05-21","F8:77"
"2018-05-21","F8:77"
"2018-05-22","FB:F1"
"2018-05-22","FC:62"
"2018-05-22","FE:D4"
"2018-05-22","FE:D4"
"2018-05-22","FC:F1"
"2018-05-23","F8:77"
"2018-05-23","F8:77"
"2018-05-23","FF:13"
"2018-05-23","F8:3F"
"2018-05-23","F8:3F"
"2018-05-23","F8:3F"
"2018-05-23","FC:B6"
"2018-05-24","FC:0D"
"2018-05-24","F8:3F"
"2018-05-24","F7:B6"
"2018-05-24","F6:96"
"2018-05-24","F6:96"
"2018-05-24","F6:96"
"2018-05-24","F6:96"
"2018-05-24","F6:96"
"2018-05-24","F6:96"
"2018-05-24","F6:96"
"2018-05-25","FC:A8"
"2018-05-25","FC:44"
"2018-05-25","FC:44"
"2018-05-25","FC:44"
"2018-05-25","FC:44"
"2018-05-25","FC:44"
"2018-05-25","FC:44"
"2018-05-25","FC:44"
"2018-05-25","FC:44"
"2018-05-26","FC:F1"
"2018-05-26","FC:A8"
"2018-05-26","FF:89"
"2018-05-26","FF:89"
"2018-05-26","FF:89"


texts: Reading values from a file and assigning to another class

texts:
I'm assigning values to an object by passing it to another class. Basically, I'm reading values from a file and assigning it by passing it to another class.

This is the POJO class for the details in a file.

public class FileDetails
{

    String URL;
    String Port;
    String UserName;
    String Pwd;

    public String getUserName() {
        return UserName;
    }

    public String getPort() {
        return Port;
    }
    public String getPwd() {
        return Pwd;
    }
    public String getURL() {
        return URL;
    }
    public void setPort(String port) {
        this.Port = port;
    }
    public void setPwd(String pwd) {
        this.Pwd = pwd;
    }
    public void setURL(String URL) {
        this.URL = URL;
    }
    public void setUserName(String userName) {
        this.UserName = userName;
    }
}

This is the class which I am using to set the values into that an instance of FileDetails.

public class FileService extends FileDetails
{
    public FileService(FileDetails fileDetails)
    {
        FileDetails fileDet = null;

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try
        {
            fileDet = objectMapper.readValue(new File("res.json"), fileDetails.class);
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        if (fileDet != null) {
            fileDetails.setUserName(fileDet.getUserName());
            fileDetails.setPwd(fileDet.getPwd());
            fileDetails.setURL(fileDet.getURL());
            fileDetails.setPort(fileDet.getPort());
        } else {
            System.out.println("Didn't set details");
        }
    }
}

This works. Everywhere I call this code, I am using two lines of code, like

FileDetails fileDetails = new FileDetails();
FileService fileService = new FileService(fileDetails);

I want to know if this is the optimum way to get things done, or if there are any better ways to do this.


texts:
I have to show price of an item. If the price is only in dollars, it should look like an integer. But if it contains cents, it should look like double value and always have two symbols after decimal separator:

  2 550$
  2 550,55$
  2 550,50$

I decided to use Decimal format for this task, but I don't know how to properly handle the cents.

Here is my solution:

public static String moneyFormat(double amount, String currency) {
    DecimalFormatSymbols dfSymbols = new DecimalFormatSymbols();
    dfSymbols.setDecimalSeparator(',');
    dfSymbols.setGroupingSeparator(' ');
    dfSymbols.setCurrencySymbol(currency);
    DecimalFormat df;
    if (isInteger(amount)) {
        df = new DecimalFormat("###,###,##0 \u00A4", dfSymbols);
    } else {
        df = new DecimalFormat("###,###,##0.00 \u00A4", dfSymbols);
    }
    df.setGroupingUsed(true);
    return df.format(amount);
}

private static boolean isInteger(double amount) {
    return  !Double.isInfinite(amount) && (amount == Math.floor(amount));
}

The amount comes from server in Double, therefore, probably, we can have some errors in case if 2$ will be represented as 1,999(9)$ but I am not sure how to test for such errors.

As an alternative to passing two patterns I can use             df.setMaximumFractionDigits();:

 df = new DecimalFormat("###,###,##0.00 \u00A4", dfSymbols);
if (isInteger(amount)) {
    df.setMaximumFractionDigits(0);
} else {
    df.setMaximumFractionDigits(2);
}

But the question stays the same: can I handle integers in some other, cleaner way?

Update

Unfortunately, changing output from server to String or other types is not an option. And I forgot to mention, that it for Android. I don't use classes of platform, so I haven't added it to tags.


texts: String contains non-overlapping letter pairs

texts:
I was trying my hand at learning Elixir via ancient adventofcode puzzles and was trying to write a function to satisfy this requirement:

  It contains a pair of any two letters that appears at least twice in
  the string without overlapping, like xyxy (xy) or aabcdefgaa (aa), but
  not like aaa (aa, but it overlaps).

Here is what I came up with, but it feels like it might be unwieldy. Is there a way to make it more elegant?

  def has_non_overlapping_pair(string) do
    0..String.length(string)-2
      |> Enum.map(fn n ->
          String.slice(string, n, 2)
      end)
      |> Enum.reduce(["_"], fn pair, acc ->
          if pair == hd(acc) do ["_"|acc]
          else [pair|acc] end
      end)
      |> count_occurrences
      |> Map.delete("_")
      |> Map.values
      |> Enum.any?(fn val -> val > 1 end)
  end


texts:
I've made a simple winhttp client in C++ and here is kind've the skeleton of the header file. I was thinking of initializing the session once and then using it throughout the rest of my http client structure. I don't know if this is super stupid but this was my thinking. This is just a skeleton of what I would like it to be and wanted to get a feel if this skeleton of a http client could be improved. Another question I have is:
"If I create multiple connections using WinHTTPConnect is that a bad idea and could their be issues, if so should I do something similar to how I have my session?"
#ifndef HTTPLITE_H
#define HTTPLITE_H
#include <Windows.h>
#include <Winhttp.h>
//everything required in terms of imports and libraries
#pragma comment(lib, "winhttp.lib")

class httplite {
private:
    //creates our local session within our class
    HINTERNET sess = WinHttpOpen(NULL,
        WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
        WINHTTP_NO_PROXY_NAME,
        WINHTTP_NO_PROXY_BYPASS,
        NULL
    );
public:
    httplite();
    ~httplite();

    LPCWSTR get(
        LPWSTR host,
        LPWSTR path=NULL,
        LPWSTR headers=NULL,
        boolean https=false
    );

    LPCSTR post(
        LPWSTR host,
        LPWSTR path=NULL,
        LPCSTR content= NULL,
        LPWSTR headers= NULL,
        boolean https=false
    );
};
#endif HTTPLITE_H


texts:
I wanted feedback/review on my implementation of a selection sort in c++ (for ints only, no templates). This is my first attempt in c++ making anything beyond simple projects/hello world!

Q: Should my for loops use uniform initialization like for(int i { 0 }; ... ?

Q: Should everything else use uniform initialization like I have below?

Q: I read selection is n^2 however I don't loop every field, I loop through only the unsorted portion, is this still n^2 or better?

#include <iostream>

void selectionSort(int arr[], int start, int size);
void printArr(int arr[], int size);

int main()
{
  const int size { 11 };
  int arr[size] { 1,9,2,3,4,1,6,6,5,3,8 };
  selectionSort(arr, 0, size);
  return 0;
}

void selectionSort(int arr[], int start, int size)
{
  printArr(arr, size);

  for (int i = start; i < size; i++)
  {
    int min_pos { i };
    for (int x = i; x < size; x++)
    {
      if (arr[x] < arr[min_pos])
      {
        min_pos = x;
      }
    }
    int temp { arr[i] };
    arr[i] = arr[min_pos];
    arr[min_pos] = temp;
    printArr(arr, size);
  }

  printArr(arr, size);
}

void printArr(int arr[], int size)
{
  for (int i = 0; i < size; i++)
  {
    std::cout << arr[i] << " ";
  }
  std::cout << std::endl;
}

output:

1 9 2 3 4 1 6 6 5 3 8
1 9 2 3 4 1 6 6 5 3 8
1 1 2 3 4 9 6 6 5 3 8
1 1 2 3 4 9 6 6 5 3 8
1 1 2 3 4 9 6 6 5 3 8
1 1 2 3 3 9 6 6 5 4 8
1 1 2 3 3 4 6 6 5 9 8
1 1 2 3 3 4 5 6 6 9 8
1 1 2 3 3 4 5 6 6 9 8
1 1 2 3 3 4 5 6 6 9 8
1 1 2 3 3 4 5 6 6 8 9
1 1 2 3 3 4 5 6 6 8 9
1 1 2 3 3 4 5 6 6 8 9


texts:
I just picked up C and am following through The C programming language.

I've previously got experience with a lot of 'higher'-level languages, so when I saw this exercise in the book:

  Write a program to copy its input to its output, replacing each string of one or more blanks by a
  single blank.

I thought I'd create a very basic and primitive trim-program that takes an input and removes all superfluous white-spaces (more than 1 in a row) and prints out a 'trimmed' string.

As mentioned I just recently started and we haven't covered dynamic arrays yet, so I'm just using static ones.

But I was hoping to get some feedback on my solution:

#include <stdio.h>

/*
** A primitive trimmer
** to remove any superflous
** whitespaces in a given
** string (input).
*/

int main () {

    /*
    ** Setting up the variables
    **
    ** Working with static
    ** arrays since I haven't
    ** been introduced to dynamic.
    */
    char input [100], output[100];
    fgets(input, 100, stdin);
    int i = 0, k = 0;

    // Looping over input until hitting
    // an item containing a null-char.
    while (input[i] != '\0') {
        if (input[i] == ' ') { // hitting first space.
            int j = i + 1;     // initiating temporary counter.
            if (input[j] != '\0') {
                               // find index of first non-space
                               // character after initial space.
                while (input[j] != '\0' && input[j] == ' ') {
                    if (input[j] == ' ') {
                        i++; // keep indexing input-index
                    }
                    j++; // keep incrementing temporary indexer.
                }
            }
        }
        output[k] = input[i]; // insert non-space item into output.
        i++;                 // increment input-indexer.
        k++;                 // prepare output-indexer for next non-space.
    }
    printf("%s", output);     // print trimmed input.
}

It's not going to be pretty and you might not like it, but please keep in mind that I am new to the language!

I'd like to get feedback on my overall solution, any thoughts on the baseline algorithm and how well I'm following best (syntactical) practices.


texts: Decide if a number is even or odd by using bitwise operator

texts:
The following exercise is from an Assembler-course I'm taking:

  Write a program that takes a number x as input, and returns:

  0 if x is even.
  1 if x is odd.

Full exercise-page here: GitHub

Here's my solution:

format PE console
entry start

include 'win32a.inc'

; ===============================================
section '.text' code readable executable

start:

    call    read_hex        ; Provided by the teacher. Reads a hexadecimal number from stdin.

    and     eax,    0x1

    cmp     eax,    0x0
    je      print_result

    mov     eax,    0x1
print_result:
    call    print_eax_binary    ; Provided by the teacher. Prints a binary number to stdout.

    ; Exit the process:
    push    0
    call    [ExitProcess]

include 'training.inc'

I would say it works alright:

Is my solution valid?
Can it be improved? Respectively, is there a better solution possible?


texts:
I'm looking for ways to improve this code (more readable, less redundant and maybe cleaner/faster).

The problem I needed to solve:

I was designated to implement a software that is going to validate an 96 column Excel file and if there is no error on it, create an XML file from it. In case there are any error in the excel file I have to display them to the user and indicate where the problem occurred.

How I attempted to solve the problem:

Since I knew the numbers of columns, I thought about making a class that represents an cell on the Excel file and include a string property to hold an possibly error description, by making that it'd make it easy to display the error log. So I actually created 2 collections of my class that is called Cell.  One collection to hold all of Excel's cell values, and the other is the error log one.

Here is the Cell class code:

public class Cell
{
    public string Value { get; set; }
    public int Row { get; set; }
    public int Column { get; set; }
    public string ErrorDescription { get; set; }
}

This is the Cells collection:

Range worksheetCells = sheet.get_Range(firstCell, lastCell);
private List<Cell> Cells = new List<Cell>();

foreach (Range item in worksheetCells)
{
     Cells.Add(new Cell{ Value = item.Text, Row = item.Row, Column = item.Column});
}

For readability purposes, I create another 96 collections of Cell, one for each column:

var Name = Cells.Where(c => c.Column == 1);
....

I've created 96 methods of validation one per column/collection:

private void NameValidation(IEnumerable<Cell> excelColumn, List<Cell> log)
{
    foreach (Cell item in excelColumn)
    {
        if (string.IsNullOrEmpty(item.Value))
        {
            item.ErrorDescription = "You need to fill up this Cell.";
        }
        else
        {
            if (item.Value.Length > 27)
            {
                item.ErrorDescription = "The MAX length of this field is 27 characters.";
            }
        }

        if (!string.IsNullOrEmpty(item.ErrorDescription))
        {
            log.Add(item);
        }
    }
}

Basically that is what I have now.  I haven't touch the XML file creation yet, but the reason why I've designed my code like this is that I can use the validation method to create the XML, instead of having to do another 96 foreach statements.  I'd only create the XML file when after calling all the validation methods if the log.count return 0, so it is ok to generate the file.

What troubles my mind:

Do I really need to do 96 things all the time?

in 60% of the the validation methods I have to check for string.IsNullOrEmpty(item.Value) and copy and paste kills me, It makes me feel like I'm doing something wrong, you know?

In a few of those methods, the item.value is only mandatory if another cell is filled up.  If it is, then the current cell is mandatory. That's why I didn't make a single method to validate when the field is mandatory, because it depends on other things.  In 30% of the validation methods, I have to check for item.Value.Length > "something".

Do you have any ideas on how to take some of those if/else out?


texts:
I use this method to get either Customer or Account. The server will determine which type it is.

The response will have a property "Type": "Customer" or "Type": "Account".

I first deserialize to Client (supertype) to check the Type property. Then deserialize to either Customer or Account.

public async Task<Models.Entities.Client> GetClient(int clientId)
{
    var getClientRequest = new RestRequest("client/details", Method.GET);
    getClientRequest.AddQueryParameter("ClientId", clientId);

    var jsonResponse = await _requestService.DoRequest(getClientRequest);

    var client = JsonConvert.DeserializeObject<Models.Entities.Client>(jsonResponse);

    switch (client.Type)
    {
        case ClientKind.Account:
            var account = JsonConvert.DeserializeObject<Account>(jsonResponse)
            return account;
        default:
            var customer = JsonConvert.DeserializeObject<Customer>(jsonResponse);
            return customer;
    }
}

Example responses:

{
    "ClientId": 1,
    "Type": "Account",
    "Name": "Company Inc."
}

{
    "ClientId": 2,
    "Type": "Customer",
    "Name":
    {
        "First": "John",
        "Last": "Smith"
    },
    "DateOfBirth": "1960-12-01"
}

DTOs:

public class Client
{
    public int ClientId { get; set; }
    public ClientType Type { get; set; }
}

public class Account : Client
{
    public string Name { get; set; }
}

public class Customer : Client
{
    public PersonalName Name { get; set; }
    public DateTime DateOfBirth { get; set; }
}


texts: Checking inactivity with periodic tasks in Java

texts:
I have created a simple HealthCheck service. I have two approaches:

Create a task canceling the previous one if the system is active, rescheduling the new task.
Create a periodic task and regularly check the last active time.

Which one is better?
Recommendations on how to improve my usage of synchronized, volatile, AtomicBoolean keywords in both approaches above are welcome.
public interface IHealthCheck {
    void start();
    void stop();
    void onActive();
    void onExpire();
}

public class Main {
    public static void main(String[] args) {
        IHealthCheck check = new HealthCheck2();

        new Thread(() -> checkTask(check, 5)).start();

        new Thread(() -> checkTask(check, 6)).start();

        new Thread(() -> checkTask(check, 7)).start();

        sleep(100);
        check.start();

    }

    private static void checkTask(IHealthCheck check, long sleep) {
        for (int i = 0; i < 1000; i++) {
            sleep(sleep);
            check.onActive();
        }
    }

    private static void sleep(long n) {
        try {
            Thread.sleep(n);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

package com.deneme;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class HealthCheck implements IHealthCheck {

    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    private ScheduledFuture<?> future;

    @Override
    public void start() {
        onActive();
    }

    @Override
    public synchronized void stop() {
        if (future != null) {
            future.cancel(true);
        }
    }

    @Override
    public synchronized void onActive() {
        if (future != null) {
            future.cancel(true);
        }
        System.out.println("Active: " + System.currentTimeMillis());
        future = scheduler.schedule(this::onExpire, 200, TimeUnit.MILLISECONDS);
    }

    @Override
    public void onExpire() {
        System.out.println("Expired: " + System.currentTimeMillis());
    }
}

package com.deneme;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class HealthCheck2 implements IHealthCheck {

    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    private ScheduledFuture<?> future;
    private Instant lastActiveTime;
    private boolean expired;

    @Override
    public void start() {
        onActive();
        future = scheduler.scheduleWithFixedDelay(this::check, 50, 50, TimeUnit.MILLISECONDS);
    }

    private synchronized void check() {
        long diff = ChronoUnit.MILLIS.between(lastActiveTime, Instant.now());
        if (diff > 100) {
            onExpire();
        }
    }

    @Override
    public synchronized void stop() {
        if (future != null) {
            future.cancel(true);
        }
    }

    @Override
    public synchronized void onActive() {
        expired = false;
        lastActiveTime = Instant.now();
        System.out.println("Active: " + lastActiveTime.toEpochMilli());
    }

    @Override
    public void onExpire() {
        if (!expired) {
            expired = true;
            System.out.println("Expired: " + System.currentTimeMillis());
        }
    }

}


texts: Implementing a binary operation for the null object pattern

texts:
Today I needed to implement a class for representing rectangular regions with some binary operations such as merging or intersection.

public class Region
{
    // Properties, such as top-left and bottom-right corner ...
    // Ctors ...

    public Region Merge(Region other)
    {
        // ...
    }

    public Region Insersect(Region other)
    {
        // ...
    }
}

Intersecting two instances of Region unfortunately does not always have a useful result. So my next step was to implement the notion of a NullRegion. It is no problem to implement the NullRegion itself. However, this would require Region to check against NullRegion, as those binary operations are commutative and the order should not matter. (i.e. nullRegion.Intersect(nonNullRegion)should yield the same result as nonNullRegion.Intersect(nullRegion), which is a NullRegion)

The first solution I can think of is to move the implementation of those methods into a seperate class. That way, I only the new class needs to know the NullRegion.

public class Region
{
    // Properties, such as top-left and bottom-right corner ...
    // Ctors ...

    public virtual bool IsNull { get { return false; } }

    public Region Merge(Region other)
    {
        return RegionMethods.Merge(this, other);
    }

    public Region Intersect(Region other)
    {
        return RegionMethods.Intersect(this, other);
    }

    private class NullRegion
    {
        public override bool IsNull { get { return true; } }
    }

    private static class RegionMethods
    {
        public static Region Merge(Region Region, Region otherRegion)
        {
            // ...
        }

        public static Region Intersect(Region Region, Region otherRegion)
        {
            // ...
        }
    }
}

Is this a good way to tackle the problem? What would be my alternatives?


texts:
The purpose of a rhythmic task controller is to accept a task and execute all the queued tasks in a cycle or "rhythm" defined by the client code. A task returns true or false depending on whether or not it is "finished". A finished task should be removed from the controller's control and won't be executed again while an unfinished task should be executed on the next cycle.

I don't think my solution is as well optimized as it could be, and this is a solution that needs to be as fast as possible as it serves as the core task controller in my game framework!

import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public final class RhythmicTaskController implements TaskController, Runnable {

    private final ExecutorService service;
    private final ConcurrentLinkedQueue<Task> queue = new ConcurrentLinkedQueue<>();

    public RhythmicTaskController(int threads, int delay, TimeUnit unit) {
        service = Executors.newFixedThreadPool(threads);

        newSingleThreadScheduledExecutor().scheduleWithFixedDelay(this, delay, delay, unit);
    }

    @Override
    public void offer(Task task) {
        queue.offer(task);
    }

    @Override
    public void run() {
        int initial = queue.size();
        ConcurrentMap<Future<Boolean>, Task> futures = new ConcurrentHashMap<>(initial);
        queue.forEach(task -> futures.put(service.submit(task::finish), task));
        futures.forEach((r, task) -> {
            try {
                if (r.get())
                    queue.remove(task);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

}


texts: Searching multiple Excel sheets for the cheapest item

texts:
I am creating an estimation tool, where users can input part numbers and quantities, and the tool will output the lowest cost for that part number based on searches through multiple databases.

I accomplish this by loading data into multiple sheets and then evaluate all possibilities on one sheet.

I believe my code is struggling, because I have multiple instances of this loop below which I'm hoping someone can help me improve.  The code below runs 3 separate times, for 3 different sheets.  There can be up-to 1000 part numbers run at a time.  Once the tool has been run, to start over I delete all the sheets, so each sheet is created every time the macro runs.

'Add Content to Summary

       'MPN and Qty add to Summary page
            Sheet22.Visible = True
            Sheet1.Select
            Range("A2").Select

            Sheet22.Select
            Range("A2").Select

            For i = 1 To 3
            Sheet1.Select
            If Len(ActiveCell.Value) > 0 Then

            xmpn = ActiveCell.Value
            xqty = ActiveCell.Offset(0, 1).Value

            Sheet22.Select
            ActiveCell.Value = xmpn
            ActiveCell.Offset(0, 1).Value = xqty
            ActiveCell.Offset(1, 0).Select
            Sheet1.Select
            ActiveCell.Offset(1, 0).Select

            Else
                i = 10
            End If
                i = i - 1
            Next

If there are 1000 part number entries, this code can take about 45 seconds to run, and causes excel to show not responding.  Any help or suggestions to improve would be greatly appreciated.


texts: Implementation of a deque using an array in Python 3

texts:
I created this double-ended queue using list. I supported the standard operations such as push, pop, peek for the left side and the right side.

I used an integer mid to track the midpoint of the deque. This way elements can be inserted to the left or to the right appropriately. Here is a list of efficiencies according to Python's documentation for list.

class Deque():
    def __init__(self):
        self.array = []
        self.mid = 0

    def push_left(self, val):
        self.array.insert(self.mid, val)

    def push_right(self, val):
        self.array.insert(self.mid, val)

        self.mid = self.mid + 1

    def pop_left(self):
        # If mid is the rightmost element, move it left.
        if self.mid == len(self.array) - 1:
            self.mid = self.mid - 1

        if (len(self.array) > 0):
            return self.array.pop()
        else:
            return None

    def pop_right(self):
        # If the mid is not the leftmost element, move it right.
        if self.mid > 0:
            self.mid = self.mid - 1

        if (len(self.array) > 0):
            return self.array.pop(0)
        else:
            return None

    def peek_left(self):
        if (len(self.array) > 0):
            return self.array[-1]
        else:
            return None

    def peek_right(self):
        if (len(self.array) > 0):
            return self.array[0]
        else:
            return None

    def __str__(self):
        ret = "["

        if len(self.array) == 0:
            return "[]"

        for idx, val in enumerate(self.array):
            if idx == self.mid:
                ret = ret + "({}) ".format(str(val))
            else:
                ret = ret + str(val) + " "

        return ret.strip() + "]"

# Test case
d = Deque()

d.push_left(19)
d.push_left(11)
d.push_left(23)
print(d)

d.push_right(17)
d.push_right(13)
print(d)

d.pop_left()
d.pop_left()
print(d)

d.pop_left()
d.pop_right()
print(d)

# Edge Case where 13 is the only element. Insert 29 left of it.
d.push_right(29)
print(d)

d.push_left(11)
print(d)

d.pop_right()
d.pop_right()
print(d)

# Edge Case where 13 is the only element. Insert 21 right of it.
d.push_left(21)
d.push_left(29)
print(d)

d.push_right(13)
d.push_right(21)
print(d)  # Symmetry!

I'm aware that the __str__ method isn't particularly efficient as it is O(n).

I specifically want to know:

Are there any edge cases I missed?
Are there any obvious optimisations I missed?
Are there any bugs in the data structure itself?
Is the code properly "Pythonic"?


texts: Yet another Sieve of Eratosthenes in Java

texts:
I wanted a reusable class for generating a list of primes till some arbitrary (but reasonable) limit. So, I wrote a class Primes that implements the Sieve of Eratosthenes and another method that makes use of this sieve. The implementation is done on the basis of clarity and swiftly obtaining results.

I admit that using a BitSet would have improved memory usage and using the Sieve of Atkin would have given me a (slightly) better runtime, but I avoided extra trouble and went for it.

Primes.java

/**
 * This is a utility class that contains methods related to prime numbers
 * that are used in many problems in Project Euler.
 *
 * @author Subhomoy Haldar
 * @version 1.0
 */
public class Primes {

    /**
     * Returns a boolean array that is essentially a sieve. In order to check
     * if a number is prime, check if the boolean at that index is true. For
     * example,
     *

     *  // ...
     *  boolean[] sieve = Prime.siftTill(someLimit);
     *  int n = (yourNumber);
     *  if (sieve[n])
     *      // ... do operations with the prime number
     *  // ...
     *

     *

     *
Time complexity:

     * O(n log log n)
     *
Space complexity:

     * O(n)
     *
     * @param n The number till which the sieve must be generated.
     * @return The sieve in the form of a boolean array.
     */
    public static boolean[] siftTill(int n) {
        // create an array of size (n + 1), to include the index n as well
        boolean[] sieve = new boolean[++n];
        // the outer loop will be limited to ~ sqrt(n) iterations
        int limit = (int) Math.sqrt(n);
        // initially set all to true except 0 and 1
        for (int i = 2; i < n; i++) sieve[i] = true;
        // start from 2 and remove all multiples of primes
        for (int i = 2; i < limit; i++) {
            if (sieve[i]) {
                for (int j = i * i; j < n; j += i) {
                    sieve[j] = false;
                }
            }
        }
        return sieve;
    }

    /**
     * Returns an array of primes upto the given inclusive limit.
     *

     *
Time complexity:

     * O(n)
     *
Space complexity:

     * O(n)
     *
     * @param limit The inclusive upper limit.
     * @return An array of primes upto the given inclusive limit.
     */
    public static long[] getPrimesTill(int limit) {
        boolean[] isPrime = siftTill(limit);
        // 1st pass: count the number of primes
        int count = 0, index = 0;
        for (int i = 2; i <= limit; i++) {
            if (isPrime[i])
                count++;
        }
        long[] primes = new long[count];
        // 2nd pass: store the primes
        for (int i = 2; i <= limit; i++) {
            if (isPrime[i])
                primes[index++] = i;
        }
        return primes;
    }
}

I welcome comments on all aspects of the code.


texts: JavaScript image-Carousel with using IIFE

texts:
I have to implement an image-Carousel.

Because I'll reuse the snippet within other projects which might contain all kinds of external libraries I used an immediately invoked function expression.

Could my code be improved?

All Hints appreciated.

(function (imgPaths, imgTag, prevButton, nextButton) {
  var length = imgPaths.length;
  var i = 0;

  function setImageSrc () {
    // Using alt-attribute for simplicity.
    // In production the src-attribute is used.
    imgTag.setAttribute('alt', imgPaths[i]);
  }

  setImageSrc();

  prevButton.addEventListener('click', function() {
    i = ((i - 1) + length) % length;
    setImageSrc();
  });

  nextButton.addEventListener('click', function() {
    i = (i + 1) % length;
    setImageSrc();
  });
})( [ 'imgs/first', 'imgs/second', 'imgs/third',
     'imgs/fourth', 'imgs/fifth' ],
   document.querySelector('.display img'),
   document.querySelector('.prev'),
   document.querySelector('.next') );

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


texts: Swapping every letter with every other letter in a string

texts:
I am doing a project and I have come up with some code to swap every letter with every other letter in a string, only the project was to be "efficient as possible".

Example:

"rya" = yra, ray, ayr.. etc

I understand exactly how the code works. I would just like to make it efficient as possible.

public String testSwap(String word) {

char[] charArr = word.toCharArray();
char[] charArr2 = new char[word.length()];
String newString = "";

for(int i = 0; i < word.length(); i++) {
    for(int j = 0; j < word.length(); j++) {
        int count = 0;

        for(char c: charArr) {
            charArr2[count] = c;
            count++;
        }

        if(charArr2[i] != charArr[j]) {
            charArr2[i] = charArr[j];
            charArr2[j] = charArr[i];

            newString = new String(charArr2);

            if(graph.keySet().contains(newString)) {
                return newString;
            } else {
                newString = "";
            }
        }
    }
}
return newString;
}

NOTE: The if statement inside is for the current project I am doing.


texts: How to optimize Method Visibility and code structures for better performance?

texts:
I'm creating an application to get data cross domain all the line of code seem work as well but I'm not much understand about performance with my code process with the real server and real action because sometime there are a lot of case will happen when I fetch those data so I want to make a method to get those errors by using getHttpCode method and however fetch and initial data in this httpData method. Moreover I want to know when I go to real server and real real time It will be facing a lot of case so I want to check that cause or errors and send it to view by using s_respond mean that Server respond with HTTP_code.

Please check my below function

    private function httpData($url =null, $id = null)
    {
        if($id){
            $url = 'website/api/v1/pro/'.$id;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLINFO_PRETRANSFER_TIME, 30);
        curl_setopt($ch, CURLINFO_HTTP_CODE, true);
        curl_setopt($ch, CURLOPT_PRIVATE, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        if (!$executed = curl_exec($ch)) {

            $res = $executed;
            $data = false;
            curl_close($ch);
        } else {

            if ($this->http_code = $this->getHttpCode(curl_getinfo($ch))) {

                $res = $this->http_code;
                $data = $executed;
            } else {
                $res = false;
            }
        }
        return ['s_respond' => $res, 'data' => $executed];
    }

    private function getHttpCode($http)
    {
        if (is_array($http)) {
            if (!empty($http['http_code'] || $http['http_code'] != 0)) {
                return $http['http_code'];
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

//Initial and send to view function....

public function products()
    {
        $url = 'http://website/api/v1/products';
        $data = $this->httpData($url);
        return view('products.list', ['data'=>$data]);
    }


texts:
I am trying to merge two pdfs - one from a razor view and one from a file on the server.  To create the pdf from the razor view I have used the following nuget package: MVCRazorToPDF.

Unfortunately this didn't allow me to merge an existing file with the pdf so I have downloaded the project and changed the PdfActionResult to accept a mergeFilename.

I then generate the new pdf using the following:

public byte[] GeneratePdfOutput(ControllerContext context, object model = null, string viewName = null,
    Action<PdfWriter, Document> configureSettings = null, string filename = null)
{
    byte[] output;

    if (!string.IsNullOrEmpty(filename) && File.Exists(filename))
    {
        using (var copyDoc = new Document())
        {
            using (var copyStream = new MemoryStream())
            {
                copyDoc.Open();

                PdfCopy copy = new PdfCopy(copyDoc, copyStream);
                copy.CloseStream = false;
                copy.AddDocument(new PdfReader(GetBytes(context, model, viewName, configureSettings)));

                using (var reader = new PdfReader(filename))
                {
                    reader.ConsolidateNamedDestinations();

                    for (int i = 1; i <= reader.NumberOfPages; i++)
                    {
                        PdfImportedPage page = copy.GetImportedPage(reader, i);
                        copy.AddPage(page);
                    }
                }

                copy.Close();
                copyDoc.Close();
                output = copyStream.ToArray();
            }
        }
    }
    else
    {
        output = GetBytes(context, model, viewName, configureSettings);
    }

    return output;
}

private byte[] GetBytes(ControllerContext context, object model = null, string viewName = null, Action<PdfWriter, Document> configureSettings = null)
{
    if (viewName == null)
    {
        viewName = context.RouteData.GetRequiredString("action");
    }

    context.Controller.ViewData.Model = model;

    using (var document = new Document())
    {
        using (var workStream = new MemoryStream())
        {
            PdfWriter writer = PdfWriter.GetInstance(document, workStream);
            writer.CloseStream = false;

            if (configureSettings != null)
            {
                configureSettings(writer, document);
            }

            document.Open();

            using (var reader = new StringReader(RenderRazorView(context, viewName)))
            {
                XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, reader);
                document.Close();
                return workStream.ToArray();
            }
        }
    }
}

I was wondering if there was anyway to do this so that the GetBytes was part of the first function - ie I open a new document and then add the razor and if there is a file on the server, I add that using the same memory stream and document (rather than having to create new ones), without the need for the else


texts:
I built a simple proxy using Meteor and its Iron Router. It currently fails at passing through other than 200 or 500 status codes, which I guess suffices. Is this proxy.js the best way to bypass CORS without modifying remote or Apache/Nginx server settings?

"use strict"

// call with "/proxy?url=" + encodeURIComponent(myUrl)
Router.route('/proxy', function(){
    var url = this.params.query.url
    console.log("proxy called with url:", url)
    /* // whitelist url
    if(!/^https:\/\/[a-z]+\.otherdomain\.com\/[a-zA-Z/.]+$/.test(url)){
        var msg = "url not allowed: " + url
        console.log(msg)
        //throw new Meteor.Error(msg)  // Too much scary stacktrace.
        this.response.writeHead(403, {'Content-Type': 'text/html'});
        this.response.end(msg)
    }
    */
    console.log("calling url:", url)
    var r = Meteor.http.call("GET", url)
    var keys = []; for(var k in r) keys.push(k)
    console.log("result has:", keys)
    console.log("result statusCode:", r.statusCode, typeof(r.statusCode))
    console.log("result data:", r.data)
    //this.response.writeHead(404, {'Content-Type': 'text/html'})  // broken?! https://github.com/iron-meteor/iron-router/issues/1055
    this.response.writeHead(r.statusCode, r.headers)
    var html = r.content
    // fix relative URLs
    if(html.indexOf('<base ') < 0) html = html.replace(/<head>/i, '<head><base href="'+url+'">')
    this.response.end(html)
}, {where: 'server'})


texts:
I am working on a little Python project to track how much time I am spending coding and doing things outdoors. Coding subtracts and outdoors stuff adds.

My code is looking pretty bad. Any suggestions on how to make it better?

import tkinter as tk
import time
import json
import atexit
from flask import Flask

root = None
start_time = 0
end_time = 0
_add = False
_sub = False
entries_num = 0
_click = False
name = ''
_name = None
run_txt = None

def simplify(_time):
    return time.strftime('%H:%M:%S', time.localtime(_time))

def simple_mode(mode):
    if mode == 0:
        return "Add"
    elif mode == 1:
        return "Subtract"

def start():
    global start_time
    start_time = int(time.time())
    run_txt.configure(text="Running", fg="green")

def end():
    global end_time
    end_time = int(time.time())
    run_txt.configure(text="Not Running", fg="red")
    time_manager()

def find_mode():
    if _add and not _sub:
        return 0
    elif _sub and not _add:
        return 1

# 0 is add 1 is subtract
def time_manager():
    global entries_num
    entries_num += 1
    mode = simple_mode(find_mode())
    entry_raw = {'name': _name.get(), 'mode': mode, 'start': simplify(start_time), 'end': simplify(end_time), 'total_time': simplify(end_time-start_time-(-2211688800))}
    entries.update({str(entries_num): entry_raw})
    display()

def add():
    global _add
    global _sub
    _add = True
    _sub = False

def sub():
    global _add
    global _sub
    _add = False
    _sub = True

def display():
    height = 1
    width = 5
    cells = {}
    for i in range(height):  # Rows
        for j in range(width):  # Columns
            b = tk.Label(root, text="")
            b.grid(row=i + 16 + entries_num, column=j)
            cells[(i, j)] = b
    cells[(0, 0)]['text'] = entries[str(entries_num)]['name']
    cells[(0, 1)]['text'] = entries[str(entries_num)]['total_time']
    cells[(0, 2)]['text'] = entries[str(entries_num)]['mode']
    cells[(0, 3)]['text'] = entries[str(entries_num)]['start']
    cells[(0, 4)]['text'] = entries[str(entries_num)]['end']

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        title_lbl = tk.Label(root)
        title_lbl['text'] = 'TimeTracker'
        title_lbl.configure(font=('Roboto', 20))
        title_lbl.grid(row=0, column=0, sticky='ew')
        srt_btn = tk.Button(root, text="Start", command=start, font=('Roboto', 8)).grid(row=10, column=0, sticky='sw')
        end_btn = tk.Button(root, text="End", command=end, font=('Roboto', 8)).grid(row=10, column=0, sticky='se')
        add_btn = tk.Button(root, text="Add Time", command=add, font=('Roboto', 8)).grid(row=11, column=0, sticky='se')
        sub_btn = tk.Button(root, text="Subtract Time", command=sub, font=('Roboto', 8))
        sub_btn.grid(row=12, column=0, sticky='se')
        global _name
        _name = tk.Entry(root, width=50)
        _name.grid(row=10, column=2)
        _name.insert(0, "Entry Name")
        _name.configure(state=tk.DISABLED)

        def on_click(event):
            _name.configure(state=tk.NORMAL)
            _name.delete(0, tk.END)

            # make the callback only work once
            _name.unbind('<Button-1>', on_click_id)

        on_click_id = _name.bind('<Button-1>', on_click)
        global run_txt
        run_txt = tk.Label(root)
        run_txt.configure(text="Not Running", fg="red")
        run_txt.grid(row=11, column=2)

def save():
    with open('data.json', 'w') as fb:
        _json = json.dumps(entries)
        fb.write(_json)

if __name__ == "__main__":
    root = tk.Tk()
    with open('data.json', 'r') as fr:
        text = fr.read()
        entries = json.loads(text)
        keys = entries.keys()
        for key in keys:
            entries_num = int(key)
            display()

    root.title("TimeTracker")
    root.minsize(200, 400)
    atexit.register(save)
    MainApplication(root).grid()
    root.mainloop()


texts:
I wrote the following in Swift to perform a sum:

let total:Double = session.courses.reduce(0) { $0 + $1.totalPrice() }

It's concise, it does the job but it does not seems very readable to me. Wouldn't a "classic" for loop be more explicit/readable/maintainable?

var total:Double = 0
for dish in session.courses {
    total += dish.totalPrice()
}

Should closures always be the way to go in Swift?


texts: Using dapper.net and repository pattern in Azure websites

texts:
I'm currently on Azure Websites & Azure SQL, some documentation recommends using Async as much as possible as cloud services higher latency and have chances of dropping traffic, but it's also cautioning that Async/Await have overhead.

Should I...

Implement an IStoreRepository interface (although I don't know if
it's helpful to me)?
Use Async versions of Query and OpenConnection?
Am I repeating myself so much in different Repository classes like GetById, GetAll, etc?  Is there a more elegant solution?

I am pretty new to dapper.net and I would like to have some feedback on my current implementation.

StoreRepository

public class StoreRepository
{
    public async Task<Store> GetById(int id)
    {
        using (var conn = await SqlHelper.GetOpenConnectionAsync())
        {
            const string sql = "Select * from Stores where Id = @Id";
            var res = await conn.QueryAsync<Store>(sql, new { Id = id });
            return res.FirstOrDefault();
        }
    }
    ...
}

StoreController

public async Task<ActionResult> Details(int id)
{
    var db = new StoreRepository();
    var store =  await db.GetById(id);
    return View(store);
}

SQLHelper

internal static class SqlHelper
{
    public static readonly string connectionString = ConfigurationManager.ConnectionStrings["ttcn"].ConnectionString;

    public async static Task<DbConnection> GetOpenConnectionAsync()
    {
        return new ProfiledDbConnection(await GetOpenConnection(false), MiniProfiler.Current);
    }
    private async static Task<SqlConnection> GetOpenConnection(bool mars = false)
    {
        var cs = connectionString;
        if (mars)
        {
            SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder(cs);
            scsb.MultipleActiveResultSets = true;
            cs = scsb.ConnectionString;
        }
        var connection = new SqlConnection(cs);
        await connection.OpenAsync();
        return connection;
    }
}


texts:
I understand that using goto in C++ code is strictly unadvised, but sometimes, it really reduces the number of lines of code like in the following case.

This is my code for SPOJ. I know this does not reduce too many lines of code, but in a big project, it potentially could.

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
bool debug=false;
typedef long long int lld;
typedef unsigned long long int llu;
int main(int argc , char **argv)
{
    if(argc>1 && strcmp(argv[1],"DEBUG")==0) debug=true;
    lld n,val;
    long double sq;
    while(true){
        scanf("%lld",&n);
        if(n==-1)break;
        n -= 1;
        if(n%3!=0)goto exit;
        n/=3;
        sq=4*n+1;sq=sqrt(sq);
        if(sq-(int)sq!=0)goto exit;
        n=sq;
        if(n%2!=1)goto exit;
        printf("Y\n");
        continue;
        exit:
            printf("N\n");
            continue;
    }
    return 0;
}

What should I do in such situations? Is there a way to do this by making a function call?


texts:
I am working on a micro project: a Haskell DSL for describing circuits.
(You can find the code here)

I'm pretty happy with everything so far, but there is an ugly function alu32:

    alu32 c0 c1 c2 a b =
      let aluc = alu1 c0 c1 c2
          (out0, cout0) = aluc (a !! 0) (b !! 0) c0
          (out1, cout1) = aluc (a !! 1) (b !! 1) cout0
          (out2, cout2) = aluc (a !! 2) (b !! 2) cout1
          (out3, cout3) = aluc (a !! 3) (b !! 3) cout2
                     ...

Can anyone suggest a more idiomatic way of representing this? Also, if you feel like browsing the repository, feel free to make any suggestions. I have a bunch of things that I would still like to implement.


texts:
Is this the correct way to cache a generator in Python, without iterating over it right away (for example using list() over it)?

@property
def results(self):
    def caching_iterator(it, r):
        for t in it:
            yield t
            r.append(t)

    if self._results:  # _results is [] initially
        return self._results
    return caching_iterator(self.run(), self._results)

This is a property of a class, as you can see. Basically, the idea is that the first time the property is accessed, a generator is returned. So the results are actually computed as the need arises. All the other subsequent times, the results are already inside a list, so they are returned straight away.

Are there simpler ways to achieve the same result? I like mine quite a bit, but I have one argument against it. The second argument of caching_iterator is a mutable type, a list. Since that object gets modified inside the function, this is potentially dangerous. However, I don't see how that could happen. The first time _results is None and caching_iterator does its job. But all the other times, the if test passes and _results is directly returned.


texts:
This is a simple Area Calculator coded in Java. What this does is that it prompts the user to select a shape, and asks for the details needed to calculate the area of that specific shape.

Main.java:

package com.AreaCalculator;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Welcome to the Area Calculator! Enter 1 to find the area of a Rectangle, Enter 2 to find the area of a Square, Enter 3 to find the area of a Triangle or Enter 4 to find the area of a Circle");

        int userInput = Integer.parseInt(scanner.next());

        if(userInput == 1) {
            System.out.println("Please enter the length of the rectangle: ");
            int length = Integer.parseInt(scanner.next());
            System.out.println("Please enter the width of the rectangle: ");
            int width = Integer.parseInt(scanner.next());

            System.out.println(length * width);
        } else if(userInput == 2) {
            System.out.println("Please enter the length of a side: ");
            int lengthOfASide = Integer.parseInt(scanner.next());

            System.out.println(lengthOfASide * lengthOfASide);
        } else if(userInput == 3) {
            System.out.println("Please enter the base of the triangle: ");
            int triangleBase = Integer.parseInt(scanner.next());
            System.out.println("Please enter the height of the triangle: ");
            int triangleHeight = Integer.parseInt(scanner.next());

            System.out.println((0.5 * triangleBase) * triangleHeight);
        } else if(userInput == 4) {
            System.out.println("Please enter the radius of the circle: ");
            int radius = Integer.parseInt(scanner.next());

            System.out.println(Math.PI * (radius * radius));
        }
    }
}


texts: C# Generic high performance vectorized math operations

texts:
I'm writing a library which simplifies the usage of intrinsics in C#.
It's a generic library which supports all numeric types.
The goal of this library is to perform these operations at the highest performance possible.
I'll gladly head any suggestions / tips which might improve the performance.
All feedback is welcome.
The whole library could be viewed at https://github.com/giladfrid009/SimpleSIMD
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace SimpleSimd
{
    // For value delegate pattern, which will allow to inline delegates.
    // The performance benefits of this pattern is quite massive (up to 5x)
    public interface IFunc<T, TResult>
    {
        TResult Invoke(T param);
    }

    // Example usage of value delegate pattern. These structs will be passed to the method
    // instead of regular delegates.
    // We use structs to prevent heap allocations
    struct Pred : IFunc<int, bool>
    {
        int num;

        public Pred(int num)
        {
            this.num = num;
        }

        public bool Invoke(int param)
        {
            return param == num;
        }
    }

    struct VPred : IFunc<Vector<int>, bool>
    {
        public Vector<int> vec;

        public VPred(Vector<int> vec)
        {
            this.vec = vec;
        }

        public bool Invoke(Vector<int> param)
        {
            return param == vec;
        }
    }

    internal static class SimdOps
    {
        // Helper method to offset a ref, to eliminate bound checks when accessing an index
        internal static ref U Offset<U>(this ref U source, int count) where U : struct
        {
            return ref Unsafe.Add(ref source, count);
        }
    }

    public static partial class SimdOps<T> where T : unmanaged
    {
        // Helper method to get a ref to the first element of a span, without bound checks.
        // Also, by getting a ref instead of a pointer, we no longer need to fix the object
        private static ref U GetRef<U>(ReadOnlySpan<U> span) where U : unmanaged
        {
            return ref MemoryMarshal.GetReference(span);
        }

        // Helper method to convert ref type
        private static ref Vector<U> AsVector<U>(in U value) where U : unmanaged
        {
            return ref Unsafe.As<U, Vector<U>>(ref Unsafe.AsRef(value));
        }

        // The actual method
        public static int IndexOf<F1, F2>(in ReadOnlySpan<T> span, F1 vPredicate, F2 predicate)

            where F1 : struct, IFunc<Vector<T>, bool>
            where F2 : struct, IFunc<T, bool>

        {
            ref var rSpan = ref GetRef(span);

            int i = 0;

            if (Vector.IsHardwareAccelerated)
            {
                ref var vrSpan = ref AsVector(rSpan);

                int length = span.Length / Vector<T>.Count;

                for (; i < length; i++)
                {
                    if (vPredicate.Invoke(vrSpan.Offset(i)))
                    {
                        int j = i * Vector<T>.Count;
                        int l = j + Vector<T>.Count;

                        for (; j < l; j++)
                        {
                            if (predicate.Invoke(rSpan.Offset(j)))
                            {
                                return j;
                            }
                        }
                    }
                }

                i *= Vector<T>.Count;
            }

            for (; i < span.Length; i++)
            {
                if (predicate.Invoke(rSpan.Offset(i)))
                {
                    return i;
                }
            }

            return -1;
        }
    }

}


texts:
Question:

  For a 1000-digit number, find the 13 adjacent digits which gives out the largest product.

My code goes like this:

series = '731...752963450' # the 1000 digit, simplified here.

# Set up variables.
adjacent_count = 13
pointer = 0
candidates = [], products_array = []
pointer_end = series.length - (adjacent_count - 1)

# Get all candidates
begin
    candidates <<  series[pointer..pointer + adjacent_count - 1]
    pointer += 1
end while pointer < pointer_end

# Eliminate All candidates with 0s
candidates = candidates.map {|s| s.include?('0') ? nil : s}.compact

# do the multiplication and compare
candidates.each_with_index do |s, index|
    char_array = s.chars
    product = 1
    char_array.each do |int|
        product = product * int.to_i
    end
    products_array[index] = product
end

answer = products_array.max
equation = candidates[products_array.each_with_index.max[1]].chars * 'x'

puts "Maximum product from this series of digits is #{equation} = #{answer}"

Well I don't know whether I need to eliminate the candidates that contains zeroes in it or just directly go multiply all of those. Not sure if it will save up time using map method first, Any thoughts?

And for the last bit I tried to print out which candidate brings up this largest product so I created another array to store it. It seems it can be done in a more elegant way. Any thoughts?


texts:
I was never really sure what the cleanest way would be to use JSP-Pages for receiving sent parameters. It's common knowledge to use as little JSP as possible - yet as some things have to be done there, for example the request.getParameter-Commands.

Right now most of my pages which are fetching parameters look like that, but I'm still not sure if this is clean enough:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%!
int id=0;
double price = 0;
%>
<%
    String article = request.getParameter("article");

    try {
        price = Double.parseDouble(request.getParameter("price"));
    } catch (NumberFormatException nufo) {
    } catch (NullPointerException nupo) {
    }

        try {
        id = Integer.parseInt(request.getParameter("id"));
    } catch (NumberFormatException nufo) {
    } catch (NullPointerException nupo) {
    }

    String user = session.getAttribute("user").toString();
%>
<jsp:useBean class="mybean.UsedBean" id="beanie" scope="page">
    <jsp:setProperty name="beanie" property="article" value="<%=article%>"/>
    <jsp:setProperty name="beanie" property="id" value="<%=id%>"/>
    <jsp:setProperty name="beanie" property="price" value="<%=price%>"/>
    <jsp:getProperty name="beanie" property="update"/>
</jsp:useBean>

setArticle, setId, setPrice are just regular setters while getUpdate is the method which actually "does" something and returns either true/false, the number of affected lines in the database or some sort of string.

Yet I doubt if this could be done better.

Skipping the receiving-part and directly forwarding the parameters to the fields via:

<jsp:setProperty name="bean" property="para" value="<%=request.getParameter("para")%>"/>

Attribute value request.getParameter("para") is quoted with " which must be escaped when used within the value is causing an exception:

> org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [jsp] in context with path [/Project] threw exception [/project/GetForm.jsp (line: 70, column: 77) Attribute value request.getParameter("para") is quoted with " which must be escaped when used within the value] with root cause
> org.apache.jasper.JasperException: /project/GetForm.jsp (line: 70, column: 77) Attribute value request.getParameter("para") is quoted with " which must be escaped when used within the value

This question has been asked already several times but I'm not sure if I want to "have it solved".

I don't want to have int or double fields in my bean which have String-setters.

Also having a setRequest method in every bean does not really seem to be the best possible way either.

So for my purposes - is the way I'm using the JSPs correct? Or what would be better?


texts: Animation for collapsing/expanding a navigation bar

texts:
I wrote the following to create an animation which collapses a navigation bar, load new content for it and expands it again. Meanwhile, the rest of the page content fades out, loads and fades in again.

It works and looks good, and is even timed well. But my code is one hell of a mess. How could I have done better?

$(function() {
var newHash      = "",
    $NavmainContent = $("#contentNavigationWrapper"),
    $mainContent = $(".contentWrapper"),
    $first       = $('#currentSection'),
    $second      = $('#project-tools'),
    $third       = $('#project-pagetools'),
    $fourth      = $('#cp'),
    $pageWrap    = $("#page-wrap"),
    baseHeight   = 0,
    $el;

$pageWrap.height($pageWrap.height());
baseHeight = $pageWrap.height() - $NavmainContent.height();

$("nav").delegate("a", "click", function() {
    _link = $(this).attr("href");
    history.pushState(null, null, _link);
    loadContent(_link);
    return false;
});

function loadContent(href){

    $mainContent
        .find("#guts")
        .fadeOut(1000, function() {
            $mainContent.hide().load(href + " #guts", function() {
                $mainContent.fadeIn(1000);

            });
        });

    $NavmainContent
        .find('#inner-cn')
        .find("#project-pagetools,#project-tools,#cp,#currentSection")
        .animate({
            'width': '0'
        },800);

    setTimeout(function(){
        $first.load(href + " #currentSection span");
        $second.load(href + " #project-tools li");
        $third.load(href + " #project-pagetools li");
        $fourth.load(href + " #cp span");
    },900);

    setTimeout(function(){

        var l = $("#project-tools li").length ;

        l = 100 / l ;
        l = l + '%';
        $("#project-tools li").css({
            'width': l
        });

        $NavmainContent
            .find("#project-pagetools,#project-tools")
            .animate({
                'width': '15%'
            },800);

        $NavmainContent
            .find("#currentSection")
            .animate({
                'width': '10%'
            },800);

        $NavmainContent
            .find("#cp")
            .animate({
                'width': '55%'
            },800);

    },1100);

}

});


texts: Merge adjacent occurrences of identical elements in data collection

texts:
There is a small programming exercise to merge adjacent identical elements in a collection.

Here are two solutions (passing the tests from the exercise).
I am asking for review of the first version using standard algorithms.
The second is just for reference of the expected behavior.

template <typename ForwardIterator, typename OutputIterator, typename Equal, typename Merge>
void merge_adjacent(ForwardIterator first, ForwardIterator last, OutputIterator out, Equal equal, Merge merge)
{
    while(first != last){
    auto start = first;
    auto stop = std::find_if_not(start,last,[&](auto const &t){return equal(*start,t);});
    if(start != stop){
        out = std::accumulate(start+1,stop,*start,merge);
    }
    else{
        out = *start;
    }
    first = stop;
    }

    /*
    while(first != last)
    {
        auto next = *first;
        first++;
        while((first != last) && (equal(next,*first)))
        {
            next = merge(next,*first);
            first++;
        }
        out = next;
    }
    */
}


texts:
I have two code snippets, doing exactly the same thing and both get the job done:

use defaults
use from config

Which is cleaner to use in golang and why?

first option:

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(getShCfg(Cfg{}), "\n================")
    fmt.Println(getShCfg(Cfg{"8MB", "4MB"}), "\n================")
    fmt.Println(getShCfg(Cfg{"8MB", ""}), "\n================")
    fmt.Println(getShCfg(Cfg{"", "4MB"}), "\n================")
}

type Cfg struct { A, B string }

func getShCfg(c Cfg) string {
    var out []string

    la := "l_sh_dit conf_data 7MB"
    lb := "l_sh_dit cert_data 3MB"

    if len(c.A) > 0 {
        out = append(out, "l_sh_dit conf_data " + c.A)
    } else {
        out = append(out, la)
    }
    if len(c.B) > 0 {
        out = append(out, "l_sh_dit cert_data "+c.B)

    } else {
        out = append(out, lb)
    }

    return strings.Join(out, ";\n\r") + ";"

}

second option:

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(getShCfg(Cfg{}), "\n================")
    fmt.Println(getShCfg(Cfg{"8MB", "4MB"}), "\n================")
    fmt.Println(getShCfg(Cfg{"8MB", ""}), "\n================")
    fmt.Println(getShCfg(Cfg{"", "4MB"}), "\n================")
}

type Cfg struct { A, B string }

func getShCfg(c Cfg) string {
    out := []string{
        getCfgProp("l_sh_dit conf_data", c.A, "7MB"),
        getCfgProp("l_sh_dit cert_data", c.B, "3MB"),
    }
    return strings.Join(out, ";\n\r") + ";"

}

func getCfgProp(key, val, def string) string {
    if len(val) > 0 {
        return key + " " + val
    }
    return key + " " + def
}

I would prefer the second option as it is more scalable i.e. if there are more than 2 parameters (two if else)  so in this case I'm skipping on another if-else in the code …

But in case there are only 2 parameters, is it worth to create a helper function?

Also if there is a better/cleaner approach to achieve it with Golang please let me know


texts: Adapter for RecyclerView with supported onClick handling and select color text on last clicked item

texts:
I have written an adapter for RecyclerView. It can handle onClicks for RecyclerView items and select the color name and edit TextView for the clicked item. By default the first item TextView name is the selected color.
When a user clicks another item the last item TextView is named black. When the the user clicks a color, such as granadier, then the TextView is changed to that color's name. And so on.

Can my code quality and code style be improved? Additionally I'm not a fan of, when a user clicks on new item, calling notifyDataSetChanged on all items.

AudioRecordsListAdapter.kt

class AudioRecordsListAdapter :
    RecyclerView.Adapter<AudioRecordsListAdapter.AudioRecordViewHolder>() {

    var items: MutableList<AudioRecordUI> = ArrayList()
        set(value) {
            if (value.size > 0) {
                value.first().isActive = true
            }
            items.clear()
            items.addAll(value)
            notifyDataSetChanged()
        }

    var isSelectableMode = false
    var onAudioRecordClickListener: OnAudioRecordClickListener? = null

    companion object {
        var dateFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm")
        var timeFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("mm::ss")
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AudioRecordViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.sound_record_item, parent, false)
        return AudioRecordViewHolder(view)
    }

    override fun getItemCount(): Int {
        return items.size
    }

    override fun onBindViewHolder(holder: AudioRecordViewHolder, position: Int) {
        holder.bind(items[position])
    }

    inner class AudioRecordViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        private var audioRecordUI: AudioRecordUI? = null

        fun bind(audioRecordUI: AudioRecordUI) {
            this.audioRecordUI = audioRecordUI

            val size = formatFileSize(itemView.context, audioRecordUI.getSize())

            itemView.name.text = audioRecordUI.getName()
            itemView.date.text = audioRecordUI.getDate().format(dateFormatter)
            itemView.time.text = audioRecordUI.getTime().format(timeFormatter)
            itemView.size.text = size
            itemView.select.isChecked = audioRecordUI.isSelect

            if (audioRecordUI.isActive)
                itemView.name.setTextColor(itemView.context.getColor(R.color.grenadier))
            else
                itemView.name.setTextColor(itemView.context.getColor(R.color.black))

            setClickListener(audioRecordUI)
            setLongClickListener()
        }

        private fun setClickListener(audioRecorderUI: AudioRecordUI) {
            itemView.setOnClickListener {
                if (isSelectableMode) {
                    itemView.select.isChecked = !itemView.select.isChecked
                } else {
                    onAudioRecordClickListener?.onClick(audioRecorderUI.audioRecorderEmpty)
                    clearActive()
                    audioRecorderUI.isActive = true
                    notifyDataSetChanged()
                }
            }
        }

        private fun clearActive() {
            items.forEach { it.isActive = false }
        }

        private fun setLongClickListener() {
            itemView.setOnLongClickListener {
                isSelectableMode = !isSelectableMode

                if (!isSelectableMode) {
                    clearSelect()
                }

                itemView.select.isChecked = !itemView.select.isChecked
                true
            }
        }

        private fun clearSelect() {
            items.forEach { it.isSelect = false }
            notifyDataSetChanged()
        }
    }

    interface OnAudioRecordClickListener {
        fun onClick(audioRecordEmpty: AudioRecordEmpty)
    }

}


texts:
Here is what I'm starting with. It is just some
 tags in a
 tag.

Arcmarks &copy;

About

Privacy

Contact

Developers

This post seems a bit unrelated as I just want to know the HTML/CSS structure for a horizontal menu.

Here is what it looks like and what I want it to look like:


texts: Using [ChildActionOnly] for generating links

texts:
I have a view which displays a list of items, in each row I'm going to have a link, a link in each row points to different location So base upon a property called CertificationType I have to generate an address, for example if the type equals to 'BirthCertificate' I need to fetch the address from a table called BirthCertificates. So I decided to use a ChildActionOnly action method because in my controller I can easily access to context and fetch the result, That why I didn't use HTML helpers.

View:

foreach(var item in Model)
{
   //...

}

Controller:

public class MainController : Controller
{
    //...
    private readonly IUserCertificateService _certificateService;
    public MainController(IUserCertificateService certificateService)
    {
        _certificateService = certificateService;
        //...
    }
    [ChildActionOnly]
    public ContentResult GetFilePath(CertificateType type, Guid certificateFkId)
    {
        var fileName = "";
        switch (type)
        {
            case CertificateType.Shenasnameh:
            {
                var result = _birthCertificateService.GetBirthCertificateById(certificateFkId);
                fileName = string.Format("/Content/Files/UserDocs/{0}/{1}", result.User.UserName, result.ShenasNamehFileName);
            }
            break;
            //....
        }
        return Content(fileName);
    }
}

It works like a charm. But I wanted to know Is there a better solution?

Any idea?


texts:
I tried to make a function able to compute the binary sum. Binary numbers are passed as list composed of 1 and 0, like [1,1,0,1], [0,0,1], etc.
It seems to work. I tried to improve the code, but I don't think  this is the best way to make it work. How can I improve this?

def check(value):
    if value%2 == 0: #check if the number can be divided by 2
        amount = int(value / 2) #if so, set the value to 0 and the amount as the number divided by 2
        value = 0
    elif value%2 != 0: #if not so, set the value to 0 and the amount as the previous even number divided by 2
        amount = int((value-1)/2)
        value = 1
    return value, amount #returns the 2 value.

def binary_sum(*args):
"""The program compute the binary sum of 2+ binary lists, like [1,1,1,1] + [0,0,0,1]"""
    i = -1 #control variable
    result = [] #list that will be filled by results' binary numbers
    value = 0
    amount = 0 #amount carried over
    binaryLength = [] #list of all args length
    for x in args:  binaryLength.append(len(x)) #get the length of each args elements
    maxLength = max(binaryLength) #get the max length among args elements
    for x in args:
        if len(set(binaryLength)) != 1: #checks if all elements have the same length
            delta = maxLength - len(x) - 1 #if not so, it adds as many zeros as delta value indicates
            while (delta) >= 0:
                x[:0] = [0]
                delta -= 1
    while i >= -maxLength: #starts the sum from the end.
        for j in args: value += j[i] #get the sum of all the last list element( for each arg)
        value += amount
        value, amount = check(value) #uses binary sum properties: it returns a value between 0 and 1, and the amount, an integer
        result.insert(i, value) #inserts the value at the beginning of the list
        i-=1 # needed to iterate the process
        value = 0 #resets the value
    if amount != 0: #At the end, if there's amount it inserts it at the beginning of result list:
        while amount not in [0,1]: #if is not equal to 0 or 1 converts the int amount in binary number
            value = amount
            value, amount = check(value)
            result.insert(i, value)
            i-=1
        result.insert(i, amount) #if is equal to 1 inserts it at the start of the list.
    return result #returns the result as list.


texts:
I have the following function that is supposed to compare current and historical transactions for each id. The logic seems to work ok, but the performance is extremely low for the amount of data I'm processing (about 20 million records); more than 10 hours to run.  What can I do to improve the performance?

Functions

def compare_historical(data):
    month_start = datetime.now().replace(day=1).isoformat()
    data_1 = data[data['trxn_datetime'] >= month_start ]
    data_1 = data_1[['id', 'amount']].groupby('id').agg(
            {'amount': 'sum'}).reset_index()
    data_n = data[data['trxn_datetime'] < month_start]
    data_n = data_n[data_n['id'].isin(data_1['id'])
    data_n = data_n.set_index('trxn_datetime')
    data_n = data_n.groupby('id').apply(
           lambda g: _compare_trend(g)).reset_index()

    data_1 = data_1.merge(data_n, on='id', how='right')
    data_1 = data_1[data_1['amount'] >= data_1[0]]
    data = data[data['id'].isin(data_1['id'])]

    return data

def _compare_trend(group):
    group = group['amount'].resample('1M').apply('sum')
    group = group[group != 0]
    mean = group.mean()
    std = group.std()

    return mean + 2 * std

Testing

import pandas as pd
import io
import requests
from datetime import datetime

url="https://api.mockaroo.com/api/49d8d220?count=1000&key=1d2c2410"
s=requests.get(url).content
c=pd.read_csv(io.StringIO(s.decode('utf-8')))
c['trxn_datetime'] = pd.to_datetime(c['trxn_datetime'])
compare_historical(c)

cProfile-ing

Here is some profiling I did using the mock data (with 40 million records and 3135 ids). The only difference is that this data has a limited number of id's compared to actual data.


texts:
I have a plist file which has URLs in it and struct class is feeding from this plist. This struct class has static variable which I use to reach URLs in every part of the app. My question is that I'm defining this static instance with "!". I can also define it with optional ("?"). I'm not sure If I'm declaring singleton variable in right way.

Note: If something happens with reading Plist or creating struct class, app needs to display a message or something then close. So reading successfully is mandatory.

    struct URLs: Codable {
    let urlBaseURL: String
    let urlCheckCMS: String
    let urlJSON: String

    static var instance: URLs!

    enum CodingKeys: String, CodingKey {
        case urlBaseURL = "base_url"
        case urlCheckCMS = "check_cms_url"
        case urlJSON = "table_json_url"
    }

}

// MARK: Convenience initializers

extension URLs {

    init?(data: Data) {
        guard let me = try? PropertyListDecoder().decode(URLs.self, from: data) else { return nil }
        self = me
        URLs.instance = me
    }

    init?(_ plist: String, using encoding: String.Encoding = .utf8) {
        guard let data = plist.data(using: encoding) else { return nil }
        self.init(data: data)
    }

    init?(fromURL url: String) {
        guard let url = URL(string: url) else { return nil }
        guard let data = try? Data(contentsOf: url) else { return nil }
        self.init(data: data)
    }

    var plistData: Data? {
        return try? PropertyListEncoder().encode(self)
    }

    var plist: String? {
        guard let data = self.plistData else { return nil }
        return String(data: data, encoding: .utf8)
    }
}

If I try to declare singleton as usual way;

static let instance = URLs()

It gives below error;

  Cannot invoke initializer for type 'URLs' with no arguments

So I get rid of this error by writing a default init method in which I read plist file and write it to instance. However, I'm not sure with this.


texts:
I'm currently working on a project where i need to access objects from various places, pretty much like std::shared_ptr. At a certain point (e.g. when a library is unloaded) i need to destruct these objects. It is crucial to the project that the object is really destructed at this point, i can not just hand out weak_ptr and rely that no one keeps a shared_ptr. If i would just hand out weak_ptr to other parts of the program, anyone could call lock() and store the shared_ptr, delaying or preventing destruction of the objects. This would crash my program.

What happens in the background is this: I have a small number of classes providing generic access to yet unknown types, e.g. a class Object providing a method virtual getChilds()=0;. Libraries might then inherit from those classes with a class template <O> class TemplateObject; implementing the pure virtual functions. This way other parts of the program, including a GUI, can access in a limited way objects of a type, which was unknown at compile time. But if i destruct the Object with its virtual destructor, i call code that lives in the library - which obviously fails if i have already unloaded the library. I therefore need to make sure that the Object is destructed when the library is unloaded. The GUI e.g. is then able to notice that the object is already gone and can no longer be used.

My Idea was to create two smart pointers, namely master_ptrand slave_ptr. The master_ptr behaves pretty much like a unique_ptr or like "the one and only" shared_ptr, destructing the managed object. The slave_ptr acts much like a weak_ptr, just allowing a more direct access and hiding the option to get back the shared_ptr. The managed objects would be non-copyable and non-movable to make sure there are no copies left somewhere.

My implementation looks like this:

class ObjectInvalid{};

template <typename O>
class slave_ptr {
private:
    std::weak_ptr<O> m_ptr;

public:
    slave_ptr() {}
    slave_ptr(std::shared_ptr<O> ptr) : m_ptr(ptr) {}

    O& operator*() const {
        if (m_ptr.expired())
            throw ObjectInvalid();

        return m_ptr.lock().operator*();
    }

    O* operator->() const {
        if (m_ptr.expired())
            throw ObjectInvalid();

        return m_ptr.lock().operator->();
    }

    void reset() {
        m_ptr.reset();
    }
};

template <typename O>
class master_ptr {
private:
    std::shared_ptr<O> m_ptr;
public:
    master_ptr() = default;
    master_ptr(O* ptr) : m_ptr(ptr) {}

    //non-copyable
    master_ptr(const master_ptr&) = delete;
    master_ptr& operator=(const master_ptr&) = delete;

    //movable
    master_ptr(master_ptr&& other) = default;
    master_ptr& operator=(master_ptr&& other) = default;

    O& operator*() const {
        if (!m_ptr)
            throw ObjectInvalid();

        return m_ptr.operator*();
    }

    O* operator->() const {
        if (!m_ptr)
            throw ObjectInvalid();

        return m_ptr.operator->();
    }

    //allows reset before going out of scope
    void reset() {
        m_ptr.reset();
    }

    //cast to slave
    operator slave_ptr<O>() {
        return slave_ptr<O>(m_ptr);
    }
};

A small test tells me it works as i would expect, but before implementing it in a bigger project i wanted to aks here if theres any flaws i didn't see right now or if you could hint me to some improvements.

About priorities: Easy use and safety (no possible memory leaks, objects destructed when needed, exceptions thrown afterwards) are top priorities here. Performance is a "nice to have".


texts: Applying Laplacian smoothing to vertices in a mesh

texts:
I'm totally new in Python and I wrote some code. It is a simple algorithm to smooth objects. I need to find adjacent vertices in mesh and sum their coordinates and after that divide by a number of adjacent vertices. This algorithm is called Laplacian Smoothing.

Could anybody point out how to make it better?

n = mesh.VPos.shape[0]
final = []

for i in range(n):
    neighbors = mesh.vertices[i].getVertexNeighbors()
    indices = map(lambda x: x.ID, neighbors)
    z = len(indices)

    help = []
    for j in indices:
        help.append([mesh.VPos[j]])
    final += [sum(x)/z for x in zip(*help)]

final = np.array(final)
mesh.VPos = final


texts:
I have a mapping application which takes string arguments in the form of string arrays. I parse these and then perform an action on the map. One of these is MoveVertex which lets the user pass in the name of an existing shape/feature on the map, the index of the vertex to move, and a new x,y location to move that vertex to.

I'm currently getting thousands of these in a row, all for the same shape. It takes anywhere from 3-10ish seconds to parse them all and complete the action. I'm looking for any improvements I could make.

One thing I did so far was stop the map from refreshing every time a vertex is moved. This helped a bit, but it's still slow.

Example of the string[] commands being sent:

command[0] = "move" //command type
command[1] = "vertex" //what to move
command[2] = "testLine[10]" //move the vertex at index 10 in testLine's list of vertices
command[3] = "x" //new x value for the vertex
command[4] = "y" //new y value for the vertex

Here's the function that does the work:

public static void MoveVertex(string[] command, Layer inMemoryFeatureLayer, Map map)
{
    int index; //this will be the index of the vertex in the collection of vertices of the shape
    string featureName; //name of the shape/feature that has the vertex to move

    if (command.Length < 5) //can't be more than 5 parameters
    {
        return;
    }

    try
    {
        if (!command[2].Contains('[')) //if it doesn't contain brackets which contain an index of the vertices
        {
            return;
        }

        const string pattern = @"\[(.*?)\]";
        var query = command[2];
        var matches = Regex.Matches(query, pattern); //Gets anything inside the brackets
        index = Convert.ToInt32(matches[0].Groups[1].Value); //should be an int

        featureName = command[2].Substring(0, command[2].IndexOf('[')).ToUpper(); //everything before the bracket is the name of the object
    }
    catch (Exception ex)
    {
        return;
    }

    if (!double.TryParse(command[3], out double longitude) || !double.TryParse(command[4], out double latitude))
    {
        return;
    }

    try
    {
        BaseShape shape;

        inMemoryFeatureLayer.Open(); //make sure the layer is open
        if (inMemoryFeatureLayer.Name.Contains(GlobalVars.LineType)) if it's the layer holding line shapes
        {
            shape = (LineShape)inMemoryFeatureLayer.FeatureSource.GetFeatureById(featureName, ReturningColumnsType.NoColumns).GetShape();
            ((LineShape)shape).Vertices[index] = new Vertex(longitude, latitude); //set the vertex to a new location
        }
        else //it's the layer holdilng polygone shapes
        {
            shape = (PolygonShape)inMemoryFeatureLayer.FeatureSource.GetFeatureById(featureName, ReturningColumnsType.NoColumns).GetShape();
            ((PolygonShape)shape).OuterRing.Vertices[index] = new Vertex(longitude, latitude); //set the vertex to a new location
        }

        inMemoryFeatureLayer.EditTools.BeginTransaction();
        inMemoryFeatureLayer.EditTools.Update(shape);
        inMemoryFeatureLayer.EditTools.CommitTransaction();
        map.Refresh(); //this won't happen because I suspend refreshes beforehand
    }
    catch (Exception ex)
    {
        //log it
    }
}