texts: Using UnsafeMutableRawPointers with Metal buffers in Swift

texts:
I've some Metal buffers which I populate with geometry data. Most data consists of Floats, but the buffer also contains custom structs for the tessellation stage.
I get the UnsafeMutableRawPointer for the Metal buffer in this way:

let origin=geometryBuffer.contents()

Which I then supply to the following function:

    func populate(bufferPointer: UnsafeMutableRawPointer, useTessellation: Bool) -> UnsafeMutableRawPointer {
        var bufferPointer = bufferPointer

        if let vertexData = vertexData {
            var floatPointer = bufferPointer.assumingMemoryBound(to: Float.self)

            for index in vertexData.indexes {
                floatPointer[0]=vertexData.vertices[Int(3*index+0)]
                floatPointer[1]=vertexData.vertices[Int(3*index+1)]
                floatPointer[2]=vertexData.vertices[Int(3*index+2)]

                floatPointer=floatPointer.advanced(by: 3)
            }

            bufferPointer = floatPointer.deinitialize(count: 0)
        } else if useTessellation, let patchData=patchData {
            memcpy(bufferPointer, patchData, patchData.count*MemoryLayout<PatchIn>.stride)
            bufferPointer=bufferPointer.advanced(by: patchData.count*MemoryLayout<PatchIn>.stride)
        }

        if let lineData = lineVertexData {
            var floatPointer = bufferPointer.assumingMemoryBound(to: Float.self)

            floatPointer[0]=lineData[0].x
            floatPointer[1]=lineData[0].y
            floatPointer[2]=0
            floatPointer[3]=lineData[1].x
            floatPointer[4]=lineData[1].y
            floatPointer[5]=0

            floatPointer=floatPointer.advanced(by: 6)
            bufferPointer = floatPointer.deinitialize(count: 0)
        }

        return bufferPointer
    }

I'm very uncertain here about my usage of assumingMemoryBound(to:), deinitialize(count:) and the memcpy().

The code seems to run fine, but according to the documentation it's quite easy to get into undefined behaviour. So I wonder whether I'm using the pointers correctly.

Thanks in advance.


texts:
I came across a problem on LeetCode.
There is an input array of integers. I need to find out if there any repeating integers, then return true else false.
So, I tried using a hashtable library available in C and wrote the code below.
My run time is approximately 44ms.

How can I optimize this code?
Using hashtable, can I improve the logic further?

struct hash {
    int key;
    int value;
    UT_hash_handle hh;
};

struct hash *hashtable = NULL;

void addToHash(int key, int value)
{
  struct hash *map;
  //I am using the array elements as hash keys
  HASH_FIND_INT(hashtable, &key, map);

  if(map == NULL)
  {
    map = (struct hash*)malloc(sizeof(struct hash));
    map->key = key;
    HASH_ADD_INT(hashtable, key, map);
  }
  map->value = value;
}

struct hash *findInHash(int key)
{
    struct hash *h;
    HASH_FIND_INT(hashtable, &key, h);
    return h;
}

bool containsDuplicate(int* nums, int numsSize) {

    struct hash *hPtr;
    int target = 0;
    hashtable = NULL;
    if((numsSize <= 1) || (nums == 0)) return false;

    int i, index1 = 0;

    for(i = 0; i < numsSize; i++)
    {
        /*The below statement will look if the key is already present in the
          hashtable*/
        hPtr = findInHash(*(nums + i) - target);
        /*If the key is found already, then it look for the value of that
        key. If the value and the current array element is same, then a
        duplicate exist*/
        if(hPtr && hPtr->key == *(nums+i))
           return true;
        addToHash(*(nums + i), i);
    }
    struct hash *temp;
    HASH_ITER(hh, hashtable, hPtr, temp) {free(hPtr);}
    return false;
}


texts: Stack implementation using a growing array

texts:
I'm working through Sedgewick's Algorithms book for fun and educational purposes. I am implementing a simple Stack<T>, using System.Collections.Generic.Stack<T> as a guide:

[System.Diagnostics.DebuggerDisplay("Count = {Count}, Size = {_values.Length}")]
public class Stack<T>
{
    // Constructors
    public Stack(int capacity)
    {
        _values = new T[capacity];
        _count = 0;
    }

    public Stack() :
        this(DEFAULT_SIZE)
    {
    }

    // Static variables
    private static readonly int DEFAULT_SIZE = 4;
    private static readonly float DEFAULT_TRIM_THRESHOLD = 0.90f;

    // Variables
    private T[] _values;
    private int _count;

    // Properties
    public int Count
    {
        get { return _count; }
    }

    // Methods
    public void Push(T value)
    {
        if (_count == _values.Length)
            Array.Resize(ref _values, _values.Length << 1);
        _values[_count++] = value;
    }

    public T Pop()
    {
        T result = _values[--_count];
        _values[_count] = default(T);
        return result;
    }

    public T Peek()
    {
        return _values[_count - 1];
    }

    public void Clear()
    {
        for (int i = 0; i < _count; i++)
            _values[i] = default(T);
        _count = 0;
    }

    public void Trim()
    {
        if (_count / (float)_values.Length < DEFAULT_TRIM_THRESHOLD)
            Array.Resize(ref _values, Math.Max(_count, DEFAULT_SIZE));
    }
}

A few things:

There were #region and <summary> tags on everything, but I removed them to post here, since it seemed like it added a lot of visual noise and made the code otherwise harder to read.
The class does not currently implement IEnumerable<T> or IEnumerable, but will.
I don't want to implement ICollection<T>, since I think Add() and Remove() would be inappropriate methods for this class. Doing something like hiding them behind an explicit interface implementation would be misrepresenting the class's intent.
Performance. Premature optimization should be avoided obviously, but I would like the classes I implement from the book to be useful in future projects. It doesn't need to outperform the default implementation, but it should be comparable.
I compared my Push() method against the default implementation by adding 1,000,000 items to the stack. It takes ~68,000 ticks for mine, and ~25,000 ticks for the default. Even if I strip Push() down to just the array assignment, using compile on Release with optimized code enabled, the default is still running at twice the speed mine is, and I have no idea why.

Any feedback or insight is appreciated!

Edit: As requested, here is the code I am using to benchmark the speed. This is what I usually do to get a sense of which of two things is faster; not sure how hackish it's considered:

int n = 10000000;
long r1, r2;

var stack1 = new Stack<int>();
{
    Stopwatch w = new Stopwatch();
    w.Start();
    {
        for (int i = 0; i < n; i++)
            stack1.Push(i);
    }
    w.Stop();
    r1 = w.ElapsedTicks;
}

var stack2 = new System.Collections.Generic.Stack<int>();
{
    Stopwatch w = new Stopwatch();
    w.Start();
    {
        for (int i = 0; i < n; i++)
            stack2.Push(i);
    }
    w.Stop();
    r2 = w.ElapsedTicks;
}

As a baseline, it takes r2 = ~37,015 ticks for the default implementation to add 1,000,000 elements.

r1 = ~76,892 ticks (compile to debug, w/ resizing)
r1 = ~66,638 ticks (compile to debug, no resize, keep resize logic)
r1 = ~57,357 ticks (compile to debug, no resize, resize logic omitted)
r1 = ~51,420 ticks (compile to release, w/ resizing)
r1 = ~40,909 ticks (compile to release, no resize, keep resize logic)
r1 = ~33,821 ticks (compile to release, no resize, resize logic omitted)

So, looking at the different results, it seems that I can achieve the same speed as the default implementation, but at the cost of making the class brittle and inflexible.


texts:
I have created a program where I first set the size of the array and
how many times I will look for consecutive values, then I fill in the
array and finally I insert the consecutive values, it should look for
the least consecutive value it finds in the array.
consecutive value means the sum of the elements in the array
consecutively.
example:
7 4 // Array size and consecutive values
6 4 2 7 10 5 1 // arrangement
1 3 4 2 // Consecutive values

Answer = 1,12,19,6

Explanation

The lowest element of the array is the one in the last position which
is 1, the answer is equal to 1.
the lowest segment is the one furthest to the left 6 4 2, the sum of
which equals 12.
the answer is obtained by choosing segment 6 4 2 7, which equals 19.
there are two segments with a minimum cost equal to 6, segments 4 2
and 5 1.

How can it be improved?
#include<iostream>
#include<vector>
using namespace std;

void suma_elementos(int elemento);
vector<int>elementos, consecutivos;
int n, q, consecutivo, total, final = 99999999;

int main()
{
    cin >> n >> q;
    elementos.resize(n);
    consecutivos.resize(q);

    for (int i = 0; i < n; i++)
    {
        cin >> elementos[i];
    }
    for (int i = 0; i < q; i++)
    {
        cin >> consecutivos[i];
    }

    for (int i = 0; i < q; i++)
    {
        suma_elementos(consecutivos[i]);

        for (int j = 0; j < consecutivo; j++)
        {
            for (int c = 0; c < consecutivos[i]; c++)
            {
                total += elementos[c + j];
            }

            if (total < final)
            {
                final = total;
            }
            total = 0;
        }
        cout << final << " ";
        //reset
        consecutivo = 0;
        final = 99999999;
        total = 0;
    }

    return 0;
}

//Suma de elementos
void suma_elementos(int elemento)
{

    int proporcion = n;

    while (proporcion >= elemento)
    {
        proporcion--;
        consecutivo++;
    }
}

edit 1:The program in small arrangements works well, but in large ones it's very slow
edit 2:must not have negative numbers in the sequence


texts:
The most basic code(i guess so) to find all the factors of a number

Note:factors include 1 and the number itself

Here's the code:

c=0
x=int(input("Enter number:"))
for i in range(1,x+1):
    if x%i==0:
        print("factor",c+1,":",i)
        c=c+1
print("Total number of factors:",c)

Please make this code efficient.....ie: Help to reduce the number of iterations


texts: Optimized pulling items out of arrays in nested objects

texts:
I found a couple of similar questions, but they were mostly outdated.
Here's the problem: create a flat array from the values in several arrays contained in several nested objects.

const data = [
  { id: 1, items: ['one', 'two', 'three'] },
  { id: 2, items: ['two', 'one', 'four'] },
]

Expected result const result = ['one', 'two', 'three', 'four']

My current solution:

function() {
  const result = []
  data.forEach(item => data.items.forEach(item => result.push(item)))

  return _.uniq(result)
}

lodash is allowed

Any suggestion is more than welcome


texts:
I've implemented a common wrapper pattern I've seen for the .NET cache class using generics as follows:

private static T CacheGet<T>(Func<T> refreashFunction, [CallerMemberName]string keyName = null)
{
    if (HttpRuntime.Cache[keyName] == null)
        HttpRuntime.Cache.Insert(keyName, refreashFunction(), null, DateTime.UtcNow.AddSeconds(600), System.Web.Caching.Cache.NoSlidingExpiration);
    return (T)HttpRuntime.Cache[keyName];
}

It could then be called like so:

public static Dictionary<string, string> SomeCacheableProperty
{
    get
    {
        return CacheGet(() =>
        {
            Dictionary<string, string> returnVal = AlotOfWork();
            return returnVal;
        });
    }
}

However, the CacheGet method could be implemented using dynamic:

private static dynamic CacheGet(Func<object> refreashFunction, [CallerMemberName]string keyName = null)
{
    if (HttpRuntime.Cache[keyName] == null)
        HttpRuntime.Cache.Insert(keyName, refreashFunction(), null, DateTime.UtcNow.AddSeconds(600), System.Web.Caching.Cache.NoSlidingExpiration);
    return HttpRuntime.Cache[keyName];
}

The questions I have:

Is there a technically (or philosophically) superior preference between these two implementations?
Are these different at runtime?
If they are both left in, which one is being called in the getter method?


texts:
I got this script which work perfectly but I got some delays because of this 2 for loops [i][j] is there any way to do the same function but with a better and effective process like foreach or other.

User.find({}).lean(true).exec((err, users) => {
        let getTEvent = [];
        //nested loops() //callbacks

        for (let i =0 ; i < users.length; i++) {
          if(users[i].events && users[i].events.length) {
const dt = datetime.create();
dt.offsetInDays(0);
const formatted = dt.format('d/m/Y');
// console.log(formatted)
for (let j = 0; j < users[i].events.length; j++) {
    if(users[i].events[j].eventDate === formatted) {
      getTEvent.push({events: users[i].events[j]});
      }
    }
  }
}

   return res.json(getTEvent)
    });

The main role of this code is:

find the data in Mongodb: find all users with or without events
loop through data and select events made by any users
push the results in an array which is getEventin order to be useful later for the client side

Details:

The User is the model: const User = require('../models/users.model');
and events is [] array.

This is Mongodb structure of that models:


texts:
Problem details from Codility:

  A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.
  Count the minimal number of jumps that the small frog must perform to reach its target.

  Write a function:

def solution(X, Y, D)

  that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.

Method 1:

def solution(X, Y, D):
    if (X == Y):
        jumps = 0
    elif Y-X % D == 0:
        jumps = (Y-X)/D
    else:
        jumps = ((Y-X)/D) + 1
    return jumps

Method 2:

def solution(X, Y, D):
    d = Y-X
    jumps=d/D
    rem=d%D
    if rem != 0:
        jumps+=1
    return jumps

I submitted the Method1 solution and received a 55% score. On the other hand, Method2 got 100%. It's not clear to me why Method2 is better than Method1.  Could someone please explain?


texts: Brute force solution to Project Euler Problem #52

texts:
I was solving Project Euler Problem #52:

It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.

in C++, and this is the code I used:
#include <algorithm>
#include <iostream>
#include <string>

bool checkCondition(long long int number);

int main()
{
    long long int num = 1;
    while (!checkCondition(num))
    {
        ++num;
    }

    std::cout << num << "\n";
}

bool checkCondition(long long int number)
{
    std::string numString = std::to_string(number);
    std::string numx2 = std::to_string(number * 2);
    std::string numx3 = std::to_string(number * 3);
    std::string numx4 = std::to_string(number * 4);
    std::string numx5 = std::to_string(number * 5);
    std::string numx6 = std::to_string(number * 6);

    return std::is_permutation(numString.begin(), numString.end(), numx2.begin()) &&
        std::is_permutation(numString.begin(), numString.end(), numx3.begin()) &&
        std::is_permutation(numString.begin(), numString.end(), numx4.begin()) &&
        std::is_permutation(numString.begin(), numString.end(), numx5.begin()) &&
        std::is_permutation(numString.begin(), numString.end(), numx6.begin());
}

As evident, this function uses the standard library function std::is_permutation and literally iterates over every single integer and converts them to strings to find the answer, which is obviously inefficient. How can I improve upon the efficiency of this program?


texts: Displaying a city name with concatenations

texts:
I am learning MVC and Android. I have create a sample program which is supposed to implement the MVC philosophy. I plan to build my codes on top of this.

I wish to know whether I have got the concept more or less, or if there are any fundamental issues in my understanding of the MVC.

Summary: This application will get a city name and display it with a few concatenations (country name etc).

Model -> Model.java

/**
 *
 */
package abc.samples.mvc;
/**
 * @author Rahul
 *
 */
public class Model {

    String mData;
    String mInput;
    String mOutput;

    public void set(String temp) {
        mInput = temp;
        mData = mInput + ", India.";
    }

    public String get() {
        mOutput = "You are from "+mData;
        return mOutput;
    }

}

View -> view.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <Button
        android:id="@+id/vControl"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Control" />

    <EditText
        android:id="@+id/vInput"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/vControl"
        android:ems="10" >
        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/vOutput"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/vInput"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>

Controller -> Controller.java

package abc.samples.mvc;

import android.app.Activity;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Controller extends Activity {

    EditText cInput;
    TextView cOutput;
    Button cControl;
    Model cData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view);

        cInput = (EditText) findViewById(R.id.vInput);
        cOutput = (TextView) findViewById(R.id.vOutput);
        cControl = (Button) findViewById(R.id.vControl);

        cControl.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                cData = new Model();

                cData.set(cInput.getText().toString());
                cOutput.setText(cData.get());
            }
        });
    }
}


texts:
How can I make my PHP script more easier? It seems quite difficult and long but I don´t know how can I make it shorter. This code is inserted in my HTML5 code on my PHP tutorial webpage, but I need it to be shorter.

<?php
$n=1;
$k=0;
for ($line=0;$line<1000;$line++)
{
  echo "
";
  if ($k==0)
{
  echo "$n"; echo"	";
  for ($p=0;$p<10-$n;$p++)
  {
    echo ""; echo"	";
  }
  $n++;
  if ($n==11)
  {
    $k=1;
    $n=9;
  }
  echo"
";
}
  if ($k==1)
  {
    echo "$n"; echo"	";
    for ($column=0;$column<10-$n;$column++)
    {
      echo ""; echo"	";
    }
    $n--;
    if ($n==1)
    {
      $k=0;
    }
    echo"
";
  }
}

?>


texts:
I solved the Longest Absolute File Path challenge from Leetcode.

The question is

  Suppose we abstract our file system by a string in the following
  manner:

  The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents:

 dir
     subdir1
     subdir2
         file.ext

  The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext.

  The string
  "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
  represents:

dir
     subdir1
         file1.ext
         subsubdir1
     subdir2
         subsubdir2
             file2.ext

  The directory dir contains two sub-directories subdir1 and subdir2. subdir1 contains a file file1.ext and an empty
  second-level sub-directory subsubdir1. subdir2 contains a second-level
  sub-directory subsubdir2 containing a file file2.ext.

  We are interested in finding the longest (number of characters)
  absolute path to a file within our file system. For example, in the
  second example above, the longest absolute path is
  "dir/subdir2/subsubdir2/file2.ext", and its length is 32 (not
  including the double quotes).

  Given a string representing the file system in the above format,
  return the length of the longest absolute path to file in the
  abstracted file system. If there is no file in the system, return 0.

  Note: The name of a file contains at least a . and an extension. The
  name of a directory or sub-directory will not contain a .. Time
  complexity required: O(n) where n is the size of the input string.

  Notice that a/aa/aaa/file1.txt is not the longest file path, if there
  is another path aaaaaaaaaaaaaaaaaaaaa/sth.png.

The approach used is very similar to the way one would do this by hand. This solution looks like it has a lot of if/else statements.

Could you please suggest a cleaner way to write this solution.

public static int LengthLongestPath(string input) {
  var prefixLength = new Dictionary < int,int > ();
  int countT = 0, lengthSoFar = 0, maxLength = 0;
  bool isFile = false;
  for (int i = 0; i < input.Length; i++) {
   if (input[i] == '\n') {
    if (prefixLength.ContainsKey(countT - 1)) {
     prefixLength[countT] = lengthSoFar + prefixLength[countT - 1] + 1;
    } else {
     prefixLength[countT] = lengthSoFar;
    }

    if (isFile == true) {
     maxLength = Math.Max(maxLength, prefixLength[countT]);
     isFile = false;
    }
    lengthSoFar = 0;
    ++i;
    countT = 0;
    while (input[i] == '\t') {
     ++countT;
     ++i;
    }
    --i;
   } else {
    ++lengthSoFar;
    if (input[i] == '.') {
     isFile = true;
    }
   }
  }
  // To handle cases where file occours in the end of the string.
  if (isFile == true) {
   if (prefixLength.ContainsKey(countT - 1)) {
    maxLength = Math.Max(maxLength, prefixLength[countT - 1] + lengthSoFar + 1);
   } else {
    maxLength = Math.Max(maxLength, lengthSoFar);
   }
   isFile = false;
  }
  return maxLength;
 }


texts: Filter a collection in a PagedCollectionView

texts:
I have a scenario wherein I have to filter a collection in a PagedCollectionView.
The filter criteria are Name and status which are checkboxes with Enabled and Disabled labels. If Enabled is checked it should filter out the list with all enabled rules and vice-versa. I have given it a try, but I believe this isn't the best way of doing it.

     private PagedCollectionView _autoDepRuleList;
    public PagedCollectionView AutoDepRuleList
    {
        get
        {
            return this._autoDepRuleList;
        }
        set
        {
            this._autoDepRuleList = value;
            RaisePropertyChanged("AutoDepRuleList");
        }
    }

    private bool _isEnabled;
    public bool IsEnabled
    {
        get
        {
            return this._isEnabled;
        }
        set
        {
            this._isEnabled = value;
            RaisePropertyChanged("IsEnabled");
        }
    }

    private bool _isDisabled;
    public bool IsDisabled
    {
        get
        {
            return this._isDisabled;
        }
        set
        {
            this._isDisabled = value;
            RaisePropertyChanged("IsDisabled");
        }
    }

    private string _name;
    public string Name
    {
        get
        {
            return this._name;
        }
        set
        {
            this._name = value;
            RaisePropertyChanged("Name");
        }
    }

     public void Search()
    {
        var tempList = new AutoDeploymentRuleList();
        var filterList = new AutoDeploymentRuleList();

        foreach (AutoDeploymentRule item in this.AutoDepRuleList)
        {
            tempList.Add(item);
        }
        if (IsEnabled && IsDisabled)
        {
            foreach (var item in tempList)
            {
                filterList.Add(item);
            }
        }
        else if (IsEnabled)
        {
            foreach (var item in tempList.Where(r => r.Status.Equals("Enabled")))
            {
                filterList.Add(item);
            }
        }
        else if (IsDisabled)
        {
            foreach (var item in  tempList.Where(r => r.Status.Equals("Disabled")))
            {
                filterList.Add(item);
            }
        }
        else
        {
            foreach (var item in tempList)
            {
                filterList.Add(item);
            }
        }
    this.AutoDepRuleList = new PagedCollectionView(filterList.Where(r => r.Name.ToLower().Contains(this.Name.ToLower())));

Now the idea is to do away with the above block and go for the below logic. I did it for the Name property, but I'm not sure how I can do it for the Status property which can be anything either Enabled or Disabled.

    this.AutoDepRuleList.Filter = new System.Predicate<object>(o =>
    {
        AutoDeploymentRule rule = (AutoDeploymentRule)o;

        if (rule.Name.ToLower().IndexOf(this.Name.Trim().ToLower()) >= 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    });
}

How can I optimize it by removing those redundant where clauses and putting the entire thing under Predicate<object>?


texts: How to make a program that lies one-third of the time?

texts:
I am supposed to take this code (that I made):

public void showUpdatedStatus()
{
    if(((itsUsersNumber - itsSecretNumber) <= 2) && ((itsUsersNumber - itsSecretNumber) >= -2))
        JOptionPane.showMessageDialog(null, "You're hot!");
    if (((itsUsersNumber - itsSecretNumber) <= 6) && ((itsUsersNumber - itsSecretNumber) >= -6))
        JOptionPane.showMessageDialog(null, "You're warm.");
    if ((itsUsersNumber - itsSecretNumber) < -6)
        JOptionPane.showMessageDialog(null, "Too low.");
    if ((itsUsersNumber - itsSecretNumber) > 6)
        JOptionPane.showMessageDialog(null, "Too high.");
}

And change it so it does this:

  Have the program lie one-third of the time that the guess is too high;
  it says it is too low. But it never lies about the guess being too
  low, nor does it lie twice in a row.

I believe I have managed to do this with this method for checking whether the guess is "too high."

public void TooHigh()
{
    int numLies = 1;
    if ((itsUsersNumber - itsSecretNumber) > 6)
    {
        itsLieNum = randy.nextInt(2);
        if(itsLieNum == 1 && numLies == 1){
            numLies = 2;
            JOptionPane.showMessageDialog(null, "Too low.");}
        else
            numLies = 1;
            JOptionPane.showMessageDialog(null, "Too high.");
    }
}

I just want to know whether or not it seems like it would work fine. I would just test it, but it would probably take me quite a while to make sure that it not only works 1/3 of the time, but also that it doesn't do it twice in a row.

EDIT: I managed to get everything working fine with this code:

public void showUpdatedStatus()
{

    if(((itsUsersNumber - itsSecretNumber) <= 2) && ((itsUsersNumber -itsSecretNumber) >= -2))
        JOptionPane.showMessageDialog(null, "You're hot!");
    else if (((itsUsersNumber - itsSecretNumber) <= 6) && ((itsUsersNumber -itsSecretNumber) >= -6))
        JOptionPane.showMessageDialog(null, "You're warm.");
    if ((itsUsersNumber - itsSecretNumber) < -6)
        JOptionPane.showMessageDialog(null, "Too low.");
    else
        TooHigh();
}

public void TooHigh()
{
    if ((itsUsersNumber - itsSecretNumber) > 6)
    {
        itsLieNum = randy.nextInt(3);
        if(canLie && itsLieNum == 1){
            canLie = false;
            JOptionPane.showMessageDialog(null, "Too low.");}
        else{
            canLie = true;
            JOptionPane.showMessageDialog(null, "Too high.");}
    }
}

Thanks to rolfl


texts: Composition or Private Inheritance for Implementing Builder?

texts:
Over on StackOverflow, I was asked if I could come up with an example where private inheritance would be preferred to composition (in C++).  The following is the situation I described, and I was wondering which implementation you would prefer.  Most of the references I've found to private inheritance are poor uses, and I agree that it is rarely useful.

Let's say you have a class Foo that should be immutable, but it's rather complicated to set up (maybe you're reading settings from a file), so you decide to create a separate class FooBuilder to set up your Foo objects for you.  My solution (using private inheritance) is to declare an abstract interface:

class MutableFoo
{
  public:
     virtual void setValue(int n) = 0;
     virtual void setSomethingElse(string s) = 0;
};

And my original Foo class:

class Foo : private MutableFoo
{
  public:
     Foo(FooBuilder builder)
     {
         builder.build(this);
     }

     int value() const { return myValue; }
     string somethingElse() const { return mySomethingElse; }

  private:
     void setValue(int n) { myValue = n; }
     void setSomethingElse(string s) { mySomethingElse = s; }

     int myValue;
     string mySomethingElse;
};

And the FooBuilder:

class FooBuilder
{
   public:
     FooBuilder(string fileWithSettings);
     void build(MutableFoo *fooToBuild);
};

Now I can create read-only Foo objects without declaring them all to be const:

Foo aFoo(FooBuilder(aFileWithSettings));

A similar implementation using composition might look something like this:

class Foo
{
   public:
      Foo(FooData d);

      int value() const { return data.value(); }
      string somethingElse() const { return data.somethingElse(); }

   private:
      FooData data;
};

class FooData
{
  public:
    int value() const { return myValue; }
    int somethingElse() const { return mySomethingElse; }

    void setValue(int n) { myValue = n; }
    void setSomethingElse(string s) { mySomethingElse = s; }

  private:
    int myValue;
    string mySomethingElse;
};

class FooBuilder
{
  public:
    FooBuilder(string fileWithSettings);
    FooData getData() const;
};

Foo aFoo(FooBuilder(aFileWithSettings).getData());

I don't see much difference between these implementations as far as coupling is concerned (which is the complaint I see most frequently leveled against inheritance vs. composition).  In fact, the version using inheritance may have less coupling, as both Foo and FooBuilder depend on an abstract interface (MutableFoo) instead of a concrete class FooData.  Also, if we have lots of methods, the composition version will end up with lots of simple delegations, which is tedious if nothing else.

Which do you prefer?  Have I found a reasonable use for private inheritance?  Have you found other reasonable uses?

And finally, has anyone ever found a legitimate use for protected inheritance? :-P


texts: How do I better structure Java code to avoid dereferencing null?

texts:
I have the situation where as long as the user gives valid input, the StringBuilder object will not be null.

StringBuilder sb = null;
switch(userInput)
{
  case 1:
    sb = method1();
    break;
case 2:
    sb = method2();
    break;
case 3:
    sb = method3();
    break;
case 4:
    sb = method4();
    break;
default:
    System.out.println("invalid input");
}

System.out.println(sb.toString);//gives warning "dereferncing possible null pointer

Update: for those commenting it should be String instead of StringBuilder could you please explain? The method does a lot of appending so it needs to use String. Why would you bother converting to String if you can directly print out a StringBuilder? It seems like there's an implicit belief that a StringBuilder should always be converted to a String.


texts: Averaging lists of values with duplicate keys

texts:
I have gene expression data that I represent as a list of genes and a list of lists of values. I average the expression data for any genes with the same name.

For example:

genes = ['A', 'C', 'C', 'B', 'A']
vals  = [[2.0, 2.0, 9.0, 9.0], # A: will be averaged with row=4
         [3.0, 3.0, 3.0, 3.0], # C: will be averaged with row=2
         [8.0, 8.0, 2.0, 2.0], # C: will be averaged with row=1
         [4.0, 4.0, 4.0, 3.0], # B: is fine
         [1.0, 1.0, 1.0, 1.0]] # A: will be averaged with row=0

is converted to

genes = ['A', 'B', 'C']
vals  = [[1.5, 1.5, 5.0, 5.0],
         [4.0, 4.0, 4.0, 3.0],
         [5.5, 5.5, 2.5, 2.5]]

Here is my function:

def avg_dups(genes, values):
    """Finds duplicate genes and averages their expression data.
    """
    unq_genes = np.unique(genes)
    out_values = np.zeros((unq_genes.shape[0], values.shape[1]))
    for i, gene in enumerate(unq_genes):
        dups = values[genes==gene]
        out_values[i] = np.mean(dups, axis=0)
    return (unq_genes, out_values)

This function is slower than any other part of my data pipeline, taking 5-10 seconds when other steps that also operate on the whole dataset take sub-seconds. Any thoughts on how I can improve this?


texts: Finding two indices of numbers which sum to N

texts:
I'm solving some online puzzles and I had this problem:

  Given a vector, write code to find the indices of TWO values which sum to a given number N

so if I'm given [2, 5, 6] and N = 8, I should output the 0-based indices [0, 2].

I wrote the following code to do this in O(N)

vector<int> twoSum(vector<int>& nums, int target) {
    unordered_multimap<int, int> numbers_multimap;
    numbers_multimap.reserve(nums.size());
    for(size_t i = 0; i < nums.size(); ++i) {
        numbers_multimap.emplace(nums[i], i);
        auto interval = numbers_multimap.equal_range(target - nums[i]);
        for (auto it = interval.first; it != interval.second; ++it) {
            int other_position = it->second;
            if (other_position != i)
                return vector<int>{i, other_position};
        }
    }
    return vector<int>{};
}

and it works, but I noticed that there are faster solutions.

Since I suppose the algorithm is already quite fast, I'd like to know if there are additional pro tips to improve the runtime of this code.


texts: Running AWS commands works ok, but the code seems messy and I don't like the time.sleep bit

texts:
This is what I've come up with for a class that handles parsing AWS Textract output. So far it only gets the AWS Textract output into a .txt file.

import json
import logging as log
import os
import sys
import subprocess
import time

log.basicConfig(
  format='%(asctime)s [%(levelname)s]: %(message)s',
  datefmt='%Y-%m-%d %H:%M:%S',
  level=log.DEBUG,
  handlers=[
    log.StreamHandler(),
    log.FileHandler('{}.log'.format(__name__))
  ]
)

class InitialParser:

  def __init__(self, filename, s3_bucket, version=1):
    self.filename = filename
    self.s3_bucket = s3_bucket
    self.version = version

    self.file = None
    self.filepath = None
    self.data = None
    self.output_filename = self.filename.replace('.pdf', '.txt')

  def run(self):
    log.info('Running initial parser on file {}'.format(self.filename))
    if self.run_textract():
      log.info('Textract process successful')
    else:
      log.info('Textract process failed, exiting')
      sys.exit(0)

  def load_file_data(self):
    self.filepath = os.path.join(os.getcwd(), '../extracted/{}'.format(filename))
    try:
      with open(self.filepath, 'r') as file:
        self.file = file
        self.data = json.load(file)
    except FileNotFoundError as e:
      log.error('Could not find parsing file: {}'.format(e))

  def run_textract(self):
    """
    Runs AWS Textract commands on the given document and sends the output
    to a .txt file.

    @param s3_bucket: the S3 Bucket where the document is located.
    """
    job_id = ''
    # note: adding "Version":<str> to the AWS object below breaks the command
    aws_object = json.dumps({"S3Object":{"Bucket":self.s3_bucket,"Name":self.filename}}).replace(' ', '')  # can't have any spaces lol picky AWS CLI

    start_textract_command = "aws textract start-document-text-detection --document-location '{}'".format(aws_object)
    get_textract_output_command = 'aws textract get-document-text-detection --job-id '

    try:
      job_id = '"{}"'.format(json.loads(subprocess.check_output([start_textract_command], shell=True, stderr=subprocess.STDOUT).decode('utf-8'))['JobId'])
    except subprocess.CalledProcessError as e:
      if 'InvalidS3ObjectException' in e.output.decode('utf-8'):
        log.error('InvalidS3ObjectException (could not fetch object metadata from S3).\n Check the document name, AWS CLI configuration region (run `aws configure list`), permissions, and the S3 Bucket name & region.')
      elif 'ProvisionedThroughputExceededException' in e.output.decode('utf-8'):
        log.error('ProvisionedThroughputExceededException (provisioned rate exceeded). You\'re doing that too much.')
      else:
        log.error('Starting Textract failed. Error: {}'.format(e.output.decode('utf-8')))

    time.sleep(10)  # wait for Textract to do its' thing

    if job_id != '':
      try:
        subprocess.call(['touch {}'.format(self.output_filename)], shell=True)
        subprocess.call(['{} > {}'.format(get_textract_output_command+job_id, self.output_filename)], shell=True, stderr=subprocess.STDOUT)
        return True
      except subprocess.CalledProcessError as e:
        log.error(e.output)
    else:
      return False

if __name__ == '__main__':
  initial_parser = InitialParser(
    filename='test1.pdf',
    s3_bucket='test-bucket',
  )
  initial_parser.run()

I'd like a better way of handling the wait period for Textract to finish other than waiting 10 seconds, and it may take longer than that in some instances.

I do know that the output file will have "JobStatus": "IN PROGRESS" so I could repeatedly search the output .txt file for "SUCCEEDED", but that could be slow if the file has 40,000+ lines when it's actually done (it will)


texts:
I have recently become annoyed enough with something about the linux command line experience to take action.

I welcome all comments, but specific things I'd like input on are:

Is there something already available that does this?
How would you do the same thing in Perl or Python?
How would you go about reducing code duplication here? (The file-types hash looks similar enough in both places that it feels like I should be able to abstract it)
In unpack, is there a better way of determining file-type?
Can you think of any situations that would cause pack to blow up (and any ways of solving those situations)? Just failing to do anything wouldn't be too bad, but (for example) compressing random other files is something I'd like to avoid.

Take 4:

unpack:

#!/usr/bin/ruby

archive_types = {
  "tar"     => ["tar", "-xvf"],
  "tar.gz"  => ["tar", "-zxvf"],
  "tgz"     => ["tar", "-zxvf"],
  "tar.bz2" => ["tar", "-jxvf"],
  "rar"     => ["unrar", "x"],
  "zip"     => ["unzip"]
}

ARGV.each do |target|
  file_type = target.match(/\.([^\W0-9]{3}?(\.\w+)?)$/)[1]
  if archive_types[file_type]
    args = archive_types[file_type].push target
    system(*args)
  else
    puts "Dunno how to deal with '#{file_type}' files"
  end
end

pack (with added --exclude options for my ease of use):

#!/usr/bin/ruby

require 'optparse'
require 'pp'
require 'fileutils'

archive_types = {
  "tar"     => ["tar", "-cvf"],
  "tar.gz"  => ["tar", "-zcvf"],
  "tgz"     => ["tar", "-zcvf"],
  "tar.bz2" => ["tar", "-jcvf"],
  "zip"     => ["zip"]
}

########## parsing inputs
options = { :type => "tar", :excluded => [".git", ".gitignore", "*~"] }
optparse = OptionParser.new do|opts|
  opts.on("-e", "--exclude a,b,c", Array,
          "Specify things to ignore. Defaults to [#{options[:excluded].join ", "}]") do |e|
    options[:excluded] = e
  end
  opts.on("-t", "--type FILE-TYPE",
          "Specify archive type to make. Defaults to '#{options[:type]}'. Supported types: #{archive_types.keys.join ", "}") do |t|
    options[:type] = t
  end
end
optparse.parse!
##########

ARGV.each do |target|
  if not archive_types[options[:type]]
    puts "Supported types are #{archive_types.keys.join ", "}"
    exit
  elsif options[:type] == "zip"
    exclude = options[:excluded].map{|d| ["-x", d]}.flatten
  else
    exclude = options[:excluded].map{|d| ["--exclude", d]}.flatten
  end
  args = archive_types[options[:type]] +
         [target + "." + options[:type], target] +
         exclude
  system(*args)
end


texts:
The errors are passed through every callback, but in fact, it might be better to throw an error at higher levels. For example, look at the mongodb.js database function. It passes through an error in the callback. However, if there was an error at that level, it might be better to deal with it at that point and just fall back on procces.on('uncaughtException')

It is a lot of extra code each time, dealing with errors in callbacks. I am wondering if there is a better way around it.

controllers/users.js

var usersModel = require('../models/users.js');

users.create = function(req, res){
  usersModel.create(req.data.username, req.data.password, function(error, user){
    if(error){
      res.statusCode = 500;
      res.end('server-error');
      return;
    }

    res.statusCode = 201;
    res.end(user._id);
  });
};

models/users.js

var db = require('../mongodb.js');

module.exports.create = function(username, password, callback){
  db.collection('main', 'users', function(error, collection){
    if(error){
      callback(error);
      return;
    }

    collection.insert({
      username: username,
      password: password,
      createdOn: new Date()
    }, callback);
  });
};

mongodb.js

var mongo = require('mongodb')
  , mongodb = module.exports
  , connections = {}
  , config = {
    main: {
      name: 'application-main',
      server: new mongo.Server('127.0.0.1', 27017, { auto_reconnect: true })
    }
  };

mongodb.database = function(key, callback){
  if(connections[key]){
    callback(null, connections[key]);
    return;
  }

  var db = mongo.Db(config[key].name, config[key].server);

  db.open(function(error, connection){
    if(error){
      callback(error);
      return;
    }

    connection.on('close', function(){
      delete(connections[key]);
    });

    connections[key] = connection;
    callback(null, connection);
  }
};

mongodb.collection = function(dbKey, collName, callback){
  mongodb.database(dbKey, function(error, connection){
    if(error){
      callback(error);
      return;
    }

    connection.collection(collName, function(error, collection){
      if(error){
        callback(error);
        return;
      }

      callback(null, collection);
    });
  });
};


texts:
Can someone review this code for me?  I'm not completely sure I did this correctly. I also would like help creating the code for the "walk" "don't walk" lights.

I needed to create a traffic intersection. Each traffic light has a cycle of 31 seconds red, followed by 26 seconds green, followed by 3 seconds yellow. The red in the north-south direction starts at the same time as the green in the east-west direction. There will be a 60 second light cycle, and a 2 second overlap where the lights are red in all directions. The walk-don't walk signal reads walk for the 26 second green light, and don't walk for all other times.

Public Class _12
Private Sub N_S_G_Lights()
    pb_N.BackColor = Color.Green
    lbl_N.BackColor = Color.Green
    pb_S.BackColor = Color.Green
    lbl_S.BackColor = Color.Green
End Sub
Private Sub N_S_Y_Lights()
    pb_N.BackColor = Color.Yellow
    lbl_N.BackColor = Color.Yellow
    pb_S.BackColor = Color.Yellow
    lbl_S.BackColor = Color.Yellow
End Sub
Private Sub N_S_R_Lights()
    pb_N.BackColor = Color.Red
    lbl_N.BackColor = Color.Red
    pb_S.BackColor = Color.Red
    lbl_S.BackColor = Color.Red
End Sub
Private Sub W_E_G_Lights()
    pb_W.BackColor = Color.Green
    lbl_W.BackColor = Color.Green
    pb_E.BackColor = Color.Green
    lbl_E.BackColor = Color.Green
End Sub
Private Sub W_E_Y_Lights()
    pb_W.BackColor = Color.Yellow
    lbl_W.BackColor = Color.Yellow
    pb_E.BackColor = Color.Yellow
    lbl_E.BackColor = Color.Yellow
End Sub
Private Sub W_E_R_Lights()
    pb_W.BackColor = Color.Red
    lbl_W.BackColor = Color.Red
    pb_E.BackColor = Color.Red
    lbl_E.BackColor = Color.Red
End Sub
Private Sub _12_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    pb_N.BackColor = Color.Red
    pb_E.BackColor = Color.Red
    pb_S.BackColor = Color.Red
    pb_W.BackColor = Color.Red
    lbl_N.BackColor = Color.Red
    lbl_E.BackColor = Color.Red
    lbl_S.BackColor = Color.Red
    lbl_W.BackColor = Color.Red

End Sub

Private Sub Lights()
    If lbl_time.Text <= 33 Then
        W_E_R_Lights()
    ElseIf lbl_time.Text >= 34 And lbl_time.Text <= 58 Then
        W_E_G_Lights()
    ElseIf lbl_time.Text >= 59 Then
        W_E_Y_Lights()
    ElseIf lbl_time.Text >= 60 Then
        W_E_R_Lights()
    End If
    If lbl_time.Text <= 26 Then
        N_S_G_Lights()
    ElseIf lbl_time.Text >= 27 And lbl_time.Text <= 29 Then
        N_S_Y_Lights()
    ElseIf lbl_time.Text >= 30 Then
        N_S_R_Lights()
    End If
End Sub
Private Sub Timer_N_Tick(sender As System.Object, e As System.EventArgs) Handles Timer_N.Tick
    lbl_time.Text = Val(lbl_time.Text) + 1

End Sub

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    lbl_time.Text = "55"
End Sub

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
    lbl_time.Text = "25"
End Sub

Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
    If lbl_time.Text <= 60 Then
        Lights()
    Else
        lbl_time.Text = "0"
    End If
End Sub
End Class


texts:
The following is my implementation of mergesort with Java generics. I chose to use the iteration variables a_iter and b_iter to prevent modifying the lists while merging. Any suggestions for improvement?

public static <T extends Comparable<T>> List<T> mergesort(List<T> list){
    // base case
    int len = list.size();
    if(len<=1)
      return list;
    // recursively sort two halves
    List<T> left = mergesort(list.subList(0,len/2));
    List<T> right = mergesort(list.subList(len/2, len));
    // merge two halves
    List<T> combined = new ArrayList<>();
    // vars to keep place in iteration (used to prevent ConcurrentModificationException)
    int a_iter = 0;
    int b_iter = 0;
    while(a_iter<left.size() || b_iter<right.size()){
      // if left exhausted
      if(a_iter>=left.size()){
        combined.add(right.get(b_iter));
        b_iter++;
        continue;
      }
      // if right exhausted
      if(b_iter>=right.size()){
        combined.add(left.get(a_iter));
        a_iter++;
        continue;
      }
      T a = left.get(a_iter);
      T b = right.get(b_iter);
      if(a.compareTo(b)<0){
        combined.add(a);
        a_iter++;
      }
      else{
        combined.add(b);
        b_iter++;
      }
    }
    return combined;
  }


texts:
I'm currently working on this for my own practice. I get 4 digits and an operation.

The input is x1 y1 op x2 y2 and the fraction is x1/y1 and x2/y2. If I get the input: 1 3 + 1 2 then it's 1/3 + 1/2 and the answer should be given the minimal fractional so it's 5/6. I pass the testcases I get and I can't figure out what I'm doing wrong.

To summarize what I do:

Read input and check the operation if it's +,-,/ or *. I generate a prime array to find the biggest common divisor.
Send the input to a function depending on which operation it is.
I count the given input with simple math.
Then I find the biggest common divisor and divide both numerator and denominator with this.
After that I print out the result.

Here is the main function and how I handle if the operation is *. I handle the other operation the same but with other math.

    #include <iomanip>
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
#include <iterator>
#include <array>
#include <stdio.h>
#include <string.h>
#include <cstddef>
#include <string>
#include <sstream>
#include <math.h>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>

       using namespace std;

long long  nwd(long long a, long long b){
    long long  c;
    while(b != 0){
        c = a % b;
        a = b;
        b = c;
    }
    return a;
}

void add(long long x1, long long y1, long long x2, long long y2){
    long long bottom = (y1) * (y2);
    long long top = ((x1) * (y2)) + ((x2) * (y1));
    //cout << bottom << " " << top << endl;
    long long frac;
    if(bottom != 0||top != 0){
        frac = nwd(top,bottom);
    }else{
        frac = 1;
    }
    string sign = "";
    if(top * bottom < 0){
        sign = "-";
    }else{
        sign = "";
    }
    printf("%s%lld / %lld\n",sign.c_str(),abs(top/frac),abs(bottom/frac) );
}

void sub(long long x1, long long y1,long long x2, long long y2){
    long long bottom = (y1) * (y2);
    long long top = ((x1) * (y2)) - ((x2) * (y1));
    long long frac;
    if(bottom != 0||top != 0){
        frac = nwd(top,bottom);
    }else{
        frac = 1;
    }
    string sign = "";
    if(top * bottom < 0){
        sign = "-";
    }else{
        sign = "";
    }
    printf("%s%lld / %lld\n",sign.c_str(),abs(top/frac),abs(bottom/frac) );
}

void divi(long long x1, long long y1, long long x2, long long y2){
    long long top = (x1) * (y2);
    long long bottom = (x2) * (y1);
    long long frac;
    if(bottom != 0||top != 0){
        frac = nwd(top,bottom);
    }else{
        frac = 1;
    }
    string sign = "";
    if(top * bottom < 0){
        sign = "-";
    }else{
        sign = "";
    }
    printf("%s%lld / %lld\n",sign.c_str(),abs(top/frac),abs(bottom/frac) );
}

void mult(long long x1, long long y1, long long x2, long long y2){
    long long top = (x1) * (x2);
    long long bottom = (y2) * (y1);
    long long frac;
    if(bottom != 0||top != 0){
        frac = nwd(top,bottom);
    }else{
        frac = 1;
    }
    string sign = "";
    if(top * bottom < 0){
        sign = "-";
    }else{
        sign = "";
    }
    printf("%s%lld / %lld\n",sign.c_str(),abs(top/frac),abs(bottom/frac) );
}

int main()
{

    int numOp;
    scanf("%d", &numOp);
    while(numOp != 0){
        long long x1,x2,y1,y2;
        char op[2];
        scanf("%lld %lld %s %lld %lld", &x1, &y1, op, &x2, &y2);
        if( op[0] == '+'){
            add(x1, y1, x2,y2);
        }
        else if(op[0] == '-'){
            sub(x1,y1,x2,y2);
        }
        else if(op[0] == '/'){
            divi(x1,y1,x2,y2);
        }
        else{
            mult(x1,y1,x2,y2);
        }
        numOp--;
    }
    return 0;
}

Here is my code with the given testcase and I get the correct result. I need some tips with either different testcases or any suggestions.


texts: querying users from table if user.id is found in another table

texts:
I am using flask with sqlAlchemy to connect with a postgresql database with two tables

Users table (id, name)

Admissions table (id, userId)

Admissions table with a foreign key (userId) connected to Users(id)

I want to get Users if user.id is found in admissions userId

This is what I am doing

users = [i for i in Users.query.all() if Admissions.query.filter_by(userid=i.id).first()]

Any better way to do this?

Thank you

Edit:
Users

Table "public.users"
  Column  |         Type          | Collation | Nullable |              Default
----------+-----------------------+-----------+----------+------------------------------------
 id       | integer               |           | not null | nextval('users__id_seq'::regclass)
 sid      | character varying(10) |           |          |
 name     | text                  |           |          |
 username | text                  |           |          |
 password | text                  |           |          |
 admin    | boolean               |           |          | false
 deleted  | boolean               |           |          | false
Indexes:
    "users_pkey" PRIMARY KEY, btree (id)
Referenced by:
    TABLE "admissions" CONSTRAINT "admissions_userid_fkey" FOREIGN KEY (userid) REFERENCES users(id)

Admissions

Table "public.admissions"
   Column   |           Type           | Collation | Nullable |                Default
------------+--------------------------+-----------+----------+----------------------------------------
 id         | integer                  |           | not null | nextval('admissions_id_seq'::regclass)
 examid     | integer                  |           |          |
 userid     | integer                  |           |          |
 startdate  | timestamp with time zone |           |          | CURRENT_TIMESTAMP
 submitdate | timestamp with time zone |           |          |
Indexes:
    "admissions_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "admissions_userid_fkey" FOREIGN KEY (userid) REFERENCES users(id)


texts: Difference between API time and server time

texts:
I'm using the openweathermap API to get weather forecast data. I want to make sure that the forecast values are at minimum 2 hours in the future. The API is providing the forecast in 3 hour steps, so I need to make sure that the weather data are in the future.

Here is an example response provided by openweathermap API:

{"city":{"id":1851632,"name":"Shuzenji",
"coord":{"lon":138.933334,"lat":34.966671},
"country":"JP",
"cod":"200",
"message":0.0045,
"cnt":38,
"list":[{
        "dt":1406106000,
        "main":{
            "temp":298.77,
            "temp_min":298.77,
            "temp_max":298.774,
            "pressure":1005.93,
            "sea_level":1018.18,
            "grnd_level":1005.93,
            "humidity":87
            "temp_kf":0.26},
        "weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],
        "clouds":{"all":88},
        "wind":{"speed":5.71,"deg":229.501},
        "sys":{"pod":"d"},
        "dt_txt":"2014-07-23 09:00:00"}
        ]}

I'm using JSON. The list property has the value dt_txt in this format: year-month-day 09:00:00. Now I need to check if this DateTime is minimum 2 hours in the future and if not I simply take the item at index 1 of the list.

I wrote following code:

 // look for next prediction
var weatherList = parsed.list;

// Check which time is relevant
// Get only time without description or/and date
// 2017-03-17 21:00:00
// ~~~~~~~~~~~~~^
var columnIndex = weatherList[0]["dt_txt"].indexOf(":") - 2;
// 2017-03-17 21:00:00
// ~~~~~~~~~~~^
var apiHoursString  = weatherList[0]["dt_txt"].substring(columnIndex, columnIndex + 2);

// server time:
var hours = String((new Date()).getHours());
if(hours.length < 2){
    hours = "0" + hours;
}

var apiHoursInt = parseInt(apiHoursString);
var hoursInt = parseInt(hours);

if((apiHoursInt - hoursInt) < 2){
    indexToUse = 1
}

I know this code is bad - what is the proper way to do that on Node.js?


texts:
Imagine code that reads from a file, cleans the data and finally writes the cleaned data to a new file.

Let's briefly define these methods as Ruby stubs:

def write(filename, data)
   File.open(filename, "w") do |f|
      f.write(data.to_yaml)
   end
end

def read(filename)
   YAML.load_file(filename)
end

def clean(data)
   data.map do |line|
      line.strip!
   end
end

We can also have an orchestrator method that triggers the whole logic:

def read_clean_write(filename)
    write(filename, clean(read(filename)))
end

I think that while the isolated read, write and clean methods are modular and apply the single responsibility principle, read_clean_write is quite the opposite (and looks ugly). What is the best way to do that while keeping SRP?


texts: Program that requests two floating-point numbers and prints the value of their difference divided by their product

texts:
From what I understand this site help to check if my solution is proper or not..so forgive me if the header is bad.

This is my solution for the question:

#include <stdio.h>

int main()

{

    double num1, num2, different, product, answer;

    printf("please enter 2 floatig point numbers:\n");
    printf("number one is?\n");
    scanf("%lf", &num1);
    printf("number two is?\n");
    scanf("%lf", &num2);

    if (num1 > num2)
    {
        different = num1 - num2;
    }

    if (num2 > num1)

    {
        different = num2 - num1;
    }

    if (num1 == num2)

    {
        different = 0;
    }

    product = num1*num2;

    answer = different/product;

    printf("%lf", answer);

}

How bad is it?


texts: Splitting a list of strings into sublists where total of bytes of each sublist is <= N

texts:
I'm given a list of strings and a length limit N. I have to write a function to accumulate consecutive strings in the list until the next string would exceed the N limit. I have to return a list of lists, where each list is the largest consecutive substring not to exceed N characters total. See the test case below for an example. Also, if any single string in the list is longer than N, I have to print a useful message and return.

My attempt to solve the problem has been this one:

def break_lst(lst, size):
    def len_lst(l):
        return len("".join(l))

    err = "Error: use a bigger size than " + str(size)
    result = []
    sublst = []

    for v in lst:
        sublst.append(v)
        ls = len_lst(sublst)

        if ls == size:
            result.append(sublst)
            sublst = []
        elif ls > size:
            prev_sublst = sublst[:-1]
            if not prev_sublst or len_lst(prev_sublst) > size:
                raise Exception(err)
            else:
                result.append(prev_sublst)
                sublst = [v]

    if sublst:
        if len_lst(sublst) > size:
            raise Exception(err)
        else:
            result.append(sublst)

    return result

if __name__ == "__main__":
    lst = ["1", "22", "333", "4444", "55555", "666666", "7777777", "88888888"]

    for i in range(17):
        try:
            print(i, break_lst(lst, size=i))
        except Exception as e:
            print(e)

Output:

Error: use a bigger size than 0
Error: use a bigger size than 1
Error: use a bigger size than 2
Error: use a bigger size than 3
Error: use a bigger size than 4
Error: use a bigger size than 5
Error: use a bigger size than 6
Error: use a bigger size than 7
8 [['1', '22', '333'], ['4444'], ['55555'], ['666666'], ['7777777'], ['88888888']]
9 [['1', '22', '333'], ['4444', '55555'], ['666666'], ['7777777'], ['88888888']]
10 [['1', '22', '333', '4444'], ['55555'], ['666666'], ['7777777'], ['88888888']]
11 [['1', '22', '333', '4444'], ['55555', '666666'], ['7777777'], ['88888888']]
12 [['1', '22', '333', '4444'], ['55555', '666666'], ['7777777'], ['88888888']]
13 [['1', '22', '333', '4444'], ['55555', '666666'], ['7777777'], ['88888888']]
14 [['1', '22', '333', '4444'], ['55555', '666666'], ['7777777'], ['88888888']]
15 [['1', '22', '333', '4444', '55555'], ['666666', '7777777'], ['88888888']]
16 [['1', '22', '333', '4444', '55555'], ['666666', '7777777'], ['88888888']]

Problems with the function:

The proposed algorithm is really ugly and unpythonic
The fact it's handling an special case when the loop has finished makes it even uglier

How would you proceed in order to make a cleaner algorithm out of it?


texts: Best place to locate filters in MVC n-layer web application and should I use services/repositories in them?

texts:
I am a little confused over which layers my filters should be contained in with an n-layer web application.

I've got 4 layers:

Presentation layer
Application layer
Business layer
Infrastructure layer

The Presentation layer can only talk to the Application layer and the Infrastructure layer. The Application layer can only talk to the Presentation layer, Business layer and the Infrastructure layer. The Business layer can only talk to the Application layer and the Infrastructure layer.

All my models, views and controllers are stored in the Presentation layer.

I have the following code:

public class AuthoriseAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        if (SkipAuthorisation(filterContext))
        {
            return;
        }

        // This line...
        var evalReportProxy = new EvalReportProxy(WebHelper.PcwAliasName);
        if (evalReportProxy.EvalReport.SubscribedToModule("Workspace Only"))
        {
            filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary
            {
                { "controller", "Redirect" },
                { "action", "Workspace" }
            });
        }

        if (string.IsNullOrEmpty(WebHelper.Username) || WebHelper.IsGuest)
        {
            filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary
            {
                { "controller", "Account" },
                { "action", "LogIn" }
            });
        }
    }

    private static bool SkipAuthorisation(AuthorizationContext filterContext)
    {
        return filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true)
            || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true);
    }
}

I've highlighted a line of code using a comment which shows where I am making use of a concrete type in the infrastructure layer to check to see if a user is subscribed to a module. By using a concrete type I've made it impossible to use mock objects which I want to avoid, but...

I'm a little confused because in the line highlighted using a comment I guess I should really be using a repository or a service although I'm not really sure if I should be or not. Also, if I use a repository then the filters can't be in the presentation layer, but I'm not sure if services are purely for controllers or whether I can use services elsewhere.

Can anyone please advise me on whether I should be putting filters in the presentation layer or not, and whether or not I should be using a service, repository, or keep the code how it is.

Also, I'm open to code improvements if you think any can be made.


texts:
I've a scenario where 10K+ regular expressions are stored in a table along with various other columns and this needs to be joined against an incoming dataset. Initially I was using "spark sql rlike" method as below and it was able to hold the load until incoming record counts were less than 50K

PS: The regular expression reference data is a broadcasted dataset.

dataset.join(regexDataset.value, expr("input_column rlike regular_exp_column")

Then I wrote a custom UDF to transform them using Scala native regex search as below,

Below val collects the reference data as Array of tuples.

val regexPreCalcArray: Array[(Int, Regex)] = {
        regexDataset.value
            .select( "col_1", "regex_column")
            .collect
            .map(row => (row.get(0).asInstanceOf[Int],row.get(1).toString.r))
    }

Implementation of Regex matching UDF,

    def findMatchingPatterns(regexDSArray: Array[(Int,Regex)]): UserDefinedFunction = {
        udf((input_column: String) => {
            for {
                text <- Option(input_column)
                matches = regexDSArray.filter(regexDSValue => if (regexDSValue._2.findFirstIn(text).isEmpty) false else true)
                if matches.nonEmpty
            } yield matches.map(x => x._1).min
        }, IntegerType)
    }

Joins are done as below, where a unique ID from reference data will be returned from UDF in case of multiple regex matches and joined against reference data using unique ID to retrieve other columns needed for result,

dataset.withColumn("min_unique_id", findMatchingPatterns(regexPreCalcArray)($"input_column"))
.join(regexDataset.value, $"min_unique_id" === $"unique_id" , "left")

But this too gets very slow with skew in execution [1 executor task runs for a very long time] when record count increases above 1M. Spark suggests not to use UDF as it would degrade the performance, any other best practises I should apply here or if there's a better API for Scala regex match than what I've written here? or any suggestions to do this efficiently would be very helpful.


texts:
A collection of sorting types as following insertion, radix, selection and heap sorts.

How can i improve it?

#include <algorithm>
#include <functional>
#include <type_traits>
#include <iostream>

template <typename Iterator>
void radixSort(Iterator begin, Iterator end)
{
    using value_type = typename std::iterator_traits<Iterator>::value_type;

    for (auto i = 0; i < 32; ++i)
    {
        std::stable_partition(begin, end,
            [&](value_type& value)
        {
            if (i == 31)
                return value < 0;
            else
                return !(value & (1 << i));
        });
    }
}

template<typename Iterator>
void insertionSort(Iterator begin, Iterator end)
{
    using value_type = typename std::iterator_traits<Iterator>::value_type;

    for (auto i = begin; i != end; ++i)
    {
        std::rotate(std::upper_bound(begin, i, *i, std::less<value_type>()), i, std::next(i));
    }
}

template <typename Iterator>
void selectionSort(Iterator begin, Iterator end)
{
    using value_type = typename std::iterator_traits<Iterator>::value_type;

    for (; begin != end; ++begin)
    {
        const auto minElemt(std::min_element(begin, end, std::less<value_type>()));

        if (begin != minElemt)
        {
            std::iter_swap(begin, minElemt);
        }
    }
}

template <typename Iterator>
void heapSort(Iterator begin, Iterator end)
{
    using value_type = typename std::iterator_traits<Iterator>::value_type;

    std::make_heap(begin, end, std::less<value_type>());
    std::sort_heap(begin, end, std::less<value_type>());
}

int main()
{
    int a[] = {9,-6, 7, -8, 6, -9, 1, 3, -4, 2, -1, -5, 5, 8, -3, 4, 0, -2, -7 };

    radixSort(std::begin(a), std::end(a));
    //insertionSort(std::begin(a), std::end(a));
    //selectionSort(std::begin(a), std::end(a));
    //heapSort(std::begin(a), std::end(a));

    for (const auto& i : a)
    {
        std::cout << i << ' ';
    }
}


texts: Project Euler # 36 Double-base palindromes in Python

texts:
The decimal number, 585 = 1001001001 (binary), is palindromic in both bases.
Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
(Please note that the palindromic number, in either base, may not include leading zeros.)

Awaiting feedback.
def is_palindrome(n):
    """returns True if palindrome, False otherwise."""
    to_str = str(n)
    if to_str == to_str[::-1]:
        return True
    return False

def find_palindromes(n):
    """generates all numbers if palindrome in both bases 2, 10 in range n. """
    decimal_binary = {decimal: bin(decimal)[2:] for decimal in range(1, n) if is_palindrome(decimal)}
    for decimal, binary in decimal_binary.items():
        if is_palindrome(binary) and not binary[0] == 0:
            yield decimal

if __name__ == '__main__':
    print(sum(list(find_palindromes(1000000))))


texts: Having graphics resize in line with the Frame in Swing

texts:
I have drawn a box within my JPanel so that it resizes appropriately when the JFrame is resized.

This is how I implement it:

public void drawBox(Graphics g){
    int num1 = getWidth()/4, num2 = getHeight()/4, num3 = getWidth() - num1,
            num4 = getHeight() - num2;
    g.drawLine(num1, num2, num3, num2);
    g.drawLine(num1, num2, num1, num4);
    g.drawLine(num3, num2, num3, num4);
    g.drawLine(num1, num4, num3, num4);
}

What I have done works but is there a better way to do this? I'd like general feedback, cleaner code would be my main priority though.


texts: Converting a range of integers from a string to an IEnumerable

texts:
Goal

Convert the following into an IEnumerable of integers accounting for the x-y ranges:

"1,2,3,0,7,8,9,10-15"

to

{ 1, 2, 3, 0, 7, 8, 9, 10, 11, 12, 13, 14, 15 }

Current implementation

I've written this little function and got something working, but I'm wondering if this can become more efficient or rich in features. My test cases all pass which cover positive and negative ranges.

public IEnumerable<int> GetRange(string numbers) {
    string[] items = numbers.Split(',');

    foreach (var item in items) {
        if (!string.IsNullOrWhiteSpace(item)) {
            //does it contain a -? it's a range then
            int result;
            if (item.Contains("-") && !item.EndsWith("-")) {
                int start, end;
                if (int.TryParse(item.Substring(0, item.IndexOf("-")), out start) && int.TryParse(item.Substring(item.IndexOf("-") + 1), out end)) {
                    int direction = start < end ? 1 : -1;
                    for (result = start; (direction == 1 ? result < end + direction : result > end + direction); result += direction)
                        yield return result;

                    continue;
                }
            }

            if (int.TryParse(item, out result)) {
                yield return result;
                continue;
            }

        }

        throw new InvalidCastException(string.Format("Unable to cast \"{0}\" to an int", item));
    }
}


texts: conditional simulation(path dependent simulation) in R

texts:
My codes are not good, I want to konw how to solve my problem efficicently and learn writing some elegant R codes.Thanks in advance!

"r" is the starting value in matrix[loop,T], I want to use it to do the simulation for 45years in 10 times,which means that I will get a new matrix[loop,T] also name "r" after first for-loop.Then, I want to use the second column data in this new matrix "r" to do the simulation again,which means that I will use r[1,2],r[2,2],r[3,2]...r[loop,2] to do the simulation, in this way,each data in r[,2] will create a matrix name "b"[loop,T],so I compute the average value of the second column in each matrix "b"[loop,T], then I get 10(=loop) new starting values again to do the simulation.At last,I have the final_data output

alpha<-0.0212;beta<-0.0063;sigma<-0.0012;dt<-1;T<-46;loop<-10
r<-matrix(rep(-0.0002,loop*T),loop,T)

for(i in 1:loop)
{
  for(j in 2:T)
  {
    r[i,j]<-r[i,j-1]+alpha*(beta-r[i,j-1])*dt+sigma*sqrt(dt)*rnorm(1,0,1)
  }

}

c<-matrix(rep(0,loop*1),loop,1)
for(k in 1:loop)
{
b<-matrix(rep(r[k,2],loop*T),loop,T)
for(i in 1:loop)
{
  for(j in 2:T)
  {
    b[i,j]<-b[i,j-1]+alpha*(beta-b[i,j-1])*dt+sigma*sqrt(dt)*rnorm(1,0,1)
  }
}
c[k,1]<-mean(b[,2])
}

e<-matrix(rep(0,loop*1),loop,1)
for(k in 1:loop)
{
  d<-matrix(rep(c[k,1],loop*T),loop,T)
  for(i in 1:loop)
  {
    for(j in 2:T)
    {
      d[i,j]<-d[i,j-1]+alpha*(beta-d[i,j-1])*dt+sigma*sqrt(dt)*rnorm(1,0,1)
    }
  }
  e[k,1]<-mean(d[,2])
}

final_data<-data.frame(r[,2],c,e)


texts: Generating permutations with repetitions of string

texts:
I have written the below code which generates all possible permutations with repetitions of a string.

I want to make this program shorter and much faster, but I don't know how to do that.

Imports System.Text

Public Class Form1

    Private blkRpt As Integer
    Private perm As Double

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim textlen As Double = TextBox1.Text.Length
        Dim rtb As Double = TextBox2.Text
        perm = textlen ^ rtb
        permutate()
    End Sub

    Private Sub permutate()

        For a As Integer = 0 To 1 Step 0
            Dim s As String = TextBox1.Text
            Dim len As Integer = TextBox2.Text
            Dim r As New Random
            Dim sb As New StringBuilder

            For i As Integer = 1 To len
                Dim idx As Integer = r.Next(0, s.Length)
                sb.Append(s.Substring(idx, 1))
            Next

            Dim sring As String = sb.ToString

            If RichTextBox1.Text.Contains(sb.ToString) Then
                blkRpt = blkRpt + 1
            Else
                RichTextBox1.AppendText(sring & vbNewLine)
           End If

           Dim s1 As String = TextBox1.Text
           Dim len1 As Integer = TextBox2.Text
           Dim r1 As New Random
           Dim sb1 As New StringBuilder

           For i As Integer = 1 To len1
               Dim idx1 As Integer = r1.Next(0, s1.Length)
               sb1.Append(s1.Substring(idx1, 1))
           Next

           Dim sring1 As String = sb1.ToString

           If RichTextBox1.Text.Contains(sb1.ToString) Then
                blkRpt = blkRpt + 1
           Else
                RichTextBox1.AppendText(sring1 & vbNewLine)
           End If

           Dim s2 As String = TextBox1.Text
           Dim len2 As Integer = TextBox2.Text
           Dim r2 As New Random
           Dim sb2 As New StringBuilder

           For i As Integer = 1 To len2
               Dim idx2 As Integer = r2.Next(0, s2.Length)
               sb2.Append(s2.Substring(idx2, 1))
           Next

           Dim sring2 As String = sb2.ToString

           If RichTextBox1.Text.Contains(sb2.ToString) Then
               blkRpt = blkRpt + 1
           Else
               RichTextBox1.AppendText(sring2 & vbNewLine)
           End If

           Dim s21 As String = TextBox1.Text
           Dim len21 As Integer = TextBox2.Text
           Dim r21 As New Random
           Dim sb21 As New StringBuilder

           For i As Integer = 1 To len1
               Dim idx21 As Integer = r21.Next(0, s2.Length)
               sb2.Append(s2.Substring(idx21, 1))
           Next

           Dim sring21 As String = sb21.ToString

           If RichTextBox1.Text.Contains(sb21.ToString) Then
               blkRpt = blkRpt + 1
           Else
               RichTextBox1.AppendText(sring21 & vbNewLine)
           End If

           If RichTextBox1.Lines.Length - 1 >= perm Then
               Exit For
           End If

           Label6.Text = blkRpt.ToString
           Label5.Text = RichTextBox1.Lines.Length - 1 & "/" & perm
       Next
    End Sub
End Class


texts:
I want to put some text next to its label (both of which are text blocks - which are faster than labels as I understand it). The best way I've found for doing this is a stack panel.

I have (repeated 3 times in a control) code like:

    <StackPanel  Grid.Column="1" Grid.Row="2" Grid.ColumnSpan="2" Orientation="Horizontal">
        <TextBlock Text="Start:" FontWeight="DemiBold" VerticalAlignment="Bottom" HorizontalAlignment="Left"/>
        <TextBlock  Text="12:00pm"  VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="5,0"/>
    </StackPanel>

Is this the cleanest way to do this, or is there a better control? I was kind of thinking about making a wrapper control around the stack panel, but then I would just end up with:

    <LabeledTextBlock Grid.Column="1" Grid.Row="2" Grid.ColumnSpan="2">
<LabledTextBlock.Label>
        <TextBlock Text="Start:" FontWeight="DemiBold" VerticalAlignment="Bottom" HorizontalAlignment="Left"/>
</LabledTextBlock.Label>
        <TextBlock  Text="12:00pm"  VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="5,0"/>
    </LabeledTextBlock >

I guess I could refine it more:

<LabeledContent Grid.Column="1" Grid.Row="2" Grid.ColumnSpan="2" Label="Start" Content="12:00pm"/>

Simplicity at the cost of flexibility. Perhaps instead I should be doing it as a style?


texts: Using a separate class in Symfony to handle a list of entities with controller injection

texts:
In my Symfony (v2.7.9) project I have a set of entities which share some view functionality i.e being displayed in a table with some of their values as columns.

Following the separation of concerns principle, I've made a ListTable class which handles getting the table headers, rows and column values and I'm extending this for entities which need a little bit of extra functionality e.g ProductListTable

class ListTable extends AbstractLibrary {
    protected $items = [];
    protected $query;
    protected $controller;

    protected $tableKeys = [
        'name',
        'status',
    ];

    public function __construct( BaseController $controller ) {
        $this->controller = $controller;
        $this->query = $controller->request->query;
    }

    public function getTableKeys() {
        return $this->tableKeys;
    }

    public function getItems() {
        if ( empty( $this->items ) ) {
            foreach ( $this->controller->getResults() as $entity ) {
                $this->items[] = [
                    'id'      => $entity->getId(),
                    'href'    => $this->controller->getUrl( 'edit', [ 'id' => $entity->getId() ] ),
                    'columns' => $this->getColumns( $entity ),
                ];
            }
        }

        return $this->items;
    }
    ...

-

class ProductListTable extends ListTable {
    protected $tableKeys = array(
        'name',
        'sku',
        'price',
        'brand',
        'status',
        'date_added',
    );
    ...

Then within a controller method I create an instance of the class with:

new ProductListTable( $this );

There's just something I don't like about having to pass in the entire controller instance so I can use some of the methods/services within it. On the other hand, there are quite a few dependencies including some services I'd need to inject through the constructor if I don't inject the controller.

So what I'd like to know is, is it bad practice to inject the controller or is that preferable to injecting 5/6 dependencies as separate function arguments for the constructor? Or does the fact I require these dependencies within the ListTable class mean I'm going about it the wrong way?


texts: Unsigned integer division ARM Cortex-M0+ Assembly

texts:
I am writing a subroutine for unsigned integer division in Assembly. I will call the subroutine DIVU.

Inputs: R1 will be the dividend. The divisor will be in R0.
Outputs: The quotient is going to be in RO and the remained in R1.

Basically, I am trying to make something like this:

R1 / R0 = R0remainderR1

If R0=0, I want to leave the input parameters unchanged and set the C flag when it returns. Otherwise, I just want to clear the C flag. I do not want to change any other registers' values after returning.

I have followed this idea:

Quotient = 0;
while (Dividend >= Divisor) {
    Dividend -= Divisor;
    Quotient += 1;
}
Remainder = Dividend;

This is just a learning exercise, so the low performance of repeated subtraction is ok, as discussed in comments on the original Stack Overflow question posted before writing this code.

And in Assembly this is what I produced:

DIVU
    CMP R1,#0       ;compares R1 to 0
    BEQ AnsZero     ;if R1=0, it branches to AnsZero (the final answer will be 0)
    CMP R0,#0       ;compares R0 to 0
    BEQ EndFlag     ;if R0=0, it will go to the end to set C flag
    PUSH    {R3, LR}        ;saves R3 so it can used as a counter for quotient
    MOV R3,#0       ;sets R3 to 0
    While   CMP R0,R1       ;start of while loop
    BLT EndWhil     ;Branches to end of while when dividend < divisor, otherwise goes through loop
    SUB R1,R1,R0    ;R1=R1-R0 , dividend=dividend-divisor
    ADD R3,R3,#1    ;R3=R3+1, quotient=quotient+1 (init is zero, so 0+1=1 if one successful loop)
    B   While       ;continues loop

EndWhil MOV R0,R3       ;R0=R3, the register that had the divisor gets the quotient
    POP {R3, PC}        ;R3's original value is returned
    BX  LR      ;ends subroutine

EndFlag SUBS    R0,R0,#1
    MOV     R0, #0
    BX  LR      ;ends subroutine

AnsZero MOV R0,#0       ;sets R0=0 because R1=1, 0/X=0r0
    BX  LR      ;ends subroutine

    BX  LR      ;ends subroutine


texts:
I have written a crawler in python with the combination of class and function. Few days back I saw a scraper in a tutorial more or less similar to what I did here. I found it hard the necessity of using class here. However, I decided to create one. My scraper is able to traverse all the next pages and print the collected results errorlesly. If there is any suggestion or input to give this scraper a better look, I'm ready to comply with that. Thanks in advance.

Here is what I've written:

import requests
from urllib.request import urljoin
from lxml.html import fromstring

main_link = "https://www.yify-torrent.org/search/western/"

class movie_doc(object):
    def __init__(self,name,genre,quality,size,rating):
        self.name = name
        self.genre = genre
        self.quality = quality
        self.size = size
        self.rating = rating

film_storage = [] # global variable

def get_links(link):
    root = fromstring(requests.get(link).text)
    for item in root.cssselect(".mv"):
        name = item.cssselect("h3 a")[0].text
        genre = item.cssselect("li b:contains('Genre:')")[0].tail
        quality = item.cssselect("li b:contains('Quality:')")[0].tail
        size = item.cssselect("li b:contains('Size:')")[0].tail
        rating = item.cssselect("li b:contains('Rating:')")[0].tail
        film_details = movie_doc(name,genre,quality,size,rating)
        film_storage.append(film_details)

    next_page = root.cssselect(".pager a:contains('Next')")[0].attrib['href'] if root.cssselect(".pager a:contains('Next')") else ""
    if next_page:
        full_link = urljoin(link,next_page)
        get_links(full_link)

if __name__ == '__main__':
    get_links(main_link)
    for item in film_storage: # as film_storage variable is declared global I called here directly
        print(item.name,item.genre,item.quality,item.size,item.rating)


texts:
If I am not mistaken, this method has a complexity \$O(N^2)\$:

int[] exampleArray = { 4, 6, 2, 2, 6, 6, 1, 55, 55, 2, 5, 6, 90, 8, 8, 8, 10, 70 };
int k = GetMaximumCycle(exampleArray);

public static int GetMaximumCycle(int[] anArray)
{
   int length = anArray.Length;
   int result = 0;
   for (int i = 0; i < length; i++)
   {
      for (int j = 0; j < length; j++)
      {
          if (anArray[i] == anArray[j])
          {
             if (!(result > Math.Abs(i - j)))
                 result = Math.Abs(i - j);
          }
      }
   }
   return result;
}

I compare values and gets the maximum difference between items of array.
The result variable is 10.

And if an input array is very large, this code works slowly. Is it possible to simplify the for loops or remove the second for loop to have a complexity of \$O(N)\$?


texts:
In my BlogList.vue component I made a search input field:
<input type="text" placeholder="Enter key word  ..." v-model="search">

And a computed property:
computed: {
    getfilteredData() {
     return this.blogs.filter(blog =>
        blog.name.toLowerCase().includes(
          this.search.toLowerCase()
        ) ||
        blog.category.toLowerCase().includes(
          this.search.toLowerCase()
        )
      )
    }
  },

The user can search on multiple values, blog.name and blog.category, which updates the list accordingly.
But can I write the above JavaScript (computed property) in a cleaner way?


texts: Writing to a file in Golang across concurrent go routines

texts:
I've been reading around how golang writes to a file, and this stack overflow question and this reddit question highlights the fact Go doesn't gurantee atomicity when writing to a file system. Although I didn't see any interleaved writes (which I guess could be due to writev(2)), I didn't want to risk it so I built a a simple Go interface to do that.

I'm not super proficient with Go, but I'd like to understand how this code can be improved with best practices and on potential issues that may arise when using it.

package main

import (
    "fmt"
    "io"
    "os"
)

// FileLogger defines the methods to log to file
type FileLogger interface {
    Write(s string)
}

type fileLogger struct {
    stream chan string
    writer io.Writer
}

func (l *fileLogger) run() {
    for {
        select {
        case s := <-l.stream:
            _, err := l.writer.Write([]byte(s))
            if err != nil {
                fmt.Println("Error writing to file: ", err.Error())
            }
        }
    }
}

func (l *fileLogger) Write(s string) {
    l.stream <- s
}

// NewFileLogger returns a new FileLogger
func NewFileLogger() FileLogger {
    file, err := os.OpenFile(
        "logs/logs.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666,
    )

    if err != nil {
        panic(err)
    }

    f := &fileLogger{make(chan string), file}
    go f.run()
    return f
}

I could for instance make it conform to the io.Writer interface, but I'm not sure what benefits there are of that?

Would there be an advantage to mutex locks here using the sync package?


texts:
This is the first exercise from https://gophercises.com/.
Basically the idea is to parse a CSV file in a form of 'question:answer' and count the number of correct answers. Also you have a time out range in which you must finish it.
I would appreciate any comments, good or bad :) Thanks a lot !
package main

import (
        "encoding/csv"
        "os"
        "fmt"
        "flag"
        "time"
)

const Ready = "yes"

var correctAnswers int

func getFileContent(filename string) (records[][] string, err error) {
        fd, err := os.Open(filename)

        if err != nil {
                exit("Problem with opening the file")
        }

        reader := csv.NewReader(fd)
        return reader.ReadAll()
}

func outputResult(totalQuestions, correctAnswers int) {
        fmt.Println("Number of total questions:", totalQuestions)
        fmt.Println("Number of corrected answers:", correctAnswers)
}

func exit(message string) {
        fmt.Println(message)
        os.Exit(3)
}

func provideQuestions(questions[][] string, done chan bool) {
        for index, value := range questions {
                question, answer := value[0], value[1]
                fmt.Println("Question N:=", index+1, "=>", question)

                var userAnswer string
                fmt.Scanf("%s", &userAnswer)

        if userAnswer == answer {
            correctAnswers ++
        }
        }

        done <- true
}

func main() {
    fileName := flag.String("name of csv file", "problems.csv", "The name of the csv file - default to 'problems.csv'")
    allowedTime := flag.Int("allowed time", 10, "The duration in seconds for which the quizz must be finished.")
    flag.Parse()

    var readyToStart string
    fmt.Println("Type 'yes' if you are ready to start")
    fmt.Scanf("%s", &readyToStart)

    if readyToStart != Ready {
        fmt.Println("Come back later if you are ready")
        os.Exit(0)
    }

    records, err := getFileContent(*fileName)

    if err != nil {
            exit("Reader problem.")
    }

    done := make(chan bool)
    timer := time.NewTimer(time.Duration(*allowedTime) * time.Second)

    go provideQuestions(records, done)

    select {
    case <- done:
            fmt.Println("Great job")
            fmt.Println("You finished with all questions.")
    case <- timer.C:
            fmt.Println("Time expired")
        }

    outputResult(len(records), correctAnswers)

}


texts:
Call from my index.php to function get_data($curr_date) goes from here

case "events" :
                    $curr_date = $_POST['current_date'];
                    if ( $eid = get_data($curr_date) )
                        {

                            $result = array( "success"=>true,
                            "eid"=>$eid);

                            $json_output = json_encode( $result );
                            echo $json_output;
                        }
                        else
                            echo FAIL;

    break;

    enter code here

This is my function which returns the result

function get_data($curr_date)
{
    $events_list = mysql_query( "SELECT eid, display_date, word_of_the_day, word_of_the_day_meaning, thought_of_the_day,
    crazyFact_of_the_day, joke_of_the_day FROM eventsoftheday WHERE display_date = '$curr_date' ");
                                // get mysql result cursor
    if( mysql_num_rows( $events_list )  > 0 ) // check if the query returned any records
    {
        $mysql_record = mysql_fetch_array( $events_list );    // parse mysql result cursor
        $events = array();
         $events['e_id'] = $mysql_record['eid'];
         $events['edisplay_date'] = $mysql_record['display_date'];
         $events['eword_of_the_day'] = $mysql_record['word_of_the_day'];
         $events['eword_of_the_day_meaning'] = $mysql_record['word_of_the_day_meaning'];
         $events['ethought_of_the_day'] = $mysql_record['thought_of_the_day'];
         $events['ecrazyFact_of_the_day'] = $mysql_record['crazyFact_of_the_day'];
         $events['ejoke_of_the_day'] = $mysql_record['joke_of_the_day'];

        return $events;     // return events

    }
    else
        return false;
}


texts:
I have the following HTTP reply saved in a local file called source.txt:

HTTP/1.1 301 Moved
Connection: close
Content-length: 111
Location: https://11.12.13.14:81/
Content-type: text/html; charset="utf-8"

<META HTTP-EQUIV="refresh" CONTENT="0;URL=https://11.12.13.14:81/">

Source code:

#include <stdio.h>
#include <stdlib.h>
#define MAXBUFLEN 1024

char* getLocation(char* source)
{
    const char *p1 = strstr(source, "Location:")+10;
    const char *p2 = strstr(p1, "\n");
    size_t len = p2-p1;
    char *res = (char*)malloc(sizeof(char)*(len+1));
    strncpy(res, p1, len);
    res[len] = '\0';
    return res;
}

char* getData(char* source)
{
    const char *p1 = strstr(source, "://")+3;
    const char *p2 = strstr(p1, "\n");
    size_t len = p2-p1;
    char *res = (char*)malloc(sizeof(char)*(len+1));
    strncpy(res, p1, len);
    res[len] = '\0';
    return res;
}

int main()
{
    char source[MAXBUFLEN];
    char host[100];
    int port;
    FILE *fp = fopen("source.txt", "r");
    if (fp != NULL) {
        size_t newLen = fread(source, sizeof(char), MAXBUFLEN, fp);
        if (newLen == 0) {
            fputs("Error reading file", stderr);
        } else {
            source[++newLen] = '\0';

//extraction code
            char* res = getLocation(source);
            printf("getLocation result: %s\n", res);
            if (strstr(res, "://"))
            {
                res = getData(source);
                printf("getData result: %s\n", res);
                if (strstr(res, ":"))
                {
                    sscanf(res, "%[^:]:%d[^/]", host, &port);
                    printf("host: %s | port: %d\n", host, port);
                }
                else
                    printf("delimiter not found\n");
            }
            else
                printf("no link\n");
//
        }
    }
    fclose(fp);
}

The program is working well, but it's very ugly.  Is there any way to improve the code to avoid doing so many operations?  I mean somehow merging the two functions, getLocation() and getData().


texts:
I wrote code using some kind of breadth-first-search algorithm in order to find a path (any path!) from a start point to an end point. There are no weights/different distances involved from path-to path-so I am not sure I should use Dijkstra's algorithm.

However, I am required to find a solution that can search for and return a path within a second (while this current code can complete it in five seconds). Assuming my code is inefficient, what can I do better?

$visited = Array.new
$queue = Array.new
def find_path (start, endpoint)
  returnArray = Array.new
  start = start.to_s
  endpoint = endpoint.to_s
  $queue.push(start)
  nextPaths = get_next_paths(start)
  if start == endpoint
    return returnArray.push(endpoint)
  else
    $visited.push(start)
    $queue.pop(start.to_i)
    nextPaths.each { |i| next if $visited.include?(i);
    $queue.push(i)
    returnArray = find_path(i.to_i, endpoint.to_i)
        if returnArray == nil
            next
        elsif !returnArray.empty?
            returnArray.unshift(start)
            return returnArray
        end
    }
  end

  if !$queue.empty?
    return []
  else
    return nil
  end
end

def get_next_paths(id)
  return $h[id.to_s]
end

def direct_connection?(id1, id2)
  next_paths = get_next_paths(id1)
  return (next_paths!=nil and next_paths.include?(id2.to_s))
end

def valid_path?(path)
  while (path.length>1)
    current_element = path.first
    next_element = path[1]

    if (!direct_connection?(current_element, next_element))
      return false
    end

    path.shift
  end
  return true
end


texts: Functional Implementation of Co-prime pairs in array

texts:
Program finds the number of pairs of co-primes in an array using
functional concepts in Node.js

const assert = require('assert')

const gcd = (a, b) => (b != 0) ? gcd(b, a % b) : a

const co_prime = (a, b) => gcd(a, b) == 1

const co_prime_pairs = (_list) => {
    co_primes = []
    _list.map(
        (x, i) => _list.slice(i + 1)
                        .filter(y => co_prime(x, y))
                        .forEach(y => co_primes.push([x, y]))
        )
    return co_primes.length
}

const main = () => {
    assert.equal(co_prime_pairs([1, 2, 3]), 3)
    assert.equal(co_prime_pairs([4, 8, 3, 9]), 4)
}

main()

Is the time complexity similar to that of the simple for-loop implementation?

Is there any scope for improving the time-complexity by using map and filter functions?

How is my choice of variable names?

How is code formatting?


texts:
I'm writing an application that is meant to validate data.  The data comes in the form of JSON and I'm using JSON Schema to validate the structure and some of the logic along with functions to validate more of the core business logic.

I need to be able to track what has failed the validation and pass that off to another application to be dealt with.  So far I have about 50 odd validation tests, 25 core business logic tests and another 25 or so that are just checking and reporting the errors from the JSON schema validation.

I'm using Node.js 9.4 and ES6.

I think i've created something kind of terrible so far and could do with some advice on a better way of implementing this:

Rule.js

class Rule {
  constructor(release) {
    this.release = release;
    this.errors = [];
    this.validator = false;
  }

  static registerRule(rule) {
    Object.assign(this.prototype, rule);
  }

  static registerValidator(validator) {
    if (!this.validator) {
      this.validator = true;
      Object.assign(this.prototype, validator);
    } else {
      throw {
        toString: function() {
          return 'validator already assigned';
        }
      };
    }
  }

  _recordError(error, options) {
    this.errors.push({
      release_id: this.release.id,
      rule: error,
      options: options,
    });
  }
}

module.exports = Rule;

I'll then have a validation rule, which might be either a check to find out the error from my json schema validator, or a business logic style rule:

NoExclusive.js

module.exports = {
  exclusive: function(errors) {
    errors.some( (error) => {
      if (error.parentSchema.regexp === '/^((?!exclusive).)*$/i') {
        this._recordError('NOEXCLUSIVE');
      }
    });
  }
};

I create a validator

Validate.js

module.exports = {
  validate: function(errors) {
    this.exclusive(errors);
    // ... Other rules too

    return this.errors;
  }
};

I then have an index page where I add the validation rules to the Rule object as well as the validator.

index.js

const Rule = require('../../Rule');

Rule.registerRule(require('./NoExclusive'));
// ... Other rules
Rule.registerValidator(require('./Validate'));

module.exports = Rule;

I'll then instantiate it later on in the application, where I pass it the data (release in the constructor).

I don't feel that this is the best way of doing this.  I kind of wanted to be able to have 2 different Rule Objects, one for business logic and the other for JSON schema errors, but i've boxed myself in with this method.  Is there a better way, or a design pattern I can leverage for this?