texts:
I wrote the following code to insert records into a database.  The user selects the rows from the RadGrid and the insert command is executed when that user clicks the button.  I've been spending a lot of time trying to make this work (nothing currently happens when I click the button).  However, I just realized my approach is probably very inefficient due to the fact that it will result in the application repeatedly opening and closing database connections.  Even though I'm dealing with only a few hundred records I'd like to follow best practices as much as possible.

How would you rewrite this code to be more efficient? My gut tells me it would be better to gather all of the new records and then deal with them as a collection.

    protected void RadButton2_Click(object sender, EventArgs e)
{
    foreach (GridDataItem item in RadGrid1.SelectedItems)
    {
        //GridDataItem item = (GridDataItem)RadGrid1.SelectedItems;
        int UserID = Convert.ToInt16(item["UserID"].Text);
        string Type = "D";
        DateTime Date = DateTime.Now;
        string Description = "Monthly Storage Fee - Tag: " + item["PackageTag"].Text + Label3.Text;
        Int32 AmountDue = Convert.ToInt32(item["AmtDue"].Text);

        string connectionString = ConfigurationManager.ConnectionStrings["Foo"].ConnectionString;
        SqlConnection connection = new SqlConnection(connectionString);

        try
        {

            SqlCommand cmd = new SqlCommand("INSERT INTO Billing (UserID, Type, Date, Description, Amount) VALUES (@UserID, @Type, @Date, @Description, @AmountDue)", connection);
            cmd.Parameters.AddWithValue("@UserID", UserID);
            cmd.Parameters.AddWithValue("@Type", Type);
            cmd.Parameters.AddWithValue("@Date", Date);
            cmd.Parameters.AddWithValue("@Description", Description);
            cmd.Parameters.AddWithValue("@AmountDue", AmountDue);

            connection.Open();
            cmd.ExecuteNonQuery();
        }

        catch
        {
            Label4.Text = "uh oh";
        }

        finally
        {
            connection.Close();
        }


texts:
This is just my simple structure. I want to know if there is a better way than this because I have so many lines of code already.

    <?php
$p1speed = 5;
$p2speed = 3;

//way for next turn: 1 for turn
$p1 = 0;
$p2 = 0;

if($p1speed>$p2speed) {

    $p1 = 1;
    $p2 = 0;

}
else if($p2speed>$p1speed) {

    $p1 = 0;
    $p2 = 1;

}

$count=0;

//begin
while($count<5){

    if($p1==1) {

        echo 'P1 turns
';

        //adjust
        $p1 = 0;
        $p2 = 1;

    }
    else if($p2==1) {

        echo 'P2 turns
';

        //adjust
        $p1 = 1;
        $p2 = 0;

    }

    $count++;

}
?>


texts: Unit test code for a private median-of-three function, using reflection

texts:
A Junit test class is used to test the class LibraryCounter. Reflection was used to test the private methods. This made the code much more complicated.

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Test;
import static org.junit.Assert.*;

public class LibraryCounterTest {

 public LibraryCounterTest() { }

 @Test
 public void medianEasyTest() {
     System.out.println("median");
     int[] sample = {7,8,9};
     Class[] args = new Class[3];
     args[0] = int[].class;
     args[1] = Integer.TYPE;
     args[2] = Integer.TYPE;

     try {
           Method m = LibraryCounter.class.getDeclaredMethod("median", args);
          m.setAccessible(true);
          try {
              Object o = m.invoke(null, sample, 0, sample.length-1);
              int result = (int)o;
              assertEquals(8, result);
          } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
             Logger.getLogger(LibraryCounterTest.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (NoSuchMethodException | SecurityException ex) {
         Logger.getLogger(LibraryCounterTest.class.getName()).log(Level.SEVERE, null, ex);
    }

     assertEquals(7, sample[0]);
     assertEquals(8, sample[1]);
     assertEquals(9, sample[2]);
 }
}

This is just the first and simplest test.  The method being tested has the following signature private static int median(int[], int, int) If the method was public then everything inside the outermost try could be condensed to one line.

Here is the method being tested from the LibraryCounter class:

/*
*Sorts first, center and last element, swaps the new center element with the one before the new last and returns its value.
*/
private static int median(int[] sample, int start, int end) {
    if(sample.length < 3) {
        throw new IllegalArgumentException("arrays of length three or greater");
    }

    int center = start + ((end-start)/2);

    if(sample[start] > sample[end])
       swap(sample, start, end);

    if(sample[start] > sample[center])
       swap(sample, start, center);

    if(sample[center] > sample[end])
       swap(sample, center, end);

int secondLast = end - 1

    swap(sample, center, secondLast );

    return sample[secondLast];

}

//swaps two elements in array given their positions
private static void swap(int[] sample, int x, int y) {
    int temp = sample[x];
    sample[x] = sample[y];
    sample[y] = temp;
}


texts: CodeIgniter AJAX messages submission security issue

texts:
I have a small social networking site built in CodeIgniter. Any registered user can send messages to others by visiting their profile.

Today I noticed that one user sent bulk messages to 200 users. How he was able to do that?

Suggestions to make the code secure are welcome.

I have a textarea and a send button on the profile page.

jQuery code on profile page (View)

$("#send").click(function(event){
    var msg=$("#quick_message").val();
    var uid=$(this).attr('uid');

    if(msg.length > 0) {
        $("#msg_status").html('');

        $.post("<?=base_url()?>message/send_message", {"ids":uid,"msg":msg}, function(data){

        $("#msg_status").html('Message sent.');
        $("#quick_message").val('');
        });
    } else {

    $("#msg_status").html('Write something to send message.');
    }
});

Here is my controller

  // send message
   function send_message()
 {
    if (!$this->users->is_logged_in()) {
    redirect('signin');
    }

    $user_id=$this->session->userdata('user_id');
    $ids=trim($this->input->post('ids'));
    $msg=trim($this->input->post('msg'));
    $msg=htmlspecialchars($msg);
    $msg=$this->replaceTolink($msg);
    $msg=$this->replaceTowinks($msg);

    $pieces=explode(",", $ids);
    foreach ($pieces as &$user_id2) {
    $this->db->insert('messages', array('user_id1' => $user_id,'user_id2' => $user_id2,'message' => $msg));
    }

    return true;
}

What I need to improve in my code and how to protect the code to send bulk messages?


texts: Modify XML attribute based on element value

texts:
I have some xml files that have some nodes like (among other nodes)

<disp-formula id="deqn*">
...\tag{1}
</disp-formula>
<disp-formula id="deqn*">
...\tag{2}
</disp-formula>
<disp-formula id="deqnxyz">
...\tag{3}
...
...\tag{4}
...\tag{5}...
...
......\tag{6}
</disp-formula>

I'm trying to get the values inside the string/strings \tag{} which is inside the nodes  with an attribute named id and modify it with the value/values inside its respective tag{} i.e. the output should be

<disp-formula id="deqn1">
...\tag{1}
</disp-formula>
<disp-formula id="deqn2">
...\tag{2}
</disp-formula>
<disp-formula id="deqn3-6">
...\tag{3}
...
...\tag{4}
...\tag{5}...
...
......\tag{6}
</disp-formula>

I've done

//for nodes containing single \tag{}
Regex regex = new Regex(@"(?<=\\tag\{)(\w+)(?=\})");
var xml = File.ReadAllText(@"D:\Test\sample.xml");
var xdoc = Xdocument.Parse(xml, LoadOptions.PreserveWhitespace);
var _descriptions = xdoc.Descendants("disp-formula")
    .Where(x => regex.Match(x.Value).Success);
foreach (var description in _descriptions)
{
    var _Result = regex.Match(description.Value).Value;
    description.Attribute("id").Value = "deqn" + _Result;
    xdoc.Save(@"D:\Test\sample.xml", SaveOptions.DisableFormatting);
}
//for nodes containing multiple \tag{}'s
var descriptions = xdoc.Descendants("disp-formula")
    .Where(x => regex.Matches(x.Value).Count > 1);
foreach (var description in descriptions)
{
    var p = regex.Matches(description.Value).Cast<Match>().Select(m => m.Value).ToArray();
    var x = p[0];
    var y = p[p.Count() - 1];
    var Result = x + "-" + y;
    description.Attribute("id").Value = "deqn" + Result;
    xdoc.Save(@"D:\Test\sample.xml", SaveOptions.DisableFormatting);
}

How do I make this code more efficient?


texts: Getting enum values of Pseudo-Enum classes

texts:
By "Pseudo-Enum" classes I mean cases where someone's used a class with public static properties to emulate enum behaviour; e.g. as described here.

Per the example below, this is useful for classes such as [System.Management.Automation.VerbsCommon], where there is a list of values we're interested in, but no "Get All Values of This Type" method.

I wrote this function for the above type, and it works well for that, but maybe I've missed a trick / there are likely other scenarios that this code could cover which I've not thought of yet.

Clear-Host
function Get-EnumValues {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory,ValueFromPipeline)]
        [Type]$Type
    )
    process {
        if ($Type) {

            Write-Verbose ("Type: {0}" -f $Type.ToString())
            Write-Verbose ("IsEnum? {0}" -f $Type.IsEnum)

            if ($Type.IsEnum) {
                [System.Enum]::GetNames($Type)
            } else {
                #handle pseudo-enums (i.e. for cases where this trick's been used https://stackoverflow.com/a/15713789/361842)
                $Type.GetFields() | ?{$_.IsStatic -and $_.IsPublic} | select -ExpandProperty Name
            }
        } else {
            Write-Verbose ("TypeName is Null")
            $null
        }
    }
}

$t = [type][System.ConsoleColor]
Get-EnumValues $t -Verbose
$t = [type][System.Management.Automation.VerbsCommon]
Get-EnumValues $t -Verbose

Output:

VERBOSE: Type: System.ConsoleColor
VERBOSE: IsEnum? True
Black
DarkBlue
DarkGreen
DarkCyan
DarkRed
DarkMagenta
DarkYellow
Gray
DarkGray
Blue
Green
Cyan
Red
Magenta
Yellow
White
VERBOSE: Type: System.Management.Automation.VerbsCommon
VERBOSE: IsEnum? False
Add
Clear
Close
Copy
Enter
Exit
Find
Format
Get
Hide
Lock
Move
New
Open
Optimize
Push
Pop
Remove
Rename
Reset
Resize
Set
Search
Show
Skip
Step
Join
Redo
Split
Switch
Select
Undo
Unlock
Watch

I'm aware that the shorthand coding style sometimes frowned upon, such as:

$Type.GetFields() | ?{$_.IsStatic -and $_.IsPublic} | select -ExpandProperty Name

could be written as:

$Type.GetFields() | Where-Object{$_.IsStatic -and $_.IsPublic} | Select-Object -ExpandProperty Name

I've taken the view whereby I allow shorthand for the most common, general-purpose cmdlets (i.e. select for select-object, % for foreach-object, ? for where-object) as those should be familiar to any powershell developer with any experience; whilst for all others I avoid aliases completely.  My view is that these common aliases are more easily readable, and are unlikely to cause confusion.


texts: How to improve performace of this Map Reduce function, Python mrjob

texts:
I'm trying to get the most out of this code, so I would understand what should I look for in the future. The code below, works fine, I just want to make it more efficient.

Any suggestions?

from mrjob.job import MRJob
import operator
import re

# append result from each reducer
output_words = []

class MRSudo(MRJob):

    def init_mapper(self):
        # move list of tuples across mapper
        self.words = []

    def mapper(self, _, line):
        command = line.split()[-1]
        self.words.append((command, 1))

    def final_mapper(self):
        for word_pair in self.words:
            yield word_pair

    def reducer(self, command, count):
        # append tuples to the list
        output_words.append((command, sum(count)))

    def final_reducer(self):
        # Sort tuples in the list by occurence
        map(operator.itemgetter(1), output_words)
        sorted_words = sorted(output_words, key=operator.itemgetter(1), reverse=True)
        for result in sorted_words:
            yield result

    def steps(self):
        return [self.mr(mapper_init=self.init_mapper,
                        mapper=self.mapper,
                        mapper_final=self.final_mapper,
                        reducer=self.reducer,
                        reducer_final=self.final_reducer)]

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


texts: Mad Libs using recursive IO for user input

texts:
I'm writing my first small programs in Haskell and still getting a feel for the syntax and idioms. I've written this Mad Libs implementation using recursive IO. I've used IO actions throughout and I'm sure there must be a better way of splitting up this code to separate pure functions from IO actions. Also, I'm not happy with the printf statement, but I couldn't find a native way to apply an arbitrary number of list items to printf.

import Text.Printf

getAnswer :: String -> IO String
getAnswer question = do
    putStrLn question
    answer <- getLine
    return answer

getAnswers :: [String] -> [String] -> IO [String]
getAnswers [] ys = return ys
getAnswers (x:xs) ys = do
    answer <- getAnswer x
    let answers = ys ++ [answer]
    getAnswers xs answers

main = do
    let questions = ["Enter a noun:", "Enter a verb:", "Enter an adjective:", "Enter an adverb:"]
    let madlib = "Your %s is %s up a %s mountain %s."
    answers <- getAnswers questions []
    printf madlib (answers!!0) (answers!!1) (answers!!2) (answers!!3)
    putStrLn ""


texts:
I am trying to write a procedure that finds the power set of a list, that is, the set of 2n subsets (where n is the number of elements in the list). I simply quite find all the subsets. I feel my code is a lot more work than it should be.

(define (element-of-set? x set)
  (cond ((null? set) false)
        ((not(pair? set)) (display "not a set\n") false)
        ((equal? x (car set)) true)
        (else (element-of-set? x (cdr set)))))

(define (length set)
  (define (length-iter a len )
    (if (null? a)
        len
        (length-iter (cdr a) (+ 1 len))))
  (length-iter set 0))

(define (adjoin-set x set)
  (if (element-of-set? x set)
      set
      (cons x set)))

(define (conS x w )
  (cond ((null? w) '())
        (else(cons (cons (car x) (cons (car w) '())) (conS x (cdr w))))))

(define (helper s)
  (define (help s newS len)

    (if (<= len 0) newS
        (help (cdr s)(append (adjoin-set s newS) (conS s (cdr s)))(- len 1))))
  (help s '() (length s)))

(define (trim s)
  (let helper((s s) (newS '()) (len (length s)))
    (cond ((<= len 0) newS)
          ((null?(cdr(car s)))
                 (helper (cdr s) newS(- len 1)))
          (else (helper (cdr s) (adjoin-set (car s) newS) (- len 1))))))

(define (subsets x)
  (define (sub x newSet)
    (if (null? x) newSet
        (sub (cdr x) (adjoin-set (cons (car x) '())
                                 (adjoin-set '() newSet)))))
  (sub x (trim (helper x))))


texts: Find all file occurences of a search term on drive

texts:
I have written a small application that lets the user search drives for their given input string. I am only returning the full name of files. What I have now is the following method to retrieve those full names:

private IEnumerable<string> FindOccurences(string searchQuery, DriveInfo drive)
{
    return drive.RootDirectory.EnumerateFiles(searchQuery).Select(file => file.FullName);
}

Where I made the choice of using EnumerateFiles over GetFiles to get faster performance as shown here:

  The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.

I was wondering if there is any other solution to increase performance even more, perhaps through a different API? Are there any other tweaks to my code you can suggest?


texts: Simple and efficient data structure for standard deviation queries in Java

texts:
I have this data structure to which the user can add number or remove them, both in constant time. Also, there is a \$O(1)\$ operation for querying the standard deviation of the current contents of the structure:

StandardDeviationNumberSet.java

package net.coderodde.stat;

import java.util.HashMap;
import java.util.Map;

public class StandardDeviationNumberSet {

    private double sum;
    private double squareSum;
    private int numberOfElements;
    private final Map<Double, Integer> countMap = new HashMap<>();

    public void add(Number number) {
        double numberValue = number.doubleValue();
        Integer count = countMap.get(numberValue);

        if (count != null) {
            countMap.put(numberValue, count + 1);
        } else {
            countMap.put(numberValue, 1);
        }

        sum += numberValue;
        squareSum += numberValue * numberValue;
        numberOfElements++;
    }

    public double remove(Number number) {
        double numberValue = number.doubleValue();
        Integer count = countMap.get(numberValue);

        if (count != null) {
            if (count > 1) {
                countMap.put(numberValue, count - 1);
            } else {
                countMap.remove(numberValue);
            }

            sum -= numberValue;
            squareSum -= numberValue * numberValue;
            numberOfElements--;
            return numberValue;
        } else {
            return Double.NaN;
        }
    }

    public double getStandardDeviation() {
        checkSetHasAtleastTwoElements();
        double step1 = squareSum - sum * sum / numberOfElements;
        double step2 = step1 / (numberOfElements - 1);
        return Math.sqrt(step2);
    }

    private void checkSetHasAtleastTwoElements() {
        if (numberOfElements < 2) {
            throw new IllegalStateException(
                    "Computing the standard deviation requires at least two " +
                    "elements.");
        }
    }

    public static void main(String[] args) {
        StandardDeviationNumberSet set = new StandardDeviationNumberSet();

        set.add(1);
        set.add(1);
        set.add(3);

        System.out.println(set.getStandardDeviation());

        set.remove(1);

        System.out.println(set.getStandardDeviation());
    }
}

As always, any critique is much appreciated.


texts:
Given an integer, sort the digits in ascending order and return the
  new integer.

  Ignore leading zeros.

  Parameters:

  Input: num {Integer}
  Output: {Integer}

  Constraints:

  Do not convert the integer into a string or other data type.
  Time: O(N) where N is the number of digits.
  Space: O(1)

  Examples:

  8970 --> 789
  32445 --> 23445
  10101 --> 111

My code (as follows) works similar to the counting sort:

def sort_digits(n):
    digit_counts = {}
    result = 0

    while n > 0:
        digit = n % 10
        digit_counts[digit] = digit_counts.get(digit, 0) + 1
        n /= 10

    power = 0
    for i in range(10, -1, -1):
        if i in digit_counts:
            while digit_counts[i] >= 1:
                result +=  i * (10 ** (power))
                power += 1
                digit_counts[i] -= 1

    return result


texts: Grep for pattern recursive and disable file

texts:
On a shared host, I'd like to setup a cron which scans folders recursively for some base64 malware strings. Therefore, I've written the following script:

#!/bin/bash

if [ $# -ne 1 ]; then
    echo $0: usage: ./findone folder_to_start_with
    exit 1
fi

folder=$1

IFS=$'\n'
searchfiles=($(grep -r -F -n -f malware-strings.dat $folder))

for (( i=0; i<${#searchfiles[@]}; i++ ));
        do
                STR=$(echo ${searchfiles[i]} | awk -F':' '{print $1}')
                    if [ -z "$STR" ];
                        then true;
                        else chmod 000 $STR;
                    fi
        done

## Do something else like mail results etc.
printf '%s\n' "${searchfiles[@]}"

My locals test are doing what I expect. If a string pattern from "malware-string.dat" is found the file permission is changed to 000. Before scanning the production sites, I wanted to ask for a code review as I'm new to Bash and do not want to mess things up. Also, your judgement of disabling the file with chmod is enough would help, or if it is advisable to move the file outside of the www directory.


texts: Making a binary tree using an array in C

texts:
If I want to make a binary tree from an array in the following order:

Example: for the following array: { -1, 17, -1, 3, -1, -1, -1, 55, -1, 4, -1, 15, 11, 2, 3 } the following tree is created:

           55

     15         3

  2     4     *    17

3 11  *   *      *    *

The function is recursive and returns a Tree input: the array and it's size. The tree nodes can only receive positive values from the array so -1 wont be considered. * means NULL prototype: Tree BuildTreeFromArray(int *arr, int size).

Would very much appreciate the help.

This is what I had so far and it's working but I don't really like it.

Tree BuildTreeFromArray(int  *arr, int  size)
{
    Tree resTree;
    Tree right;
    Tree left;
    resTree.root = (TreeNode*)malloc(sizeof(TreeNode));
    checkMemoryAllocation(resTree.root);
    int halfSize;

    if (size == 1)
    {
        resTree.root->data = arr[0];
        resTree.root->left = NULL;
        resTree.root->right = NULL;
    }
    else
    {
        halfSize = size / 2;
    resTree.root->data = arr[halfSize];

    if (arr[halfSize/2] != -1)
    {//we check if there's a valid array data we can input to the tree
        left = BuildTreeFromArray(arr, halfSize);
        resTree.root->left = left.root;
    }
    else
        resTree.root->left = NULL;

    if (arr[halfSize + (halfSize / 2) + 1] != -1)
    {
        right = BuildTreeFromArray(arr + halfSize + 1, halfSize);
        resTree.root->right = right.root;
    }
    else
        resTree.root->right = NULL;

    }
    return resTree;
}

Could this be written in a different version?


texts: Random integer generation in given range

texts:
Can my rand_int function be improved?

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

int rand_int(int a,int b)
{
    //The basic function here is like (rand() % range)+ Lower_bound

    srand(time(0));
    if (a > b)
        return((rand() % (a-b+1)) + b);
    else if (b > a)
        return((rand() % (b-a+1)) + a);
    else
        return a;
}

int main()
{
    int a,b;

    printf("\nEnter the range in which the a random no. is required: ");
    scanf("%d %d", &a, &b);

    printf("%d\n", rand_int(a,b));
}


texts:
I've finished implementing a dynamic array in C++. I'm a beginner in C++ and also in algorithms and data structures, so any constructive feedback about improving the implementation would be greatly appreciated.

#include <iostream>

using namespace std;
#define INITIAL_CAPACITY 5

template <class T>
class dynamic_array {
    T *array;
    int MIN_CAPACITY = INITIAL_CAPACITY;
    int GROWTH_FACTOR = 2;
    int size;

public:
    // constructor init
    dynamic_array() {
        array = new T[MIN_CAPACITY];
        size = 0;
    }

    // append @ the end
    void append(T element) {
        if(size == MIN_CAPACITY) {
            resize();
        }
        array[size] = element;
        size++;

    }

    void deleteAt(int pos) {
        if((pos > size) || (pos < 0)) {
            cout << "Invalid index";
            return;
        }

        for(int i = pos; i <= size; i++) {
            array[i] = array[i+1];
        }
        size--;
    }

    void insertAt(int element, int pos) {
        if((pos > size) || (pos < 0)) {
            cout << "Invalid index";
            return;
        }

        if(size == MIN_CAPACITY) {
            resize();
        }

        size++;

        for(int i = size - 1; i >= pos; i--) {
            if(i == pos) {
                array[i] = element;
            } else {
                array[i] = array[i-1];
            }
        }
    }

    // returns size of array
    int length() {
        return size;
    }

    // doubles capacity if it has to and deletes reference to current array.
    void resize() {
        MIN_CAPACITY *= GROWTH_FACTOR;
        T *temp = new T[MIN_CAPACITY];
        copy(temp);
        delete [] array;
        array = temp;

    }

    // copies original array into temp
    void copy(T temp[]) {
        for(int i = 0; i < size; i++) {
            temp[i] = array[i];
        }
    }

    // returns element in x position.
    T get(int pos) {
        return array[pos];
    }
};

int main() {
    dynamic_array<int> dynArr;
    dynArr.append(3);
    dynArr.append(4);
    dynArr.append(5);
    dynArr.append(4);
    dynArr.append(33);
    dynArr.append(3);

    dynArr.deleteAt(6);

    return 0;
}


texts:
For educational purposes I wrote a little piece of code to rotate greyscale images as "low level" as possible, that is, not using any rotate() function, but doing the math. I was wondering if it could be improved in any way, specially in order to achieve better performance. I'm not concerned with the libraries or the programming language chosen to perform this task, I am aware that they aren't the best option if what I want is performance. I'm only concerned with the code itself.

It basically maps the pixels on the new image to the ones in the original image and interpolates using nearest neighbor or bilenear.

def affine_t(x, y, a, b, c, d, e, f):
    # A lot faster than numpy.dot([[a,b],[c,d]],[x,y])+[e,f]
    return round(a*x + b*y + e, 3), round(c*x + d*y + f, 3)

def mrotate(r, cx=0, cy=0):
    # Returns the coefficients to an affine transformation which rotates
    # a point clockwise by r radians in respect to a central point. For counter
    # clockwise, just pass r as -r.
    return (math.cos(r), -math.sin(r), math.sin(r), math.cos(r), cx, cy)

def lin_interp(x, x0, x1, y0, y1):
    # Faster than numpy.interp()
    return y0 + (y1 - y0)*((x-x0)/(x1-x0))

def bilinear(bmp, ox, oy):
    # Try to interpolate. If the pixel falls on the image boundary, use the
    # nearest pixel value (nearest neighbor).
    try:
        x0, x1, y0, y1 = int(ox), int(ox)+1, int(oy), int(oy)+1
        a = lin_interp(ox, x0, x1, bmp[y0][x0], bmp[y0][x1])
        b = lin_interp(ox, x0, x1, bmp[y1][x0], bmp[y1][x1])
    except IndexError:
        return nn(bmp, ox, oy)
    return int(lin_interp(oy, y0, y1, a, b))

def nn(bmp, ox, oy):
    return bmp[oy][ox] # bmp is numpy.array, it casts float indexes to int

def rotate(bmp, r, mx=0, my=0, filename=None, interpol=None):
    """Rotate bitmap bmp r radians clockwise from the center. Move it mx, my."""

    # Get the bitmap's original dimensions and calculate the new ones
    oh, ow = len(bmp), len(bmp[0])
    nwl = ow * math.cos(r)
    nwr = oh * math.sin(r)
    nhl = ow * math.sin(r)
    nhu = oh * math.cos(r)
    nw, nh = int(math.ceil(nwl + nwr)), int(math.ceil(nhl+nhu))
    cx, cy = ow/2.0 - 0.5, oh/2.0 - 0.5 # The center of the image
    # Some rotations yield pixels offscren. They will be mapped anyway, so if
    # the user moves the image he gets what was offscreen.
    xoffset, yoffset = int(math.ceil((ow-nw)/2.0)), int(math.ceil((oh-nh)/2.0))
    for x in xrange(xoffset,nw):
        for y in xrange(yoffset,nh):
            ox, oy = affine_t(x-cx, y-cy, *mrotate(-r, cx, cy))
            if ox > -1 and ox < ow and oy > -1 and oy < oh:
                pt = bilinear(bmp, ox, oy) if interpol else nn(bmp, ox, oy)
                draw.point([(x+mx,y+my),],fill=pt)
    if filename is not None:
        im.save(filename)

The complete code, used to generate the examples below:

http://pastebin.com/2j7BQyzi

Some example rotations, first image is the original, to the left is one rotated 90 degrees and the one below is rotated 45 degrees.

Using Nearest Neighbors:

Using Bilinear:

Note: The original "Lenna.png" image was first resized to 0.5 the original size using bilinear interpolation and flatten to a greyscale.


texts: Creating & reading CSV with system own tools

texts:
There are lot libraries for creating/parsing CSV but how about not using any of them and instead use Windows own tools like PowerShell?

I thought I'll try and create some extensions for that purpose so here they are. One for converting a collection into a CSV and the other one for reading a CSV. Do you think it's cheating? ;-)
public static class Converter
{
    public static string ToCsv<T>(this IEnumerable<T> objects, char delimiter = ';')
    {
        var currentCulture = CultureInfo.CurrentCulture;
        CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
        try
        {
            using (var ps = PowerShell.Create())
            {
                ps.AddCommand("ConvertTo-Csv");
                ps.AddParameter("NoTypeInformation");
                ps.AddParameter("Delimiter", delimiter);

                var results = ps.Invoke(objects);
                var errors = ps.Streams.Error.ReadAll();

                if (errors.Any())
                {
                    throw new AggregateException(errors.Select(err => err.Exception));
                }

                return string.Join(Environment.NewLine, results);
            }
        }
        finally { CultureInfo.CurrentCulture = currentCulture; }
    }

    public static IEnumerable<T> ParseCsv<T>(this string csv, char delimiter = ';') where T : new()
    {
        var currentCulture = CultureInfo.CurrentCulture;
        CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
        try
        {
            using (var ps = PowerShell.Create())
            {
                ps.AddCommand("ConvertFrom-Csv");
                ps.AddParameter("Delimiter", delimiter);
                ps.AddParameter("InputObject", csv);

                var results = ps.Invoke();
                var errors = ps.Streams.Error.ReadAll();

                if (errors.Any())
                {
                    throw new AggregateException(errors.Select(err => err.Exception));
                }

                var properties = typeof(T).GetProperties().ToLookup(p => p.Name);
                return results.Select(result =>
                {
                    var obj = new T();
                    foreach (var psProperty in result.Properties)
                    {
                        var property = properties[psProperty.Name].Single();
                        property.SetValue(
                            obj,
                            Convert.ChangeType(
                                psProperty.Value,
                                property.PropertyType));
                    }
                    return obj;
                });
            }
        }
        finally { CultureInfo.CurrentCulture = currentCulture; }
    }
}

In order for this to work you'll need the System.Management.Automation package.

Examples:
Test object:
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

Usage:
var items = new[]
{
    new Person { FirstName = "Name 1",  LastName ="LName1", Age = 160 },
    new Person { FirstName = "Name 2" }
};

items.ToCsv().Dump();

@"""FirstName"";""LastName"";""Age""
""Name 1""; ""LName1""; ""160""
""Name 2""; ; ""0""".ParseCsv<Person>().Dump();


texts: Dynamic AuthorizeAttribute with database

texts:
I want to create a AuthorizeAttribute that gets the current ActionMethod RouteData and searches in a database for a user that has access to this ActionMethod.

I created a UserAccessPermission table:

public class UserAccessPermission
{
    [Key]
  public int  UserAccessPermissionId { get; set; }
    public string ActionMethod { get; set; }
    public string Controller { get; set; }
    public string Area { get; set; }
    public bool HasAccess { get; set; }

    [DisplayName("User ID")]
    [ForeignKey("ApplicationUser")]
    public string Id { get; set; }
    [DisplayName("User")]
    public virtual ApplicationUser ApplicationUser { get; set; }

}

and then link it to the User table:

 public class ApplicationUser : IdentityUser
{
    public ApplicationUser()
    {
        AccessPermissions = new HashSet<UserAccessPermission>();

    }
 some custome field

    //*******************************************************************

    public virtual ICollection<UserAccessPermission> AccessPermissions { get; set; }

 }

so each user has multi ActionMethod that can access it. Then I create my custom AuthorizeAttribute:

  public class DynamicRoleAuthorizeAttribute : AuthorizeAttribute
{
   private readonly UserManager<ApplicationUser> _userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        bool result = false;
        if (httpContext == null)
        {
            throw new ArgumentNullException("httpContext");
        }

        IPrincipal user = httpContext.User;
        if (!user.Identity.IsAuthenticated)
        {
            return false;
        }

        //var rolesProvider = new RoleProvider();
        var routeData = httpContext.Request.RequestContext.RouteData;
        var controller = routeData.GetRequiredString("controller");
        var action = routeData.GetRequiredString("action");
        string area = null;
        var userId = httpContext.User.Identity.GetUserId();
        var _user = _userManager.FindById(userId);

        if (routeData.DataTokens["area"] != null)
        {
            area = routeData.GetRequiredString("area");
            result = _user.AccessPermissions.Where(x => x.Controller.Equals(controller) && x.ActionMethod.Equals(action) && x.Area.Equals(area)).Select(x => x.HasAccess).FirstOrDefault();

        }
        else
        {
            result = _user.AccessPermissions.Where(x => x.Controller.Equals(controller) && x.ActionMethod.Equals(action)).Select(x => x.HasAccess).FirstOrDefault();

        }

        if (result)
        {
            return true;
        }

        return false;
        //return base.AuthorizeCore(httpContext);
    }
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new HttpUnauthorizedResult();
    }
}

But this approach is too hard for page management and the admin should give user access permission for each ActionMethod. Is there any better way to do this?


texts:
I really enjoy Haskell but feel I still have a total beginner's style, and would like to move beyond that.  The code below - for Dijkstra's shortest path algorithm - is a case in point.  I feel as though I have ended up with a copy of the imperative pseudo code I began with, having done some small transformations, but not the sort of big ones an expert would come up with.  (Perhaps it was the very fact that I had pseudo code to start with that got me into this mess - without it would I have pursued a generate and prune strategy?)

But the big decision I needed was how to store the 3 elements of state

The results
The Dijkstra scores of the points not yet turned into results; and
The set of points already found (i.e. the keys of the results)

In the end I used a Vector to Dijkstra scores, and have been passing around my state variables, whereas they could probably have been put into the background with a Monad.  I know that having Vector manipulations in two places is not smart (I could probably have reduced that 1 by passing the deletion request into recalc....).

I'd welcome any constructive comments, on how an expert would approach the state challenge.

import qualified Data.ByteString.Char8 as BS
import qualified Data.Vector as V
import qualified Data.List   as L

type NodeName = Int
type Dist = Int
type Edge = (NodeName, Dist)
type Edges = [Edge]
type Graph = V.Vector Edges

-- STATE
type Explored = [NodeName] -- IntSet?
type Results = [(NodeName, Dist)] -- need to add to randomly
type DijkstraScores = V.Vector (Maybe Dist)

-- take top from DijkList
-- add to results
-- get update DijkList
mainLoop :: Graph -> Explored -> DijkstraScores -> Results -> Results
mainLoop gr exs ds res =
    let
        minIdx = V.minIndexBy maybeOrder ds
        Just minVal = ds V.! minIdx
        res' = (minIdx,minVal) : res
        exs' = minIdx : exs
        newDists = filter (not . (`elem` exs') . fst) $ gr V.! minIdx
        newDs = recalcDijkDist newDists minVal $ ds V.// [(minIdx,Nothing)] -- remove this value
    in case V.all (==Nothing) newDs of
        True -> res
        False -> mainLoop gr exs' newDs res'

-- run over new Dists
    -- change if lower
    -- leave if higher
    -- add if no existing data
    -- recombine with all other data
recalcDijkDist :: Edges -> Dist -> DijkstraScores -> DijkstraScores
recalcDijkDist newDists distOfNewPoint ds =
    let
        comps = map process newDists
        process :: Edge -> (Int, Maybe Int)
        process (x,y) =
            case ds V.! x of
                Just z -> (x, Just $ min (y + distOfNewPoint) z)
                Nothing -> (x, Just $ y + distOfNewPoint)
    in ds V.// comps

getEdges :: String -> IO Graph
getEdges path = do
    -- init removes a trailing '\r'
    lines <- (map (init . (BS.split '\t')) . BS.lines) `fmap` BS.readFile path
    let gr = V.fromList $ ([] :) $ map processLine lines
    return gr

processLine :: [BS.ByteString] -> Edges
processLine (n:connections) = map splitter connections
    where
        myread  = maybe (error "can't read Int") fst . BS.readInt
        splitter c = let
                (x,y) = (\(xx,yy) -> (xx, BS.tail yy)) $ BS.break (==',') c
            in (myread x, myread y)

main = do
    gr <- getEdges "dijkstra.txt"
    let
        --mloop = mainLoop gr [] (initDijkstra $ gr V.! 1) []
        mloop = mainLoop gr [] (recalcDijkDist (gr V.! 1) 0 $ V.replicate 201 Nothing) []
        anstoFind = [7,37,59,82,99,115,133,165,188,197]
        -- maybe :: b -> (a -> b) -> Maybe a -> b
        answers = map (\x -> snd $ maybe (error "not found") id $ L.find ((==x).fst) mloop) anstoFind
    return answers
    --return gr

-- Nothing is interpreted as 0 otherwise
maybeOrder :: Maybe Int -> Maybe Int -> Ordering
maybeOrder Nothing x = GT
maybeOrder x Nothing = LT
maybeOrder (Just x) (Just y) = compare x y


texts:
It is common to shorten city names when writing, or at least in Sweden.

"Göteborg" (Gothenburg) is often referred to as "Gbg"
"Uddevalla" is commonly written as "Ua"
"Trollhättan" is often written as "Thn"
...and a whole lot of other city names are often shortened

"Uddevalla" could also be shortened as "Uva", "Uvalla", or even "Udl" (although I've never seen anyone actually type that, according to my rules here it would be allowed). "vd" however would not be allowed as the letters must appear in order, "dv" would be allowed as an abbreviation for "Uddevalla" as "v" comes after "d".

Given a list of cities (or more generally: Strings) and a search string, print the city names that can be constructed by using these abbreviation rules.

Example cities (my townnames.txt file):

Strömstad
Skee
Överby
Tanum
Rabbalshede
Hällevadsholm
Dingle
Munkedal
Uddevalla
Ljungskile
Svenshögen
Stenungsund
Stora Höga
Kode
Ytterby
Göteborg
Trollhättan
Vänersborg
Varberg
Stockholm
Simrishamn

These are cities in Sweden, mostly in around my area. With the above list and the search string "Sm" the following cities are printed:

["Strömstad", "Stockholm", "Simrishamn"]

Instead given the string "Vbg" the results are:

["Vänersborg", "Varberg"]

After looking at the review I got from my previous Haskell question I wrote the following code to accomplish this:

module Main
   where

nameMatch :: [Char] -> [Char] -> Bool
nameMatch [] [] = True
nameMatch s [] = False
nameMatch [] s = True
nameMatch search@(s:restSearch) (c:city)
   | c == s    = nameMatch restSearch city
   | otherwise = nameMatch search city

main = do
  putStrLn "Loading list of towns..."
  text <- readFile "townnames.txt"
  putStrLn "Enter search phrase:"
  search <- getLine
  let cities = lines text
  putStrLn $ show $ filter (nameMatch search) cities

Any possible improvements or suggestions welcome.


texts:
I am creating a code which checks a user inputted password and gives points based on it. One of the points is: If it has 3 letters adjacent/consecutive on the QWERTY UK keyboard then it will be -5 points. e.g "qwerty" will be -20 points for "qwe" "wer "ert" "rty". I have got a solution to this but I was wondering if there is any way of improving it.

input = input("What is your password?")
qwerty = 'qwertyuiopasdfghjklzxcvbnm'
lower = input.lower()
for idx in range(0, len(lower) - 2):
    test_seq = lower[idx:idx + 3]
    if test_seq in qwerty:
        points -= 5
print(points)


texts:
I'm new to Android and I wanted to create a class that would load an ad inside the current layout.  All the layouts have a RelativeLayout id=adLayout

From my main, I have:

AdLoader al = new AdLoader();
al.GrabAd(this,"123");

Then on my AdLoader.java class I have:

public class AdLoader {

    private DfpAdView adView;

    public void GrabAdFor(Activity act, String adId) {
        adView = new DfpAdView(act, AdSize.BANNER, adId);
        RelativeLayout rl = (RelativeLayout) act.findViewById(R.id.adLayout);
        rl.addView(adView);
        adView.loadAd(new AdRequest());
    }
}

Is it incorrect to pass the Activity?  Am I even passing the activity or the View/Context?


texts: Javascript - Extract data from html table

texts:
I want to extract the headers data and column data (not row data) from an HTML table using JavaScript.

Is this a good approach of doing it? And how can I simplify this using jQuery?

let table = document.getElementById('tab')
debugger
let headers = Array.from(table.rows[0].cells).map(x => x.innerText)
let columnData =
Array.from(table.rows).
      slice(1, table.rows.length).
      map(row =>Array.from(row.cells).map(x => x.innerText))
     .reduce((acc,rowData)=>{
           rowData.forEach((value,index)=>{
           acc[index]= acc[index] || [ ]
           acc[index].push(value) })
      return acc },[])
console.log(headers)
console.log(columnData)

      Name

      Age

      Location

      Jason

      22

      Texas

      Lawson

      21

      Florida

      Jose

      25

      London


texts:
I have the following log4j2.properties file:

status = info
name = my-app

# properties
property.name = my-app
property.basePath = log
property.filename = ${basePath}/${name}.log

# console layout
appender.console.type = Console
appender.console.name = console-logger
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{ISO8601} %-5p [%t] %c{1}.%M:%L - %msg%n

# rolling layout
appender.rolling.type = RollingFile
appender.rolling.name = rolling-file-logger
appender.rolling.fileName = ${filename}
appender.rolling.filePattern = ${basePath}/${name}-%d{yyyy-MM-dd-hh-mm}.log
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d{ISO8601} %-5p [%t] %c{1}.%M:%L - %msg%n

# rolling policies
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
appender.rolling.policies.time.modulate = true
appender.rolling.strategy.type = DefaultRolloverStrategy

# root logger
rootLogger.level = info
rootLogger.appenderRefs = rolling, stdout
rootLogger.appenderRef.console.ref = console-logger
rootLogger.appenderRef.rolling.ref = rolling-file-logger

The main criteria I am aiming for is:

Log files to log/my-app.log.
Rollover log files each minute to log/my-app-yyyy-MM-dd-hh-mm.log.

The properties file above works for my purposes, but I would like to remove redundancy wherever possible.

A couple questions:

Is there a way to use the variable name = my-app? I created another variable property.name, but not entirely sure that's necessary.
Both console-logger and rolling-file-logger have the same layout.type and layout.pattern. Is there a simpler way to have both loggers use the same layout.type and layout.pattern without defining it twice?
Any other opportunities for simplifying.


texts:
I have the following code on my server that takes a string and inserts newlines in such a way that the string is separated into lines, all of which are shorter than maxLineLength in characters. This ensures that the text, when printed, will fit within a certain width.

const formatTextWrap = (text, maxLineLength) => {
  var words = text.replace(/[\r\n]+/g, ' ').split(' ')
  var lineLength = 0
  var output = ''
  for (var word of words) {
    if (lineLength + word.length >= maxLineLength) {
      output += `\n${word} `
      lineLength = word.length + 1
    } else {
      output += `${word} `
      lineLength += word.length + 1
    }
  }
  return output
}

What optimizations could I make? This code works, but are there any pitfalls to using this?


texts:
I am using PySide and the following widget sublassed from QLabel to display either the current day or time in my application:

# -*- coding: utf-8 -*-

import datetime
from PySide import QtGui, QtCore

class DateTimeLabel(QtGui.QLabel):
    """ Displays current date or time in a label."""
    choice = "Time"

    def __init__(self, parent=None):
        super(DateTimeLabel, self).__init__(parent)

        timer = QtCore.QTimer(self)
        timer.setInterval(100)
        timer.timeout.connect(self.display_current_date_time)
        timer.start()

    def display_current_date_time(self):
        """ Get today's date and current time"""
        now = datetime.datetime.now()
        today_date = datetime.datetime.strftime(now, "%d/%m/%Y")
        today_time = datetime.datetime.strftime(now, "%H:%M:%S")

        if self.choice == "Time":
            content = today_time
        else:
            content = today_date
        self.setText(content)

I think it can be improved. Any ideas ?


texts: Proper way to log progress and resume in Python

texts:
I often have a need to log my progress when doing a repetitive task.  Logging allows me to continue where I left off if execution is halted (for example, perhaps my VPS server was rebooted by my host).

My current working solution is a bit ad hock.  Any input on improving this would be appreciated:

class RepeatingTask(object):
    def __init__(self, first, logfile):
        self.current = first
        self.logfile = logfile

    def page(self):
        self.process_request()
        self.increment()
        self.log_progress()

    def process_request(self):
        # do processing here...
        pass

    def increment(self):
        # set self.current = next item for processing
        # when items are exhausted, set self.current=None
        pass

    def log_progress(self):
        if self.current is None:
            os.remove(self.logfile)
        else:
            with open(self.logfile, 'w') as logfile:
                logfile.write(json.dumps([["current","key-xyz"],
                                          [self.current,self.val_abc]]))

    def resume(self):
        try:
            with open(self.logfile, 'r') as logfile:
                content = logfile.read()
        except IOError:
            return False
        content = json.loads(content)
        content = dict(zip(content[0],content[1]))
        self.current = content['current']
        self.val_abc = content['key-xyz']
        return True

if __name__ == "__main__":
    task_object = RepeatingTask("first_item_to_process","/path/to/logfile")
    if task_object.resume():
        print "Resuming progress, current:", task_object.current
    else:
        print "Starting freash, current:", task_object.current
    while task_object.current is not None:
        task_object.page()
        # do some work
        print "Next:", task_object.current


texts:
Find nCr for given n and r.

  Input:

  First line contains no of test cases T, for every test case 2
  integers as inputs (n,r).

  Output:

  Compute and print the value in separate line. Modulus your
  output to 10^9+7. If n

  Constraints:

  1<=T<=50

  1<=n<=1000

  1<=r<=800

  Example:

  Input:

  1

  3 2

  Output:

  3

My approach:

import java.util.Scanner;
import java.lang.Math;
import java.math.BigInteger;

class GFG {

    private static int calcBinCoeff (int num, int r) {

        BigInteger numerator = new BigInteger("1");
        int limit = (int)(Math.pow(10,9) + 7);
        BigInteger modulus = new BigInteger(String.valueOf(limit));

        for (int i = num; i > num - r ; i--) {
            BigInteger ind = new BigInteger(String.valueOf(i));
            numerator = numerator.multiply(ind);
        }

        BigInteger fact = new BigInteger("1");

        for (int i = 2; i <= r; i++) {
            BigInteger elem = new BigInteger(String.valueOf(i));
            fact = fact.multiply(elem);
        }

        BigInteger ans = (numerator.divide(fact)).mod(modulus);

        return ans.intValue();
    }

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

            while (numTests-- > 0) {
                int num = sc.nextInt();
                int r = sc.nextInt();

                System.out.println(calcBinCoeff(num, r));
            }
        }

    }
}

I have the following questions with regards to the above code:

1.Is there a smarter way to approach this question?

How can I improve the space and time complexity of the given question?
Have I gone too overboard by using BigInteger Library for this question?

Reference


texts:
I have this JavaScript function which checks if the format has 'yyyy' and replaces 'yy' with 'y':

function validateDateFormat(format) {
    if(format.indexOf("yyyy") != -1)
     return format.replace(/yy/g, 'y');
     else return format;
}

I feel like it can be simplified further. Can someone help me to refactor/optimize it?


texts: Check if all lotto numbers are covered in input

texts:
Each ticket for the Pick-10 lotto has 10 unique numbers ranging from 1 to 99. Suppose you buy a lot of tickets and like to have them cover all numbers from 1 to 99. Write a program that reads the ticket numbers from a file and checks whether all numbers are covered. Assume the last number in the file is 0. Suppose the file contains the numbers:

80 3 87 62 30 90 10 21 46 27
12 40 83 9 39 88 95 59 20 37
80 40 87 67 31 90 11 24 56 77
11 48 51 42 8 74 1 41 36 53
52 82 16 72 19 70 44 56 29 33
54 64 99 14 23 22 94 79 55 2
60 86 34 4 31 63 84 89 7 78
43 93 97 45 25 38 28 26 85 49
47 65 57 67 73 69 32 71 24 66
92 98 96 77 6 75 17 61 58 13
35 81 18 15 5 68 91 50 76
0

Your program should display:

"The tickets cover all numbers"

Suppose the file contains the numbers

11 48 51 42 8 74 1 41 36 53
52 82 16 72 19 70 44 56 29 33
0

Your program should display:

  "The tickets do not cover all numbers"

    import java.util.Scanner;

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

        //Create an array of booleans
        boolean[] neededNumbers = new boolean[99];

        //Prompt input
        System.out.println("Enter your ticket numbers: ");
        int ticketNumber = input.nextInt();

        while (ticketNumber != 0) {
            for (int i = 1; i <= neededNumbers.length; i++) {
                neededNumbers[i] = true;
            }
            ticketNumber = input.nextInt();
        }

        for (int i = 0; i < neededNumbers.length; i++) {
            if (neededNumbers[i] == false) {
                System.out.println("You do not have all the numbers.");
                System.exit(0);
            }
        }
        System.out.println("You have all the numbers.");
    }
    }


texts: Fixing navbar when scrolling beyond a certain number of pixels

texts:
I have written a jquery code, which fixes a navbar header on top of page when a user scrolls down to a certain pixels. But I am not sure whether is this the correct way to do this.

Because this is going to be a majorly used function by all users, it would be better if I can improve it in terms of optimizations and speed.

What basically I am doing is removing few classes and adding few classes when that breakpoint reaches.

$(function () {
    $(window).scroll(function (event) {
        var scroll = $(window).scrollTop();

        if(scroll > 130){
            $('#catNavBar').removeClass("navbar-static-top");
            $('#catNavBar').addClass("navbar-fixed-top");
            $('.gbText').addClass('hidden');
            $('.small-logo').removeClass('hidden');
            $('#headerGbCont').css('width', '50px');
        } else{
            $('#catNavBar').addClass("navbar-static-top");
            $('#catNavBar').removeClass("navbar-fixed-top");
            $('.gbText').removeClass('hidden');
            $('.small-logo').addClass('hidden');
            $('#headerGbCont').css('width', '109px');
        }
    });
});

Can you suggest any improvements in this code? Or anything that I am doing wrong that should be avoided?


texts: Implementing my own Integer.toBinaryString(int n) method

texts:
Our senior developer gave us (trainees/jr. developers) a small exercise and that is to make our own Integer.toBinaryString(int n) implementation. This is the answer I came up with. I would just like to hear comments/suggestions/opinions on this. Especially, if there is a way to optimize my answer.

public static String toBinaryString(int n){

 String binary = "";

 if(n == 0) return "0";

 // I know, I'm desperate :(
 if(n == Integer.MIN_VALUE) return "10000000000000000000000000000000";

 if(n < 0){

     // Get the positive equivalent
     int val = n * -1;

     // Convert into binary
     String initial = toBinaryString(val);
     String inverted = "";

     // Get 1's complement
     for(char chars : initial.toCharArray()){
        inverted += String.valueOf(((chars == '1') ? '0' : '1'));
     }

     int carry = 0;

     /*Check least significant bit.
     If 0, simply change it to 1.
     If 1, perform addition of 0b1*/
     if(inverted.charAt(inverted.length()-1) == '1'){

         boolean carriedOver = false;

         for(char chars : new StringBuilder(inverted).reverse().toString().toCharArray()){

             if(carriedOver){
                 binary = chars + binary;
                 continue;
             }

             if(carry > 0){
                 if(chars == '1'){
                     binary = "0" + binary;
                     continue;
                 }else{
                    binary = "1" + binary;
                    carriedOver = true;
                    continue;
                 }
             }

             binary = "0" + binary;
             carry += 1;
         }
     }else{
          StringBuilder sb = new StringBuilder(inverted);
          sb.setCharAt(inverted.length()-1, '1');

          binary = sb.toString();
     }

     return String.format("%32s", binary).replace(" ", "1");
 }

 // Convert to binary
 while(n > 0){
     binary = (n & 1) + binary;
     n /= 2;
 }

 return binary;
 }

If you were our senior developer, would you accept this as a valid answer? Why? Why not?


texts:
Since reading Robert Martin's book "Clean Code" I have been inspired to revisit and refactor some of my code to break it down into succinct methods and small specialised classes.

Given the need to retrieve the NameAttribute off the Name2 property of the TestObject class below...

    public class TestObject
    {
        public string Name1 { get; set; }
        [Name("Address")]
        public string Name2 { get; set; }
    }

I have built a class called PropertyNameAttributeFinder to acheive this.

public class PropertyNameAttributeFinder
{
    #region Fields

    private readonly PropertyInfo _property;
    private NameAttribute _attributeFound;

    #endregion

    #region Construtors

    /// <summary>
    /// Initializes a new instance of the <see cref="PropertyNameAttributeFinder"/> class.
    /// </summary>
    /// <param name="property">The property.</param>
    /// <exception cref="System.ArgumentNullException">property</exception>
    public PropertyNameAttributeFinder(PropertyInfo property)
    {
        if (property == null) throw new ArgumentNullException("property");

        _property = property;
    }

    #endregion

    #region Public Members

    /// <summary>
    /// Checks for attribute.
    /// </summary>
    /// <returns>The current instance for fluid API</returns>
    public PropertyNameAttributeFinder CheckForAttribute()
    {
        SetAttributeIfExists();
        return this;
    }

    /// <summary>
    /// Gets a value indicating whether this instance has found an attribute.
    /// </summary>
    /// <value>
    /// <c>true</c> if this instance has found an attribute; otherwise, <c>false</c>.
    /// </value>
    public bool HasFoundAttribute
    {
        get { return _attributeFound != null; }
    }

    /// <summary>
    /// Gets the AttributeFound that was found.
    /// </summary>
    /// <value>
    /// The AttributeFound.
    /// </value>
    public NameAttribute AttributeFound
    {
        get
        {
            if (!HasFoundAttribute)
            {
                throw new InvalidOperationException("No attribute type was found so cannot be returned. Hint: Use HasFoundAttribute first.");
            }
            return _attributeFound;
        }
    }

    #endregion

    #region Private Members

    private void SetAttributeIfExists()
    {
        _attributeFound = _property.GetAttribute<NameAttribute>();
    }
    #endregion
}

The class will be used as follows...

    [TestMethod]
    public void AttributeFound_WhenCalledAfterCheckAttributeAndPropertyDoesHaveAtrribute_ReturnsInstanceOfAttribute()
    {
        // ARRANGE
        Type testType = typeof(TestObject);
        PropertyInfo property = testType.GetProperty("Name2");

        // ACT
        NameAttribute actual = new PropertyNameAttributeFinder(property)
            .CheckForAttribute()
            .AttributeFound;

        // ASSERT
        Assert.IsNotNull(actual);
    }

Can this class be written better to express it's intent in a clearer manner?

EDIT:
Following request from @Heslacher, here is the code from the extension method called by _property.GetAttribute<NameAttribute>(); in SetAttributeIfExists.

    /// <summary>
    /// Get an attribute for a property
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="propertyInfo"></param>
    /// <returns></returns>
    public static T GetAttribute<T>(this PropertyInfo propertyInfo)
        where T : Attribute
    {
        var attribute = propertyInfo.GetCustomAttributes(typeof(T), false).FirstOrDefault();
        return (T)attribute;
    }

Please note: It is not the code in this extension which I want reviewed, but rather the PropertyNameAttributeFinder class and how calling it reads. I.E. doe the public members clearly reveal the intent of the class.


texts: Using JavaScript's Array.splice with assigning the replacements item as an array

texts:
I've got to delete / replace elements in an array.
For accomplishing these task one usually uses Array.splice().

Problem: Array.splice() expects the replacement items as a comma separated list. But I got the values as an array. I've made this
helper function which makes it possible to use splice with an array instead of single values.

    // Deletes elements in an array and
    // replaces the elements with other
    // values.
    // -- Parameter -------------------
    // 1. Array - The array from which
    // elements shall be deleted.
    // 2. Number - The index at which to
    // start the deletion.
    // 3. Number - The count of elements
    // to delete.
    // 4. Array - The elements to insert
    // into the target array.
    // -- Return ----------------------
    // Array - The deleted elements.

    function replaceArrayElements(
                                   targetArray,
                                   startIndex,
                                   deleteCount,
                                   replacements ) {
    // 1. Parameter of .apply():
    //   Defining the context (this-keyword).
    // 2. Parameter:
    //   a.) Start with the element startIndex.
    //   b.) Delete 3 elements.
    //   c.) Put these elements into the array
    //   as new values.
    //   a.), b.), c.) concated together
    //   into one array. The array is then
    //   used as the parameters of .splice().
    return Array.prototype.splice.apply(
                 targetArray,
                 [startIndex, deleteCount].concat(replacements));
    }

    // -------- TEST ---------------------------------
    var test = [];

    for (var i = 1; i <= 10; i++) {
      test.push(i);
    }

    console.log('Before insert: %o', test);

    var ret =
      replaceArrayElements(test, 5, 3, ['Six', 'Seven', 'Eight']);

    console.log('After insert: %o', test);
    console.log('Return: %o', ret);
    // -- RESULTS -----
    // Before insert: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    // After insert: [1, 2, 3, 4, 5, "Six", "Seven", "Eight", 9, 10]
    // Return: [6, 7, 8]

The function does as expected.
But anyway: If someone knows a better way to accomplish the task then please let me know. The same for improvement suggestions.


texts: (AutoHotkey) Script taking random values from the website

texts:
I made a script that-

Reads numbers (nearly 30,000 different numbers) from a list, and applies the numbers to a specific position in the URL.
Then it searches for the value of 'PHE10' mentioned in the script on the website.
Then it stores the result as a .csv file in this format- 'the number from the list,' 'PHE10,' 'the value of PHE10.'

A typical information displayed on the website looks like this in a tabular form-

Now, the problem is- I wanted the script to take the value of 'PHE10' from the 'Assgn1' column, but the code is taking values at random from the website.
Any suggestions to improve my code and improve its efficiency?
here's the website's source code- https://pastebin.com/Xva4q6eM
Here's the autohotkey code-
SetBatchLines, -1

min := 1 ; Course minimum
, max := 0 ; Course maximun
, limit := 0 ; Record limit (Cero means no limit)
, codeList := A_Desktop "\list.txt" ; List of codes
, results := A_Desktop "\phe10.csv" ; Results file
, out := "Code,Course,Assign 1" "`n" ; Headings of the file
, courses := ["PHE10"] ; Courses
, URL := "https://gradecard.ignou.ac.in/gradecardB/Result.asp?eno=#&program=BSC&hidden_submit=OK"

loop, read, % codeList
{

    if (limit && A_Index >= limit)
    {
        break
    }

    html := getUrl(StrReplace(URL, "#", A_LoopReadline))

    for i,code in courses
    {
        if (RegExMatch(html, "(" code ").+>(\d+)<", match))
        {
            line := A_LoopReadline ","
            if (match)
            {
                if match2 between %min% and %max%
                {
                    line .= match1 "," match2 "`n"
                }
            }
            out .= line
        }
    }

}

loop {
    if (!fileObj := FileOpen(results, "w-"))
    {
        MsgBox, 0x40010, ERROR, Could not update the file, please close any open instance of the document and click OK
    }
    fileObj.Write(out)
    if (!ErrorLevel)
    {
        MsgBox, 0x40040, Finished, Task Completed!
    }
    fileObj.Close()
} until (!ErrorLevel)

getUrl(URL)
{
    whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
    whr.Open("GET", URL, true)
    whr.Send()
    whr.WaitForResponse()
    return whr.ResponseText
}

#SingleInstance, force


texts:
A binary relation \$R\$ on a set \$A\$ is called reflexive if and only if \$R(a, a)\$ for every element \$a \in A\$.

I want to know if there can be any improvements made on the function below to make it more efficient.

def reflexive(R):
    '''
    @param R : set containing homogenous elements
    '''
    result = []
    a = []
    y = []

    for a1, a2 in R:
        if (a1 == a2):
            result.append((a1,a2))
            y.append(a1)

        if (a1 not in a):
            a.append(a1) #contains list of a0

    if (set(a) == set(y)):
        print("Reflexive")
        return (result, True)

    print("Not Reflexive")
    return ([] , False)

Test case:

R2 = reflexive([(1, 3), (1, 5), (3, 1), (3, 5), (7, 5)])

Not Reflexive
[]


texts: Build object with different input, using super-class and sub-class style, Python 3

texts:
I want to model a object of air, the temperature of which can be given in 3 different ways:

if the value is known (assuming the temperature is a constant)
if a curve of the values with different time is known (using interpolation)
if the formula of the temperature vs time is known.

My code is below:

from script.interpolate import interp1d
from importlib import import_module

class Air1:
    # case 1: temperature, which is a constant value, is given in the input.
    def __init__(self, meta: dict):
        self.city = meta['city']
        self.temperature = meta['temperature']

class Air2(Air1):
    # case 2: a curve of temperature vs time is given in meta.
    # times is a list, temperatures is a list.
    # so self.get_temperature is an interpolated function.
    # To get a new temperature, I can use new_temp = self.get_temperature(new_time)
    def __init__(self, meta: dict):
        super().__init__(meta=meta)
        times = meta['times']
        temperatures = meta['temperatures']
        self.get_temperature = interp1d(times, temperatures)

class Air3(Air1):
    # case 3: the formula to calculate temperature from time is known.
    # this formula is implemented in a python file called file_of_fomurla.
    # so self.get_temperature is an imported function.
    # To get a new temperature, I can use new_temp = self.get_temperature(new_time)
    def __init__(self, meta: dict):
        super().__init__(meta=meta)
        file_of_formula = meta['file_of_formula']
        self.get_temperature = import_module(file_of_formula + '.my_function')

One thing I have noticed in my code is that .temperature should only be in Air1, since Air2 and Air3 both just have a function to calculate temperature value based on time. However, like in my code, Air2 and Air3 are sub classes of Air1, but their input meta will not have the key 'temperature'. So this is an error.

Do you have any better way to implement the physics behind into the model. Maybe using some abstract class?


texts:
I wrote a basic Python script that consolidates and customizes several popular adblocking hosts files.  I was interested in making it more efficient if possible, and I'd like to improve my style and best practices.

import urllib.request
import re
import os

os.chdir('C:/Windows/System32/drivers/etc')

# This contains a list of URLs where popular hosts files are located.
sources = [...]

def listDomains(sources):
    domains = set()
    for s in sources:
        lines = list(urllib.request.urlopen(s))
        for l in lines:
            str = l.decode('utf-8')
            if isValid(str):
                d = getDomain(str)
                if isDomestic(d):
                    domains.add(d)
    return domains

def isValid(line):
    match = re.search('^(0\.0\.0\.0|127\.0\.0\.1)', line)
    if match:
        return True
    return False

def getDomain(str):
    return str.split()[1]

def isDomestic(domain):
    match = re.search('\.(com|net)$', domain)
    if match:
        return True
    return False

def makeHostsFile(domains):
    f = open('hosts', 'w')
    for d in domains:
        f.write('0.0.0.0 ' + d + '\n')
    f.close()

makeHostsFile(listDomains(sources))


texts: Assign monthly interest rate based on credit card input

texts:
I have currently been working on a program for a few days now, and I am just about done.  The goal of my program is to ask the user for the amount they still owe on their credit card, and assign an appropriate monthly interest rate.  I have commented the code to make it a bit easier to understand, and I believe it is correct for the most part.  My only issue is I do not believed I have called my two other methods properly in Main.

import java.util.*;

/**
* Creates an account statement for a client of a credit card company based
* on their input.
*/

public class CSCard {

private static double interestRate;
private static double newBalance;
private static double interest;
public static void main(String[] args) {
    Scanner keyboard;
    double priorBalance;
    double addtlCharges;
    double newBalance;
    double minPayment;

    // initialize needed variables here
    keyboard = new Scanner(System.in);

    // make sure that the number entered is a double and if so read it in.
    // if not, use a default value of zero. No error message to the user.
    System.out.print("Type the balance: ");
    priorBalance = keyboard.nextDouble();

    if (keyboard.hasNextDouble() == true) {
        interestRate = 0.0;
    } else {
        interestRate = 0.02;
    }

    // make sure that the number entered is a double and if so read it in.
    // if not, use a default value of zero.  No error message to the user.
    System.out.print("\nType the new charge amount: ");
    addtlCharges = keyboard.nextDouble();

    // perform the calculation of interest, new balance and minimum payment
    newBalance = calculateInterest(priorBalance, addtlCharges);
    minPayment = calculateMinPayment(newBalance);

    // output the resulting statement (DO NOT CHANGE)
    System.out.println("\n");
    System.out.println("CS CARD International Statement");
    System.out.println("===============================");
    System.out.printf("Previous balance:   $%,8.2f\n", priorBalance);
    System.out.printf("Additional charges: $%,8.2f\n", addtlCharges);
    System.out.printf("Interest:           $%,8.2f\n\n", interest);
    System.out.printf("New balance:        $%,8.2f\n\n", newBalance);
    System.out.printf("Minimum payment:    $%,8.2f\n", minPayment);
}

/**
 * This method will take in the previous balance and
 * additional charges and compute the amount of interest.
 * If the priorBalance is 0 or less, the interest is 0.
 * If there was a priorBalance, the interest is 2% of the
 * priorBalance plus the additional charges.
 *
 * @param priorBalance balance before the new charges are added
 * @param addtlCharges charges added this month
 * @return amount of interest to charge
 */
public static double calculateInterest(double priorBalance,
                                       double addtlCharges) {
    // first create a stub and get the input and output working
    // then replace the stub later on with the calculation
    interest = (priorBalance + addtlCharges) * interestRate;
    return interest;
}

/**
 * This method will take in the previous balance and
 * additional charges and compute the minimum payment.
 *          $0.00          for new balance less than $0
 *      new balance        for new balance between $0 and $49.99 (inclusive)
 *         $50.00          for new balance between $50 and $300 (inclusive)
 * 20% of the new balance  for new balance over $300
 *
 * @param balance after interest and charges are added
 * @return minimum payment amount
 */
public static double calculateMinPayment(double balance) {
    // first create a stub and get the input and output working
    // then replace the stub later on with the calculation
    if (newBalance < 0) {
        balance = 0;
    }
    if (newBalance >= 0 && newBalance <= 49.99) {
        balance = newBalance;
    }
    if (newBalance >= 50 && newBalance <= 300) {
        balance = 50.0;
    }
    if (newBalance > 300) {
        balance = (newBalance * 0.2) + newBalance;
    }
    return balance;

}

}


texts: Transform snake_case to camelCase with sed

texts:
I want to convert my_long_variable to myLongVariable in sed.

This works:

echo "my_long_variable" | sed -r 's/(^|_)([a-z])/\U\2/g' | sed -r 's/^(.)/\l\1/g'

Is there a more elegant way to do that with sed?


texts: Removal of jQuery from script to auto-apply coupons from a link

texts:
We are using a small extension that auto-applies coupons from a link.

The extension had pop-up JS based on jQuery:

It was our highest traffic page, in order to increase page speed we were removing unnecessary libraries and jQuery was one of them. So we needed to turn this code into pure JS.

The dev commented:

  As far as I can see, this script performs a very simple task in a very
  complicated way.

  First: there is no need to use fadeIn\fadeOut methods in this case.
  These methods freeze browser in loading moment. We need to use CSS
  transitions and just add opacity.

  Second: there is no need to change top and left params during resize.
  We can use CSS and make the browser do it for us.

He did small changes to CSS of the extension, and final pure JS equivalent is:

My response to the comments asking why both load and DOMContentLoaded are used:

  Yes, there is a reason to use DOMContentLoaded.

  Since until the DOM is built, we can not add events to the elements,
  they simply do not exist.

  For a sample, if I tried to get in global scope
  document.getElementsByClassName("modal-overlay__close"); this
  instruction would return []

  Also, we can not show the popup until all popup styles and popup
  picture are loaded.

  That's why, I use window load event.


texts:
The first version of my solution was wrong (the usage of compile() function), for details see Stack Overflow.

The solution has been fixed and now it works correctly. Another approach is used: my_add.__code__. The questions stayed the same.

I am reading the book: Obi Ike-Nwosu. Inside The Python Virtual Machine and have reached the "Code Objects" chapter. This chapter has all code object fields printed out:

co_argcount = 1
co_cellvars = ()
co_code = b'|\x00d\x01\x16\x00d\x02k\x02r\x1e|\x00d\x03\x16\x00d\x02k\x02r\x1ed\\
x04S\x00n,|\x00d\x01\x16\x00d\x02k\x02r0d\x05S\x00n\x1a|\x00d\x03\x16\x00d\x02k\x02r\
Bd\x06S\x00n\x08t\x00|\x00\x83\x01S\x00d\x00S\x00'
co_consts = (None, 3, 0, 5, 'FizzBuzz', 'Fizz', 'Buzz')
co_filename = /Users/c4obi/projects/python_source/cpython/fizzbuzz.py
co_firstlineno = 6
co_flags = 67
etc...

but there is no explanation how this can be done programatically, so I wrote my own code:

# The explored function
def my_add(a,b):
    first = a
    second = b

    return first + second

def print_co_obj_fields(code_obj):
    # Iterating through all instance attributes
    # and calling all having the 'co_' prefix
    for name in dir(code_obj):
        if name.startswith('co_'):
            co_field = getattr(code_obj, name)
            print(f'{name:<20} = {co_field}')

# The function code object (__code__) usage
print_co_obj_fields(my_add.__code__)

Output

co_argcount          = 2
co_cellvars          = ()
co_code              = b'|\x00}\x02|\x01}\x03|\x02|\x03\x17\x00S\x00'
co_consts            = (None,)
co_filename          = ./source.py
co_firstlineno       = 17
co_flags             = 67
co_freevars          = ()
co_kwonlyargcount    = 0
co_lnotab            = b'\x00\x01\x04\x01\x04\x02'
co_name              = my_add
co_names             = ()
co_nlocals           = 4
co_stacksize         = 2
co_varnames          = ('a', 'b', 'first', 'second')

Have I done this the optimal way? How would you solve this problem?


texts: Leeetcode - Best time to buy and sell stock to get maximum profit

texts:
Question

  Say you have an array for which the ith element is the price of a
  given stock on day i.

  If you were only permitted to complete at most one transaction (i.e.,
  buy one and sell one share of the stock), design an algorithm to find
  the maximum profit.

  Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1)
             and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than
             buying price.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

My Approach is brute force.(Naive approach)
Take each element and iterate through right to see how much profit can be made.

public int maxProfit(int[] prices) {
        int size = prices.length;

        if(size == 0 || size == 1) {
            return 0;
        }

        int maxProfit = 0;
        // Iterate through each right element.
        for(int i =0; i<size; i++) {
            for(int j = i+1; j<size; j++) {
                if(prices[j] > prices[i]) {
                    int diff = prices[j] - prices[i];
                    if(diff > maxProfit) {
                        maxProfit = diff;
                    }
                }
            }
        }

        return maxProfit;
    }

How can I improve this from O(n2) . Also, what if more than 1 transactions are allowed to get the profit.


texts:
I am using Merton default model with complex iterative approach.

I have already prepared my R codes but as I am quite new in R, they seem very inefficient, in sense that they runs almost 7 hours. My main problem is my for loop part.

I kindly ask you review my R codes and give any corrections which could make my R code more efficient i.e. they run less time.

I downloaded all data and R code here.

library(plyr)
library(nleqslv)
library(data.table)
library(zoo)
library(TTR)
df5<-read.table(file="df5final.txt", sep="\t", header=T)
df5<-df5[,-8]
NONA <- function(data, columns) {
  completeVec <- complete.cases(data[, columns])
  return(data[completeVec, ])
}
head(df5)
df5<-NONA(df5,9)
nrow(df5)

freq<-ddply(df5, .(id,BSheetyearlag),  "nrow")
df5<-join(df5, freq, by=c("id","BSheetyearlag"))
nrow(df5)
df5<-subset(df5, !nrow < 250)
df5<-subset(df5 , !nrow > 260)
unique(df5$nrow)
nrow(df5)
df5$logret<-log(1+df5$ret)
df5<-as.data.table(df5)
head(df5, n=25)
df5$year<-format(as.Date(df5$date, "%d-%b-%y"), "%Y")
df5$year<-as.numeric(df5$year)

####annual risk free rate
df5$convert<-as.Date(paste("1",df5$BSheetyearlag,sep=""),
                     format="%d %b %Y")
df5$year<-format(df5$convert, "%Y")
rfabsolyear<-read.table(file="riskfreeannual.txt", sep="\t", header=T)
head(rfabsolyear)
tail(df5,n=2)
rfabsolyear<-rfabsolyear[,-2]
library(plyr)
df5<-join(df5, rfabsolyear, by=c("year"))

sp500<-read.table(file="spdata.txt", sep="\t", header=T)
colnames(sp500)<-c("date", "price", "retsp")

sp500<-na.omit(sp500)
sp500$date<-format(as.Date(sp500$date, "%d-%b-%y"), "%d-%b-%y")

head(df5,n=20)
sp500<-na.omit(sp500)
df5<-join(df5, sp500, by=c("date"))

head(df5)
blackscholes <- function(S, X, rf, h, sigma) {
  d1 <- (log(S/X)+(rf+sigma^2/2)*h)/sigma*sqrt(h)
}

df5<-subset(df5,  ! LTD %in% NA )
df5<-subset(df5,  ! STD %in% NA )
df5<-subset(df5,  ! LTD %in% 0 )
df5<-subset(df5,  ! cap %in% 0 )
df5<-subset(df5,  ! STD  %in% -882 )
df5$cap<-df5$cap/1000
df5<-within(df5, LTD05<-df5$STD+0.5*df5$LTD)
nrow(df5)
df5<-within(df5, iterK<-df5$LTD05+df5$cap)
df5$logiterK<-log(df5$iterK)
df5<-as.data.table(df5)

df5[,rollsd:=rollapply(logret, 250, sd, fill = NA, align='right')*sqrt(250), by=c("id", "BSheetyearlag")]
df5[,assetreturn:=c(NA,diff(logiterK)),by=c("id", "BSheetyearlag")]
df5[,rollsdasset:=rollapply(assetreturn, 249, sd, fill=NA, align='right')*sqrt(250), by=c("id", "BSheetyearlag")]
df5[,iterK1:=(cap+LTD05*exp(-rfabsol)*pnorm(blackscholes(iterK,LTD05,rfabsol,   1,rollsdasset[250]))-rollsdasset[250])/pnorm(blackscholes(iterK,LTD05,rfabsol, 1,rollsdasset[250])),by=c("id", "BSheetyearlag")]
head(df5, n=254)
errors<-ddply( df5, .(id, BSheetyearlag), function(x) sum((x$iterK-x$iterK1)^2))
head(errors)
df5<-as.data.frame(df5)
nrow(df5)
head(df5)
df5<-join(df5, errors, by=c("id", "BSheetyearlag"))
df5<-as.data.table(df5)

for ( i in 1:nrow(errors)){
  while(errors$V1[i] >= 10^(-10)) {
    df5<-as.data.table(df5)
    df5[,iterK:= iterK1,by=c("id", "BSheetyearlag")]
    df5[,assetreturn:=c(NA,diff(log(iterK))),by=c("id", "BSheetyearlag")]
    df5[,rollsdasset:=rollapply(assetreturn, 249, sd, fill=NA, align='right')*sqrt(250), by=c("id", "BSheetyearlag")]
    df5[,iterK1:=(cap+LTD05*exp(-rfabsol)*pnorm(blackscholes(iterK,LTD05,rfabsol, 1,rollsdasset[250]))-rollsdasset[250])/pnorm(blackscholes(iterK,LTD05,rfabsol, 1,rollsdasset[250])),by=c("id", "BSheetyearlag")]
    df5<-as.data.frame(df5)
    errors$V1[i]<-sum((df5[df5$V1 %in% errors$V1[i],"iterK"]-df5[df5$V1 %in% errors$V1[i],"iterK1"])^2)
  }
}


texts:
I am making a simulator game "BEE HUNT SIMULATOR" and in that game we have bees and we have to collect pollen from different fields,this is fully command line game that means a typing game so i have made all things that should be there but the main thing is of collecting pollen out of specific storage for that i had tried this-:
import time

global aa
aa = 15 # POWER OF ALL BEES WHICH ADDED IN POLLEN PER FUNCTION
global b
b = 100 # MAX POLLEN STORAGE
global honey
honey = 0 # IGNORE THIS VARIABLE
global pollen
pollen = 0 # POLLEN WHICH ADDS ON EACH FUNCTION AND DID NOT EXCEND THE STORAGE

def add():

    global pollen
    if pollen < b:

        ss = aa + pollen
        if ss > b:

            pollen = b
        elif ss <= b:
            print("Collecting pollen....")
            time.sleep(0.5)
            pollen += aa

    else:
        print("Backpack Full convert it to honey or buy a new backapck.")
while True:

    a = input("Press enter or any key: ")

    if a == "s":
        print(a,b,honey,"",pollen)
        print(type(aa))
    else:
        add()
        print("Pollen Collected-: ",pollen,"/",b)
        time.sleep(1)

That code is fully working and its output is like this-:
Press enter or any key:
Collecting pollen....
Pollen Collected-:  15 / 100
Press enter or any key:
Collecting pollen....
Pollen Collected-:  30 / 100
Press enter or any key:

But i think that this can bored peoples and they can easliy collect pollen so i need more system like this which should not bored peoples and they take enough time to collect pollen.
I am using pyCharm
This code is fully working i only need ideas for collecting pollen , so that players like to do and they dont get bored and they take time to collect pollen.


texts:
I have a method that converts characters to numbers.
It expects a single alphabetical character and returns the equivalent number.
For example, if A is provided it returns 1, for B it returns 2.
If an array is passed, it returns the message "array not accepted".

function characterToNumberCoverter(character) {
  if (Array.isArray(character)) {
    return { status: "failure", message: "array not accepted" };}
  character = character.toUpperCase();
  let myRegExp = /[A-Z]/;
  if (myRegExp.test(character)) {
    return character.charCodeAt(0) - 64;}}

The method returns an object if the input is invalid and an integer if the input is valid. The method is invoked like this:

let intConvertedInt=characterToNumberCoverter('A');

This works fine when the input is valid. What is a better way to handle the use case where an invalid input is passed? Example in which the result will be an object:

    let intConvertedInt=characterToNumberCoverter({});

Are there any other function design patterns that I should be following?


texts:
I am using PHP to get data from a MySQL database, and use the data to drop multiple markers into Google Maps. Please give me some suggestions for my code.

<?php
require_once 'Common/system_start.php';
$sql="select * from tab_mem order by sn desc ";
$result=  mysql_query($sql);
$data=mysql_fetch_assoc($result);
$row=mysql_num_rows($result);

header("Content-type: text/xml");

// Iterate through the rows, adding XML nodes for each

while ($row = @mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);

$newnode->setAttribute("address", $row['address']);

}

 echo $dom->saveXML();
?>

HTML5


texts: Construct a monochromatic graph flipping nodes of the edges

texts:
Given a letter (A or B) representing the color for N nodes of a graph and the set of M edges. Its possible to make all the graph have the letter A by flipping the nodes connected by an edge ?

Example:

  Given the following letter graph:
  A - B

  Its impossible to make all the letters A by flipping the nodes connected by some edge.

  With this graph is possible to make it (Just flip the second edge ):
  A - B - B

To solve this problem i've tried brute force. For every edge the program make two paths (flip the ith edge or not flip). I've tried to memoize some paths that was visited in the search to make it more faster.

Description of the input:

  There will be several test cases. Each test case begins with two integers: N (1 ≤ N ≤ 1000) and M (1 ≤ M ≤ 4000). The next line contains N letters, indicating the starting letter of each node. Then follows M lines, each with two integers, a and b (1 ≤ a,b ≤ N and a != b), describing that there is an edge from a to b. Input ends with EOF.

Description of the output:

  For each test case you should output Y if it is possible to meet the requirements or N otherwise.

Above example input:

2 1
A B
1 2
3 2
A B B
1 2
2 3

Above example output:

N
Y

#include <cstdio>
#include <vector>
#include <utility>
#include <unordered_map>
#include <algorithm>

#define A 0
#define B 1

using edge = std::pair<int, int>;

std::unordered_map<unsigned int , int > visited_state;
std::vector<edge> edge_list;
std::vector<char> node_letters;

bool circuit;

bool isAllA(){
    for (int i = 0; i < node_letters.size(); ++i)
        if(node_letters[i] == B)
            return false;
    return true;
}

//flip the color of the nodes in the eth edge
void flipColors( int e ){
    int u = edge_list[e].first;
    int w = edge_list[e].second;

    node_letters[u] = !node_letters[u];
    node_letters[w] = !node_letters[w];
}

unsigned int getHashState(){
    unsigned int hash1 = 63689 , hash2 = 378551;
    unsigned int hash_state = 0;

    for (int i = 0; i < node_letters.size(); ++i){
        hash_state = hash_state * hash1 + node_letters[i];
        hash1 *= hash2;
    }

    return hash_state;
}

void brute_search( int i ){

    //if its possible ends the recursion
    if ( circuit )
        return;

    unsigned int hash = getHashState();

    if (  visited_state[ hash ] ) {

        //this state was visited on higher depth (dont need to search again)
        if ( visited_state[ hash ] >= i + 1){
            //puts("test repeated problems");
            return;
        }

    }

    visited_state[ hash ] = i + 1;

    if(i == edge_list.size() ){
        circuit = isAllA();
        return;
    }

    //search without change the nodes on the ith edge
    brute_search(i + 1);

    //test with the changes
    flipColors(i);
    brute_search(i + 1);
    flipColors(i);

}

int main ( void ){
    int n,m;

    while( scanf("%d %d ",&n,&m) != EOF ) {

        //init and reset global variables
        circuit = false;
        node_letters.clear();
        edge_list.clear();
        visited_state.clear();

        //read the letter of each node
        for ( int i = 0 ; i < n ; ++i ) {
            node_letters.push_back(getchar() - 'A');
            getchar();//remove space
            //printf("%d\n",c[i]);
        }

        //read the edges
        for (int i = 0; i < m; ++i) {
            int u,w;
            scanf("%d %d",&u,&w);
            edge_list.push_back(edge(u - 1,w - 1));
            //printf("%d %d\n",v[i].first,v[i].second);
        }

        brute_search(0);

        putchar(circuit ? 'Y' : 'N');
        putchar('\n');
    }
}


texts:
My question, REST API and lazy loading objects, didn't receive any answers (or many views), so here is my attempt at the solution.

Problem overview:
My mobile app requests a list of objects through a HTTP REST API but only required a small subset of each item to display items in a list. Other larger properties should not be returned unless requested i.e. in an an object detailed view.

My attempt:
API will act as normal unless a querystring is appended with the fields that are required.

I know that I need to fix the requiredFields.Contains(property.Name) call to ignore case during comparison.

My other concern is that this code is redundant due to my use of Automapper that may include functionality similar to this.

Also, could it be more efficient?

public static Object FilterFields(Object target, Uri requestUri)
    {
        NameValueCollection mapQuery = UriExtensions.ParseQueryString(requestUri);

        IEnumerable<string> requiredFields = null;

        if (mapQuery != null && mapQuery.Get("fields") != null)
            requiredFields = mapQuery.Get("fields").Split(new char[] { ',' });

        if (requiredFields != null)
        {
            foreach (PropertyInfo property in target.GetType().GetProperties())
            {
                if (!requiredFields.Contains(property.Name))
                {
                    property.SetValue(target, null);
                }
            }
        }

        return target;
    }


texts: Extracting matched items from an object which has properties of arrays

texts:
I have a data object like that:

const data = {
  "id": ["1", "2", "3"],
  "name": ["foo", "bar", "baz"],
  "age": [20, 30, 40 ],
  "location": ["pluto", "mars", "jupiter"],
};

Those properties are matched in the array order. I need to create an array which holds all the items like:

[
  { id: '1', name: 'foo', age: 20, location: 'pluto' },
  { id: '2', name: 'bar', age: 30, location: 'mars' },
  { id: '3', name: 'baz', age: 40, location: 'jupiter' }
]

I tried many things including reduce but can't get a decent way of doing this. Here is how I'm creating this result:

let item = {};
let items = [];
const length = Object.values( data)[0].length;

for( i = 0; i < length; i++) {
  Object.entries( data ).forEach( ( [key,value] ) =>
      item = { ...item, [key]: value[i] }
  );

  items = [ ...items, item ];
}

But, the way that I am getting the length, using a for loop really bothers me.


texts: Calculating men's risk of getting coronary heart disease

texts:
I'd like anyone here to help me clean up my code. It's about calculating men's risk of getting coronary heart disease. Here's the link to my method.

private void calculateForMen(){

 // TODO
 // For Men
 // 20–34 years: Minus 9 points.
 // 35–39 years: Minus 4 points.
 // 40–44 years: 0 points.
 // 45–49 years: 3 points.
 // 50–54 years: 6 points.
 // 55–59 years: 8 points.
 // 60–64 years: 10 points.
 // 65–69 years: 11 points.
 // 70–74 years: 12 points.
 // 75–79 years: 13 points.

        // TODO Men Age 20-34
        if( strAge.equals("20 to 34") ){ // Minus 7 points

            // First point
            points = points - 9;

            // Second point
            if( strTotalCholesterol.equals("160 to 199") ){// 4 points
                points = points + 4;
            }
            else if( strTotalCholesterol.equals("200 to 239") ){ // 8 points
                points = points + 7;
            }
            else if( strTotalCholesterol.equals("240 to 279") ){ // 11 points
                points += 9;
            }
            else if( strTotalCholesterol.equals("280 or greater") ){ // 13 points
                points += 11;
            }

            // Third point
            if( strHDL.equals("60 or greater") ) // Minus 1 point
            {
                points -= 1;
            }
            else if( strHDL.equals("40 to 49") ){ // 1 point
                points += 1;
            }
            else if( strHDL.equals("Less than 40") ){ // 2 points
                points += 2;
            }

            // Fourth point
            if( strSBP.equals("130 to 139") ){ // 2 points
                points += 1;
            }
            else if( strSBP.equals("140 to 159") ){ // 3 points
                points += 1;
            }
            else if( strSBP.equals("160 or greater") ){ // 4 points
                points += 2;
            }


texts: Java enum containing a hash map for look up

texts:
I have the below enum. I need to get the description by code. It is working but can it be improved still?

public enum Maps {

    COLOR_RED("ABC", "abc description");

    private final String code;
    private final String description;
    private static Map<String, String> mMap;

    private Maps(String code, String description) {
        this.code = code;
        this.description = description;
    }
    public String getCode() {
        return code;
    }

    public String getDescription() {
        return description;
    }

    public static String getDescriptionByCode(String code) {
        if (mMap == null) {
            initializeMapping();
        }
        if (mMap.containsKey(code)) {
            return mMap.get(code);
        }
        return null;
    }

    private static void initializeMapping() {
        mMap = new HashMap<String, String>();
        for (Maps s : Maps.values()) {
            mMap.put(s.code, s.description);
        }
    }
}


texts:
I'd like to know if the following code is a good implementation of MergeSort? I tried some examples and the code was right, so I guess that the algorithm works correctly.

public static int[] myMerge (int[] array, int[] array2){

    int[] giveback = new int[array.length + array2.length];
    int i = 0;
    int j = 0;

    for (int x = 0; x < giveback.length; x++){

        if (array[i] >= array2[j]){

            giveback[x] = array2[j];
            j++;

        }
        else{

            giveback[x] = array[i];
            i++;
        }

        if (i == array.length){

            x++;
            for(int c = j; c < array2.length; c++){

                giveback[x] = array2[c];
                x++;
            }

            return giveback;
        }

        if (j == array2.length){

            x++;
            for (int b = i; b < array.length; b++){

                giveback[x] = array[b];
                x++;
            }
            return giveback;
        }

    }
    return giveback;
}

public static int[] myMergeSort (int[] array){

    if (array.length <= 1 ){

        return array;
    }

    if (array.length % 2 == 0){

        int[] right = new int[array.length/2];
        int[] left = new int[array.length/2];
        int counter = 0;

        for (int i = 0; i < array.length/2; i++){

            left[i] = array[i];

        }

        for (int j = array.length/2; j < array.length; j++){

            right[counter] = array[j];
            counter++;

        }
        return myMerge(myMergeSort(right),myMergeSort(left));
    }
    else{

        int[] right = new int[array.length/2];
        int[] left = new int[array.length/2];
        int counter2 = 0;

        for(int i = 0; i < array.length/2 +1; i++){

            left[i] = array[i];
        }

        for(int j = array.length/2 +1; j < array.length; j++){

            right[counter2]=array[j];
            counter2++;
        }
        return myMerge(myMergeSort(right),myMergeSort(left));
    }
}


texts: Find the next 8 dates that are Mondays (exclusive of today)

texts:
Any thoughts on improving this method of finding the next 8 Mondays not including today?

var app = angular.module("angularApp", []);
app.controller("appController", function($scope, $filter) {
  $scope.mondays = [];

  var MILLISECONDS_IN_A_DAY = 1000 * 60 * 60 * 24,
    now = new Date(),
    nowTime = now.getTime(),
    mondayOffset = 7 - (now.getDay() - 1);

  for (var i = 0; i < 8; i++) {
    $scope.mondays.push(
      new Date(nowTime + ((MILLISECONDS_IN_A_DAY * mondayOffset) + (MILLISECONDS_IN_A_DAY * 7 * i)))
    );
  };
});
body {
  font-family: verdana;
  font-size: 10pt;
}

{{date | date}}


texts:
I've got this method and I realize that an instance of HttpClass is going to be created for each call to it. While working seemingly OK, I'm considering moving it out and placing it as a private property accessible to each call to the method. There might be other methods making use of it in the future as well. I have no information on how often these calls will occur. (There's a try/catch too but it's omitted for brevity's sake.)

[OperationContract]
[WebGet(UriTemplate = "Poof"]
public async Task<String> GetPoof()
{
  String url = BaseUrl + "poofy";
  using (HttpClient client = new HttpClient())
  {
    client.DefaultRequestHeaders.TryAddWithoutValidation(
      "Authorization", GetAuthorizationSchema());
    HttpResponseMessage message = await client.GetAsync(url);
    return await message.Content.ReadAsStringAsync();
  }
}

What I'm thinking of is something like this:

private HttpClient _Client
private HttpClient Client { get { return _Client ?? GetNewClient(); } }

[OperationContract]
[WebGet(UriTemplate = "Poof"]
public async Task<String> GetPoof()
{
  String url = BaseUrl + "poofy";
  HttpResponseMessage message = await client.GetAsync(url);
  return await message.Content.ReadAsStringAsync();
}

My worry is, though, that the different calls utilizing the same client instance will somehow collide and call huge issues later on, especially if the number of calls per time unit raises beyond a critical level. Should I be worried?