texts:
I wrote this program just to remove duplicates from wordlist used for brute-force, but it can be used for every txt file i guess.
It is a pretty long program for what it does, and I'm sure there is a way I can make it easier and better for everyone to look at.
I'm still a beginner in python.

def wordcount_initial():  # count the numbre of words in the input file
    global num_words_initial

    with open(file_initial, 'r') as f:
        for line in f:
            words = line.split()
            num_words_initial += len(words)

def dupfilter():
    content = open(file_initial, "r").readlines()
    content_set = set(content)  # filter duplicates
    cleandata = open(file_final, "w+")  # write the text filtered in the new   file

    for line in content_set:
        cleandata.write(line)

def wordcount_final():  # count number of words in the new file
    global num_words_final

    with open(file_final, 'r') as f:
        for line in f:
            words = line.split()
            num_words_final += len(words)

if __name__ == '__main__':
    num_words = 0
    num_words_initial = 0
    num_words_final = 0

    ready = False
    while not ready:
        file_initial = input("What is the name of the text?")

        file_final = input("How do you want to name the filted file?")

        if file_initial and file_final != "":

            wordcount_initial()
            ready = True

    dupfilter()

    wordcount_final()

    print("Number of duplicates filtered:" + str(num_words_initial - num_words_final))
    input("\nPress <ENTER> to quit the program.")


texts: Language switch based on parameters and session state

texts:
I use this to set language session for navigation. Someone said that this switch is too cumbersome. Why? Is there an easier way?

$defaultLang = 'it';

if (!empty($_GET["lang"])) {
    switch (strtolower($_GET["lang"])) {
        case "en":

            $_SESSION['lang'] = 'gb';
            break;
        case "tr":

            $_SESSION['lang'] = 'tr';
            break;
        default:

            $_SESSION['lang'] = $defaultLang;
            break;
    }
}

if (empty($_SESSION["lang"])) {
        $_SESSION["lang"] = $defaultLang;
}


texts:
I am working with some Java code. Basically I have a wrapper class that holds a string and implements some of the many useful python string methods in Java. My goal here is to implement the Python method .ljust and my hope is to be as efficient as possible. Currently, I am using a while loop which I imagine is terrible inefficient especially because it includes a +=. What's more, I am not sure which of the following alternatives is more efficient

String news = "";
news = this.toString();
int length = news.length();
while (length < size) {
        news += " ";
        length++;
}
return new PythonString(news);

In the above case, news.length() is only called once, but now there is an extra int and a new instruction length++.

The other option would be

String news = "";
news = this.toString();
while (news.length() < size) {
        news += " ";
}
return new PythonString(news);

In this case, news.length() is called every time.

I am interested in perspectives on which of these alternatives is most efficient as well as any other optimizations you could provide for this method, which is meant to pad a string with size spaces to the right so that all following characters line up at the same column.


texts: Getting the count of how many times a route has been hit

texts:
I have this log file (example below) and I'm trying to find the number of times a particular route is called.

Example log file:

2019-05-29 11:00:00 192.168.1.1 POST /route1 200  100000

2019-05-29 11:00:01 10.1.1.2 POST /route1 200  100000

2019-05-29 11:00:01 192.168.1.2 GET /route2 404 200000

2019-05-29 11:00:02 192.168.1.3 GET /route3 200  100000

2019-05-29 11:00:03 10.1.1.3 GET /route4 200  200000

2019-05-29 11:00:04 192.168.1.1 POST /route1 200 100000

Here is the code I've written:

route_count = Hash.new(0)
File.open('test.log').each do |line|
  temp_array = line.split(" ")
  route = temp_array[4]
  if route_count.has_key?(route)
    route_count[route] = route_count[route] + 1
  else
    route_count[route] = 1
  end
end
puts( route_count.map{ |k,v| "#{k},#{v}" })

and it gives the output:

/route1,3

/route2,1

/route3,1

/route4,1

I wanted to know if there is a better way to do this.


texts: Formatting big integers as hexadecimal digits separated by colons

texts:
I'm pretty sure this can be written as a couple of lines, but I'm unable to come up with a better solution.

package main

import (
    "fmt"
    "math/big"
)

func colonedSerial(i *big.Int) string {
    hex := fmt.Sprintf("%x", i)
    if len(hex)%2 == 1 {
        hex = "0" + hex
    }
    numberOfColons := len(hex)/2 - 1
    colonedHex := make([]byte, len(hex)+numberOfColons)
    for i, j := 0, 0; i < len(hex)-1; i, j = i+1, j+1 {
        colonedHex[j] = hex[i]
        if i%2 == 1 {
            j++
            colonedHex[j] = []byte(":")[0]
        }
    }
    // we skipped the last one to avoid the colon at the end
    colonedHex[len(colonedHex)-1] = hex[len(hex)-1]
    return string(colonedHex)
}

func main() {
    fmt.Println(colonedSerial(big.NewInt(1234)))
    // "04:d2"
    fmt.Println(colonedSerial(big.NewInt(123456)))
    // "01:e2:40"
    fmt.Println(colonedSerial(big.NewInt(1234567891011121314)))
    // "11:22:10:f4:b2:d2:30:a2"
}

Also the []byte(":")[0] is very ugly. Is there a better way to do that? (I did not wanted to write the ASCII value of colon (58) as it would be a magic number).

Go Playground version: https://play.golang.org/p/GTxajcr3NY


texts:
I tried to implement a stack using Linked Lists. How could I make it more efficient? Any other suggestions will be greatly appreciated. I am a beginner C programmer.

Any other tips to clean up my code?

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

typedef struct NODE {
    int data;
    struct NODE* next;
}node;

node* top = NULL;
// Push Function
void push(int x)
{
    node *temp;
    temp = (node *) malloc(sizeof(node));
    temp -> data = x;
    temp -> next = top;
    top = temp;

}
// Pop function
int pop()
{
    node* temp;
    int num=0;
    temp = top;
    num = temp -> data;
    top = top -> next;
    free(temp);
    return num;
}

int Top()
{
    return top -> data;
}

void display(node *head)
{
    if(head == NULL) printf("NULL!\n");
    else
    {
        printf("%d\n", head -> data);
        display(head->next);
    }
}
int main() {
    int element,choice,val,tp;
    do
    {
    printf("---Stack Operations---\n");
    printf("1.PUSH\n");
    printf("2.POP\n");
    printf("3.DISPLAY\n");
    printf("4.Top element\n");
    printf("5.EXIT\n");
    printf("Enter an option\n");
    scanf("%d",&choice);

    switch(choice)
    {
        case 1:
        printf("Enter the element to push\n");
        scanf("%d",&val);
        push(val);
        break;

        case 2:
        element = pop();
        printf("Popped element is: %d\n",element);
        break;

        case 3:
        display(top);
        break;

        case 4:
        tp = Top();
        printf("Top element is:%d\n",tp);
        break;

        case 5:
        exit(0);
        default:
        printf("Enter a valid option\n");
        }
    }while(choice != 5);

}


texts: Eliminate duplication in similar fake data access classes

texts:
Can I combine this two classes and have one fake db class?

public class FakeDb : Dictionary<string, List<string>>
{
    public const string Table1 = "Table1";

    public void AddToTable(string tableName, string line)
    {
        if(!ContainsKey(tableName))
            Add(tableName, new List<string>());

        List<string> rows = GetTableData(tableName);
        rows.Add(line);
    }

    internal List<string> GetTableData(string tableName)
    {
        return this[tableName];
    }
}

public class FakeComplexDb : Dictionary<string, List<Dictionary<string,List<string>>>>
{
    public void AddToTable(string tableName, Dictionary<string, List<string>> line)
    {
        if (!ContainsKey(tableName))
            Add(tableName, new List<Dictionary<string, List<string>>>());

        List<Dictionary<string, List<string>>> rows = GetTableData(tableName);
        rows.Add(line);
    }

    internal List<Dictionary<string, List<string>>> GetTableData(string tableName)
    {
        return this[tableName];
    }
}


texts: Fibonacci-Counter implemented with React-Redux

texts:
After learning the basics of React-Redux I've made an app to familiarize myself more with the concepts. It's a counter which counts-up the Fibonacci-Number.

Here's my code:

// -- index.js -----------------------------------
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

// ---- App.js -------------------------------------------
import React, { Component } from 'react';
import { Provider } from "react-redux";
import { createStore } from "redux";

import FibonacciCounter from "./FibonacciCounter";
import './App.css';

const init = {
  index: 1,
  last: 1,
  current: 1
}

const reducer = (state = init, action) => {
  switch (action.type) {
    case "NEXT":
      const lastCopy = state.last;
      const currentCopy = state.current;

      return {
        ...state,
        last: state.current,
        current: currentCopy + lastCopy,
        index: state.index + 1
      };
    default:
      return state;
  }
}

const store = createStore(reducer);

class App extends Component {
  render() {
    return (
      <Provider store={store}>

          <FibonacciCounter />

      </Provider>
    );
  }
}

export default App;

// -------- FibonacciCounter.js -------------------------------------
import React, { Component } from 'react';
import { connect } from "react-redux";

class FibonacciCounter extends Component {
    render() {
      return (

                {("00" + this.props.index).slice(-3)}. Fibonacci Number:
                {this.props.current}

                Increment

      );
    }
  }

  const mapStateToProps = (state) => {
    return {
        current: state.current,
        index: state.index
    };
  }

  const mapDispatchToProps = dispatch => {
      return {
          onNext: () => {
              dispatch({
                  type: "NEXT"
              });
          }
      }
  }

  export default connect(mapStateToProps, mapDispatchToProps)(FibonacciCounter);

Is my implementation of the concepts correct and done in a good way and fashion? What shall / must I change and why?

Looking forward to reading your answers and comments.


texts:
The Problem

  A character is known to its homeboys as a super freq if it occurs with frequency greater than 15% in a given passage of text. Write a program that reads an ASCII text file and identifies all the English alphabet (A-Z, a-z) super freqs in that text file. Your program should be case insensitive.

  Sample Input

  Your program should take its input from the text file prob2.in. Three examples (A, B and C) of the possible content of this file are shown below:

(A) Sally sells sea shells by the sea shore.
(B) How now brown cow.
(C) Hey Sam!

  Sample Output

  Your program should direct its output to the screen. Appropriate output for the sample inputs (A, B and C) is shown below:

(A) S is a super freq.
(B) O is a super freq.
    W is a super freq.
(C) There are no super freqs.

superfreq.py

import re
from collections import Counter

with open('prob2.in') as f:
    for line in f:
        s = re.sub(r"[^a-z]+", '', line.lower())
        d, c = Counter(s), 0
        for e in d:
            if d[e] / len(line) > 0.15:
                print('{0} is a super freq.'.format(e.upper()))
                c += 1
        if (c == 0):
            print('There are no super freqs.')

Any advice on performance enhancement and solution simplification or that is topical is appreciated!


texts:
This is all about a whole lot of animations which should happen sequentially. That's why I am using promise().done() functions. In the end I'm binding a function to the mousemove event (similar to a dragging feeling on hover).

How can I optimize / shorten it?

function showSpecialNavigation(){
    $('.special-navigation_section').each(function(i) {
        $(this).delay(400*i).fadeIn('fast');
        $(this).find('li').each(function(i2) {
            $(this).delay(400*i).fadeIn('800');
        });
    }).promise().done(function(){
        $(".special-navigation_section").each(function(i3) {
            $(this).find('a.transition_text').fadeIn('800');
        }).promise().done(function(){
            $(".showup1").each(function(i4) {
                $(this).delay(50*i4).fadeIn('fast').delay(10).find('img').fadeIn('fast');
            }).promise().done(function(){
                $(".showup2").each(function(i5) {
                    $(this).delay(50*i5).fadeIn('fast').delay(10).find('img').fadeIn('fast');
                }).promise().done(function(){
                    $(".showup3").each(function(i6) {
                        $(this).delay(50*i6).fadeIn('fast').delay(10).find('img').fadeIn('fast');
                    }).promise().done(function(){
                        $(".showup4").each(function(i7) {
                            $(this).delay(50*i7).fadeIn('fast').delay(10).find('img').fadeIn('fast');
                        }).promise().done(function(){
                            $(".showup5").each(function(i8) {
                                $(this).delay(50*i8).fadeIn('fast').delay(10).find('img').fadeIn('fast');
                            }).promise().done(function(){
                                $(".showup1, .showup2, .showup3, .showup4, .showup5").find('.handle').css({display: 'block'});
                                $(".dragged").each(function(i9) {
                                    $(this).delay(20*i9).animate({width: '130px'}, 300);
                                }).promise().done(function(){
                                    $(".transition").bind("mousemove", function(event){
                                        var dragged         =   $(this).find('.dragged');
                                        var containerWidth  =   $(this).width();

                                        var stopLeft        =   56;
                                        var stopRight       =   132;
                                        var mouse2Container =   event.pageX - $(this).offset().left;
                                        var controller      =   mouse2Container-56;

                                        if((stopRight > mouse2Container) && (mouse2Container > stopLeft)){
                                            dragged.stop(true, false).animate({left: controller}, 200);
                                        }
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });
    });
}


texts: Encryption scripts using the module cryptography

texts:
Its meant to password protect python scripts by using encryption
It should use os.urandom(40)'s output in hex as the salt. The kdf (cryptography.io) is using Scrypt (cryptography.io) password input is using getpass.getpass. It's on my GitHub: Python Script Locker (GitHub), and is required to work with both Python 2 and 3.

#!/usr/bin/env python
import sys
def exitmsg(msg):
    print(msg)
    input("Press ENTER to exit the script")
    sys.exit()
if sys.version_info<(3,0,0):
    def input(string):
         return raw_input(string)
import base64
import binascii
import os
import getpass
try:
    from cryptography.fernet import Fernet
except ImportError:
    exitmsg("cryptography not installed install it with pip install cryptography via cmd or powershell (On Windows)")
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
print("PyLock beta v1.0.3 https://github.com/OfficialNoob/Python-Script-Locker")
salt = binascii.hexlify(os.urandom(40))
kdf = Scrypt(salt=salt,length=32,n=2**14,r=8,p=1,backend=default_backend())
loc = input("Script to use: ")
try:
    fscript = open(loc)
except IOError:
    exitmsg("Unable to read file")
script = fscript.read()
fscript.close
print("Can be used to overwrite your script")
sloc = input("Save as: ")
nc = '''#!/usr/bin/env python
#Made using PyLock https://github.com/OfficialNoob/Python-Script-Locker
import sys
def exitmsg(msg):
    print(msg)
    input("Press ENTER to exit")
    sys.exit()
if sys.version_info<(3,0,0):
    def input(string):
         return raw_input(string)
import getpass
import base64
try:
    from cryptography.fernet import Fernet
except ImportError:
    exitmsg("cryptography not installed install it with pip install cryptography via cmd or powershell (On Windows)")
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
kdf = Scrypt(salt=%s,length=32,n=2**14,r=8,p=1,backend=default_backend())
try:
    exec(Fernet(base64.urlsafe_b64encode(kdf.derive(getpass.getpass("Password to use: ").encode()))).decrypt(%s))
except Exception as ex:
    if(type(ex).__name__ == "InvalidToken"):
        exitmsg("Wrong password (-:")
    print(ex)''' % (salt, Fernet(base64.urlsafe_b64encode(kdf.derive(getpass.getpass("Password to use: ").encode()))).encrypt(script.encode()))
try:
    f = open(sloc,"w+")
    f.write(nc)
except IOError:
    exitmsg("Unable to write to file")
f.close
exitmsg("Your file has been created")


texts: Testing a Collatz Conjecture Conjecture (Python)

texts:
I had an intuition that the maximal trajectory lengths for collatz conjecture numbers would be produced by numbers of the form (2**n)-1 so I wrote a program to test it (I was wrong). I thought I would put it up for review to catch any coding sins I committed, and see how others would improve my code.
Orginal Code
'''
*    I had a conjecture that maximal trajectory lengths for the collatz conjecture were yielded by numbers of the form (2**n)-1. This program attempts to test it.
*    "conjecture()" finds the number with the highest trajectory lengths in a given range. The ranges are of the form [2**n, 2**(n+1)).
'''

import math, pprint

f = open("CollatzConjecture.txt")
text =  f.read()

def key(value, dct):
    for key in dct.keys():
        if dct[key] == value:
            return key
    return None

def conjecture(text):
    traj = {int(j.split(" ")[0]): int(j.split(" ")[1]) for j in text.split("\n")}    #Processes the text file into a dict mapping numbers to their trajectory length.
    result = {}
    bound = math.floor(math.log(len(traj),2))
    traj2 = {num: traj[num] for num in list(traj.keys())[:2**bound+1]}    #Slices the dictionary to receive the section of interest.
    for st in (2**x for x in range(1, bound+1)):        #Generator for powers of 2.
        slce = list(traj2.items())[int((math.log(st,2)-1)**2):st]    #Slices "traj2" into powers of 2.
        result[st] = key(max([n[1] for n in slce]), traj2)
    return pprint.pformat(result)

print(conjecture(text))

"CollatzConjecture.txt" is a text file containing number trajectoryLength on separate lines. I wanted to find the number corresponding to the maximum trajectory length between successive powers of 2 in order to test my hypothesis.


texts:
I am fetching data from the database using Entity Framework and Linq queries. I am wondering about the performance of getting data. I just want to check whether or not a well exists in the database. The database table has 15 columns and the number of rows are unknown.

internal static bool WellExists(string name, DatabaseContext context)
{
    var name = context.Wells.Where(w => w.name == name).Select(w => w.name).FirstOrDefault();
    return !string.IsNullOrEmpty(databaseUwi);
}

Here my point of concern is the line in which I am using Linq queries. In this I am using a Where, then Select and then FirstOrDefault. Another solution is using FirstOrDefault only.

var well = context.Wells.FirstOrDefault(w => w.name == name);
return !(well == null);

The first query will get only selected data (Select) which is not required. Which solution's performance is better?


texts: Pythonic code to convert 3 digit number into all possible letter combinations

texts:
Given a dictionary where 1:a , 2:b ... 26:z. I need to find all the possible letter combinations that can be formed from the three digits.

Either each digit should translate to a letter individually or you can combine adjacent digits to check for a letter. You can't change the order of the digits. For example -

121 translates to aba, au, la;

151 translates to aea, oa;

101 translates to ja;

I was able to get this working but I feel my code is not very "pythonic". I am trying to figure out a more efficient & python-like solution for this problem.

# creating the dict that has keys as digits and values as letters
root_dict = {}
for num in range(0,26):
    root_dict[str(num+1)] = string.ascii_lowercase[num]

# asking user for a three digit number
sequence_to_convert = raw_input('Enter three digit number \n')

# storing all possible permutations from the three digit number
first_permutation = sequence_to_convert[0]
second_permutation = sequence_to_convert[1]
third_permutation = sequence_to_convert[2]
fourth_permutation = sequence_to_convert[0]+sequence_to_convert[1]
fifth_permutation = sequence_to_convert[1]+sequence_to_convert[2]

# checking if the permutations exist in the dict, if so print corresponding letters
if first_permutation in root_dict and second_permutation in root_dict and third_permutation in root_dict:
    print root_dict[first_permutation]+root_dict[second_permutation]+root_dict[third_permutation]
if first_permutation in root_dict and fifth_permutation in root_dict:
    print root_dict[first_permutation]+root_dict[fifth_permutation]
if fourth_permutation in root_dict and third_permutation in root_dict:
    print root_dict[fourth_permutation]+root_dict[third_permutation]


texts:
I have a small Django project to help organize museum artwork. In my models.py file, my museum object is defined as follows:

class Museum(models.Model):
    """Model representation of an art museum"""
    title = models.CharField(max_length=50)
    website = models.URLField()
    description = models.TextField()
    image = models.ForeignKey(AppImage, blank=True, null=True)
    longitude = models.FloatField()
    latitude = models.FloatField()

    @property
    def marker_info(self):
        """Get information accessible for google map"""
        return { "title": self.title, "website" : self.website, "description" : self.description,
            "latitude" : self.latitude, "longitude" : self.longitude, "id" : self.id }

    @property
    def artwork(self):
        """Get the museum's artwork"""
        return Artwork.objects.filter(museum__id=self.id)

    @property
    def artists(self):
        """Get the museums' unique artists"""
        return { artwork.artist.id : artwork.artist for artwork in self.artwork }.values()

    @property
    def count(self):
        """Get the museum's number of artworks"""
        return len(self.artwork)

    @property
    def nearby(self):
        """Get neighboring museums by distance"""
        return sorted(Museum.objects.all().exclude(id__exact=self.id), key=lambda x: self.distance(x))

    def distance(self, other):
        """ Compute the Euclidean distance between
            this and another museum """
        def cartesian(obj, r=3959): # mean radius of earth in miles
            lon = math.radians(obj.longitude)
            lat = math.radians(obj.latitude)
            x = r * math.cos(lat) * math.cos(lon)
            y = r * math.cos(lat) * math.sin(lon)
            z = r * math.sin(lat)
            return x, y, z

        x1, y1, z1 = cartesian(self)
        x2, y2, z2 = cartesian(other)
        return math.sqrt((x1 - x2)**2 + (y1 - y2)**2 + (z1 - z2)**2)

    def __str__(self):
        return '%s, %s' % (self.title, self.website)

Since most of the business logic for display is stored in the model, my views are pretty clean:

def museum(request):
    return render(request, "museum.html",
        { "museum" : center(request) })

def nearby(request):
    return render(request, "tabs/nearby.html",
        { "nearby" : center(request).nearby })

def artists(request):
    museum = center(request)
    return render(request, "tabs/artists.html",
        { "artists" : [(artist, artist.count(museum)) for artist in museum.artists] })

def gallery(request):
    return render(request, "tabs/gallery.html",
        { "artworks" : center(request).artwork })

def center(request):
    return Museum.objects.get(pk=request.GET['id'])

With the MVVM pattern, we would put these functions in a view model class rather than in a model class. Coming from this perspective, I'm concerned that my business logic is crowding and polluting the purity of my model. Is this a valid concern? Is there a better place I should be putting these properties and business logic functions?


texts: IniReader template overrides become ambiguous

texts:
I was tasked with refactoring our existing IniReader class, which is Windows only compatible, to be cross-platform ( specifically UNIX compatible ). We decided that boost::property_tree was a good fit for this and a quick play with property_tree confirms this.

The original class had many readValue overloads for the various data types. During the refactoring I was happy to discover that boost::property_tree::get_value is templatized so it made it simple to declare the following new readValue functions:

// read and return a value from the inifile
// throws boost::property_tree:ptree_error if not found
template <class T>
T readValue( const std::string& section, const std::string& param ) const;

// read and return value from section.param in the inifile
// if the param does not exists in the section return |defaultValue|
template <class T>
T readValue( const std::string& section, const std::string& param, const T& defaultValue ) const;

However, I later discover there's a couple of special overridden readValue functions which accept an additional int index. This allows values to be read using param name appended with the index value like this:

[TextFileFilters]
count=3
filter1=*.txt
filter2=*.csv
filter3=*.log
num1=50
num2=20
num3=10

Originally I thought of adding two more readValue overrides which includes the index argument:

// read and return a value from the inifile
// throws boost::property_tree:ptree_error if not found
template <class T>
T readValue( const std::string& section, const std::string& param, const int index ) const;

// read and return value from section.param in the inifile
// if the param does not exists in the section return |defaultValue|
template <class T>
T readValue( const std::string& section, const std::string& param, const T& defaultValue, const int index ) const;

BUT, there's a problem. When using T = int it becomes ambiguous to the compiler:

// is 3 the default int value OR the index ?
int count = ini.readValue<int>( "TextFileFilters", "num", 3 );

What I've done, currently, is to remove the 3 parameter "indexed" override of readValue. Therefore mandating that all indexed readValue calls must be called with the default argument. This is not ideal.

The only thoughts around this I have was to introduce an new IniPath class, which attempts to replace the section, param or section, param, index combinations:

class IniPath
{
public:
  IniPath( const std::string& section, const std::string& path );
  IniPath( const std::string& section, const std::string& path, const int index );
};

...

template <class T>
T readValue( const IniPath& path ) const;

template <class T>
T readValue( const IniPath& path, T& defaultValue ) const;

but does that seems excessive? Too many temporaries?

int count = ini.readValue<int>( IniPath( "TextFileFilters", "count" ) );
int log_num = ini.readValue<int>( IniPath( "TextFileFilters", "num", 3 ) );

Do you have any suggestions or ideas?


texts: Initialize a hash with all 0 values based on two arrays

texts:
Given two arrays (for instance a list of people and a list of subjects), I need to initialise a Hash with all zeros for all possible combinations of these two arrays. I can manage to do that with the code on the bottom, but it seems like there should be a less convoluted, more elegant way to do this.

people = %w(tom mary rob)
subjects = %w(math english)

Hash[people.map { |person| [person, Hash[subjects.map { |subject| [subject, 0] }]]}]

# output: => {"tom"=>{"math"=>0, "english"=>0},
# "mary"=>{"math"=>0, "english"=>0},
# "rob"=>{"math"=>0, "english"=>0}}


texts: Reading configuration from a file for video rendering

texts:
I haven't done anything similar so I got nothing to go on. The point was to load everything from the file and I thought a struct would be a good choice to be the handler to store the information.

The loading part is, however, not really something that is to my satisfaction as I find it very primitive and illusive. I try to walk around issues as I don't really know how to handle them if anything goes awry.

    //Set Config Value from File
bool ConfigValue(std::string contents, std::string setting, unsigned int& MySettings){
    int pos1 = NULL, pos2 = NULL;
    pos1 = contents.find(setting);
    pos2 = contents.find('\n', pos1);
    if (pos1 == -1)
        return false;
    else
        pos1 += setting.length();
    contents = contents.substr(pos1, pos2 - pos1);
    for (int i = 0; i < contents.length();i++){
        if (!(contents[i] >= '0' && contents[i] <= '9' || contents[i] == ' '))
            return false;
    }
    MySettings = std::stoi(contents);
    return true;
}
//Reads ConfigFile with some safe measures if it's wrongly written for some reason
Config ConfigFile(){
start:
    video::E_DRIVER_TYPE renderer = video::EDT_DIRECT3D9;
    //Set Default if file doesn't contain them.
    Config MySettings;
    std::string line;
    fstream input("config.ini", fstream::in);

    if (input){
        //Read config file to buffer
        std::stringstream buffer;
        buffer << input.rdbuf();
        std::string contents(buffer.str());

        if (!ConfigValue(contents, "width=", MySettings.Width) || //Set Width
            !ConfigValue(contents, "height=", MySettings.Height) || //Set Height
            !ConfigValue(contents, "fullscreen=", MySettings.Fullscreen) || //Set Fullscreen
            !ConfigValue(contents, "renderer=", MySettings.renderer))  //Gets renderer value
            goto makeDefault;

        //Set renderer according to value obtained
        switch (MySettings.renderer){
        case 0: MySettings.renderer = video::EDT_DIRECT3D8;
            break;
        case 1: MySettings.renderer = video::EDT_DIRECT3D9;
            break;
        case 2: MySettings.renderer = video::EDT_OPENGL;
            break;
        default: goto makeDefault;
        }
    }
    else{
    makeDefault:
        input.close();
        input.open("config.ini", fstream::out);
        input << "//renderer options - 0: D3D8, 1: D3D9, 2: OpenGL\nwidth=640\nheight=480\nfullscreen=0\nrenderer=1"; //Set Default Resolution;
        goto start;
    }

    return MySettings;
}

Config:

struct Config{
    unsigned int renderer;
    unsigned int Width;
    unsigned int Height;
    unsigned int Fullscreen; //should be bool

};

As you can see, I use goto a lot as a kind of safety net. If anything ever goes awry (in my detection), I reset everything. However, the tests I do to make sure it's correct is something I would like reviewed.

The config in its current state is supposed to contain this:

//renderer options - 0: D3D8, 1: D3D9, 2: OpenGL
width=640
height=480
fullscreen=0
renderer=1

The first line is just an instruction for the renderer as it's kinda hard to guess it. Nothing else needs any instructions so they are normal. It's always supposed to be "WhatItIs=Value". (Worth noting is that Fullscreen is a bool, as 0 and 1 works the same I see no reason to mess with conversion).

Any suggestion on this is wanted as I really find pretty much all of this code to be extremely bad even though it works. But as I got nothing to compare to it, I can only guess.


texts: Largest product in a grid: Project Euler 11


texts:
I have created one method that get whois information from arin server is this any changes in this code for good code structure.

public ArinResponse GetWhoisInfo(string domainName)
{
    if (string.IsNullOrEmpty(domainName))
    {
        throw new ArgumentException("You have to supply a domainName.", nameof(domainName));
    }
    using (var clientService = new HttpClientService<ArinResponse>(arinBaseUrl))
    {
        string query = string.Format("pocs;domain={0}", domainName);
        var arinResponse = clientService.GetAPI(query);
        if (arinResponse != null)
        {
            return arinResponse;
        }
    }
    return new ArinResponse();
}

it should be very helpful to me. thanks.

HttpClientService is generic common class for calling rest api.


texts:
I wrote this quick script to convert a genotype file into a BED file. Running it seems to be taking a very long time.

#BED file format
#http://genome.ucsc.edu/FAQ/FAQformat.html#format1
#1.chrom - The name of the chromosome (e.g. chr3, chrY, chr2_random) or scaffold (e.g. scaffold10671).
#2.chromStart - The starting position of the feature in the chromosome or scaffold. The first base in a chromosome is numbered 0.
#3.chromEnd - The ending position of the feature in the chromosome or scaffold. The chromEnd base is not included in the display of the feature. For example, the first 100 bases of a chromosome are defined as chromStart=0, chromEnd=100, and span the bases numbered 0-99.

from collections import defaultdict
from operator import itemgetter
from itertools import groupby
from __future__ import print_function

genotype = open("<file>", "rU")

def listToRange(list):
    ranges = []
     for k, g in groupby(enumerate(list), lambda (i,x):i-x):
        group = map(itemgetter(1), g)
        ranges.append((group[0], group[-1]))
    return ranges

#Create Dictionary with all positions for each chrom
chromDict = defaultdict(list)

genotypeLines = list(genotype.readlines()[1:])

for item in genotypeLines:
    objects = item.split()

    chromDict[objects[0]].append(int(objects[1]))

#print() implemented in python 3 for use in python 2 need to: from __future__ import     print_function
for key, value in chromDict.iteritems():
    if len(listToRange(value)) > 1:
        for i in range(0,(len(listToRange(value)))):
            print(key, listToRange(value)[i][0],listToRange(value)[i][1], sep="\t")
    else:
        print(key, listToRange(value)[0][0], listToRange(value)[0][1], sep="\t")

#need to capture output to terminal i.e. python script.py > myfile.bed

genotype.close()

Input file example:

Chr             Position 1      2      3
HE669507        9752    C       C       C
HE669507        9753    T       T       T
HE669507        9755    A       A       A

This is what the output looks like. It turns positions into intervals

HE669507        9752    9753
HE669507        9755    9755

I am not sure what is causing it to be so inefficient, but I suspect it might be something to do with the way I print the output.


texts: Finding the last successful route by ID using Python

texts:
I have a script that iterates through a series of URLs that have the same pattern to parse them via BeautifulSoup. The URL structure is an aspx page that ends its route with a sequential id, very similar to this one here.

In my case the challenge is I'm iterating through several routes and I don't know the endpoint, so I don't know when to stop looping through the series.

My attempted remedy could be found in the below code sample. Here you see my soup function that makes a request to the url and returns the soup when the request returns a good status (200).

The next function is a binary search that loops through the range I give with a while loop which stops running when I get a last successful URL request.

import requests
from bs4 import BeautifulSoup

####
#
# Souped Up just makes the request and passes you the soup to parse when there is one available.  Just pass the URL.
#
####
def soupedUp(url):
    theRequest = requests.get(url, allow_redirects=False)
    if theRequest.status_code == 200:
        soup = BeautifulSoup(theRequest.text, "lxml")
    else:
        soup = None
    return soup

def binarySearch(theRange):
    first = 0
    last = len(theRange)-1
    while first <= last:
        middle = (first + last) // 2
        if soupedUp(url+str(middle)) is None:
            last = middle - 1
        else:
            first = middle + 1
    return middle

url = 'http://cornpalace.com/gallery.aspx?PID='

print(binarySearch(range(1,10000000)))

My functions are working, but I feel like there may be a faster, simpler or cleaner approach to find the last route in this URL.

Does anyone have a simpler way to handle this sort of looping through URLs while scraping the same pattern URL?

I'd be happy to see another approach at this, or any python modules that already offer this type of URL probing.


texts:
I've made some improvments on the code from : Csharp-AES-bits-Encryption-Library-with-Salt

saltBytes is now the SHA512 of the password.
Random IV for each encryption call. ( IV length 16 is added to the encrypted file , removed from file before decryption)

Do you see any flows, something that needs optimization ?

Is generateIV() safe and secure ?

The Code bellow is working, I've made a test to encrypt 2 text files with exact same text inside each. the result is both have different data, and decrypt succeed.

also made test before the random IV, both files had same encrypted text, results in same data.

Encryption code :

    private static int IV_LENGTH = 16;

    public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
    {

        byte[] encryptedBytes = null;
        byte[] encryptedBytesAndIV = null;
        byte[] saltBytes = SHA512.Create().ComputeHash(passwordBytes);
        using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
        {
            using (AesCryptoServiceProvider AES = new AesCryptoServiceProvider())
            {
                AES.KeySize = 256;
                //AES.BlockSize = 128;

                var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 100);
                AES.Key = key.GetBytes(AES.KeySize / 8);
                AES.IV = generateIV();

                AES.Mode = CipherMode.CBC;

                using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                    cs.Close();
                }
                encryptedBytes = ms.ToArray();
                encryptedBytesAndIV = new byte[encryptedBytes.Length + AES.IV.Length];
                AES.IV.CopyTo(encryptedBytesAndIV, 0);
                encryptedBytes.CopyTo(encryptedBytesAndIV, IV_LENGTH);
            }
        }

        return encryptedBytesAndIV;
    }

    private static byte[] generateIV()
    {
        using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
        {
            byte[] nonce = new byte[IV_LENGTH];
            rng.GetBytes(nonce);
            return nonce;
        }
    }

Decryption code :

    public static byte[] AES_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
    {
        byte[] decryptedBytes = null;

        byte[] saltBytes = SHA512.Create().ComputeHash(passwordBytes);

        using (MemoryStream ms = new MemoryStream())
        {
            using (AesCryptoServiceProvider AES = new AesCryptoServiceProvider())
            {
                AES.KeySize = 256;
                //AES.BlockSize = 128;

                var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 100);
                AES.Key = key.GetBytes(AES.KeySize / 8);
                AES.IV = getIV(bytesToBeDecrypted);
                bytesToBeDecrypted = removeTagAndIV(bytesToBeDecrypted);
                AES.Mode = CipherMode.CBC;

                using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
                    cs.Close();
                }
                decryptedBytes = ms.ToArray();

            }
        }

        return decryptedBytes;
    }

    private static byte[] removeTagAndIV(byte[] arr)
    {
        byte[] enc = new byte[arr.Length - IV_LENGTH];
        Array.Copy(arr, IV_LENGTH, enc, 0, arr.Length - IV_LENGTH);
        return enc;
    }

    private static byte[] getIV(byte[] arr)
    {
        byte[] IV = new byte[IV_LENGTH];
        Array.Copy(arr, 0, IV, 0, IV_LENGTH);
        return IV;
    }


texts: Print all combinations of balanced parentheses

texts:
Given ( and ) and length of 4, generate the following combinations -
  ()() and (()).

Looking for code review, optimizations and best practices. Also verifying complexity to be O(2(n+1) - 1), where n is half the 'input length'.

public final class BraceCombinations {

    private BraceCombinations() {}

    /**
     * Returns sets of valid combinations.
     *
     * @param length    the sum of length of all- opening + closing braces
     * @return          the valid brace combinations
     */
    public static List<List<String>> getBraceCombinations(int length) {
        if (length <= 0) {
            throw new IllegalArgumentException("The length should be greater than zero");
        }

        if (length % 2 == 1) {
            throw new IllegalArgumentException("The length should be positive");
        }

        final List<List<String>> paranthesesCombo = new ArrayList<List<String>>();
        generate(paranthesesCombo, new LinkedList<String>(), 0, 0, length/2);
        return paranthesesCombo;
    }

    private static void generate(List<List<String>> paranthesesCombo,  LinkedList<String> parenthesis, int openBrace, int closeBrace, int halfLength) {
        if (openBrace == halfLength && closeBrace == halfLength) {
            paranthesesCombo.add(new ArrayList<String>(parenthesis));
        }
        if (openBrace > halfLength || closeBrace > openBrace) {
            return;
        }
        parenthesis.add("(");
        generate(paranthesesCombo, parenthesis, openBrace + 1, closeBrace, halfLength);
        parenthesis.removeLast();

        parenthesis.add(")");
        generate(paranthesesCombo, parenthesis, openBrace, closeBrace + 1, halfLength);
        parenthesis.removeLast();
    }

    public static void main(String[] args) {
        List<List<String>> paths1 = Arrays.asList(
            Arrays.asList("(", ")")
        );
        assertEquals(paths1, getBraceCombinations(2));
        List<List<String>> paths = Arrays.asList(
                Arrays.asList("(", "(", ")", ")"),
                Arrays.asList("(", ")", "(", ")")
            );
        assertEquals(paths, getBraceCombinations(4));
    }
}


texts: how to Transpose two-dimensional arrays values from rows into columns in postgres?

texts:
Table "matrices"
 Column |  Type  | Modifiers
--------+--------+-----------
 matrix | text[] | not null

rows count 2,values are in this format given below

     matrix
-------------------
 {{1,2,3},{4,5,6}}
 {{a,b,c},{d,e,f}}

output i'm looking for in this format
     matrix
---------------------
 {{1,4},{2,5},{3,6}}
 {{a,d},{b,e},{c,f}}

can anybody suggest me a better solution, i tried crosstab with giving 2 integer value,it didn't work in my server,these syntaxes are new to me.


texts:
The following code runs correctly:

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

bool is_palindrom(const std::string& str)
{
    std::string temp(str);
    std::transform(temp.begin(), temp.end(), temp.begin(), ::tolower);
    return temp == std::string(temp.rbegin(), temp.rend());
}

int main()
{
    std::string str{ "KArak" };
    std::cout << is_palindrom(str) << std::endl;
    return 0;
}

Can I do this better? The constraint is to keep the declaration of the function the same and only change the implementation.


texts:
I'm using the darksky api to get weather data for a display board website.

The free version is limited to 1000 api calls per month.
I have a lot of devices (iPads) displaying this information in the building and refreshing every minute or so to update weather and the message of the hour.

I think that caching the weather into a file and reading it when the refresh time is over is a solution to my problem.
Is it the best solution?
And is this the best implementation of this solution

function getWeather(){
    //compares the time of the saved weather at each call of the method
    $last_modif = filemtime("weather.json");

    //if the weather is 10 minutes old, renew it by calling the api
    if(time() - $last_modif > WEATHER_REFRESH_TIME){
        //echo "call api";
        $file = fopen("weather.json", "w");
        $request = 'https://api.darksky.net/forecast/MY_KEY/LAT,LNG?lang=fr&units=si&exclude=minutely,flags';
        $data = file_get_contents($request);
        fwrite($file,$data);
        fclose($file);
    }

    $file = fopen("weather.json", "r");
    $weather = fread($file,filesize("weather.json"));
    fclose($file);

    return json_decode($weather);
}

Should i write the data in a database instead or is there any other way to store the weather?
What are the best practices in this case ?


texts:
How can I improve this PHP MySql Rank generation function?
(Mostly looking to improve speed, but any feedback is very welcome)

Right now I keep stats and ranks in 2 separate tables. The only problem with this is I don't know how combine the select and update queries to possibly increase speed by cutting the PHP processing of the results and the update out of it. Also this function is very time consuming. It takes about 5-10 minutes to process 300,000+ ranks. This isn't really too bad, except I have to do this 50+ times. I do like how it doesn't lock up my database because getting the ranks only takes a few seconds, and all the updates are done individually, which leaves room for other queries to process instead of locking for 5-10 minutes each time.

function get_ranking($rank, $rank_order, $DBH, $test_mode=true)
{
    $test_mode == true ? $limter = ' LIMIT 50' : $limter = '';

    $query0 = 'SET @rank=0';
    $query1 = 'SELECT @rank:=@rank+1 AS rank, player_id FROM player_stats ORDER BY '.$rank_order.$limter;

    try
    {
        $DBH->exec($query0);
        $qh = $DBH->prepare($query1);
        $qh->setFetchMode(PDO::FETCH_ASSOC);

        if ($qh->execute())
        {
            while ($result = $qh->fetch())
            {
                $query2 = 'UPDATE `player_ranks` SET '.$rank.' = \''.$result['rank'].'\' WHERE `player_id` =\''.$result['player_id'].'\'';

                $qh2 = $DBH->prepare($query2);
                $qh2->execute();
            }

            return true;
        }

        return false;
    }
    catch (PDOException $e)
    {
        save_PDO_error_to_file($e);
        return false;
    }
}

Thanks for any advice/feedback/help!


texts: Choose random instants in a day with a low memory footprint

texts:
I'm looking for a way to plan a list of X events at the start of the day...
What I did before:
At 02:00 every day, choose X timestamps from "now" to 01:59 the next day.
That worked well but I had to "remember" X timestamps
What I did to optimize:
Each day, create a counter events_planned = X
Each second, in the loop, make the event if random(0, seconds_left_before_0200) <= events_planned
If the event was made, remove 1 from events_planned
It seems to be working well, but when you graph the number of events in a day, you get

As you can see, each time we approch 02:00, more events are created (And that's not a single occurence)
Minimal exemple:
import time
import random

def planifie():
    now = int(time.time())
    this_day = now - (now % 86400)
    seconds_left = 86400 - (now - this_day)
    multiplicator = round(seconds_left / 86400, 5) # In case we restarted, and it's not 02:00. That's not used in the graph before
    return round(getPref("events_per_day") * multiplicator)

def mainloop():
    planday = 0
    is_closed = False
    while not is_closed:
        now = int(time.time())
        this_day = now - (now % 86400)
        seconds_left = int(86400 - (now - this_day))
        if int(now / 86400) != planday:
            planday = int(now / 86400)
            events_planned = planifie()

        if random.randrange(0, seconds_left) < events_planned:
            events_planned -= 1
            do_event()
        time.sleep(1)

def do_event(): #Dummy def for do_event()
     print("Ping")

def getPref(_): # Dummy def for getpref, as it is only used in planifie(). We will assume 20 000 events a day
     return 20000
mainloop()

(The code is much more complicated than that, so if you might need it in full, here is planifie() and here is mainloop())


texts: Sudoku solver recursive backtrack in Java

texts:
I am implementing recursive backtracking algorithm for sudoku. Below is the code to create board with random filling. I wonder if I can make it better in any terms of readable coding especially validation methods. in Board class.

public class Board {
private int[][] board;
public final static int SIZE = 9;

public Board() {
    create();
}

public int[][] getBoard() {
    return board;
}

private void create() {
    int openspots = 20;
    board = new int[SIZE][SIZE];
    Random rand = new Random();
    int random, randomrow, randomcolumn;

    while (openspots-- > 0) {
        random = rand.nextInt(SIZE) + 1;
        randomrow = rand.nextInt(SIZE);
        randomcolumn = (rand.nextInt(SIZE));

        if (board[randomrow][randomcolumn] == 0) {
            board[randomrow][randomcolumn] = random;
            int count = 0;

            while (!isValid(randomrow, randomcolumn)) {
                if (count++ == 9) {
                    board[randomrow][randomcolumn] = 0;
                    openspots++;
                    break;
                }

                random = rand.nextInt(SIZE) + 1;
                board[randomrow][randomcolumn] = random;
            }
        }
    }
}

public void printBoard() {
    for (int row = 0; row < SIZE; row++) {
        for (int column = 0; column < SIZE; column++) {
            System.out.print(board[row][column] + " ");
        }
        System.out.println();
    }
}

public boolean isValid(int row, int column) {
    return isValidRow(row) && isValidColumn(column) && isValidBlock(row, column);
}

private boolean isValidRow(int row) {
    if (row > 8 || row < 0)
        throw new IllegalArgumentException("Row must be between 0 and " + (SIZE - 1) + " inclusive!");

    Set<Integer> set = new HashSet<>();

    for (int i = 0; i < SIZE; i++) {
        if (board[row][i] != 0 && set.contains(board[row][i])) {
            return false;
        } else {
            set.add(board[row][i]);
        }
    }

    return true;
}

private boolean isValidColumn(int column) {
    if (column > 8 || column < 0)
        throw new IllegalArgumentException("Column must be between 0 and " + (SIZE - 1) + " inclusive!");

    Set<Integer> set = new HashSet<>();

    for (int i = 0; i < SIZE; i++) {
        if (board[i][column] != 0 && set.contains(board[i][column])) {
            return false;
        } else {
            set.add(board[i][column]);
        }
    }

    return true;
}

private boolean isValidBlock(int row, int column) {
    if (column > 8 || column < 0)
        throw new IllegalArgumentException("Column must be between 0 and " + (SIZE - 1) + " inclusive!");

    int blockrow = (row / 3) * 3;
    int blockcolumn = (column / 3) * 3;

    Set<Integer> set = new HashSet<>();

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            if (board[blockrow + i][blockcolumn + j] != 0 && set.contains(board[blockrow + i][blockcolumn + j])) {
                return false;
            } else {
                set.add(board[blockrow + i][blockcolumn + j]);
            }
        }
    }

    return true;
}
}

The one below is the solver class which has the main algorithm to solve sudoku.

public class Solver {

public boolean solve(Board board) {
    int[][] boardarr = board.getBoard();

    for (int i = 0; i < board.SIZE; i++) {
        for (int j = 0; j < board.SIZE; j++) {
            if (boardarr[i][j] == 0) {
                for (int k = 1; k <= board.SIZE; k++) {
                    boardarr[i][j] = k;
                    if (board.isValid(i,j) && solve(board)) {
                        return true;
                    }
                    boardarr[i][j] = 0;
                }
                return false;
            }
        }
    }

    return true;
}
}


texts: Create User profile with separate social media data

texts:
I am creating user profile logic for a blogging platform.  I have the UserProfile model and then two separate models, UserSocialLink and SocialLinkType to control the user's various social media contacts (i.e. Facebook, Twitter, Google+, etc...).  I am looking for feed back on the execution of the methods used to Add new UserProfiles.  Is this the way you would handle it? Is there a better way? What are some of the issues you see with my methods (specifically in the service class)?

The Models

public class UserProfile
{
    public int Id { get; set; }
    public string UserName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string ProfilePicUrl { get; set; }
    public string Location { get; set; }
    public string DateOfBirth { get; set; }
    public string Bio { get; set; }
    public DateTime Created { get; set; }
    public DateTime Updated { get; set; }
 }

public class UserSocialLink
{
    public int Id {get; set;}
    public int UserProfileId { get; set; }
    public int SocialLinkTypeID { get; set; }
    public string LinkValue { get; set; }
    public DateTime Created { get; set; }
    public DateTime Updated { get; set; }

    public virtual UserProfile UserProfile { get; set; }
    public virtual SocialLinkType SocialLinkType {get; set;}
}

public class SocialLinkType
{
    public int Id { get; set; }
    public string LinkType { get; set; }
    public string URLFormat { get; set; }
}

The Add Methods in The Service Class

public class UserProfileService : IUserProfileService
{
    public UserProfile Add(UserProfile userProfile)
    {
        var now = DateTime.UtcNow;

        if (userProfile == null)
            throw new ArgumentNullException("User Profile");

        userProfile.Created = now;
        userProfile.Updated = now;
        using (var db = new ApplicationDbContext())
        {
            db.UserProfiles.Add(userProfile);
            db.SaveChanges();
        }
        return userProfile;
    }

    public UserProfile AddSocialLink(string userName, UserSocialLink userSocialLink, string socialLinkType)
    {
        var now = DateTime.UtcNow;
        var userProfile = Get(userName);
        if (userProfile == null)
            throw new Exception("User Profile Not Found");
        using (var db = new ApplicationDbContext())
        {
            var linkType = db.SocialLinkTypes.SingleOrDefault(p => p.LinkType.ToUpper() == socialLinkType.ToUpper());
            if (linkType == null)
                throw new Exception("Social Media Type Not Found");
            userSocialLink.Created = now;
            userSocialLink.Updated = now;
            userSocialLink.SocialLinkTypeID = linkType.Id;
            db.UserSocialLinks.Add(userSocialLink);
            db.SaveChanges();
            return userProfile;
         }
    }
}

  Related GitHub Issue #14


texts: Is this the best way to print dynamic percent value?

texts:
Is there any better way of printing it?

public class PercentPrinter {

/**
 * @param args
 */
public static void main(String[] args) {

    for (int i = 0; i < 100; i++) {
        if (i == 0)
            System.out.print("percent completed: " + i + " %");
        try {
            Thread.sleep(500);
        } catch (Exception e) {
            System.out.println(e);
        }
        if (i > 9 && i <= 99) {
            System.out.print('\b');
            System.out.print('\b');
            System.out.print('\b');
            System.out.print('\b');

            System.out.print(i + " %");
        } else {
            System.out.print('\b');
            System.out.print('\b');
            System.out.print('\b');

            System.out.print(i + " %");

        }
    }
}
}


texts: Activator with simple dependency injection

texts:
In one of my projects I needed a simple dependency incjection activator so I've built one. It performs only type/inheritance matching because I'm not creating a second Autofac and I think I won't need anything more complex any time soon (aka YAGNI).

To find the dependencies I use a Join with a custom comparer. It runs over constructor parameters and tries to match a dependency and maintain the order of the parameters. If the parameters and dependencies counts don't match I use Except to find the missing ones and put their names in the exception message.

I don't use a DI container because I use it for creating commands based on the command line.

public interface IDependencyInjectionActivator
{
    object CreateInstance(Type type, params object[] candidates);
}

public class DependencyInjectionActivator : IDependencyInjectionActivator
{
    private static readonly IEqualityComparer<Type> TypeInheritanceComparer =
        AdHocEqualityComparer<Type>
            .CreateWithoutHashCode((candidate, parameter) => parameter.IsAssignableFrom(candidate));

    public object CreateInstance(Type type, params object[] candidates)
    {
        var constructor = type.GetConstructors().Single();

        var parameters =
            constructor
                .GetParameters()
                .Join(
                    candidates,
                    parameter => parameter.ParameterType,
                    candidate => candidate.GetType(),
                    (parameter, candidate) => candidate,
                    TypeInheritanceComparer
                ).ToArray();

        var dependenciesResolved = (parameters.Length == constructor.GetParameters().Length);
        if (dependenciesResolved)
        {
            return Activator.CreateInstance(type, parameters);
        }

        var missingDependencies =
            constructor
                .GetParameters()
                .Select(p => p.ParameterType)
                .Except(parameters.Select(p => p.GetType()), TypeInheritanceComparer)
                .ToList();

        var message =
            $"Some dependecies for {type.ToPrettyString().QuoteWith("'")} could not be resolved: " +
            $"{missingDependencies.Select(t => t.ToPrettyString()).Join(", ").EncloseWith("[]")}";
        throw DynamicException.Factory.CreateDynamicException($"MissingDependency{nameof(Exception)}", message, null);
    }
}

The compare I use here takes two Funcs for each interface method. Factory methods make the creation easier.

public class AdHocEqualityComparer<T> : IEqualityComparer<T>
{
    private readonly Func<T, T, bool> _equals;
    private readonly Func<T, int> _getHashCode;

    private AdHocEqualityComparer(Func<T, T, bool> equals, Func<T, int> getHashCode)
    {
        _equals = equals;
        _getHashCode = getHashCode;
    }

    public static IEqualityComparer<T> CreateWithoutHashCode([NotNull] Func<T, T, bool> equals)
    {
        if (equals == null) throw new ArgumentNullException(nameof(@equals));

        return Create(equals, _ => 0);
    }

    public static IEqualityComparer<T> Create([NotNull] Func<T, T, bool> equals, [NotNull] Func<T, int> getHashCode)
    {
        if (equals == null) throw new ArgumentNullException(nameof(equals));
        if (getHashCode == null) throw new ArgumentNullException(nameof(getHashCode));

        return new AdHocEqualityComparer<T>(equals, getHashCode);
    }

    public bool Equals(T x, T y)
    {
        if (ReferenceEquals(null, x)) return false;
        if (ReferenceEquals(null, y)) return false;
        if (ReferenceEquals(x, y)) return true;
        return _equals(x, y);
    }

    public int GetHashCode(T obj) => _getHashCode(obj);
}

This time without examples because I think the usage is strightforward. You create and instance of the activator, specify the type you want to create and pass an array of dependency caditates.

Do you think this DI is smart enough or does it need any improvements?


texts: PHP rating function for getting the average value of column

texts:
I created a function to add and return the average rating.

Rating Function

// Adding AddRating
    final function AddRating($rt_target_id, $u_id, $rt_vote,$moduleName){
        $error  = 0;
        if(!empty($moduleName) && $rt_target_id != 0 && $u_id != 0){
            $tableName =  '';
            switch ($moduleName) {
                case 'promotion':
                $tableName = 'ws_promotion';
                break;
                default:
                $tableName = 'invalid';
            }
            if($tableName!='invalid'){
                $addRating = "INSERT INTO ws_rating (u_id, rt_target_id, rt_vote, rt_table_name, date_added)
                VALUES ('".$u_id."','".$rt_target_id."','".$rt_vote."','".$tableName."', '".date("Y-m-d H:i:s")."')";

                $dataInsert = mysqli_query($this->connection,$addRating);
                if($dataInsert){
                    $Rating = "select avg(rt_vote) as Rating from `ws_rating` where `rt_target_id` = ".$rt_target_id. " and `rt_table_name` = '".$tableName."'";
                    $RatingQuery = mysqli_query($this->connection,$Rating);
                    $rowRating = mysqli_fetch_assoc($RatingQuery);
                    $response['rating'] =  $rowRating;
                }
                echo json_encode($response);
            }

        }// end if

    }

Table

---------------------------------------------------------------------
|rt_id | u_id | rt_target_id | rt_vote | rt_table_name | date_added |
-------------------------------------------------------------------
|1     | 1    | 2            | 5       | promotion_tb | 2016-03-24  |
---------------------------------------------------------------------

I added 12432 rows with same data in above table. Below select query is giving this 4.9936 result of added rows 12432.

SELECT AVG(rt_vote) AS Rating FROM `ws_rating` WHERE `rt_target_id` = 2 AND `rt_table_name` = 'ws_promotion'

I wanted to know whether my table structure and function are correct.  In the future, if there are 1 million rows then will my function return the correct average?


texts:
The code creates a meta class and its implementation to set the values passed in as arguments to methods on a class automatically on the object avoiding a lot of self.a=a code at the start of methods.

>>> from functools import wraps
>>> import inspect
>>>
>>> def setMethodAttrs(func):
...    @wraps(func)
...    def wrapper(*args, **kwargs):
...        formalArgs=inspect.getargspec(func)[0]
...        if len(args)>1:
...           for x in range(1, len(args)):
...              setattr(args[0], formalArgs[x], args[x])
...        for k, v in kwargs.iteritems():
...           setattr(vars()['args'][0], k, v)
...        return func(*args, **kwargs)
...    return wrapper
...
>>> def classAttrs(cls):
...     for key, val in vars(cls).items():
...         if callable(val):
...             setattr(cls,key, setMethodAttrs(val))
...     return cls
...
...
>>>
>>> @classAttrs
... class trythis:
...    def __init__(self):
...       self.firstvar=1
...       self.secondvar=2
...       self.thirdvar=3
...       self.fourthvar=4
...    def method1(self,firstvar=None,secondvar=None,thirdvar=None):
...       print("firstvar {}".format(self.firstvar))
...       print("secondvar {}".format(self.secondvar))
...       print("thirdvar {}".format(self.thirdvar))
...       print("fourthvar {}".format(self.fourthvar))
...    def method2(self, secondvar=None, fourthvar=None):
...       print("firstvar {}".format(self.firstvar))
...       print("secondvar {}".format(self.secondvar))
...       print("thirdvar {}".format(self.thirdvar))
...       print("fourthvar {}".format(self.fourthvar))
...
...
...
>>> a=trythis()
>>> a.method1()
firstvar 1
secondvar 2
thirdvar 3
fourthvar 4
>>> a.method1(firstvar=9)
firstvar 9
secondvar 2
thirdvar 3
fourthvar 4
>>> a.method2(11)
firstvar 9
secondvar 11
thirdvar 3
fourthvar 4
>>> a.method1(19, thirdvar=21)
firstvar 19
secondvar 11
thirdvar 21
fourthvar 4
>>> a.method2(fourthvar=40)
firstvar 19
secondvar 11
thirdvar 21
fourthvar 40
>>>


texts: Class(es) for animating objects on a canvas

texts:
I'm building a simple canvas animation engine as an exercise in learning ES6. Coming from C++ and Java, I miss static properties, but I've read that "Prototypes having data properties is generally considered an anti-pattern".

The animation engine simulates \$n\$ river waves (simple lines), flowing from right to left in an HTML5 canvas, using requestAnimationFrame. Waves come in three lengths, based on a baseLength that should be configurable and have a default: 1x, 5x, and 7x. When creating a new wave, I'm picking one of the lengths at random. All waves have a constant flowing velocity on the x axis. You can see this in motion on CodePen (ES5 approach; ignore the boats).

How should this simple universe be organized into classes? One "Wave" class with a constructor and draw method, and another "Waves" class with an animate method?
Should the velocity (same for all waves) be stored at the Wave, or Waves level?
Is the static config() method a good idea, or should each property be separate? Let's assume for simplicity we won't build an interface to modify these properties at runtime, but they are to be grouped at the top of the class for easy editing in the code.
Is it better to use just one class, Waves, and have a createWave method which the constructor will call \$n\$ times to create all waves? I don't imagine ever needing to create a Wave in isolation from its river / Waves.

Here's the first stab at this in ES6:

'use strict';

class Wave {
  static config() {
    const waveBaseLength = 5;
    return {
      color: '#4F5E5B',
      waveLengths: [waveBaseLength, waveBaseLength * 7, waveBaseLength * 15],
      velocity: 5
    }
  }

  constructor(x, y, velocity) {
    this.x = x;
    this.y = y;
    let waveLengths = Wave.config().waveLengths;
    this.l = waveLengths[Math.floor(Math.random() * waveLengths.length)];
    this.velocity = velocity || 0.5;  // Chrome currently fails at `velocity=0.5` in the constructor declaration
  }

  draw(context) {
    context.beginPath();
    context.moveTo(this.x, this.y);
    context.lineTo(this.x + this.l, this.y);
    context.strokeStyle = Wave.config().color;
    context.stroke();
  }
}

class Waves {
  constructor(n, context) {
    this.waves = [];
    this.context = context;
    for (var i = 1; i <= n; i++) {
      var x = Math.random() * context.canvas.width,
        y = context.canvas.height / n * i;
      this.waves.push(new Wave(x, y));
    }
  }

  step() {
    for (var i = 0; i < this.waves.length; i++) {
      var wave = this.waves[i];

      if (wave.x + wave.l > 0) {
        // if still partially visible in the canvas, draw it
        wave.draw(this.context);
        wave.x -= wave.velocity;
      } else {
        // otherwise, recreate the wave off-screen to the right, at a different Y location to keep it interesting
        // TODO this does create a "gap" as waves come on-screen, but fixing it is not a priority
        wave.x = this.context.canvas.width;
        wave.y = Math.random() * this.context.canvas.height;
      }
    }
  }
}

let canvas = document.getElementById('river');
let context = canvas.getContext('2d');
let waves = new Waves(150, context);

window.requestAnimationFrame = window.requestAnimationFrame || window.msRequestAnimationFrame;

(function loop(timestamp) {
  context.clearRect(0, 0, canvas.width, canvas.height);

  waves.step();

  // keep animating
  window.requestAnimationFrame(loop);
})();
<canvas id="river"></canvas>


texts: Parzen window density estimation in MATLAB

texts:
This was my C# implementation of Parzen Window Density Estimation.

The following is my implementation of the same in Matlab:

parzen.m

function [retval] = parzen (matrix, dataPoint, variance)
    [r c] = size(matrix);
    A = ones(r, c).*dataPoint;
    sub = matrix - A;
    up = sub.^2;
    dw = 2 * variance;
    firstPart = 1/(sqrt(2*pi*variance));
    retval = firstPart * exp((-1)*(up/dw));

What do you think about this implementation? Is it correct?


texts:
I have made a UI that guesses the number that the user is thinking of(0 - 100), and I am wondering if it can be improved(I guess this is simple AI). I tried to shorten it as best I could, but it still seems a bit "fluffed." I would greatly appreciate anyone willing to help me shorten and/or improve it.  It has 3 buttons, a "Too High", "Too Low", and "Just Right" button, and the guess is displayed in the center of the window. I have posted an image below also.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;

public class NumberGuesser extends JFrame {
    private static final long serialVersionUID = 1L;
    private Random rand = new Random();
    private int min = 0;
    private int max = 100;
    private int guess = rand.nextInt(max);
    private JLabel guesses;
    private Font font = new Font("Times New Roman", Font.BOLD, 30);

    public NumberGuesser() {
        initGUI();
        setTitle("Number Guesser");
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void initGUI() {
        JLabel title = new JLabel(" I Guess Your Number(0-100) ");
        title.setFont(font);
        title.setHorizontalAlignment(JLabel.CENTER);
        title.setBackground(Color.BLACK);
        title.setForeground(Color.WHITE);
        title.setOpaque(true);
        add(title, BorderLayout.NORTH);

        guesses = new JLabel(Integer.toString(guess));
        guesses.setFont(font);
        guesses.setHorizontalAlignment(JLabel.CENTER);
        add(guesses, BorderLayout.CENTER);

        JPanel buttons = new JPanel();
        add(buttons, BorderLayout.SOUTH);

        JButton higher = new JButton("Too High");
        higher.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                max = guess;
                guessAgain(min, max);
            }
        });
        buttons.add(higher);

        JButton correct = new JButton("Just Right");
        correct.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                guesses.setText("I WIN!");
            }
        });
        buttons.add(correct);

        JButton lower = new JButton("Too Low");
        lower.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                min = guess;
                guessAgain(min, max);
            }
        });
        buttons.add(lower);
    }

    private void guessAgain(int min, int max) {
        guess = min + (int)(Math.random() * ((max - min) + 1));
        guesses.setText(Integer.toString(guess));

    }

    public static void main(String[] args) {
        try {
            String laf = UIManager.getCrossPlatformLookAndFeelClassName();
            UIManager.setLookAndFeel(laf);
        }
        catch (Exception e) {}

        EventQueue.invokeLater(new Runnable(){
            public void run() {
                new NumberGuesser();
            }
        });
    }
}

The output looks like this:


texts:
I'm working through Chapter 6 in "Automate the Boring Stuff, 2nd Edition." Here is the chapter project at the end.
Write a function named printTable() that takes a list of lists of strings and displays it in a well-organized table with each column right-justified. Assume that all the inner lists will contain the same number of strings. For example, the value could look like this:
tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

Your printTable() function would print the following:

   apples Alice  dogs
  oranges   Bob  cats
 cherries Carol moose
   banana David goose

The first time I tackled this project, here was what I came up with:
#! python3
# Displays a table with each column right-justified.

table_data = [["apples", "oranges", "cherries", "bananas"],
    ["Alice", "Bob", "Carol", "David"],
    ["dogs", "cats", "moose", "goose"]]

def print_table(table_data):
    # Create a new list of 3 "0" values: one for each list in table_data
    col_widths = [0] * len(table_data)
    # Search for the longest string in each list of table_data
    # and put the numbers of characters in the new list
    for y in range(len(table_data)):
        for x in table_data[y]:
            if col_widths[y] < len(x):
                col_widths[y] = len(x)

    # Rotate and print the list of lists
    for x in range(len(table_data[0])):
        for y in range(len(table_data)):
            print(table_data[y][x].rjust(col_widths[y]), end=" ")
        print()

print_table(table_data)

The second time, I found out about the MAX method after several searches on Google. Here is what I came up with using the MAX method.
#! python3
# Displays a table with each column right-justified

table_data = [["apples", "oranges", "cherries", "bananas"],
            ["Alice", "Bob", "Carol", "David"],
            ["dogs", "cats", "moose", "goose"]]

def print_table(table_data):
    # Create a new list of 3 "0" values: one for each list in table_data
    col_widths = [0] * len(table_data)
    # Search for longest string in each list of table_data
    # and put the numbers of characters in new list
    for y in range(len(table_data)):
        x = max(table_data[y], key=len)
        if col_widths[y] < len(x):
            col_widths[y] = len(x)

    # Rotate and print the lists of lists
    for x in range(len(table_data[0])):
        for y in range(len(table_data)):
            print(table_data[y][x].rjust(col_widths[y]), end=" ")
        print()

print_table(table_data)

Any feedback would be greatly appreciated. Thanks!


texts: Design of thread pool reuse with Executors.newFixedThreadPool in Java

texts:
In my application I have code which should run every hour on a new items and execute some expensive operation with multithreading:

int i = 1;

//noinspection InfiniteLoopStatement
while (true) {

    try {
        Logger.printIterationNum("Text analysis", "beg", i);

        Document query = new Document("fetchStatus", new Document("$lte", fetchStatusParam));
        ArrayList<Document> unfetchedEvents = dbC_Events.find(query).projection(
                fields(include("_id"), include("link"), include("title"), include("summary"))
        ).into(new ArrayList<>());

        // get full text and images of the events
        this.getFullTextImg(dbC_Events, unfetchedEvents);

        Logger.printIterationNum("Text analysis", "end", i++);

        // make a pause between executions
        Pauser.rest(Pauser.Units.SECONDS, PAUSE_TIME_OUT);
    } catch (Exception e) {
        i = 1;
        e.printStackTrace();
    }
}

private void getFullTextImg(MongoCollection<Document> dbC_Events, ArrayList<Document> unfetchedEvents) {

    int cpuCoresNum = SYS_MAX_NUM_CPU_CORES;
    int itemsPerCore = unfetchedEvents.size() / cpuCoresNum;

    // prevent infinite thread generation if num of unfetched events is less than number of CPU cores
    if (itemsPerCore == 0) {
        itemsPerCore = unfetchedEvents.size();
    }

    // update status of queried items
    DBAgent.updateItemsStatus(dbC_Events, unfetchedEvents, FetchStatus.IN_PROCESS_FETCH.getID());

    int itNum = 1;
    int upperIndex = 0;

    ExecutorService service = Executors.newFixedThreadPool(cpuCoresNum);

    for (int i = 0; i < unfetchedEvents.size(); i += itemsPerCore) {

        int indexFrom = i;
        upperIndex += itemsPerCore;
        int toIndex = upperIndex;

        if (((unfetchedEvents.size() - toIndex) <= itemsPerCore) && (itNum == cpuCoresNum)) {
            toIndex = unfetchedEvents.size();
            i = unfetchedEvents.size();
        }

        int indexTo = toIndex;
        int treadID = itNum++;

        service.execute(() -> {
            try {
                Thread.currentThread().setName("im_evFullTextImg_#" + String.format("%03d", treadID));
                this.fetcher(dbC_Events, new ArrayList<>(unfetchedEvents.subList(indexFrom, indexTo)));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    // wait until all threads will be finished
    service.shutdown();
    try {
        service.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

My questions:

Is it a good idea to initialize the Executors.newFixedThreadPool(cpuCoresNum) each time I execute the getFullTextImg() method, or is it better to initialize it once and pass it as a parameter each time I call getFullTextImg()?
If I initialize Executors.newFixedThreadPool(cpuCoresNum) out of getFullTextImg() and pass it as a paramete,  will it cause some issues since I use service.shutdown();, which prevents accepting new tasks to the thread pool?
If service.shutdown(); is a problematic to reuse the thread pool, how can I redesign it in order to still wait until all threads in a poll will be finished, and only after to continue the code flow?
Can the Executors.newFixedThreadPool(cpuCoresNum) reuse lead to memory leak issues? Is there some important thing I have to do (e.g. clean the pool) with the thread pool in order to reuse it?


texts: Implementing a dictionary and thesaurus in Python

texts:
Write code that functions as both a dictionary and a thesaurus.
  Supported operations:

  Add a word and its definition to the dictionary
  Add a synonym to a word in the dictionary
  Look up the definition of a word in the dictionary
  Look up the synonym of a word in the dictionary
  Synonyms should be considered both commutative and transitive

Hello All,

I was just asked this question in a coding interview and I was wondering how I could do better. I wrote code to the point where I had completed all of the methods of the question, except the final of commutative and transitive properties weren't working for synonyms.  Here's my code so far:

dict = defaultdict(list)
thes = defaultdict(list)

def add_word(word, definition):
    dict[word].append(definition) #add word and definition to dict

def add_synonym(word, syn):
    thes[word].append(syn)
    thes[syn].append(word)

# add the synonym as a second value in the dict
def lookup_word(word):
    if(dict[word]):
       print dict[word] #prints the word and the definition

def lookup_synonym(word):
    if(thes[word]):
        print thes[word]

add_word("cat", "a furry creature")
add_word("feline","a cat")
add_synonym("cat", "feline")

lookup_word("cat")
lookup_synonym("cat")
lookup_synonym("feline")

I realize that it might be better to create either a word object or a dictionary object and then pass in the values as data members, but I'm not sure how to model it and where I could improve the add_synonym function in order to make it commutative.

Thanks!


texts: Wrapping C++ library in C++/CLI using shared_ptr

texts:
Background: I'm writing C++ code after a fairly long time, so I may not be up to date on the best practices, so please bear with me. I'm only trying to improve and learn.

Problem I need to write a wrapper in C++/CLI for a C++ library so that I can use it in C#. The limitation that C++/CLI managed types can only contain pointers to native types is very frustrating. Part of the reason is that the native library I'm wrapping around has classes that are often passed around among themselves as shared_ptr or native references to instances.

Code My code is inspired by this post but I'm trying to use shared_ptrs instead of the raw pointers.

#pragma once
#include <memory>

namespace App
{
    using namespace System;

    template<typename T>
    public ref class Managed
    {
    private:
        std::shared_ptr<T>* native;

    protected:
        !Managed()
        {
            delete native;
        }

    private protected:
        // Allows derived classes to construct native objects with parameters
        // but only accepts shared_ptr
        Managed(std::shared_ptr<T> t) : native(new std::shared_ptr<T>(t)) {}

        // Assumes default constructor for the native object
        Managed() : Managed(std::make_shared<T>()) {}

    internal:

        /*
        Return a reference to the native object
        */
        [CLSCompliantAttribute(false)]
        property T& WrappedObject
        {
            T& get()
            {
                return **native;
            }
        }

        /*
        Return a shared pointer by value to the native object
        */
        [CLSCompliantAttribute(false)]
        property std::shared_ptr<T> WrappedPointer
        {
            std::shared_ptr<T> get()
            {
                return *native;
            }
        }

    public:
        virtual ~Managed()
        {
            this->!Managed();
        }
    };
}

The wrapper can be used like so (this is just an example, not something I'm actually using):

public ref class NativeObjWrapper: Managed<NativeObj>
{
public:
        NativeObjWrapper(int x) : Managed<NativeObj>(std::make_shared<NativeObj>(x)) {}

        NativeObjWrapper() {}

        // Example for passing by reference
        void SetPropertyByReference(AnotherNativeObjWrapper^ another)
        {
            WrappedObject.setProperty(another.WrappedObject);
        }
}

If somebody could take a look and point some obvious flaws that I'm overlooking, that'd be great.


texts: Version of lexical_cast that doesn't use exceptions

texts:
I love boost::lexical_cast but its usage of exceptions there is not preferred in most situations I use it.

I have implemented a version and it seems to work but I want to share it here to hopefully find any defects and/or simply find improvements.

template<typename T1, typename T2>
T1 lexical_cast(T2 const& value, T1 const& defaultValue = T1{})
{
    T1 convertedValue;
    std::stringstream ss;
    if (!(ss << value) || !(ss >> convertedValue))
    {
        return defaultValue;
    }

    return convertedValue;
}

Here is the code on Coliru where I've been testing.


texts: Setting value of controller controls for domain objects with Reflection

texts:
Is my use of Java Reflection an OK design?

Each domain object contains an annotation to declare what controller would be initialized to edit/create the object:

Each field of the domain object has an annotation to declare what control in the specified controller that the user would use to edit its value:

@Edit(controller = EmployeeController.class)
public class Employee extends Item {

     @Node(name = "lastNameField", type = TextField.class)
     private StringProperty lastName = new SimpleStringProperty();

     //Control similar to a TableView
     @Node(name = "contacts", type = ListBox.class)
     private List <Contact> contacts;

}

public @interface Edit {
     Class<? extends ModifyEntityController> controller();
}

public @interface Node {
     String name();
     Class<?> type();
 }

 public Class EmployeeController {
         @FXML
         private TextField lastNameField;
    }

Double-clicking on a ListCell would call .edit() on the domain object.

This method is in the parent class Item.

.edit() does: example = employee.edit();

create an instance of the @Edit controller
use @Node  to create a binding between the specified control
set the root node of controller to the main window of the application.

//create an instance of the controller
Edit edit = getClass().getAnnotation(Edit.class);
Class<? extends Controller> controller = edit.controller();

Object controllerInstance = null;

try {
    controllerInstance = edit.controller().newInstance();
} catch (Exception e) {
    e.printStackTrace();
}

//create bindings between the specified controls
List <Field> itemFields = FieldUtils.getFieldsListWithAnnotation(getClass(), Node.class);

for (Field field : itemFields ) {
     Node node = field.getAnnotation(Node.class);
     Object itemObject = FieldUtils.readField(field, this, true);
     Object controllerControl = FieldUtils.readDeclaredField(controllerInstance, node.name(), true);

     if (node.type() == TextField.class) {
          TextInputControl tc = (TextInputControl) controllerControl;
          StringProperty sp = (StringProperty) itemObject;
          tc.textProperty().bindBidirectional(sp);
    }

     else if (node.type() == ListBox.class) {
          ListBox lb =  (ListBox) controllerControl;
          List <CellObject> list = (List<CellObject>) itemObject;
          lb.setList(FXCollections.observableArrayList(list));
    }

}

*The implementation of a ListBox is actually not a binding of properties but setting the value of its ListView to the List Field of the domain object.
All objects that would be the value of a ListCell would implement CellObject.

//set the root node of controller to the main window of the application
AgendaApp.setContent(Controller) controllerInstance);

I went with reflection as the controllers to update/create domain objects consist of mainly TextFields and ListBox's.  This would save a lot of time writing the application.


texts: Changing a single jQuery plugin option on window resize

texts:
I'm looking to change a single jQuery plugin option when the window hits certain breakpoints.

The code below works, however I'm conscious of repeating code and feel there is a more elegant way writing code for examples like this.

My initial thoughts would be to store the first call in a variable.

$(window).smartresize(function () {

        if ( config.wWidth >= 768 && config.wWidth <= 1024 ) {

            $('#va-accordion').vaccordion({
                accordionW       : config.wWidth,
                accordionH       : config.wHeight,
                visibleSlices    : 2,
                expandedHeight   : 600,
                expandedWidth    : 1000,
                contentAnimSpeed : 200
            });

        } else if ( config.wWidth < 768 ) {

            $('#va-accordion').vaccordion({
                accordionW       : config.wWidth,
                accordionH       : config.wHeight,
                visibleSlices    : 1,
                expandedHeight   : 600,
                expandedWidth    : 1000,
                contentAnimSpeed : 200
            });

        } else {

            $('#va-accordion').vaccordion({
                accordionW       : config.wWidth,
                accordionH       : config.wHeight,
                visibleSlices    : 3,
                expandedHeight   : 600,
                expandedWidth    : 1000,
                contentAnimSpeed : 200
            });
        }

    });

    $(window).trigger("smartresize");


texts:
(defn merge [pred left right]
    (loop [v [] l left r right]   ; v is a vector, so conj will append to the end
        (if (and (seq l) (seq r)) ; if both left and right are not empty
            (if (pred (first l) (first r))
                (recur (conj v (first l)) (rest l) r)
                (recur (conj v (first r)) l        (rest r)))
            (concat v l r))))     ; One of l and r is empty, so concatenate what is already sorted

(defn mergesort [pred v]
    (let [
        n (count v)
        h1 (int (/ n 2))        ; floor(n/2)
        h2 (int (/ (inc n) 2))] ; ceil(n/2)
        (if (< n 2)
            v
            (merge pred
                (mergesort pred (take h1 v))          ; take the first half of elements
                (mergesort pred (take-last h2 v)))))) ; take the last half of elements

I'd like critics on how to turn this mergesort algorithm more Clojuric, if there are any Clojure API I could use to simplify it and other issues.

Specially, I've used a vector to store elements within merge, because otherwise the conj would append to its front, thus producing a reversed sequence. Also, is take and take-last the way to go to catch two halfs of a seq?

The following test code shows it works for vectors, lists and maps. Anything else I should consider?

(def v [3 -2 4 5 -3 0 7 -8 1 -1 2])
(def m [{:x 1 :y 2} {:x 0 :y 3} {:x 2 :y 1}])
(def s (seq v))
(mergesort < v)
;=> (-8 -3 -2 -1 0 1 2 3 4 5 7)
(mergesort > v)
;=> (7 5 4 3 2 1 0 -1 -2 -3 -8)
(mergesort #(< (java.lang.Math/abs %1) (java.lang.Math/abs %2)) v)
;=> (0 -1 1 2 -2 -3 3 4 5 7 -8)
(mergesort #(< (:x %1) (:x %2)) m)
;=> ({:x 0, :y 3} {:x 1, :y 2} {:x 2, :y 1})
(mergesort > s)
;=> (7 5 4 3 2 1 0 -1 -2 -3 -8)


texts: C# Better structure in my code & any other critiques

texts:
Any advice on how to make this code; cleaner, more effective, just overall better!
Program creates a 'post' in the console. The post has a:

message
create on date
score for 'upvotes' and 'downvotes'

Users are able to upvote or downvote the post using upvote or downvote with a simple trim and to lower applied to the string.
Any feedback is good feedback. I am currently a working programmer but being self-taught the confidence is not always there..
Want to see it in action? https://repl.it/repls/RoughGhostwhiteApplet
namespace StackOverflowPost
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Write a post!");
            string post = Console.ReadLine();
            Post newPost = new Post();
            newPost.AddPostMessage(post);

            bool val = true;
            while (val)
            {
                newPost.ShowPost();
                Console.WriteLine("What would you like to do now? \n You can 'UpVote', 'DownVote'");
                string inputData = Console.ReadLine();
                string cleanData = inputData.Trim().ToLower();

                if (cleanData == "upvote")
                {
                    newPost.Upvote();
                }
                else if (cleanData == "downvote")
                {
                    newPost.DownVote();
                }
                else
                {
                    val = false;
                }
            }
        }

        class Post
        {
            int voteScore;
            string postMessage;
            DateTime postDate;

            public Post()
            {
                this.postDate = DateTime.Now;
            }

            public void AddPostMessage(string post)
            {
                postMessage = post;
            }

            public void Upvote()
            {
                voteScore++;
            }
            public void DownVote()
            {
                voteScore--;
            }

            public void ShowPost()
            {
                Console.WriteLine("------------------------------------");
                Console.WriteLine($"Original Post Date {postDate}");
                Console.WriteLine($"User wrote: {postMessage}");
                Console.WriteLine($"Votes: {voteScore}");
                Console.WriteLine("------------------------------------");
            }

        }
    }
}


texts: Caesar Cipher implementation - Odin Project

texts:
I am going through the Odin Project Ruby section, and just finished implementing a Caesar cipher interpretation.  Should I use classes, or more than one method to distribute the flow?  Is there really a need for initialization in this?

def caesar_cipher(string, shifter)
    ciphered = []
    string.split("").each do |char|
        if char == " " then ciphered << char
            next
        end

        char = char.to_s.ord

        if ("a".ord.."z".ord).include? char
            if char + shifter < "z".ord
                ciphered.push((char + shifter).chr)
            else
                ciphered.push((shifter - ("z".ord - char) + "a".ord).chr)
            end
        elsif ("A".ord.."Z".ord).include? char
            if char + shifter < "Z".ord
                ciphered.push((char + shifter).chr)
            else
                ciphered.push((shifter - ("Z".ord - char) + "A".ord).chr)
            end
        else
            next
        end

    end
    print ciphered.join + "\n"
end

#test: caesar_cipher("Hello friend my Name is Sam",10)


texts: Nested stream to check the truth condition at first instance

texts:
Lets say I have  Cars with Features, and I have been given a List of features to look for in the Cars available with me. Though I could have done that using for-loop, what are the suggestions for below? Is this production-worthy?

import java.util.Arrays;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;

public class LookupTest {

    public static void main(String[] args) {
        Feature ft11 = new Feature(1);
        Feature ft12 = new Feature(2);
        Feature ft13 = new Feature(4);
        Car fer = new Car("Ferrari", ft11, ft12, ft13);

        Feature ft21 = new Feature(1);
        Feature ft22 = new Feature(2);
        Feature ft23 = new Feature(8);
        Car suz = new Car("Suzuki", ft21, ft22, ft23);

        List<Car> cars = Arrays.asList(fer, suz);
        List<Integer> lookForTypes = Arrays.asList(4); // look whether any car has feature-type 4

        if (CollectionUtils.isNotEmpty(lookForTypes)) {
            /* code block in question : start */
            boolean atLeastOneTypeFound = cars
                    .parallelStream()
                    .anyMatch(holding -> holding.getAmounts()
                            .parallelStream()
                            .anyMatch(feature -> {
                                return lookForTypes.contains(feature.type);
                            }));
            /* code block in question : end */
            System.out.println("atLeastOneTypeFound=" + atLeastOneTypeFound);
        }
    }
}

class Car {
    List<Feature> featureList;
    String name;

    public Car(String name, Feature... features) {
        featureList = Arrays.asList(features);
        this.name = name;
    }

    public List<Feature> getAmounts() {
        return featureList;
    }

    public String getName() {
        return name;
    }
}

class Feature {
    int type;

    public Feature(int type) {
        this.type = type;
    }

    public int getType() {
        return type;
    }
}


texts: Simple bcrypt Register User and User Login using PHP - is this approach acceptable?

texts:
I am learning PHP and have been looking into a suitable way to safely store password data in MySQL.

Following advice from here (https://stackoverflow.com/questions/4795385/how-do-you-use-bcrypt-for-hashing-passwords-in-php), is this an acceptable way to deal with passwords?

The code is a very basic example and I haven't included things like error checking / checking if user already exists etc. to keep my example concise.

New Register User:

$fld_email =    $_POST['fld_email'];
$fld_name =     $_POST['fld_name'];
$fld_pwd =      $_POST['fld_pwd'];

$hashToStoreInDb = password_hash($fld_pwd, PASSWORD_BCRYPT, array("cost" => 11));

  $sql = "INSERT INTO tbl_a_users (fld_email
                                 , fld_name
                                 , fld_pwd
                                 , fld_date)
                           VALUES (:fld_email
                                 , :fld_name
                                 , :fld_pwd
                                 , now())";

$stmt = $pdo->prepare($sql);

$stmt->bindParam(':fld_email', $fld_email);
$stmt->bindParam(':fld_name', $fld_name);
$stmt->bindParam(':fld_pwd', $hashToStoreInDb);

$stmt->execute();

New Process Login:

$fld_email    = $_POST['fld_email'];
$fld_pwd_form = $_POST['fld_pwd'];

$stmt = $pdo->prepare('SELECT fld_pwd FROM tbl_a_users WHERE fld_email = :email LIMIT 1');
$stmt->bindParam(':email', $fld_email);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_OBJ);

$isPasswordCorrect = password_verify($fld_pwd_form, $row->fld_pwd);

if ($isPasswordCorrect == true) {
    // do something
} else {
    // do something else
}

There is no error message here, but I wanted to check with experts about whether this is an acceptable approach before I continue work on this area.

I will also be using HTTPS for the login / register pages.


texts: Print every line of file, last to first, with recursion

texts:
Had a discussion with a friend to solve this extra credit problem, and we came up with two separate solutions. What are the differences between these two? Is one better than the other? How can I make this code better?

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Scanner;

public class ExtraCredit {

    public static void main(String[] args) throws FileNotFoundException {
        int count = 0;
        Scanner scan = new Scanner(new File("src/ExtraCredit.java"));
        recursiveCountEveryOtherLine(count, scan);
        scan = new Scanner(new File("src/ExtraCredit.java"));
        System.out.println("***SECOND METHOD***");
        recursiveScannerExploit(scan);
    }
    // Write a method called from main that prints
    // every other line of this file from last to first
    // use recursion NO LOOPS!!
    // print line 10, 8, 6, 4, 2

    public static void recursiveCountEveryOtherLine(int count, Scanner scan) {
        count++;
        if (!scan.hasNextLine()) {
            scan.close();
            return;
        } else if (count % 2 == 0) {
            String temp = scan.nextLine();
            recursiveCountEveryOtherLine(count, scan);
            System.out.println(count + " " + temp);

        } else {
            scan.nextLine();
            recursiveCountEveryOtherLine(count, scan);
        }
    }

    public static void recursiveScannerExploit(Scanner scan) {
        if (closeScanner(scan)) {
            return;
        }
        String tempGarbage = scan.nextLine(); // Used to pop an element off the scanner
        if (closeScanner(scan)) {
            return;
        }
        String temp = scan.nextLine();
        recursiveScannerExploit(scan);
        System.out.println(temp);
    }

    public static boolean closeScanner(Scanner scan) {
        if (!scan.hasNextLine()) {
            scan.close();
            return true;
        } else {
            return false;
        }
    }
}