texts:
Say you have an array that is "semi-sorted", e.g. something like this:

[7,8,9,10,1,2,3,4,5,6]

Where a part of the end of the sorted array was transferred to the beginning.

Is there a way to still find an element in it in log(n) time?

Here's my solution:

def findVal(arr, val):
    return helper(arr, 0, len(arr) - 1, val)

def helper(arr, start, end, val):
    if (start > end) :
        return False  # empty array

    mid = start + (end - start) // 2

    if (arr[mid] == val):
        return True

    if (mid == 0):
        return False  # 1 element array which is not the value

    rightSorted = arr[mid] <= arr[end]

    if (rightSorted):
        if (val > arr[mid] and val <= arr[end]):
            return helper(arr, mid + 1, end, val)
        else:
            return helper(arr, start, mid - 1, val)

    else:
        if (val < arr[mid] and val >= arr[start]):
            return helper(arr, start, mid - 1, val)
        else:
            return helper(arr, mid + 1, end, val)

I guess you could also do this with a simple while loop instead of recursion.


texts:
I am writing a method to synchronize the local Core Data entities with a remote web service (in this case, Parse.com).

To update changed or created objects, I fetch all where the updatedAt date property is larger than the last local sync date. So far, so good.

But I am struggling with the deletion of local objects that have been removed on the server. My current approach is the following. This however seems quite expensive to me (\$O(r*l)\$ in the worst case, if I recall correctly). Is there any way to reduce the two loops?

PFQuery *idQuery = [PFQuery queryWithClassName:@"Product"];
[idQuery selectKeys:@[]];
NSArray *allRemote = [idQuery findObjects];
NSArray *allRemoteIds = [allRemote valueForKey:@"objectId"];

NSArray *allLocal = [Product all];
for(Product *p in allLocal) {
    BOOL shouldDelete = YES;
    for(NSString *remoteId in allRemoteIds) {
        if([remoteId isEqualToString:p.productId]) {
            shouldDelete = NO;
            break;
        }
    }

    if(shouldDelete) {
        [p delete];
    }
}


texts: Create new DataFrame containing mean information

texts:
I have a dataframe with the columns "Action", "Filt" and "Val" which measure the resulting error of filtering an action. I want to calculate the mean of the error for each "Action" and "Filt". Currently, I do this by iterating through each combination of "Action" and "Filt". However, I'm afraid the slicing is taking up more time than I would like.

import pandas as pd

in_dat = [
    ("run", "raw", 1),
    ("run", "deep", 1),
    ("jump", "raw", 2),
    ("jump", "deep", 2),
    ("run", "raw", 2),
    ("run", "deep", 2),
    ("jump", "raw", 3),
    ("jump", "deep", 3)

]

all_err = pd.DataFrame(in_dat, columns=("action", "filt", "val"))

mean_vals = []

for act in tuple(all_err.action.unique()):
    for filt in tuple(all_err.filt.unique()):
        mean_val = all_err[(all_err.action == act) & (all_err.filt == filt)].val.mean()
        mean_vals.append((act, filt, mean_val))

mean_err = pd.DataFrame(mean_vals, columns=("Action", "Filt", "Error"))

This gives the result of mean_err being:

  Action  Filt  Error
0    run   raw    1.5
1    run  deep    1.5
2   jump   raw    2.5
3   jump  deep    2.5

What's a faster way to do this with Pandas and getting a similar result?


texts: Generating a warning when I/O size limit is exceeded

texts:
A function is doing IO operation . If the IO reaches a size more than warning limit storage array will send the event to host. The same function will fetch the event.

I have used the verb-noun pattern and the name of the function is as below.

  "Get-SoftAlertAfterRunIO"

It is not making sense as it is not only getting, it is also generating.

Another name I can use is:

  Generate-SoftAlert

But it is not an approved verb. What could be the equivalent verb for generate?

Or is there any good name to reflect the behavior of this code.

The full code is given below

    function Generate-SoftAlert  {
    param
    (
        $VolumeObject,
        $Size
    )

    $Path = $VolumeObject.Path
    $IOTimeStamp = StartIO -Path $Path -LimitSizeInGB $Size

    $IOStarttimeInArray = $IOTimeStamp.IOStarttimeInArray
    $IOStarttimeInHost = $IOTimeStamp.IOStartTimeInHost

    $IOEndtimeInArray = $IOTimeStamp.IOEndtimeInArray
    $IOEndtimeInHost = $IOTimeStamp.IOendTimeInHost

    $VolumeName = $VolumeObject.Name
    $IsSoftAlertInArray= Test-SoftAlertInArray -VolumeName $VolumeName -FromTimeStamp $IOStarttimeInArray -ToTimestamp $IOEndtimeInArray

    $DiskNumber = $VolumeObject.DiskNumber
    $SoftAlert = Get-SoftAlertInHost -After $IOStarttimeInHost -Before $IOEndtimeInHost -DiskNumber $DiskNumber
    $IsSoftAlert = ($SoftAlert -ne $null)

    $Message = $SoftAlert.Message
    $IsLogSense = $false
    If($IsSoftAlert -eq $true)
    {
        $IsLogSense = Test-LogSenseMessage -LogMessage $Message -DiskNumber $DiskNumber -thresholdInGb $WarningLimit
    }

    return [pscustomobject]@{
        SoftAlert = $IsSoftAlert
        LogSense = $IsLogSense
        SoftAlertInArray = $IsSoftAlertInArray
    }
}


texts: Work around for querying type of derived class

texts:
I have an application where messages are collected and dispatched to various handlers. Messages are derived from the base class MessageBase, handlers derived from HandleBase, so what typically happens is a handler will receive a  MessageBase pointer. Now, the handlers need to know the derived type of message to determine how to process the message. I'm trying to avoid switch statements based off message types, so here is my work around...

HandleBase will have default virtual methods to handle all message types. Instead of passing the message to the handler, we pass the handler to the message, and the message hooks itself in to the right handler method.

Questions:

Is there a name for this (pattern)?
What are your thoughts? Is this what you would consider a good solution?

Here is the example code, feel free to review as well:

Header.h

    #include <iostream>

    //Use smart enum to define message types
    #define MESSAGE_TYPES \
      ITEM(Start) \
      ITEM(Stop) \
      MORE_MESSAGE_TYPES

    #ifndef MORE_MESSAGE_TYPES
    #define MORE_MESSAGE_TYPES
    #endif

    //Create enum of all message types
    #define ITEM(x) MessageType_##x,
    enum MessageTypes
    {
      MESSAGE_TYPES
      MessageType_COUNT
    };

    template<int X>
    class Message;

    //Forward declare all Message types
    #undef ITEM
    #define ITEM(x) template<> class Message<MessageType_##x>;
    MESSAGE_TYPES

    class HandlerBase
    {
    public:

      //Add default handler methods for all message types
    #undef ITEM
    #define ITEM(x) virtual void Handle(Message<MessageType_##x> *) {std::cout << "Message not handled!\n";}
      MESSAGE_TYPES
    };

    //Test handler class
    class StartHandler : public HandlerBase
    {
    public:

      void Handle(Message<MessageType_Start> *);
    };

    //-- Messages ----------------------------------------------------------
    class MessageBase
    {
    public:

      virtual void Submit(HandlerBase *) = 0;
    };

    #define ADD_SUBMIT_METHOD(x) void Submit(HandlerBase * a_pHandler)\
    {\
      a_pHandler->Handle(static_cast<Message<x>*>(this));\
    }

    template<>
    class Message<MessageType_Start> : public MessageBase
    {
    public:

      ADD_SUBMIT_METHOD(MessageType_Start)
      int GetTime() {return 12;}
    };

    template<>
    class Message<MessageType_Stop> : public MessageBase
    {
    public:

      ADD_SUBMIT_METHOD(MessageType_Stop)
      std::string GetString() {return "System stopped!";}
    };

cpp

    #include "Header.h"

    void StartHandler::Handle(Message<MessageType_Start> * a_pMsg)
    {
      std::cout << "System started at time = " << a_pMsg->GetTime() << '\n';
    }

    int main()
    {
      Message<MessageType_Start> msgStart;
      Message<MessageType_Stop> msgStop;

      MessageBase * pMsgStart = & msgStart;
      MessageBase * pMsgStop = & msgStop;
      StartHandler handler;

      pMsgStart->Submit(&handler);
      pMsgStop->Submit(&handler);

      char t(0);
      std::cin >> t;
    }

Output:

    Started!
    Not handled!


texts: Enforcing a constraint that a user may vote on each post at most once

texts:
I have the following table in a PostgreSQL database:

    creator uuid not null,
    post    uuid not null,
    type    text not null,
    content text not null,
    constraint check_type check
           (type = 'comment' or
               (type = 'vote' and
                   (content = 'up' or
                    content = 'down')))

In order to enforce the constraint that there is no duplicate pair of (creator, post, type) where type = 'vote' (ie. a specific user can only vote on a specific post once) I can either create a unique index like so:

create unique index interactions_index on posts.interactions
    (creator, post, type, content) where type = 'vote';

Or I can query the table on in the server code and do a check there.

My questions:

which one is more efficient, or should I include both for safeguards? How much will having a unique index impact performance (say 100,000 posts @ 1000 likes/post = 100,000,000 database lines)?
I am using this to store "interactions" with a post (ie. likes, comments), is this a good/sustainable way to approach this, or should I be doing something different?


texts: Reorganizing inventory items into a data structure

texts:
I'm currently refactoring some old code of mine that I had done a few years ago, where it takes in two Lists to compare their contents, and then return the mapped contents that were matched. With 750 items for potential needles, and over 25000 items as the haystack, the original code took about 22-25 seconds to process. After a bit of refactoring however I was able to reduce it to just over a second. Is there a way to improve it further?

Here's the original code

Map<String, ArrayList<TreeMap<String, String>>> map = new TreeMap<String, ArrayList<TreeMap<String, String>>>();

String charsToFilter = "[" + Pattern.quote("_-") + "]";

for (int i = 0 ; i < baseDataArray.size() ; i++) {
  String currentProduct = baseDataArray.get(i).get("product_name").replaceAll(charsToFilter, "  ").toLowerCase();

  for (int j = 0 ; j < inventoryArray.size() ; j++) {
      String currentListing = inventoryArray.get(j).get("title").replaceAll(charsToFilter, " ").toLowerCase();

      if (currentListing.contains(currentProduct)) {
          ArrayList<TreeMap<String, String>> currentListingArray = new ArrayList<TreeMap<String, String>>();
          TreeMap<String, String> currentListingMap = new TreeMap<String, String>();

          for (Map.Entry<String, String> keyValue : inventoryArray.get(j).entrySet()) {
              currentListingMap.put(keyValue.getKey(), keyValue.getValue());
          }

          currentListingArray.add(currentListingMap);

          if (map.get(currentProduct) == null) {
              map.put(currentProduct, currentListingArray);
          } else {
              map.get(currentProduct).add(currentListingMap);
          }
      }
  }
}

return map;

And here's the new code:

Map<String, ArrayList<TreeMap<String, String>>> map = new TreeMap<String, ArrayList<TreeMap<String, String>>>();

String charsToFilter = "[" + Pattern.quote("_-") + "]";

ArrayList<String> productNameArray = new ArrayList<String>();

for (Map<String, String> baseDataItem : baseDataArray) {
    productNameArray.add(baseDataItem.get("product_name")
      .replaceAll(charsToFilter, " ").toLowerCase());
}

for (Map<String, String> inventoryItem : inventoryArray) {

    //moving this to the for loop below increase execution time by 100%
    String processedInventoryItem = inventoryItem.get("title").replaceAll(charsToFilter, " ").toLowerCase();

    for (String productName : productNameArray) {
        if (processedInventoryItem.contains(productName)) {
            ArrayList<TreeMap<String, String>> currentListingArray = new ArrayList<TreeMap<String, String>>();
            TreeMap<String, String> currentListingMap = new TreeMap<String, String>();

            for (Map.Entry<String, String> keyValue :  inventoryItem.entrySet()) {
                currentListingMap.put(keyValue.getKey(),  keyValue.getValue());
            }

            currentListingArray.add(currentListingMap);

            if (map.get(productName) == null) {
                map.put(productName, currentListingArray);
            } else {
                map.get(productName).add(currentListingMap);
            }

            break;
        }
    }
}

return map;

There's some differences such as going from for to foreach loops, but nothing that I can see that would make such a change. Anyone have any thoughts on how to improve it further, or why it has come so far already.


texts:
I need a class that holds a huge amount of data, which should be useable across multiple threads. To avoid copying the data every time, I used a std::shared_ptr. To make it thread-safe I need a mutex to secure the data. But if I'm right, this mutex must be shared too. Since boost::recursive_mutex (and other mutexes I guess) are non-copyable, I put it into a std::shared_ptr too, to make sure the same mutex is used in all threads sharing the same data.

Questions:

Can I use a mutex in a shared_ptr? The implementation is shown below and it works, but I'm unsure, since I didn't find a definite answer elsewhere.
Are the copy-constructor, the assignment-operator and the swap-method correctly (thread-safe) implemented?

SharedData.h:

#ifndef SHAREDDATA_H
#define SHAREDDATA_H

#include <boost/thread/recursive_mutex.hpp>
#include <memory>

class SharedData
{
private:
  std::shared_ptr<float> m_pData;
  std::shared_ptr<boost::recursive_mutex> m_pMutex;

public:
  SharedData(void)
  {
    m_pMutex = std::make_shared<boost::recursive_mutex>();
    m_pData = std::make_shared<float>(1.23456789);
  }

  SharedData(SharedData const &_copyFrom)
  {
    m_pMutex = _copyFrom.m_pMutex;
    boost::recursive_mutex::scoped_lock otherLock(*_copyFrom.m_pMutex);
    m_pData = _copyFrom.m_pData;
  }

  SharedData const & operator=(SharedData const &_copyFrom)
  {
    if (this != &_copyFrom)
    {
      boost::recursive_mutex::scoped_lock myLock(*m_pMutex, boost::defer_lock);
      boost::recursive_mutex::scoped_lock otherLock(*_copyFrom.m_pMutex, boost::defer_lock);
      boost::lock(myLock, otherLock);

      SharedData tmp(_copyFrom); //Copy-and-swap
      this->swap(tmp);
    }

    return *this;
  }

  ~SharedData(void)
  {
  }

  void swap(SharedData &_other)
  {
    boost::recursive_mutex::scoped_lock myLock(*m_pMutex, boost::defer_lock);
    boost::recursive_mutex::scoped_lock otherLock(*_other.m_pMutex, boost::defer_lock);
    boost::lock(myLock, otherLock);

    std::swap(m_pData, _other.m_pData);
    std::swap(m_pMutex, _other.m_pMutex);
  }

  //If data is going to be modified and thus needs to be copied
  operator float *()
  {
    boost::recursive_mutex::scoped_lock lock(*m_pMutex);

    if (m_pData.unique() == false)
    {
      SharedData data;
      *this = data;
    }

    return m_pData.get();
  }

  //The data is not modified
  operator float const *() const
  {
    boost::recursive_mutex::scoped_lock lock(*m_pMutex);

    return m_pData.get();
  }

  void reset()
  {
    boost::recursive_mutex::scoped_lock lock(*m_pMutex);
    m_pData.reset();
  }
};

#endif /*SHAREDDATA_H*/

main.cpp :

#include <boost/thread.hpp>

boost::mutex g_mutexCout;

void dontmodify(SharedData const data)
{
  g_mutexCout.lock();
  //const-operator is called
  std::cout << "Thread id : " << boost::this_thread::get_id() << " ptr = " << data << " value = " << *data << std::endl;
  g_mutexCout.unlock();
}

void modify(SharedData data)
{
  g_mutexCout.lock();
  //const-operator is not called
  std::cout << "Thread id : " << boost::this_thread::get_id() << " ptr = " << static_cast<float const *>(data) << " value = " << *static_cast<float const *>(data) << std::endl;
  g_mutexCout.unlock();
}

int main(int argc, char* argv[])
{
  SharedData data;
  boost::thread t1(dontmodify, data);
  boost::thread t2(modify, data);

  t1.join();
  t2.join();

  return 0;
}

The above code of SharedData is wrong. I let it run with the Application Verifier active, and it crashed in the assignment-operator, since (I think), the mutexes are swapped and the application broke when the assign-block is leaved.

Have a look here and here.


texts:
I have this piece of code I would like some help with. I'm running a lengthy process that I want to interrupt at any time. The thing is, as you can see in the code, I have if(stop) everywhere, also in the methods inside the for (since they have for loops also).

stop is a member variable of the class, and the Stop() method is called from the UI from a different thread.

I don't think making it multithreading would be a good option since would be more complex to keep state and to communicate between threads.

Can you think of a better way to solve this, making the code cleaner?

public void Start()
{
    for(int i = 0; i < Length; i++)
    {
        if(stop)
            return;

        LengthyMethodA();

        if(stop)
            return;

        LengthyMethodB();

        if(stop)
            return;

        LengthyMethodC();
    }
}

public void Stop()
{
    stop = true;
}


texts: Finding the length of the longest common substring from two given strings in Java

texts:
The following code returns the length of longest common substring from given two strings in Java. For cases of around \$10^6\$ characters, it is still not fast enough to get the answer in a few seconds.

Any suggestions for efficiency will be greatly appreciated!

int longestCommonSubstring(String s, String t){
    int maxlength = 0;
    for(int i=0; i<s.length(); i++){
        for(int j=0; j<t.length(); j++){
            int count = 0;
            int g = 0;
            while(i+g<s.length() && j+g<t.length()){
                if(t.charAt(j+g)==s.charAt(i+g)){
                    count++;
                    maxlength = Integer.max(count, maxlength);
                }
                else{
                    count = 0;
                }
                g++;
            }
        }
    }
    return maxlength;
}


texts: JavaScript dragon slayer game (Codecademy)

texts:
I'm currently doing the Javascript course at Codecademy, and decided to customize their dragon slayer game. I would appreciate any help/pointers that can help me optimize the code. There's a lot of repetition that I'm sure can be done in a smarter way.

var slaying = true;
var youHit = Math.floor(Math.random() * 2);
var totalDamage = 0;
var playerHp = 100;
var dragonHp = 100;

function dragonSlayer() {
    while(slaying) {
        var damageThisRound = Math.floor(Math.random() * 50 + 1);
        console.log("Player HP: " + playerHp);
        console.log("Dragon HP: " + dragonHp);
        if(youHit) {
            totalDamage += damageThisRound;
            console.log("You did " + totalDamage + " damage!");
            console.log(" ");
            dragonHp -= totalDamage;
            if(dragonHp <= 0) {
                console.log("Player HP: " + playerHp);
                console.log("Dragon HP: 0");
                console.log("YOU WIN!");
                slaying = false;
            } else {
                totalDamage = 0;
                youHit = Math.floor(Math.random() * 2);
            }
        } else {
            totalDamage += damageThisRound;
            console.log("The dragon did " + totalDamage + " damage!");
            console.log(" ");
            playerHp -= totalDamage;
            if(playerHp <= 0) {
                console.log("Player HP: 0");
                console.log("Dragon HP: " + dragonHp);
                console.log("YOU ARE DEAD!");
                slaying = false;
            } else {
                totalDamage = 0;
                youHit = Math.floor(Math.random() * 2);
            }
        }
    }
};

dragonSlayer();


texts: Can I somehow tidy up this (overuse?) of generics?

texts:
I'm building a generic flat file reader which looks something like this.

 public class GenericReader<TComposite, THeader, TData, TTrailer>
    where TComposite : GenericComposite<THeader, TData, TTrailer>, new()
    where THeader : new()
    where TData : new()
    where TTrailer : new()
{
    public TComposite Read()
    {
        // read stuff, do parsing etc
        var composite = new TComposite();

        composite.Header = new THeader();
        composite.Data = new TData();
        composite.Trailer = new TTrailer();

        return composite;
    }
}

It could be consumed like so.

var reader = new GenericReader<Composite<Header, Data, Trailer>, Header, Data, Trailer> ();

var composite = reader.Read();
Console.WriteLine(composite.Data.SomeProperty);

Console.ReadLine();

Here are the classes used.

public class Composite<THeader, TData, TTrailer> : GenericComposite<THeader, TData, TTrailer>
{

}

public class GenericComposite<THeader, TData, TTrailer>
{
    public THeader Header { get; set; }

    public TData Data { get; set; }

    public TTrailer Trailer { get; set; }
}

public class Header {
    public string SomeProperty { get { return "SomeProperty"; } }
}

public class Data {
    public string SomeProperty { get { return "SomeProperty"; } }
}

public class Trailer {
    public string SomeProperty { get { return "SomeProperty"; } }
}

Is there a way how I could remove or encapsulate that generic type information in the GenericReader? I'm looking for an extra pair of eyes to show me something what I've been missing. We already did something with returning interfaces, and making the consumer do a cast, but that just moves the responsibility to the wrong location in my opinion, plus there is a small performance penalty.

Thanks.


texts:
I'm new to PHP programming. I would love some feedback on this simple code I wrote which queries a database based on some arguments supplied by a user and returns an HTML table displaying the data.

The table in my db has three columns: Manufacturer, Model, ForSale.

The user picks from three drop down menus on the web page and this php script is called with the data.

<?php
$db = new SQLite3("db/mantisui.db");

$manufacturer= $_GET['mfr'];
$model = $_GET['mod'];
$forsale = $_GET['forSale'];

// create the query
$q = "SELECT * FROM vehicles";
$addwhere = true;

// if all mfrs chosen, skip WHERE clause
$pos = strpos($manufacturer, 'All');
if ($pos === false) {
    $q .= " WHERE Manufacturer='$manufacturer'";
    $addwhere = false;
}

// if any models chosen, skip WHERE clause
$pos = strpos($model, 'Any');
if ($pos === false) {
    if ($addwhere == false) {
        $q .= " AND";
    }
    else {
        $q .= " WHERE";
        $addwhere = false;
    }

    $q .= " Model='$model'";
}

// if any for sale status chosen, skip WHERE clause
$pos = strpos($forsale, 'Any');
if ($pos === false) {
    if ($addwhere == false) {
        $q .= " AND";
    }
    else {
        $q .= " WHERE";
        $addwhere = false;
    }

    $q .= " ForSale='$forsale'";
}

$response = $db->query($q);

// generate the output table
$output = "
";
$output .= "

MANUFACTURER	MODEL	FOR SALE

";
while ($res = $response->fetchArray()) {

    $id = $res['Id'];
    $txtMfr= $res['Manufacturer'];
    $txtModel= $res['Model'];
    $txtForSale = $res['ForSale'];

    $output .= "
$id	$txtMfr	$txtModel	$txtForSale	$status
";
}

$output .= "
";
echo $output;

$db->close();
?>


texts:
As a kind of test of some newer features of C++ I implemented a thread pool. I'm aware that there are probably libraries out there that already have thread pools implemented but this was just as a small test for myself. I'm looking for opinions on my implementation as well as suggestions on how to improve it if possible.

The current intention of it is just to have a simple way to add functions that should be executed to the pool without having to worry about the overhead of starting a new thread each time.

Here's the class:

typedef std::function<void(void)> work_function;

class ThreadPool {
  private:
    bool _running;
    std::queue<work_function> _work_queue;
    std::atomic<size_t> _num_work;
    std::mutex _mutex;
    std::vector<std::thread> _threads;
  public:
    ThreadPool(size_t num_threads = std::thread::hardware_concurrency());
    virtual ~ThreadPool();
    void addWork(work_function work);
    void clearWork();
    void wait();
};

An here's the implementation:

ThreadPool::ThreadPool(size_t num_threads) :
    _running(true), _num_work(0) {
  auto thread_loop = [&](size_t id) {
    while (_running) {
      _mutex.lock();
      if (!_work_queue.empty()) {
        auto work = _work_queue.front();
        _work_queue.pop();
        _mutex.unlock();
        work();
        _num_work--;
      } else {
        _mutex.unlock();
        std::this_thread::yield();
      }
    }
  };
  _threads.reserve(num_threads);
  for (size_t i = 0; i < num_threads; i++) {
    _threads.push_back(std::thread(thread_loop, i));
  }
}

ThreadPool::~ThreadPool() {
  _running = false;
  for (std::thread& t : _threads) {
    t.join();
  }
}

void ThreadPool::addWork(work_function work) {
  _mutex.lock();
  _work_queue.push(work);
  _num_work++;
  _mutex.unlock();
}

void ThreadPool::clearWork() {
  std::queue<work_function> empty;
  _mutex.lock();
  _num_work -= _work_queue.size();
  std::swap(_work_queue, empty);
  _mutex.unlock();
}

void ThreadPool::wait() {
  while (_num_work.load() > 0) {
    std::this_thread::yield();
  }
}


texts: Finding the smallest missing positive number in an array

texts:
Any suggestions to improve?

public class FindSmallestMissingPositive {
    public static void main(String args[]){
        int a[] = {3,5,4,-1,1,-1,0};
        System.out.println("Smallest Missing positive : "+ findSmPositive(a));
    }

    public static int findSmPositive(int input[]){
        int min = input[0];
        int max= input[0];

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

        for(int i=0;i<input.length;i++){
            set.add(input[i]);

            if(input[i]<min){
                min = input[i];
            }
            if(input[i]>max){
                max = input[i];
            }
        }

        for(int i=min;i<=max;i++){
            if(i>0 && !set.contains(i)){
                return i;
            }
            else continue;

        }
        return -1;
    }
}


texts: Finding the closest pair of numbers which add to a target number

texts:
This function takes two lists of same length and a target number: the number which is to be summed. The function then returns a list of pairs whose sum is closest to the target number than any other pairs. It also finds the pair whose sum is equal to the target number.

def pair_finder(list1, list2, t):
    list1.sort()
    list2.sort()
    list1.reverse()
    t_low = list1[-1] + list2[0]
    t_high = list1[0] + list2[-1]
    pairs_low = []
    pairs_high = []
    pairs_equal = []
    for i in list1:
        k = 0
        for j in list2:
            if i + j < t:
                if i + j > t_low:
                    pairs_low.clear()
                    t_low = i + j
                    pairs_low.append([i, j])
                elif (i + j == t_low):
                    pairs_low.append([i, j])
            if i + j > t:
                if i + j < t_high:
                    pairs_high.clear()
                    t_high = i + j
                    pairs_high.append([i, j])
                    list2 = list2[k:]
                    break
                elif i + j == t_high:
                    pairs_high.append([i, j])
            if i + j == t:
                pairs_equal.append([i, j])
            k += 1
    pairs = []
    for q in pairs_low:
        pairs.append(q)
    for w in pairs_high:
        pairs.append(w)
    for r in pairs_equal:
        pairs.append(r)
    return pairs

while True:
    try:
        l1 = []
        l2 = []
        li = input("enter the first sequence of numbers by giving exactly one space between numbers:")
        for i in li.split(" "):
            l1.append(int(i))
        lj = input("enter the second sequence of numbers by giving exactly one space between numbers:")
        for j in lj.split(" "):
            l2.append(int(j))
        if len(l1) == len(l2):
            target = int(input("enter the target number: "))
            break
        else:
            print("the length of both sequences should be same!")
            l1 = []
            l2 = []
    except ValueError:
        print("only integer type values are allowed!")
for pair in pair_finder(l1, l2, target):
    print(pair)

Example:
Let list 1 be 2 98 63 41 25 27 -51 48 18 54 31 28 55 11  and list 2 be 21 56 87 65 21 12 75 41 33 91 32 15 8 -35 and target number be 43 hence the pairs (15, 27),(33, 11),(41, 2),(32, 11),(15, 28),(12, 31)


texts: jQuery nested ajax deffereds- looking for improvements

texts:
Following is a working solution for a single xml ajax to retrieve category list, then individual ajax calls for each category. This was developed in response to a question on SO.

Solution creates one deffered for the category ajax call, and array of deffereds for the items ajax calls. Bottom of code nests $when(itemsCallsArray) inside $.when( catgoryCall)

Working demo

Categories should stay in order of xml  but looking for any improvements that could be used to keep the items calls in order.

/* store all ajax content in object*/
var content = {};

function parseContent(content) {
    $.each(content, function() {
        $('body').append('

' + this.a + '
' + this.b.join('
'));
    })
}
/* array to store nested ajax promises */
var deferreds_b = [];
/* A promise and ajax*/
var xml_A = $.post("/echo/xml/", {
    xml: a
}, function(returnedXML) {

    var $el_A = $(returnedXML).find("ElementA");
    var total_A = $el_A.length;
    $el_A.each(function(counter) {
        var countA = counter;
        var name_of_Attribute_of_Element_A = $(this).attr("name");
        /* create EL A object , store EL A content, create array to push B content to */
        content[countA] = {
            a: countA + ". " + name_of_Attribute_of_Element_A,
            b: []
        }

        var xml_B = $.post("/echo/xml/", {
            xml: b
        }, function(returnedXML) {

            var $el_B = $(returnedXML).find("ElementB");
            var total_B = $el_B.length;
            $el_B.each(function(idx) {
                var name_of_Attribute_of_Element_B = $(this).attr("name");
                content[countA].b.push(countA + ". " + name_of_Attribute_of_Element_B);
            });
        });
    /* push B promise to array*/
        deferreds_b.push(xml_B);

    });
});

$.when(xml_A).done(function() {
    /* when A is done , wait for B to be done*/
    $.when.apply(null, deferreds_b).done(function() {
        parseContent(content);
        $("body").append("
All done!
");
    });

})


texts:
I want to know if what I have coded is good enough or if there is any simpler/faster/better/less size taking substitute.

I am trying to take input from push buttons and I also want to remove repeated input so I coded like it and saved in a variable key. I used internal pullup to eradicated random input from digital pins. I am in pre-graduation in computer applications and a beginner in electronics.

byte key=0;
unsigned int st=millis(),ct=millis(); //st-starttime , ct-currenttime

void setup()
{
  delay(5000);            //start prog after 5 sec
  pinMode(7, INPUT);
  pinMode(8, INPUT);
  pinMode(9, INPUT);
  byte i;
  for(i=7;i<=9;i++)
    digitalWrite(i, HIGH);    //7,8,9 pins HIGH  for internal pullup
  Serial.begin(9600);
}
void loop()
{
  byte i;

  for(i=7;i<=9;i++)
    if(checkswitch(i)==1)       //check which switch was last pressed
    {
      key=i;
      st=millis();
      while(st>65000)            //controlling limits of unsigned int
        st=st-65000;
    }
  ct=millis();
  while(ct>65000)
    ct=ct-65000;                 //controlling limits of unsigned int

  if(ct>st+200)                 //Triggers only if 200 ms passed
  {                             //to not fill the Serial input

    if(key!=0)
    {
      Serial.println(key);
      key=0;                       //clear saved key
    }

  }
}

byte checkswitch(byte n)           //Check button pressed with internal pullup
{
  byte p=0;
  if(digitalRead(n)==LOW) p=1;      //my best algo for if-else statement
  return p;
}


texts:
Backstory: I'm creating department level workbooks that contains director-level information, so I can't use a single workbook (as easy as it would make this). I need to split (and combine) 4 workbooks into 140 or more. I manage to do this relatively quickly (~30 minutes), but I was hoping to speed it up more.

For each sheet I create, I need certain filtered columns from the original 4 reports. After filtering the reports, I have this macro copy the columns:

Sub copyVisibleCells(fromWb As String, fromWS As String, fromCol As Integer, towb As String, toWS As String, toCol As Integer)

On Error GoTo errhnd

    Dim myCopyRange As Range
    Dim toCopyRange As Range
    ' Get the intersection of the column we want, and the range that has been used
    Set myCopyRange = Intersect(Workbooks(fromWb).Sheets(fromWS).Columns(fromCol), Workbooks(fromWb).Sheets(fromWS).UsedRange)
    ' If there's at least one visible cell (there was some error here once about trying to copy 0 cells, go figure)
    If myCopyRange.SpecialCells(xlCellTypeVisible).Cells.Count > 1 Then
        ' Remove the first row (swap the 1 with a 2) to remove the headers
        Set myCopyRange = Workbooks(fromWb).Sheets(fromWS).Range(Left(myCopyRange.Address, InStr(myCopyRange.Address, ":") - 2) & "2:" & Right(myCopyRange.Address, Len(myCopyRange.Address) - InStr(myCopyRange.Address, ":")))
        ' Copy the cells over: works, but seems slow
        myCopyRange.SpecialCells(xlCellTypeVisible).Copy
        Workbooks(towb).Sheets(toWS).Cells(6, toCol).PasteSpecial(xlValues)
    End If
    ' Done
    Exit Sub
errhnd:
    Debug.Print (vbNewLine & vbNewLine & "Error: " & err.Number & vbNewLine & err.Description & vbNewLine & "Press F8 to see error location")
    Stop
    Resume
End Sub

Is there a better way to do this? I was under the impression that Range.Copy and Range.PasteSpecial(xlValues) were very inefficient much like I've heard of Range.Select


texts:
Recently, I implemented an RenderBatch class, which renders any objects, using a specific shader (with its configuration). I'd like to improve on the way my render process works.

RenderBatch.h:

#pragma once
#include "alpha/Shader.h"
#include "alpha/RenderComponent.h"
#include <glm/glm.hpp>
#include "alpha/Mesh.h"
#include "alpha/Transform.h"
#include "alpha/Model.h"

class ShaderConfiguration
{
public:
    ShaderConfiguration();
    virtual ~ShaderConfiguration();
    virtual void Update(Shader& shader);
    void SetProjectionView(const glm::mat4& projectionView){
        m_projectionView = projectionView;
    }
    glm::mat4 GetProjectionView() const{
        return m_projectionView;
    }
    void SetTransform(const Transform& transform){
            m_transform = transform;
    }
    Transform GetTransform(){
        return m_transform;
    }
protected:
    glm::mat4 m_projectionView;
    Transform m_transform;
};
typedef ShaderConfiguration DefaultShaderConfiguration;

///Render Batch is really low lovel... It is only advised to use it
///in case you want to experiment with GLSL shaders : for more basic uses,
///ModelBatch is actually integrated in the GameObject system...
class RenderBatch : RenderComponent
{
public:
    RenderBatch(){
        m_shader.loadFromFile(GL_VERTEX_SHADER, "res/basicShader.glslv");
        m_shader.loadFromFile(GL_FRAGMENT_SHADER, "res/basicShader.glslf");
        m_shader.CreateAndLink();
    }
    RenderBatch(Shader shader)
        : m_shader(shader){}
    virtual ~RenderBatch(){}
    void SetShader(Shader shader){this->m_shader = shader;}
    Shader GetShader()const {return m_shader;}

    ///Genereal way of updating -----------------> using polymorphism
    void UpdateShaderConfiguration(ShaderConfiguration* config){
        m_shader.Bind();
            config->Update(m_shader);
        m_shader.UnBind();
    }
    ///Update for simple rendering --------------> ProjectionView + Transform ()
    ///Equivalent of :
    ///DefaultShaderConfiguration defaultShaderConfiguration
    ///UpdateShaderConfiguration(&defaultShaderConfiguration);
    void Update(glm::mat4 projectionView, Transform transform){
        m_shader.Bind();
            glUniformMatrix4fv(
                m_shader.GetUniformLocation("MVP"),
                1,
                GL_FALSE,
                glm::value_ptr(projectionView * transform.GetModelView())
                );
        m_shader.UnBind();
    }
    void Render(Mesh& mesh){
        m_shader.Bind();
            mesh.Draw();
        m_shader.UnBind();
    }
    glm::mat4 GetProjectionViewMatrix(){
        return m_projectionView;
    }
    void SetProjectionViewMatrix(glm::mat4 projectionView){
        this->m_projectionView = projectionView;
    }
protected:
    Shader m_shader;
    glm::mat4 m_projectionView;
};

RenderBatch.cpp

#include "alpha/RenderBatch.h"

ShaderConfiguration::ShaderConfiguration()
    : m_projectionView(glm::mat4(1))
{}
ShaderConfiguration::~ShaderConfiguration(){}

void DefaultShaderConfiguration::Update(Shader& shader){
    glUniformMatrix4fv(
    shader.GetUniformLocation("MVP"),
    1,
    GL_FALSE,
    glm::value_ptr(m_projectionView * m_transform.GetModelView())
    );
}

Main.cpp

 ///example 1 ---->using defaults
 RenderBatch batch = RenderBatch();
 Mesh mesh("res/Test.obj");
 Camera camera;

 while(isRunning)
 {
     /*Update */
     batch.Update(camera.Combined(), transform)
     /*some more update code...*/

     /*Render*/
     batch.Render(mesh);
 }

 ///example 2 ---->using custom configuration
 RenderBatch batch = RenderBatch();
 Mesh mesh("res/Test.obj");
 Camera camera;
 ShaderConfiguration config;

 while(isRunning)
 {
     config.SetProjectionView(camera.combined());
     config.SetTransform(transform)
     /*Update */
     batch.Update(config);
     /*some more update code...*/

     /*Render*/
     batch.Render(mesh);
 }


texts: Fetch: how to deal with a json payload in an error response?

texts:
Trying to get https://github.com/github/fetch working with an API that almost always returns a json payload, even when the response is an error:

{
  "message": "User not logged in",
  "code": 401
}

So I came up with this, adopting their status check example

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response
  } else {
    return response.json()
      .catch(() => {
        var error = new Error(response.statusText)
        error.response = response
        throw error
      }).then((json) => {
        var error = new Error(json.message || response.statusText)
        error.response = response
        throw error
      });
  }
}

This would handle both json and an invalid json reponse in case the api isn't able to produce valid json.

Would this be okay or am I missing something? I don't really like the .catch before the .then, but otherwise the .catch will catch the thrown error.. which is not what we want..


texts: UI error display window with task async in WPF

texts:
I am new to async and was wondering if any improvement can be made to the solution I put together from scattered information on the web.

The following (working) code shows how a button press runs logic and if there are any errors they will appear in the returned task.Exception.Handle variable which I can check in my ContinueWith code. If it's not null, I open the error dialog window for the user. By passing in FromCurrentSynchronizationContext, I get to open the window on the UI thread and avoid issues with UI thread access.

Any improvements to make it more readable or suggest a different patter for this would be much welcomed.

public void StartButton()
{
    //prevent multiple button presses with IsRunning switch
    if (!IsRunning)
    {
        IsRunning = true;

        Threading.Task.Factory.StartNew(() =>
        {
            ProgramLogic();
            IsFabRunning = false;
        })
        .ContinueWith(p =>
        {
            if (p.Exception != null)
                p.Exception.Handle(x =>
                {
                    logger.Error(p.Exception);
                    windowManager.ShowDialog(new ForceCloseViewModel(p.Exception.Message), null, null);
                    IsFabRunning = false;
                    return true;
                });
        }, Threading.TaskScheduler.FromCurrentSynchronizationContext());
    }
}


texts:
I'm writing a C program to reserve seats in a movie theater. I am validating the selection of seats:

const int TOTAL_ROWS = 10;            // 1 to 26 -> 'A' to 'Z'
const int SEATS_PER_ROW = 5;          // 1 to 9
int seats[TOTAL_ROWS][SEATS_PER_ROW]; // reserved seats, reserved seat == 1
char codes[TOTAL_SEATS][2];           // selected seats, e.g. A1, ..., Z9
...
for (i = 0; i < required_seats; i++) {
    printf("Enter the code for the seat: %i: ", i + 1);
    scanf("%s", codes[i]);
    if (codes[i][0] >= 'A' &&
        codes[i][0] <= 'A' + TOTAL_ROWS - 1 &&
        codes[i][1] >= '1' &&
        codes[i][1] <= '1' + SEATS_PER_ROW - 1) {

        if (seats[codes[i][0] - 'A'][codes[i][1] - '1'] == 1) {
            printf("Reserved seat. Select other.\n");
            i--;
        }
        for (j = 0; j < i; j++) {
            if (codes[j][0] == codes[i][0] && codes[j][1] == codes[i][1]) {
                printf("Repeated selection. Select other.\n");
                i--;
                break;
            }
        }
    } else {

        printf("Invalid code for seat.\n");
        i--;
    }
}

This code works fine. However, how can I refactor the code for this loop? In my opinion, using i-- does not look professional.

* By the way, you may want to see the full code —originally, in Spanish.


texts:
Wherever the biggest number is always use the 'big' value

If another number is equal to that number, use the 'big' value

Set the next number in line to 'medium'

If another number is equal to that number, use the 'medium' value

Set the next number in line to 'small'

If another number is equal to that number, use the 'small' value

entries: any { "FirstNames": 6, "Names": 8, "": 6, "Locations": 3, "Others": 2};

let sorted = this.sortByValues(this.entries);

var obj = {};
for (var i = 0; i <= sorted.length; i++) {
    if (Object.keys(obj).length === 0 && obj.constructor === Object)
        obj[sorted[i]] = "big";
    else if (this.entries[sorted[i]] == this.entries[sorted[i-1]] && obj[sorted[i-1]] == "big")
        obj[sorted[i]] = obj[sorted[i-1]];
    else if(this.entries[sorted[i]] < this.entries[sorted[i-1]] && obj[sorted[i-1]] == "big")
        obj[sorted[i]] = "medium";
    else if(this.entries[sorted[i]] == this.entries[sorted[i-1]] && obj[sorted[i-1]] == "medium")
        obj[sorted[i]] = obj[sorted[i-1]];
    else if(this.entries[sorted[i]] < this.entries[sorted[i-1]] && obj[sorted[i-1]] == "medium")
        obj[sorted[i]] = "small";
    else if(this.entries[sorted[i]] == this.entries[sorted[i-1]] && obj[sorted[i-1]] == "small")
        obj[sorted[i]] = obj[sorted[i-1]];
    else
        obj[sorted[i]] = obj[sorted[i-1]];
}

sortByValues(list : any)
{
    return Object.keys(list).sort(function(a,b){return list[a]-list[b]}).reverse());
}


texts: Is the JavaScript code I've provided following Functional Programming best-practices?

texts:
I'm trying to wrap my head around JavaScript Functional Programming.

I have created a very basic script that creates a new elements and appends them to the DOM.

If anyone could share any feedback, or great resources on the subject, that would be awesome.

Where does this style of programming lend itself best? Web Development, or more Software development? I understand that React uses this coding paradigm. I'm actually very comfortable using React - but, I'm wondering how it might be best utilised with vanilla JavaScript

Thanks!

// create a button that accepts text and a callback function

const createButton = (text, func) => {
    const button = document.createElement('button');
    const buttonText = document.createTextNode(text);
    button.appendChild(buttonText);

    button.addEventListener('click', () => {
        return func();
    });

    return button;
};

// create paragraph tag that accepts a text arg

const createText = (text) => {
    const pTag = document.createElement('p');
    const pTagText = document.createTextNode(text);
    pTag.appendChild(pTagText);

    return pTag;
};

// pure functions

const myList = [1, 2, 3];

const sayHello = (name) => {
    return `Hello, ${name}!`;
};

const addNums = (x, y) => {
    return x + y;
};

const simpleLog = () => {
    return 'This is a simple log';
};

const addToArray = (item) => {
    return [...myList, item];
}

// view - component that will get rendered to the DOM

const view = () => {
    const component = document.createElement('div');

    // create a button element that has a callback function that will append the returned value to the DOM

    component.appendChild(createButton('Hello', () => {
        return component.appendChild( createText( sayHello('Kristian') ) );
    }));

    component.appendChild(createButton('Add Numbers', () => {
        return component.appendChild( createText( addNums(3, 7) ) );
    }));

    component.appendChild( createButton('Log', simpleLog) );

    component.appendChild(createButton('Add to array', () => {
        console.log( `Original array: [${myList}] - New array: [${addToArray(4)}]`);
    }));

    return component;
};

// grab the el that you want to append the view to

const rootNode = document.getElementById('app');

// append view component to el

rootNode.appendChild(view());


texts:
I'm making a few forms of a mortgage calculator for my intro to computer science class. With inputs, I currently have it outputting the monthly payments. I'll eventually be outputting how long it will take to pay off the loan once I add some code. I'm just looking for suggestions for any easier/quicker ways to do it. It currently compiles and runs fine.

#include "math.h"
#include <iostream>
using namespace std;

int main()
{
   int a; //amount of the loan
   double i; // the loan interest rate
   int y; //years of the loan
   int t = 12; //loan term in months
   double mPayment; //variable for ouputting the payment

   cout.setf(ios::fixed);
   cout.setf(ios::showpoint);
   cout.precision(2);

   cout << "\n Enter the amount of loan in $ = ";
   cin >> a;
   cout << "\n Enter the interest rate = ";
   cin >> i;
   cout << "\n Enter years of the loan = ";
   cin >> y;

   mPayment = (a * i) / (1 - pow(1+i,-t)); //Formula to figure mortgage payment amount

   cout<< "\nYour Monthly Payment Amount is: $"<< mPayment; //prints out montyly payment amount

   return 0;
}


texts: Extracting length-3 subsequences from a list

texts:
For a list li, I want to print only the values of the triplets a, b, c where 0 <= index(a) < index(b) < index(c) < len(li).

Example:

f([6, 3, 88, 4])
6 3  88
6 3  4
6 88 4
3 88 4

Here is my solution, but it is O(n**3) (time complexity):

def f(li):
    for i, n in enumerate(li):
        for j, o in enumerate(li):
            for k, p in enumerate(li):
                if i < j < k:
                    print n, o, p

However, it should be doable in O(n). Any clues?

I have the following function as well:

def f(li):
    i = 0
    j = i + 1
    k = j + 1
    n = li[i]
    o = li[j]
    p = li[k]
    while i < j < k:
        print n, o, p
        if n == li[-3]:
            break
        if p != li[-1]:
            k += 1
        elif o == li[-2]:
            i += 1
            j = i + 1
            k = j + 1
        elif p == li[-1]:
            j += 1
            k = j + 1

        n = li[i]
        o = li[j]
        p = li[k]

I believe this is O(n).


texts: Using T type parameter to clone a collection

texts:
I want to clone a collection with the following method and I want to know if it can be optimized:

public T CloneCollection<T>(IEmployees employees) where T : IEmployees, new()
{
    T collection = new T();
    foreach (IEmployee employee in employees)
    {
        collection.Add(employee);
    }
    return collection;
}

These are the other classes which are related to the method above:

public class RegularEmployee : Entities, IEmployee
{
//properties
}

public class User : Entities, IEmployee
{
//properties
}

public class Manager : Entities, IEmployee
{
//properties
}

public class ManagerCollection : List<Manager>, IEmployees
{
   void Add(IEmployee employee);
}

public class RegularEmployeeCollection : List<RegularEmployee>, IEmployees
{
   void Add(IEmployee employee);
}

public class UserCollection : List<User>, IEmployees
{
   void Add(IEmployee employee);
}


texts: Calculating longest increasing sub-sequence recursively

texts:
I have trouble understanding recursion, so I'm trying to implement algorithms using it. I wrote this code that calculates the length of the longest increasing sub-sequence. How can I improve this?

int _lis(int arr[], int n){
  if(n==0) return 1;

  int m=1, temp;
  for(int i=0; i<n; i++){
    if(arr[i]<arr[n]){
        temp= 1 + _lis(arr, i);
        if(temp > m)
            m=temp;    //   m = max(m, 1 + _lis(arr, i));
    }
  }
  return m;
}

int LIS(int arr[], int n){
  int temp, m=0;

  for(int i=0; i<n; i++){
    temp = _lis(arr, i);
    if(temp>m)
        m= temp;
  }
  return m;
}

Examples:

{3, 1, 2, 5, 1, 6} returns 4. (LIS : 1, 2, 5, 6)
{ 10, 22, 9, 33, 21, 50, 41, 60 } returns 5. (LIS : 10, 22, 33, 50, 60)


texts: Remove parameters from string containing URL

texts:
Is this the best way to remove URL parameters from a string containing an URL?

$url = "http://www.test.com/test.html?parameter=hey&parameter2=ho";
if (strstr($url, "?")) {
   $url = strstr($url, "?", true);
}

Is there a better one-line solution? It seems so bad to run the same function twice.


texts:
I've got a case where I need to call a couple of methods, checking if they return null, and return some property from the result of the second when neither returns null.

I've thought of two ways to do this - one "verbose" and one "concise". For the purposes of this question, I'll just call the return types 'dynamic' since I'm not interested in those details here.

private dynamic VerboseVersion()
{
     var a = CallMethodA();
     if ( a == null )
     {
         return null;
     }

     var b = CallMethodB( a );
     if ( b == null )
     {
         return null;
     }

     return b.SomeProperty;
}

private dynamic ConciseVersion()
{
    dynamic a;
    dynamic b;

    if ( ( a = CallMethodA() ) == null ||
         ( b = CallMethodB( a ) ) == null )
    {
        return null;
    }

    return b.SomeProperty;
}

I the first because the intent at each step is very obvious but I find it somewhat verbose; I like the second because the intent of the function seems more obvious and it is less verbose but it may be a bit harder to follow at first.

Thoughts?

Update: Corrected a typo and corrected the formatting of the "Verbose" version to what I would actually use in committed code.


texts: Time spent by product in process represented by clockin and clock out

texts:
This is the code I wrote to find out the time spent by product in process represented by clockin and clock out. Time stamps X and Y (for example, 7/23/2013 7:00 AM and 7/23/2013 8:00 AM) reflect the time period where in I am calculating the time.

X, Y, CLOCK_IN and CLOCK_OUT are all timestamps.

I wrote this code, but I am not a programmer. Is there a better way to do it? Please explain step by step.

It runs against a huge set of data. How can I reduce its runtime?

Here is a calculation I'm running in MS Access 2010:

Sum(

     IIf([CLOCK_IN]<[X] And [X]<[CLOCK_OUT] And [CLOCK_OUT]<[Y],([CLOCK_OUT]-[X])*24*60,0)+
     IIf([CLOCK_IN]<[X] And [Y]=[CLOCK_OUT],60,0)+
     IIf([CLOCK_IN]=[X] And [Y]<[CLOCK_OUT],60,0)+
     IIf([X]<[CLOCK_IN] And [CLOCK_IN]<[Y] And [Y]<[CLOCK_OUT],([Y]-[CLOCK_IN])*24*60,0)+
     IIf([X]<[CLOCK_IN] And [CLOCK_IN]<[CLOCK_OUT] And [CLOCK_OUT]<[Y],([Y]-   [CLOCK_IN])*24*60,0)+
     IIf([CLOCK_IN]<[X] And [X]<[Y] And [Y]<[CLOCK_OUT],60,0)+
     IIf([X]=[CLOCK_IN] And [Y]=[CLOCK_OUT],60,0)+
     IIf([X]=[CLOCK_IN] And [CLOCK_OUT]<[Y],24*60*([CLOCK_OUT]-[X]),0)+
     IIf([X]<[CLOCK_IN] And [CLOCK_OUT]=[Y],24*60*([CLOCK_OUT]-[X]),0))/60)

)


texts:
I need help to simplify this code about implicit date calculation.

The context: I have sentences with implicit and explicit dates. For instance:

  "From the 5th to the 7th of September 2017, the 12th, 13th and 15th of June, from the 25th to the 31th December, the 1st and the 2nd of January 2019."

A program (not shown here) can parse implicit and explicit dates, so I can get an ordered list (in chronological order) like that:

    history = [
        [5],
        [7, 9, 2017],
        [12],
        [13],
        [15, 6],
        [25],
        [31, 12],
        [1],
        [2, 1, 2019],
    ]

The purpose of the program below is to calculate the dates.

import datetime

class ImplicitDate(object):
    def __init__(self, day: int, month: int = None, year: int = None):
        self.day = day
        self.month = month
        self.year = year

    def __repr__(self):
        cls = self.__class__.__name__
        return f"<{cls}(day={self.day!r}, month={self.month!r}, year={self.year!r})>"

    def __str__(self):
        s = []
        if self.year:
            s.append(f"{self.year:04d}")
        if self.month:
            s.append(f"{self.month:02d}")
        if self.day:
            s.append(f"{self.day:02d}")
        return "-".join(s)

    @property
    def date(self) -> datetime.date or None:
        if self.year is None or self.month is None or self.day is None:
            return None
        return datetime.date(self.year, self.month, self.day)

    def estimate_date(self, future_date: datetime.date) -> datetime.date:
        if self.day is None:
            # weird
            return future_date
        elif self.month is None:
            day = self.day
            month = future_date.month
            year = future_date.year
            date = datetime.date(year, month, day)
            if date < future_date:
                return date
            else:
                month = future_date.month - 1
                if month == 0:
                    month = 12
                    year = future_date.year - 1
                date = datetime.date(year, month, day)
                return date
        elif self.year is None:
            day = self.day
            month = self.month
            year = future_date.year
            date = datetime.date(year, month, day)
            if date < future_date:
                return date
            else:
                year = future_date.year - 1
                date = datetime.date(year, month, day)
                return date
        else:
            day = self.day
            month = self.month
            year = self.year
            date = datetime.date(year, month, day)
            return date

def demo_implicit_dates():
    history = [
        ImplicitDate(5),
        ImplicitDate(7, 9, 2017),
        ImplicitDate(12),
        ImplicitDate(13),
        ImplicitDate(15, 6),
        ImplicitDate(25),
        ImplicitDate(31, 12),
        ImplicitDate(1),
        ImplicitDate(2, 1, 2019),
    ]

    curr = history.pop()
    dates = [curr.date]
    while history:
        top = dates[-1]
        curr = history.pop()
        estimated = curr.estimate_date(top)
        dates.append(estimated)
    dates.reverse()

    for date in dates:
        print(date.isoformat())

    # 2017-09-05
    # 2017-09-07
    # 2018-06-12
    # 2018-06-13
    # 2018-06-15
    # 2018-12-25
    # 2018-12-31
    # 2019-01-01
    # 2019-01-02

Do you think this program is complex or over-designed? How to simplify it?

Do you think this algorithm is well-implemented? Is there something I am missing?


texts:
#include <sys/types.h>
#include <sys/socket.h>

#include <netdb.h>
#include <string.h>
#include <unistd.h>

#include <string>
class Website
{
    int status, sock;
    struct addrinfo hints;
    struct addrinfo *servinfo;
    public:
      int init(std::string url){
          memset(&hints, 0, sizeof hints);
          hints.ai_family = AF_UNSPEC;
          hints.ai_socktype = SOCK_STREAM;
      if((status = getaddrinfo(url.c_str(), "80", &hints, &servinfo)) != 0){
              return status;
          }
          if((sock = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == -1){
              return -1;
      }
          return 0;
       }
     int connectToSite(){
        return connect(sock, servinfo->ai_addr, servinfo->ai_addrlen);
     }
     int sendToSite(std::string request){
        return send(sock, request.c_str(), strlen(request.c_str()), 0);
     }
     int recvFromSite(char buf[], int maxsize){
        return recv(sock, buf, maxsize, 0);
     }
    void closeSocket(){
      close(sock);
      freeaddrinfo(servinfo);
     }
};

I have a networking class that implements low level c functions in a simple class. I am looking to make my code more efficient


texts: Accessing a UIView's parent UIViewController using the UIResponder chain

texts:
I recently found a static C function on Stack Overflow which returns a UIViewController reference from a containing subview using the responder chain:

static UIViewController *viewControllerForView(UIView *view) {
    UIResponder *responder = view;
    do {
        responder = [responder nextResponder];
    }
    while (responder && ![responder isKindOfClass:[UIViewController class]]);
    return (UIViewController *)responder;
}

I wanted to write this in Swift 3 as a programming exercise.  My first pass looked like this:

func viewController(forView view: UIView) -> UIViewController? {

    var responder = view as? UIResponder

    while (responder != nil) {
        if let viewController = responder as? UIViewController {
            return viewController
        }
        responder = responder?.next
    }

    return nil
}

Then I tried using a repeat while loop, to see if the structure would look any better:

func viewController(forView view: UIView) -> UIViewController? {

    var responder: UIResponder? = view

    repeat {
        responder = responder?.next
        if let vc = responder as? UIViewController {
            return vc
        }
    } while responder != nil

    return nil
}

I'm really not a fan of the while responder != nil.  Is there a way I can loop while checking if the responder is a UIViewController?  Maybe I can make this a recursive function by making the parameter a generic UIResponder object.


texts: Quickly find percentile with high precision

texts:
I need to find the percentile where a list of values is higher than a threshold. I am doing this in the context of optimization, so it important that the answer is precise. I am also trying to minimize compute time. I have a O(n) solution which is not very precise, then I use scipy's minimize optimizer to find the exact solution, which is time-intensive. The numbers in my problem are NOT normally distributed.

Is there a more time-efficient way to do this while preserving precision?

from scipy.optimize import minimize
my_vals = []
threshold_val = 0.065
for i in range(60000):
    my_vals.append(np.random.normal(0.05, 0.02))

count_vals = 0.
for i in my_vals:
    count_vals += 1
    if i > threshold_val: break
percKnot = 100 * (count_vals/len(my_vals))
print minimize(lambda x: abs(np.percentile(my_vals, x[0]) - threshold_val), percKnot, bounds=[[0,100]], method='SLSQP', tol=10e-9).x[0]


texts: How can I simplify these if/else clauses?

texts:
I have a few if, else-if, else clauses.  The only different thing in the context of these clauses is my LINQ query, one clause has StartsWith, one clause has Contains, and the other does a simple match.  Is there a way to have all of this in one clause and somehow create a variable that can change between StartsWith, Contains, etc.?  My ultimate goal is to reduce the lines of code.

if (parameters[0].ToUpper() == "STARTSWITH" && parameters[1] != null)
    {
        string searchname = parameters[1];
        ViewBag.MyMessage = "Displaying device names beginning with \"" + searchname + "\"";

        SampleEntities sampleEntities = new SampleEntities();

        try
        {
            var Model = (from dev in sampleEntities.NetworkDevices
                         where dev.Name.StartsWith(searchname)
                         from inter in sampleEntities.DeviceInterfaces
                         where inter.NetworkDevice.Id == dev.Id
                         select new DeviceInterfaceModel
                         {
                             DeviceName = dev.Name,
                             InterfaceName = inter.Name,
                             IPv4Address = inter.IPv4Address,
                             IPv4SubnetMask = inter.IPv4SubnetMask,
                             CIDR = inter.CIDR,
                             Subnet = inter.Subnet
                         }).ToList();

            return View(Model);
        }
        catch
        {
        }

        return View();
    }
    #endregion
    #region Name Contains
    else if (parameters[0].ToUpper() == "CONTAINS" && parameters[1] != null)
    {
        string searchname = parameters[1];
        ViewBag.MyMessage = "Displaying device names containing \"" + searchname + "\"";

        SampleEntities sampleEntities = new SampleEntities();

        try
        {
            var Model = (from dev in sampleEntities.NetworkDevices
                         where dev.Name.Contains(searchname)
                         from inter in sampleEntities.DeviceInterfaces
                         where inter.NetworkDevice.Id == dev.Id
                         select new DeviceInterfaceModel
                         {
                             DeviceName = dev.Name,
                             InterfaceName = inter.Name,
                             IPv4Address = inter.IPv4Address,
                             IPv4SubnetMask = inter.IPv4SubnetMask,
                             CIDR = inter.CIDR,
                             Subnet = inter.Subnet
                         }).ToList();

            return View(Model);
        }
        catch
        {
        }

        return View();
    }
    #endregion
}

else
{
    ViewBag.MyMessage = "Diplaying device names equal to \"" + name + "\"";
    SampleEntities sampleEntities = new SampleEntities();

    try
    {
        var Model = (from dev in sampleEntities.NetworkDevices
                     where dev.Name == name
                     from inter in sampleEntities.DeviceInterfaces
                     where inter.NetworkDevice.Id == dev.Id
                     select new DeviceInterfaceModel
                     {
                         DeviceName = dev.Name,
                         InterfaceName = inter.Name,
                         IPv4Address = inter.IPv4Address,
                         IPv4SubnetMask = inter.IPv4SubnetMask,
                         CIDR = inter.CIDR,
                         Subnet = inter.Subnet
                     }).ToList();

        return View(Model);
    }
    catch
    {
    }

    return View();
}


texts:
I've made a dice game that rolls three die, calculates the sum of their results, and asks the user whether he/she thinks the next roll's total will be higher, the same, or lower than the current roll. It works but I want to know if there is a better/more efficient way to do this. I just started C programming a couple days ago.

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

int main()
{
    int i;
    int runTime;
    int die1;
    int die2;
    int die3;
    int temp;
    int total;
    char guess;
    int count = 0;
    srand(time(NULL));

    printf("How many times do you want to play?\n");
    scanf(" %d", &runTime);
    printf("");

    die1 = ( (rand() % 6) + 1);
    die2 = ( (rand() % 6) + 1);
    die3 = ( (rand() % 6) + 1);
    total = (die1 + die2 + die3);

    if(runTime != 0){

        printf("Die 1: %d\n", die1);
        printf("Die 2: %d\n", die2);
        printf("Die 3: %d\n", die3);
        printf("-------------------\n");
        printf("Total: %d\n\n", total);
        temp = total;

        printf("Do you think the next total will be higher, the same, or lower than the previous total? (h, s, l) \n\n");
        scanf(" %c", &guess);

        for(i = 0; i < runTime - 1; i++){
            die1 = ( (rand() % 6) + 1);
            die2 = ( (rand() % 6) + 1);
            die3 = ( (rand() % 6) + 1);
            total = (die1 + die2 + die3);

            printf("Die 1: %d\n", die1);
            printf("Die 2: %d\n", die2);
            printf("Die 3: %d\n", die3);
            printf("-------------------");
            printf("Total: %d\n", total);

            if( (total > temp) && (guess == 'h') ){
                printf("You guessed correctly!\n");
                count++;
            }else if( (total == temp) && (guess == 's') ){
                printf("You guessed correctly!\n");
                count++;
            }else if( (total < temp) && (guess == 'l') ){
                printf("You guessed correctly!\n");
                count++;
            }else{
                printf("You guessed incorrectly :(\n");
            }
            temp = total;
            printf("Do you think the next total will be higher, the same, or lower than the previous total? (h, s, l) \n");
            scanf(" %c", &guess);

        }
    printf("You got a total of %d guesses correct!", count);
     }else{
    printf("Goodbye.");
    }
    return 0;
    }


texts: Rebuilding WAR files in webapps directory

texts:
This script cleans up destination directory and copies file into it with new name. Can this intent be expressed more cleanly with shelly?

main = shellyFailDir $ verbosely $ do
  escaping False $ rm_rf $ webapps </> "*"
  cp (m2repo
       </> groupPath
       </> artifact
       </> version
       </> (intercalate "-" [artifact, version] `append` ".war")
     ) $ webapps </> (finalName `append` ".war")
  echo "done"

Alternate take:

main = shellyFailDir $ verbosely $ do
  ls webapps >>= mapM_ rm_rf
  cp (m2repo <> groupPath <> (mconcat . map fromText $ [artifact, version, artifactFileName]))
     $ webapps <> fromText (finalName <> extension)
  echo "done"

artifactFileName = intercalate "-" [artifact, version] <> extension

Having (types match only second version because they help pick correct Monoid):

m2repo = ".m2/repository" :: FilePath
version = "1.0-SNAPSHOT" :: Text
webapps = "tomcat/webapps" :: FilePath
groupPath = "com/example" :: FilePath
artifact = "app" :: Text
finalName = artifact
extension = ".war" :: Text


texts: Extension method to get the Sunday date from current date based on weekOffset

texts:
I want to write an extension method for getting Sunday Date based on weekOffset and current date. For example if weekOffset value is 1 that means next week sunday date and if weekOffset is 2 that means next to next week's Sunday date.
I have come up with below code
private static List<string> GetWeekRange(this DateTimeOffset date, int weekOffset = 0)
        {
            var sundayDate = new DateTimeOffset(date.Year, date.Month, date.Day, 0, 0, 0, date.Offset).AddDays(weekOffset * 7 - (int) new DateTimeOffset(date.Year, date.Month, date.Day, 0, 0, 0, date.Offset).DayOfWeek);
            var saturdayDate = new DateTimeOffset(weekStartDate.Year, weekStartDate.Month, weekStartDate.Day, 0, 0, 0, weekStartDate.Offset).AddDays(7).AddMilliseconds(-1);
            return new List<string> { weekStartDate.ToString("o"), weekEndDate.ToString("o") };
        }

I was wondering if there can be a better way to do this?


texts:
I'm working my way through The Java Programming Language, 4th edition.  This is exercise 2.2:

  Write a LinkedList class that has a field of type Object and a reference to the next LinkedList element in the list.

Is this an adequate solution? Is there a more efficient way to build up a test list for this example?

class Node {
    private Object data;
    private Node next;

    public Node(Object data) {
        this(data, null);
    }

    public Node(Object data, Node next) {
        this.data = data;
        this.next = next;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public Object getData() {
        return data;
    }

    public Node getNext() {
        return next;
    }
}

class LinkedListTest {

    public static void main(String[] args) {

        Node node3 = new Node("puke");
        Node node2 = new Node("vomit", node3);
        Node node1 = new Node("blah", node2);

        Node node = node1;
        while (node != null) {
            System.out.println("Data = " + node.getData());
            node = node.getNext();
        }
    }
}


texts: Truncating integer using string manipulation

texts:
I have a class with a data member that needs to be rounded up to a 2 digit integer, irrespective of the number of the input digits.

For example:

roundUpto2digit(12356463) == 12
roundUpto2digit(12547984) == 13 // The 5 rounds the 12 up to 13.

Currently my code looks like:

int roundUpto2digit(int cents){
    // convert cents to string
    string truncatedValue = to_string(cents);
    // take first two elements corresponding to the Most Sign. Bits
    // convert char to int, by -'0', multiply the first by 10 and sum the second
    int totalsum =  int(truncatedValue[0]-'0')*10 + int(truncatedValue[1]-'0');
    // if the third element greater the five, increment the sum by one
    if (truncatedValue[2]>=5) totalsum++;
    return totalsum;
}

How can this be made less ugly?


texts:
I am creating a web service that uses a component I've licensed that is restricted to two concurrent instances at any one time. Creating a new instance of the component takes a long time (seconds) so I want to maintain a pool of objects for re-use. Here's my first (working) attempt, but it seems fairly inelegant, and also likely that I've made some mistakes (although it hasn't failed in my own tests):

public class MyWebService : System.Web.Services.WebService
{
    static RestrictedClass rc1, rc2;

    [WebMethod]
    public byte[] MyMethod(byte[] Stream1, byte[] Stream2)
    {
        RestrictedClass rc = null;
        Mutex m1 = null, m2 = null;
        if (rc1 == null)
        {
            m1 = new Mutex(true, "rc1");
            m1.WaitOne();
            rc1 = new RestrictedClass();
            rc = rc1;
        }
        else if (rc2 == null)
        {
            m2 = new Mutex(true, "rc2");
            m2.WaitOne();
            rc2 = new RestrictedClass();
            rc = rc2;
        }
        else
        {
            bool m1Granted, m2Granted;
            m1 = new Mutex(true, "rc1", out m1Granted);
            m2 = new Mutex(true, "rc2", out m2Granted);
            int idx;
            if (m1Granted)
            {
                idx = 0;
            }
            else if (m2Granted)
            {
                idx = 1;
            }
            else
            {
                idx = Mutex.WaitAny(new Mutex[] { m1, m2 });
            }
            if (idx == 0)
            {
                rc = rc1;
                m2.Close();
            }
            else if (idx == 1)
            {
                rc = rc2;
                m1.Close();
            }
        }

        Result = rc.DoStuff();

        if (m1 != null && rc == rc1)
            m1.ReleaseMutex();
        if (m2 != null && rc == rc2)
            m2.ReleaseMutex();
        return Result.ToArray();
    }
}

Please pick it apart and suggest any improvements you like.


texts:
I'm writing a bash script to handle the PPA's on Ubuntu & derivatives. I was wondering how to know if I'm handling this the right way.

So, the script works (flawlessly), but I posted it to a blog and got this feedback :

  The way you wrote you script is the one we all use when we begin : we don't know the variables, so we use traditionnal commands, and in the end if we remove the "#" arguments from the script, the code is sad (maybe he meant 'poor' ?)

Here is a sample :

#! /bin/bash
SCRIPT="ppa-tool"
VERSION="2.0.1"
DATE="2014-03-26"
RELEASE="$(lsb_release -si) $(lsb_release -sr)"

[ -n "`echo "$1" | grep ppa`" ] && PPA=$1
[ -n "`echo "$2" | grep ppa`" ] && PPA=$2

helpsection()
{
echo -e "Usage : $SCRIPT [OPTION]... [PPA]...
-h, --help     shows this help
-c, --check    check if [PPA] is available for your release

Version $VERSION - $DATE"
exit 0
}

error() { echo -e "$SCRIPT - Oops, something went wrong\nTry « $SCRIPT --help » for more information." && exit 0 ; }

ppa_verification()
{
wget http://ppa.launchpad.net/$(echo $PPA | sed -e 's/ppa://g')/ubuntu/dists -O /tmp/"$SCRIPT-check.tmp" -q
if [[ -n "`cat "/tmp/$SCRIPT-check.tmp" | grep $(lsb_release -sc)`" ]] ; then
    echo -e "$SCRIPT : '$PPA' is available for $RELEASE"
else
    echo -e "$SCRIPT : '$PPA' is NOT available for $RELEASE"
fi
rm "/tmp/$SCRIPT-check.tmp"
}

[ "$1" == "--help" ] || [ "$1" == "-h" ] && helpsection

if [ "$1" == "--check" ] || [ "$1" == "-c" ] || [ "$1" == "check" ]  ; then
    [ -n "`echo $2`" ] && ppa_verification && exit 0
    error
fi

error

(complete script - also in French)

Apparently, my syntax is bad, but I don't see what I could do to improve this, and I don't understand the feedback I recieved. Could you help me figure it out ?

EDIT: From Unix&Linux (where I first posted, but was redirected here), someone said it wasn't good to use capital letters for variables. So $SCRIPT should become $script.


texts: Extract numbers from an AlphaNumeric string

texts:
I have an alphanumeric string like sdff45hg589>@#DF456&<jk778P&&FHJ75, of which I want to extract only the numbers, without using regex or any other functions.

Dim input As String = "sdff45hg589>@#DF456&<jk778P&&FHJ75"
Dim output As String = New String((From c As Char In input Select c Where Char.IsDigit(c)).ToArray())
MsgBox(output) 'Display the output

The message box will display 4558945677875.

For extracting letters from the same string, I use the following:

 Dim input As String =  "sdff45hg589>@#DF456&<jk778P&&FHJ75"
 Dim output As String = New String((From c As Char In input Select c Where Char.IsLetter(c)).ToArray())
 MsgBox (output)

Is this a better way to extract both?


texts: A multithreaded, growable vector with immutable elements, which has wait-free reads

texts:
I wrote a small vector with a few lines of unsafe Rust.

The idea is to have a vector, which can be read from simultaneously, but it needs the ability to grow. To realize that, the storage is organized in pages. As page, I use arrayvec:

const ELEMENTS_PER_PAGE: usize = 1024;

type Page<T> = ArrayVec<[T; ELEMENTS_PER_PAGE]>;

The main problem is, when putting those pages in a Vec, the access may gets invalidated, while pushing to the vector. To solve this, I have an array of *mut Page<T> (so basically Vec<Box<Page<T>>>) and another pointer which points to this array: *mut *mut Page<T>. When adding pages, the vector will be copied without cloning the Pages (this is why I need the raw pointer). Now the *mut *mut ptr will be updated to the new vector and everyone will be headed to the correct memory.

As a small optimization, I use Box<[_]> instead of Vec, since the Vec will never grow directly:

pub struct ConstVec<T> {
    // storage, which holds the actual pages
    pages: Mutex<Box<[*mut Page<T>]>>,
    // points to the storage. Used for wait-free access.
    pages_pointer: AtomicPtr<*mut Page<T>>,
    len: AtomicUsize,
}

We need two helper functions to get the indices for the page and the element in a specific page:

const fn page_index(index: usize) -> usize {
    index / ELEMENTS_PER_PAGE
}

const fn element_index(index: usize) -> usize {
    index % ELEMENTS_PER_PAGE
}

and a len method:

pub fn len(&self) -> usize {
    self.len.load(atomic::Ordering::Acquire)                           // 1
}

This is the function for pushing into the vector:

pub fn push(&self, value: T) {
    let mut pages = self.pages.lock().unwrap();

    let index = self.len.load(atomic::Ordering::Acquire);              // 1
    let page_index = Self::page_index(index);

    // do we need an new page?
    if page_index == pages.len() {
        // allocate a new vector, which will replace the old one
        // and copy old elements into it.
        let mut new_pages = Vec::with_capacity(page_index + 1);
        new_pages.extend(pages.iter().cloned());
        new_pages.push(Box::into_raw(Box::new(Page::new())));          // 2

        // Update the pages pointer first. This will be used
        // to receive data. The pointers remains valid.
        self.pages_pointer
            .store(new_pages.as_mut_ptr(), atomic::Ordering::SeqCst);  // 1
        // replace "vector"
        mem::replace(pages.deref_mut(), new_pages.into_boxed_slice());
    }
    unsafe {
        (*pages[page_index]).push(value);                              // 2
    }
    self.len.store(index + 1, atomic::Ordering::Release);              // 1
}

And of course we need to implement Drop:

fn drop(&mut self) {
    for page_ptr in self.pages.lock().unwrap().iter() {
        unsafe { Box::from_raw(*page_ptr) };                           // 2
    }
}

Now two questions came up (see the code numbers for references):

Am I using the right Ordering for atomic access? If I see correctly, I can use Acquire/Release everywhere but in storing the pages_pointer. This needs to be SeqCst, because it would be fatal, if the mem::replace would be executed before (the old pointer would dangle). Also I don't thing, Relaxed can be used anywhere here. Are my assumptions correct?
Are those unsafe actually safe?

playground


texts: Finding differences in strings with Levenshtein distance and soundex

texts:
I am trying to find a way to optimize the code runtime. Improvements I have implemented include using dictionaries, removing redundancies and using str.translate.

from collections import namedtuple
import string

import jellyfish as jf
import Levenshtein as l #conda install -c conda-forge python-levenshtein

#instantitiate trans table
words2numbers = {
    '1' : 'one ',
    '2' : 'two ',
    '3' : 'three ',
    '4' : 'four ',
    '5' : 'five ',
    '6' : 'six ',
    '7' : 'seven ',
    '8' : 'eight ',
    '9' : 'nine ',
    '0' : 'zero '
    }

string_punc = {key: None for key in string.punctuation}
replace_with = str.maketrans({**words2numbers, **string_punc})
String = namedtuple('String','encode lev ori')

def norm_func(s):
    '''
    Normalize number characters and punctuations

    '123' -- > 'one two three'
    '.?1 12 gray' --> 'one two gray'
    '''
    s = s.translate(replace_with)
    return s.lower()

def encode_phonetic(s): #should return normalize string here
    '''
    Tag sentence by tokenizing string and returns soundex via jellyfish.
    Creates a dictionary that stores the normalized string and key value pairs
    for each tokenized string.

    '123 washington blvd' -->
    '{'T000': 'two',
    'B413': 'blvd',
    'T600': 'three',
    'W252': 'washington',
    'O500': 'one',
    'KEY': 'one two three  washington blvd'}'
    '''
    norm = norm_func(s)
    norm_set = set(norm.split())
    norm_dict = {jf.soundex(i):i for i in norm_set}
    norm_dict['KEY'] = norm
    return norm_dict

def bstring(s,o):
    '''
    Compares both 2 strings based on soundex differences and string distance in a namedtuple.
    encode: difference in soundex encoding
    lev: difference in string distance
    ori: holds original string

    bstring('123 washington blvd','123 washington boulevard') -->
    String(encode={'B413': 'blvd'}, lev=5, ori=('123 washington blvd', '123 washington boulevard'))
    '''
    s_dict = encode_phonetic(s)
    o_dict = encode_phonetic(o)
    e_d = {**s_dict, **o_dict}
    e_diff = {k:e_d[k] for k in set(s_dict) - set(o_dict)}

    dist = l.distance(s_dict['KEY'], o_dict['KEY'])
    return String(e_diff, dist, (s,o))

I also tried timing the functions and I understand that a big part of the runtime depends on the string length, which I am leaving out at the moment.

import timeit

print(bstring('123 washington blvrd','123 washington boulevard'))
print(timeit.timeit(lambda: bstring('123 washington blvd','123 washington boulevard'), number= 1000000))
>>String(encode={}, lev=4, ori=('123 washington blvrd', '123 washington boulevard'))
>>47.34113038036594

Is there anything I to improve the code runtime from the data model perspective?


texts:
I looked at a bunch of AngularJS directives checking for uniqueness of a username and decided to try for the simplest implementation. It does what I want but may not really be 'idiomatic' Angular.

Here is the form element:

<input type="text"
    name="username"
    ng-model="form.username"
    unique-username=""
    required
/>
Username taken!

Here's the directive:

.directive('uniqueUsername', function($http) {
      return {
           restrict: 'A',
           require: 'ngModel',
           link: function (scope, element, attrs, ngModel) {
                element.bind('blur', function (e) {
                     ngModel.$setValidity('unique', true);

                     $http.get("/api/checkUnique/" + element.val()).success(function(data) {
                          if (data) {
                              ngModel.$setValidity('unique', false);
                          }
                     });
                });
           }
      };
})

And the ExpressJS call:

if (data) {
      console.log("found " + data.username);
      return res.send(data.username);
}
else {
      console.log("not found");
      return res.send(404);
}

I would appreciate any feedback on why this is good or bad and if possible a revision that uses $scope.watch on the model.


texts:
So i made a tic tac toe bot with the following rules (its not unbeatable)
    1) If bot is about to win, it will find the winning move.
    2) If bot is about to lose, it will find a move that prevents the other player from winning.
    3) if none of rule 1 or 2 is found, then it will play a random move

and i think it's highly inefficient, so if you could give optimization advice, that would be great!
class Cell(str): # a class for strings with unique ids, every time
    pass

def mediumbot_move(self, player):
    """
    medium level bot player - allows a bot with two rules to play
    1) If bot is about to win, it will find the winning move.
    2) If bot is about to lose, it will find a move that prevents the other player from winning.
    3) if none of rule 1 or 2 is found, then it will play a random move
    """
    print('Making move level "medium"')
    opponent = self.other_player[player]
    board = self.board.board # the board represented as an array like ["X", "O", " ", "O", ...]
    winning_three = set(itertools.permutations([player, player, " "])) # permutation for all the winning positions
    losing_three = set(itertools.permutations([opponent, opponent, " "])) # permutation for all the losing positions

    # the three across positions
    horizontals = [board[i:i+3] for i in range(0, 7, 3)]
    verticals   = [board[i:9:3] for i in range(3)]
    diagonals   = [board[0:9:4], board[2:7:2]]

    # if a winning pattern found win
    for pattern in (horizontals + verticals + diagonals):
        pattern = tuple(pattern)
        if pattern in winning_three:
            for winning_pattern in winning_three:
                if pattern == winning_pattern:
                    position_id = id(pattern[pattern.index(" ")]) # storing the id of the empty spot to place player on to win
                    for i in range(9): # looping through the board (array) to find the stored id, to place player
                        if id(board[i]) == position_id:
                            self.board.board[i] = Cell(player)
                            return

    # if no winning patterns found, choose a move, that would not result in a loss
    for pattern in (horizontals + verticals + diagonals):
        pattern = tuple(pattern)
        if pattern in losing_three:
            for losing_pattern in losing_three:
                if pattern == losing_pattern:
                    position_id = id(pattern[pattern.index(" ")])
                    for i in range(9):
                        if id(board[i]) == position_id:
                            self.board.board[i] = Cell(player)
                            return

    # if no patterns found, choose a random move
    available_indexes = [index for index in range(9) if board[index] == " "]
    bot_index = random.choice(available_indexes)
    self.board.board[bot_index] = Cell(player)


texts: Get users from groups in active directory, disposing of everything

texts:
I am trying to get active directory groups with their users, all while disposing of all IDisposable assets when they reach the end of their usefulness. The groups and users are passed into a method that extracts certain properties and adds them to ExpandoObjects. This requires a decent number of nested using blocks.

Since the method is private, and most of the variables only exist in the using blocks, I gave the variables very short names. Naming them properly as groupPrincipal or principalSearchResult would involve breaking even more lines to fit the long names.

private IEnumerable<ExpandoObject> GetOuGroupsUsersData(
    PrincipalContext pc)
{
    var data = new List<ExpandoObject>();
    using (var gp = new GroupPrincipal(pc))
    {
        using (var ps = new PrincipalSearcher(gp))
        {
            using (var psr = ps.FindAll())
            {
                foreach (var g in psr.GetGroupPrincipals())
                {
                    using (var gpsr = g.GetMembers())
                    {
                        data.AddRange(
                            gpsr.GetUserPrincipals().Select(
                                u => GenerateData(g, u))
                                .Cast<ExpandoObject>());
                    }
                }
            }
        }
    }
    return data;
}

Is there anything I can do to reduce the number of using blocks? Am I even disposing of everything properly?


texts: Set an attribute to change an objects behavior, at specific times and for a specific period

texts:
I have a program which I require to cease some of it's activities at specific times. This can change day-to-day, week-to-week.

The code below (working) is a test script. My program would check use the sleep_data() data set to check if the current date falls within any of the periods for a given day alongside the other updating of the program's state (every 2 sec). If so, it would call a method and the program sleeps a particular sub-set of it's activities.

There must be a better way.

 #!/usr/bin/env python3

import datetime
import logging
import time

from dateutil.parser import parse

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s - %(levelname)s - %(message)s")
#logging.disable(logging.CRITICAL)

def sleep_data():
    """Return a dict of lists containing tuples of the periods in which to stand
       down selected bot's activities
    """
    #
    # parse("00:00") + oneday_delta = end of current day
    #
    oneday_delta = datetime.timedelta(hours=24)
    #
    # 1 = Monday, 5 = Friday etc. parse returns datetime.datetime object.
    #
    times = {
        1 : [(parse("21:55"), parse("23:15"))],

        2 : [(parse("21:55"), parse("23:15"))],

        3 : [(parse("21:55"), parse("23:15"))],

        4 : [(parse("21:55"), parse("23:15")),
             (parse("15:45"), parse("15:45:10"))],  # test use

        5: [(parse("20:55"), parse("00:00") + oneday_delta)],

        6: [(parse("00:00"), parse("00:00") + oneday_delta)],  # sleep all Sat

        7: [(parse("00:00"), parse("23:15"))],
        }
    return times

class Test:
    def __init__(self, sleep_times: dict):
        self.sleep_times = sleep_times
        self.trading = True

    def check_times(self, day: int, date_time: object):
        """If time within an exclusion period, set trading attrib to False"""
        exclusion_periods = self.sleep_times.get(day)

        for period in exclusion_periods:
            _from, to = period
            if date_time > _from and date_time < to:
                self.trading = False
                return
            self.trading = True

    def run(self):
        while True:
            date_time = datetime.datetime.now()
            day = date_time.isoweekday()
            self.check_times(day, date_time)
            print(self.trading)
            time.sleep(1)

if __name__ == "__main__":
    t = Test(sleep_data()).run()


texts: Linear SVM(in R) giving suspiciously high CV accuracy

texts:
Here is my code that reads a text dataset, featurizes the text column and then does CV using Linear SVM. Could I be leaking labels from somewhere as the accuracy I get is suspiciously high and way more that the accuracy I get from Scikit's Linear SVM(on multiple datasets)?

library(RTextTools)
library(tm)

dataset <- read.csv("Sentiment.csv")
names(dataset)[1] <- "label"
dataset <- dataset[!(is.na(dataset$label) | dataset$label==""),]
labels <- dataset[,1]
text <- dataset[,4]
label <- as.numeric(as.factor(labels))

textCorpus <- Corpus(VectorSource(text))
dtm_matrix <- DocumentTermMatrix(textCorpus, control = list(weighting=weightTf))
container <- create_container(dtm_matrix, label, trainSize = 1:dim(dataset)[1], virgin = FALSE)
svm <- cross_validate(container = container, nfold = 5, algorithm = "SVM", kernel = "linear")

print(svm$meanAccuracy)


texts: Extract a number from a consecutive range in a Google Sheet

texts:
I'm new in coding and I use google script in my spreadsheet to add a list of consecutive numbers automatically by giving the first number to add and the last one (with an arrival date and an option "A" or "B" for each number). I created a table to put all the informations with an html file. The code is "OK", it's working but it's too slow and I reached my limits in coding to improve the code so...is there somebody that can help me or give an hint on that ?

To make the message clearer, here is what I have and what I want at the end :

Before launching the code :

After launching the code, completing the table (forget about the first line) :

Final result with consecutive range of number added :

Code.gs

function onOpen(e) {
   SpreadsheetApp.getUi()
       .createMenu('Arrivage')
       .addItem('Add a new one', 'Arrivee')
       .addToUi();
 }

function Arrivee() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet().getSheetName();
  if (sheet.indexOf("Br") == 0) {
    SpreadsheetApp.getUi().alert("Vous devez sélectionner
la feuille où ajouter l'arrivage et pas celle des colis !");
    return false
  }else{
  var html = HtmlService.createHtmlOutputFromFile('index.html')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
  SpreadsheetApp.getUi()
       .showModalDialog(html, 'Remplissez les infos
nécessaires pour le nouvel arrivage des ' + sheet);
  }
}

function itemAdd(form) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var feuille = ss.getActiveSheet();
  var nb_total = form.colis2 - form.colis1;
  for (i = 0; i <= nb_total; i++) {
    if (i < form.gare){
      var a_values = [[ +form.colis1 + i, form.ddc, "A" ]];
      feuille.getRange(feuille.getLastRow() + 1, 6, 1, 3).setValues(a_values);
    }else{
      var b_values = [[ +form.colis1 + i, form.ddc, "B" ]];
      feuille.getRange(feuille.getLastRow() + 1, 6, 1, 3).setValues(b_values);
    }
  }
}

index.html

<!DOCTYPE html>

    <base target="_top" >

  <form>
    Numéro arrivage :
    <input type="text" name="br">

    Numéro colis 1 :
    <input type="text" name="colis1">

    Numéro colis 2 :
    <input type="text" name="colis2">

    Gare :
    <input type="text" name="gare">

    Date de création :
    <input type="text" name="ddc">

     <input type="button" value="Ajouter"
        onclick="google.script.run
            .withSuccessHandler(google.script.host.close)
            .itemAdd(this.parentNode)" />
    </form>


texts:
I have an algorithm for generating permutations in Python

from collections import Counter

def permutations(A):
    def permutations(A):
        if len(A) == 0:
            return
        if len(A) == 1:
            yield A
        else:
            for i in range(1, len(A)):
                for p in permutations(A[i:]): # Pretend slicing is O(1)
                    for q in permutations(A[:i]): # Pretend slicing is O(1)
                        yield p + q # Pretend O(1)
                        yield q + p # Pretend O(1)
    return set(permutations(A))

P = permutations((1, 2, 3))
C = Counter(P)
print(P)
print(C)

Which has output

{(3, 1, 2), (1, 3, 2), (3, 2, 1), (2, 3, 1), (1, 2, 3), (2, 1, 3)}
Counter({(2, 1, 3): 1, (1, 3, 2): 1, (3, 1, 2): 1, (3, 2, 1): 1, (2, 3, 1): 1, (1, 2, 3): 1})

Assuming I don't care about the time it takes to slice/concatenate arrays, is this the most efficient algorithm for generating permutations? If not, what can I do to improve it?


texts:
Is there a better method for covering errors in my case? I am looking for best practice for now and future instances.

Foreseen errors that could arise:

No attributes at all
Some attributes could be missing
Attribute value could be empty

// converting dom into array to use later
$fields = $dom->getElementsByTagName($field);
$arr['field'] = array();

foreach ($fields as $field) {
    $attributes = isset($field->attributes) ? $field->attributes : NULL;

    if (!empty($attributes)) {
        // the method getNamedItem($string) returns NULL if not found
        $name = !empty($attributes->getNamedItem('name')) ? $attributes->getNamedItem('name')->nodeValue : NULL;
        $id = !empty($attributes->getNamedItem('id')) ? $attributes->getNamedItem('id')->nodeValue : NULL;
        $field_name = !empty($attributes->getNamedItem('field_name')) ? $attributes->getNamedItem('field_name')->nodeValue : NULL;

        if (!empty($name) && !empty($id) && !empty($field_name)) {
            $arr['field'][$name][$id][$field_name] = $field->nodeValue;
        }
    }
}


texts:
I'm starting to learn about data structures and coding in C. The stack is the simplest of all data structures so I'm trying to implement an ADT stack with dynamically allocated array in C. This implementation does have one obvious problem i.e. it hoards memory even after popping the data. How do I solve this problem?

stacklib.h

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

#ifndef STACKLIB_H
#define STACKLIB_H

/* generic type pushed into the stack */
/* in this case it's just an int */
typedef int item_t;

/* our stack data type */
typedef struct {
    int size;
    int capacity;
    int *elements;
} stack;

/* interface to our new stack data type */
stack* create_stack(int capacity);
int push_stack(stack *mystack, item_t data);
void* pop_stack(stack *mystack);
void delete_stack(stack *mystack);

#endif

stacklib.c

#include "stacklib.h"

/* a helper function to handle exceptions */
void handle_error(const char* message)
{
    if(errno) {
        perror(message);
    } else {
        printf("Error: %s\n", message);
    }

    exit(1);
}

stack* create_stack(int capacity)
{
    stack *stack_ptr = (stack*) malloc(sizeof(stack));

    if(stack_ptr == NULL)
        handle_error("Error while allocating memory.");

    int *elements_ptr = (item_t *) malloc(capacity*sizeof(item_t));

    if(elements_ptr == NULL)
        handle_error("Error while allocating memory.");

    stack_ptr->size = -1;
    stack_ptr->capacity = capacity;
    stack_ptr->elements = elements_ptr;

    return stack_ptr;
}

void delete_stack(stack *mystack)
{
    free(mystack->elements);
    free(mystack);
    mystack = NULL;
}

/* Returns 0 on success, 1 on failure */
int push_stack(stack *mystack, item_t data)
{
    int res = 0;
    /* double the array size when stack is full */
    if(mystack->size == (mystack->capacity - 1)) {
        item_t *tmp = (item_t*) realloc(mystack->elements, sizeof(item_t) * mystack->capacity * 2);
        if(tmp == NULL) {
            res = 1;
        } else {
            mystack->elements = tmp;
            mystack->capacity = mystack->capacity * 2;
        }
    }
    mystack->size++;
    mystack->elements[mystack->size] = data;

    return res;
}

/* Returns a pointer to the popped data or NULL if the stack is empty */
void* pop_stack(stack *mystack)
{
    int *res;
    if(mystack->size == -1) {
        res = NULL;
    } else {
        res = &mystack->elements[mystack->size];
        mystack->size--;
    }
    return res;
}

main.c

#include "stacklib.h"

int main(void){
    stack *my_stack = create_stack(5);
    item_t i;
    for(i = 0; i < 50; i++)
        push_stack(my_stack, i);

    item_t res, *item ;
    while((item = (item_t*)pop_stack(my_stack)) != NULL) {
        res = *item;
        printf("data: %d\n", res);
    }
    delete_stack(my_stack);
    printf("last item popped was  %d\n", res);
    return 0;
}


texts: VBA - create separate spreadsheets from a filtered table

texts:
The task is relatively simple and until now it was always performed by some poor admin soul.  There is a large table that needs to be filtered based on a simple criteria and each view has to be saved as a new spreadsheet.
The code is as simple as the task (and as my coding skills) so I would love to get some feedback about any tricks I might have missed to make it more robust or "best practices" advice.
Option Explicit

Sub SplitWorksheet()

    Dim d As Long
    Dim dctList As Object
    Dim varList As Variant
    Dim varName As Variant
    Dim wkb As Workbook
    Dim wks As Worksheet
    Dim rng As Range
    Dim wkbNew As Workbook
    Dim strPath As String

    Application.DisplayAlerts = False
    Application.ScreenUpdating = False

    Set wkb = ThisWorkbook
    Set wks = wkb.Sheets("Data")
    Set rng = wks.Range("A1").CurrentRegion

    strPath = Application.ThisWorkbook.Path & "\Distribution\"

    Set dctList = CreateObject("Scripting.Dictionary")
    dctList.CompareMode = vbTextCompare

    With wks

        varList = .Range(.Cells(6, "H"), .Cells(Rows.Count, "H").End(xlUp)).Value2

        For d = LBound(varList) To UBound(varList)
            dctList.Item(varList(d, 1)) = vbNullString
        Next

        For Each varName In dctList
            .Range("a1").CurrentRegion.AutoFilter Field:=8, Criteria1:="=" & varName, Operator:=xlFilterValues

            Set wkbNew = Workbooks.Add
            .Range("A1").CurrentRegion.SpecialCells(xlCellTypeVisible).Copy _
                Destination:=wkbNew.Sheets(1).Range("A1")
            wkbNew.SaveAs strPath & varName & ".xlsx"
            wkbNew.Close

        Next

        .Range("a1").CurrentRegion.AutoFilter

    End With

    Application.DisplayAlerts = True
    Application.ScreenUpdating = True

    MsgBox "All done, individual spreadsheets have been saved", vbOKOnly, "Great success!"

End Sub