texts:
This generic function invokes a property of a given object by name:

  Private Shared Function GetPropertyValueByName(Of TObject, TProperty)(
        ByVal T As TObject,
        ByVal PropertyName As String) As TProperty

        Dim result = GetType(TObject).GetProperties() _
            .Where(
                Function(p) (p.Name = PropertyName) _
                    AndAlso p.CanRead() _
                    AndAlso (p.PropertyType Is GetType(TProperty))
                ).FirstOrDefault()

        If (result IsNot Nothing) Then
            Return CType(result.GetValue(T), TProperty)
        End If

        Return Nothing

    End Function

Can this function be improved in some way? Can it generate some sort of issues I have to be aware of? Can it be improved in terms of readability?


texts: Drawing stars around the center of the screen

texts:
I have an homework as follows:

  Write a program where you enter from the keyboard a number n. Then n
  stars are drawn onto the screen, circling around the center of your
  screen. You can assume that 1 < n < 20.

The solution I came up with is below.

import turtle

window=turtle.Screen()
window.screensize(1200,1200)

draw=turtle.Turtle()
draw.pensize(2)

draw.speed('fastest')

angle = [36,144,144,144,144]

GetNumber = int(input("Enter a number: "))

while GetNumber <= 1 or GetNumber >= 20:
    print("Enter a number between from 2 to 19")
    GetNumber = int(input("Enter a number: "))

for shape in range(GetNumber):
    for i in angle:
        draw.left(i)
        draw.forward(180)
    draw.penup()
    draw.forward(60)
    draw.pendown()
    draw.left(170)

Is there any way to improve this code? I think my code is OK, but I believe there are perhaps more concise or better solutions (working faster perhaps?)

Perhaps angle (currently 170) should be changed or perhaps an dynamic angle changer code can be implemented for the sake of improving the solutions. What do you think?


texts:
I have a simple text file setup as a Resource through my application's Properties as a byte[]. In order to access a "Stream.ReadLine" function, I believe I need to make it into a StreamReader. Is there a way to get the following result using only 1 Stream, or else, any tricks to make it better?

List<string> list = new List<string>();

using (Stream s = new MemoryStream(myFile))
{
    using (StreamReader sr = new StreamReader(s))
    {
        while (!sr.EndOfStream)
        {
            list.Add(sr.ReadLine());
        }
    }
}


texts:
I am trying to build something similar to planning poker and am very new to Knockout and was wondering if anyone could help me improve on my very crude start?

This is what I have so far:

HTML

Selected Card

CSS

 .profile { width: 50px; height: 80px; color: #FFF; background: black; border: 1px solid   #FFF; float: left; line-height:80px }
 .highlight { background: yellow !important; border:1px solid #000; color: black; }

JavaScript/Knockout

function Step(number) {
    this.active = ko.observable(false);
    this.name = ko.observable( number);
}

var model = function () {
    var items = ko.observableArray([new Step(1), new Step(2), new Step(3), new Step(5),new Step(8),new Step(13),new Step(20),new Step(40),new Step(100)]);
    var selectedItems = ko.computed(function () {
        return _.filter(items(), function (item) {
            return item.active();
        });
    })

    var clicked = function (item) {
        items().forEach(function(item){ item.active(false) });
        item.active(!this.active());
    };

    var save = function () {
        alert("sending items \n" + ko.toJSON(selectedItems()));
    }

    return {
        items: items,
        selectedItems: selectedItems,
        save: save,
        clicked: clicked
    }
}

ko.applyBindings(model);

http://jsfiddle.net/grahamwalsh/63yeD/


texts: PHP Dictionary class accepting objects as keys

texts:
I started creating a Dictionary class that accepts objects as there keys:

class Dictionary
    implements ArrayAccess
{
    private $_keys = array();

    private $_values = array();

    public function offsetExists( $key )
    {
        return false !== array_search( $key, $this->_keys, true );
    }

    public function offsetGet( $key )
    {
        if( false === ( $index = array_search( $key, $this->_keys, true ) ) )
        {
            throw new OutOfBoundsException( 'Invalid dictionary key' );
        }

        if( !isset( $this->_values[ $index ] ) )
        {
            throw new LogicException( 'No matching value found for dictionary key' );
        }

        return $this->_values[ $index ];
    }

    public function offsetSet( $key, $value )
    {
        if( false !== ( $index = array_search( $key, $this->_keys, true ) ) )
        {
            $this->_values[ $index ] = $value;
        }
        else
        {
            $this->_keys[] = $key;
            $this->_values[] = $value;
        }
    }

    public function offsetUnset( $key )
    {
        if( false === ( $index = array_search( $key, $this->_keys, true ) ) )
        {
            throw new OutOfBoundsException( 'Invalid dictionary key' );
        }

        if( !isset( $this->_values[ $index ] ) )
        {
            throw new LogicException( 'No matching value found for dictionary key' );
        }

        array_splice( $this->_keys, $index, 1 );
        array_splice( $this->_values, $index, 1 );
    }
}

It works pretty well for the very elementary test cases I've done so far. However, I'm worried about three things:

Can you think of a situation where $this->_keys and $this->_values will not be synchronized with each other anymore, thus leading to data corruption? I thought maybe there could occur a situation where something might happen between the two array_splices, for instance, in:

public function offsetUnset( $key )
{
    ...

    array_splice( $this->_keys, $index, 1 );
    array_splice( $this->_values, $index, 1 );

... leading to data corruption.
I feel array_search() might be inefficient, but I specifically don't want to resort to using spl_object_hash() as keys (and thereby circumventing the need for an internal keys and values array) as I belief this is not bulletproof, as it doesn't guarantee hash uniqueness for objects at all.
I feel array_splice() might be inefficient, but I don't want to resort to unset() as I feel this could lead to unwieldy internal arrays keys eventually. I'd like to keep the internal arrays keys as tightly packed as possible.

Looking forward to your feedback.


texts: Manage Recent List Of user and staff type objects

texts:
So I have a view which shows recent 5 staff users and 5 customers for a restaurant app. I am storing this in user default.

I am also managing the currently selected object.

Here is my class.

//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
//This class is used for saving the user object and fetching the user object from user default
// user obejct can be Staff User or Customer object

enum RecentStaffErros : Error {
    case userObjectAddUpdateFailed
}

protocol RecentListManagable:FireCodable {
    var firstName: String? { get set }
    var lastName: String? { get set }
}

class RecentUserDataManager<T:RecentListManagable> {

    var selectedData:T? = nil
    private let recentLimit = 5
    private(set) var recentUsers:[T] = []
    private var userDefaultKey:UserDefaults.RecentUsersList.ArrayDefaultKey

    var recentUserDidChanged:(([T]) -> Void)?

    var isDataAvailable:Bool {
        return recentUsers.isEmpty
    }

    init(userDefaultKey:UserDefaults.RecentUsersList.ArrayDefaultKey) {
        self.userDefaultKey = userDefaultKey
        fetchLastFiveStaffUsersFromUserDefault()
    }

    private func fetchLastFiveStaffUsersFromUserDefault() {
        let staffUsers = UserDefaults.RecentUsersList.array(forKey: userDefaultKey) as? [[String:Any]]
        self.recentUsers =   staffUsers?.map({ (object) -> T?  in
            if let staffData = object.data {
                return try? JSONDecoder().decode(T.self, from: staffData)
            }
            return nil
        }).compactMap{$0} ?? []

    }

    private func saveLastFiveCustomerToUserDefault() {
        let arrayOfDictionary = self.recentUsers.map {$0.values}.compactMap{$0}
        UserDefaults.RecentUsersList.set(arrayOfDictionary, forKey: userDefaultKey)
    }

    func addOrUpdateStaffUserIfRequired(_ user:T) throws  {
        guard  let data = user.values else {
            throw RecentStaffErros.userObjectAddUpdateFailed
        }
        //we found the data remove from that index and append to bottom
        if let index =  recentUsers.firstIndex(where: {$0.id == user.id}) {
            self.recentUsers.remove(at: index)
        }
            //append new object
        self.recentUsers.insert(user, at: 0)

        if self.recentUsers.count > 5 {
            //keep only 5 users
            self.recentUsers = Array(self.recentUsers.prefix(recentLimit))
        }

        saveLastFiveCustomerToUserDefault()
        switchCurrentSelectedUser(user)
        self.recentUserDidChanged?(self.recentUsers)

    }

    func switchCurrentSelectedUser(_ user:T) {
        self.selectedData = user
    }

}

In my view controller where I am managing the list

 private var recentStaffUsers:RecentUserDataManager<ObjectUser> = RecentUserDataManager(userDefaultKey: .arrayStaffUsers)

 private var recentCustomerUsers:RecentUserDataManager<ObjectCustomer> = RecentUserDataManager(userDefaultKey: .arrayCustomerUser)

 private func setupForCustomer() {
        createButtonsForCustomer() //create 5 buttons
        recentCustomerUsers.recentUserDidChanged = {[weak self] _ in
            DispatchQueue.main.async {
                //When New customer added or removed update Buttons
                self?.createButtonsForCustomer()
            }
        }
    }

In my code do you see any improvements or issues?
Should I think to refactor RecentUserDataManager  more deeply like separate logic


texts: MIPS Assembly Program to access elements in the 4x4 matrix, row or column-major oder

texts:
This MIPS Assembly program will make you access the elements in the 4x4 matrix in either row or column-major order i.e. accessing all elements row by row or column by column.

Output is posted below as well.

Data section has variables declared, Text section has the main function.

This took me several days to put together since I just started this from scratch.
I'll appreciate any feedback.
I also hope this helps out those who are looking to to some matrix calculations and such.

# Data Section
.data
    .globl array

    .align 4
    array: .float 1.00, 2.00, 3.00, 4.00, 5.00, 6.00, 7.00, 8.00, 9.00, 10.00, 11.00, 12.00, 13.00, 14.00, 15.00, 16.00

    matrix_size: .word 4
    float_size: .word 4

    lb_:    .asciiz "Print in row or column-major order\n" #uncomment a line in ADDING OFFSET section to change which to print (can't print both at the same time!)

    j_:     .asciiz "j: "
    k_:     .asciiz " k: "
    bar_:   .asciiz " | "
    colon:  .asciiz ": "
    lineBrk: .asciiz "\n"

    # MIPS Printing Syntax
    # li $v0  n     # n = 1:(print_integer), 2:(print_float), 4:(print_str)
    # la $a0 text_  # text_ should be defined in the .data section above beforehand
    # syscall

# Text Section
.text
    .globl main
main:
    #Print title
    li $v0 4
    la $a0 lb_
    syscall

    la $a1 array
    move $s7 $a1 # base address of array

    lw $s1 matrix_size # $s1 = matrix_size
    lw $s2 float_size # $s2 = float_size

li $t5 0 # j counter
jloop:
    li $t6 0 # k counter
    # j kloop
        kloop:
            #Print j and k value
            #j: t5
            #k: t6

            li $v0 4        # "j"
            la $a0 j_
            syscall

            li $v0 1
            move $a0 $t5
            syscall         # value_j

            li $v0 4        # "k"
            la $a0 k_
            syscall

            li $v0 1
            move $a0 $t6
            syscall         # value_k

            li $v0 4        # " | "
            la $a0 bar_
            syscall

        ## Caculate column major offset
                # $s0 = offset result
                # $s1 = matrix_size: 4
                # $s2 = float_size: 4
                # $s7 = base address stored
                # $t5 = j
                # $t6 = k

                # offset = 4*(4*k + j) = float_size * (matrix_size*k + j)

            mul $s0 $s1 $t6 # s0 = 4*k
            add $s0 $s0 $t5 # s0 = s0 + j
            mul $s0 $s0 $s2 # s0 = 4*s0, offset stored in s0

            # print( offset: )
            li $v0 1
            move $a0 $s0
            syscall

            li $v0 4
            la $a0 colon
            syscall

        #### ADDING OFFSET ####

            # This will increase the memory address. It's like increasing the index for accessing next element.
            # addi $a1 $a1 4    #row major    -> new_addr += 4  (cumulatively increase the address to access the array by 4)
            add $a1 $s7 $s0     #column major -> new addr = base_addr + offset

            # print( element\n )
            lwc1 $f12 0($a1)
            li $v0 2
            syscall

            li $v0 4
            la $a0 lineBrk
            syscall

            # k_counter++
            addi $t6 $t6 1
            bne $t6 $s1 kloop

    # j_counter++
    addi $t5 $t5 1
    bne $t5 $s1 jloop

#Done, terminate program
    li $v0, 10
        syscall

.end main

Output: #0,16,32.. etc. are the offset added to the base address

it is in multiple of 4 since floats are 4 bytes


texts:
I'm just beginning to get the idea of queue and threading.

I would welcome input on this exercise script:

from threading import Thread as T
from Queue import Queue as Q
from random import randint as R
import time

'''
Silly script exploring simple use of threadding.Thread and Queue.Queue
'''

q = Q()

now = time.time()

def one_up(queue):
        while time.time() - now <= 20:
                other_num = queue.get()
                big_num = 5*other_num
                print("       {}!?!?".format(other_num))
                queue.put(big_num)
                print("Oh yea, well I put {} in the queue!".format(big_num))
                time.sleep(1)
        print("{} is a BIG number, man. Wow. Look. We made a pyramid.".format(big_num))

a_num = R(1,10)
q.put(a_num)
print("I put {} in the queue.".format(a_num))
t = T(target=one_up, args=(q,))
t.start()

Which outputs something along the lines of:

    I put 5 in the queue.
       5!?!?
Oh yea, well I put 25 in the queue!
       25!?!?
Oh yea, well I put 125 in the queue!
       125!?!?
Oh yea, well I put 625 in the queue!
       625!?!?
Oh yea, well I put 3125 in the queue!
       3125!?!?
Oh yea, well I put 15625 in the queue!
       15625!?!?
Oh yea, well I put 78125 in the queue!
       78125!?!?
Oh yea, well I put 390625 in the queue!
       390625!?!?
Oh yea, well I put 1953125 in the queue!
       1953125!?!?
Oh yea, well I put 9765625 in the queue!
       9765625!?!?
Oh yea, well I put 48828125 in the queue!
       48828125!?!?
Oh yea, well I put 244140625 in the queue!
       244140625!?!?
Oh yea, well I put 1220703125 in the queue!
       1220703125!?!?
Oh yea, well I put 6103515625 in the queue!
       6103515625!?!?
Oh yea, well I put 30517578125 in the queue!
       30517578125!?!?
Oh yea, well I put 152587890625 in the queue!
       152587890625!?!?
Oh yea, well I put 762939453125 in the queue!
       762939453125!?!?
Oh yea, well I put 3814697265625 in the queue!
       3814697265625!?!?
Oh yea, well I put 19073486328125 in the queue!
       19073486328125!?!?
Oh yea, well I put 95367431640625 in the queue!
       95367431640625!?!?
Oh yea, well I put 476837158203125 in the queue!
476837158203125 is a BIG number, man. Wow. Look. We made a pyramid.


texts:
This is the final iteration of an iterative review. The previous iteration can be found here: Utilities for various builtins #1

This code solves the following issue:

var i = 9
i.sqrt();     // 3
Math.sqrt(i); // 3

And other similar dilemmas. It also saves you from having to write your own mean and max function. I've also been told this is known as "syntatic sugar".

It's also worth it's weight in keypresses.

/**
 * Adds some utilities to the base classes.
 * Note that this is modular and is able to modify any class it is given.
 * @author FreezePhoenix
 * @version 1.1.0
 */

/**
 * @type {Object}
 * @constant
 */
const XtraUtils = {};
/**
 * @class
 * @classdesc Enables utilities to be added to classes.
 */
class Utility {
   /**
    * Create a new utility
    * @param {Object} ofWhat               - First part of the filter to test if it is a constructor.
    * @param {Function} ofWhat.constructor - Second part of the filter.
    * @return {Boolean}                    - false means something went wrong, true means it succeded.
    * @this Utility
    * @throws {TypeError} The first argument of Utility must be a class.
    */
    constructor(ofWhat) {
        if (typeof ofWhat == 'function' && typeof new ofWhat() === 'object') {
            this.utils = {};
            Object.defineProperty(this, 'aidsIn', {
                value: ofWhat,
                writable: false
            });
            this.Activated = [];
            this.OverWritten = {};
            return true;
        } else {
            console.error(
                'new Utility expects an object template to be passed as the first argument.'
            );
            return false;
        }
    }
    /**
     * Activates the utilities in this Utility instance.
     * @this Utility
     */
    activate() {
        for (const x in this.utils) {
            if (this.aidsIn.prototype[x]) {
                this.OverWritten[x] = this.aidsIn.prototype[x].valueOf();
            }
            this.aidsIn.prototype[x] = this.utils[x];
            this.Activated.push(x);
        }
    }
   /**
    * @this Utility
    */
    deactivate() {
        this.Activated.forEach((item, index) => {
            if (this.OverWritten[item]) {
                this.aidsIn.prototype[item] = this.OverWritten[item];
            } else {
                delete this.aidsIn.prototype[item];
            };
        });
        this.Activated = [];
    }
    /**
     * @this Utility
     */
    addUtil(name, util) {
        this.utils[name] = util;
    }
}
XtraUtils.Number = new Utility(Number);
XtraUtils.String = new Utility(String);
XtraUtils.Array = new Utility(Array);
XtraUtils.Number.addUtil('map', function(in_min, in_max, out_min, out_max) {
    return (this - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
});
XtraUtils.Number.addUtil(function(inputBase = 10, outputBase = 10) {
    parseInt(this, inputBase).toString(outputBase);
}, 'toBaseN');
XtraUtils.Number.addUtil('pow', function(n) {
    return Math.pow.apply(Math, this, n);
});
XtraUtils.Number.addUtil('ceil', function() {
    return Math.ceil.apply(Math,this);
});
XtraUtils.Number.addUtil('floor', function() {
    return Math.floor.apply(Math,this);
});
XtraUtils.Number.addUtil('sqrt', function() {
    return Math.sqrt.apply(Math,this);
});
XtraUtils.Array.addUtil('max', function() {
    return Math.max.apply(Math, this);
});
XtraUtils.Array.addUtil('min', function() {
    return Math.min.apply(Math, this);
});
XtraUtils.Array.addUtil('mean', function() {
    let total = 0;
    var isFirst = true;
    this.forEach(function(item) {
        if (typeof item === 'string') {
            throw Error('Item must be all numbers');
        }
        total += item;
    });
    const mean = total / this.length;
    return mean;
});


texts: Calculate questions per day on CodeGolf.SE

texts:
I wrote a short script in Python 3 that connects to the Stack Exchange API, gets all questions on Programming Puzzles & Code Golf over the past two weeks, and determines the average number of questions per day as well as the average number of answers per question.

The number of questions per day is intended to match that on Area 51, which it does. Obviously it's much easier to just scrape Area 51 directly, but I wanted to figure it out myself for practice.

I'm not an expert with Python or with web APIs, so I was hoping you fine Code Review folks can help me improve my practices.

import requests, datetime, time

def seconds_since_epoch(dt):
    epoch = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)
    return int((dt - epoch).total_seconds())

today = datetime.datetime.now(datetime.timezone.utc)

params = {
    "site": "codegolf",
    "fromdate": seconds_since_epoch(today - datetime.timedelta(days=14)),
    "todate": seconds_since_epoch(today),
    "pagesize": 100,
    "page": 1
}

base_url = "https://api.stackexchange.com/2.2"

results = []

while True:
    req = requests.get(base_url + "/questions", params=params)
    contents = req.json()
    results.extend(contents["items"])
    if not contents["has_more"]:
        break
    if "backoff" in contents:
        time.sleep(contents["backoff"])
    params["page"] += 1

questions_per_day = len(results) / 14
answers_per_question = sum([q["answer_count"] for q in results]) / len(results)

print("Over the past 2 weeks, PPCG has had...")
print(round(questions_per_day, 1), "questions per day")
print(round(answers_per_question, 1), "answers per question")

My approach is to build the query using a dict and make the request to the API using the requests module. I set the page size to the maximum to reduce the number of requests made so that the daily quota isn't exhausted quite so fast.

The code is hosted on GitHub, should you want to fork and adapt it for your own purposes, assuming it isn't too terrible.


texts:
I'm new to programming and in back-end. Right now I'm trying to learn flask, so I wrote a very simple website that currently encrypts and decrypts the message using RSA and DES.

I feel like my app.py file is just bad and should do it much better. I mean, there're a lot of repeating code like this:

@app.route('/rsa_encrypt', methods=['GET', 'POST'])
def RSA_enc():
    global get_form
    if request.method == "GET":
        get_form = True
        return render_template('rsa_encrypt.html', gf=get_form)
    else:
        get_form = False
        rsa = RSA(request.form.get('pt'), p=request.form.get('p'),
                  q=request.form.get('q'), e=request.form.get('e'))
        return render_template('rsa_encrypt.html', gf=get_form, rsa=rsa, gspn=gspn)

I tried to write some decorators for those routes, but they didn't work well.

Can you take a look and tell me what should I do better? It works but I think not as well as it should.

app.py

from flask import Flask, render_template, request, url_for, jsonify
from ciphers import RSA, DES
from prime import generate_semiprime_number as gspn

app = Flask(__name__)
get_form = None

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/rsa_encrypt', methods=['GET', 'POST'])
def RSA_enc():
    global get_form
    if request.method == "GET":
        get_form = True
        return render_template('rsa_encrypt.html', gf=get_form)
    else:
        get_form = False
        rsa = RSA(request.form.get('pt'), p=request.form.get('p'),
                  q=request.form.get('q'), e=request.form.get('e'))
        return render_template('rsa_encrypt.html', gf=get_form, rsa=rsa, gspn=gspn)

@app.route('/rsa_decrypt', methods=['GET', 'POST'])
def RSA_dec():
    global get_form
    if request.method == "GET":
        get_form = True
        return render_template('rsa_decrypt.html', gf=get_form)
    else:
        get_form = False
        ct = [int(x) for x in request.form.get('ct')[1:-1].split(',')]
        rsa = RSA(ciphertext=ct, p=request.form.get('p'),
                  q=request.form.get('q'), e=request.form.get('e'))
        return render_template('rsa_decrypt.html', gf=get_form, rsa=rsa)

@app.route('/des_encrypt', methods=['GET', 'POST'])
def DES_enc():
    global get_form
    if request.method == "GET":
        get_form = True
        return render_template('des_encrypt.html', gf=get_form)
    else:
        get_form = False
        des = DES(request.form.get('pt'), user_key=request.form.get('key'))
        return render_template('des_encrypt.html', gf=get_form, des=des)

@app.route('/des_decrypt', methods=['GET', 'POST'])
def DES_dec():
    global get_form
    if request.method == "GET":
        get_form = True
        return render_template('des_decrypt.html', gf=get_form)
    else:
        get_form = False
        des = DES(ciphertext=request.form.get('ct'), user_key=request.form.get('key'))
        return render_template('des_decrypt.html', gf=get_form, des=des)

@app.route('/gpsn', methods=['POST'])
def _gpsn():
    return jsonify({'result' : str(gspn(request.form['bits']))})

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

Other files repository. It's also hosted so you can quickly take a look.


texts:
In Pascal/Delphi, there's a built-in function for inserting a substring into a main string.

procedure Insert ( const InsertStr : string; var TargetStr : string; Position : Integer ) ;

I'm used to this function, so I'd like to simulate it in C.

Because the main string will generally become longer after an insertion, the way to proceed is:

To have some extra space in a char array allocated in stack, or
To use dynamically allocated strings.

I've chosen the second option. At the moment my code looks like this. It uses the standard C string.h library.

#include "stdlib.h"
#include "string.h"

void myStrInsert(const char *pWord, char **pStr, int pos)
{
    // Only dynamically allocated strings are allowed.
    if (pos < 0)
        return;
    int lenStr = strlen(*pStr);
    if (pos > lenStr)
        pos = lenStr;
    int lenWord = strlen(pWord);

    char *pResult = (char *)malloc(lenStr + lenWord + 1);
    if (pResult != NULL) {
        memcpy(pResult, *pStr, pos);
        memcpy(pResult + pos, pWord, lenWord);
        memcpy(pResult + pos + lenWord, *pStr + pos, lenStr - pos + 1);
        free(*pStr);
        *pStr = pResult;
    }
}

Can this function be simplified/optimized?


texts: Two times same code in methode except one little line

texts:
In Service.Insert(), I call DeviceRepo.Insert() and in Service.Update(), I call DeviceRepo.Update(). All my other code is exactly the same.

I'm thinking I can make one method that do the same thing update. I want to update and insert when I will insert a device.

The methods respectively insert a new or update an existing (IoT) device into my database with entity framework 6.

How could I refactor the code? You can see I have the same methods twice where only another method is called.

public class DeviceService : IDeviceService
{
    internal IGenericRepo<Device> _deviceRepo;

    public DeviceService()
    {
        _deviceRepo = new DeviceRepo(); // P.S.: DeviceRepo overrides GenericRepo<Device> who implements IGenericRepo<Device>
    }

    public void Insert(Device device, IEnumerable<int> selectedFrameworks, IEnumerable<int> selectedOSs)
    {
        device.Framework = GiveObjects<Framework>(selectedFrameworks, _frameworkRepo);
        device.OS = GiveObjects<OS>(selectedOSs, _osRepo);

        SetStateUnchanged<Framework>(device.Framework);
        SetStateUnchanged<OS>(device.OS);

        _deviceRepo.Insert(device);
        _deviceRepo.SaveChanges();
    }

    public void Update(Device device, IEnumerable<int> selectedFrameworks, IEnumerable<int> selectedOSs)
    {
        device.Framework = GiveObjects<Framework>(selectedFrameworks, _frameworkRepo);
        device.OS = GiveObjects<OS>(selectedOSs, _osRepo);

        SetStateUnchanged<Framework>(device.Framework);
        SetStateUnchanged<OS>(device.OS);

        _deviceRepo.Update(device);
        _deviceRepo.SaveChanges();
    }
}

GenericRepo<Device>:

public class GenericRepo<TEntity> : IGenericRepo<TEntity> where TEntity : class
{
    internal ApplicationDbContext context;
    internal DbSet<TEntity> dbSet;

    public GenericRepo()
    {
        context = new ApplicationDbContext();
        dbSet = context.Set<TEntity>();
    }

    public virtual TEntity Insert(TEntity entity)
    {
        return dbSet.Add(entity);
    }

    public virtual void Update(TEntity entityToUpdate)
    {
        context.Entry(entityToUpdate).State = EntityState.Modified;
        dbSet.Attach(entityToUpdate);
    }

    public virtual void SaveChanges()
    {
        context.SaveChanges();
    }
}

public class DeviceRepo : GenericRepo<Device>
{ /* not important methods I override for this question */ }


texts: Removing commented dead code without removing the legitimate comments

texts:
This question is the real question asked on StackOverflow. I'm here to review my answer and see how can I optimize it.

Here is the answer text:

This is a basic approach, but it proposes a proof of concept of what might be done. I do it using Bash along with the usage of the GCC -fsyntax-only option.

Here is the bash script:

#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
    LINE=`echo $line | grep -oP "(?<=//).*"`
    if [[ -n "$LINE" ]]; then
            echo $LINE | gcc -fsyntax-only -xc -
            if [[ $? -eq 0 ]]; then
                   sed -i "/$LINE/d" ./$1
            fi
    fi
done < "$1"

The approach I followed here was reading each line from the code file. Then, greping the text after the // delimiter (if exists) with the regex (?<=//).* and passing that to the gcc -fsyntax-only command to check whether it's a correct C/C++ statement or not. Notice that I've used the argument -xc - to pass the input to GCC from stdin (see my answer here to understand more). An important note, the c in -xc - specifies the language, which is C in this case, if you want it to be C++ you shall change it to -xc++.

Then, if GCC was able to successfully parse the statement (i.e., it's a legitimate C/C++ statement), I directly remove it using sed -i from the file passed.

Running it on your example (but after removing <- commented code from the third line to make it a legitimate statement):

// Those parameters control foo and bar... <- valid comment
int t = 5;
// int t = 10;
int k = 2*t;

Output (in the same file):

// Those parameters control foo and bar... <- valid comment
int t = 5;
int k = 2*t;

(if you want to add your modifications in a different file, just remove the -i from sed -i)

The script can be called just like: ./script.sh file.cpp, it may show several GCC errors while these are the correct


texts:
Please have a look at the code below:

ClassLibrary1 has a structure as follows:

Namespace com.app.test
Public Class Class1

End Class
End Namespace

ClassLibrary2 has a structure as follows:

Namespace com.app.test
Public Class Class2

End Class
End Namespace

WindowsApplication1 has a structure like this:

Imports com.app.test

Public Class Form1
    Dim c1 As Class1
    Dim c2 As Class2
End Class

Notice that Class1 and Class2 are in different projects (DLL's), but they have the same namespace.  Is this poor practice? I have never seen it done before.


texts:
I have a graph represented using a dict of sets, e.g.

graph = {
    0: {1, 2, 3},  # neighbors of node "0"
    1: {0, 2},
    2: {0, 1},
    3: {0, 4, 5},
    4: {3, 5},
    5: {3, 4, 7},
    6: {8},
    7: {5},
    8: {9, 6},
    9: {8}
}

I use the following code to find connected components in the graph:

def get_connected_components(graph):
    seen = set()
    components = []

    for node in graph:
        if node not in seen:
            component = []
            nodes = {node}

            while nodes:
                node = nodes.pop()
                seen.add(node)
                component.append(node)
                nodes.update(graph[node].difference(seen))
            components.append(component)

    return components

print(get_connected_components(graph))  # [[0, 1, 2, 3, 4, 5, 7], [6, 8, 9]]

Is there a better way to do this (e.g. a better representation of the graph or an algorithm) ?


texts: How should I name a function which shows or hides an element?

texts:
I have a function to display or hide some elements. What I want to do is to manage the display of those elements regarding a value.

How should I replace the term toggle? Toggling for me means 'show the element if it's hidden, or hide it if it shown.' (yes, I mean toggling visibility)

function togglePassengers() {
    var nbPassengers = $("#nbPassengersForTravel").val(),
        $passengers = $('#d_passenger').find('fieldset');

    $passengers.each( togglePassenger );

    function togglePassenger(i){
        $passenger = $(this);
        if( ++i <= nbPassengers )
            showPassenger($passenger);
        else
            hidePassenger($passenger);
    }

    function showPassenger($passenger){
        $passenger
            .removeClass("hidden")
            .find("select.age option[value='-1']").remove();
    }

    function hidePassenger($passenger){
        $passenger.addClass("hidden");
        var $passengerAge = $passenger.find("select.age");
        if ( ! $passengerAge.find("option[value='-1']:first-child").length )
            $passengerAge.prepend("<option value='-1'>---------</option>").val('-1');
    }
}


texts:
I am working on the problem of removing comments from C-like source code. Here is my code in Python 2.7, and if anyone could advise improvement areas (especially performance), or any functional bugs which I do not discover, it will be great.

Problem statement

Given a file path represented as string, take this input string and remove all the comments in the file, print this file or save this to a new txt file by your choice.

Cases to consider:

// comment
/*

    comment
    */
    foo(); // comment

Source code

code='''// comment
/*
    /* hello python */
    comment
    */
    foo(); // comment
'''

def remove_comment(content):
    index = 0
    comment_line_inside = False
    comment_block_level = 0
    result = []
    while index < len(content):
        if content[index] == '/' and index + 1 < len(content) and content[index+1] == '*':
            comment_block_level += 1
        elif content[index] == '/' and content[index-1] == '*':
            comment_block_level -= 1
        elif content[index] == '/' and index + 1 < len(content) and content[index + 1] == '/':
            comment_line_inside = True
        elif content[index] == '\n' and comment_line_inside == True:
            comment_line_inside = False
        elif not comment_line_inside and comment_block_level == 0:
            result.append(content[index])
        index += 1

    return ''.join(result)

if __name__ == "__main__":
    print remove_comment(code)


texts: Printing all primes < 1,000,000 to a text file

texts:
It takes a long time to execute and the CPU usage for the executable is about 25% while it is executing. Any ideas on how to make this faster?

primes.c:

#include <stdio.h>
#include "primes.h"

/* COUNT will be how many numbers to
 * check and see if they are prime */
#define COUNT 1000000

int main(void)
{
  FILE *ftp;
  /* open the file for writing*/
  ftp = fopen("primes.txt", "w");

  printPrimes(ftp, COUNT);
  return 0;
}

primes.h:

#include <stdbool.h>

bool isPrime(int number)
{
  int i;
  for (i = 1; i <= number; i++)
  {
    /* if i is not 1 and i is not the number itself,
     * ...then, check to see if the number divided
     * by i has a remainder of 0 */

    /* If the number divided by i (i != 1 or itself
     * has a remainder of zero, return false
     * (the number is NOT prime */

    if (i != 1 && i != number && (number % i == 0))
    {
      return false;
    }

  }
    /* If number is NOT found to be NOT prime, return true */
      return true;
}

void printPrimes(FILE *ftp, int count)
{
  int number;
  /* is the prime number, the first prime, second, etc
   * that is the value the places variable holds */
  int place = 0;

  /* print all primes starting at true and going to count */
  for (number = 2; number <= count; number++)
  {
    /* if the number is prime */
    if (isPrime(number))
    {
    place++;
    /* print to number to the file*/
    fprintf(ftp, "%d. %d\n", place, number);
    }
  }
}


texts: Select second field in text table with shell script

texts:
I am writing a bash script to mount openshift service accounts into kubernetes objects. The right secret to use is highlighted in this text:

$ oc describe sa sa-build-webhook-realworld
Name:                sa-build-webhook-realworld
Namespace:           your-eng2
Labels:              app=sa-build-webhook-realworld
Annotations:         <none>
Image pull secrets:  sa-build-webhook-realworld-dockercfg-4qz9g
Mountable secrets:   sa-build-webhook-realworld-token-bqtnw
                     sa-build-webhook-realworld-dockercfg-4qz9g
Tokens:              sa-build-webhook-realworld-token-bqtnw
                     sa-build-webhook-realworld-token-k7lq8
Events:              <none>

I want the code to be reasonably robust so I am thinking of this as a job for awk where I need "anything in column 2 that is a 'Mountable secret' that isn't the docker secret". Here is the logic I have come up with:

MOUNTABLE_SECRETS='Mountable secrets:'
SECRET_NAME=$(\
   oc describe sa sa-build-webhook-realworld \
   | sed $(printf 's/./&,/%s' ${#MOUNTABLE_SECRETS}) \
   | awk  'BEGIN{FS=OFS=","} {if ($1 ~ /^[ \t]*$/) $1=ch; else ch=$1} 1'  \
   | grep "$MOUNTABLE_SECRETS" \
   | sed 's/[, ]*//g' \
   | awk -F':' '{print $2}' \
   | grep -v docker \
   | grep token)
echo "SECRET_NAME=$SECRET_NAME"

Basically, I insert a character just beyond the width of that phrase to cut the table in half, copy cells on the left into blanks below, then select the second column then grep what I am looking for.

To my mind, it breaks things into pieces that can be understood. It works, but past experiences have taught me that someone looking to maintain that may not be best pleased. Since performance is not an issue what I am really aiming for is maintainability. I also want portability and I am looking to stick with to typical bash and coreutils tools.

How might I improve that script?


texts: 115 line brainfuck interpreter written in C++

texts:
This is a simple brainfuck interpreter I've written in C++. It takes a path to a brainfuck source file as a command line argument. The program uses a tape size of 30000 and cell size of one byte. Decrementing a cell's value under 0 will wrap it to 255 and vice versa.

I would really appreciate any kind of feedback, especially on how the existing code could be improved.

I'm using Apple Clang/LLVM and I've been compiling with the command:

clang++ -pedantic -O3 -std=c++17 brainfuck.cpp -o brainfuck

brainfuck.cpp:

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

/* Read the source file into a char vector, and return the vector. */
std::vector<char> read_source(std::string&& file_path)
{
    std::ifstream file(file_path);

    std::vector<char> source;

    char c;
    while (file.get(c)) {
        source.push_back(c);
    }

    return source;
}

/* Remove all but chars, which don't have meaning in brainfuck, from the source file.
 * This removes whitespace, newlines and comment chars. */
void filter_chars(std::vector<char>& source)
{
    auto new_end = std::remove_if(source.begin(), source.end(),
                                  [](char c) { return !std::strchr("<>+-[],.", c); });

    source.erase(new_end, source.end());
}

/* The actual interpreter. Goes through the source char by char and
 * acts according to brainfuck's rules. */
void interpret(std::vector<char>& source)
{
    std::vector<unsigned char> tape(30000, 0);
    int h = 0;  // the tape head

    int brace_count = 0;  // keeps track of nested braces

    int i = 0;  // the index to read the source
    while (i < source.size()) {
        switch (source[i]) {
            case '<':
                --h;
                break;
            case '>':
                ++h;
                break;
            case '+':
                ++tape[h];
                break;
            case '-':
                --tape[h];
                break;
            case '.':
                std::cout << tape[h] << std::flush;
                break;
            case ',':
                std::cin >> tape[h];
                break;

            case '[':
                if (tape[h] == 0) {
                    ++brace_count;
                    while (source[i] != ']' || brace_count != 0) {
                        ++i;
                        if (source[i] == '[') {
                            ++brace_count;
                        }
                        else if (source[i] == ']') {
                            --brace_count;
                        }
                    }
                }
                break;

            case ']':
                if (tape[h] != 0) {
                    ++brace_count;
                    while (source[i] != '[' || brace_count != 0) {
                        --i;
                        if (source[i] == ']') {
                            ++brace_count;
                        }
                        else if (source[i] == '[') {
                            --brace_count;
                        }
                    }
                }
                break;

        }
        ++i;
    }
}

int main(int argc, char* argv[])
{
    if (argc > 1) {
        std::vector<char> source = read_source(argv[1]);
        filter_chars(source);
        interpret(source);
        return 0;
    }
    else {
        std::cout << "Expected a brainfuck source file as a command line argument.\n";
        std::cout << "Terminating the program." << std::endl;
        return 1;
    }
}


texts: Storing configuration data in a global variable on application startup

texts:
I've never used a global variable in one of my programs(of which there are few) before, is this a fair use of one?

Currently, I have several classes calling a function to grab the data they require from a .yaml file stored in the user home folder. Each class constructs the full path of where the .yaml file should be using two vars; os.path.expanduser("~") and the default filename. This I feel, is messy.

The code below is a simple example of my actual program:

hub.py(Context manager instantiated on startup by main.py):

class Hub:

    def __init__(self):
        self.filename = "config_data.yaml"
        self.filepath = os.path.join(os.path.expanduser("~"), self.filename)

    def __enter__(self):
        global config_data

        with open(self.filepath) as f:
            config_data = yaml.load(f)

        return self

    def __exit__(self, exc_type, value, traceback):
        pass

with Hub() as hub:
    pass

Example use:

from hub import config_data

class Bot:
    def __init__(self):
        self.pricing_params = config_data["pricing"]


texts: Fast evaluation of Euclidean distance with sparse data

texts:
I am working on a KNN implementation for sparse datasets (that I apply to text analysis). My points are represented by a Dictionary<string, double>, each key represents a word of the text and the value, its count or TFIDF.

I am using index inversion to reduce the number of distances to evaluate. However, evaluating the distance remains the bottleneck. It is represented in the following method:

    public static double Euclide(Dictionary<string, double> sp1, Dictionary<string, double> sp2)
    {
        double distance = 0;
        foreach (KeyValuePair<string, double> kvp1 in sp1)
        {
            if (sp2.ContainsKey(kvp1.Key))
                distance += Math.Pow((kvp1.Value - sp2[kvp1.Key]), 2);
            else
                distance += Math.Pow((kvp1.Value), 2);
        }

        foreach (KeyValuePair<string, double> kvp2 in sp2)
            if (!sp1.ContainsKey(kvp2.Key))
                distance += Math.Pow((kvp2.Value), 2);

        return distance;
    }

How can I make it faster? Any help would be greatly appreciated.

I think I could reduce the time of evaluation using a Dictionary<int, double>, but I prefer to stick to strings, as it allows me to see at a glance what is going on (hashing words would compromise that).

The following yieled a 1.3~2.1x improvement (depending on the length of the input, but it is still not enough) :

    public static double FastEuclide(Dictionary<string, double> sp1, Dictionary<string, double> sp2)
    {
        double distance = 0;
        foreach (KeyValuePair<string, double> kvp1 in sp1)
        {
            double sp1Value = kvp1.Value;

            if (sp2.ContainsKey(kvp1.Key))
            {
                double sp2Value = sp2[kvp1.Key],
                    diff = kvp1.Value - sp2[kvp1.Key];
                distance += diff * diff;
            }
            else
                distance += sp1Value * sp1Value;
        }


texts: Checking for new software updates to the client

texts:
I have written a very simple web service with MVC and WebApi. Now I'm working on the client code which will be a WPF application (and soon Windows 8 Store/Phone app). What I have done works, but I'm not sure I'm doing it the "right" way. The purpose of the service is to check if there are any new software updates to the client.

My server code looks like this (simplified):

public class ProductVersionsController : ApiController
{
    private ApplicationDbContext db = new ApplicationDbContext();

    [HttpGet]
    public CheckVersionResult CheckVersion(string product, string platform, string version)
    {
        CheckVersionResult result = new CheckVersionResult();

        //Logic removed...

        return result;
    }
}

My client code looks like this (simplified):

string parameters = "product=myproduct&platform=wpf&version=1.2.3.4";
string CheckUrl = "http://localhost:61933/api/ProductVersions/CheckVersion";

var url = new Uri(CheckUrl + "?" + parameters);
using (var client = new System.Net.WebClient())
{
    var json = await client.DownloadStringTaskAsync(url);

    CheckVersionResult data = JsonConvert.DeserializeObject<CheckVersionResult>(json);

    //Logic removed...
}

The deserializing is done with Json.net.

Should I use HttpGet for a service like this, or should I use Post to send the parameters? How the parameters are sent feels a bit clumsy. If the parameters were encapsulated in a class, how should that be solved on the client side? Is there any good practice I have missed?


texts: How to find the next sequence of integers?

texts:
I was thinking of the following problem: List all sequences \$ a_1, a_2, a_3, a_4, a_5, a_6, a_7 \$ of positive integers where \$ 1 \le a_1 < a_2 < \ldots < a_7 \le 39 \$. For any sequence with this property, my code computes the next sequence in lexicographic order. Starting with the initial sequence \$ [1,2,3,4,5,6,7] \$, calling next_row(a) repeatedly  produces all such sequences.
Is there more elegant way to code the function that returns the next row than this?
def next_row(a):
    if a[-1]<39:
             a[-1]+=1
             return a
    elif a[-2]<38:
            a[-2]+=1
            a[-1]=a[-2]+1
            return a
    elif a[-3]<38:
            a[-3]+=1
            a[-2]=a[-3]+1
            a[-1]=a[-2]+1
            return a
    elif a[-4]<37:
            a[-4]+=1
            a[-3]=a[-4]+1
            a[-2]=a[-3]+1
            a[-1]=a[-2]+1
            return a
    elif a[-5]<36:
            a[-5]+=1
            a[-4]=a[-5]+1
            a[-3]=a[-4]+1
            a[-2]=a[-3]+1
            a[-1]=a[-2]+1
            return a
    elif a[-6]<35:
            a[-6]+=1
            a[-5]=a[-6]+1
            a[-4]=a[-5]+1
            a[-3]=a[-4]+1
            a[-2]=a[-3]+1
            a[-1]=a[-2]+1
            return a
    elif a[-7]<34:
            a[-7]+=1
            a[-6]=a[-7]+1
            a[-5]=a[-6]+1
            a[-4]=a[-5]+1
            a[-3]=a[-4]+1
            a[-2]=a[-3]+1
            a[-1]=a[-2]+1
            return a


texts: A couple of basic string parsing functions

texts:
I have an app that does a fair bit of text-parsing based on free-form user inputs.  In this, I run searches on the whole string, and then on the last value of the string separate from the rest of the string.  Here is a pair of functions I wrote to getLast and getSubString.

<cffunction name="getLast" output="no" returnType="string" access="public" hint="Takes a string and returns the last value by either comma or space, or returns nothing if the string is only one value long">
    <cfargument name="str" required="yes" type="string">

    <cfset var returnVar = "">

    <cfif listLen(arguments.str) GT 1>
        <cfoutput>listLen(#arguments.str#)</cfoutput>
        <cfset returnVar = trim(listLast(arguments.str))>
    <cfelseif listLen(arguments.str, " ") GT 1>
        <cfoutput>listLen(#arguments.str#, " ")</cfoutput>
        <cfset returnVar = trim(listLast(arguments.str, " "))>
    </cfif>

    <cfreturn returnVar>
</cffunction>

<cffunction name="getSubString" output="no" returnType="string" access="public" hint="Takes a string and returns the beginning of the string minus the last value">
    <cfargument name="str" required="yes" type="string">

    <cfset var last = getLast(arguments.str)>
    <cfset var lastLen = len(last) + 1>
    <cfset var thisLen = len(str) - lastLen>
    <cfset var returnVar = str>

    <cfif thisLen GTE 1>
        <cfset returnVar = trim(mid(str, 1, thisLen))>
    </cfif>

    <!--- remove trailing commas --->
    <cfif right(trim(returnVar), 1) IS ",">
        <cfset returnVar = mid(returnVar, 1, len(trim(returnVar)) - 1)>
    </cfif>

    <cfreturn returnVar>
</cffunction>

And just for fun, some code that was commented out of the second function:

<!---
<cfset var listDelim = ",">
<cfset var i = 0>
<cfset var returnVar = "">

<!--- if the string is longer than one value --->
<cfif len(last)>
    <cfif NOT findNoCase(arguments.str, ",")>
        <cfset listDelim = " ">
    </cfif>
    <cfloop from="1" to="#evaluate(listLen(arguments.str, listDelim) - 1)#" index="i">
        <cfset returnVar = "#returnVar# #listGetAt(arguments.str, i, listDelim)#">
    </cfloop>
    <cfset returnVar = trim(returnVar)>
<cfelse>
    <cfset returnVar = arguments.str>
</cfif>
--->

Next time I think I'm going to avoid parsing all my own text and just dumping it all into SOLR.


texts: Pattern matching deeply nested arguments in Elixir

texts:
I've recently started working with Elixir and am writing an app that queries various URLs and parses the response. I am having issues with my parse method, which is included below. The code works just fine, but I am concerned that I may have taken pattern matching too far. The method signature looks like spaghetti.

This is the code that sets the whole thing in process. I think it's fine, but include it to give you some background:

  def run(job) do
    HTTPStatusCheck.query(job)
    |> HTTPStatusCheck.parse
    |> update_db
    |> send_alerts
  end

The query method returns this "object":

%HTTPCheckResult{parsed: false, http_response: resp}

# resp is a %HTTPoison.Response{} "object"

Here is the parse method I need help with:

  def parse(%HTTPCheckResult{
    parsed: false, http_response: {:ok, %Response{status_code: c}}} = result)
    when c in @up do
      %{result | parsed: true, code: c, result: :up}
  end
  def parse(%HTTPCheckResult{
    parsed: false, http_response: {:ok, %Response{status_code: c}}} = result)
    when c in @down do
      %{result | parsed: true, code: c, result: :down}
  end
  def parse(%HTTPCheckResult{
    parsed: false, http_response: {:ok, %Response{status_code: c}}} = result) do
      %{result | parsed: true, result: :error, error: "http code #{c}"}
  end
  def parse(
    %HTTPCheckResult{parsed: false, http_response: {:error, %HTTPoison.Error{reason: reason}}} = result) do
      %{result | parsed: true, result: :error, error: reason}
  end
  def parse(%HTTPCheckResult{parsed: false} = result) do
    %{result | result: :error, error: "unknown"}
  end

My biggest objection is really the size of the parse method signatures, which are three lines in some cases. The important parts also seem pretty deeply nested in there.

How can the parse method can be improved?


texts: How can the following pandas script be made more efficient?

texts:
I have an excel sheet G0.xlsx which has 3 sheets in it Winter, Summer, Rest

Since the file has multiple contents, I am sharing the link of the file: Link to the file

I am trying to manipulate the data in all the 3 sheets in order to build one huge file for one entire year and the time must be of a 15min frequency (as it is in the file).

I also have the following conditions:

  Winter: 01.11 - 20.03

  Summer: 15.05 - 14.09

  Rest: 21.03 - 14.05 & 15.09 - 31.10

and based on these conditions, the final table must contain the values.

The below code works perfectly fine for me, but it takes a lot of time for generating the output. I want to know if this code can be made more time-efficient.

import pandas as pd
import holidays
import numpy as np
import functools

YEAR = 2020
seasons = ['Winter', 'Summer', 'Rest']

def get_holidays(year, country='DE', province=None):
    if province is not None:
        country_holidays = holidays.CountryHoliday(
            country, years=int(year), prov=province)
    else:
        country_holidays = holidays.CountryHoliday(
            country, years=int(year))
    country_holidays = list(country_holidays.keys())
    country_holidays = [d.strftime('%Y-%m-%d') for d in country_holidays]
    return country_holidays

def calculate_day(x):
    # get previous day for timestamp before hh:15
    if x.hour == 0 and x.minute < 15:
        return (x - pd.DateOffset(days=1)).day_name()
    return x.day_name()

def date_editing_df(df, holiday_list, year):
    year = str(year)
    weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']

    td = pd.to_timedelta(df['Time'].astype(str))
    df1 = df.assign(Time=td.mask(td == pd.Timedelta(0),
                                 td + pd.Timedelta(1, 'd')), a=1)
    df2 = pd.DataFrame({'dates': pd.date_range(
        '01.01.'+year, '31.12.'+year), 'a': 1})

    df = df2.merge(df1, how='outer').drop('a', axis=1)
    df['dates'] = df['dates'].add(
        df.pop('Time')).dt.strftime('%d.%m.%Y %H:%M')

    df['dates'] = pd.to_datetime(df['dates'], dayfirst=True)
    df['day'] = df['dates'].apply(calculate_day)

    df['day'].replace(weekdays, 'Werktag', inplace=True)
    df['day'].replace(
        {'Saturday': 'Samstag', 'Sunday': 'Sonntag'}, inplace=True)

    holiday_list = pd.to_datetime(holiday_list).tolist()
    comp = [(df['dates'] > h) & (df['dates'] <= h +
                                 pd.offsets.DateOffset(days=1))
            for h in holiday_list]
    # join all mask by logical or
    mask = np.logical_or.reduce(comp)

    df['day'] = np.where(mask, 'Sonntag', df['day'])
    df['Final'] = df.lookup(df.index, df['day'])
    df.drop(['Samstag', 'Sonntag', 'Werktag'], axis=1, inplace=True)
    return df

for season in seasons:
    df = pd.read_excel('G0.xlsx', header=0, sheet_name=seasons)

w_df = df['Winter']
s_df = df['Summer']
r_df = df['Rest']

h_list = get_holidays(YEAR)

w_df = date_editing_df(w_df, h_list, YEAR)
s_df = date_editing_df(s_df, h_list, YEAR)
r_df = date_editing_df(r_df, h_list, YEAR)

w_df.rename(columns={'Final': 'winter'}, inplace=True)
s_df.rename(columns={'Final': 'summer'}, inplace=True)
r_df.rename(columns={'Final': 'rest'}, inplace=True)

all_dfs = [w_df, s_df, r_df]
final_df = functools.reduce(
    lambda left, right: pd.merge(left, right, on='dates'), all_dfs)

d = pd.to_datetime(final_df['dates'].dt.strftime('%m-%d-' + str(YEAR)))
m1 = d.between(
    str(YEAR)+'-11-01', str(YEAR)+'-12-31') | d.between(str(YEAR)+'-01-01',
                                              str(YEAR)+'-03-20')
m2 = d.between(str(YEAR)+'-05-15', str(YEAR)+'-09-14')
final_df['Season'] = np.select(
    [m1, m2],
    ['winter', 'summer'],
    default='rest'
)
final_df['values'] = final_df.lookup(
    final_df.index,
    final_df['Season']
)
final_df = final_df[['dates', 'values']]


texts: Let's play Rock, Paper, Scissors with Ruby

texts:
I'm just looking for any tips to improve the code, particularly easier ways to change the main logic of the code so that it's shorter.

puts "Let's play rock, paper, scissors"

#scores
compScore = 0
humanScore = 0

until compScore == 5 || humanScore == 5

    puts "Select your weapon. Rock, paper or scissors?"

    human = gets.chomp.downcase
    comp = ["rock", "paper", "scissors"].sample

    #human wins
    if (human == "rock" && comp == "scissors") || (human == "scissors" && comp == "paper") || (human == "paper" && comp == "rock")
        p "You won!"
        humanScore += 1

    #draws
    elsif (human == "rock" && comp == "rock") || (human == "paper" && comp == "paper") || (human == "scissors" && comp == "scissors")
        p "Draw! No point awarded"

    #computer wins
    else compScore += 1
        p "You lose."
    end

    #Resulted Scores
    p "Human Score: #{humanScore}"
    p "Computer Score: #{compScore}"

    #Resulted Choices
    p "Human chose: #{human}"
    p "Computer chose: #{comp}"
end
    #Tell who wins
    p humanScore > compScore ? ("YOU WIN!") : ("COMPUTER WINS!.")


texts:
It is just a simple piece of C code that generates random lenght random HEX srings. Any ideas how this code can be improved?

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

#define MAX_SIZE 256

int main() {
    time_t t;
    srand((unsigned) time(&t));

    const char* digits = "0123456789ABCDEF";

    unsigned char str_len = rand() % MAX_SIZE;

    char* str = malloc((str_len + 1) * sizeof(char));
    if (str == NULL) {
        fprintf(stderr, "malloc failed\n");
        return -1;
    }

    char* init_ptr = str;
    char tmp_char;

    for (int i = 0; i < str_len; i++) {
        if (i == 0) {
            do {
                tmp_char = *(digits + (rand() % 16));
            } while (tmp_char == '0');
        }
        *str = tmp_char;
        tmp_char = *(digits + (rand() % 16));
        str++;
    }

    *str = '\0';

    printf("%s", init_ptr);
    free(init_ptr);

    return 0;
}


texts: Returning all possible player moves on a board

texts:
Recently I started to learn Haskell. I did this by making exercises on the Internet. The problem of making these exercises is that I never know if I solved it the correct way. I currently wrote a function which I think looks really ugly, but I don't know how to improve it. I hope that someone could give me some tips to improve it.

In this exercice I need to make a tic-tac-toe-game. Wikipedia

The question of the function I wrote is as follows:

  Write a function moves :: Player -> Board -> [Board] that, given the
  current player and the current state of the board, returns all
  possible moves that player can make expressed as a list of resulting
  boards. (For now, you should continue making moves, even if one of the
  players has already won.)

I wrote the following code:

data Field = X | O | B
    deriving (Eq, Ord)

instance Show Field where
    show X = "X|" :: String
    show O = "O|" :: String
    show B = " |" :: String

symbol :: Player -> Field
symbol P1 = X
symbol P2 = O

type Row   = (Field, Field, Field)
type Board = (Row, Row, Row)

I only want to improve this function: (Because the above code is part of bigger code)

moves :: Player -> Board -> [Board]
moves p ((a,b,c),(d,e,f), (g,h,i)) = (moves' a (((symbol p),b,c), (d,e,f), (g,h,i))) ++
                                     (moves' b ((a,(symbol p),c), (d,e,f), (g,h,i))) ++
                                     (moves' c ((a,b,(symbol p)), (d,e,f), (g,h,i))) ++
                                     (moves' d ((a,b,c), ((symbol p),e,f), (g,h,i))) ++
                                     (moves' e ((a,b,c), (d,(symbol p),f), (g,h,i))) ++
                                     (moves' f ((a,b,c), (d,e,(symbol p)), (g,h,i))) ++
                                     (moves' g ((a,b,c), (d,e,f), ((symbol p),h,i))) ++
                                     (moves' h ((a,b,c), (d,e,f), (g,(symbol p),i))) ++
                                     (moves' i ((a,b,c), (d,e,f), (g,h,(symbol p))))

moves' :: Field -> Board -> [Board]
moves' c m = if c == B then [m] else []

Is there a way to improve my code?


texts: Codility: An activity selection problem about scheduling two enemies to watch movies at a festival

texts:
I don't remember the exact wording of the question, but it is clearly an activity selection problem, which is

  [...] notable in that using a greedy algorithm to find a solution will always result in an optimal solution.

I put a rough description of the problem in the docstring, and present it together with my solution:

def solution(movies, K, L):
    """
    Given two integers K and L, and a list movies where the value at the ith index
    represents the number of movies showing on the (i + 1)th day at the festival, returns
    the maximum number of movies that can be watched in two non-overlapping periods of K and
    L days, or -1 if no two such periods exist.
    """
    kl_days = [
        sum(movies[k_start:k_start + K] + movies[l_start:l_start + L])
        for k_start in range(len(movies) - K)
        for l_start in range(k_start + K, len(movies) - L + 1)
    ]
    lk_days = [
        sum(movies[k_start:k_start + K] + movies[l_start:l_start + L])
        for l_start in range(len(movies) - L)
        for k_start in range(l_start + L, len(movies) - K + 1)
    ]
    days = [-1] + kl_days + lk_days
    return max(days)

Is there a more elegant way to solve this?

P.S. The function name is fixed for grading purposes.


texts: Displaying data as binary in C with bitmasks

texts:
I wrote a program to display data in memory as binary and it worked. (It gave me immense sense of satisfaction and joy to see this work. I guess this happens to newbies who are just testing the waters). I know this isn't some terribly smart code, and I'm sure there must be surely lots of better ways to do this. Any advice and help would be great. If I've done something wrong in this program or if there is any bad programming practice, I would be happy to be corrected.

#include<stdio.h>

int main()
{

  char mychar = 'a';
  int count = 0;
  int bitmask = 128;
  while (count < 8){

    if (mychar &  bitmask){
      printf("1");
    }
    else{
       printf("0");
    }

    bitmask = bitmask / 2;
    count = count +1;
  }

return 0;

}


texts:
I'm writing my first somewhat production ready (or not) Go program and could do with some feedback from someone more experienced with go.

The code reads a list of URLs from a JSON file and then makes a GET request to each URL in a loop to check that they are returning a 200 OK response. I have attempted to do this concurrently using go routines but I'm concerned about my synchronization step.

monitor.go

package main

import (
    "encoding/json"
    "fmt"
    "github.com/bradfitz/gomemcache/memcache"
    "os"
    "time"
)

// Configuration encapsulates the result of reading the JSON configuration
// file.
type Configuration struct {
    URLs      []string
    Memcached string
}

// loadConfig loads a configuration file in JSON format and returns a
// Configuration instance.
func loadConfig(path string) (Configuration, error) {
    file, _ := os.Open(path)
    defer file.Close()

    decoder := json.NewDecoder(file)
    configuration := Configuration{}
    err := decoder.Decode(&configuration)

    return configuration, err
}

func main() {
    type Result struct {
        url    string
        status Status
    }

    rc := make(chan Result)

    configuration, err := loadConfig("config.json")

    if err != nil {
        fmt.Println("Error :", err)
        return
    }

    sites := make(map[string]*Site, len(configuration.URLs))

    for _, url := range configuration.URLs {
        sites[url] = &Site{url, UNCHECKED}
    }

    mc := memcache.New(configuration.Memcached)

    sites_output := make(map[string]bool)

    for {
        for _, site := range sites {
            go func(site *Site, rc chan Result) {
                status, _ := site.Status()
                rc <- Result{site.url, status}
            }(site, rc)
        }

        for i := 0; i < len(sites); i++ {
            res := <-rc
            site := sites[res.url]
            if site.last_status != res.status {
                sites[res.url].last_status = res.status
            }
        }

        for k, v := range sites {
            sites_output[k] = v.last_status == 2
        }

        site_json, err := json.Marshal(sites_output)

        if err != nil {
            panic(err)
        }
        mc.Set(&memcache.Item{
            Key:   "mission_control.sites",
            Value: site_json,
        })
        time.Sleep(time.Second * 5)
    }
}

site.go

package main

import (
    "net/http"
)

type Status int

const (
    UNCHECKED Status = iota
    DOWN
    UP
)

// The Site struct encapsulates the details about the site being monitored.
type Site struct {
    url         string
    last_status Status
}

// Site.Status makes a GET request to a given URL and checks whether or not the
// resulting status code is 200.
func (s Site) Status() (Status, error) {
    resp, err := http.Get(s.url)
    status := s.last_status

    if (err == nil) && (resp.StatusCode == 200) {
        status = UP
    } else {
        status = DOWN
    }

    return status, err
}


texts: Check if strings from a list in a text and return first longest match

texts:
I'm trying to design an application that binds a phrase or word to some item, for example image, and saves phrase-item pair in the database. Then it receives a text, and if it contains binded substring, corresponding item should be returned.
It should return only one item (first match), and longest substrings should take precedence.

I wrote a function, that returns expected values:

from operator import itemgetter

def get_item(text, bindings):
    text = text.lower()
    matches = []
    for phrase, item in bindings:
        phrase = phrase.lower()
        index = text.find(phrase)
        if index != -1:
            matches.append((phrase, item, index))
    if matches:
        matches.sort(key=lambda x: len(x[0]), reverse=True)
        matches.sort(key=itemgetter(2))
        item_id = matches[0][1]
    else:
        item_id = None
    return item_id

Example:

bindings = [
('i', 'item1'), ('like', 'item2'), ('i like', 'item3'), ('turtles', 'item4'),
]
text = 'I like turtles!'
print(get_item(text, bindings)) # should return item3

Is there cleaner ways to complete such task, or faster, perhaps?


texts: Usage of TPL vs Parallel.ForEach() on file processing

texts:
i've been working on an implementation of a my own from scratch set of library Astron and I wanted to get my TPL usage reviewed because i'm not confident with this technology :/

My app is currently unpacking .d2p files, which is a custom file format from a french game called Dofus, it's simply an archive of others inflated archives of another custom file format .dlm. Here is the current output of my app :

The progress bars came from here.

So everything seems to works as expected, files are processes concurrently, 308mo of .dlm files are parsed deflated in 10sec, that is exactly what i wants it to do but i may have misused the TPL. The full project can be found at this address, but the portion of code I want to get reviewed is from src/Astron.Unpacker/Managers/D2PManager.cs :

public class D2PManager : BaseFileManager
{
    private readonly ILogger _logger;
    private readonly string _dlmFilesFolder;
    public D2PManager(IContainer container) : base(container)
    {
        _logger = ServiceLocator.Logger;
        _dlmFilesFolder = container.GetInstance<Settings>().DlmOutputFolder;
    }

    public async Task UnpackAll(string[] filesPath)
    {
        _logger.Log<D2PManager>(LogLevel.Info, $"Attempting to unpack {filesPath.Length} d2p files...");

        var tasks = new List<Task>(filesPath.Length);
        tasks.AddRange(filesPath.Select(d2PFilePath => UnpackD2PFile(d2PFilePath)));

        await Task.WhenAll(tasks).ConfigureAwait(false);
    }

    public async Task UnpackD2PFile(string path)
    {
        var d2PFile      = new FileAccessor(path);
        var metaUnpacker = new D2PFileMetadataUnpacker(_binaryFactory, _serDes);
        metaUnpacker.Unpack(d2PFile);

        var archiveUnpacker = new DlmArchivesUnpacker(_binaryFactory, _serDes, metaUnpacker.Value);
        archiveUnpacker.Unpack(d2PFile);

        var progressCount = 1;
        var progressBar   = new ProgressBar(PbStyle.SingleLine, archiveUnpacker.Values.Count);
        progressBar.Refresh(0, Path.GetFileName(d2PFile.FullPath));
        await Task.Delay(10); // doesn't print all either way
        foreach (var archive in archiveUnpacker.Values)
        {
            var filePath      = (_dlmFilesFolder + archive.RelativePath).Replace('/', '\\');
            var fileDirectory = Path.GetDirectoryName(filePath);
            using var decompressedData = new MemoryStream();
            using var deflatedStream = new DeflateStream(new MemoryStream(archive.CompressedData),
                CompressionMode.Decompress);

            await deflatedStream.CopyToAsync(decompressedData);
            if (!Directory.Exists(fileDirectory)) Directory.CreateDirectory(fileDirectory);

            File.WriteAllBytes(filePath, decompressedData.GetBuffer());
            progressBar.Refresh(progressCount, filePath);
            progressCount++;
        }
    }
}

Here are my questions :

If I don't add the Task.Delay() right after the processbar initialization, the files seems to be processed synchronously (the progress bar show up when the last completed), why does it happen ?
Is it right to use .ConfigureAwait(false) on Task.WhenAll() ?
Am I starting every tasks the right way ? Shouldn't I use Task.Run() instead with Task.WaitAll() ?


texts: Modal dialog box window replaces the original URl in testcafe

texts:
I am unable to figure out the issue which am facing. I opened a modal-dialog box(it should be pop up window-- which has some info form filled and save it). which I had already solved it -- but here action URL is confusing the testcafe.

When I run it, the modal dialog opened and replaced(in 2s) as main page URL with black and white window and executed (with out saving- because div element different).
how can open my modal dialog as popup window and fill the form and save it!
Here is my sample code:
export async function test() {
   // open urls by click functions here
//required page was opened and searching the user exists or not
    const searchUserExists = 'user1'
    await t.typeText('[type="search"]', searchUserExists);

    const firstNameUser = "UserFirstName"
    const lastNameUser = "UserLastName"
    const emailUser = "moderator@moderator.de"
    await t.debug().click(' #ent_administration_user_new, .modal-body,
    [action="null"]')  // worked

**here problem  arises**

    await t.typeText(Selector("#user_firstname"), firstNameUser)
        .typeText(Selector("#user_lastname"), lastNameUser)
        .typeText(Selector("#user_username"), searchUserExists)
        .typeText(Selector("#user_email"), emailUser)
        .click(".save-item");
}


texts: splitting and merging Ranges array in javascript

texts:
I have an array of ranges as you can see in the snippet. when user select certain number from dropdown I want to remove that number from the range and return new ranges,

Everything is working as per my expectation but I think, I have over coded and used too many if else statements in my code. I was wondering if there is any better way to do it?

If yes please let me know, if Javascript has any methods to make this simple and reduce the amount of code.

var ranges = [
  {start: 1, end: 100},
  {start: 150, end: 300},
  {start: 400, end: 500},
  {start: 550, end: 650},
];

function onSelect(event) {
  let newRange = [];
  let HMID = parseInt(document.getElementById("mySelect").value);

  for (let range of ranges) {

      if ((HMID > range.start) && (HMID < range.end)) {

          newRange.push({start: range.start, end: (HMID - 1)});
          newRange.push({start: (HMID + 1), end: range.end});
      } else if (HMID === range.start) {

          newRange.push({start: (range.start + 1), end: range.end});
      } else if (HMID === range.end) {

          newRange.push({start: range.start, end: (range.end - 1)});
      } else {

          newRange.push(range);
      }
  }
  console.log(JSON.stringify(newRange));

}

function onSelectAdd() {

  let newRange = [];
  let HMID = parseInt(document.getElementById("mySelectAdd").value);

  for (let i = 0; i < (ranges.length); i++) {

  let start, end;

  if (HMID == (ranges[i].start -1)) {
      start = HMID;
      end = ranges[i].end;

      newRange.push({start: start, end: end});
  } else if (HMID == (ranges[i].end + 1)) {
      start = ranges[i].start;

      if (ranges.length === (i + 1)) {
          end = HMID;
      } else {

          if (HMID == (ranges[i+1].start - 1)) {
              end = ranges[i+1].end;
              i++;

          } else {
              end = ranges[i].end;
          }
      }

      newRange.push({start: start, end: end});

  } else {
      newRange.push({start: ranges[i].start, end: ranges[i].end});
  }

  }

  console.log(JSON.stringify(newRange));
}

Remove item

<select id="mySelect" onchange="onSelect()">
  <option value="1">1</option>
  <option value="150">150</option>
  <option value="450">450</option>
  <option value="650">650</option>
</select>

Add removed item

<select id="mySelectAdd" onchange="onSelectAdd()">
  <option value="1">1</option>
  <option value="150">150</option>
  <option value="450">450</option>
  <option value="650">650</option>
</select>

EDIT:
I am looking only for logical and functional code review. Please don't comment on syntax and variable names. Thanks.


texts: Various type Tuple flatten tool implementation

texts:
For some reason, I am trying to implement a various type tuple flatten tool with the following requirements:

The nested Tuple object Tuple<Tuple<...>> can be unwrapped into Tuple<...>.

There are various types in the nested Tuple object.

The return type is set on Tuple<...> (not generic object).

I have checked how to flatten nested tuples in c#?. JuanR's answer is good but the same type is specified in Tuple. As the result, the following TupleFlattener has been implemented.
The experimental implementation
public static class TupleFlattener
{
    public static Tuple<T1> Perform<T1>(in Tuple<Tuple<T1>> input)
    {
        if (input is null) throw new ArgumentNullException(nameof(input));
        return new Tuple<T1>(input.Item1.Item1);
    }

    public static Tuple<T1, T2> Perform<T1, T2>(in Tuple<Tuple<T1, T2>> input)
    {
        if (input is null) throw new ArgumentNullException(nameof(input));
        return new Tuple<T1, T2>(input.Item1.Item1, input.Item1.Item2);
    }

    public static Tuple<T1, T2, T3> Perform<T1, T2, T3>(in Tuple<Tuple<T1, T2, T3>> input)
    {
        if (input is null) throw new ArgumentNullException(nameof(input));
        return new Tuple<T1, T2, T3>(input.Item1.Item1, input.Item1.Item2, input.Item1.Item3);
    }

    public static Tuple<T1, T2, T3, T4> Perform<T1, T2, T3, T4>(in Tuple<Tuple<T1, T2, T3, T4>> input)
    {
        if (input is null) throw new ArgumentNullException(nameof(input));
        return new Tuple<T1, T2, T3, T4>(input.Item1.Item1, input.Item1.Item2, input.Item1.Item3, input.Item1.Item4);
    }

    public static Tuple<T1, T2, T3, T4, T5> Perform<T1, T2, T3, T4, T5>(in Tuple<Tuple<T1, T2, T3, T4, T5>> input)
    {
        if (input is null) throw new ArgumentNullException(nameof(input));
        return new Tuple<T1, T2, T3, T4, T5>(input.Item1.Item1, input.Item1.Item2, input.Item1.Item3, input.Item1.Item4, input.Item1.Item5);
    }

    public static Tuple<T1, T2, T3, T4, T5, T6> Perform<T1, T2, T3, T4, T5, T6>(in Tuple<Tuple<T1, T2, T3, T4, T5, T6>> input)
    {
        if (input is null) throw new ArgumentNullException(nameof(input));
        return new Tuple<T1, T2, T3, T4, T5, T6>(input.Item1.Item1, input.Item1.Item2, input.Item1.Item3, input.Item1.Item4, input.Item1.Item5, input.Item1.Item6);
    }

    public static Tuple<T1, T2, T3, T4, T5, T6, T7> Perform<T1, T2, T3, T4, T5, T6, T7>(in Tuple<Tuple<T1, T2, T3, T4, T5, T6, T7>> input)
    {
        if (input is null) throw new ArgumentNullException(nameof(input));
        return new Tuple<T1, T2, T3, T4, T5, T6, T7>(input.Item1.Item1, input.Item1.Item2, input.Item1.Item3, input.Item1.Item4, input.Item1.Item5, input.Item1.Item6, input.Item1.Item7);
    }
}

Test cases
Tuple<Tuple<int, char, double>> tupleInput =
    new Tuple<Tuple<int, char, double>>(new Tuple<int, char, double>(10, 'a', 5.5));
var output = TupleFlattener.Perform(tupleInput);
Console.WriteLine($"Output type: {output.GetType()}");
Console.WriteLine($"Item1: {output.Item1}");
Console.WriteLine($"Item2: {output.Item2}");
Console.WriteLine($"Item3: {output.Item3}");

The output of the above test:
Output type: System.Tuple`3[System.Int32,System.Char,System.Double]
Item1: 10
Item2: a
Item3: 5.5

If there is any possible improvement, please let me know.


texts:
I just began learning programming and I'm learning Objective-C. I'm taking an online course and in that course we were doing a magic crystal ball app. Then I decided to use what I learned and make my own app.

Viewcontroller .h

#import <UIKit/UIKit.h>

@class MBFQuotes;

@interface MBFViewController : UIViewController

@property (strong, nonatomic) MBFQuotes *quotes;

@property (strong, nonatomic) IBOutlet UILabel *quoteLabel;

@property (strong, nonatomic) IBOutlet UIButton *generalButton;
@property (strong, nonatomic) IBOutlet UIButton *lifeButton;
@property (strong, nonatomic) IBOutlet UIButton *politicsButton;
@property (strong, nonatomic) IBOutlet UIButton *smartButton;

//Action

- (IBAction)generalButton:(id)sender;
- (IBAction)lifeButton:(id)sender;
- (IBAction)politicsButton:(id)sender;
- (IBAction)smartButton:(id)sender;

@end

Viewcontroller .m

#import "MBFViewController.h"
#import "MBFQuotes.h"

@interface MBFViewController ()

@end

@implementation MBFViewController

- (void)viewDidLoad
{
[super viewDidLoad];
self.quotes = [[MBFQuotes alloc] init];
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (IBAction)generalButton:(id)sender {
self.quoteLabel.text = [_quotes randomGeneral];
self.quoteLabel.backgroundColor = [UIColor redColor];

}

- (IBAction)lifeButton:(id)sender {
self.quoteLabel.text = [_quotes randomLife];
self.quoteLabel.backgroundColor = [UIColor blueColor];

}

- (IBAction)politicsButton:(id)sender {
self.quoteLabel.text = [_quotes randomPolitics];
self.quoteLabel.backgroundColor = [UIColor blackColor];

}

- (IBAction)smartButton:(id)sender {
self.quoteLabel.text = [_quotes randomSmart];
self.quoteLabel.backgroundColor = [UIColor orangeColor];

}
@end

Class Quotes .h

#import <Foundation/Foundation.h>

@interface MBFQuotes : NSObject

-(NSString *)randomGeneral;
-(NSString *) randomLife;
-(NSString *) randomPolitics;
-(NSString *) randomSmart;
@end

Class Quotes.m

#import "MBFQuotes.h"

@implementation MBFQuotes

-(NSString *) randomGeneral {

 NSArray *generalQuotes = @[@"g1", @"g2", @"g3", @"g4"];

int randomGeneral = arc4random_uniform([generalQuotes count]);

return [generalQuotes objectAtIndex:randomGeneral];
}

-(NSString *) randomLife {

NSArray *lifeQuotes = @[@"l1", @"l2"];

int randomLife = arc4random_uniform([lifeQuotes count]);

 return [lifeQuotes objectAtIndex:randomLife];
}

-(NSString *) randomPolitics {

NSArray *politicsQuotes = @[@"p1", @"p2"];

int randomPolitics = arc4random_uniform([politicsQuotes count]);

return [politicsQuotes objectAtIndex:randomPolitics];
}

-(NSString *) randomSmart {

 NSArray *smartQuotes = @[@"s1", @"s2"];

int randomSmart = arc4random_uniform([smartQuotes count]);

return [smartQuotes objectAtIndex:randomSmart];
 }

 @end

The app works perfectly, but I just want to see if there is better or easier way to do it, or is there there a better design.


texts: Remove duplicates from csv based on conditions

texts:
The task is basically this:

I am given the following csv file with lots of duplicate email addresses

Display Name,First Name,Last Name,Phone Number,Email Address,Login Date,Registration Date
John,John,Doe,99999999,johndoe@yahoo.com,4/20/2015 21:56,4/20/2015 21:56
John,John,DOE,99999999,johndoe@yahoo.com,3/31/2015 14:05,3/31/2015 14:05

I need to remove duplicates based on email address with the following conditions:

The row with the latest login date must be selected.
The oldest registration date among the rows must be used.

I used Python/pandas to do this.

How do I optimize the for loop in this pandas script using groupby? I tried hard but I'm still banging my head against it.

import pandas as pd

df = pd.read_csv('pra.csv')

# first sort the data by Login Date since we always need the latest Login date first
# we're making a copy so as to keep the original data intact, while still being able to sort by datetime
df['Login Date Copy'] = pd.to_datetime(df['Login Date'])
df['Registration Date Copy'] = pd.to_datetime(df['Registration Date'])

# this way latest login date appears first for each duplicate pair
df = df.sort_values(by='Login Date Copy', ascending=False)

output_df = pd.DataFrame()

# get rows for each email address and replace registration date with the oldest one
# this can probably be optimized using groupby
for email in df['Email Address'].unique():
    subdf = df.loc[df['Email Address'] == email]
    oldest_date = subdf['Registration Date Copy'].min()

    # get corresponding registration date for a particular registration date copy
    oldest_reg_date = df[df['Registration Date Copy'] == oldest_date]['Registration Date'].values[0]

    subdf['Registration Date'] = oldest_reg_date
    output_df = output_df.append(subdf)

# drop working columns
output_df.drop(['Login Date Copy', 'Registration Date Copy'], axis=1, inplace=True)

# finally, get only the first of the duplicates and output the result
output_df = output_df.drop_duplicates(subset='Email Address', keep='first')
output_df.to_csv('~/output.csv', index=False)


texts:
I am very new to Python and I am trying to learn through personnal projects and today I needed to collect a lot of baksetball player names and decided this was a good time to learn and practice.
The script is able to pull out all of the players names, height, nationality and DOB but I need to enter the link to the pages before launching it.
Next step will be either to build a graphic interface where I can copy/past the links or asking in the console wether I want to enter a new team.
I am looking forward to hearing from you since this is maybe my first personnal project :)
import os
import requests
import pandas as pd
import xlsxwriter
from bs4 import BeautifulSoup

def reverse(name):
    to_reverse = name
    return ' '.join(reversed(name.split(' ')))

def conversion_df(url):
    requete = requests.get(url)
    page = requete.content
    soup = BeautifulSoup(page, features="lxml")

    header = [th.getText() for th in soup.findAll("th")]    # Why do I have to put th. before getText for it to work | Why do we use th as an updator
    header = header[1:5] # Here we exclude the first (O) entry and we display the entries situated before 5

    row = soup.findAll("tr")[1:]
    stats = [[td.getText().strip() for td in row[i]] for i in range(len(row))]
    for j in stats:
        del j[0]
        del j[4]
    #print(stats)

    for i in range(len(stats)):
        stats[i][0] = reverse(stats[i][0])

    table = pd.DataFrame(data = stats, columns = header)
    return table

nanterre = conversion_df("https://www.lnb.fr/fr/espa/equipe/espoirs-nanterre-61344.html")
monaco = conversion_df("https://www.lnb.fr/fr/espa/equipe/espoirs-monaco-61343.html")
boulazac = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-boulazac-61331.html")
boulogne = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-boulogne-levallois-61332.html")
bourg = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-bourg-en-bresse-61333.html")
chalon = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-chalon-saone-61334.html")
cholet = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-cholet-61336.html")
chalon_reims = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-chalons-reims-61335.html")
dijon = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-dijon-61337.html")
gravelines = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-gravelines-dunkerque-61338.html")
le_mans = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-le-mans-61339.html")
le_portel = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-le-portel-61340.html")
orleans = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-orleans-61345.html")
pau = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-pau-lacq-orthez-61346.html")
roanne = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-roanne-61347.html")
strasbourg = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-strasbourg-61348.html")
limoges = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-limoges-61341.html")
lyon = conversion_df("https://www.lnb.fr/fr/espoirs/equipe/espoirs-lyon-villeurbanne-61342.html")

clubs = [boulazac,boulogne,bourg,chalon,cholet,chalon_reims,dijon,gravelines,le_mans,le_portel,limoges,lyon,monaco,nanterre,orleans,pau,roanne,strasbourg]

# Creating Excel Writer Object from Pandas
writer = pd.ExcelWriter('liste_espoir.xlsx',engine='xlsxwriter')
workbook=writer.book
worksheet=workbook.add_worksheet('Espoirs')
writer.sheets['Espoirs'] = worksheet

row_count = 0
i = 0

for i in range(len(clubs)):
    clubs[i].to_excel(writer,sheet_name='Espoirs',startrow=row_count , startcol=0)
    row_count += 20

writer.save()


texts: Finding all possible pairs of square numbers in an array

texts:
I am writing a program that allows me to find all possible pairs of square numbers including duplicates. We can also assume the array elements to be of positive integers only.
e.g an array of {5,25,3,25,4,2,25} will return [5,25],[5,25],[2,4],[5,25]
since 25 is square of 5.

Currently, I am using a nested for loop to find the squares. I'm just wondering if there is a better way to do this?

import java.lang.Math.*;

public static void main(String args[])
{
    int arr[] = {5,25,3,25,4,2,25};
    String s = "";

    for(int i =0; i < arr.length;i++)
    {

        for(int j = 0;j < arr.length;j++)
        {
            if(Math.sqrt(arr[i]) == arr[j])
            {
                s += arr[j] + "," + arr[i] + " ";
            }
        }

    }

    System.out.println(s);

}


texts: (Brilliant.org) Arrays Intermediate 3: Contiguous Knapsack

texts:
Problem

Given an array and a number \$t\$, write a function that determines if there exists a contiguous sub-array whose sum is \$t\$.

Source (Note that the URL may not link to the exact problem as it's from a quiz site, and questions seem to be randomly generated).
I was able to come up with a \$O(n^2)\$ solution, and further thinking hasn't improved upon it:
def substring_sum(lst, target):
    sums = []
    for val in lst:
        if val == target:
            return True
        for idx, _ in enumerate(sums):
            sums[idx] += val
            if sums[idx] == target:
                return True
        sums.append(val)
    return False


texts:
How could I make my code follow the DRY principle?
I feel like they are better ways to do things in my code. So any feedback will help me!

js fiddle: https://jsfiddle.net/fr6ut238/

    /*---------------------------
        Variables
    ---------------------------*/
    const $containerGrid = $(".containerGrid");
    let boxSide = 16;

    const $gridLength = $("#gridLength");
    const $gradientButton = $("#gradient");
    const $randomButton = $("#random");
    const $resetButton = $("#reset");

    /*-- -------------------------
        Buttons & input
    ---------------------------*/
    $gridLength.on("input", gridLength);
    $gradientButton.on("click", incrementOpacity);
    $randomButton.on("click", getRandomColors);
    $resetButton.on("click", () => {
        reset(boxSide);
    });

    /*---------------------------
    Corresponding to Event listeners
    ---------------------------*/
    function gridLength() {
        if (event.target.value !== 16) {
            reset(event.target.value);
        }
    }

    function incrementOpacity() {
        $(".cell").off("mouseenter");
        $(".cell").mouseenter((event) => {
            let opacity = parseFloat(event.target.style.opacity);
            if (opacity <= 0.9) {
                $(event.target).css({
                                    "opacity": `${opacity + 0.1}`,
                                    "backgroundColor": "#f5f5f5"});
            }
        });
    }

    function setRandomColors() {
        return Math.floor((Math.random() * 256));
    }

    function getRandomColors() {
        $(".cell").off("mouseenter");
        $(".cell").mouseenter((event) => {
            $(event.target).css({
                                "backgroundColor": `rgb(${setRandomColors()}, ${setRandomColors()}, ${setRandomColors()})`,
                                "opacity": "1" })
        });
    }

    function reset(length) {
        boxSide = length;
        main();
        $(".cell").css({
                    "opacity": "0.1",
                    "border": "0.5px solid black",
                    "backgroundColor": "transparent"});
    }

    /*-- -------------------------
        Creates the Grid
    ------------------------------*/
    function main() {
        $($containerGrid).empty();
        for (let row = 0; row < boxSide; row++) {
            for (let column = 0; column < boxSide; column++) {
                createCell();
            }
        }
        $(".cell").css("height", `${(300 / boxSide) - 1}px`);
        $(".cell").css("width", `${(300 / boxSide) - 1}px`);
    }

    function createCell() {
        const $cell = $('

');
        $cell.css("opacity", "0.1");
        $containerGrid.append($cell);
    }

    main();


texts: Chess AI Using Minimax and Alpha-Beta Pruning

texts:
I am working on a Chess AI using chess.js, and currently, it can run 3 layers in under 10 seconds, but 4 or more takes minutes. How can I optimize my current code to be able to run 4 or 5 layers, or do I have to implement a different algorithm.

Here is my code:

function startMinimax(depth, game, isMaximisingPlayer) {
  var moves = game.moves({ verbose: true });
  var bestEval = -9999;
  var bestMove;
  for (var i = 0; i < moves.length; i++) {
    var move = moves[i];
    game.move(move);
    var value = minimax(depth - 1, game, -10000, 10000, !isMaximisingPlayer);
    game.undo();
    if (value >= bestEval) {
      bestEval = value;
      bestMove = move;
    }
  }
  return bestMove;
}

function minimax(depth, game, alpha, beta, isMaximisingPlayer) {
  if (depth === 0) {
    return -evaluateBoard(game);
  }
  var moves = game.moves({ verbose: true });

  if (isMaximisingPlayer) {
    var bestEval = -9999;
    for (var i = 0; i < moves.length; i++) {
      game.move(moves[i]);
      bestEval = Math.max(bestEval, minimax(depth - 1, game, alpha, beta, !isMaximisingPlayer));
      game.undo();
      alpha = Math.max(alpha, bestEval);
      if (beta <= alpha) {
        return bestEval;
      }
    }
    return bestEval;
  } else {
    var bestEval = 9999;
    for (var i = 0; i < moves.length; i++) {
      game.move(moves[i]);
      bestEval = Math.min(bestEval, minimax(depth - 1, game, alpha, beta, !isMaximisingPlayer));
      game.undo();
      beta = Math.min(beta, bestEval);
      if (beta <= alpha) {
        return bestEval;
      }
    }
    return bestEval;
  }
}


texts:
The program asks the user to input 10 integers, and then prints the largest odd number that was entered. If no odd number was entered, it prints a message to that effect.

q = int(raw_input("Please enter an integer:"))
r = int(raw_input("Please enter another integer:"))
s = int(raw_input("Please enter another integer:"))
t = int(raw_input("Please enter another integer:"))
u = int(raw_input("Please enter another integer:"))
v = int(raw_input("Please enter another integer:"))
w = int(raw_input("Please enter another integer:"))
x = int(raw_input("Please enter another integer:"))
y = int(raw_input("Please enter another integer:"))
z = int(raw_input("Please enter one last integer:"))

odd = []
if q%2 != 0:
    odd += [q]
if r%2 != 0:
    odd += [r]
if s%2 != 0:
    odd += [s]
if t%2 != 0:
    odd += [t]
if u%2 != 0:
    odd += [u]
if v%2 != 0:
    odd += [v]
if w%2 != 0:
    odd += [w]
if x%2 != 0:
    odd += [x]
if y%2 != 0:
    odd += [y]
if z%2 != 0:
    odd += [z]
if q%2 == 0 and r%2 == 0 and s%2 == 0 and t%2 == 0 and u%2 == 0 and v%2 == 0 and w%2 == 0 and x%2 == 0 and y%2 == 0 and z%2 == 0:
    print "None of the values given are odd."
else:
    print max(odd), "is the largest odd number."


texts: Get locations that are x km away using Latitude/Longitude

texts:
So I have a solution for this which uses a for loop and calculates distance between the main point and other points. I found the code for distance between two points online, changed it to my needs and wrote the rest of the code. While this code works pretty well, I'm just curious if there's a better and more efficient way of doing this. This fits really well with my current code as it's just a small scale project. But I always like looking for stuff I can optimise and improve.
function findDistanceInKm(location1, location2) {
    const lat1 = location1.lat;
    const lon1 = location1.lon;
    const lat2 = location2.lat;
    const lon2 = location2.lon;
    const earthRadius = 6371;
    const dLat = convertDegToRad(lat2 - lat1);
    const dLon = convertDegToRad(lon2 - lon1);
    const squarehalfChordLength =
      Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.cos(convertDegToRad(lat1)) * Math.cos(convertDegToRad(lat2)) *
      Math.sin(dLon / 2) * Math.sin(dLon / 2);

    const angularDistance = 2 * Math.atan2(Math.sqrt(squarehalfChordLength), Math.sqrt(1 - squarehalfChordLength));
    const distance = earthRadius * angularDistance;
    return distance;
}

function convertDegToRad(deg) {
    return deg * (Math.PI/180)
}

let nearLocations = [];
let newLocation = {
    lat: 65.33714,
    lon: -82.11508
}

let locationList = [
    {
        lat: 65.33714,
        lon: -82.11503
    },
    {
        lat: -1.38370,
        lon: 10.32156
    },
    {
        lat: -69.98601,
        lon: 18.80178
    },
    {
        lat: -29.37968,
        lon: -156.32350
    },
]

for(let i =0; i < locationList.length; i++){
    let distance = findDistanceInKm(newLocation, locationList[i]);
    console.log(distance)
    if(distance < 1){
        nearLocations.push(locationList[i])
    }
}


texts:
I am writing a fully functional single player Connect 4 game. I am working on the second player and the while loop that tells the player who won.

GUI

package lab7;

import java.awt.GridLayout;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class GUIClass implements Runnable {

    @Override
    public void run() {

        JFrame f = new JFrame("CSE 115 Connect 4");
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        GridLayout myGrid = new GridLayout(7, 6);
        JPanel panel;
        panel = new JPanel();
        panel.setLayout(myGrid);
        f.setLayout(myGrid);

        f.pack();

        ArrayList<JButton> col_button = new ArrayList<JButton>();
        for (Integer i = 1; i <= 7; i++)
        {
            JButton b = new JButton("Col " + i.toString());
            col_button.add(b);
            f.add(b);
        }

        ArrayList<ArrayList<JLabel>> col_list = new ArrayList<ArrayList<JLabel>>();
        for (int i = 0; i < 7; i++)
        {
            col_list.add(new ArrayList<JLabel>());
        }

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

            JLabel label = new JLabel(new ImageIcon("images/blank.png"));
            //System.out.println(label.getIcon().toString())
            col_list.get(i % 7).add(label);
            f.add(label);
        }
        GameClass gc = new GameClass(col_list);

        for (int i = 0; i < 7; i++)
        {
            col_button.get(i).addActionListener(new ColButton(col_list.get(i)));
        }

        f.pack();

    }

    ImageIcon whiteCircle = new ImageIcon("blank.png");
}

that contains all of the graphical interface behind my code, as you might have guessed I used Java and Eclipse.

This is my game class where my second player is going to be, and I also assume my winning loop will be here.

import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JLabel;

public class GameClass{

    public GameClass(ArrayList<ArrayList<JLabel>> col_list)
    {

    }
}

finally this is my column class which contains the 1st player and all the buttons.

package lab7;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JLabel;

public class ColButton implements ActionListener {

    private ArrayList<JLabel> _column;
    private GameClass _game;

    public ColButton(ArrayList<JLabel> c)
    {
        _column = c;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        for (int i = _column.size() - 1; i >= 0; i--)
        {
            JLabel l = _column.get(i);
            if(l.getIcon().toString().equals("images/blank.png"))
            {
                l.setIcon(new ImageIcon("images/red.png"));
                break;
            }
        }
    }

}

What do you think?  Any suggestions on how to get get going for the second part? I am working on the 2nd player but I have run into some setbacks.