texts: generic implementation approaches for a recursive function

texts:
Let's take the famous fibonacci problem as an example but this is a generic problem. Also, taking scala as the language as it's rather feature-rich. I want to know which solution you'd prefer.

we all know that the following implementation is evil as it's not stack-safe:

//bad!
def naiveFib(n: Int): BigInt = {
  if (n <= 1)
    1
  else
    naiveFib(n - 1) + naiveFib(n - 2)
}

we can improve it and make it tail-recursive and stack-safe:

def fibStackSafe(n: Int): BigInt = {
  @tailrec
  def internally(cycles: Int, last: BigInt, next: BigInt): BigInt =
    if (cycles > 0)
      internally(cycles-1, next, last+next)
    else
      next
  internally(n - 2 , last = 1, next = 1)
}

acceptable solution. Equally acceptable, is a solution like:

def fibByEval(n: Int): BigInt = {
  def internally(cycles: Int, last: BigInt, next: BigInt): Eval[BigInt] =
    Eval.always(cycles > 0).flatMap {
      case true =>
        internally(cycles-1, next, last+next)
      case false =>
        Eval.now(next)
    }
  internally(n - 2 , last = 1, next = 1).value
}

which uses cats's Eval/Monix's Coeval (slight difference between the two, feel free to comment on your preference) which guarantees stack-safety by definition. Although an Eval-powered function can still lack heap-safety and give you memory error. It does win you a few other things too.

Here is a Stream/LazyList attempt which uses the concepts of lazy-evaluation:

def fibByZip(n: Int): BigInt = {
  def inner:Stream[Pure, BigInt] = Stream(BigInt(1)) ++ Stream(BigInt(1)) ++ (inner zip inner.tail).map{ t => t._1 + t._2 }
  inner.drop(n-1).take(1).compile.toVector.head
}

this one comes with the feature/overhead of internally "caching" the intermediate results.

Here is a more/less (depending on your point of view) readable version of the above:

def fibByScan(n: Int): BigInt = {
  def inner: Stream[Pure, BigInt] = Stream(BigInt(1)) ++ inner.scan(BigInt(1))(_ + _)
  inner.drop(n-1).take(1).compile.toVector.head
}

and finally, here is an effect-full approach which uses fs2 streams and cats's Ref:

def fibStream(n: Int): IO[Int] = {
  val internal = {
    def getNextAndUpdateRefs(twoBefore: Ref[IO, Int], oneBefore: Ref[IO, Int]): IO[Int] = for {
      last <- oneBefore.get
      lastLast <- twoBefore.get
      _ <- twoBefore.set(last)
      result = last + lastLast
      _ <- oneBefore.set(result)
    } yield result

    for {
      twoBefore <- Stream.eval(Ref.of[IO, Int](1))
      oneBefore <- Stream.eval(Ref.of[IO, Int](1))
      _ <- Stream.emits(Range(0, n-2))
      res <- Stream.eval(getNextAndUpdateRefs(twoBefore, oneBefore))
    } yield res
  }

  internal.take(n).compile.lastOrError
}

it's not pure but it's thread-safe and pretty readable.

The code starts simple but will change in the future and needs to be maintained.

model changing whereas instead of using the last two entries, you might need the last three elements.
you want to easily debug it and/or reason about it.
you want to easily and efficiently test it
the model might become numerical and non-exact so you might want to test it for more than just correctness.
model will become async to calculate.
might need to introduce parallelism.

I appreciate we should be agile and not future proof things too much, but I am interested to know which option people would go for, considering the following criteria:

readability
conciseness
flexibility to maintain
performance

feel free to mention other criteria I might be ignoring here.


texts: Function to grab all windows and nested windows on a page

texts:
I wrote the following function which takes in a window and returns all nested windows on a webpage (I can get all the windows by calling the function with window.top). Is there a more elegant/efficient way to grab a reference to all the windows and child windows on the page? The function works, but I was having a hard time wrapping my head around writing it completely recursively (without the for loop) as the DOM tree is an n-ary tree, not binary.

function getNestedWindows(window) {
    var windows = [window];
    if (window.length === 0) {
      return windows;
    }
    else {
      for (var i = 0; i < window.length; i++) {
        windows = windows.concat(getNestedWindows(window[i]));
      }
    }
    return windows;
}


texts: Elixir / Phoenix login controller, allowing multiple attempts

texts:
I have a login method in my controller.  I would like to get rid of the imperative "thinking" and write something more functional.

  def login(conn, %{"login" => %{"password" => password}}) do

    conn = conn |> fetch_session

    if count_attempt_login(conn) <= 10 do
      conn
        |> attempt_login(password)
    else
      conn
        |> redirect(to: "/")
    end

  end

  defp count_attempt_login(conn) do
    (conn |> get_session(:count_attempt_login)) || 1
  end

  defp attempt_login(conn, password) when password == @password_login do
      conn
        |> put_session(:is_admin, true)
        |> delete_session(:count_attempt_login)
        |> redirect(to: "/dashboard")
  end

  defp attempt_login(conn, _) do
    conn
      |> put_session(:count_attempt_login, count_attempt_login(conn) + 1)
      |> put_flash(:error, "Impossible to connect with this password")
      |> redirect(to: "/dashboard/auth")
  end


texts: Counting different kinds of line terminator characters in files

texts:
Can someone take a look if this code piece is ok. I'm most interested whether the goroutines are used correctly, but also general Go best practices.

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "path/filepath"
    "regexp"
)

type Endings struct {
    crlf, lf uint
}

func check(e error) {
    if e != nil {
        panic(e)
    }
}

func getFileList(searchDir string) []string {
    fileList := []string{}
    filepath.Walk(searchDir, func(path string, f os.FileInfo, err error) error {
        if !f.IsDir() {
            fileList = append(fileList, path)
        }
        return nil
    })

    return fileList
}

func getFileEndings(filename string, c chan Endings) {
    fileContent, err := ioutil.ReadFile(filename)
    check(err)
    c <- countEndings(string(fileContent))
}

func countEndings(s string) Endings {
    crlf := regexp.MustCompile("\r\n")
    lf := regexp.MustCompile("\n")

    x := len(crlf.FindAllStringIndex(s, -1))
    y := len(lf.FindAllStringIndex(s, -1))

    return Endings{uint(x), uint(y - x)}
}

func splitIntoChunks(arr []string, chunkSize int) [][]string {
    if chunkSize <= 0 {
        panic("chunk size too small")
    }

    if len(arr) <= chunkSize {
        return [][]string{arr}
    }

    numChunks := int(len(arr)/chunkSize) + 1
    chunks := make([][]string, numChunks)

    for i := 0; i < numChunks; i++ {
        l := i * chunkSize
        u := l + chunkSize

        if u > len(arr) {
            u = len(arr)
        }

        chunks[i] = arr[l:u]
    }

    return chunks
}

func main() {
    searchDir := os.Args[1]
    c := make(chan Endings)
    chunkSize := 1000

    fileList := getFileList(searchDir)

    count := Endings{0, 0}
    for _, chunk := range splitIntoChunks(fileList, chunkSize) {
        for _, file := range chunk {
            go getFileEndings(file, c)
        }

        for _ = range chunk {
            result := <-c

            count.crlf += result.crlf
            count.lf += result.lf
        }
    }

    fmt.Printf("crlf: %d, lf: %d\n", count.crlf, count.lf)
}


texts:
I'm solving 387. First Unique Character in a String LeetCode problem defined as:

  Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

  Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

  Note: You may assume the string contain only lowercase letters.

Taking advantage of the input being fully lowercase ASCII I created two bit vectors to track when we encounter a character for the first and second time.

Can this code be improved further? LeetCode says that below code is better than 94.33% solutions. What else could have been done by the last 5.67% solutions that they were better?

class Solution {

  public int firstUniqChar(String s) {
    int firstSpot = 0;
    int secondSpot = 0;
    char[] chars = s.toCharArray();

    for (char c : chars) {
      int mask = 1 << c - 'a';
      if ((firstSpot & mask) == 0) {
        firstSpot |= mask;
      } else if ((secondSpot & mask) == 0) {
        secondSpot |= mask;
      }
    }

    int i = 0;
    for (char c : chars) {
      int mask = 1 << c - 'a';
      if ((secondSpot & mask) == 0) {
         return i;
      }
      i++;
    }
    return -1;
  }

}

Are there tricks that can be done to improve the LeetCode score? It seems that enhanced for-each loop performs better than standard for loop but I can't prove it. It's an observation based on few of my previous submissions.


texts: Multi threading with webrequests/responses

texts:
I have been working with multi threading and would like some feedback on the code, i generally suck at class design/OO which i am trying to improve. Im sure there is a better way of making it neater and maximizing readability.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;

namespace XMLSender
{
    class Program
    {
        private static string serverUrl;
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter the URL to send the XML File");
            serverUrl = Console.ReadLine();

            List<Thread> threads = new List<Thread>();
            List<string> names = new List<string>();
            string fileName = "";

            do
            {
                Console.WriteLine("Please enter the XML File you Wish to send, To start simulation type 'start'");
                fileName = Console.ReadLine();
                if (fileName != "start")
                {
                    Thread t = new Thread(new ParameterizedThreadStart(send));
                    threads.Add(t);
                    names.Add(fileName);
                }
            }
            while (fileName != "start");

            for (int i = 0; i < threads.Count; i++)
            {
                var t = threads[i];
                var name = names[i];
                t.Start(name);
            }

            foreach (Thread t in threads)
            {
                t.Join();
            }

        }
        static private void send(object data)
        {
            try
            {
                //Set the connection limit of HTTP
                System.Net.ServicePointManager.DefaultConnectionLimit = 10000;

                //ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(http://www.contoso.com/example.aspx);

                byte[] bytes;

                //Send XML data to Webserver
                bytes = File.ReadAllBytes((string)data);
                request.ContentType = "text/xml; encoding='utf-8'";
                request.ContentLength = bytes.Length;
                request.Method = "POST";
                //request.Timeout = 20000;
                request.KeepAlive = false;

                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Close();
                }

                // Get response from Webserver
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Stream responseStream = response.GetResponseStream();
                    string responseStr = new StreamReader(responseStream).ReadToEnd();
                    Console.WriteLine(responseStr + Environment.NewLine);
                    responseStream.Close();
                }

            }
            catch (Exception e)
            {
                Console.WriteLine("An Error Occured" + Environment.NewLine + e);
                Console.ReadLine();
            }
        }
    }
}


texts: Refactor module for calls to internal image service

texts:
Looking for help refactoring the following code to follow a Functional Programming paradigm.

The first function builds a configuration object with default settings and optional presets, while the buildResourcePath will assemble a URL for the image service.

getSizedUrl and getSizedSkuUrl returns a URL that will be used for an image tag.

var imgSvcPath = './imageSizer.svc';

/**
 * configureImg
 * Build a configurtion object with sane defaults applied that can be used to construct a url for the ImageResizer service
 */
function configureImg( options ){
    options = options || {};

    var defaults = {
            type: null,
            src: '',
            width: 120,
            height: null
        },
        // use Image presets if an option.type provided
        presets = options.type ? Images.getPresets( options.type ) : {};

    return $.extend( defaults, options, presets );
};

/**
 * buildResourcePath
 * Construct a url for the ImageResize service to be used for the src of <img />
 */

function buildResourcePath( svcName, options ){
    // imageSizer.svc/GetResizedImage?path=[path]&size=[size]&quality=[quality]
    var resourcePath = [],
        conf = configureImg( options ),
        src = ( conf.skuId !== undefined )
            ? '?sku=' + conf.skuId
            : '?path=' + encodeURI( conf.src ),
        size = '&size=' + ( conf.height ? 'h|' + conf.height : 'w|' + conf.width ),
        quality = conf.quality ? '&quality=' + conf.quality : '';

    resourcePath.push( imgSvcPath, svcName, src, size, quality );
    return resourcePath.join( '' );
};

/**
 * getSizedUrl
 * return src of <img /> for GetResizedImage
 */
var getSizedUrl = function( options ){
    if( 'undefined' === typeof options.src ) {
        console.error( 'upi.Services.Image::getSizedUrl configuration options must provide an image src string' );
    }

    return buildResourcePath( 'GetResizedImage', options );
};

/**
 * getSizedSkuUrl
 * return src for an <img /> for GetResizedSkuImage
 */
var getSizedUrlForSku = function( skuId, options ){
    if( 'undefined' === typeof skuId ) {
        console.error( 'upi.Services.Image::getSizedSkuUrl configuration options must provide sku ID' );
    }

    options = options || {};
    options[ 'skuId' ] = skuId;
    return buildResourcePath( 'GetResizedSkuImage', options );
};

Image = {
    getSizedUrlForSku: getSizedUrlForSku,
    getSizedUrl: getSizedUrl
};


texts: Web API with IoC and database integration tests

texts:
I've made integration tests for a major part of my application. I test my dependency injection is set up correctly, creating controllers with it's dependencies going all the way to the database (using localDB) and returning the response. I'm looking for what could be improved.

Here is the general concept of my tests:

public class TestDbInitializer : DropCreateAlways<MyContext>()
{
    public static List<Item> Items;

    public override Seed(DbContext context)
    {
        Items = new List<Item>();

        // Adding items
        // ..

        Items.ForEach(x => context.Add(x));

        context.SaveChanges();
    }
}

public class BaseTransactionsTests
{
    private TransactionScope _scope

    [TestInitialize]
    public void Initialize()
    {
        _scope = new TransactionScope();
    }

    [TestCleanup]
    public void Cleanup()
    {
        _scope.Dispose();
    }
}

[TestClass]
public class IntegrationTests : BaseTransactionsTests {

    private IDependenciesContainer _container;

    public static void AssemblyInit(TestContext context)
    {
        Database.SetInitializer(new TestDbInitializer());

        _container = new DependenciesContainer();

        // Registers all my application's dependencies
        _container.RegisterAll();
    }

    [TestInitialize]
    public void Initialize()
    {
        using (var context = new MyContext("TestsDatabase"))
        {
            context.Initialize(true);
        }
    }

    [TestMethod]
    public void TestAddItem()
    {
        var controller = _container.Resolve<MyController>();

        var result = controller.AddItem(new Item({Name = "Test"}))

        var goodResult = result as OkNegotiatedResult<string>();

        if (result == null)
            Assert.Fail("Bad result")

        using (var context = new MyContext("TestsDatabase"))
        {
            Assert.AreEqual(context.Items.Count, TestDbInitializer.Items.Count + 1)
        }
    }
}

I use my dependency injector in my tests, registering all dependencies once (AssemblyInitialize).

I created a DB instance for testings, and a specific DropCreateAlways initializer with a fake data Seed method, which I set as the initializer in the AssemblyInitialize as well.

I want to reseed the database with my fake data before each test run. For that case I implemented the base class which holds a transaction scope.

When I run my tests, the following exception is thrown when seeding the database in the TestInitialize:

  DROP DATABASE statement cannot be used inside a user transaction

How should I deal with it?

Is there a way I can stimulate a real Http request, so that my ModelState.IsValidvalidation will function as it does when running the real thing? Are there any more ways I can improve those testings?


texts:
I am trying to scrape the YouTube video streaming page to get the metadata of the video. I am considering this YouTube page as an example. You can find the HTML contents of that page over here (I have removed some not-so-useful JavaScript and provided the relevant HTML content).
I am using Jsoup (a Java HTML parser) for this.
I am getting the content what I want but I just wanna know is this the right way to do it?

public VideoData getVideoData(String videoUrl) throws IOException {
    Document doc = Jsoup.connect(videoUrl).header("User-Agent", "Chrome").get();
    Element body = doc.body();
    String videoThumbnail = body.getElementsByAttributeValue("itemprop", "thumbnailUrl").get(0).attr("href");
    String videoEmbedUrl = body.getElementsByAttributeValue("itemprop", "embedURL").get(0).attr("href");
    String videoTitle = body.getElementById("eow-title").attr("title");
    String userLink = body.getElementById("watch7-user-header").getElementsByAttributeValue("class", "yt-user-photo yt-uix-sessionlink      spf-link").attr("href");
    String userPhoto = body.getElementById("watch7-user-header").getElementsByTag("img").attr("data-thumb");
    String channelLink = body.getElementById("watch7-user-header").getElementsByClass("yt-user-info").get(0).child(0).attr("href");
    String channelName = body.getElementById("watch7-user-header").getElementsByClass("yt-user-info").get(0).child(0).wholeText();
    boolean isChannelVerified;
    try {
        isChannelVerified = body.getElementById("watch7-user-header").getElementsByClass("yt-user-info").get(0).child(1).attr("aria-label").equalsIgnoreCase("Verified") ? true : false;
    } catch (Exception e) {
        isChannelVerified = false;
    }
    String noOfSubs = body.getElementsByClass("yt-subscription-button-subscriber-count-branded-horizontal yt-subscriber-count").attr("title");
    String viewCount = body.getElementsByClass("watch-view-count").text();
    String noOfLikes = body.getElementsByAttributeValue("title", "I like this").get(0).text();
    String noOfDislikes = body.getElementsByAttributeValue("title", "I dislike this").get(0).text();
    String publishedOn = body.getElementById("watch-uploader-info").text().replace("Published on ", "");
    String description = body.getElementById("watch-description-text").children().text();
    boolean isFamilyFriendly = body.getElementsByAttributeValue("itemprop", "isFamilyFriendly").attr("content").equalsIgnoreCase("True") ? true : false;
    String genre = body.getElementsByAttributeValue("itemprop", "genre").attr("content");
    VideoData videoData=new VideoData(videoThumbnail,videoEmbedUrl,videoTitle,userLink,userPhoto,channelLink,channelName,isChannelVerified,noOfSubs,viewCount,noOfLikes,noOfDislikes,publishedOn,description,isFamilyFriendly,genre);
    return videoData;
}


texts: Fulfillment webhook with Dialogflow to operate on a Firestore database

texts:
I'm currently calling a fulfillment webhook with dialogflow in my node backend, performing crud operations on a firestore db. Is there a better, cleaner way to write these?

My code seems very poorly written but it works. I am striving to write cleaner more readable code so I'm looking for someone to give me some pointers on how to write better API calls with webhooks.

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });

//DATABASE API CALLS HERE!//
switch (agent.action) {
case "FAV_COLOR":
  agent.handleRequest(agent => {
    return new Promise(() => {
      async function writeToDb() {

        const databaseEntry = agent.parameters.color;

        const dialogflowAgentRef = db.collection("user").doc("color");

      try {
        await db.runTransaction(transaction => {
          transaction.set(dialogflowAgentRef, {
            entry: databaseEntry
          });
          return Promise.resolve("Write complete");
        });
        agent.add(
          `Wrote "${databaseEntry}" to the Firestore database.`
        );
      } catch (e) {
        agent.add(
          `Failed to write "${databaseEntry}" to the Firestore database.`
        );
      }
    }
    writeToDb();
  });
});
break;

default:
  console.log("ITS BROKEN");

});

It's currently inside a switch statement because I want to trigger different fulfillments based on actions. Neither agent.add statement is triggered.

Also, if someone could throw in some tips about debugging these I would really appreciate it. I've just been deploying the functions, adding a console.log(JSON.stringify()); and then checking in the firebase console functions section for errors. Seems incredibly inefficient.


texts: Use async/await to implement mutual exclusion in JavaScript

texts:
I needed to execute a sequence of async tasks in JavaScript. They are async because I need them to be non-blocking, but I still want the current task to end before starting the next one.
The order of tasks doesn't matter, the only important thing is that they are in mutual exclusion with each other.
For this reason, maybe because of C/C++ background, I was about to implement a queue and a system of locks. Then I stop to think if the problem could be solved just using async/await, and I ended up with this solution:
previousPromise = null;

async function enqueue(task) {
  while (previousPromise) {
    await previousPromise;
  }

  previousPromise = executeTask(task);
  await previousPromise;
  previousPromise = null;
}

In practice, I use the promise subscribers internal queue as the lock queue, in order to achieve a non-blocking wait. When the promise resolves, it awakes all the async tasks† and the first finding previousPromise equals to null will continue.
Here is a codepen example.
Is there any problem in this solution?
Thank you

Side note 1: a real lock system is obviously not needed. JavaScript is single-threaded, so there isn't any risk to be preempted after the while and before executeTask assignment.

Side note 2: the tasks arrive from the server in an asynchronous fashion, so I can't collect them all before executing.

† It actually calls the first callback in the subscriber's list


texts: What is the simplest way to hide labels and inputs with javascript?

texts:
What is the simplest way of hiding labels and inputs in a way that they do not affect the layout. See image and the code below. The label text3 is hidden and there is no extra gap between text2 and text4. In this implementation I put both in div container and change its .style.display property.

Edit: the figure is excactly what I want but the implementation is not good. In other words, how to rewrite the function (e.g. getting rid of div and using css...).

<html>
<body>
<script type="application/javascript">

    function hideableLabelAndTextInput(divId, inputId, labelTxt){
        // container
        var hiderDiv = document.createElement('div');
        hiderDiv.style.display = 'block';
        hiderDiv.id = divId

        // label
        var newLabel = document.createElement('label');
        newLabel.innerHTML = labelTxt;

        // textBox
        var newTextBox = document.createElement('input');
        newTextBox.type = 'text';
        newTextBox.id = 'inputId';

        // grouping
        hiderDiv.appendChild(newLabel);
        hiderDiv.appendChild(newTextBox);

        return hiderDiv;
    }

    for (var i=0; i<10; i++){
        elem = hideableLabelAndTextInput('div' + i, 'text' + i, 'text' + i);
        document.body.appendChild(elem);
    }

    document.getElementById('div3').style.display = 'none';
    document.getElementById('div6').style.display = 'none';

</script>
</body>
</html>


texts:
I have the following dataset

kkk<-data.frame(days=1:100,positive=rbinom(100,1,0.05))

Over the monitoring period of 100 days, if an event occurs then for that day kkk$positive==1 else kkk$positive==0

The following function, samples k=s.freq=1:12 number of times j=s.length=1:30 consecutive elements from the sample space and checks if at least in one of the samples an event was recorded. The sample space consists of all possible j consecutive combinations of kkk$days. The elements of the sample space are overlapping. Before each of the k=s.freq=1:12 samples, the sample space is reevaluated and elements that have common days with the sampled element are removed before the next sampling occurs (for the total of k samplings).

my.sampling<-function(days, status, s.length, s.freq, iter){

    start<-Sys.time()

    #build the data frame
    ddd<-data.frame(days=days, positive=status)

#length of each sample
    j<-s.length

#Buld the sample space
    monitor.ss<-matrix(nrow=dim(ddd)[1]-j+1, ncol=j+1)
    n.row<-dim(ddd)[1]-j+1

    #Create the elements of sample space: each row of the monitor.ss is an element of the sample space
    for (i in 1:j){
        monitor.ss[,i]<-i:(n.row-1+i)
    }
    rm(i)

    #adds if the each of the possible samples of the sample space at least one event was observed or not
    monitor.ss[,j+1]<-apply(monitor.ss,1,function(x) {
        r.low<-range(x,na.rm=T)[1]
        r.high<-range(x,na.rm=T)[2]
        return(as.numeric(sum(ddd$positive[r.low:r.high])>0))})

    #Build the initial sample space as data frame
    sampling.start<-data.frame(monitor.ss)

suc.list<-rep(NA, iter) #Initiate a vector to keep track of successes

    #Now the sampling takes place

    for (i in 1:iter) { #for each iteration

        sampling.start<-data.frame(monitor.ss)
        k<-s.freq #number of samples drawn from the sample space
        k.t=0 #controller to break the while loop
        suc<-0

        while (k.t<=k | dim(sampling.start)[1]>0) { #breaks the while loop if k reaches the specified limit (k=s.freq) or if the reduction of the sample space (see below) does not leave any elements in the sample space

            s<-sampling.start[sample(nrow(sampling.start),1),] #samples the first trial
            suc<-suc+s[1,j+1] #adds up if there is a success or not ( a tleast one event in the sample was observed)
            sampling.start <- sampling.start[apply(sampling.start, 1, function(x) !any(x %in% as.numeric(s[,1:j]))),] #sample space reduction: Elements of the sample space that intersect with the sample that was just selected are removed from the sample space before the next sampling occurs
            k.t<-k.t+1 #controller for the wile loop
        }

        suc.list[i]<-(suc/k.t)

    }
    print(Sys.time()-start)
    message("")
    #hist(suc.list, breaks=sqrt(iter))
    return(suc.list)
}

For example:

my.sampling(kkk$days, kkk$positive, s.length=3, s.freq=5, iter=300)

My problem is that the function requires about 100msec for each iteration and I need to run this function about 100.000 times with at least 1000 iterations each time. I have used preallocation of the vectors and apply to speed things up, however its still too slow.

Parallel processing is applicable to my problem as I can split the data on which the function will have to run on multiple cores, however if my calculations are right I need about 120 days of processing pro CPU core.

Is this possible to reduce the run time of the function? I have tried cpmfun but without much improvement. Otherwise I have to resort to some type of AWS EC2 solution.

Thanks a lot


texts: Checks size of and number of files in each subdirectory

texts:
The code snippet here checks in every folder for subfolders, and stores the sub-sub folders
This is my sample directory structure. I want to read through every sub-folders to find the number of files and total size of the sub folder.

--Parent
    |---FolderA
    |   |__subFolder1
    |   |__subFolder2
    |
    |---FolderB
        |__subFolder3
        |__subFolder4
        |__subFolder5

import glob
import os
from IPython import embed
import subprocess
import humanize

list_of_files = os.listdir(os.getcwd())
total_stats =[]
path = os.getcwd()

for files in list_of_files:  #check FolderA, Folder B etc.,
        print files
        while (os.walk(path+"/"+files).next()):
            curr_path ,dirs,_ = os.walk(path+"/"+files).next()
            data_dict = {}
            flag = "_hd"

            for d in dirs:  #check subFolder1,2,3,4...
                 sub_p,sub_d,_ = os.walk(curr_path+"/"+d).next()
                 for d  in sub_d:         #reads through files inside subfolder
                   p,_,f =os.walk(sub_p+"/"+d).next()
                   total_size = 0
                   for fn in f:          #Finds total size of all files
                       total_size += os.path.getsize(p+"/"+fn)
                   data_dict[d+flag] =  [len(f),humaize.naturalsize(total_size)] #prints file size in human readable form Ex: '2.3MB'
                 flag = "_rd"
            break
    total_stats.append([files,data_dict])        #updates no. of files and sizes

How can I optimize this code to avoid these many ridiculous amounts of for loops?


texts: Implementation of exp function in C using Taylor Series expansion

texts:
I am trying to write code to calcultate ex using:

$$e^x = \sum_{n=0}^\infty \frac{x^n}{n!} = 1 + x + \frac{x^2}{2!} + \frac{x^3}{3!} + \frac{x^4}{4!} + \cdots $$

This is the code I have, which works for small values of x.
Please do not pay attention to the variable e, specifically to the fact that user enters it.

#include <stdio.h>
#include <math.h>

int main(void) {
    double x0,x1,e,x,sum=0.0;
    int n=0;
    scanf("%lf %lf",&x,&e);
    x1=1;
    do{
        sum+=x1;
        x0=x1;
        x1=(x/++n)*x0;
    }
    while(x1/x0>e);

    printf("sum=%lf, \nexp=%lf",sum,exp(x));
    return 0;
}

For input 50 0.00001 number of decimal places for e doesn't matter.
it generates:

sum=5184705528587076239360.000000,
exp=5184705528587072045056.000000

For input 21 0.00000001:

sum=1318815734.483214,
exp=1318815734.483215

The difference only increases as x increases.
I assume that condition is wrong but see no other way of doing it.


texts: How could I make my controller a little less hideous?

texts:
I have a controller. It functions as follows:

A user imports a file and decides whether the files contents contain new entries to be placed into a database, or existing entries entries to be updated.

The user clicks on the import button and is sent to the controller below. If there are any warnings or errors, the validation results screen is shown - to help the users correct their data.

If the file doesn't contain any errors or warnings, the validation screen will be skipped and their file contents will be inserted/updated into the database.

This is clearly far too much logic for a controller as I have read that the controller is simply meant to decide which view to send the data to. I am having a rather difficult time determining how to extract out the data.

I am looking for suggestions on what my next step should be. Thank you to anyone who takes time to help me.

public ActionResult ValidationResultsScreen(HttpPostedFileBase file, DatabaseAccessMode databaseAccess)
{
    try
    {
        var fileLocation = Path.Combine(Path.GetTempPath(), string.Join(Guid.NewGuid().ToString(), file.FileName));

        Session["TempFileLocation"] = fileLocation;
        Session["DatabaseAccessMode"] = databaseAccess;

        file.SaveAs(fileLocation);

        var importer= new Importer(_connectionString, _logManager, databaseAccess,Server.MapPath("..\\bin"));

        var parsedValues= importer.ParseFile(fileLocation);

        var failedValues = ParsedValues.Where(x => x.ParsedState != ParsedState.Success);

        if (failedValues.Any())//if there were any warnings or errors display the validation results screen
        {
            return View(processedValues);
        }
        //else import the file to the database

        var transactionResults = importer.UploadToDatabase(parsedValues);

        var failedDBTransactions= RetrieveFailedResults(transactionResults);

        return failedDBTransactions.Any()
            ? View("DatabaseImportErrorScreen", failedDBTransactions)
            : View("DatabaseImportResults", transactionResults);
    }
    catch (Exception exception)
    {
        ViewBag.ExceptionMessage = exception.Message;
        return View("DefaultErrorScreen");
    }
}


texts:
Looking for feedback/critiques/alternatives to my solution for the 1st Project Euler question:

{-|
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3,5,6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.
-}

import Data.List

-- Finds all multiples of a factor below set limit, by computing factor*n and adding to a list, until factor*n > limit
f_multiple :: [Int] -> Int -> Int -> Int -> [Int]
f_multiple multiples current limit factor
        | (current * factor) >= limit   = multiples
        | otherwise         = f_multiple (multiples ++ [current * factor]) (current + 1) limit factor

sum_multiples :: Int -> Int -> Int -> Int
sum_multiples max first_factor second_factor = foldr (+) 0 ( (f_multiple [] 0 max first_factor) `union` (f_multiple [] 0 max second_factor))


texts:
I am new to database design but am fairly familiar with SQL and its syntax. I want to create a database for an e-commerce website that will sell a single product type such as a shirt. They could be different sizes, colors, and design. I formulated list of information I thought would be necessary to collect from a visitor and are included in the tables I made.

Right now I have tables being:

Products
Customer
Credit_Card_Details
Order_Details
State_tax
Shopping_Cart
Purchase_history
Shipping type

The tables I created:

 CREATE TABLE `shipping_type`
  (
 `type_of_shipping` VARCHAR(30) NOT NULL DEFAULT '',
 `price`            DOUBLE(6, 2) NOT NULL,
 `aprox_delivery`   INT(11) NOT NULL,
 PRIMARY KEY (`type_of_shipping`)
 )
 engine=innodb
 DEFAULT charset=latin1;

 CREATE TABLE `shopping_cart`
  (
 `shopping_cart_id` INT(11) UNSIGNED NOT NULL auto_increment,
 `inventory_id`     VARCHAR(11) NOT NULL DEFAULT '',
 `price`            DOUBLE(6, 2) NOT NULL,
 `date`             DATE NOT NULL,
 `user_id`          VARCHAR(30) NOT NULL DEFAULT '',
 `quantity`         INT(11) NOT NULL,
 PRIMARY KEY (`shopping_cart_id`)
 )
 engine=innodb
 DEFAULT charset=latin1;

 CREATE TABLE `state_tax`
 (
 `state_name`     VARCHAR(11) NOT NULL DEFAULT '',
 `sales_tax_rate` DOUBLE(6, 2) NOT NULL,
 PRIMARY KEY (`state_name`)
 )
 engine=innodb
 DEFAULT charset=latin1;

 CREATE TABLE `purchase_history`
 (
 `user_id`      VARCHAR(30) NOT NULL DEFAULT '',
 `inventory_id` INT(11) NOT NULL,
 `date_ordered` DATE NOT NULL,
 `order_id`     INT(11) NOT NULL,
 `quantity`     INT(11) NOT NULL,
 `price`        DOUBLE(6, 2) NOT NULL,
 PRIMARY KEY (`user_id`)
 )
 engine=innodb
 DEFAULT charset=latin1;

CREATE TABLE `products`
(
 `inventory_id` INT(11) UNSIGNED NOT NULL auto_increment,
 `shirt_name`   VARCHAR(50) NOT NULL DEFAULT '',
 `shirt_size`   VARCHAR(30) NOT NULL DEFAULT '',
 `shirt_color`  INT(11) NOT NULL,
 `price`        DOUBLE(6, 2) NOT NULL,
 PRIMARY KEY (`inventory_id`)
)
engine=innodb
DEFAULT charset=latin1;

 CREATE TABLE `order_details`
 (
 `order_id`         INT(11) UNSIGNED NOT NULL auto_increment,
 `user_id`          VARCHAR(30) NOT NULL DEFAULT '',
 `reciever_name`    VARCHAR(100) NOT NULL DEFAULT '',
 `address`          VARCHAR(30) NOT NULL DEFAULT '',
 `city`             VARCHAR(30) NOT NULL DEFAULT '',
 `zip`             VARCHAR(11) NOT NULL DEFAULT '',
 `state`            VARCHAR(30) NOT NULL DEFAULT '',
 `type_of_shipping` VARCHAR(30) NOT NULL DEFAULT '',
 `date_ordered`     DATE NOT NULL,
 PRIMARY KEY (`order_id`)
 )
 engine=innodb
 DEFAULT charset=latin1;

CREATE TABLE `customer`
 (
 `user_id`      VARCHAR(30) NOT NULL DEFAULT '',
 `password`     VARCHAR(30) NOT NULL DEFAULT '',
 `fname`        VARCHAR(30) NOT NULL DEFAULT '',
 `lname`        VARCHAR(30) NOT NULL DEFAULT '',
 `email`        VARCHAR(30) NOT NULL DEFAULT '',
 `address`      VARCHAR(30) NOT NULL DEFAULT '',
 `city`         VARCHAR(30) NOT NULL DEFAULT '',
 `zip`          INT(11) NOT NULL,
 `state`        VARCHAR(30) NOT NULL DEFAULT '',
 `phone number` VARCHAR(11) DEFAULT NULL,
 PRIMARY KEY (`user_id`)
)
engine=innodb
DEFAULT charset=latin1;

CREATE TABLE `credit_card_details`
(
 `cc_num`    VARCHAR(30) NOT NULL DEFAULT '',
 `card_type` VARCHAR(30) NOT NULL DEFAULT '',
 `sec_code`  INT(3) NOT NULL,
 `exp_date`  DATE NOT NULL,
 `user_id`   VARCHAR(30) NOT NULL DEFAULT '',
 PRIMARY KEY (`cc_num`)
)
engine=innodb
DEFAULT charset=latin1;

Is this the most efficient way to do this? I am pretty sure all tables would be in third normal form, and all can be linked. If this is not the correct way to do this, could somebody please point out to me what I could be doing differently to improve my design or how to implement this design in a better way?


texts:
I am building an web application that is going to work in a similar way like photoshop or illustrator regarding layers. Here are my code that is searching the ".case" div for images, and then put these images id's to an array. When that is done we are looping the array to find out if the received image is the same as the one we loop through from the array.

When finding this image we wan't to move it one step up or down in the hierarchy. But this image have a div with controllers associated, so we have to move this in the same way.

So do you think this is the best possible code we can create to get this work? It does work, I only want to find out if there are any better solutions for it.

var arrangeLayers = function(e,direction) {

    var timestampId = e.attr('id');
        timestampId = timestampId.replace('name', '');

    var elem = [];
    $('.case img').each(function(){
        elem.push($(this).attr('id'));
    });

    for (i=0;i<elem.length;i++) {
        if (timestampId == elem[i] && direction == 'down') {
            if (i != 0) {
                $('#' + timestampId).insertBefore($('#' + elem[(i-1)]));
                $('#name' + timestampId).insertBefore($('#' + timestampId));
            }
        } else if (timestampId == elem[i] && direction == 'up') {
            if (i != (elem.length) -1) {
                $('#' + timestampId).insertAfter($('#' + elem[(i+1)]));
                $('#name' + timestampId).insertBefore($('#' + timestampId));
            }
        }
    }
}


texts: Sending user information to server to track hits / traffic on site

texts:
This is working pretty well right now:

var p='';
if(typeof parameters!=='undefined'){p='&p='+parameters;}
var t='';
var l='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for(var i=0;i<64;i++){t+=l.charAt(Math.floor(Math.random()*62));}
if(!sessionStorage.t){sessionStorage.t=t;}
if(!localStorage.t){localStorage.t=t;}
var r=new XMLHttpRequest();
r.open('POST','https://example.com/hit',true);
r.setRequestHeader('Content-type','application/x-www-form-urlencoded');
r.send('r='+document.referrer+'&u='+localStorage.t+'&s='+sessionStorage.t+p);

I have two questions.

About 1% of my hits are getting r, the referrer, correctly, while u and s are NULL. u is like a user id to keep track of unique users, and s is a session id to track the user's session. Are these NULL because of lack of web storage support in the user's browser, or is there another explanation?
Are there any other ways to improve this? Do you see any potential problems?

p is for custom parameters that I need for my individual sites. I already ignore requests from user agents that look like bots. I am pretty sure that the 1% is real users.


texts: Testing Terminal Text Game with Classes and Game Loop

texts:
I am making a super simple and dumb terminal text game to try out unittest in python. I have ran into a problem. When I run the test, the game loop is ran, and I have to manually insert input to continue to the tests.

Is there a way to not run the game loop when I run my tests, so I can test the class methods only?

Any other advice on the code in general would be helpful appreciated as well.

Game concept: Player is prompted to build, gather, recruit, or attack every turn and when someone's castle health is <= 0, game is over.

import os, random

class Player():
    def __init__(self):
        self.castle = 1
        self.villagers = 1
        self.warriors = 0
        self.food = 0
        self.stone = 0

    def takeTurn(self):
        action = 0
        action = int(input("1) Build\n2) Gather\n3) Recruit\n4) Attack\n"))
        if action == 1:
            self.build()
        elif action == 2:
            self.gather()
        elif action == 3:
            self.recruit()
        elif action == 4:
            self.attack()
        else:
            self.takeTurn()

    def build(self):
        if self.stone >= 1:
                self.castle += 1
                self.stone -= 1
        else:
            os.system('clear')
            if self.__class__.__name__ == "Player":
                print("You don't have enough stone!\n")
                printMenu()
            self.takeTurn()

    def gather(self):
        self.food += self.villagers
        self.stone += self.villagers

    def recruit(self):
        if self.food >= 1:
                self.warriors += 1
                self.food -= 1
        else:
            os.system('clear')
            if self.__class__.__name__ == "Player":
                print("You don't have enough food!\n")
                printMenu()
            self.takeTurn()

    def attack(self):
        if self.warriors >= 1:
            if self.__class__.__name__ == "Player":
                ai.castle -= self.warriors
            elif self.__class__.__name__ == "AI":
                player.castle -= self.warriors

class AI(Player):
    def __init__(self):
        super().__init__()

    def makeMove(self):
        action = 0
        # Win if player castle weak
        if player.castle == self.warriors:
            player.castle -= self.warriors
        # Build if castle weak
        elif self.castle == player.warriors:
            if self.stone >= 1:
                self.castle += 1
            else:
                action = random.randint(2, 4)
        else:
            action = random.randint(1, 4)

        if action == 1:
            super().build()
        if action == 2:
            super().gather()
        if action == 3:
            super().recruit()
        if action == 4:
            super().attack()

player = Player()
ai = AI()

def printMenu():
    print("You:\nCastle: " + str(player.castle) + " Food: " + str(player.food) + " Stone: " + str(player.stone) + " Villagers: " + str(player.villagers) + " Warriors: " + str(player.warriors) + "\n")
    print("Computer:\nCastle: " + str(ai.castle) + " Food: " + str(ai.food) + " Stone: " + str(ai.stone) + " Villagers: " + str(ai.villagers) + " Warriors: " + str(ai.warriors) + "\n")

def gameLoop():
    # MAIN LOOP
    playing = False
    if playing:
        printMenu()

        player.takeTurn()
        ai.makeMove()

        if ai.castle <= 0:
            playing = False
            print("You Win!\n")
        elif player.castle <= 0:
            playing = False
            print("You Lose!")
        else:
            os.system('clear')

gameLoop()

import unittest

from game.main import Player

class TestPlayer(unittest.TestCase):
    def setUp(self):
        self.player = Player()

    def test_build(self):
        # Should fail
        self.player.castle = 2
        self.player.stone = 1
        self.player.build()
        self.assertEqual(self.player.castle, 1)

if __name__ == '__main__':
    unittest.main()


texts:
There is a function with bunch of a redundant lets and ←s inside a list monad.

example ∷ (Int, Int, Int, Int, Int)
example = head $ do
  let list1 = [0,1]
  e1 ← list1
  let list2 = φ list1 e1
  e2 ← list2
  let list3 = φ list2 e2
  e3 ← list3
  let list4 = φ list3 e3
  e4 ← list4
  let list5 = φ list4 e4
  e5 ← list5
  return (e1,e2,e3,e4,e5)
    where φ ∷ [Int] → Int → [Int]

So, all list# values are unusable. How can example could be rewritten with >>= or maybe with something else to get (e1,e2,e3,e4,e5) without any lets?


texts: Computational verification of Collatz conjecture

texts:
Prerequisites

The typedef name uint128_t designates an unsigned integer type with width exactly 128 bits.

The UINT128_MAX is maximum value for an object of type uint128_t.

Function int ctz(uint128_t n) returns the number of trailing 0-bits in n, starting at the least significant bit position. If n is 0, the result is undefined.

The macro UINT128_C(n) shall expand to an integer constant expression corresponding to the type uint128_t.

The following macros are defined.

/* all 3^n for n < 41 fits into uint64_t */
#define LUT_SIZE64 41
/* all 3^n for n < 81 fits into uint128_t */
#define LUT_SIZE128 81

The following array is defined and initialized with corresponding values.

/* lut[n] contains 3^n */
uint128_t lut[LUT_SIZE128];

Problem

My program is concerned with verifying the convergence of the Collatz problem, using this algorithm.

The convergence for all values n ≤ 87 × 260 has been proven. [Source: Christian Hercher, Uber die Lange nicht-trivialer Collatz-Zyklen, Artikel in der Zeitschrift "Die Wurzel" Hefte 6 und 7/2018.]

The following function is called for n of the form \$4n+3\$, in order from the smallest one to the largest one, only if all preceding calls returned zero.

The following function should either

return 0 if the Collatz problem for the n is convergent,
return 1 if the function cannot verify the convergence using 128-bit arithmetic,
loop infinitely if the trajectory for the n is cyclic.

Code

int check_convergence(uint128_t n)
{
    uint128_t n0 = n;
    int e;

    do {
        if (n <= UINT128_C(87) << 60) {
            return 0;
        }

        n++;

        e = ctz(n);

        n >>= e;

        if (n < UINT128_C(1) << 64 && e < LUT_SIZE64) {
            return 0;
        }

        if (n > UINT128_MAX >> 2*e || e >= LUT_SIZE128) {
            return 1;
        }

        n *= lut[e];

        n--;

        n >>= ctz(n);

        if (n < n0) {
            return 0;
        }
    } while (1);
}


texts: Python Cartesian Product in a constrained dictonary

texts:
I want to calculate the Cartesian product of n copies of a small list, marker=[0,1,2]. I want to use these Cartesian product tuples as keys in a dictionary. The value per each key is to be a numpy array with n random floats between 0 and 1.

The only twist is that for each key:value pair in the dictionary, if the key has a non-zero number in its index a, I want the corresponding value np.array to have np.nan for the same index.

Below is the function I wrote for that. My question is whether there is a quicker / more efficient way to get the same result.

import itertools
import numpy as np
def create_constrained_dict(n, markers):
    '''
    Create cartesian product of a the same list repeated n times
    It returns a dictionary whose keys are the cartesian products of the
    input lists. The values of the dictionary are numpy arrays of length 'n'.
    If the corresponding dictionary key element for a value is not zero, we replace the value
    with np.nan.
    Belwo is an example:
    So for some key-value pair, NaN's would be lcoated as follows:
         d={(0,0,1): np.array([0.1234, 0.7543, np.nan]),
            (1,2,1): np.array([np.nan, np.nan, np.nan]),
            (1,0,1): np.array([np.nan, 0.2634, np.nan]),
    }

    '''
    d = dict()
    for element in itertools.product(*[markers  for i in xrange(n)]):
        d[element] = np.random.uniform(0, 1,n)
        for i in xrange(n):
            if element[i] !=0:
                d[element][i]= np.nan
    return d

rep_num = 3
marker = [0,1,2]
d = create_constrained_dict(rep_num, marker)

The output looks like this:

print d
{
  (0, 1, 1): array([ 0.84049621,         nan,         nan]),
  (0, 1, 2): array([ 0.17520962,         nan,         nan]),
  (1, 0, 1): array([        nan,  0.96110224,         nan]),
  (0, 2, 1): array([ 0.10395044,         nan,         nan]),
  (2, 2, 0): array([        nan,         nan,  0.60131589]),
  (0, 2, 0): array([ 0.64515576,         nan,  0.05946614]),
  (0, 2, 2): array([ 0.02054272,         nan,         nan]),
  (1, 0, 0): array([        nan,  0.98472074,  0.93688277]),
  (2, 0, 1): array([        nan,  0.64348266,         nan]),
  (1, 2, 0): array([        nan,         nan,  0.71462777]),
  (2, 0, 0): array([        nan,  0.98370414,  0.3517195 ]),
  (1, 2, 1): array([ nan,  nan,  nan]),
  (0, 0, 2): array([ 0.29771489,  0.83521032,         nan]),
  (2, 2, 2): array([ nan,  nan,  nan]),
  (1, 2, 2): array([ nan,  nan,  nan]),
  (2, 0, 2): array([        nan,  0.95682699,         nan]),
  (0, 0, 1): array([ 0.26649784,  0.38120757,         nan]),
  (0, 0, 0): array([ 0.98960411,  0.70080955,  0.25540202]),
  (2, 1, 2): array([ nan,  nan,  nan]),
  (1, 1, 1): array([ nan,  nan,  nan]),
  (0, 1, 0): array([ 0.94015447,         nan,  0.56849242]),
  (1, 1, 0): array([        nan,         nan,  0.30593067]),
  (2, 1, 0): array([        nan,         nan,  0.74205853]),
  (2, 2, 1): array([ nan,  nan,  nan]),
  (2, 1, 1): array([ nan,  nan,  nan]),
  (1, 1, 2): array([ nan,  nan,  nan]),
  (1, 0, 2): array([        nan,  0.27788722,         nan])
}


texts:
I am still pretty new to Haskell and am working on a graph generator for undirected unlabeled graphs containing loops and I have a bottleneck in the following functions. So far, I have not given any thought to performance and just looked for correctness.

I know this kind of question is not really popular, but I'd be interested in general guidelines for improving performance given some naive but correct implementation like the following.

For instance:

Where to enforce strictness?
Should I use vector/array instead of lists? When, where and why?
Should I improve single functions by replacing recursion using folds/maps/etc. or similar?

Additional info:

I'm using -O2  with ghc
profiling shows (when normalizing runtime of connections to 100%)

arqSeq 40% (with almost all time spend in boundsequences)
connectionCombinations 60% with a quarter of the time spend in occurences

I don't think you need to understand all the details.  I'm looking more for micro-improvements (the following determines arcs from a given node to equivalence classes of vertices grouped by their degree).

import Data.List
import Control.Monad

type Arcs = Int
type Count = Int
type Vertex = Int
type MSequence = [Int]
data EquivClass = EC { order :: Int, verts :: [Vertex] } deriving (Eq, Show)
type ECPartition = [EquivClass]
type NodeSelection = [(Arcs,Count)]
type ECNodeSelection = (EquivClass, NodeSelection)

-- number of occurences of unique elements in a list
occurences :: (Ord a) => [a] -> [(a, Int)]
occurences = map (\xs@(x:_) -> (x, length xs)) . group . reverse . sort

-- number of vertices in an equivalence class
ecLength :: EquivClass -> Int
ecLength = length . verts

-- for a given y = (y_1,...,y_n) and a bound m, find all vectors
-- x = (x_1,...,x_n) such that |x| = m and x_i <= y_i
boundSequences :: (Num a, Ord a, Enum a) => a -> [a] -> [[a]]
boundSequences m x | m <= sum x = (fByM . sequence . ranges) x
                   | otherwise = [[]]
    where fByM = filter (\x -> sum x == m)
          ranges = map (\x -> [0..x])

-- return m-sequences (combinations of number of arcs) for the given
-- order to an ECPartition
arcSeq :: Int -> ECPartition -> [MSequence]
arcSeq m x = boundSequences m (map ecProd x)
    where ecProd e = ecLength e * order e

-- return all the possible arc combinations  to an equivalence
-- class for a given number of arcs
connectionCombinations :: Int -> EquivClass -> [NodeSelection]
connectionCombinations arcs = map groupOcc . prune arcs . sequence . orderRep
    where orderRep (EC o v) = replicate (length v) [0..o]
          prune a = nub . map (reverse . sort) . filter ((== a) . sum)
          groupOcc = filter ((/= 0) . fst) . occurences

-- return all the possible lists of equivalence class node selections
-- from a Partition and a givne number of arcs
connections :: ECPartition -> Int -> [[ECNodeSelection]]
connections p order = concatMap (con p) $ arcSeq order p
     where con p arcs = map (zip p) $ zipWithM connectionCombinations arcs p

main = do
    -- small example. In the complete app this is called 10,000's of
    -- times in case of high degrees or vertex counts
    let cons = connections [EC 4 [1], EC 1 [2,3,4]] 5
    mapM_ (print) cons


texts: Create multiple divs inside a containing div

texts:
The below function is used to create multiple content division elements (i.e. <div>) inside a containing <div>. The function is working correctly and is as expected, I just feel the quality of the code itself is a bit poor.

Therefore, can the following function be, in any way, simplified or improved?

generate(chartData) {
      var container = document.createElement("div");
      $(container).attr("class", "container2");

      var myNode = document.getElementById(chartData.bindto.replace("#", "")).appendChild(container);

      for(var i = 0; i < 10; i++) {
        var div = document.createElement('div');
        $(div).attr("class", "block");
        var span = document.createElement('span');
        var text = "Hello World!";
        span.append(text);
        div.append(span);
        myNode.append(div);
      }
    }


texts: Replacing dynamic polymorhism with static polymorphism in C++

texts:
Motivated due to the fact, that the avr-g++ places the vtables in RAM, I wrote a replacement using static polymorphy.

Consider the following example:

volatile uint8_t x;

struct IX {
    virtual void f() const = 0;
//    virtual ~IX() = default; // need delete
};

struct A : public IX {
    const uint8_t v = 0;
    void f() const override {
        x = v;
    }
};

struct B : public IX {
    const uint8_t v = 1;
    void f() const override {
        x = v;
    }
};

struct C : public IX {
    const uint8_t v = 2;
    void f() const override {
        x = v;
    }
};

volatile uint8_t index = 2;

int main() {
    A a;
    B b;
    C c;
    const std::array<const IX*, 3> cc{&a, &b, &c};

    cc[index]->f();

    while(true) {}
}

Here we have some types A, B and C implementing an interface IX and placing pointers in the array cc. Then we call the virtual function f() for a specific instance. (Using this on a small µC like the AVRs, there is a "waste" of RAM, since the vtables are placed in RAM and each object contains a vptr, and a performance penalty due to the indirect call of f().

So I looked for an alternative solution in this case: the simplest way is to use an heterogenous container like std::tuple and write a switch-statement:

const std::tuple<A, B, C> t;

auto f = [](const auto& v) {
    v.f();
};

switch (index) {
case 0:
    f(std::get<0>(t));
    break;
case 1:
    f(std::get<1>(t));
    break;
case 2:
    f(std::get<2>(t));
    break;
default:
    assert(false);
    break;
}

This yields to optimale machine-code but it is an unflexible solution. So I wrote a metafunction to call f() for a specific element of the tuple:

const std::tuple<A, B, C> t;

Meta::visitAt(t, index, [](const auto& v){v.f();});

And the implementation looks like:

namespace Meta {
    namespace detail {
        template<uint8_t  N>
        struct visit {
            template<typename T, typename F>
            static void at(T& tuple, uint8_t index, const F& f) {
                if (index == (N - 1)) {
                    f(std::get<N - 1>(tuple));
                }
                else {
                    visit<N - 1>::at(tuple, index, f);
                }
            }

        };
        template<>
        struct visit<0> {
            template<typename T, typename F>
            static void at(T&, uint8_t , const F&) {
                assert(false);
            }
        };

        template<typename T, typename F, size_t... I>
        void all(const T& tuple, const F& f, std::index_sequence<I...>) {
            (f(std::get<I>(tuple)), ...);
        }

    }
    template<typename... T, typename F>
    void visitAt(const std::tuple<T...>& tuple, uint8_t index, const F& f) {
        detail::visit<sizeof...(T)>::at(tuple, index, f);
    }
    template<typename... T, typename F>
    void visitAt(std::tuple<T...>& tuple, uint8_t index, const F& f) {
        detail::visit<sizeof...(T)>::at(tuple, index, f);
    }
    template<typename... T, typename F>
    void visit(const std::tuple<T...>& tuple, const F& f) {
        detail::all(tuple, f, std::make_index_sequence<sizeof...(T)>{});
    }
}

This works very well in my scenarios, yet is obviously limited to static containers (like std::tuple). There is also a for-each-like iteration Meta::visit().

My question is: are there any other drawbacks / limitations with this approach?

Are there any improvements?


texts: Alternately taking elements from an array

texts:
Given the task of having to return an array that alternately takes elements from two arrays, what would be most Ruby way of completing the task? As of now, I have this code, but it doesn't feel very elegant.

def alternateTake (a, b)
  raise ArgumentError, "Unequal length" if a.length != b.length
  build = []
  (0..a.length-1).each do |x|
    build << (x.even? ? a[x] : b[x])
  end
  build
end

Example input & output:

method([1, 4, 3, 7], [1, 4, 2, 33]) = [1, 4, 3, 33]
method([98, 12, 41], [35, 22, 14]) = [98, 22, 41]
method([12, 33], [66, 45, 3]) = ERROR


texts:
Online coding challenge Hacker Rank.

I tried to solve it using the naive appraoch first but its failing on some of the inputs and rest its getting timed out. How to get started in problem like these so that I could reduce the time complexity involved?

public class Solution {
    private static Set<String> substrings(String text) {
        int length = text.length();
        Set<String> set = new TreeSet<>();

        for (int i = 0; i < length; i++) {
            for (int j = i + 1; j <= length; j++) {
                set.add(text.substring(i, j));
            }
        }
        return set;
    }

    public static void main(String[] args) {
        Scanner scanner =  new Scanner(System.in);
        int T = scanner.nextInt();
        String s = scanner.next();
        int K = scanner.nextInt();
        StringBuilder sb = new StringBuilder();
        for (String sub : substrings(s)) {
            sb.append(sub);
        }
        System.out.println(sb.charAt(K - 1));
    }
}


texts: Counting the number of "on" bits in an int

texts:
Here is some code I wrote as a solution to Programming Exercise 15.3 in Stephen Prata's C Primer Plus, 6th Edition. It is probably worth pointing out that the title of the chapter is Bit Fiddling. The question asks:

  Write a function that takes an int argument and returns the number
  of "on" bits in the argument. Test the function in a program.

My code seems to work for a variety of test-cases. But bit-fiddling seems finicky, and I was wondering if anyone could see any mistakes here. I would also be very interested to hear about ways to improve this code, or better approaches (e. g., more concise, or more efficient) to the problem.

The code that I have forms a bitmask from an unsigned int with only the bit corresponding to the sign bit of the input int set to "on", and then proceeds to check the bits of the input int against the bitmask, moving the test bit towards the lower order bits at each iteration until the last bit has been tested.

Since first posting this question, I have begun to feel uneasy about the expression:

(b_mask & num)

as b_mask is an unsigned int and num is an int. It usually seems like a bad idea to mix signed and unsigned types in the same expression. Is the result of this operation reliable? Any thoughts on this particular issue would be welcome.

#include <stdio.h>
#include <limits.h>

int on_bits(int num);

int main(void)
{
    int input;

    printf("Enter an int value ('q' to quit): ");
    while (scanf("%d", &input) == 1) {
        printf("%d\n", on_bits(input));
        printf("Enter an int value ('q' to quit): ");
    }

    return 0;
}

int on_bits(int num)
{
    int res = 0;
    unsigned b_mask = 0x1;

    /* Move to sign bit */
    for (int i = 1; i < (sizeof(num) * CHAR_BIT); i++)
        b_mask <<= 1;

    /* Check bits */
    while (b_mask > 0) {
        if (b_mask & num)
            ++res;
        b_mask >>= 1;
    }

    return res;
}

Here is a sample interaction:

Enter an int value ('q' to quit): 255
8
Enter an int value ('q' to quit): -255
25
Enter an int value ('q' to quit): 2048
1
Enter an int value ('q' to quit): 2047
11
Enter an int value ('q' to quit): -2047
22
Enter an int value ('q' to quit): 4095
12
Enter an int value ('q' to quit): -4095
21
Enter an int value ('q' to quit): -1234567
22
Enter an int value ('q' to quit): -987654321
16
Enter an int value ('q' to quit): q


texts: Test whether target string is substring of source string

texts:
The code is self-explanatory. It has \$O(n)\$ complexity, and it tells whether a given string is the substring of the source string. Are there any cases where this algorithm fails? Is there anything that can be improved?

    public static boolean isSubStringOf(char src[], char target[]) {
    int pointTarget=0;
    for (int pointSrc = 0;pointSrc < src.length; pointSrc++) {
        // If target's pointer is at target's length , Voila !
        if (pointTarget == target.length)
            return true;

        //If value at src's pointer equals value at target's pointer increment target's pointer and continue.
        if (src[pointSrc] == target[pointTarget]) {
            pointTarget++;
            continue;
        }
        //However if they are not equal reset target's pointer back to target's beginning.
        else if (src[pointSrc] != target[pointTarget]) {
            pointTarget = 0;
        }
    }
    // To handle right corner case
    return pointTarget == target.length;
}


texts: Calling methods of another module from a module, from a class extending both?

texts:
module A
  def methodInA
    # do stuff
    methodInB
    # do stuff
  end
end

module B
  def methodInB
    puts "this is a B method!"
  end
end

class C
  extend A
  extend B

  def initialize
    methodInA
  end
end

c = new C

I'm not feeling good about this.  Is this a good idea in general?  Any pointers as to where I can learn the best pattern for this?


texts:
I am trying to learn clear and concise C++. Currently I'm learning classes in school, and to practice I have made a Fraction class.

I'd appreciate any help regarding style, cleanliness or anything else that would be good to know.

(I know using namespace std; is frowned upon, but it's required in our course.)

#include <iostream>
using namespace std;

class Fraction {
    int numerator, denominator;
private:
    int gcd(int a, int b) {
        while (a != b) {
            if (a > b)
                a -= b;
            else
                b -= a;
        }
        return a;
    }
public:
    Fraction (int, int);
    double decimal();
    string fraction();
    Fraction add(Fraction);
    Fraction subtract(Fraction);
    Fraction multiply(Fraction);
    Fraction divide(Fraction);
};

int main() {
    Fraction f = {2,3};
    cout << f.decimal() << endl;
    Fraction k = {1,4};
    Fraction d = {1,3};
    Fraction result = k.add(d).add(f);
    cout << result.fraction() << endl;
    return 0;
}

Fraction::Fraction(int n, int d) {
    numerator = n / gcd(n, d);
    denominator = d / gcd(n, d);

}
string Fraction::fraction() {
    return to_string(numerator) + "/" + to_string(denominator);
}
double Fraction::decimal() {
    return (double)numerator / (double)denominator;
}

Fraction Fraction::add(Fraction f) {
    return Fraction(numerator * f.denominator + f.numerator * denominator, denominator * f.denominator);
}
Fraction Fraction::subtract(Fraction f) {
    return Fraction(numerator * f.denominator - f.numerator * denominator, denominator * f.denominator);
}
Fraction Fraction::multiply(Fraction f) {
    return Fraction(numerator * f.numerator, denominator * f.denominator);
}
Fraction Fraction::divide(Fraction f) {
    return Fraction(numerator * f.denominator, denominator * f.numerator);
}


texts: Find the total number of ways W, in which a sum S can be reached in N throws of a dice

texts:
I was solving this question:

Given there is a 6 sided dice. Find the total number of ways W, in which a sum S can be reached in N throws.

  Example:

  S = 1, N = 6 => W = 0

  S = 6, N = 6 => W = 1

  S = 7, N = 6 => W = 6

  S = 3, N = 2 => W = 2

How to improve its complexity and make it more readable?

def get_sum_dp(n,s):
    t = [[0 for i in xrange(1,s+2)] for j in xrange(1,n+2)]
    for j in xrange(1,7):
        t[1][j] = 1
    for i in range(2, n+1):
        for j in range(1, s+1):
            for k in range(1,7):
                if k < j:
                    t[i][j] += t[i-1][j-k]
    print t[n][s]

get_sum_dp(2,8)


texts:
I'm looking to improve the efficiency of my code.  Although my current method works, I feel it can be improved.

if ouroraddrlen == (4,):
        ouropip = struct.unpack(">bbbb", payload[6:10]) # Need to change this to accept ipv6 as well
        print "Our I.P : ", ouropip
        notheirip = struct.unpack(">b", payload[10])
        print "No. of their I.P's : ", notheirip
        theiroripv = struct.unpack(">b", payload[11])
        print "Their I.P version:: ", theiroripv
        theiroraddrlen = struct.unpack(">b", payload[12])
        print "Length of their Ip : ", theiroraddrlen
        theirfirstip = struct.unpack(">bbbb", payload[13:17])
        print "First Ip : ", theirfirstip
        theirsecondip = struct.unpack(">bbbb", payload[18:22])
        print "Second Ip : ", theirsecondip

The output is:

Time :  (1401734263,)
Our onion address :
Ip version :  (4,)
Ip length :  (4,)
Our I.P :  ( )
No. of their I.P's :  (2,)
Their I.P version::  (4,)
Length of their Ip :  (4,)
First Ip :  ( )
Second Ip :  ( )

I have removed the real IPs, but they are just IPV4 addresses.

However, what I am wondering, is if it is possible to include an if statement after this section of code:

notheirip = struct.unpack(">b", payload[10])
        print "No. of their I.P's : ", notheirip

where if the notheirip is greater than zero and depending on the length of:

        theiroraddrlen = struct.unpack(">b", payload[12])
        print "Length of their Ip : ", theiroraddrlen

which would be either 4 or 16, then it would set the payload values of the next section.

For example, if notheirip = (2,) and theiroraddrlen = (4,), then I would want it to print out

theirip = struct.unpack(">b       << the number of b required so either 4 or 16 and then the range, this will always start at 13 and go up to either 4 or 16 in the future and loop until all the IPs are displayed.


texts: C-string appender for buffers and strings

texts:
Is this C appender safe, and reasonably optimal?

#define REALLOC_BUFFER_SIZE 4096

char *append(char *orig_str, size_t *orig_str_size, const char *append_str) {
    // no action required if appending an empty string
    if (append_str[0] == 0) {
        return orig_str;
    }

    // does the current char* have enough space?
    size_t req_space = strlen(orig_str) + strlen(append_str) + 1; // +1 for NULL byte

    // resize if the required space is greater than the original buffer size.
    if (req_space > *orig_str_size) {
        // prepare the variable with the amount of space we want
        size_t allocate = *orig_str_size + req_space + REALLOC_BUFFER_SIZE;

        char *new_str = (char *)realloc(orig_str, allocate);
        // resize success..
        if (new_str == NULL) {
            fprintf(stderr, "Couldn't reallocate memory\n");
            return NULL;
        }

        // the realloc didn't fail, here is our new pointer
        orig_str = new_str;

        // overwrite the free space with NULL's
        memset(orig_str + strlen(orig_str), 0, req_space);

        // copy the appending text to the string
        strcpy(orig_str + strlen(orig_str), append_str);

        // modify the original size
        *orig_str_size = allocate;

    } else {
        // append the string
        strcpy(orig_str + strlen(orig_str), append_str);
    }

    return orig_str;
}

Example usage:

char *buffer;
size_t buffer_size = 20;
int i;

buffer = (char *)malloc(sizeof(char) * buffer_size);
strcpy(buffer, "1234567890123456789"); // fill some data prior..

// original string
for (i=1; i < 100; ++i) {
    buffer = append(buffer, &buffer_size, "AABBCC");
}

free(x);

Latest changes: GitHub


texts: Using recursion to count substrings (with exceptions to the rule) in Java

texts:
I am going through the CodingBat exercises for Java. Here is the one I have just finished:

  Given a string, compute recursively the number of times lowercase hi appears in the string, however do not count hi that have an x immedately before them.

And here is my code:

public int countHi2(String str) {

    if (str.length() < 3) {
        return str.equals("hi") ? 1 : 0;
    }

    if (str.substring(0, 3).equals("xhi")) {
        return countHi2(str.substring(2));
    }

    if (str.substring(0, 2).equals("hi")) {
        return 1 + countHi2(str.substring(2));
    } else {
        return countHi2(str.substring(1));
    }

}

This is the first in a recursion exercise which I have needed to change the base case to accommodate how the rest of the code works. I originally made it so that whenever an x is reached, it returns a substring from 2 (because the following hi is irrelevant), but of course, this is useless when there are two x's adjacent to one another.

I am still getting used to the idea of recursion, so I would like to know if this is a 'good' solution or not. Can it be made more efficient?


texts:
I'm trying to apply sound today, and the goal in mind was a simple violin tuner. The actionListener seems repetitive/  How might I optimize it (what I tried just broke everything)? I also noticed the sounds bleed into each other.  I don't mind that so much for the different keys (though I'm thinking of a toggle option for this) but it also is the case for the same key, which is undesirable.  I'm not sure how to handle that.

/* Author: Luigi Vincent
A simple violin tuner, emits G, D, A, and E sounds to facilitate violin tuning
*/

import javax.swing.*;
import javax.sound.sampled.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class ViolinTuner {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Violin Tuner");
        // get and set icon for the program
        ImageIcon icon = new ImageIcon("Images/Icon.png");
        frame.setIconImage(icon.getImage());
        // Buttons
        final JButton G_KEY = new JButton("G");
        final JButton D_KEY = new JButton("D");
        final JButton A_KEY = new JButton("A");
        final JButton E_KEY = new JButton("E");
        // Listener to play sounds on click
        ActionListener violinSounds = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == G_KEY) {
                    try {
                        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("Sounds/G.wav").getAbsoluteFile());
                        Clip clip = AudioSystem.getClip();
                        clip.open(audioInputStream);
                        clip.start();
                    }catch(Exception x) { x.printStackTrace(); }
                }
                else if (e.getSource() == D_KEY) {
                    try {
                        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("Sounds/D.wav").getAbsoluteFile());
                        Clip clip = AudioSystem.getClip();
                        clip.open(audioInputStream);
                        clip.start();
                    }catch(Exception x) { x.printStackTrace(); }
                }
                else if (e.getSource() == A_KEY) {
                    try {
                        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("Sounds/A.wav").getAbsoluteFile());
                        Clip clip = AudioSystem.getClip();
                        clip.open(audioInputStream);
                        clip.start();
                    }catch(Exception x) { x.printStackTrace(); }
                }
                else if (e.getSource() == E_KEY) {
                    try {
                        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("Sounds/E.wav").getAbsoluteFile());
                        Clip clip = AudioSystem.getClip();
                        clip.open(audioInputStream);
                        clip.start();
                    } catch(Exception x) { x.printStackTrace(); }
                }
            }
        };
        // Register buttons to listener
        G_KEY.addActionListener(violinSounds);
        D_KEY.addActionListener(violinSounds);
        A_KEY.addActionListener(violinSounds);
        E_KEY.addActionListener(violinSounds);
        // buttons to panel
        JPanel p = new JPanel();
        p.add(G_KEY);
        p.add(D_KEY);
        p.add(A_KEY);
        p.add(E_KEY);
        // Panel to frame
        frame.add(p);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(225, 75);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
};


texts:
I have a couple of answers that I wrote up for this exercise. Both of my methods work. I'm hoping to get some feedback on each and how I could improve them, if needed.

The idea is to take a string, such as 'abc' and return an array like this: ['a', 'ab', 'abc']

For the second method, I used #map, but I'm not sure if this is the best way to achieve my desired result.

def substrings(string)
  subbed = []
  (0..string.length-1).each do |i|
    subbed.push(string.slice(0..i))
  end
  return subbed
end

def substrings2(string)
  string.split('').map.with_index do |c,i|
    string.slice(0..i)
  end
end

print substrings2('abc')


texts: C++ Calculator for complex numbers - follow-up

texts:
After following the suggestions from the first question on that topic (link), I'd like to show you the result now:

#include <iostream>

class ComplexNumber {

    private:
        double real;
        double imaginary;

    public:
        ComplexNumber operator+(ComplexNumber b) {

            //Just add real- and imaginary-parts
            double real = this->real + b.real;
            double imaginary = this->imaginary + b.imaginary;
            ComplexNumber c = ComplexNumber(real, imaginary);
            return c;
        }

        ComplexNumber operator-(ComplexNumber b) {

            //Just subtract real- and imaginary-parts
            double real = this->real - b.real;
            double imaginary = this->imaginary - b.imaginary;
            ComplexNumber c = ComplexNumber(real, imaginary);
            return c;
        }

        ComplexNumber operator*(ComplexNumber b) {

            //Use binomial theorem to find formula to multiply complex numbers
            double real = this->real * b.real - this->imaginary * b.imaginary;
            double imaginary = this->imaginary * b.real + this->real * b.imaginary;
            ComplexNumber c = ComplexNumber(real, imaginary);
            return c;
        }

        ComplexNumber operator/(ComplexNumber b) {

            //Again binomial theorem
            double real = (this->real * b.real + this->imaginary * b.imaginary) / (b.real * b.real + b.imaginary * b.imaginary);
            double imaginary = (this->imaginary * b.real - this->real * b.imaginary) / (b.real * b.real + b.imaginary * b.imaginary);
            ComplexNumber c = ComplexNumber(real, imaginary);
            return c;
        }

        void printNumber(char mathOperator) {
            std::cout << "a " << mathOperator << " b = " << this->real << " + (" << this->imaginary << ") * i" << std::endl;
        }

    /*
     * Constructor to create complex numbers
     */
    ComplexNumber(double real = 0.0, double imaginary = 0.0) {
        this->real = real;
        this->imaginary = imaginary;
    }
};

int main() {

    /*
     * Variables for the real- and imaginary-parts of
     * two complex numbers
     */
    double realA;
    double imaginaryA;
    double realB;
    double imaginaryB;

    /*
     * User input
     */
    std::cout << "enter real(A), imag(A), real(B) and imag(B) >> ";
    std::cin >> realA >> imaginaryA >> realB >> imaginaryB;
    std::cout << std::endl;

    /*
     * Creation of two objects of the type "ComplexNumber"
     */
    ComplexNumber a(realA, imaginaryA);
    ComplexNumber b(realB, imaginaryB);

    /*
     * Calling the functions to add, subtract, multiply and
     * divide the two complex numbers.
     */
    ComplexNumber c = a + b;
    c.printNumber('+');

    c = a - b;
    c.printNumber('-');

    c = a * b;
    c.printNumber('*');

    c = a / b;
    c.printNumber('/');

    return 0;
}

If you have any suggestions on further improving the code, I would really appreciate it if you share them with me.


texts: Bad performance bash, changing display brightness

texts:
I have a script that changes the display brightness using xrandr. It is my first bash script. I mainly had a lot of trouble with dealing with the floating point values. I think that is one of the main reasons the performance is bad.

  1 #!/bin/bash
  2 # increase/decrease display brightness of xrandr of both displays
  3 # use:
  4 # $ ./change_brightness [up/down (0/1)]
  5
  6 export current_brightness=$(xrandr --verbose | awk '/Brightness/ { print $2; exit }')
  7
  8 export increase=$1
  9 export new_brightness=$current_brightness
 10
 11 if [ "$increase" = "1" ]; then
 12     if [ $current_brightness != "1.0" ]; then
 13         new_brightness="$current_brightness + 0.2"
 14     fi
 15 elif [ "$increase" = "0" ]; then
 16     if [ $current_brightness != "0.20" ]; then
 17         new_brightness="$current_brightness - 0.2"
 18     fi
 19 fi
 20
 21 new_brightness=$(bc <<< "$new_brightness")
 22
 23 xrandr --output eDP-1-1 --brightness $new_brightness
 24 xrandr --output DP-0 --brightness $new_brightness

The performance isn't terrible, but any improvements would be highly appreciated. Also the improvements that have nothing to do with performance.


texts:
I've developed a function in the Julia language, using the SymEngine library, which builds an equation. This function works quite quickly, returning a lambdified equation.

The problem is, calculation of the value of this equation in the point takes too long time! And as the equation becomes longer, the calculation time also increases.

Is there a way to optimize the equation, generated by the function?

function func()

  @vars x y z myu

  longitude=atan(y/x)+pi*sign(y)*(1-sign(x))/2
  r=(x^2+y^2+z^2)^(1/2)

  dUx=0
  dUy=0
  dUz=0
  for i=2:degree
      for j=0:degree

          index=1+j; for ll=2:i-1 index+=ll+1; end

          P_i=(myu^2-1)^i
          for k=1:i+j P_i=diff(P_i,myu) end

          if(i>20) F=factorial(Int128(i)); else F=factorial(i); end
          P_ij=(((1-myu^2)^(j/2))/(F*2^i))*P_i

          if(P_ij!=0)
            CS_exp=CS[index,3]*cos(j*longitude)+CS[index,4]*sin(j*longitude)
            CS_diff_x= j*CS[index,4]*cos(j*longitude)*(-y/(x^2+y^2)) - j*CS[index,3]*sin(j*longitude)*(-y/(x^2+y^2))
            CS_diff_y= j*CS[index,4]*cos(j*longitude)*( x/(x^2+y^2)) - j*CS[index,3]*sin(j*longitude)*( x/(x^2+y^2))
            CS_diff_z= 0

            L=P_ij(z/r)

            dUx+= GMe*(diff((L*(Req/r)^i)/r,x)*CS_exp + CS_diff_x*(L*(Req/r)^i)/r)
            dUy+= GMe*(diff((L*(Req/r)^i)/r,y)*CS_exp + CS_diff_y*(L*(Req/r)^i)/r)
            dUz+= GMe*(diff((L*(Req/r)^i)/r,z)*CS_exp + CS_diff_z*(L*(Req/r)^i)/r)

          end
       end
  end

  return lambdify(dUx, [x,y,z], cse=true),lambdify(dUy, [x,y,z], cse=true),lambdify(dUz, [x,y,z], cse=true)

end

dU=func();

dy= [
       dU[1](y[1],y[2],y[3]),
       dU[2](y[1],y[2],y[3]),
       dU[3](y[1],y[2],y[3])
    ]

The calculation of dy takes too long. Any ideas?


texts: Ensure only a single instance of static template class member

texts:
I am interacting with a C library, whose documentation states that certain functions are not thread safe. Since its functions deal heterogeneously with multiple types, I have written a template wrapper to use it in a homogeneous manner from C++. However, I now need to ensure serialized access to certain functions, serialized across all instantiated template wrappers.

I believe the following approach should work; what I would like to know is, are there any caveats to the following approach, and if so, what are they and how can I get around them?

struct LibMutexPolicy
{
    static std::mutex & getMutexInstance()
    {
        static std::mutex inst;
        return inst;
    }
};

template <typename T>
struct A : private LibMutexPolicy
{
    void foo()
    {
        std::lock_guard<std::mutex> lock(getMutexInstance());
        // Call non thread-safe library code
    }
};


texts: Dynamic programming solution to "Climbing Stairs"

texts:
This is the "Climbing Stairs" problem from leetcode.com:

  You are climbing a stair case. It takes \$n\$ steps to reach to the top.

  Each time you can either climb 1 or 2 steps. In how many distinct ways
  can you climb to the top?

  Note: Given \$n\$ will be a positive integer.

  Example 1:

  Input: 2 Output:  2 Explanation:  There are two ways to climb to the
  top.

  1 step + 1 step
  2 steps

  Example 2:

  Input: 3 Output:  3 Explanation:  There are three ways to climb to the
  top.

  1 step + 1 step + 1 step
  1 step + 2 steps
  2 steps + 1 step

I thought this question is very similar to Fibonacci question. I use dynamic programming,

dp[n] = dp[n - 1] + dp[n - 2]

class Solution:
    # @param n, an integer
    # @return an integer
    def climbStairs(self, n):
        dp = [1 for i in range(n+1)]
        for i in range(2, n+1):
            dp[i] = dp[i-1] + dp[i-2]
        return dp[n]


texts: Reading contents of a thousand CSV files

texts:
I'm fairly new to VBA and just completed my first script. It's completing the task I want it to do just fine, but it's really slow in doing so. It has to open and read about 1000 CSV files for each CSV filter for specific rows and copy those into tabs in a newly created document. It then has to save and close that new document and open the next CSV.

Are there parts in the script that are not "good-practice" in the sense that they severely slow down execution time?

It takes about 3 seconds per loop iteration, so 50 minutes for all 1,000 files. The machine has also crashed halfway through, although I'm not 100% sure that's because of the script.

Sub createLists()

    Application.DisplayAlerts = False
    Application.ScreenUpdating = False

    Dim startDate As Date
    Dim endDate As Date
    Dim dateLooper As Date
    Dim currDate As String

    'Set date range for existing files
    startDate = #1/1/2012#
    endDate = #9/12/2014#

    'Array, which contains names for new worksheets as strings
    Dim tsN(1 To 12) As String
    tsN(1) = "AA11"
    tsN(2) = "AA22"
    tsN(3) = "AA33"
    tsN(4) = "AA44"
    tsN(5) = "AA55"
    tsN(6) = "AA66"
    tsN(7) = "BB11"
    tsN(8) = "BB22"
    tsN(9) = "BB33"
    tsN(10) = "BB44"
    tsN(11) = "BB55"
    tsN(12) = "BB66"

    Dim w1 As Workbook
    Dim w2 As Workbook
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet

    Dim localPath As String
    localPath = ThisWorkbook.path

    'Check for folder "Lists", create if non-existend
    Dim fso, folderN
    Set fso = CreateObject("Scripting.FileSystemObject")
    folderN = localPath & "\Lists\"
    If fso.FolderExists(folderN) = False Then MkDir folderN

    For dateLooper = startDate To endDate

        currDate = Format(dateLooper, "yyyy-mm-dd")

        'Open / create workbook objects
        Set w1 = Workbooks.Open(Filename:=localPath & "\roh\daten" & currDate & ".CSV", Local:=True)
        Set w2 = Workbooks.Add()

        'Array, which contains worksheet-objects which will reference new worksheets
        Dim ts(1 To 12) As Worksheet

        'Create new file and add/name new worksheets, set references to array ts
        For i = 1 To 12
            With w2.Sheets.Add()
                .Name = tsN(13 - i)
                .Activate
            End With
            If i = 1 Then w2.Worksheets(2).Delete
            Set ts(13 - i) = ActiveSheet
        Next i

        'Copy data:
        Set ws1 = w1.Sheets(1)

        'Iterate through products and copy corresponding data to seperate sheets in prev. created new file
        For i = 1 To 12
            Set ws2 = ts(i)

            'Filter data for product
            ws1.Range("A1:H1").AutoFilter Field:=2, Criteria1:="=" & tsN(i)
            ws1.Range("A1:H1").AutoFilter Field:=7, Criteria1:="=ja"

            'Select range and copy
            Dim lastRow As Long
            lastRow = ws1.UsedRange.Rows.Count
            ws1.Range("A1:H" & lastRow).Copy ws2.Range("A1:H1")

            'Sort copied data
            With ws2
                .Range("A1").Sort Key1:=.Range("D1"), Order1:=xlAscending, DataOption1:=xlSortNormal, Header:=xlYes
            End With

            ws1.AutoFilterMode = False
        Next i

        'Save newly created file
        w2.SaveAs Filename:=localPath & "\Lists\Lists-" & currDate & ".xls", FileFormat:=xlNormal
        w2.Close

        w1.Close

    Next dateLooper

    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub


texts:
I decided to spend some time working with parsec. I've written some code to check for primality and for whether something is a Fibonacci number. I'm mainly hoping for feedback on readability, but if you have any performance tips I'd be interested in those as well.

import Text.Parsec
import Text.Parsec.Error
import Control.Applicative hiding ((<|>))

toXTerminatedAs :: Int -> String
toXTerminatedAs = end . parse (manyAccum acc digit) "" . show
  where acc digit cur = concat (replicate 10 cur) ++ toAs digit
        toAs digit    = replicate (fromEnum digit - 48) 'a'
        end (Left _)  = error "I can't deal with negative numbers, sorry"
        end (Right x) = x ++ "x"

isLeft :: Either a b -> Bool
isLeft (Left _) = True
isLeft _        = False

fib :: Int -> Bool
fib = not . isLeft . parse (fibParser "a" "") "" . toXTerminatedAs

fibParser a b = char 'x' <|> (\_ -> fibParser b (a++b)) =<< string a

prime :: Int -> Bool
prime = isLeft . parse (char 'x' <|> primeParser "a") "" . tail . toXTerminatedAs

primeParser x = (\c -> try (many1 (string (c:x)) *> char 'x') <|> primeParser (c:x)) =<< char 'a'

toXTerminatedAs is pretty ugly, but I haven't been able to think of any improvements. As the name/signature implies it turns a number n into n 'a's followed by an x.

prime works for all natural numbers, but it returns True for 0, and I'm not really sure what to do about it besides hard-coding it in somewhere.


texts: Using a compiler specified on the command line or automatically detected

texts:
Here is part of my build system.

guessCompilers :: Options -> IO Options
guessCompilers options =  foldl (>>=) (return options) modifiers where
  modifiers =
    [guessMetapost
     -- guessAsymptote,
     -- guessTex,
     -- guessLatex,
     -- guessXelatex
    ]
guessMetapost :: Options -> IO Options
guessMetapost opts = if isJust $ optMetaPost opts
                         then
                           putStrLn $ printf "using enforced Metapost compiler: %s" (fromJust $optMetaPost opts)
                           >> return opts
                         else do
                           cc <- compiler Metapost.interface
                           if isJust cc then putStrLn $ printf "found Metapost compiler: %s" (fromJust cc)
                                             else putStrLn "found Metapost compiler: none"

Compiler can be spectified by cmd args or can be guessed. But double checking for Nothing is not cool in my opinion. Also, I heard fromJust is evil. Any suggestions to improve my code?


texts:
We have a console application which runs to perform an incremental load of our data warehouse staging area, with data from a number of production databases.
The source database don't necessarily have a rowversion/timestamp/etc. column so we are currently using change data tracking in SQL to load changes to the tables. This all works fine and I think most of the code is okay, however, I don't like the way the 'main' pipeline works and was wondering if anyone had any better suggestions.

At the moment I have each 'step' as an instance of a class like this. This is so I can show a status of each step and if errors happen we have a descriptive name of the action it was performing. I was also thinking of adding pre and post conditions to each step so we can more easily tell the reason it fails.

public abstract class PipeLineStep
{
    public abstract String StepName { get; }
    public bool WasSuccessful { get; set; }
    internal abstract void Run();
}

These steps are run by the following method to enable a common type of logging. If an error is detected in the run, and we are not performing a full load, then the process will run again but perform a full load.

private bool RunStep(PipeLineStep step, TableContext context, Boolean isFullLoad, Boolean errorRerun)
{
    try
    {
        step.Run();
        return true;
    }
    catch (Exception ex)
    {
        Logging.Log(false, String.Format("Error during Pipeline Step [{0}]. {1}", step.StepName, ex.Message), context.TaskId, context.TableId, step.StepName, true, CurrentRunNumber);
        Logging.Log(false, String.Format("{0}", !isFullLoad && !errorRerun ? "Attempting Full Load of Table." : "Aborting Table Load."), context.TaskId, context.TableId, step.StepName, true, CurrentRunNumber);

        // If not currently doing a full load and we have an error - trying doing full load to refresh schema
        if (!isFullLoad && !errorRerun)
        {
            Run(context, CurrentRunNumber, isFullLoad, true);
            return false;
        }

        UpdateProgress(context.TableId, "Finished with Error", true, true);
        return false;
    }
}

In the main loop this method is called for each step, with control flow logic:

var step1 = new CheckChangeTrackingEnabledOnDatabaseStep(...);
if (!RunStep(step1, context, isFullLoad, errorRerun)) return false;

I don't see the actual order or control flow changing too much because each step is fairly well defined and we would handle any additional processing after the data is loaded into the staging area. So this part does not need to be too flexible.


texts:
Please review this small program I wrote to create a World Cup Group Table. You feed the program match info, and it builds a table based on that info.

  def table_for(matches)
    # Defaults that each team in the table should have
    defaults = { goals_for: 0, points: 0 }

    # Using the matches, let's create a hash for each team involved in a match
    teams = matches.each_with_object([]) do |match, array|
      array.push({ name: match[:home_team] }.merge!(defaults))
      array.push({ name: match[:away_team] }.merge!(defaults))
    end

    # We have 6 matches; each match involves 2 teams; we have 12 teams in our array.
    # Each team plays 3 matches, so we have 4 unique.
    teams.uniq

    # Loop through matches to build the table.
    matches.each do |match|

      # We only want to calculate data for matches that were played
      if match[:home_score].present? && match[:away_score].present?

        # Grab the teams for this particular match from the list of teams
        home_team = teams.detect { |team| team[:name] == match[:home_team] }
        away_team = teams.detect { |team| team[:name] == match[:away_team] }

        # Compute goals_for
        home_team[:goals_for] += match[:home_score]
        away_team[:goals_for] += match[:away_score]

        # Home team wins
        if match[:home_score] > match[:away_score]
          home_team[:points] += 3

        # Away team wins
        elsif match[:home_score] < match[:away_score]
          away_team[:points] += 3

        # It's a draw
        else
          home_team[:points] += 1
          away_team[:points] += 1
        end
      end
    end

    teams
  end

The rules are a win earns three points, a draw one point, a loss zero points.

For example, if we feed the method this match data:

[
  { id: 1, home_team: "Honduras", away_team: "Chile", home_score: 0, away_score: 1 },
  { id: 2, home_team: "Spain", away_team: "Switzerland", home_score: 0, away_score: 1 },
  { id: 3, home_team: "Chile", away_team: "Switzerland", home_score: 1, away_score: 0 },
  { id: 4, home_team: "Spain", away_team: "Honduras", home_score: 2, away_score: 0 },
  { id: 5, home_team: "Chile", away_team: "Spain", home_score: 1, away_score: 2 },
  { id: 6, home_team: "Honduras", away_team: "Switzerland", home_score: 0, away_score: 0 }
]

We should see this table:

| TEAM        | GF | POINTS |
| Spain       | 4  | 6      |
| Chile       | 3  | 6      |
| Switzerland | 1  | 4      |
| Honduras    | 0  | 0      |

How can I improve this? If there a better way to get the unique teams from the match info? That parts looks convoluted. I also feel that the method is too large.


texts: Looping text in Python with directional control

texts:
The code is an implementation of looping text (similar to a circular buffer - wraps around when it reaches the edge of the defined bounds) with directional control.

The code is functional and works as intended, but I'm curious if there is anyway to improve the code even if it is only a small improvement (e.g. less garbage produced per loop cycle as a micro-optimisation, etc).

# cleaned up and improved prototype code for looping text scroll.
# added direction from the original code.

from sys import stdout
from time import sleep

global_shifted_text_array = []
global_text_length = 0

DIRECTION_LEFT_TO_RIGHT = -1
DIRECTION_RIGHT_TO_LEFT = 1

def set_text(text):
    global global_shifted_text_array
    global global_text_length

    global_shifted_text_array = pad_text(text)
    global_text_length = len(global_shifted_text_array)

def pad_text(text, padding = 5):
    text += ' ' * padding
    return list(text)

def shift_text(direction):
    global global_shifted_text_array
    range = xrange(global_text_length - 1, -1, -1) if direction == DIRECTION_LEFT_TO_RIGHT else xrange(global_text_length)

    # by the time the zero element is set in the for loop.
    # it is set to the last element (which is empty)
    # so we have to account for this by correcting for it.
    if direction == DIRECTION_RIGHT_TO_LEFT:
        first_element = global_shifted_text_array[0]

    for i in range:
        global_shifted_text_array[i] = global_shifted_text_array[((i + direction) % global_text_length)]
        # print 'global_shifted_text_array[{}] = global_shifted_text_array[{}]'.format(i, ((i + direction) % global_text_length))

    if direction == DIRECTION_RIGHT_TO_LEFT:
        global_shifted_text_array[global_text_length - 1] = first_element

def update_loop(direction = DIRECTION_LEFT_TO_RIGHT, frequency = 0.1):
    while 1:
        shift_text(direction)
        stdout.write('\r{0}'.format(''.join(global_shifted_text_array)))
        sleep(frequency)

set_text('Beautiful Lie')
update_loop()


texts: Merging two hashes with the mean values of each key if both hashes exist

texts:
There are two methods, hash1 and hash2, that return hashes or nil. The hashes have the same keys. I want to merge them with their mean value only if both methods have hashes.

(I added Array#mean to calculate the average value of an array).

def merged_hashes
    return if hash1.nil? && hash2.nil?
    return hash2 if hash1.nil?
    return hash1 if hash2.nil?
    hash1.merge(hash2) do |key, v1, v2|
      [v1, v2].compact.mean
    end
end

Is there more succinct way to write this?