texts: Making a conditionally visible page-up button

texts:
I wanted to make a button that goes to the top of the page but only appears when you're not at the top. There are probably libraries that already do this, but I wanted to make it myself and after some tinkering the following is what I came up with.

There is an occasional annoyance from quickly scrolling up & down with the mouse-wheel which causes jitters/unwanted permanence of the button @ top, but otherwise it works.

setInterval is throttled in consideration for performance. I really get the feeling this could be improved, so I wondered if there is a more idiomatic/better way. What do you think?

var scrollVisible = false;
var userScrolled = false;

window.addEventListener('load', init, false);

function init() {
 window.addEventListener('scroll', function() {
  userScrolled = true;
 }, false);

 setInterval(function() {
     if(userScrolled) {
      if (window.pageYOffset == 0 && scrollVisible) {
       document.getElementById("scrollbutton").style.visibility = 'hidden';
       scrollVisible = false;
      } else if (!scrollVisible) {
       document.getElementById("scrollbutton").style.visibility = 'visible';
       scrollVisible = true;
      }
         userScrolled = false;
     }
 }, 100);
}

function scrollUp() {
 scrollTo(0, 0);
}
body {
 background-color: #272822;
 color: #F3F3F3;
}

#scrollbutton {
 background-color: #666664;
 border-radius: 100%;
 position: fixed;
 visibility: hidden;
 font-size: 1.5em;
    bottom: 0;
    right: 0;
}
#scrollbutton:hover {
 color: #A6E22E;
}
<!DOCTYPE html>

 <link rel="stylesheet" type="text/css" href="test.css"/>

<input type="button" value="&#8679" id="scrollbutton" onclick="scrollUp();"/>

Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.

 Contrary to popular belief, Lorem Ipsum is not simply random text.
    It has roots in a piece of classical Latin literature.


texts: Akka streams: Bidirectional flow that completes the stage when one side is completed

texts:
This is meant to be a bidirectional flow BidiFlow that works exactly as BidiFlow.identity, except that it completes the stage as soon as one of the Flows (in1 -> out1 or in2 -> out2) is completed.

This can be useful to automatically close a connection fully when one of the two sides is closed.

There are a few tricks to prevent object allocation.

import akka.stream.{ Outlet, Inlet, Attributes, BidiShape }
import akka.stream.stage._

object DisconnectBidiFlow {

  def apply[A, B]: GraphStage[BidiShape[A, A, B, B]] = Impl.asInstanceOf[GraphStage[BidiShape[A, A, B, B]]]

  private object Impl extends GraphStage[BidiShape[Any, Any, Any, Any]] {

    val in1: Inlet[Any] = Inlet("DisconnectBidiFlow.in1")
    val out1: Outlet[Any] = Outlet("DisconnectBidiFlow.out1")
    val in2: Inlet[Any] = Inlet("DisconnectBidiFlow.in2")
    val out2: Outlet[Any] = Outlet("DisconnectBidiFlow.out2")

    override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new GraphStageLogic(shape) {
      def map[T](in: Inlet[T], out: Outlet[T]) = {
        val handler = new InHandler with OutHandler {
          override def onPush(): Unit =
            push(out, grab(in))

          override def onPull(): Unit =
            pull(in)
        }
        setHandler(in, handler)
        setHandler(out, handler)
      }
      map(in1, out1)
      map(in2, out2)
    }

    override def shape = BidiShape(in1, out1, in2, out2)
  }
}

Questions:

Can/should the shape be a val
Suggestions for a better name.

It is not really a BidiFlow but just shaped like one. It is a GraphStage[BidiShape[A, A, B, B]]
Should the name contain the purpose (FullDisconnectBidiFlow?)


texts: Is my implementation of insertion sort is correct?

texts:
I'm currently learning about different sorting algorithms and after reading on the concept of the insertion sort of how it's done I've tried to implement it by myself before seeing how it was implemented in the source from which I'm learning.

This was my implementation:

void insertionSort(int arr[])
{
    for(int i = 1; i < SIZE; i++)
    {
        int j = i;
        while(j > 0 && arr[j] < arr[j - 1])
        {
            int swap = arr[j];
            arr[j] = arr[j + 1];
            arr[j + 1] = swap;
            j--;
        }
    }
}

Now I think I've implemented it correctly (not talking about efficient or anything just the algorithm itself), but when I saw the way it was implemented in the course I'm seeing I had a bit of concerns about my implementation because they're really different and I just wanted to make sure my implementation is really an insertion sort algorithm implementation and I didn't done anything else.

Here's the implementation by the source I'm learning from:

void insertionSort(int arr[])
{
  for(int i = 1;, i < SIZE; i++)
  {
      int value = arr[i];
      int j = i - 1;
      int done = 0;
      do
      {
          if (arr[j] > value)
          {
              arr[j + 1] = arr[j];
              j--;
              if (j < 0)
                  done = 1;
          }
          else
          {
              done = 1;
          }
      } while(!done)
      arr[j + 1] = value;
  }
}

Also I would appreciate if you could compare my implementation to the one made by the source I'm learning from, any efficient differences or any other thing you think would worth mentioning.


texts:
Here's my solution to Project Euler problem 40.

import operator
import math

def levels(n):
    return 9 * n * 10 ** (n - 1)

def face_value(i):
    def level_filler(i):
        n = 1
        yield 1

        while i > levels(n):
            yield int(levels(n)/n * 1.0)
            i -= levels(n)
            n += 1

        yield int(math.ceil(i / n * 1.0))

    if i == 1: return 1
    else:
        return sum(level_filler(i))

def d(i):
    j = str(face_value(i))
    k = len(j)
    l = sum(levels(x) for x in xrange(1, k)) + 1
    m = (i-l)%k

    return int(j[m])

# d(1) * d(10) * d(100) * d(1000) * d(10000) * d(100000) * d(1000000)
print(reduce(operator.mul, (d(10**i) for i in xrange(7))))

It answers without building the actual string, and gets the value of d(i) in (quasi-)linear time.

The problem is that it's messy and I feel it's not easy to read. I cannot even find proper names for my variables.

I was wondering if anyone could give me a code review tell me how my ideas are unclear and how can I express them better.

(I tested the code on Python 2.6)


texts: Determining if there is data left after fetching a page of data

texts:
I just faced a problem where I needed to know if extra data was present in a given collection after a Take operation took place. Specifically, this is related to generating @odata.nextLink values in an OData-enabled API only if there is remaining data on the server: the user should not receive a "nextLink" if no more data is available, so that he can properly rely on this value for paging purposes.

The common strategy used in these cases AFAIK is to take one more element on the target, and then check if the results "went past" the limit or not.

For example, when we want to return 10 results:

const int pageSize = 10;
var data = dataSource
    .Take(pageSize + 1)
    .ToList();

var hasRemainingData = data.Count > pageSize;

return new PageResult(
    data: data.Take(pageSize),
    nextLink: hasRemainingData ? CreateNextLink(pageSize) : null);

Now this all felt a bit convoluted to me, so I created an extension method to abstract part of the logic away:

public static (IEnumerable<T> Data, bool HasRemainingData) TakeWithRemainder<T>(this IEnumerable<T> sequence, int count)
{
    if (sequence == null)
        throw new ArgumentNullException(nameof(sequence));

    if (count < 0)
        throw new ArgumentOutOfRangeException(nameof(count));

    var data = sequence.Take(count + 1).ToArray();

    return (new ArraySegment<T>(data, 0, count), data.Length > count);
}

This allows me to clean up the original code significantly, like this:

const int pageSize = 10;
var results = dataSource.TakeWithRemainder(pageSize);

return new PageResult(
    data: results.Data,
    nextLink: results.HasRemainingData ? CreateNextLink(pageSize) : null);

I have a few problems with the extension though, and was wondering if you've got any ideas to make this better:

It materializes the collection

Not sure if there is a way to avoid this since we need to count the elements anyways, but it sounds unexpected to have a Take overload that materializes the results vs the normal one that does not. Right now it seems like I'm violating the Principle of Least Astonishment here. Should I consider an approach that does not materialize the collection, or should I rename it to something else? Other options?

.
It relies on ArraySegment to avoid unneeded iteration

The original code had 2 Take calls in it, which is kinda bad in and of itself. I decided to try using something more decent and went with ArraySegment. Is that intuitive enough to you? I found the code somewhat hard to follow with that in place. Any other options that would still allow me to avoid multiple enumeration are more than welcome.

.
It uses a value Tuple to get the results out

Would also want to see your take on this aspect. The named tuple seemed like the most straightforward way to get both the data and the boolean indicator. This of course "breaks" the fluent chain, as you can't immediately chain extra LINQ methods on top of the whole tuple (which could again be seen as a Principle of Least Astonishment violation). Should I consider something else, like a custom iterator class with an extra property that still implemented IEnumerable<T>? That would allow callers to access the boolean, but still chain more LINQ calls as needed.

At the same time, I wonder if it wouldn't be extra misleading due to the materialization of the collection.

.
HasRemainingData and TakeWithRemainder seem like poor names to me

I'm not liking these 2 names, but I'm failing to thinking of something better for them if I am to keep this approach.


texts:
I have been studying C# for 2 weeks already, I wrote a simple math game but not quite sure how bad it is. I'm just teaching myself to code through internet references. If you could review my work, I would appreciate it.

It is a simple math quiz game
player gets 1 point in every correct answer
the game will be over when the player gives the incorrect answer
it displays total score the player earned, then the score resets.
Is my program reasonable or is there anything i need to improve?

    static void Main(string[] args)
    {
        Console.Write("Please enter your Name: ");
        string userName = (Console.ReadLine());

        Console.WriteLine("Hello " + userName + ", Press ENTER to start the Math Quiz");

        Console.WriteLine();
        Console.ReadKey();

        Start:

        Random numberGenerator = new Random();
        int score = 0;

        while (true)
        {
            int num01 = numberGenerator.Next(1, 11);
            int num02 = numberGenerator.Next(1, 11);

            Console.WriteLine("What is " + num01 + " times " + num02 + " equal to?");

            int Answer = Convert.ToInt32(Console.ReadLine());
            int correctAnswer = num01 * num02;

            if (Answer == num01 * num02)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                ++score;
                int responseIndex = numberGenerator.Next(1, 5);
                switch (responseIndex)
                {
                    case 1:
                        Console.WriteLine("Great!");
                        Console.WriteLine("Your score: " + score);
                        break;
                    case 2:
                        Console.WriteLine("You nailed it!");
                        Console.WriteLine("Your score: " + score);
                        break;
                    case 3:
                        Console.WriteLine("You're correct!");
                        Console.WriteLine("Your score: " + score);
                        break;
                    default:
                        Console.WriteLine("Good Job " + userName + ", Keep it up!");
                        Console.WriteLine("Your score: " + score);
                        break;
                }
                Console.ResetColor();
                Console.ReadLine();
                Console.WriteLine();
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                int responseIndex2 = numberGenerator.Next(1, 5);
                switch (responseIndex2)
                {
                    case 1:
                        Console.WriteLine("Are you even trying? The correct answer is " + correctAnswer);
                        break;
                    case 2:
                        Console.WriteLine("Ooops!!! The correct answer is " + correctAnswer);
                        break;
                    case 3:
                        Console.WriteLine("Oh, come on " + userName + " I know you can do better than that! The correct answer is " + correctAnswer);
                        break;
                    default:
                        Console.WriteLine("Sorry " + userName + ", that's incorrect, the correct answer is " + correctAnswer);
                        break;
                }
                Console.WriteLine(Environment.NewLine + "Game Over, Your score: " + score);
                Console.ResetColor();
                Console.WriteLine();
                Console.ReadLine();
                goto Start;
            }
        }
    }


texts: Custom shapes objects using polymorphism in JavaScript

texts:
I have made the following example and want to know if it properly represents polymorphism in JavaScript.

var customShape = function(){
    this.sides = 4;
    this.length = 5;
    this.perimeter = 4 * this.length;
};

customShape.prototype.noOfSides = function(){
    return ("Total No of Sides = " + 4);
}

var rect = new customShape();
var square = new customShape();
var triangle = new customShape();
triangle.noOfSides = function(){
    return ("Total No of Sides = " + 3);
}

console.log(rect.noOfSides());
console.log(square.noOfSides());
console.log(triangle.noOfSides());

My intention was to make a function noOfSides() which works for different objects.

References:

What is polymorphism, what is it for, and how is it used?
What is polymorphism? Explain with an example?
What is polymorphism in Javascript?
Basic javascript inheritance and polymorphism


texts: Finding capitalized characters and printing their position & ASCII value

texts:
I was trying to find out if a string contained a capitalized letter and if it did I wanted to know the position of the character and its ASCII code. I might have refactored a little to much.

Given an input such as:

(is-capitalized "Meow mEow kItus kaTus")

My function returns:

((18 . 84) (11 . 73) (6 . 69) (0 . 77))

where the car of each sublist is the position in the string and the CDR of the sublist is the character ASCII code.

Given an input such as:

(is-capitalized "omg my cat attacked my face.")

My function returns: NIL

So I guess it works for what I want but I feel like I reinvented so many things.

How can I improve this code?

(defun string-to-ascii (str)
    "Converts string of characters into a list of ascii character codes
       Returns list of ascii character codes"
      (loop
           :for i
         :in (coerce str 'list)
         :collect (char-code i)
         :into numbers
         :finally (return numbers)))

(defun return-capital-positon (list)
  "Returns list of positions where capitalized characters appear"
  (loop
       :for i
     :in list
     :collect (if (and (> i 65) (< i 90))
                  (position i list)
                  )))

(defun capital-hash (list-1 list-2 &key (test 'eql))
  "Return hash table where key: list-1 :pair list-2"
  (assert (= (length list-1)
              (length list-2)))
  (let ((table (make-hash-table :test test :size (length list-1))))
    (map nil (lambda (k v) (setf (gethash k table) v))
         list-1 list-2)
    table))

(defun do-hash (str)
  "Returns a hash table of key: position in string :pair ascii code character"
  (capital-hash
   (return-capital-positon
    (string-to-ascii str))
   (string-to-ascii str)))

(defun hash-table-alist (table)
  "Returns an association list containing the keys and values of hash table TABLE."
  (let ((alist nil))
    (maphash (lambda (k v)
               (push (cons k v)
                      alist)) table) alist))

(defun is-capitalized (str)
  "Returns a list of sublists in the form:
   ((position in string . ascii code of character)...)
   if string contains capitalized characters
   otherwise returns nil"
  (remove 'nil (hash-table-alist (do-hash str)) :key #'first))


texts:
I'm trying to improve my skills with the Task-based Asynchronous Pattern (TAP), by writing simple task-based wrappers around some WMI methods:

void Main()
{
    var driveLetter = "E:";
    var query = string.Format("select * from Win32_Volume WHERE DriveLetter = '{0}'", driveLetter);
    var searcher = new ManagementObjectSearcher(query);
    foreach (ManagementObject volume in searcher.Get())
    {
        // LINQPad Progress Bar
        var pb = new Util.ProgressBar("Formatting:");
        var progress = new Progress<int>(pct => pb.Percent = pct);
        pb.Dump();

        var task = volume.InvokeMethodAsync("Format", new object[] { "FAT", false, 16384, "", false }, progress);
        var result = task.Result; // or var result = await task;
        result.Dump();
    }
}

static class ManagementObjectExtensions
{
    public static Task<object> InvokeMethodAsync(this ManagementObject managementObject, string methodName, object[] args)
    {
        return InvokeMethodAsync(managementObject, methodName, args, null);
    }

    public static Task<object> InvokeMethodAsync(this ManagementObject managementObject, string methodName, object[] args, IProgress<int> progress)
    {
        var watcher = new ManagementOperationObserver();
        var tcs = new TaskCompletionSource<object>();
        object returnValue = null;
        watcher.ObjectReady += (obj, a) => returnValue = a.NewObject.GetPropertyValue("ReturnValue");
        watcher.Completed += (obj, a) => tcs.TrySetResult(returnValue);
        if (progress != null)
        {
            watcher.Progress += (obj, a) => progress.Report(a.Current);
        }

        managementObject.InvokeMethod(watcher, methodName, args);
        return tcs.Task;
    }
}

So far, this seems to work, but it seems almost too easy, and I keep thinking there have to some gotchas I need to watch out for. Am I doing this right?


texts: Python implementation of Conway's Game of Life

texts:
For learning purpose I've started creating my implementation of Conway's Game of Life. I've used numpy to store big array, contating dead and alive cells, then I've apllied Conway's rules, to create mechanics of cells life. To manage grid, and graphics I used pygame module. After many reviews, and rewriting code in many ways, I can't find out what's wrong with it, so I decided to ask you. For example I've tried to make a glider, (as code shows), but he dies after 3 loop cycles. I'd be appreciate for help and tips. Can you help me find out why the cells aren't reproducing? Thanks in advance. Code:

import pygame
import numpy as np

BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
N = 195
WIDTH = 10
HEIGHT = 10

grid = np.zeros(shape=(N, N), dtype=np.int32)
glider = np.array([[0, 0, 1],
                       [1, 0, 1],
                       [0, 1, 1]])
grid[3:6, 3:6] = glider

pygame.init()

WINDOW_SIZE = [980, 980]
screen = pygame.display.set_mode(WINDOW_SIZE)

pygame.display.set_caption("GAME OF LIFE")

done = False

clock = pygame.time.Clock()

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
    for row in range(N):
        for column in range(N):
            color = BLACK
            if grid[row][column] == 1:
                color = GREEN
            pygame.draw.rect(screen, color,
                             [WIDTH * column,
                              HEIGHT * row,
                              WIDTH,
                              HEIGHT])

    newGrid = grid.copy()
    for i in range(N):
        for j in range(N):
            total = grid[(i-1) % N:(i+1) % N, (j-1) % N:(j+1) % N].sum() - grid[i, j]
            if grid[i, j] == 1:
                if(total < 2) or (total > 3):
                    newGrid[i, j] = 0
                else:
                    if total == 3:
                        newGrid[i, j] = 1
    grid = newGrid

    clock.tick(60)
    pygame.display.flip()

pygame.quit()


texts:
I am splitting a csv file where the first 3 columns will be common for all the output files.

input file:

h1 h2 h3 o1 o2 ....
a  b  c  d  e  ....
a1 b1 c1 d1 e1 ....

output files:

o1.csv:

h1 h2 h3 o1
a  b  c  d
a1 b1 c1 d1

o2.csv:

h1 h2 h3 o2
a  b  c  e
a1 b1 c1 e1

So if there are n columns in the input file , the code creates n-3 output files.
However my code is inefficient and is quite slow. It takes 20 seconds for 50000 rows.

old_IFS=$IFS
START_TIME=`date`
DELIMITER=,

# reading and writing headers
headers_line=$(head -n 1 "$csv_file")
IFS=$DELIMITER read -r -a headers <<< $headers_line
common_headers=${headers[0]}$DELIMITER${headers[1]}$DELIMITER${headers[2]}

for header in "${headers[@]:3}"
do
   # writing headers to every file
   echo $common_headers$DELIMITER$header > "$header$START_TIME".csv
done

# reading csv file line by line
i=1
while IFS=$DELIMITER read -r -a row_data
do
    test $i -eq 1 && ((i++)) && continue      # ignoring headers

    j=0

    common_data=${row_data[0]}$DELIMITER${row_data[1]}$DELIMITER${row_data[2]}
    for val in "${row_data[@]:3}"
    do
        #  appending row to every new csv file
        echo $common_data$DELIMITER$val >> "${headers[(($j+3))]}$START_TIME".csv
        ((j++))
    done

done < $csv_file
IFS=${old_IFS}

Any suggestions are appreciated.


texts: Active Directory security groups Search application optimization

texts:
I have a Web API method that returns the  Active Directory security groups for the specific login user. The below code was working fine but it was taking so munch time nearly 45 sec to get the results.

DirectoryEntry root = GetDirectoryEntry()
  using (var groups = root.Children.Find("OU=Sample Security Groups"))
                        {
                            using (var directory = groups.Children.Find("OU=Permissions"))
                            {
                                using (var searcher = new DirectorySearcher(directory))
                                {
                                    searcher.Filter = `filter condition`
                                    var results = searcher.FindAll();
                                    foreach (SearchResult result in results)
                                    {
                                        if (result != null)
                                        {
                                            using (DirectoryEntry group = result.GetDirectoryEntry())
                                            {
                                                items.Add((string)group.Properties["sAMAccountName"].Value);
                                            }
                                        }
                                    }
                                }
                            }
                        }

Update:  In the GetDirectoryEntry method we are creating the connection to the active directory using the username and password.

Can anyone help to optimize the code using Parallel.ForEach or threading etc..


texts: Read a number with commas and decimal dots not using "builtin" support

texts:
I recently had a job interview and messed up on writing an algorithm which, realistically I wouldn't have any trouble with if I wasn't under pressure. I was annoyed and wrote the solution up when I got home in like 5 minutes. My conclusion as to why this happened: I am a bit rusty at writing algorithms so drawing a blank when pressure is applied, therefore I am practicing several questions to get my mind ticking again.

I ran into this question;

"Write a program that reads a number with commas and decimal dots (such as “23,419.34”) and then prints a
number that is half of it. Do not use Double.parseDouble()."

Constraints:

Integer.parseInt only (Assumed)
No use of Arrays/Lists etc.

Here is my solution;

private static void textToNum() {
    System.out.println("Enter Number nnn,xxx,yyy.zz");
    String text = sc.nextLine();

    double res = 0.0;
    StringBuilder bd = new StringBuilder();

    for (int i = 0; i < text.length(); i++) {
        if (Character.isDigit(text.charAt(i))) {
            System.out.println("CA: " + text.charAt(i));
            bd.append(text.substring(i, i+1));
            if (i == text.length() - 1) {
                double d = Math.pow(10, bd.length());
                double temp = Integer.parseInt(bd.toString()) / d;
                res += (temp / 2);
            }
        }
        else if (text.charAt(i) == '.') {
            res = Integer.parseInt(bd.toString()) / 2.0;
            System.out.println("1Res: " + res);
            bd = new StringBuilder();
        }
    }
    System.out.println("Res: " + res);
}

While this solves the problem, I couldn't help thinking there must be a cleaner solution that I was missing.

Any suggestions?


texts: How would I unit test a method that gets data from an RSS feed?

texts:
I have a method that gets an RSS feed using LINQ to XML and returns a collection of an object that grabs only the data I need. There's really only one other method in the class I'm concerned about that you'll see in the sample -- RemoveUrlNoise.

How do I test a method like this or change it to be more testable?

    public IEnumerable<PostDetails> GetPostDetails(string rssUrl)
    {
        XElement feed = XElement.Load(rssUrl);

        var items = from item in feed.Elements("channel").Elements("item")
                    select item;

        return items.Select(item => new PostDetails
            {
                Title = item.Element("title").Value,
                Url = RemoveUrlNoise(item.Element("guid").Value),
                PubDate = item.Element("pubDate").Value
            }).OrderBy(i => i.PubDateAsDateTime).ToList();
    }


texts: WCF wrapper implementing dispose-finalize pattern

texts:
I tried to implement the dispose-finalize pattern on this WCF wrapper.

Do you have any comments about this? Something I missed?

namespace System.ServiceModel
{
    public class WCFClientWrapper<TProxy> : IDisposable where TProxy : class
    {
        private string _endpointAddress;
        public TProxy Service { get; private set; }

        public WCFClientWrapper(string endpointAddress)
        {
            _endpointAddress = endpointAddress;

            var factory = new ChannelFactory<TProxy>(new NetTcpBinding(), new EndpointAddress(endpointAddress));
            Service = factory.CreateChannel();

            (Service as IClientChannel).Faulted += WCFClientWrapper_Faulted;
        }

        private TProxy CreateChannel(string endpointAddress)
        {
            var factory = new ChannelFactory<TProxy>(new NetTcpBinding(), new EndpointAddress(endpointAddress));
            return factory.CreateChannel();
        }

        void WCFClientWrapper_Faulted(object sender, EventArgs e)
        {
            DisposeService();
            Service = CreateChannel(_endpointAddress);
        }

        public void Dispose(bool disposing)
        {
            if (disposing)
            {
                // get rid of managed resources
            }

            DisposeService();
            GC.SuppressFinalize(this);
        }

        private void DisposeService()
        {
            IClientChannel serviceChannel = Service as IClientChannel;
            if (serviceChannel == null)
                return;

            bool success = false;
            try
            {
                (Service as IClientChannel).Faulted -= WCFClientWrapper_Faulted;

                if (serviceChannel.State != CommunicationState.Faulted)
                {
                    serviceChannel.Close();
                    success = true;
                }
            }
            finally
            {
                if (!success)
                {
                    serviceChannel.Abort();
                }
            }
        }

        public void Dispose()
        {
            Dispose(true);
        }

        ~WCFClientWrapper()
        {
            Dispose(false);
        }
    }
}


texts:
I need to run filtering on nested Lists and return a List of items from back

I will put a sample code here with my model

import lombok.Data;

import java.util.List;
import java.util.stream.Collectors;

class Scratch {
    public static void main(String[] args) {

        ParentModel parent = new ParentModel();
        List<Information> informationList = parent.getChildDatas().stream()
                //Filtering null && empty grandchild
                .filter(childData -> childData.getGrandChildDatas() !=null && !childData.getGrandChildDatas().isEmpty())
                .flatMap(childData -> childData.getGrandChildDatas().stream() )
                //Filtering null && empty information
                .filter(grandChild -> grandChild.getInformations() !=null && !grandChild.getInformations().isEmpty())
                .flatMap(grandChild-> grandChild.getInformations().stream())
                //filtering key
                .filter(information -> information.getKey().equals("SOMETHING"))
                .collect(Collectors.toList());

    }

    @Data
    static class ParentModel {
        private List<ChildModel> childDatas;
    }

    @Data
    static class ChildModel {
        private List<GrandChildModel> grandChildDatas;
    }

    @Data
    static class GrandChildModel {
        private List<Information> informations;
    }

    @Data
    static class Information{
        private String info1;
        private String info2;
        private String key;
    }
}

So here you can see, I'm filtering and mapping it back to child streams two times.

Is there alternate way to achieve what I'm trying to do here ??


texts:
I have implemented Visitor and Decorator Pattern in python. I am much used to java design pattern style and hence thought would try in python as well. Could anyone tell me if this is the correct way to do in Python.

Is there any better way to do this?

I have made coffee class and decorating it with Sugar and Milk. I have a visitor that will calculate the tax or the cost. The values are random in TaxVisitor and CostVisitor

from abc import ABC, abstractmethod

class Visitable(ABC):

    @abstractmethod
    def accept(self, visitor):
        pass

class CostVisitor(ABC):

    @abstractmethod
    def cost(self, node):
        pass

class TaxVisitor(CostVisitor):

    def cost(self,node):
        if isinstance(node, Milk):
            return 150
        if isinstance(node, Sugar):
            return 100
        if isinstance(node, Plain_Coffee):
            return 10

class CostVisitor(CostVisitor):

    def cost(self,node):
        if isinstance(node, Milk):
            return 15
        if isinstance(node, Sugar):
            return 10
        if isinstance(node, Plain_Coffee):
            return 1

class Coffee(Visitable):

    @abstractmethod
    def cost(self):
        raise ValueError('Implement')

    @abstractmethod
    def display(self):
        raise ValueError('Implement')

class Plain_Coffee(Coffee):

    def cost(self):
        return 2

    def display(self):
        return 'Coffee'

    def accept(self, visitor):
        return visitor.cost(self)

class CoffeeDecorator(Coffee):

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

    def accept(self, visitor):
        return visitor.cost(self) + self.m_base.accept(visitor)

class Milk(CoffeeDecorator):

    def __init__(self, m_base):
        CoffeeDecorator.__init__(self, m_base)

    def cost(self):
        return self.m_base.cost() + 1

    def display(self):
        return self.m_base.display() + ' milk'

class Sugar(CoffeeDecorator):

    def __init__(self, m_base):
        CoffeeDecorator.__init__(self, m_base)

    def cost(self):
        return self.m_base.cost() + .5

    def display(self):
        return self.m_base.display() + ' sugar'

coffee = Plain_Coffee()
coffee = Milk(coffee)
coffee = Sugar(coffee)

print(coffee.accept(CostVisitor()))

```


texts: Read first column of a space delimited file with Java 8 stream

texts:
Code:

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Created by IDEA on 16/11/14.
 */
public class TestStream {
    private final static Pattern pattern = Pattern.compile("^(\\S+)\\s+");
    public static String firstWord(String s) {
        Matcher matcher = pattern.matcher(s);
        if(matcher.find()) {
            return matcher.group();
        }
        return null;
    }
    public static void main(String[] args) throws Exception {
        List<String> x =  Files.lines(Paths.get("/tmp/testfile"), Charset.defaultCharset()).map(line -> firstWord(line)).collect(Collectors.toList());
        System.out.println(x);

    }
}


texts:
I feel I am over-complicating things, and that there should be a succinct way to achieve this - perhaps using concepts I have not learnt - or some prelude function I have missed out on.

How can I improve this?

data Mat2x2 = MkMat2x2 Integer Integer Integer Integer
  deriving (Show, Eq)

-- modified versions of preludes readParanthesis
readBrackets :: ReadS a -> ReadS a
readBrackets g = mandatory
                 where mandatory r = do
                              ("[", s) <- lex r
                              (x,t)    <- g s
                              ("]", u) <- lex t
                              return (x,u)

readInt :: String -> Maybe (Integer, String)
readInt s = listToMaybe ((reads :: String -> [(Integer, String)]) s)

-- greedy consumption of comma separated values and returns them as list and remaining string, ex:
-- parseCsv readInt "2,3,5,2"
-- ([2,3,5,2],"")
parseCsv :: (String -> Maybe (a, String)) -> String -> ([a], String)
parseCsv f s = case (f s) of
                        Nothing          -> ([], s)
                        Just (x,(',':r)) -> (x : (nextXs r), (nextR r))
                        Just (x,r)       -> ([x], r)
                      where nextXs ns = fst (parseCsv f ns)
                            nextR  ns = snd (parseCsv f ns)

-- reads an arbitrary length vector "[1,2,3,...N]" -> Just [1,2,3...,N]
readVec :: String -> Maybe ([Integer], String)
readVec s = listToMaybe (readBrackets ((:[]) . parseCsv readInt) s) -- note: (:[]) is operator making a list of one element

readVec2 :: String -> Maybe ((Integer, Integer), String)
readVec2 s = case readVec s of
                Just ((a:[b]), r)  -> Just ((a,b), r)
                Just (_, _)        -> Nothing
                Nothing            -> Nothing

read2Vec2 :: String -> Maybe (((Integer, Integer),(Integer,Integer)), String)
read2Vec2 s = case readVec2 s of
                    Nothing          -> Nothing
                    Just ((a,b), r1) -> case readVec2 r1 of
                                            Nothing          -> Nothing
                                            Just ((c,d), r2) -> Just (((a,b),(c,d)), r2)

readMat2x2 :: String -> Maybe (Mat2x2, String)
readMat2x2 s = case listToMaybe (readBrackets (maybeToList . read2Vec2) s) of
                    Nothing                 -> Nothing
                    Just (((a,b),(c,d)), r) -> Just ((MkMat2x2 a b c d), r)


texts:
The following class is used for handling sessions:

class DBHandler implements SessionHandlerInterface {

    protected $exists;

    public function open($save_path, $name) {
        try {
            DBCxn::get();
            return true;
        } catch(PDOException $e) {
            return false;
        }
    }

    public function close() {
        return true;
    }

    public function destroy($session_id) {
        $sth = DBCxn::get()->prepare("DELETE FROM sessions WHERE session_id = ?");
        $sth->execute(array($session_id));
        return true;
    }

    public function gc($maxlifetime) {
        $sth = DBCxn::get()->prepare("DELETE FROM sessions WHERE last_update < ?");
        $sth->execute(array(time() - $maxlifetime));
        return true;
    }

    public function read($session_id) {
        $sth = DBCxn::get()->prepare("SELECT session_data FROM sessions WHERE session_id = ?");
        $sth->execute(array($session_id));
        $rows = $sth->fetchALL(PDO::FETCH_NUM);
        if (count($rows) == 0) {
            $this->exists = "n";
            return '';
        }
        else {
            $this->exists = "y";
            return $rows[0][0];
        }

    }

    public function write($session_id, $session_data) {

        if ($this->exists == "y") {
            $sth = DBCxn::get()->prepare("UPDATE sessions SET session_data = ?, last_update = NOW() WHERE session_id = ?");
            $sth->execute(array($session_data, $session_id));
        }
        if ($this->exists == "n") {

            $sth = DBCxn::get()->prepare("INSERT INTO sessions (session_id, session_data, last_update) VALUES (?, ?, NOW())");
            $sth->execute(array($session_id, $session_data));
        }

    }
}

session_set_save_handler(new DBHandler);

How could this class be improved?


texts: Shopping cart in Rails for karaoke items

texts:
This is my first cart implementation in Rails so I wanted to get some feedback on the correct method to implement it.

First of all, I am storing the data directly in the session because the items in the cart are small.

The idea is that I save a list of integers(ids of the items) in session[]. When a user clicks on "Add to Cart" then the id of that product will be added to the list stored in the rails session variable.

Application controller

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  before_action :set_cart

  private

    def set_cart

      if session[:cart]
        @cart = session[:cart]
      else
        session[:cart] = []
        @cart = session[:cart]
      end

    end

end

Main index file lists entries with "Add to Cart" button for each entry. After the user clicks on "Add to Cart" then the add_item method of CartController is called.

  <% @karaokes.each do |karaoke| %>

      <%= link_to karaoke.name, karaoke_path(karaoke) %>
      <%= link_to "Add to Cart", add_path(karaoke) %>

  <% end %>

Cart Controller looks as follows:

class CartController < ApplicationController

    def add_item

       k = Karaoke.find(params[:id])

       if !@cart.include?(k.id)
        @cart.push(k.id)
       end

       redirect_to cart_path

    end

    def list_items

       @items = @cart

    end

    def remove_item

       @cart.delete_at(params[:index].to_i)

       redirect_to cart_path

    end

end

Finally the cart page looks as follows which lists all the items added to cart.

 Cart

<% @items.each_with_index do |itm, index| %>

        <%= Karaoke.find(itm).name %>
        <%= link_to "Remove", remove_path(index) %>

<% end %>


texts:
I have written a function that fills in the values between points and creates one continuous path (essentially walks between the points) and I'd like some feedback on it's implementation.

If two points are provided that are not "in line" with one another then an error is thrown, as I do not want to support diagonal movement.

Here is an example of the code's input and output:

The route to walk

|_Point_|_X_|_Y_|
| A     | 0 | 0 |
| B     | 2 | 0 |
| C     | 2 | 2 |
| D     | 2 | 4 |
| E     | 4 | 4 |

Diagram of the route in 2D space

  0_1_2_3_4_X
0|A   B
1|
2|    C
3|
4|    D   E
Y|

Calling the walk function

const output = walk(
  { x: 0, y: 0 }, // A
  { x: 2, y: 0 }, // B
  { x: 2, y: 2 }, // C
  { x: 2, y: 4 }, // D
  { x: 4, y: 4 }  // E
);

The output from the walk function

[
  { x: 0, y: 0 }, // A
  { x: 1, y: 0 }, // A -> B
  { x: 2, y: 0 }, // B
  { x: 2, y: 1 }, // B -> C
  { x: 2, y: 2 }, // C
  { x: 2, y: 3 }, // C -> D
  { x: 2, y: 4 }, // D
  { x: 3, y: 4 }, // D -> E
  { x: 4, y: 4 }  // E
]

And the function itself:

function walk(...points) {
  const result = [];
  let lastPoint = null;

  points.forEach((point, index) => {
    if (lastPoint === null) {
      result.push(point);
    } else {
      const direction = {
        x: Math.sign(point.x - lastPoint.x),
        y: Math.sign(point.y - lastPoint.y)
      };

      if (direction.x !== 0 && direction.y !== 0) {
        throw new Error(`points are misaligned at ${index}`);
      } else if (direction.x % 1 !== 0 || direction.y % 1 !== 0) {
        throw new Error(`points must be whole values at ${index}`);
      } else if (direction.x === 0 && direction.y === 0) {
        return;
      }

      const axis = direction.x !== 0 ? 'x' : 'y',
            otherAxis = axis === 'x' ? 'y' : 'x';

      const start = lastPoint[axis] + direction[axis],
            comparator = direction[axis] > 0 ? (a, b) => a <= b : (a, b) => a >= b,
            delta = direction[axis];

      for (let value = start; comparator(value, point[axis]); value += delta) {
        result.push({
          [axis]: value,
          [otherAxis]: point[otherAxis]
        });
      }
    }

    lastPoint = point;
  });

  return result;
}

Things I think could be improved

I don't like how the comparator variable works — it seems a bit of a hack and there's most likely a more mathematical way of working it out.
Are there more "ES6-y" ways of doing what I've done? For example using reduce or similar functions.


texts: Prism 6 Popup Window with EventAggregator to replace a service

texts:
I have a WPF project with Prism 6 and EF6. In my project I have a MainTabModule which has four ViewModels. One of these ViewModels is called ContactViewModel.

The MainTabModule will initialize and resolve my EF context and will also resolve my services. Finally I register my views to the regions in the Shell. This means that all four ViewModels are always active during the entire lifetime of the application (this is intended).

Now comes the challenging part. I've created a custom popup notification class that can pass in an entity. In that popup I can modify the entity and return it. Seems simple enough, however that entity may have foreign keys. Which means I need some way to search for that new foreign entity.

As far as I know I can't dependency inject my own services into the PopupViewModel. But I can use the EventAggregator. So I created two events.

public class ContactSearchEvent : PubSubEvent<string>
{
}

public class ContactCollectionEvent : PubSubEvent<List<Contact>>
{
}

The ContactViewModel (which is already active, see the first a second paragraph) will subscribe to the ContactSearchEvent in the constructor.

    public ContactSearchViewModel(IEventAggregator eventAggregator)
    {
        _eventAggregator = eventAggregator;
        _eventAggregator.GetEvent<ContactSearchEvent>().Subscribe(EventAggregatorSearch);
    }

Then PopupViewModel will subscribe to the ContactCollectionEvent in its constructor.

    public ContactSearchViewModel(IEventAggregator eventAggregator)
    {
        _eventAggregator = eventAggregator;
        _eventAggregator.GetEvent<ContactCollectionEvent>().Subscribe(SetCollection);
    }

The user can now type in the string payload from the Popup Window and search.

    private void Search()
    {
        _eventAggregator.GetEvent<ContactSearchEvent>().Publish(SearchPayload);
    }

The ContactSearchViewModel will now receive the payload then publish to ContactCollectionEvent. Normally it would use the service to search the datbase.

    private void EventAggregatorSearch(string payload)
    {
        _eventAggregator.GetEvent<ContactCollectionEvent>().Publish(new List<Contact>
        {
            new Contact
            {
                FirstName = "Test1"
            },
            new Contact
            {
                FirstName = "Test2"
            },
            new Contact
            {
                FirstName = "Test3"
            }
        });
    }

Back in the PopupViewModel we can now set the collection to the property.

    private void SetCollection(List<Contact> contacts)
    {
        SearchResults = contacts;
    }

This process works. However, I feel like there may be a better way in order to use my services to search the database from a Popup Window in Prism 6. Does anyone have any suggestions on how I can make it simpler or better?


texts: Method injection into TestClass local namespace for automatic generation of Python unittest "test_xxx" methods

texts:
I am writing a series of unit tests in Python 3.5 unittest, which run the exact same test methods on different datasets.  The purpose is to validate proper behavior of each tested function over a range of inputs at different extremes of the likely numerical range of use (large values, small values, badly scaled values, etc.). I would like to construct the TestCase so that it dynamically generates all relevant test_xxx methods for the datasets I've entered.  This way it leaves me less room for typos, and avoids the need to write a raft of new functions every time I add a dataset.

I first wrote the test code with all of my dataset dict objects housed in a simple list, and a single test_the_thing function within my unittest.TestCase subclass.  test_the_thing would iterate over the list of dict datasets, running the test code on each. Two primary problems arose with this approach:

unittest considers the entire execution of test_the_thing to be a single test, and thus I have to search within my datasets to figure out which one failed when the test fails/errors.
When any given test fails/errors in the middle of the iteration, the remainder of the tests are not run.

What I've now got in its place is the following (the code for the entire class can be perused on GitHub):

class TestOpanUtilsVectorProjRejAngle(unittest.TestCase):
    import numpy as np
    from opan.const import OpanEnum

    class DType(OpanEnum):
        V1 = 'V1'
        V2 = 'V2'
        PROJ = 'PROJ'
        REJ = 'REJ'
        ANG = 'ANG'

    class VecType(OpanEnum): # Types of vectors
        O1 = 'O1'   # Both order-one
        LOL = 'LOL' # Both large (large on large)
        SOS = 'SOS' # Both small (small on small)
        LOS = 'LOS' # Large onto small
        SOL = 'SOL' # Small onto large
        BS = 'BS'   # Badly-scaled

    class RelType(OpanEnum): # Type of vector relationship
        NS = 'NS'      # Nonspecific
        PAR = 'PAR'    # Nearly parallel
        NORM = 'NORM'  # Nearly normal
        AP = 'AP'      # Nearly anti-parallel

    namestr = "{0}_{1}"

    # Dict of dicts of data
    data = {
            # Unremarkable vectors with ~order-one components
            namestr.format(RelType.NS, VecType.O1) :
                {DType.V1: np.array([1, 2, 3]),
                 DType.V2: np.array([-1, 3, 8]),
                 DType.PROJ: np.array([-0.391892, 1.175676, 3.135135]),
                 DType.REJ: np.array([1.391892, 0.824324, -0.135135]),
                 DType.ANG: np.float_(25.712002)},
            # ... more data sub-dictionaries are included
            }

    # Template functions
    # Vector projection template
    def template_proj(self, name, data):
        from opan.utils.vector import proj

        v1 = data[self.DType.V1]
        v2 = data[self.DType.V2]
        p = proj(v1, v2)
        for i, t in enumerate(zip(p, data[self.DType.PROJ])):
            self.assertAlmostEqual(*t, delta=1e-6,
                       msg="Test {0}: Index {1}; V1 = {2}; V2 = {3}"
                            .format(name, i, v1, v2))

    # Two more template functions ...

    # Populate the local namespace with the auto-generated
    #  test methods
    for k, d in data.items():
        # Vector projection
        fxnname = "test_Vector_Proj_Good_{0}".format(k)
        fxn = lambda self, k=k, d=d: self.template_proj(k, d)
        locals().update({fxnname: fxn})

    # Populate for the other two template methods by the same approach ...

The test suite runs as expected: if I insert artificial errors in my 'known-good' values in TestOpanUtilsVectorProjRejAngle.data, the respective tests all fail as desired.

Some questions I have include:

Is there a way to achieve this that is better/more secure than locals().update(...)?
Is the lambda the best (or only?) way to encapsulate each function for packaging into the TestOpanUtilsVectorProjRejAngle local namespace?

General recommendations on making the code cleaner, more Pythonic, etc. are also appreciated.


texts: Refactoring a function with different signature

texts:
I call several WebServices which return each a different exception type:

try {
   //calling first WS1 here
} catch (my.package1.FaultWS_Exception e) {
        StringBuilder sb = getMessageFromException(e);
        log(sb);
}

try {
   //calling first WS2 here
} catch (my.package2.FaultWS_Exception e) {
        StringBuilder sb = getMessageFromException(e);
        log(sb);
}

my getMessageFromException simply returns a pretty printed message from the exception.

But as my exceptions are in different packages (each method is in a different WS), I had to create different getMessageFromException() functions for each exception:

private StringBuilder getMessageFromException(my.package1.FaultWS_Exception e) {
    StringBuilder sb = new StringBuilder();
    if (e.getFaultInfo() != null) { //returns my.package1.FaultWS
        sb.append(e.getFaultInfo().getDescfault());
        sb.append("\n");
        sb.append(e.getFaultInfo().getCodefault());
        sb.append("\n");
    } else if (e.getMessage() != null) {
        sb.append(e.getMessage());
        sb.append("\n");
    }
    return sb;
}

private StringBuilder getMessageFromException(my.package2.FaultWS_Exception e) {
    StringBuilder sb = new StringBuilder();
    if (e.getFaultInfo() != null) { //returns my.package2.FaultWS
        sb.append(e.getFaultInfo().getDescfault());
        sb.append("\n");
        sb.append(e.getFaultInfo().getCodefault());
        sb.append("\n");
    } else if (e.getMessage() != null) {
        sb.append(e.getMessage());
        sb.append("\n");
    }
    return sb;
}

This code looks very ugly and a bit repetitive (I have 4 different signatures so far), is there a way to refactor it ? knowing that the Exceptions are defined the same, except from the package name.


texts: Navigate a WebBrowser control asynchronously

texts:
I wrote a little method to navigate a WebBrowser control asynchronously and returns DocumentResult, yet i wanna know if this is a good approach for solving such problem.

Code

SemaphoreSlim _ = new SemaphoreSlim(1);

public async Task<string> NavigateAsync(string url, string targetFrameName = null, byte[] postData = null, string additionalHeaders = null, CancellationToken c = default(CancellationToken))
{
    await _.WaitAsync(c);

    var o = new TaskCompletionSource<string>(null);
    #pragma warning disable 4014
    Task.Factory.StartNew(() =>
    #pragma warning restore 4014
    {
        void OnDocumentCompleted(object x, WebBrowserDocumentCompletedEventArgs e)
        {
            if (e.Url.AbsolutePath != Url.AbsolutePath)
                return;

            DocumentCompleted -= OnDocumentCompleted;

            _.Release();
            o.SetResult(DocumentText);
        }

        Navigate(url, targetFrameName, postData, additionalHeaders);
        DocumentCompleted += OnDocumentCompleted;
    }, c);
    return await o.Task;
}


texts: Computing values with several large numeric vectors

texts:
I have several large numeric vectors (close to 1e6 entries each) and I need to make some computations with their values:

iters=100
iters2=100
set.seed(91)
sampleSubset<-sample(1:1e6, iters)
mR12 <- mR1[sampleSubset]
mRy2 <- mRy[sampleSubset]
mDMDuc12 <- mDMDuc1[sampleSubset]
mDMDc2 <- mDMDc[sampleSubset]
mFR <- matrix(, nrow = 0, ncol = 1)
mFR <- foreach(i=1:iters, .combine=rbind, .packages="foreach") %do% {
          mp2 <- mp[sample(1e6, iters2)]
          mFR3 <- matrix(, nrow = 0, ncol = 1)
          foreach(j=1:iters2, .combine=c) %do% {
             if (mp2[j]>mR12[i]) {
               Frv = 1
             } else if ((mR12[i]<mRy2[i]) | (mR12[i]<0.005) |
                          (mRy2[i]<0.005) | (mDMDuc12[i]<1e4) |
                          (mDMDc2[i]<1e7) | (mDMDc2[i]<mDMDuc12[i])) {
               Frv = NA
             } else if (mp2[j]<=mRy2[i]) {
               Frv = 0
             }  else {
               #points A(Ry,0) and B(R1,DMDuc1)
               #linear: y = mx + b
               #m = -b/Ry
               #m = (mDMDuc1 - b)/R1
               #-b/Ry = (mDMDuc1 - b)/R1 -> -b*R1/Ry = (mDMDuc1 - b) -> b(1-R1/Ry) = mDMDuc1 -> b= mDMDuc1/(1-R1/Ry)
               b = mDMDuc1[i]/(1-mR12[i]/mRy2[i])
               m = -b/mRy2[i]
               DMDp = m*mp2[j] + b
               Frv = (DMDp - 0)/(mDMDc2[i] - 0)
             }
             mFR3 <- rbind(mFR3,matrix(Frv, ncol=1, nrow = 1))
             mFR3
           }
            mFR <- mFR3
            mFR
}
colnames(mFR) <- "mFR"
mFR <- mFR[rowSums(is.na(mFR)) != ncol(mFR),1]

But for large values of iters and iters2, close to 1e6 (as I want to get accurate results), this takes hours. I'd like to reduce the execution time.

Examples to run:

mR1<- matrix(rnorm(1e6), nrow = 1e6, ncol = 1)
mRy<- matrix(rnorm(1e6), nrow = 1e6, ncol = 1)
mDMDuc1 <- matrix(rnorm(1e6), nrow = 1e6, ncol = 1)
mDMDc <- matrix(rnorm(1e6), nrow = 1e6, ncol = 1)
mp<- matrix(rnorm(1e6), nrow = 1e6, ncol = 1)


texts:
I'm writing a wordpress plugin that makes changes to the admin menu. To add some context: The wordpress global $menu is a multidimensional array. Each array in $menu represents a menu item, with the title, url, css classes etc at  specific indexes in the array. the oa_custom_menu option is a similarly structured multidimensional array, but each menu item may have additional indexes in its array to store things like wether the menu item should be hidden or not.

the oa_custom_menu array is only updated when changes are made in my custom admin page. The $menu array may have changed since the last time this happened (e.g. new plugins or themes being activated and adding menu items), so I need to check for any added or removed items in the array.

index 2 in both menu arrays are the URL and the only thing that will consistently be unique. $custom_menu_item[7] is a bool that indicates wether the item should be hidden or not, so we ignore these items if they are hidden..

I hope that all makes sense, I'm not the best at explaining things!

The code I have works perfectly well, it just seems like too many foreach loops to me, but I can not for the life of me figure out a better way to do it. Am I right?

public function compare_menu_arrays() {

    global $menu;
    $custom_menu = get_option('oa_custom_menu') ? get_option('oa_custom_menu') : $menu;

    $menu_sort_keys = array();
    $custom_menu_sort_keys = array();

    foreach ( $menu as $menu_item ) {
        $menu_sort_keys[] = $menu_item[2];
    }

    foreach ( $custom_menu as $custom_menu_item ) {
        if ( empty($custom_menu_item[7]) ) {
            $custom_menu_sort_keys[] = $custom_menu_item[2];
        }
    }

    $new_menu_items     = array_diff( $menu_sort_keys, $custom_menu_sort_keys );
    $removed_menu_items = array_diff( $custom_menu_sort_keys, $menu_sort_keys );

    /*
     * add any new $menu items to our $custom_menu
     */
    if ( !empty($new_menu_items) ) {
        foreach ( $menu as $menu_item ) {
            if ( in_array( $menu_item[2], $new_menu_items ) ) {
                $custom_menu[] = $menu_item;
            }
        }
    }

    /*
     * remove any missing $menu items from our $custom_menu
     */
    if ( !empty($removed_menu_items) ) {
        foreach ( $custom_menu as $index => $custom_menu_item ) {
            if ( in_array( $custom_menu_item[2], $removed_menu_items ) ) {
                unset( $custom_menu[$index] );
            }
        }
    }
}


texts: Addition of two number using array of unequal size

texts:
I tried my level best to get it done. But I would like to have a better solution in all terms.

  Given 2 huge numbers as seperate digits, store them in array and
  process them and calculate the sum of 2 numbers and store the result
  in an array and print the sum.

  Input:

Number of digits:12

9 2 8 1 3 5 6 7 3 1 1 6
Number of digits:9
7 8 4 6 2 1 9 9 7

  Output:

9 2 8 9 2 0 2 9 5 1 1 3

    #include<stdio.h>
    #include<stdlib.h>
    int main()
    {
        int num1[]={9,9,9,9,9,9,9,9,9};
        int num2[]={1,1,1};
        int num1_n=sizeof(num1)/sizeof(int);
        int num2_n=sizeof(num2)/sizeof(int);
        int z=num1_n+num2_n;

        int carry=0;
        int digi=0;
        int i=0;
        int j=0;
        int *num3;
        if(num1_n>num2_n)
        {
            num3=(int*)malloc(sizeof(int)*(num1_n+1));
            for(i=0;i<num1_n+1;i++)
            {
                num3[i]=0;
            }
            for(i=num1_n-1,j=num2_n-1;i>=0 || j>=0 ;i--)
            {
                num3[i+1]=num3[i+1]+num1[i]+num2[j];
                printf("i %d j %d num3[i] %d num1[i] %d num2[i] %d\n",i,j,num3[i],num1[i],num2[j]);
                if(num3[i+1]>9)
                {
                    carry=1;
                    num3[i+1]=num3[i+1]%10;
                }
                if(carry==1)
                {
                    num3[i]=1;
                    carry=0;
                }
                if(j>=0)
                {
                    j--;
                }
            }
        }
        for(i=0;i<num1_n+1;i++)
        {
            printf("%d ",num3[i]);
        }
        return 0;
    }


texts: Removing exact instances of elements in one list from another

texts:
Basically, here's the problem statement:

  Given an IEnumerable<T> source and an IEnumerable<T> exceptions, return an IEnumerable<T> result which contains all of source, without exceptions, only omitting exact instances of a value. I.e.: if a value appears twice in source, but once in exceptions, then result will have that value exactly one time.

Let's take an example:

Exception list:

{ 2, 2, 3, 4, 5}

Source list:

{ 2, 2, 2, 6 }

Result:

{ 2, 6 }

Code:

public static IEnumerable<T> ExceptExact<T>(this IEnumerable<T> source, IEnumerable<T> exceptions)
{
    var tExceptions = new List<T>();
    tExceptions.AddRange(exceptions);

    var result = new List<T>();

    foreach (var el in source)
    {
        if (tExceptions.Contains(el))
        {
            tExceptions.RemoveAt(tExceptions.IndexOf(el));
        }
        else
        {
            result.Add(el);
        }
    }

    return result;
}

Usage:

var a = new List<int> { 2, 3, 5, 4, 2 };
var b = new List<int> { 2, 2, 2, 6 };

var c = b.ExceptExact(a);
var d = a.ExceptExact(b);

Console.WriteLine("A: { " + string.Join(", ", a) + " }");
Console.WriteLine("B: { " + string.Join(", ", b) + " }");
Console.WriteLine("C: { " + string.Join(", ", c) + " }");
Console.WriteLine("D: { " + string.Join(", ", d) + " }");

Output:

A: { 2, 3, 5, 4, 2 }
B: { 2, 2, 2, 6 }
C: { 2, 6 }
D: { 3, 5, 4 }


texts:
Given:

k = {'MASTER_HOST': '10.178.226.196', 'MASTER_PORT': 9999}

I want to flatten into the string:

"MASTER_HOST='10.178.226.196', MASTER_PORT=9999"

This is the ugly way that I'm achieving this right now:

result = []
for i,j in k.iteritems():
    if isinstance(j, int):
        result.append('%s=%d' % (i,j))
    else:
        result.append("%s='%s'" % (i,j))

', '.join(result)

I'm sure my developer colleagues are going to chastize me for this code. Surely there is a better way.


texts:
I think I have this working, but I'm not sure it's completely accurate.

I'm trying to parse Option Symbols. An Option Symbol is made up of 4 parts:

Root Symbol (up to 6 characters)
Expiration Date (yymmdd)
Option Type (1 character)
Strike price (8 digits)

After parsing the following examples, the results should be as follows:

C020216P00035000

Root Symbol ='C'
Expiration Date = datetime.date(2002, 2, 16)
Option Type = P
Strike Price = int(00035000) x .001 = 35.00

P020216C00040000

Root Symbol = 'P'
Expiration Date = datetime.date(2002, 2, 16)
Option Type = C
Strike Price = int(00040000) x .001 = 40.00

SBC020216C00030000

Root Symbol = 'SBC'
Expiration Date = datetime.date(2002, 2, 16)
Option Type = C
Strike Price = int(00030000) x .001 = 30.00

I'm using the following code:

import re
import datetime as dt

opra_symbol = re.compile(r'(^[^0-9]+)').search(OPRA).group()

opra_expiry = dt.datetime.strptime(re.compile(r'\d{2}\d{2}\d{2}').search(OPRA).group(), '%y%m%d').date()

opra_cp = re.compile(r'([CP])').search(re.compile(r'([CP]\d+$)').search(OPRA).group()).group()

opra_price = int(re.compile(r'(\d+)$').search(OPRA).group()) * .001

Is this the best way of getting my results? I'm mostly concerned with the nested regex expression for the Option Type.


texts:
I have a scenario where I need to chain nest XmlElements, and I got a working solution using a recursive function, but  I can't help but feel that it can be made better.

Here's my code so far:

function AppendChild
{
    param
    (
        [string[]]$string,
        $obj,
        [System.Xml.XmlDocument]$XML
    )
    if ($string.Length -gt 0)
    {
        $child = $XML.CreateElement($string[0])
        $child.InnerText = ""
        AppendChild -string ($string | Select -Skip 1) -obj $child -XML $XML
        $obj.AppendChild($child)
    }
}

$string = "this is a somewhat long string" -split " "

$XML = New-Object System.Xml.XmlDocument
$root = $XML.CreateElement($string[0])

AppendChild -string ($string | Select -Skip 1) -obj $root -XML $XML

$root.OuterXml # <this><is><somewhat><long><string></string></long></somewhat></is></this>

Any suggestions?


texts: Simple Makefile to build and run scala program

texts:
I wrote this simple Makefile but it ended up like a spaghetti code. I used basename multiple times. I have a special case for first.spec.scala.run and follow.spec.scala.run and maybe more antipattern code that I am not aware of. I am not happy with my code and I appreciate any feedback or review. Thank you.
SPECS=First Follow
EXAMPLES_PATH=../..
ROOT_PATH=../${EXAMPLES_PATH}
SCALAV=2.12
APSLIB=${ROOT_PATH}/lib/aps-library-${SCALAV}.jar
SCALA_FLAGS=.:${APSLIB}
APS2SCALA=${ROOT_PATH}/bin/aps2scala

all: $(addsuffix Spec.compile, $(SPECS)) $(addsuffix Spec.run, $(SPECS))

%.generate:
    ${APS2SCALA} -DCOT -p ${EXAMPLES_PATH}:${ROOT_PATH}/base $*

%.run:
    @scala -cp ${SCALA_FLAGS} $(basename $@)

GrammarUtil.compile: grammar.generate
    scalac -cp ${SCALA_FLAGS} grammar.scala $(basename $@).scala

first.compile:
    scalac -cp ${SCALA_FLAGS} $(basename $@).scala

follow.compile:
    scalac -cp ${SCALA_FLAGS} $(basename $@).scala

Spec.compile:
    scalac -cp ${SCALA_FLAGS} $(basename $@).scala

FirstSpec.compile: Spec.compile grammar.generate GrammarUtil.compile first.generate first.compile
    scalac -cp ${SCALA_FLAGS} $(basename $@).scala

FollowSpec.compile: Spec.compile grammar.generate GrammarUtil.compile follow.generate follow.compile
    scalac -cp ${SCALA_FLAGS} $(basename $@).scala

clean:
    rm -f *.class grammar.scala first.scala follow.scala


texts: Pointer hover animation for a five-star-rating picker

texts:
I want to shorten my code. You can see the following code i used many function for addClass, removeClass. But it is not usefully. Can do my work in one hover function ? If yes can anyone help me ?

$(document).ready(function() {
    $('.star-one').hover(function() {
       $('.star-one').removeClass('rate-btn-hover');
       var therate = $(this).attr('id');
       for (var i = therate; i >= 0; i--) {
          $('.star-one-' + i).addClass('rate-btn-hover');
       };
    });
    // Red
    $('.star-two').hover(function() {
       $('.star-two').removeClass('rate-btn-hover');
       var therate = $(this).attr('id');
       for (var i = therate; i >= 0; i--) {
          $('.star-two-' + i).addClass('rate-btn-hover');
       };
    });
    // Pink
    $('.star-tree').hover(function() {
       $('.star-tree').removeClass('rate-btn-hover');
       var therate = $(this).attr('id');
       for (var i = therate; i >= 0; i--) {
          $('.star-tree-' + i).addClass('rate-btn-hover');
       };
    });
    });

This is my Demo page: DEMO

I was thinking of simplifying the code like this, but then the CSS animation wouldn't work.

 $(".star").hover(
    function() {
      var prevStars = $(this).prevAll();
      prevStars.toggleClass('rate-btn-hover');
    }
  );

  $("body").on("click", ".star", function() {
    $(this).siblings().removeClass('rate-btn-active');
    var prevStars = $(this).prevAll().addBack();
    prevStars.addClass('rate-btn-active');
  });

This is shorten code demo.

This is old code demo.

You can see old code demo not have any css animation problem.


texts: Sign-up wizard structure seems too repetitive

texts:
I think my current structure is way too repetitive.  I feel like I must be missing something that would easily make this sign up wizard work far better.

Step 1

Step 2

Step 3

        <form ng-submit="registerSubmit()">
        </form>

        <form>

        </form>

        <form>

        </form>

app.controller('registerCtrl', function($scope, $http, $location, FlashService){

    $scope.step1 = {active: true, done:false, todo: false};
    $scope.step2 = {active: false, done:false, todo: true};
    $scope.step3 = {active: false, done:false, todo: true};

    $scope.wiz = function(step){
        $scope.step = step;
        switch (step) {
            case 'step1':
                $scope.step1 = {active: true, done:false, todo: false};
                $scope.step2.active = false;
                $scope.step3.active = false;
                $scope.step2.todo = true;
                $scope.step3.todo = true;
                break;
            case 'step2':
                $scope.step1.active = false;
                $scope.step1.todo = true;
                $scope.step2 = {active: true, done:false, todo: false};
                $scope.step3.active = false;
                $scope.step3.active = false;
                break;
            case 'step3':
                $scope.step1.active = false;
                $scope.step2.active = false;
                $scope.step1.todo = true;
                $scope.step2.todo = true;
                $scope.step3 = {active: true, done:false, todo: false};
                break
            default:
                $scope.step1 = {active: true, done:false, todo: false};
                $scope.step2 = {active: false, done:false, todo: true};
                $scope.step3 = {active: false, done:false, todo: true};
        }
    }

    $scope.registerSubmit = function(){
        $http.post()
            .success(function(data, status, headers, config){
                $scope.step = 'step2';
                $scope.step1 = {active: false, done:true , todo:false}
                $scope.step2.active = true;
                if (data.msg !='') {
                      $scope.msgs.push(data.msg);
                  } else {
                       $scope.errors.push(data.error);
                   }
              }).error(function(data, status){
                      FlashService.show(response.flash);
                    $scope.errors.push(status);
                })
    };
});

I'm worried that the switch and ngclass statements are way more than I need. Is there a simpler way to accomplish this? This just doesn't feel DRY at all.


texts: A simple assembly program to count the number of ones in a register

texts:
I made a simple assembly program to count the number of ones in a register. Since this is basically my first ever, I would like to hear what I can improve or if there are some major flaws in this one:

#PURPOSE:  Simple program which counts the number of ones in the edx register and returns them as a status code

#INPUT:    none

#OUTPUT:   Returns the number of ones as a status code.  This can be viewed
#          by typing
#
#          echo $?
#
#          after running the program

#VARIABLES:
#          %eax holds the carry flag bits and eventually the status code
#          %ebx holds the final return value
#          %ecx stores the loop index
#      %edx stores the register whose digits are examined
#      %edi accumulates the sum of ones

.section .data

.section .text
.globl _start
_start:

movl $255, %edx         # Initialize edx to some value
movl $0, %ecx       # Initialize ecx to zero
movl $0, %edi       # Initialize edi to zero
movl $0, %eax       # Initialize eax to zero

start_loop:
    cmpl $32, %ecx      # Loop runs over all 32 bits of the register
    jge loop_exit
    inc %ecx        # Increase the index variable
    shrl $1, %edx       # Right shift edx so the LSB moves into the carry-flag
    pushf           # Get the flags register
    pop %ax         # Put the least 16 bit of the flags into ax register
    and $01, %ax        # ... but store only the LSB
    add %ax, %di        # Now add the carry bit to the result
    jmp start_loop

loop_exit:
    movl $1, %eax       # We dont need eax any more at this point so we can use it for the syscall
    movl %edi, %ebx     # Return value will be edi
    int $0x80


texts: readable validation with python regex and simple logic

texts:
I have come with such a code for checking IP addresses. But would like to know how clean and good it is from 1 to 10. What I care about are readability and simplicity. Please give me any feedback.
Should I go here with unittests?
import re
import logging

logging.basicConfig(level=logging.ERROR)

pattern = re.compile(r'^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$')

def is_in_bounds(s):
    return int(s) >= 0 and int(s) <= 255

def is_leading_zeros(s):
    if s is not '0':
        return s[0] is not '0'
    return True

def validate_ipv4(ipv4: str, expectFail: bool = False) -> bool:
    logging.info(f"Validating IP '{ipv4}' START.")

    try:
        match = pattern.match(ipv4)
        assert(match)

        groups = match.groups()
        assert(len(groups)==4)

        for s in match.groups():
            assert(is_leading_zeros(s))
            assert(is_in_bounds(s))

        logging.info(f"Validating IP '{ipv4}' SUCCESS.")

    except AssertionError:
        logging.info(f"Validating IP '{ipv4}' FAILED.", exc_info=True)
        if not expectFail:
            raise

if __name__ == '__main__':
    octets = []
    octets.extend(range(0,3))
    octets.extend(range(9,12))
    octets.extend(range(98,102))
    octets.extend(range(198,202))
    octets.extend(range(250,256))

    for i in octets:
        for j in octets:
            for k in octets:
                for l in octets:
                    validate_ipv4(f'{i}.{j}.{k}.{l}')

    octets = []
    octets.extend(range(-3,0))
    octets.extend(range(256, 260))

    exceptions = []

    for i in octets:
        for j in octets:
            for k in octets:
                for l in octets:
                    validate_ipv4(f'{i}.{j}.{k}.{l}', True)


texts:
I need to write some code that checks thousands of websites, to determine if they are in English or not.
Below is the source code. Any improvements would be appreciated.

import nltk
import urllib2
import re
import unicodedata

ENGLISH_STOPWORDS = set(nltk.corpus.stopwords.words('english'))
NON_ENGLISH_STOPWORDS = set(nltk.corpus.stopwords.words()) - ENGLISH_STOPWORDS

STOPWORDS_DICT = {lang: set(nltk.corpus.stopwords.words(lang)) for lang in nltk.corpus.stopwords.fileids()}

def get_language(text):
    words = set(nltk.wordpunct_tokenize(text.lower()))
    return max(((lang, len(words & stopwords)) for lang, stopwords in STOPWORDS_DICT.items()), key=lambda x: x[1])[0]

def checkEnglish(text):
    if text is None:
        return 0
    else:
        text = unicode(text, errors='replace')
        text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore')
        text = text.lower()
    words = set(nltk.wordpunct_tokenize(text))
    if len(words & ENGLISH_STOPWORDS) > len(words & NON_ENGLISH_STOPWORDS):
        return 1
    else:
        return 0

def getPage(url):
    if not url.startswith("http://"):
        url = "http://" + url
    print "Checking the site ", url
    req = urllib2.Request(url)
    try:
        response = urllib2.urlopen(req)
        rstPage = response.read()
    except urllib2.HTTPError, e:
        rstPage = None
    except urllib2.URLError, e:
        rstPage = None
    except Exception, e:
        rstPage = None
    return rstPage

def getPtag(webPage):
    if webPage is None:
        return None
    else:
        rst = re.search(r'<p\W*(.+)\W*</p>', webPage)
        if rst is not None:
            return rst.group(1)
        else:
            return rst

def getDescription(webPage):
    if webPage is None:
        return None
    else:
        des = re.search(r'<meta\s+.+\"[Dd]escription\"\s+content=\"(.+)\"\s*/*>', webPage)
        if des is not None:
            return des.group(1)
        else:
            return des

def checking(url):
    pageText = getPage(url)
    if pageText is not None:
        if checkEnglish(getDescription(pageText)) == 1:
            return '1'
        elif checkEnglish(getPtag(pageText)) == 1:
            return '1'
        elif checkEnglish(pageText) == 1:
            return '1'
        else:
            return '0'
    else:
        return 'NULL'

if __name__ == "__main__":
    f = open('sample_domain_list.txt').readlines()
    s = open('newestResult.txt', "w")
    for line in f[:20]:
        url = line.split(',')[1][1:-1]
        check = checking(url)
        s.write(url + ',' + check)
        s.write('\n')
        print check

#    f.close()
    s.close()


texts: Threshed and Malachi'd: Sieve of Eratosthenes

texts:
I took a little bit from all the answers to my previous question Threshing: Sieve of Eratosthenes.

This may be bordering on code-golfing, but I think that I have a pretty good piece of code here.

Is there any major concepts that I am overlooking, although it still seems super simple?

var upperLimit = 9999;
var primes = new List<long>();
primes.Add(1);
primes.Add(2);
for (var i = 3; i < upperLimit; i+=2)
{
    primes.Add(i);
}

for (var i = 7; i < upperLimit; i+=2)
{
    foreach (var number in primes.ToList())
    {
        if (number == i) { continue; }
        if (number % i == 0) { primes.Remove(number); }
    }
}
primes.ForEach(Console.WriteLine);
Console.WriteLine("The Last Prime is " + primes[primes.Count - 1]);
Console.WriteLine("what are you waiting for? Exit the program!");

Obviously I could start off with all the primes I know by just adding them to start with and then starting my loops higher, but I think that is cheating just a little bit.

Is there any way to make this faster and able to calculate (and store) higher numbers using less memory?


texts: python: less ugly solution to the intersection of 3 lines in 3 dimensional space

texts:
I've tagged this as homework because it was originally a school project, it was accepted but I'm not satisfied with the code.

I've used cramers rule to find the intersection of 3 lines in three dimensional space given the x, y and z coefficients but the code is hideous.

def trinomial():

       print "Trinomials require 3 equations with three variables each."
       firstX = input ("Please enter the coeficcient of X in the first equation: ")
       firstY = input ("Please enter the coefficient of Y in the first equation: ")
       firstZ = input ("Please enter the coefficient of Z in the first equation: ")
       firstA = input ("and what's after the = sign?")
       secondX = input ("Please enter the coefficient of X in the second equation: ")
       secondY = input ("Please enter the coefficient of Y in the second equation: ")
       secondZ = input ("Please enter the coefficient of Z in the second equation: ")
       secondA = input ("And what's after the = sign?")
       thirdX = input ("Please enter the coefficient of X in the third equation: ")
       thirdY = input ("Please enter the coefficient of Y in the third equation: ")
       thirdZ = input ("Please enter the coefficient of Z in the third equation: ")
       thirdA = input ("And what's after the = sign?")
       D= firstX*secondY*thirdZ+firstY*secondZ*thirdX+firstZ*secondX*thirdY-thirdX*secondY*firstZ-  thirdY*secondZ*firstX-thirdZ*secondX*firstY
       DX = firstA*secondY*thirdZ+firstY*secondZ*thirdA+firstZ*secondA*thirdY-thirdA*secondY*firstZ-thirdY*secondZ*firstA-thirdZ*secondA*firstY
       DY = firstX*secondA*thirdZ+firstA*secondZ*thirdX+firstZ*secondX*thirdA-thirdX*secondA*firstZ-thirdA*secondZ*firstX-thirdZ*secondX*firstA
       DZ = firstX*secondY*thirdA+firstY*secondA*thirdX+firstA*secondX*thirdY-thirdX*secondY*firstA-thirdY*secondA*firstX-thirdA*secondX*firstY
       #the next two if statements evaluate the D's, or determinants, to see if it's an inconsistant or identical systerm
       #if it's not, then it does the math to solve the equation
       if D == 0:
           print "Determinant is 0 evaluate for identical or inconsistant systems."
           if DX ==0 and DY == 0 and DZ == 0:
               print "System is dependant, there are infinite solutions"
               print
           else:
               print "System is inconsistant, there are no solutions"
               print
       if D != 0:
           AX = DX/D
           AY = DY/D
           AZ= DZ/D
       print "the solution to the set of equations is ("+str(AX)+","+str(AY)+","+str(AZ)+")."
       print

I'm sorry for the huge wall of text, the code works, and the solutions are correct, I'd just like to know if there's a neater way of doing this.


texts: Invert n bits beginning at position p of an unsigned integer

texts:
In an attempt to create a function that returns x with the n bits that begin at position p inverted, leaving the others unchanged - following the exercise in K&R - I've come up with the following piece of code.
Still, I find it unclear where to start counting, i.e. the result would be different if starting from the right. I am starting from the left - bit one is the first bit from the left.
unsigned invert(unsigned x, unsigned p, unsigned n)
{
  return x ^ ((~0U >> (p - 1 + (sizeof(int) * CHAR_BIT - p + 1 - n))) << (sizeof(int) * CHAR_BIT - p + 1 - n));
}

Which I'd then simplify to:
unsigned invert(unsigned x, unsigned p, unsigned n)
{
  return x ^ ((~0U >> (sizeof(int) * CHAR_BIT - n)) << (sizeof(int) * CHAR_BIT - p + 1 - n));
}

I'm not performing any boundary checks.
Is this good practice? Is there a cleaner solution?


texts:
I have this code which compares data from two data tables.  It does this by using a primary column and inserting the new record from table2 to table1. This loop continues for a large number of tables. I want to optimize it. Kindly give suggestions.

foreach (DataRow drRow in table2.Rows)
{
    if(!table1.Rows.Contains(drRow["KeyId"]))
    {
        table1.ImportRow(drRow);
    }
}


texts: Transforming http request into linq query

texts:
I wrote something that has probably done thousands of times:
a function that takes a parsed http query as input and return a linq query.

Any input is appreciated.

public IList<Lead> GetLeads(NameValueCollection nvc)
{
    IQueryable<MyContext> queryBase = QueryBase();

    foreach (string key in nvc)
    {
        const string format = "dd-MM-yyyy";

        if (nvc[key] == "all")
            continue;

        //case where an array of possible values is sent
        const string regex = "\\[.*\\]";

        Expression<Func<MyContext, bool>> predicate = c => false;

        string[] values = nvc[key].Split(',');
        foreach (string value in values)
        {
            Expression<Func<MyContext, bool>> predicateTemp;
            DateTime date;
            switch (Regex.Replace(key, regex, ""))
            {
                case "nature":
                    string value1 = value;
                    predicateTemp =
                        c => c.Typologies.NatureDemande == value1;
                    break;
                case "departementCode":
                    string value2 = value;
                    predicateTemp = c => c.Geographies.DepartementCode == value2;
                    break;
                case "start":
                    String start = value;
                    date = DateTime.ParseExact(start, format, null);

                    DateTime date1 = date;
                    predicateTemp = c => c.Temps.Date >= date1;
                    break;
                case "end":
                    String end = value;
                    date = DateTime.ParseExact(end, format, null);

                    DateTime date2 = date;
                    predicateTemp = c => c.Temps.Date <= date2;
                    break;
                default:
                    predicateTemp =
                        c => true;
                    break;
            }
            predicate = OrElse(predicate, predicateTemp);
        }

        queryBase = queryBase.Where(predicate);
    }

    //query all leads
    IQueryable<Lead> query = (from x in queryBase
                              select new Lead
                                  {
                                      id = Convert.ToInt32(x.Leads.DemandeWeb_FK),
                                      lng = Convert.ToDouble(x.Leads.longitudeClient.Replace(",", ".")),
                                      lat = Convert.ToDouble(x.Leads.latitudeClient.Replace(",", ".")),
                                      temps = Convert.ToInt32(x.Leads.GeolocDureeTrajetDistrib),
                                      distance = Convert.ToInt32(x.Leads.GeolocDistanceRouteDistrib),
                                      nature = x.Typologies.NatureDemande,
                                      type = x.Distributeurs.DistribType,
                                      reseau = x.Distributeurs.ReseauDistributeur,
                                      instance = x.Demands.IdInstance,
                                      distribution = Convert.ToInt32(x.Distributeurs.DistribIdPointDeVente),
                                  });

    return query.ToList();
}


texts: Implementation of a Custom Database Class

texts:
Following Database Class is what I'm using as a wrapper to connect with MySqli in a application, and below the class is how i'm implementing it currently I'm not sure if this is the right way to handle it or how I can further improve.

class Database {
/**
 * @var $conn: type Mysqli
 **/

private $conn = null;
private $stmt = null;

/**
 * @__construct: establishes a new Connection to db
 **/

function __construct() {
    $this->conn = new mysqli(
        DatabaseHelper::DB_HOST,
        DatabaseHelper::DB_USERNAME,
        DatabaseHelper::DB_PASSWORD,
        DatabaseHelper::DB_NAME
    );
}

/**
 * @ret: $conn
 **/
public function connect() {
    return $this->conn ? true : false;
}

public function prepare($query) {
    $this->stmt = $this->conn->prepare($query);
    if ($this->stmt) {
        return true;
    } else {
        return false;
    }
}

public function set_params($sql_str, ...$params) {
    // bind the sql string
    $bind_args = array();
    $bind_args[] = $sql_str;

    foreach ($params as $param_key => $param_val) {
        $bind_args[] = &$params[$param_key]; // pass the reference to bind_Args
    }

    if (call_user_func_array(array($this->stmt, 'bind_param'), $bind_args)) {
        return true;
    } else {
        return false;
    }
}

public function exec_query() {
    $ret = $this->stmt->execute();
    $this->stmt->close();
    return $ret ? $ret : false;
}

public function exec_query_array() {

    $ret = $this->stmt->execute();
    if ($ret) {
        $this->stmt->store_result();
        $response = array();
        while($r = $this->getResultByArray($this->stmt)) {
            $response[] = $r;
        }
        $this->stmt->close();

        return $response;
    } else {
        return false;
    }
}

private function getResultByArray($stmt) {
    if($stmt->num_rows>0) {
        $result = array();
        $md = $stmt->result_metadata();
        $params = array();
        while($field = $md->fetch_field()) {
            $params[] = &$result[$field->name];
        }
        call_user_func_array(array($stmt, 'bind_result'), $params);
        if($stmt->fetch())
            return $result;
    }
    return null;
}}

and accessing it in this way

 public function findUserByMobile($mobile) {
    $db = new Database();
    $query = "SELECT * FROM users WHERE mobile = ?";
    $sql_str = "s";
    if ($db->connect()) {
        if ($db->prepare($query)) {
            if ($db->set_params($sql_str, $mobile)){
                $ret = $db->exec_query_array();
                if ($ret) {
                    return $ret;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
}

This code is also available here.


texts: Roughly removing 'duplicate' photos based on filename

texts:
I quickly wanted a script that'll go through a lot of photos in a folder and only keep one photo per minute (gotta love burst shots on iPhone).

Fortunately, Dropbox names them with a timestamp upon import: I was thus allowed to base this one on the filename (an example filename is '2013-11-06 23.32.19 XXXXXX.jpg').

I was thinking of maybe moving these files to a 'duplicate' folder or something, just didn't have the time to figure it out for now. I only just started Python, and it was definitely fun to have such a tiny assignment done in under 10 minutes :)

Any comments on how I could've done this in a more pretty way is appreciated!

import os
directory = "{pathToPhotos}"

dt_counter = {}
for filename in os.listdir(directory):
    if not filename.endswith('.ini'):
        dt_rounded = filename[:16]
        if dt_rounded in dt_counter.keys():
            dt_counter[dt_rounded] += 1
        else:
            dt_counter[dt_rounded] = 1
        if dt_counter[dt_rounded] > 1:
            os.remove(os.path.join(directory, filename))

Additionally, I was thinking of expanding this due to the many 'duplicate' photos I have (same setting, different photo's) by grouping them in 10 second buckets and creating a GUI or so to show all alternatives and choose one to keep, any tips on where to start with this would also be greatly appreciated!


texts: Program for calculating and ranking scores

texts:
I've recently completed a vanilla JS challenge . It is a method for calculating and ranking scores.
If possible, I would love to make it better. Any suggestions are welcome.
Challenge Directions:
The input array contains a series of objects that hold user scores. Scores are ranked both individually (within the object) as well as against the other score objects to find overall ranking.
MY CODE:

//STEP 1 - CALCULATE TOTAL SCORE & SCORE RANKS FOR EACH OBJECT
function calculateResults(input) {
    return input.map((scoreSeries) => {
        let final_rank = 0;
        calculatedScoreSeries = {...scoreSeries}

        Object.keys(scoreSeries).forEach((key) => {
          if (key !== 'category') {
            final_rank = final_rank + scoreSeries[key]  //Adding up the score.
            calculatedScoreSeries[key] = calculateSourceRank(scoreSeries, key) //calculating the rank
          }})
        calculatedScoreSeries.final_rank = final_rank //adding total_score prop to the new object
        return calculatedScoreSeries
    })
}
//to calculate the ranking of each source
function calculateSourceRank(scoreSeries, key) {
    let rank = 1;
    for (let i = 1; i < Object.keys(scoreSeries).length; i++) {
      if (scoreSeries[Object.keys(scoreSeries)[i]] > scoreSeries[key]) {
        rank++
      }
    }
   return rank
}

//STEP 2 - COMPARE OBJECTS FOR FINAL RANK
function calculateFinalRank(calculatedResults) {
    return calculatedResults.map((calculatedScoreSeries) => {
        let rankedScoreSeries = {...calculatedScoreSeries}
        let rank = 1;
        for (let i = 0; i < calculatedResults.length; i++) {
            if (calculatedResults[i].final_rank > calculatedScoreSeries.final_rank) {
            rank++
            }
          rankedScoreSeries.final_rank = rank
        }
    return rankedScoreSeries
  })
}

let output = calculateFinalRank(calculateResults(input))
console.log(output)

TEST INPUTS W EXPECTED OUTPUTS:

//each object's score sources are ranked (if two are equal they share the higher ranking).
//then all objects are compared for the overall rnking (if two are equal they share the higher ranking)
input = [ // test input 1
    {
    "category":"test3",
    "source1":50,
    "source2":100,
    "source3":30,
    "source4":10,
    "source5":10,
    },

    {
    "category":"test4",
    "source1":100,
    "source2":30,
    "source3":10,
    "source4":10,
    "source5":50,
    },

    {
    "category":"test5",
    "source1":5,
    "source2":10,
    "source3":10,
    "source4":40,
    "source5":5,
    },
    ]

    output = [
    {
    "category":"test3",
    "source1":2
    "source2":1
    "source3":3
    "source4":4
    "source5":4
    "final_rank":1
    },

    {
    "category":"test4",
    "source1":1
    "source2":3
    "source3":4
    "source4":4
    "source5":2
    "final_rank":1
    },

    {
    "category":"test5",
    "source1":4,
    "source2":2,
    "source3":2,
    "source4":1,
    "source5":4,
    "final_rank":3
    },
    ]

    input = [ // test input 2
    {
    "category":"cat1",
    "src1":20,
    "src2":30,
    "src3":40,
    "src4":50,
    "src5":50
    },

    {
    "category":"cat1",
    "src1":10,
    "src2":0,
    "src3":20,
    "src4":20,
    "src5":100
    },
    ]

    output = [
    {
    "category":"cat1",
    "src1":5,
    "src2":4,
    "src3":3,
    "src4":1,
    "src5":1,
    "final_rank":1
    },

    {
    "category":"cat1",
    "src1":4,
    "src2":5,
    "src3":2,
    "src4":2,
    "src5":1,
    "final_rank":2
    },
  ]

BUSINESS LOGIC:
1 - Category will always have at least one 'category'. More than 1 catgeory will be saved as an array under the category key. Category will always be the first key.
2 - each object in the input array will have an equal number of sources (although this number can be any amount)
3 - if a total score is equal to anothers, then they will share the higher ranking (same as individual score ranking)


texts: Rock, Paper, Scissors, Lizard and Spock with OOP

texts:
Today I saw an extremely interesting question on the Rock, Paper, Scissors, Lizard and Spock game. I've decided to take my swing at it and I've written the following OOP implementation:

function RockPaperScissors(name, hard_action, soft_action) {
    this.name = (name + '').toLowerCase();
    this.hard_action = hard_action + '';
    this.soft_action = (soft_action || hard_action) + '';
    this.strengths = {};
    this.weaknesses = {};
}

RockPaperScissors.prototype = {
    getName: function(){
        return this.name;
    },
    addStrength: function(strength) {
        if( !(strength instanceof RockPaperScissors) ) {
            throw new TypeError('A strength must be an instance of RockPaperScissors');
        }

        this.strengths[strength.getName()] = strength;
    },
    getStrengths: function() {
        var strengths = {};
        for(var k in this.strengths)
        {
            strengths[k] = this.strengths[k];
        }
        return strengths;
    },
    addWeakness: function(weakness, soft) {
        if( !(weakness instanceof RockPaperScissors) ) {
            throw new TypeError('A weakness must be an instance of RockPaperScissors');
        }

        this.weaknesses[weakness.getName()] = {
            enemy: weakness,
            soft: !!soft
        };
    },
    getWeaknesses: function() {
        var weaknesses = {};
        for(var k in this.weaknesses)
        {
            weaknesses[k] = this.weaknesses[k];
        }
        return weaknesses;
    },
    getAction(soft){
        return soft? this.soft_action : this.hard_action;
    },
    winsTo: function(enemy) {
        if( !(enemy instanceof RockPaperScissors) ) {
            throw new TypeError('An enemy must be an instance of RockPaperScissors');
        }

        return (enemy.getName() in this.strengths);
    }
};

function RockPaperScissorsGame(){
    this.score = {
        won: 0,
        lost: 0,
        tied: 0
    };
    this.games = 0;
}

RockPaperScissorsGame.prototype = {
    match: function(user, enemy){
        if( !(user instanceof RockPaperScissors) ) {
            throw new TypeError('The user must be an instance of RockPaperScissors');
        }
        if( !(enemy instanceof RockPaperScissors) ) {
            throw new TypeError('The enemy must be an instance of RockPaperScissors');
        }

        this.games++;

        if( user == enemy ) {
            this.score.tied++;
            return 'Tie';
        }

        var userName = user.getName();
        var enemyName = enemy.getName();

        if( user.winsTo(enemy) ) {
            this.score.won++;
            var enemyWeakness = enemy.getWeaknesses()[userName] || {enemy: enemy, soft: false};

            return userName + ' ' + user.getAction(enemyWeakness.soft) + ' ' + enemyName;

        } else {
            this.score.lost++;
            var userWeakness = user.getWeaknesses()[enemyName] || {enemy: enemy, soft: false};

            return enemyName + ' ' + enemy.getAction(userWeakness.soft) + ' ' + userName;
        }
    },
    getMatches: function(){
        return this.games;
    },
    getWins: function(){
        return this.won;
    },
    getLosses: function(){
        return this.lost;
    },
    getTies: function(){
        return this.tied;
    }
};

So far so good. The setup is minimal, allows to extend it to as many as you want (you can add a tornado, a hurricane, a thunder .... anything!).

Here, there's the concept of hard and soft actions. Soft actions may be, for example, the paper wrapping the rock. Hard actions are, for example, the scissor beheading the lizard. You can define if a weakness is soft or hard.

To make it easier, I've also implemented a way to have multiple games and easily start a new one.

It is a good idea, but I'm not 100% happy with its quality. There's something that makes me uneasy.

In terms of overall quality and OOP, what am I doing wrong? What readability improvements can be made?


texts: Code runs slower when executed from ribbon compared to directly in module

texts:
We use third party addin that downloads market data from the internet into a workbook. The addin works with custom functions that begin with CompanyAddin. For instance, a formula in a cell could look like this:

=A1+CompanyAddin(formulaparameters)

My macro (code below) looks for all formulas that contains CompanyAddin. The macro then inserts a comment with the formula as the comment text. The cell then becomes the value without the formula. There are two ways I can execute the sub.

1) I can execute the code directly in the module where I write the code by hitting F5. The sub runs in about 1 second.

2) I can execute the code from the ribbon. Developer -> Macros -> CompanyAddinSave -> click Run. For some reason, the code takes 15 seconds to complete.

I don't understand how the execution time can be so different. I have tried a few things. For intance, from the ribbon, I clicked "Step Into" at which point the code pops up. If I hit F5 immediately after, the code runs at the faster execution.

Sub CompanyAddinSave()

    'Turn off automatic calculations & screen updating significnatly improves performance
    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False

    Dim ws As Worksheet
    Dim datacell As Range
    Dim wb As Workbook
    Set wb = ActiveWorkbook

    Dim sheetarray As Sheets
    Set sheetarray = wb.Sheets(Array("Fun Discount", "Multiples", "EV Calc", "Beta", "Bandaid", "Company Reference", "Input"))

    'First For Loop goes through all sheets in workbook
    'Second For Loop identifies all cells with formulas, tests if cell formula contains "companyaddin"
    'If it does contain "companyaddin", add comment with formula text as the comment text, save as values

    For Each ws In sheetarray
        For Each datacell In ws.Cells.SpecialCells(xlCellTypeFormulas)
            If datacell.Formula Like "*""companyaddin*" Then
                datacell.AddComment datacell.Formula
                datacell.Value = datacell.Value
            End If
        Next datacell
    Next ws

    'clears object variables, restores automatic calculations & screenupdate
    Set ws = Nothing
    Set sheetarray = Nothing
    Set wb = Nothing
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub


texts: How could I reduce repetition with properties/methods?

texts:
I'm serializing instances of a lot of classes (in C# 3.0), and I've found myself writing this:

[DataContract]
public class ModelClass
{
    public static Guid GetID(ModelClass instance) { ... }

    public static T FromID<T>(Guid value) where T : ModelClass { }

    [DataMember] public Guid m_id { get; set; }
}

[DataContract]
public class ConcreteModel: ModelClass
{
    [DataMember]
    public string      m_name;

    // Stuff we don't serialize
    public Sector      m_sector;
    public Theater     m_theater;
    public Weather     m_weather;
    public TerrainType m_terrainType;

    // Link serialized ids to real objects through GetID & FromID
    [DataMember] private Guid m_sectorID
    {
        get { return GetID(m_sector); }
        set { m_sector = FromID<Sector>(value); }
    }

    [DataMember] private Guid m_theaterID
    {
        get { return GetID(m_theater); }
        set { m_theater = FromID<Theater>(value); }
    }

    [DataMember] private Guid m_weatherID
    {
        get { return GetID(m_weather); }
        set { m_weather = FromID<Weather>(value); }
    }

    [DataMember] private Guid m_terrainTypeID
    {
        get { return GetID(m_terrainType); }
        set { m_terrainType = FromID<TerrainType>(value); }
    }
}

ConcreteModel is just one of many (~100) classes that will have some objects that are going to be saved using IDs, but not the whole objects, so we'll have to write that kind of properties a lot of times.

Is there any way of avoiding this? In C++ I'd be using macros, but not in C#...

My main concern here is not writing those properties all over again like 500 times or more. Any idea on how could I avoid that?