texts:
In order to convert a database type DB_NUMERIC to real, I noticed that a call to IDataConvert::Release() does not return 0, which is indicative of some additional pointers to the object dangling somewhere. In order to free the object, I would need a loop, which in my case has exactly 19 iterations. Or can it be IDataConvert is actually stack based? In which case I think it is odd that it would retain a reference count at all instead of Release() returning a fixed value. One more Release() at the end does not crash the program, suggesting a stack based object. Of course I don't want my program to leak memory, so would it be safe to ignore the problem and call Release() just once? And of course it is bad to release pointers that you do not own...

HRESULT hr;
IDataConvert* pConv;
hr = CoCreateInstance(CLSID_OLEDB_CONVERSIONLIBRARY, NULL, CLSCTX_INPROC_SERVER, IID_IDataConvert, (LPVOID*)&pConv);
hr = pConv->CanConvert(DBTYPE_NUMERIC, DBTYPE_R8);
hr = pConv->DataConvert(DBTYPE_NUMERIC, DBTYPE_R8,  (ULONG)sizeof(DB_NUMERIC), &len, (void*)&test.m_cur, (void*)&result, sizeof(result), DBSTATUS_S_OK, &status, test.m_cur.precision, test.m_cur.scale, DBDATACONVERT_DEFAULT);
UINT n;
int i = 0;
while (n = pConv->Release()) // this strange looking code seems the only way to make Release() return 0
{
    i++;
}
//n = pConv->Release(); // for testing purpose only, an extra release does not crash the program.


texts: Javascript browser charset rendering detection

texts:
I am attempting to polyfill the broken character encoding system in javascript. For example, characters such as , have a length of 2 and are treated as 2 separate characters in regular expressions when they should have a length of 1 and be treated as a single character in regular expressions. This may not seem important, but I don't want to have a programming nightmare when I deploy my site multilingually with asian and african languages. I am attempting to polyfill the whole thing, but since I can't find any articles, this is the best I can do. I am attempting to detect the encoding based on the size of different characters since that is what I am, in essence, doing: polyfilling the size of the characters.

<script>
 // Charset Polyfiller
 let   charsettransfer = Object.create(null),
        maxUniChar = String.fromCodePoint(0x10ffff);
  let   needsPolyfill = true;

  if ('\xE2'.length === '\xE1'.length*2){
    charsettransfer.to = 'GB 18030';
    if ('\xE1'.length === 2){
      charsettransfer.from = 'ascii';
    } else if ('\xE1'.length === 1) {
      charsettransfer.from = 'UCS-16';
    }
  } else if ('\x7f'.length === 1 && '\x80'.length === 2){
    charsettransfer.from = 'ascii';
    charsettransfer.to = 'utf-7';
  } else if (maxUniChar.length === 4){
    charsettransfer.from = 'ascii';
    if ('\0'.length <= 1){
      charsettransfer.to = 'utf-8';
    } else if ('\u9999'.length === 3 && '\0'.length === 3){
      charsettransfer.to = 'utf-20';
    } else if ('\u9999'.length === 4) {
      charsettransfer.to = 'utf-32';
    } else {
      charsettransfer.to = 'utf-16';
    }
  } else if (maxUniChar.length === 3) {
    charsettransfer.from = 'ascii';
    charsettransfer.to = 'utf-24';
  // utf-24 is my own nickname for when a browser uses only the minimal
  // 24 bits for utf-32 (like python)
  } else if (maxUniChar.length === 2) {
    charsettransfer.from = 'ucs-16';
    charsettransfer.to = 'utf-16';
  } else if (maxUniChar.length === 1) {
    charsettransfer.from = 'ucs-32';
    charsettransfer.to = 'utf-32';
    needsPolyfill = false;
  }

 /*if ('\u9999'.length === 3){
  charsettransfer.from = 'ascii';
  charsettransfer.to = 'utf-8';
 } else if ('\0'.length === 4) {
  charsettransfer.to = 'utf-32';
    charsettransfer.from = 'ascii';
 } else if ('\0'.length === 3) {
  charsettransfer.to = 'utf-24';
  charsettransfer.from = 'ascii';
 } else if ('\0'.length === 2) {
  charsettransfer.to = 'utf-16';
  // utf-24 is my own nickname for when a browser uses only the minimal
  // 24 bits for utf-32 (like python)
  charsettransfer.from = 'ascii';
 } else if ('\uD83D\uDE12'.length === 1){
  charsettransfer.from = 'ucs-32';
  charsettransfer.to = 'utf-32';
 }*/

  document.write('Your browser is attempting to render ' + charsettransfer.to
       + ' in ' + charsettransfer.from + '.\<br /> Your browser needing the polyfill is ' + needsPolyfill + '.');
</script>

How did I do? Am I on the right track? Are there any things I could add? Any improvements I could make? Any bugs that should be fixed? (sorry if i'm ranting, but i'm really concerned about this segment of code because LOTS of days of work are gonna depend on it, and I can't seem to find any helpful articles reguarding it).


texts: Fitting multiple images in a given width

texts:
I was looking for a function which would take the overall width, max height, min height parameters as the input and fit multiple images in the given overall width adjusting their width.

For an example in this page, all the images (in the same row) should get auto-adjusted to the same height, keeping their original aspect ratio with JavaScript changing their widths.

Is there a simple and better way to do this?

The solved example page is here.

$(function(){

//var pics;

var pic1 = {height:"10", width:"20", ap:1.374, rh:0};
var pics = [pic1];

//pics.push(pic3);

//$('#test').html(pics[2].height);

$('#some').imagesLoaded(function() {

$('#test').html('test ');
$('#some img').each(function(index) {
  //setting const height
  $(this).height(150);
  var apic = {height:$(this).height() , width: $(this).width() ,ap: $(this).width() / $(this).height() , rh:0};
  pics.push(apic);

});

$('#test').append(pics.length+ '
');

for (var j=1; j <pics.length;j++) {

  $('#test').append(pics[j].width  + ' ' + pics[j].ap + '
');
}
$('#test').append('Calculating width ' + '
');
var set = [0];

for (var j=1; j <pics.length;j++) {

  var t = 0;
  var c = j
  do {
    t = t+ pics[c].width;
    $('#test').append(c + ' ' + t+ '
');
    c=c+1;
  }while (t < 645 && c<pics.length);
  c=c-1;
  if(t>645) {
    c = c -1;
  }

  set.push(c);
  j = c;

}
$('#test').append('Sets are:
');
var v = 1;
var st = 0;
for (p = 1; p<set.length; p++) {

  $('#test').append(set[p] + ' ');
  st = v;
  v = set[p];
  $('#test').append(p + ': ');

  var tot = 0;
  var inc = 0;
  while(tot < 645 ) {
    var tot1=0;
    for(var g = st; g<v+1; g ++) {
      tot1 =tot1+ (pics[g].ap * (pics[g].height+inc));

    }
    tot=tot1;
    inc = inc+1;
  }
  for(var g = st; g<v+1; g ++) {
      $('#some img').eq(g-1).height ( 150 + inc);
  }

  $('#test').append( '
');
  v = v+1;

}

$('#test').append('
');

/*
var tot = 0
var wid;
var wid1;
var inc=0;
var r = 1;
for (r =1; r<pics.length-1; r++) {
  inc = 0;
  tot = 0;
while ( tot < 645) {

  wid = pics[r].ap * (pics[r].height+inc);
  wid1 = pics[r+1].ap * (pics[r+1].height+inc);

  tot = wid + wid1;
  inc = inc+ 1;
}

$('#test').append('Total ' + inc +' '+ wid  + ' ' + wid1 + '
');
$('#some img').eq(r-1).height ( 150 + inc);
$('#some img').eq(r).height ( 150 + inc);
  r=r+1;
  */
}
  );

});


texts: Delaying a function call for 30 seconds using sleep() or checking the time in a loop

texts:
I need a way to delay a function call by 30 seconds on a machine that runs on electric power, not battery (if it matters). I have heard from my colleague not to use sleep, but this post suggests it:

sleep(30) // sleep for 30 sec

Reasons invoked for not using sleep include:

I will violate Single Responsibility Principle.
Abstraction leak, etc.

Not sure why though; I feel it's good because it reduces CPU load and executes important tasks. In the below approach I am trying to just avoid sleep because I am asked not to use it though I am curious to know what a better (best?) approach would be?

void waiting (unsigned int secs)
{
        unsigned int retTime = time(0) + secs;   // Get finishing time.
        while (time(0) < retTime);               // Loop until it arrives.
}


texts: Checking if three numbers sum to a given number

texts:
I'm working on the following interview practice problem, and got the following solution, which runs in worst case n! time (best case constant), and I'm trying to optimize it.

Can you offer any suggestions to go about this? I think it should be able to be reduced down to quadratic, if not nlogn, but I'm not entirely sure of an approach to achieve this.

/** Write a function to check if any three numbers in an array sum to a given number, X */
public class SumToNum {

  public static void main(String[] args) {
  int[] test = {1,8,2,3,11,4};
  System.out.println(threeSumTo(test, 6)); //Returns true

  }
  public static boolean threeSumTo(int[] array, int x) {
      List<Integer> items = new LinkedList<>();
      for (int i : array) { items.add(i); }
      return threeSumTo(items, x, 3);
  }
  public static boolean threeSumTo(List<Integer> items,int numRemaining, int count) {
      if (numRemaining == 0) {
          return true;
      }
      if (count == 0){
          return false;
      }
      for (int i = 0; i < items.size(); i++) {
          int curr = items.remove(i);
          if (curr <= numRemaining) {
              boolean result = threeSumTo(items, numRemaining - curr, count - 1);
              if (result) {
                  return result;
              }
          }
          items.add(i, curr);
      }
      return false;
  }

}

EDIT: Ok, here's a solution based on Rafa's advice, using some more clever deduction. Basically, I'm just reducing it down to two integers that sum up to a number, and doing this for every number in the array.  It looks like it works as intended, but in N2 worst case time this time.It also assumes the array is sorted, otherwise, as answered below, the problem is NP-Complete. Thanks for the help.

public static boolean threeSumTo(int[] array, int x) {
    for (int i = 0; i < array.length; i++) {
        boolean result = twoSumTo(array, x - array[i], i);
        if (result) {
            return result;
        }
    }
    return false;
}

private static boolean twoSumTo(int[] array, int x, int low) {
    int high = array.length - 1;
    while (low < high) {
        if (array[low] + array[high] == x) {
            return true;
        }
        if (array[low] + array[high] > x) {
            high--;
        } else {
            low++;
        }
    }
    return false;
}


texts: Check if all leaves are at same level in a binary tree

texts:
I have written this code for checking whether all leaves are in the same level or not, in a binary tree. Any suggestion or improvement is appreciated.

import java.util.LinkedList;
import java.util.Queue;

public class Methods {

    //* ---- Method for check whether all leaves are in the same level or not --- *
    public static boolean leavesIn1Level(Node root){

        if(root == null){
            return false;
        }
        if(root.left == null && root.right == null){
            return true;
        }
        Queue<Node> q = new LinkedList<Node>();
        q.add(root);

        int levelNumber = 0;
        int height = height(root);

        while(true){

            int nodeCount = q.size();
            if(nodeCount == 0){
                break;
            }
            while(nodeCount > 0){

                Node current = q.remove();
                nodeCount--;

                if(current.left == null && current.right == null){
                    if(height != levelNumber){
                        return false;
                    }else{
                        return true;
                    }
                }
                if(current.left != null){
                    q.add(current.left);
                }
                if(current.right != null){
                    q.add(current.right);
                }
            }
            levelNumber++;
        }
        return false;
    }

    //* ---- Method for finding height of a binary tree ---- *
    public static int height(Node root){

        if(root == null){
            return -1;

        }else{

            return Math.max(height(root.left), height(root.right))+1;
        }
    }

    public static void main(String[] args) {

        Node root1 = new Node(8);                      //              8
        root1.left = new Node(9);                      //             / \
        root1.right = new Node(5);                     //            9   5
        root1.left.left = new Node(4);                 //           /   /
        root1.right.left = new Node(1);                //          4   1
        root1.right.left.left = new Node(3);           //             /
        root1.right.left.left.left = new Node(2);      //            3
                                                       //           /
                                                       //          2

        Node root2 = new Node(1);                      //              1
        root2.left = new Node(2);                      //             /  \
        root2.right = new Node(3);                     //           2     3
        root2.left.left = new Node(4);                 //          / \   /
        root2.left.right = new Node(5);                //        4    5 6
        root2.right.left = new Node(6);

        System.out.println(leavesIn1Level(root1));
        System.out.println(leavesIn1Level(root2));
   }
}

Node class:

public class Node {
    int data;
    Node left;
    Node right;
    public Node(int d){
        data = d;
        left = null;
        right = null;
    }
}

This code is different from:
Check if all leaves are at same level


texts:
As some of you might know I'm working my way through The C Programming Language as recommended by the "The Definitive C Book Guide and List" on StackOverflow.

I just finished my version of squeeze(s1, s2), a function to remove all occurrences of s2 in s1 and was hoping to get some feedback on my solutions.

This exercise is part of the second chapter (ex 2.4) so we haven't really gone through pointers and de-referencing yet. So basically all experience I have with the language is with using basic and primitive data types and the previous feedback I've received here!

All sort of feedback would be greatly appreciated; syntactical changes, algorithmic shortcomings etc. Just keep in mind that I just recently started out with the language!

Here is the code:

/*
    Exercise 2.4
    squeeze (s1, s2): Remove all characters of s2 in s1.
    INPUT : s1.length >= s2 > 0.
    OUTPUT: The rest of s1 after deleting all occurances of letters in s2.
*/

#include <stdio.h>

void squeeze (char s1[], const char *s2);  /* Returns (by-ref) the resulting string s1 after removing all occurences of s2. */
int toUpper(char c);                       /* Returns the numerical representation of a hexadecimal digit. */
int contains(char toCheck, const char *toRemove); /* Function to see if toRemove contains toCheck. */

int main () {
    char s1[] = "I am a test.\0";
    const char *s2 = "AE\0";
    printf("Before manipulation: %s\n", s1);
    squeeze(s1, s2);
    printf("After manipulation:  %s", s1);
}

/*
    Returns the (by-ref) resulting string s1 after removing all occurences
    of letters in s2.
*/

void squeeze (char s1[], const char *s2) {
    int index, left_shift;

    for (index = 0, left_shift = 0; s1[index] != '\0'; index++) {
        if (contains(s1[index], s2))
            continue;
        s1[left_shift] = s1[index];
        left_shift++;
    }
    s1[left_shift] = '\0';
}
/*
    Returns the upper-case representation of char c.
*/

int toUpper (char c) {
    if (c >= 'a' && c <= 'z')
        return c - 32;
    else
        return c;
}

/*
    Returns an indicator (integer) of if
    the string toRemove contains toCheck.
*/
int contains(char toCheck, const char *toRemove) {
    int index = 0, c = 0;

    while (toRemove[index] != '\0') {
        if ((c = toUpper(toCheck)) == toRemove[index]){
            return 1;
        }
        index++;
    }
    return 0;
}


texts: scoped_ptr for C++/CLI (ensure managed object properly frees owned native object)

texts:
Motivating SO question: Is there a C++/CLI smart pointer project (e.g. scoped_ptr)?

I'm interested in any reviewer comments, and especially identified bugs or inconsistencies with the native scoped_ptr template after which this code is patterned.

#pragma once

/** @file clr_scoped_ptr.h
 ** @author R Benjamin Voigt (richardvoigt@gmail.com)
 **
 ** Rights reserved.  This code is not public domain.
 **
 ** Licensed under CC BY-SA 3.0             http://creativecommons.org/licenses/by-sa/3.0/
 **             or Lesser GPL 3 or later    http://www.gnu.org/copyleft/lesser.html
 ** with the following restrictions (per GPL section 7):
 **  - all warranties are disclaimed, and if this is prohibited by law, your sole remedy shall be recovery of the price you paid to receive the code
 **  - derived works must not remove this license notice or author attribution
 **  - modifications must not be represented as the work of the original author
 **  - attribution is required in the "about" or "--version" display of any work linked hereto, or wherever copyright notices are displayed by the composite work
 **/

struct safe_bool { private: safe_bool(); };

/** \brief C++/CLI analogue to boost::scoped_ptr, also similar to std::unique_ptr, for management of the lifetime of an unmanaged class instance by a managed object
 **/
template<typename T>
public ref class clr_scoped_ptr
{
    T* m_native_ptr;

    // declare copy-constructors and assignment operators to prevent double-free
    clr_scoped_ptr( clr_scoped_ptr<T>% ) /* = delete */ { throw gcnew System::InvalidOperationException("clr_scoped_ptr is non-copyable"); }

    template<typename U>
    clr_scoped_ptr( clr_scoped_ptr<U>% ) { throw gcnew System::InvalidOperationException("clr_scoped_ptr is non-copyable"); }

    clr_scoped_ptr% operator=( clr_scoped_ptr<T>% ) /* = delete */ { throw gcnew System::InvalidOperationException("clr_scoped_ptr is non-copyable"); }

    template<typename U>
    clr_scoped_ptr% operator=( clr_scoped_ptr<U>% ) { throw gcnew System::InvalidOperationException("clr_scoped_ptr is non-copyable"); }

public:
    clr_scoped_ptr( void ) : m_native_ptr(nullptr) {}
    explicit clr_scoped_ptr( T* ptr ) : m_native_ptr(ptr) {}
    !clr_scoped_ptr( void ) { reset(); }
    ~clr_scoped_ptr( void ) { clr_scoped_ptr::!clr_scoped_ptr(); }

    template<typename U>
    clr_scoped_ptr( U ptr ) : m_native_ptr(ptr) {}

    void reset( T* ptr ) { delete m_native_ptr; m_native_ptr = ptr; }
    void reset( void ) { reset(nullptr); }

    clr_scoped_ptr% operator=( T* ptr ) { reset(ptr); }

    template<typename U>
    clr_scoped_ptr% operator=( U ptr ) { reset(ptr); }

    operator struct safe_bool*() { return reinterpret_cast<struct safe_bool*>(m_native_ptr); }

    void swap( clr_scoped_ptr<T>% other )
    {
        using std::swap;
        swap(m_native_ptr, other.m_native_ptr);
    }

    T* release( void ) { T* retval = m_native_ptr; m_native_ptr = nullptr; return retval; }
    T* get( void ) { return m_native_ptr; }

    static T* operator->( clr_scoped_ptr<T>% sptr ) { return sptr.get(); }
    static T& operator*( clr_scoped_ptr<T>% sptr ) { return *sptr.get(); }
};

template<typename T>
inline void swap( clr_scoped_ptr<T>% left, clr_scoped_ptr<T>% right )
{
    left.swap(right);
}


texts: Using Scanner input to do some basic math and format an output

texts:
Write a static method named plusScores that accepts as a parameter a
  Scanner containing a series of lines that represent student records.
  Each student record takes up two lines of input. The first line has
  the student's name and the second line has a series of plus and minus
  characters. Below is a sample input:

Kane, Erica
--+-+
Chandler, Adam
++-+
Martin, Jake
+++++++
Dillon, Amanda
++-++-+-

  The number of plus/minus characters will vary, but you may assume that
  at least one such character appears and that no other
  characters appear on the second line of each pair. For each student
  you should produce a line of output withthe student's name followed by
  a colon followed by the percent of plus characters. For example, if
  the input above is stored in a Scanner called input, the call of
  plusScores(input); should produce the following output:

Kane, Erica: 40.0% plus
Chandler, Adam: 75.0% plus
Martin, Jake: 100.0% plus
Dillon, Amanda: 62.5% plus

I'm looking for alternative ways of solving this problem, and of course any potential bugs or pitfalls my code may have. If you have something interesting to share, please do! I'm new to programming and am eager to see other ways of accomplishing a problem such as this one. Here's my code:

public static void plusScores(Scanner sc) {
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        if (!line.startsWith("+") && !line.startsWith("-")) {
            System.out.print(line);
        } else {

            int plus = 0;
            int minus = 0;

            for (char ch : line.toCharArray()) {
                if (ch == '+') {
                    plus++;
                } else {
                    minus++;
                }
            }

            float percentPlus = ((float) (plus) / (plus + minus)) * 100;
            System.out.format(": %.1f%% plus\n", percentPlus);
        }
    }
}


texts: Settings Model to read multiple settings files and writes to one

texts:
I am writing a Model to read, write and store settings.
I think my code is pretty good, but I am not 100% sure.
Any advice on how I could possibly improve it is welcome.

import ntpath

import yaml

class Settings:
    def __init__(self, paths=None, default_path=None):
        """Load, write and store settings

        This model manages setting files (YAML).

        Keyword Arguments:
            paths {list or None} -- list of full or relative
                                    paths with filenames (default: {None})
            default_path {str or None} -- path to user settings, read last
                                          and default for writing
                                          (default: {None})
        """
        paths = paths or []
        # Make sure paths are unique and sorted by file name
        self.paths = sorted(set(paths), key=lambda p: ntpath.basename(p))
        # Remove default_path from paths (look at next comment)
        try:
            self.paths.remove(default_path)
        except ValueError:
            pass
        # Readd default_path at the end to make sure it's loaded last
        if default_path is not None:
            self.paths.append(default_path)
        # Set remaining attributes
        self.default_path = default_path
        self.settings = {}

        # Load files
        self.reload()

    def reload(self):
        """Reload files into buffer

        Reloads the files specified in self.paths
        and writes them into the buffer.
        """
        # Clear settings to ensure no unwanted leftovers
        self.settings.clear()
        # Load every path (sorted by filename, self.default_path last)
        for path in self.paths:
            with open(path, 'r') as f:
                content = f.read()
            self.settings.update(yaml.load(content) or {})

    def write(self, key, value, path=None):
        """Write into file

        Writes key and value into the file specified
        by path (or self.default_path if None)

        Arguments:
            key {immutable} -- key to use (valid YAML key)
            value {ANY} -- value to save

        Keyword Arguments:
            path {str} -- path to save file (default: {None})
        """
        path = path or self.default_path
        assert path is not None

        with open(path, 'r') as f:
            settings = yaml.load(f.read()) or {}

        settings[key] = value
        self.settings[key] = value

        with open(path, 'w') as f:
            f.write(yaml.dump(settings, default_flow_style=False))


texts: Sum All Odd Fibonacci Numbers, freecodecamp challenges

texts:
recently i take a challenge on freecodecamp to solve given problem.
Sum All Odd Fibonacci Numbers
here is my code, any suggestion, code review, help appreciate

Sum All Odd Fibonacci Numbers of number <input type='number' id='val' min="0"/>
<button onclick="getOutput()">get Result</button>


texts: Where should I put code which calculates stats which will be sent via mail

texts:
I want to send mail which will have day to day report. I have setup action mailer like this

class ReportMailer < ApplicationMailer
  ...

  def send_stats(hash)
    @emails = ["my@email.com"]
    @stat = hash
    mail(:to => @emails.join(","), :subject => "Daily Count of tasks")
  end
end

The send_stats method will need parameter hash which should be passed. This hash will have different counts which are not limited to one model. So I came with an idea of report module.

module Report
  def self.email_stats(date)
    hash = {}
    hash["TaskCount"] = Task.where(adate: date).count
    hash["ProfileCount"] = Profile.where(ad_date: date).count
    ReportMailer.delay.send_stats(hash)
  end
end

Is this a right approach? Does anyone have better idea than this?


texts:
This is a simple implementation of vector in C++. Please offer your reviews to improve the code.

#ifndef VECTOR_HPP
#define VECTOR_HPP

template <typename T> class vector{
    int size;//size allocated on the memory
    int index;//current number of elements
    T* arr;
    void resize(){
        T* temp = new T[size];
        for (int i = 0; i <index ; ++i) {
            temp[i] = arr[i];
        }
        delete[] arr;

        T* arr = new T[size*2];
        for (int i = 0; i < index ; ++i) {
           arr[i] = temp[i];
        }
        size = size*2;
        delete[] temp;

    }
public:
    vector(){
        size = 50;
        index = 0;
        T* arr = new T[size];
    }
    vector(int sz){
        size = sz;
        index = 0;
        T* arr = new T[size];

    }
    ~vector(){
        delete[] arr;
    }

    typedef T* iterator;

    iterator begin(){
        return arr;
    }

    iterator end(){
        return arr + index;
    }

    T* front(){
        return arr[0];
    }

    T* back(){
        return arr[index];
    }
    void push_back(const T& t){
        if((size - index) == 1){
            resize();

        }
        arr[index+1] = t;
        index++;

    }
    void pop_back(){
        index--;
    }

    void insert(iterator pos, const T& t){
        if((size -index) < 1) resize();
        int npos = pos - arr;
        for (int i = index; i > npos ; i--) {
            arr[i+1] = arr[i];
        }
        arr[npos] = t;
        index++;

    }

    void erase(iterator pos){
        int npos = arr - pos;
        if((size - index) < 1) resize();
        for (int i = npos; i <index-1 ; ++i) {
            arr[i] = arr[i+1];
        }
        index--;

    }

    T& operator[](int){

    }

    int length(){
        return index;
    }
    bool empty(){
        return index == 0;
    }

};

#endif //VECTOR_HPP


texts: Read date from a file and rename two files using the date

texts:
Problem
I have image files that are RAW data and have the extension .NEF Whatever edits I make to these files are stored in what is called a sidecar file with the extension .xmp
Given there are many photos and the photo numbering in the camera can only go up to 9999, there is a possibility that I may get duplicate filenames in the same folder over time.
Objective
Given the image files and the sidecar files must have the same base name to remain associated, I'd like to append the date the photo was taken to the base name for both files.
The original date can be found within the .xmp file on a line beginning with a specific string.
I want to

find all image files that have a sidecar file
Get the image date from within the sidecar file
Rename both the image file and sidecar file with the date appended at the end of the base name

Code
I'm pretty sure I'm not importing any namespace except System.IO, so this should all be the .NET way, not any VB6.
Option Explicit On
Option Strict On
Option Infer On
Option Compare Text
Imports System.IO
Module PhotoRename

    Sub Main()
        Const DIR_PATH As String = "C:\Temp\"
        Const IMAGE_EXTENSION As String = ".NEF"
        Const SIDECAR_EXTENSION As String = ".xmp"
        GetFilesInDirectory(DIR_PATH, IMAGE_EXTENSION, SIDECAR_EXTENSION)
    End Sub

    Private Sub GetFilesInDirectory(ByVal path As String, ByVal photoExtension As String, ByVal sidecarExtension As String)
        Const EXTENSION_LENGTH As Integer = 4
        Dim arrayOfFiles() As String = Directory.GetFiles(path, "*" & photoExtension)
        Dim baseName As String
        Dim photoFileName As String
        Dim sidecarFileName As String
        Dim originalDate As String
        For arrayIndex As Integer = 0 To arrayOfFiles.Length - 1
            photoFileName = arrayOfFiles(arrayIndex)
            baseName = photoFileName.Substring(0, photoFileName.Length - EXTENSION_LENGTH)
            sidecarFileName = baseName & sidecarExtension
            If File.Exists(sidecarFileName) Then
                originalDate = GetFileDate(sidecarFileName)
                RenamePhotoFiles(baseName, originalDate, photoExtension, sidecarExtension)
            End If
        Next
    End Sub

    Private Function GetFileDate(ByVal sidecarFile As String) As String
        Const LINE_START As String = "   exif:DateTimeOriginal="
        Const DATE_STRING_LENGTH As Integer = 10
        Const CHAR_TO_REMOVE As String = "-"
        Dim lines = File.ReadAllLines(sidecarFile)
        Dim targetData As String = Nothing
        For i As Integer = 0 To lines.Length - 1
            If lines(i).StartsWith(LINE_START) Then
                targetData = lines(i)
                Exit For
            End If
        Next
        targetData = targetData.Substring(LINE_START.Length + 1, DATE_STRING_LENGTH)
        GetFileDate = targetData.Replace(CHAR_TO_REMOVE, "")
    End Function

    Private Sub RenamePhotoFiles(ByVal oldName As String, ByVal fileDate As String, ByVal photoExtension As String, ByVal sidecarExtension As String)
        Const FILE_EXTENDER As String = "_"
        Dim newName As String = oldName & FILE_EXTENDER & fileDate
        File.Move(oldName & photoExtension, newName & photoExtension)
        File.Move(oldName & sidecarExtension, newName & sidecarExtension)
    End Sub

End Module


texts:
I am solving https://codefights.com/challenge/Qjts7cukDvYpDW4Bc/main

My approach is simple.
Get all subsequences by combination.
Simple loop over combinations.
Find minimum.

closestSequence2 <- function(a, b) {
LA = length(a);
LB = length(b);
minimum = Inf;

indexes = utils::combn(1:LB, LA);

for(i in 1:ncol(indexes))
{
 suma = (sum(abs(b[indexes[,i]]-a)));
 if(suma < minimum )
 {
   minimum = suma;
 }
}
return(minimum);
}

I am not sure but I think it is failing due to the time because it pass the sample tests. Are there some easy tricks how to speed this up ot do I need different approach?


texts:
I have created this memory writer helper to ease the write into memory process and I want your suggestions regarding it. I am very new to C++ but have 6 years knowledge of .NET languages like VB and C#.

#include <wtypes.h>

class MemoryWriter {
private:
    USHORT _currentIndex;
    LPVOID _targetAddress;
    template<typename T>
    static void editMemory(DWORD address, T data)
    {
        DWORD oldProtection;
        VirtualProtect((LPVOID)address, sizeof(T), PAGE_EXECUTE_READWRITE, &oldProtection);
        *((T*)address) = data;
        VirtualProtect((LPVOID)address, sizeof(T), PAGE_EXECUTE_READWRITE, NULL);
    }
public:
    MemoryWriter(DWORD address) {
        _currentIndex = 0;
        _targetAddress = (LPVOID)address;
    }
    template<typename T>
    void write(T data)
    {
        editMemory<T>(((DWORD)_targetAddress + _currentIndex), data);
        _currentIndex += sizeof(T);
    }
    template<typename T>
    void write(LPVOID address, T data)
    {
        editMemory<T>((DWORD)address, data);
        _currentIndex = (DWORD)address;
    }
    void reset(LPVOID newAddress = NULL)
    {
        _currentIndex = 0;

        if (newAddress)
            _targetAddress = newAddress;
    }
};


texts: Combine multiple if statements with multiple properties

texts:
I'm looking into using my loop to combine and narrow down this piece of code into maybe a switch statement or other methods, how would I be able to achieve that? This is what I have so far which has worked for me but I also have other items[i].ApplicationType such as 'OneDrive', 'Teams', etc..

for(i = 0; i < items.length; i++)
{
    if(items[i].ComputerType == 'Windows' && items[i].RequestType == 'Single User' && items[i].ApplicationType == 'OneDrive')
    {
        ODwindows += 1;
    }
    else if(items[i].ComputerType == 'Windows' && items[i].RequestType == 'Single User' && items[i].ApplicationType == 'Teams')
    {
        Teamswindows += 1;
    }
    else if(items[i].ComputerType == 'Mac' && items[i].RequestType == 'Single User' && items[i].ApplicationType == 'OneDrive')
    {
        ODmac += 1;
    }
    else if(items[i].ComputerType == 'Mac' && items[i].RequestType == 'Single User' && items[i].ApplicationType == 'Teams')
    {
        Teamsmac += 1;
    }
    else if(items[i].ComputerType == 'Both' && items[i].RequestType == 'Team' && items[i].ApplicationType == 'OneDrive')
    {
        ODboth += 1;
    }
    else if(items[i].ComputerType == 'Both' && items[i].RequestType == 'Team' && items[i].ApplicationType == 'Teams')
    {
        Teamsboth += 1;
    }
}


texts:
I'm struggling if this is the correct way to implement an MVC-like pattern for small websites.
I have separate controllers and models, my main concern is the view part, did I understand it correctly?

Folders:

app/
 - controllers/
   - homepage.php

 - models/
   - homepage.php

 - template.php

App/Template.php

namespace App;

class Template {

    public static $templateFolder = __DIR__ . '/../html/templates/';

    public static $defaultParts = [
        'header' => 'parts/header',
        'footer' => 'parts/footer'
    ];

    public static $headerDefaults = [
        'meta_title' => '-'
    ];

    public static function render( $templateName, $data = [] ) {

        $content = !empty( $data['content'] ) ? $data['content'] : [];
        $objects = !empty( $data['objects'] ) ? $data['objects'] : [];
        $pageName = !empty( $data['name'] ) ? $data['name'] : null;

        $header = self::show($parts['header'], $pageName, !empty( $content['header'] ) ? $content['header'] : self::$headerDefaults);
        $footer = self::show($parts['footer'], $pageName, !empty( $content['footer'] ) ? $content['footer'] : []);
        $body = self::show($templateName, $pageName, !empty( $content['body'] ) ? $content['body'] : [], $objects);

        return $header.$body.$footer;
    }

    public static function show( $templateName, $pageName, $data = [], $objects = [] ) {
        if ( file_exists( self::$templateFolder . $templateName.'.tpl' ) ) {
            if ( !empty($objects) ) extract( $objects, EXTR_SKIP );
            ob_start();
            include self::$templateFolder . $templateName . '.tpl';
            $content = ob_get_contents();
            ob_end_clean();
            return $content;
        }
        return self::notFound();
    }

    public static function notFound( $full = false ) {
        if ( $full ) return self::render('not_found', [ 'content' => [ 'header' => [ 'meta_title' => 'Страница не найдена' ] ] ]);
        ob_start();
        include self::$templateFolder . 'not_found.tpl';
        $content = ob_get_contents();
        ob_end_clean();
        return $content;
    }
}

App/Controllers/Homepage.php

namespace Controllers;

class Homepage {

    public $templates = [
        'default' => 'public/homepage'
    ];

    public function response($data) {
        if (!empty($data['method']) && $data['method'] == 'GET') {
            return $this->getResponse($data);
        } else {
            return $this->postResponse($data);
        }
        return $data;
    }

    public function getResponse($data) {
        return \App\Template::render($this->templates['default'], [
            'name' => 'homepage',
            'content' => [
                'body' => \Models\Hompage::getInstance()->mainpage(),
                'footer' => [],
                'header' => [
                    'page_class' => 'main-page',
                    'styles' => ['/css/mainpage.css']
                ],
            ]
        ]);
    }

    public function postResponse($data) {
        if (!empty($data['name'])) {
            $name = $data['name'];
            if (method_exists($this, $name)) return $this->$name($data);
        }
        return 'undefined command';
    }
}

App/Models/Homepage.php

namespace Models;

class Homepage extends \App\PDOWrap {

    static private $instance = null;

    public function __construct() {
        parent::__construct();
    }

    static public function getInstance() {
        if ( self::$instance == null ) self::$instance = new self();
        return self::$instance;
    }

    public function all() {
        $this->query('SELECT * FROM table');
        return $this->resultset();
    }

    public function mainpage() {
        $this->query('SELECT * FROM table INNER JOIN tabl2 ...');
        return $this->resultset();
    }
}


texts: Plotting an input curve and its FFT using gnuplot in C++

texts:
I'm currently working on a project1 which will result in millions of FFTs being solved time and time again. I have a finished prototype in Python (using numpy, scipy, and the pyfftw3 package), but there are significant bottlenecks in calculation speed. I have been writing a GPU version using arrayfire, but there's still a large amount of number crunching which can't be done in parallel. I'm hoping that translating the project to C++, either the entire thing or just the compute-intensive parts, will provide an extra boost over Python where the GPU isn't appropriate.

As a starting point, I have written a very basic C++ script which defines a Gaussian curve, takes the FFT using the FFTW3 library, and plots the input curve with its FFT using gnuplot. As this is my first script in C++ (neglecting 'hello world') I'd like to make sure I'm not wandering severely off track when it comes to optimizing efficiency and speed. I haven't benchmarked this yet, but was hoping that someone with more experience in using these libraries and the language could scan over it and point out any howlers.

The code:

#include "gnuplot-iostream.h"
#include <iostream>
#include <vector>
#include <cmath>
#include <fftw3.h>
#include <complex>

typedef std::complex<double> doubleComp;

int main()
{
    Gnuplot gp;

    doubleComp i;
    i = -1;
    i = sqrt(i);

    int gridOrder = 9;
    int nPoints = pow(2, gridOrder);
    int halfPoints = pow(2, gridOrder-1);
    float tau = 18;
    float inTemp, outTemp;

    fftw_complex in[nPoints], out[nPoints], pArr1[nPoints], pArr2[nPoints];
    fftw_plan p;

    for (int idx=0; idx<nPoints; idx++) {
        in[idx][0] = exp(-pow((idx-halfPoints)/tau, 2));
        in[idx][1] = 0;
    }

    p = fftw_plan_dft_1d(nPoints, pArr1, pArr2, FFTW_FORWARD, FFTW_MEASURE);
    fftw_execute_dft(p, in, out);

    for (int idx=0; idx<nPoints; idx++) {
        out[idx][0] *= (1/double(nPoints));
        out[idx][1] *= (1/double(nPoints));
    }

    std::vector<std::pair<double, double> >inPlot;
    std::vector<std::pair<double, double> >outPlot;
    for (int idx=0; idx<nPoints; idx++) {
        inTemp = std::abs(in[idx][0] + i*in[idx][1]);

        // Deal with fftshifts needed for visuals:
        if (idx > halfPoints)
            outTemp = std::abs(out[idx-halfPoints][0] +
                                i*out[idx-halfPoints][1]);
        if (idx < halfPoints)
            outTemp = std::abs(out[idx+halfPoints][0] +
                                i*out[idx+halfPoints][1]);

        inPlot.push_back(std::make_pair(idx-halfPoints, inTemp));
        outPlot.push_back(std::make_pair(idx-halfPoints, outTemp));
    }

    gp << "set xlabel 'Grid points' font 'Helvetica, 12'\n" <<
        "set ylabel 'Intensity' font 'Helvetica, 12'" << std::endl;
    gp << "set tics font 'Helvetica, 10'" << std::endl;
    gp << "set title 'Gaussian pulse example' font 'Helvetica, 13'" << std::endl;
    gp << "set grid xtics lt 0 lw 1 lc 'gray'\n" <<
        "set grid ytics lt 0 lw 2 lc 'gray'" << std::endl;

    gp << "set term wxt '0'" << std::endl;
    gp << "plot '-' lt 1 lw 2 linecolor 'blue' with line title 'Time domain'\n";
    gp.send1d(inPlot);

    gp << "set term wxt '1'" << std::endl;
    gp << "plot '-' lt 11 lw 2 with line title"
        "'Spectral domain'\n";
    gp.send1d(outPlot);

    fftw_destroy_plan(p);

    return 0;
}

To compile (Ubuntu 16.04):

g++ -O3 GaussianPulseDefinition.cpp -o GaussianPulseDefinition -lboost_system -lboost_iostreams -lboost_filesystem -lfftw3 -lm

1 For those who like to know the application: The project is basically a coupled PDE solver (with Qt GUI) aimed at simulating the nonlinear dynamics of optical pulse propagation in optical fibre, fibre laser systems, optical amplifiers, etc.


texts: Building XML by enumerating through array & hashes

texts:
data =
[ { 'name' => 'category1',
    'subCategory' => [ {'name' => 'subCategory1',
                        'product' => [ {'name' => 'prodcutName1',
                                        'desc' => 'desc1'},
                                       {'name' => 'prodcutName2',
                                        'desc' => 'desc2'}]
                        } ]

  },
  {
    #category2 ...and so on
  }
]

Just recently finished a small project with Ruby. I used the above array of hashes to produce a XML.

I think my solution is quite messy nesting loops and builder tags. Can anyone help me out with a more elegant approach?

builder = Nokogiri::XML::Builder.new { |xml|
data.each { |category| # go through every category in the data array
    xml.category {
        xml.name category['name']
        category['subCategory'].each { |subCategory| # go through each subCategory in the category
            xml.subCategory {
                xml.name subCategory['name']
                subCategory['product'].each { |product| # go though each products and print their data
                    xml.name product['name']
                    xml.desc product['desc']
                }
            }
        }
    }
}

puts builder.to_xml


texts: Compare two directories, apply the changes, backup and restore

texts:
I’ve written a small utility tool capable of

backing up a directory,
restoring a backed up directory,
syncing two directories (copying missing or changed files from src to dst).

I’d love your feedback - any code smells, improvements, potential bugs, non-idiomatic approaches, etc., please let me know.

Here's how I backup and revert:

SHA1_DIGEST_REGEX = "[a-fA-F0-9]{40}"

def backup(directory, repo=REPO, backup_file=BACKUP):
    if not os.path.isdir(repo):
        os.makedirs(repo)
    key = str(time.time())
    sha = hashlib.sha1(key).hexdigest()
    archive_path = os.path.join(repo, sha)
    assert not os.path.isfile(archive_path)
    shutil.make_archive(archive_path, "zip", directory)
    backup_path = os.path.join(directory, backup_file)
    with open(backup_path, 'w') as b:
        b.write(sha)

def revert(directory, repo=REPO, backup_file=BACKUP):
    try:
        with open(os.path.join(directory, backup_file)) as b:
            sha = b.readline()
        if re.compile(SHA1_DIGEST_REGEX).match(sha):
            backup_path = os.path.join(repo, sha + ".zip")
            if not os.path.isfile(backup_path):
                raise IOError
            if os.listdir(directory):
                shutil.rmtree(directory)
            with zipfile.ZipFile(backup_path) as zf:
                zf.extractall(directory)
        else:
            print "Backup file corrupted."
    except IOError:
        print "Either no history is available or the backup files are missing."

Comparing two directories and applying the changes:

def find_diff(src, dst):
    if os.path.isdir(dst):
        diff = filecmp.dircmp(src, dst)
        return diff.left_only + diff.diff_files
    else:
        return [f for f in os.listdir(src)]

def apply_diff(src, dst, diff_list=None, auto_backup=True):
    if diff_list is None:
        diff_list = find_diff(src, dst)
    if diff_list:
        if auto_backup:
            backup(dst)
        for item in diff_list:
            src_item = os.path.join(src, item)
            dst_item = os.path.join(dst, item)
            if os.path.isdir(src_item):
                shutil.copytree(src_item, dst_item)
            else:
                shutil.copy(src_item, dst_item)

Sync (read multiple src dirs from a file):

def sync(directory, sync_file=SYNC):
    try:
        with open(os.path.join(directory, sync_file)) as s:
            src_list = s.read().splitlines()
        if src_list:
            for src in src_list:
                if not os.path.isdir(src):
                    raise IOError
            backup(directory)
            for src in src_list:
                apply_diff(src, directory, auto_backup=False)
        else:
            print "Sync file is empty."
    except IOError:
        print "Sync file is either missing or contains invalid sources."

I hope the code speaks for itself, but I'm happy to clarify things if they don't make sense.


texts: Create D lists of nodes where D is the depth of the binary tree

texts:
I have used a HashMap of ArrayLists to maintain the nodes at each depth.
Also i maintained a depth at each node in the binary tree by using a HashMap that stores . While traversing the tree in a breadth first manner, store the depth of each node(just one more than the depth of its parent) in the hashmap and add the node to the queue. And add each element from the queue to the ArrayList corresponding to its depth in the binary tree.

import java.util.Collection;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.LinkedList;
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}
public class Solution {

    public List<List<Integer>> levelOrder(TreeNode root)
    {
        List<List<Integer>> outputList = new ArrayList<List<Integer>>();
        if(root == null)
        {
            return outputList;
        }
        Queue<TreeNode> queue =  new LinkedList<TreeNode>();
        HashMap<Integer, ArrayList<Integer>> haMap = new HashMap<>();
        HashMap<TreeNode, Integer> nodeDepth = new HashMap<>();
        nodeDepth.put(root,0);
        queue.add(root);
        ArrayList<Integer>  tempList;
        while(!queue.isEmpty())
        {
            root = (TreeNode) queue.poll();
            if(root.left != null)
            {
                nodeDepth.put(root.left, nodeDepth.get(root)+1);
                queue.add(root.left);
            }
            if(root.right != null)
            {
                nodeDepth.put(root.right, nodeDepth.get(root)+1);
                queue.add(root.right);
            }
            if(haMap.containsKey(nodeDepth.get(root)))
            {
                tempList = haMap.get(nodeDepth.get(root));
                tempList.add(root.val);
                haMap.put(nodeDepth.get(root), tempList);
            }
            else
            {
                tempList = new ArrayList<>();
                tempList.add(root.val);
                haMap.put(nodeDepth.get(root), tempList);
            }
        }

        //List<List<Integer>> outputList = new ArrayList<List<Integer>>();

        outputList.addAll(haMap.values());

        return outputList;

    }

}


texts:
Are there any security vulnerabilities in this code?

class Session {
    private $id = array();
    private $data = array();
    private $name = 'session';

    public function __construct() {
        session_start();

        global $db;

        $this->id = isset($_COOKIE[$this->name]) ? $_COOKIE[$this->name] : $this->create_id();

        $id = $this->id;
        $ip = $_SERVER['REMOTE_ADDR'];
        $user_agent = $_SERVER['HTTP_USER_AGENT'];

        $check = $db->query("SELECT session_data FROM sessions WHERE session_id = ? AND user_ip = ? AND user_agent = ?");
        $db->execute(array($id, $ip, $user_agent));

        if ($db->row_count() != 0) {
            $this->data = $db->fetch_column();
            $this->data = unserialize($this->data);
        } else {
            $this->id = $this->create_id();

            $id = $this->id;
            $data = serialize($this->data);
            $time = time();
            $ip = $_SERVER['REMOTE_ADDR'];
            $user_agent = $_SERVER['HTTP_USER_AGENT'];
            $current_page = $_SERVER['REQUEST_URI'];

            $insertion_data = array(
                'session_id'                =>      $id,
                'session_data'              =>      $data,
                'session_last_activity'     =>      $time,
                'user_ip'                   =>      $ip,
                'user_agent'                =>      $user_agent,
                'user_current_page'         =>      $current_page
            );

            $db->insert('sessions', $insertion_data);
        }
    }

    public function end() {
        global $db;

        $this->garbage();
        $id = $this->id;
        $data = serialize($this->data);
        $time = time();
        $ip = $_SERVER['REMOTE_ADDR'];
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $current_page = $_SERVER['REQUEST_URI'];

        $name = $this->name;

        // note to self: create update function in db class
        $db->query("UPDATE sessions SET session_data = ?, session_last_activity = ?, user_ip = ?, user_agent = ?, user_current_page = ? WHERE session_id = ?");
        $db->execute(array($data, $time, $ip, $user_agent, $current_page, $id));

        @setcookie($name, $id, time()+3600, '/', '');
    }

    public function create_id() {
        return strtoupper(md5(rand(-1000000, 1000000)));
    }

    public function garbage() {
        global $db;

        $expiration = time() - '2419200';

        $db->query("DELETE FROM sessions WHERE session_last_activity < ?");
        return $db->execute(array($expiration));
    }

    public function regenerate() {
        global $db;

        $old_id = $this->id;
        $new_id = $this->create_id();

        $this->id = $new_id;

        $db->query("UPDATE sessions SET session_id = ? WHERE session_id = ?");
        return $db->execute(array($new_id, $old_id));
    }
}


texts:
The following script is being used to generate the status line in wmii. I'm curious if there are faster/more efficient ways to find the various info I'm grabbing. I'm also a relative newbie when it comes to zsh (and shell scripting in general) so I'd also suspect that there are better ways to process some of the data.

#!/bin/zsh
cpu_freq=$(grep "cpu MHz" /proc/cpuinfo | sed 's/[\t ]*//g; s/cpuMHz://g')

cpu0=$(echo "scale=2;" `echo $cpu_freq | head -n 1 | tail -n 1` / 1000 | bc)
cpu1=$(echo "scale=2;" `echo $cpu_freq | head -n 2 | tail -n 1` / 1000 | bc)
cpu2=$(echo "scale=2;" `echo $cpu_freq | head -n 3 | tail -n 1` / 1000 | bc)
cpu3=$(echo "scale=2;" `echo $cpu_freq | head -n 4 | tail -n 1` / 1000 | bc)

stat=$(mpstat | tail -n 1 | tr -s ' ')
usr=$(echo $stat | cut -d ' ' -f 4)
nice=$(echo $stat | cut -d ' ' -f 5)
sys=$(echo $stat | cut -d ' ' -f 6)
cpu=$(echo $usr + $nice + $sys | bc)

memline=$(free | head -n 2 | tail -n 1 | tr -s ' ')
cached=$(echo $memline | cut -d ' ' -f 7)
free=$(echo $memline | cut -d ' ' -f 4)
cachedfree=$(echo $cached + $free | bc)
mem=$(echo "scale=3;" $cachedfree / 1000000 | bc)

network=$(nmcli nm | sed 's/  */\;/g' | cut -d \; -f 2 | tail -n 1)

tun0=$(ifconfig tun0 2>/dev/null)
vpn=$(if [[ -n $tun0 ]]; then; echo "(vpn:" $(cat /tmp/current-vpn)")"; else; echo ""; fi)

battery=$(acpi -b | sed 's/Battery 0: //; s/ until charged//; s/ remaining//; s/Charging/C/; s/Discharging/D/; s/Full, //; s/Unknown, //')

load=$(uptime | sed 's/.*://; s/,//g')

date=$(date +%a\ %b\ %d\ %H:%M)

echo -n $vpn $network '||' $mem GB '||' $cpu% '('$cpu0 $cpu1 $cpu2 $cpu3') ||' $load '||' $date '||' $battery


texts: Looping through an Array of objects to find an ID in a sub array

texts:
I have an Array of objects, each which contain their own sub Tags Array, and I need to loop through and find a matching id.

Array: [
    Object {
        tags: [
            { tag_id: 1 },
            { tag_id: 2 }
        ]
        name: name_1
    },
    Object {
        tags: [
            { tag_id: 3 },
            { tag_id: 4 },
            { tag_id: 5 }
        ]
        name: name_2
    }
]

I have a click action when sends in 1 tag from the page to compare and I need to check it's ID to the id of all tags in the larger array.

This is what I have so far which works, but is there a cleaner, simpler more efficient way to do this? With a hashtable perhaps? If so, how?

// I get the large stored Array to compare too:
var tagObjects = TagFactory.retrieveTags();
var index = -1;
var temp_tags = [];

// tagObj is the single tag that is sent from the markup to check:
// Below is what I'm trying to find in the larger array:
console.log(tagObj.tag_id);

// Checking if the large Array has anything
if (tagObjects.length > 0) {

    // I go through and separate the smaller tag Arrays out:
    for (var i = 0; i < tagObjects.length; i++) {
        temp_tags.push(tagObjects[i].tags);
    }

    // Finally I try to find the ID inside of the temp_tags Array:
    for (var i = 0; i < temp_tags[0].length; i++) {
        if (tagObj.tag_id === temp_tags[0][i].tag_id) {
            console.log('found id YEAH!');
            index = 1;
        }
    }
}

// If I found the ID, it means I can remove the tag
if (index !== -1) {
    tagObj.selected = false;
    TagFactory.removeTags(tagObj);
}

// If I did not find the ID, it means I can add it
// Add tag:
else {


texts: Replace array element with multiplication of neighbors in Scala

texts:
Given an array of integers, update the index with multiplication of previous and next integers,

 Input: 2 , 3, 4, 5, 6
 Output: 2*3, 2*4, 3*5, 4*6, 5*6

Following is a scala implementation for the same. Kindly review.

import scala.util.Random

object NeighborMultiplication extends App {
  val numbers = List.fill(10)(Random.nextInt(10))

  println(numbers mkString ",")

  def multiplication(l: List[Int], carryOver: Int = 1, useCarryOver: Boolean = false ): List[Int] = l match {
    case Nil => List()
    case x::Nil => List(carryOver * x)
    case x::y::Nil => List(carryOver * x * y, y * x)
    case x::y::z::Nil => List(carryOver * x * y, x * z, y * z)
    case x::y::z::tail =>
      if (useCarryOver) List(carryOver * y, x * z, y * tail.head) ++ multiplication(tail, z, true)
      else List(x * y, x * z, y * tail.head) ++ multiplication(tail, z, true)
  }

  println(multiplication(numbers).mkString(","))

}


texts: Min-Heap based priority queue class written in ES6

texts:
I would appreciate any feedback on syntax, naming convention, possible shortcuts, clarity of code and any other constructive feedback. This code was based off of the Priority Queue chapter in The Algorithm Design Manual.
CODE
'use strict';

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

class PriorityQueue {
    constructor(values) {
        this._n = -1;
        this._Q = [];

        if (Array.isArray(values)) {
            for (let value of values) {
                this.insert(value);
            }
        }
    }

    get n() {
        return this._n;
    }

    set n(value) {
        this._n = value;
        return;
    }

    get Q() {
        return this._Q;
    }

    set Q(value) {
        this._Q = value;
        return;
    }

    getParent(n) {
        if (n === 0) return -1;
        return Math.floor((n - 1) / 2);
    }

    getYoungChild(n) {
        return (n + 1) * 2 - 1;
    }

    insert(x) {
        this.Q[++this.n] = x;
        this.bubbleUp(this.n);
    }

    bubbleUp(x) {
        var parent = this.getParent(x);
        if (this.Q[parent] > this.Q[x]) {
            this.swap(parent, x);
            this.bubbleUp(parent);
        }
    }

    bubbleDown(parent) {
        var child = this.getYoungChild(parent);
        var min_index = parent;

        for (let i=0; i<=1; i++) {
            if (this.Q[min_index] > this.Q[child+i]) min_index = child+i;
        }

        if (min_index !== parent) {
            this.swap(parent, min_index);
            this.bubbleDown(min_index);
        }
    }

    swap(x, y) {
        var temp = this.Q[x];
        this.Q[x] = this.Q[y];
        this.Q[y] = temp;
    }

    extractMin() {
        if (this.n < 1) throw 'The queue is empty.';

        var min = this.Q[0];

        if (this.n === 1) {
            this.Q = [];
            this.n = 0;
            return min;
        }

        if (this.n === 2) {
            this.Q = [this.Q[1]];
            this.n = 1;
            return min;
        }

        this.Q[0] = this.Q.splice(this.n, 1)[0];
        this.bubbleDown(0);
        this.n--;

        return min;
    }

    heapsort() {
        var original = this.Q;
        var A = [];

        for (let i=0; i<=this.n; i++) {
            A.push(this.extractMin());
        }
        this.Q = original;
        return A;
    }
}

var test = [];
for (let i=0; i<20; i++) {
    test.push(getRandomInt(0, 999));
}

console.log('test array is', test);

var pq = new PriorityQueue(test);

console.log(pq.heapsort());


texts: Pythonic way to select element in a list window

texts:
Here is a list where I would like to keep only the 'windows' where there are a group of number higher than 3, but if in any case inside this group you find a smaller number, you keep it.

Moreover, if there is an isolated high number (between zeros for example), we need to delete it.

l = [3.5, 0, 0, 0.5, 4, 10, 20, 3, 20, 10, 2, 0, 0, 3.5, 0, 2, 18, 15, 2, 14, 2, 0]

and the expected result :

[4, 10, 20, 3, 20, 10, 18, 15, 2, 14]

This program does it but I feel this it not very pythonic, could you think of any other way ?

l = [3.5, 0, 0, 0.5, 4, 10, 20, 3, 20, 10, 2, 0, 0, 3.5, 0, 2, 18, 15, 2, 14, 2, 0]

new_l = []
index = []
seuil = 3

for i, elt in enumerate(l):
    if elt > seuil:
        if (l[i-1] and l[i+1]) > 1:
            new_l.append(elt)
            index.append(i)
        else:
            pass
    else:
        try:
            if (l[i-1] and l[i+1]) > seuil:
                new_l.append(elt)
                index.append(i)
        except IndexError:
            pass
print index
print new_l


texts: Splitting each word using longest substring that matches in a vocab/dictionary

texts:
This function takes in a string and a fixed list of vocab:

splits a string into words by spaces
for each word, check in the dictionary/vocab and find the longest matching substrings, if none matching use the [UNK] word
if a word is longer than a predefined length, it'll also become [UNK]

Code:

def tokenize(text, vocab, max_input_chars_per_word=10, unk_token="[UNK]"):
    output_tokens = []
    for token in text.split():
        chars = list(token)
        if len(chars) > max_input_chars_per_word:
            output_tokens.append(unk_token)
            continue

        is_bad = False
        start = 0
        sub_tokens = []

        while start < len(chars):
            end = len(chars)
            cur_substr = None
            while start < end:
                substr = "".join(chars[start:end])
                if start > 0:
                    substr = "##" + substr
                if substr in vocab:
                    cur_substr = substr
                    break
                end -= 1
            if cur_substr is None:
                is_bad = True
                break
            sub_tokens.append(cur_substr)
            start = end

        if is_bad:
            output_tokens.append(unk_token)
        else:
            output_tokens.extend(sub_tokens)
    return output_tokens

And example input and expected output:

vocab = ["the", "go", "##es", "to", "eat", "pum", "##pkins", "of", "##gos", "##stein"
         "#400", "1", "boredom", "##folk", "man", "##go", "out", "folks", "##0",
        "un", "##aff", "##able"]

s = "the unaffable folks goes to eat 1400 folkspkinsgosgo pumpkins and 10 mangos out of boredom"

tokenize(s, vocab)

[out]:

['the',
 'un',
 '##aff',
 '##able',
 'folks',
 'go',
 '##es',
 'to',
 'eat',
 '[UNK]',
 '[UNK]',
 'pum',
 '##pkins',
 '[UNK]',
 '1',
 '##0',
 'man',
 '##gos',
 'out',
 'of',
 'boredom']

The nested while loop looks a complicated and checking each token isn't parallelized since it looks like it's independent of other tokens.  How can this function be improved?

Simpler loops, or checking in parallel or maybe an easier to find longest matching substring from a list when iterating through the tokens? Or regexes?


texts:
I'm sure code indentation is a basic requirement for correct development. I have checked out may pages to learn more and results of my coding are below.

I like to share that here to receive opinions and suggestions.

<?php
include_once "../../config.php";

// Start
if (!isset($_SESSION)) session_start();
$level = 2;

if (!isset($_SESSION['user_id']) OR ($_SESSION['user_levell'] > $req_level)) {
    header("Location: $url/dashboard.php?error=1"); exit;
}

// Load permissions
$result = mysql_query("
    SELECT conf
    FROM adm_users
    WHERE user_id=".$_SESSION['user_id']
);
$row = mysql_fetch_array($result, MYSQL_BOTH);
    $access = $row['acess'];

if (($_SESSION['user_level'] != "1") && ($access_config != "1")) {
    header("Location: index.php?error=1"); exit;
}
// End

include_once "$url/includes/head.php";
include_once "$url/includes/menu.php";

// Load ser
$result = mysql_query("
    SELECT  *
    FROM    adm_ser
    WHERE   ser_id='$ser_id'
");

$row = mysql_fetch_array($result, MYSQL_BOTH);
    $ser_id = stripslashes($row['ser_id']);
    $ser_cod = stripslashes($row['ser_cod']);
    $ser_cd = stripslashes($row['ser_cnpj']);
    $ser_name = stripslashes($row['ser_name']);
    $ser_status_id = stripslashes($row['ser_status_id']);

// Dropdown Ser Status
$sql2 = mysql_query("
    SELECT *
    FROM adm_ser_status
    WHERE status_id=".$ser_status_id
);

while($row = mysql_fetch_array($sql2)) {
    $status_id_dropdown = $row['status_id'];
    $status_de_dropdown = $row['status_desc'];
}
?>


texts: Settings the height of rows for multiple screens within a TableViewController

texts:
Is there a better way to write this? This is a class that displays a preferences menu. We do this when the user first installs the app during a walk-through where we only show them some of the settings with additional guidance on how to set them. We also show the entire preferences menu if the user selects our preferences button.

    /**
 Manages the height of the table's cells, hiding them if necessary.

 parameter: The table we'll edit
 parameter: The height in dpi of the row at a given row
*/

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    switch walkthroughStep {

        // step 1 of the walkthrough
        case 1:

            switch indexPath.row {
            case 0: return 0.1
            case 3:
                if ((promptLabel.intrinsicContentSize().height * promptLabel.font.pointSize) > 350){
                    //print ("the result of this is:  ---------- \(promptLabel.intrinsicContentSize().height * promptLabel.font.pointSize)")
                    return 80
                }
                else { return 50.0 }
            case 4: return 9.0
            case 5: return 0.1
            case 6: return 0.1
            case 7: return 0.1
            case 8: return 0.1
            case 9: return 0.1
            case 10: return 0.1
            case 11: return 0.1
            default: break
        }

        // step 2 of the walkthrough
        case 2: switch indexPath.row {
            // hide all cells of teh default methos table
            case 0: return 0.1
            case 1: return 0.1
            case 2: return 0.1
            case 3: return 0.1
            case 4: return 0.1
            case 5:
                if enableNotifications.on {
                    return selectedCellHeight
                }
                return unselectedCellHeight
            case 6: return 9.0
                // hide propmt me to modify number cell
            case 7: return 0.1
            case 8: return 0.1
            case 9: return 0.1
            case 10: return 0.1
            case 11: return 0.1
            default: break
        }

        // normal state
        default:
            switch indexPath.row {
            // hide all cells of teh default methos table
            case 0: return 50.0
            case 1: return 50.0
            case 2: return 50.0
            case 3:
                if ((promptLabel.intrinsicContentSize().height * promptLabel.font.pointSize) > 350){
                    //print ("the result of this is:  ---------- \(promptLabel.intrinsicContentSize().height * promptLabel.font.pointSize)")
                    return 80
                }
                else { return 50.0 }
            case 4: return 9.0
            case 5:
                if enableNotifications.on {
                    return selectedCellHeight
                }
                return unselectedCellHeight
            case 6: return 9.0
                // hide propmt me to modify number cell
            case 7:
                if ((modifyNumbersLabel.intrinsicContentSize().height * modifyNumbersLabel.font.pointSize) > 310){
                    //print ("the result of this is:  ---------- \(modifyNumbersLabel.intrinsicContentSize().height * modifyNumbersLabel.font.pointSize)")
                    return 90
                }
                else { return 50.0 }
            case 8: return 9.0
            case 9: return 50.0
            case 10: return 50.0
            case 11: return 50.0
            default: break
        }
    }

    return 50.0
}


texts: Multiple loops versus multiple stringbuilders

texts:
I've come across the following piece of code in a Razor view

        Company
        @foreach (Customer c in Model.SelectedInstallers)
        {
            @c.Name
        }

        Address
        @foreach (Customer c in Model.SelectedInstallers)
        {

                @c.Street

                @c.City

                @c.County

                @c.Postcode

        }

        Contact Details
        @foreach (Customer c in Model.SelectedInstallers)
        {

                @c.Telephone

                @c.Website

        }

        Remove
        @foreach (Customer c in Model.SelectedInstallers)
        {
            Remove installer
        }

Now would it better to stay with this code or change it to do one loop with multiple stringbuilders:

StringBuilder company = new StringBuilder();
StringBuilder address = new StringBuilder();
StringBuilder contact = new StringBuilder();
StringBuilder remove = new StringBuilder();

foreach (Customer customer in Model.SelectedInstallers)
{
    company.AppendFormat("\n    {0}	", customer.Name);
    address.AppendFormat("\n    {0}
{1}
{2}
{3}	", customer.Street, customer.City, customer.County, customer.Postcode);
    contact.AppendFormat("\n    {0}
{1}	", customer.Telephone, customer.Website);
    remove.AppendFormat("\n    Remove {1} from the list	", removeUrl, customer.Name);
}

        Company
        @Html.Raw(company.ToString())

        Address
        @Html.Raw(address.ToString())

        Contact Details
        @Html.Raw(contact.ToString())

        Remove
        @Html.Raw(remove.ToString())

Or does it not matter if there is only going to be a maximum of ten installers


texts: Solve 6 simultaneous equations for 8 variables puzzle with Java

texts:
I came across this mathematical puzzle, where one really cool answer was a python script to brute force answers.

Here's my take, which is essentially a translation of that to Java:

public class TerribleMath {

    public static void main(String[] args) {
        findAndPrintSolutions(1, 20);
    }

    private static void findAndPrintSolutions(int from, int to) {
        for (int a = from; a < to; a++) {
            for (int b = from; b < to; b++) {
                for (int c = from; c < to; c++) {
                    for (int d = from; d < to; d++) {
                        for (int e = from; e < to; e++) {
                            for (int f = from; f < to; f++) {
                                for (int g = from; g < to; g++) {
                                    for (int h = from; h < to; h++) {
                                        if (isSolution(a, b, c, d, e, f, g, h))
                                            printSolution(new int[] { a, b, c, d, e, f, g, h });
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private static boolean isSolution(int a, int b, int c, int d, int e, int f, int g, int h) {
        if (a + b - 9 != 4)
            return false;
        if ((c - d) * e != 4)
            return false;
        if (f + g - h != 4)
            return false;
        if ((a + c) / f != 4)
            return false;
        if ((b - d) * g != 4)
            return false;
        if (9 - e - h != 4)
            return false;
        return true;
    }

    private static void printSolution(int[] variables) {
        StringBuilder output = new StringBuilder();
        for (int variable : variables) {
            output.append(variable + ", ");
        }
        output.deleteCharAt(output.length() - 1);
        output.deleteCharAt(output.length() - 1);
        System.out.println(output.toString());
    }
}

There are a few ways of abusing the findAndPrintSolutions method that I know of. Also, I get the feeling it could be recursive, although I'm not sure exactly how to write that. Lastly, the class name comes from the fact that the puzzle had to be solved by not doing operations in the pemdas order.


texts: Displaying available destinations using Angular.JS

texts:
I wonder to know if there is any bad smell on my practice for i18n on Angular.
I put the I18n translating function on Angular controller (because I don't know how to put it on HTML template file)

And about the i18n scope, I use this way I18n.t("city." + city_name) to indicate that the city_name is under "city" scope. Could I write it in this way I18n.t(city_name, scope: "city") to make it more understandable.

I appreciate every comment and suggestion to enhance my current solution.

Data structure

departures_lst is a list of countries' English name e.g.,: [US, China, Japan]

Each country has many cities name. e.g. [New York, LA, Boston]

Angular controller

App.controller("departures_ctrl", function($scope, $location, $http) {
    $http.get("/departures.json")
    .success(function (response) {
      $scope.departures_lst = response;
    });
    $scope.get_destinations = function(city_name) {
          return $location.url("/depart_from/" + city_name);
    };
    $scope.i18nCountryName = function(country_name) {
          return I18n.t("country." + country_name) + country_name
    };
    $scope.i18nCityName = function(city_name) {
          return I18n.t("city." + city_name) + city_name
    };
});

HTML teamplate?

{{i18nCountryName(departure.country)}}

        {{i18nCityName(city)}}


texts:
I am trying to brush up on Java after not programming for a few years. The idea behind this code is simply to get used to object oriented programming, modularization techniques, and basic arrays. Any comments and critiques are obviously welcome!

Here is my code:

/*
 * This code is meant to ask the user for ten sentences,
 * store them in an array, and print that array out one sentence at a time.
 * The goal is to work on modularization and general OOP principles as well as basic arrays and loops.
 */

import java.util.Scanner;

/*
 * ArrayBuilder is a public class that creates an array of ten strings
 * and gives the ability to print them out with the printMessages
 * method.
 */

public class ArrayBuilder{
    //Initialize an array
    public String[] s;

    /*
     * The build method generates ten sentences based on user input
     * and stores them in an array of strings.
     */
    public String[] build(){
        //Create the 10 index array
        s = new String[10];
        //Initialize a scanner object to receive user input
        Scanner scanner = new Scanner(System.in);
        //Loop 10 times asking the user for a new sentence each time
        for (int i = 0; i < 10; i++){
            System.out.println("Enter a new sentence: ");
            //Store the input in the 's' array
            s[i] = scanner.nextLine();
        }
        //Return the 's' array to make it available to the printMessages method
        return s;
    }

    /*
     * The printMessages method loops through a given array and prints the
     * string at each index.
     */
    public void printMessages(String[] s){
        //Loop as many times as there are strings in the list, printing out each index
        for (int i = 0; i < s.length + 1; i++){
            System.out.println(s[i]);
        }
    }

    /*
     * Main method that instantiates an ArrayBuilder object, then calls the
     * build and printMessages methods to create and display an array of user input.
     */
    public static void main(String[] args){
        //Create a new ArrayBuilder object
        ArrayBuilder AB = new ArrayBuilder();
        //Invoke the build method to build up an array
        AB.build();
        //Invoke the printMessages method to display what is stored in the array
        AB.ptrintMessaages(AB.s);
    }
}


texts:
I am a Haskell beginner. Here is my function to find prime factors of a number

primes = 2:takePrimes [3, 5 ..]
    where takePrimes (x:xs) = let smallPrimes = untilRoot x primes
                              in  if 0 `notElem` (map (mod x) smallPrimes)
                                  then x:takePrimes xs
                                  else takePrimes xs

untilRoot n = takeWhile (\x -> x*x < n)

firstPrimeDivisor :: Integer -> Integer
firstPrimeDivisor x = head [p | p <- primes, x `mod` p == 0]

primeFactor 1 = []
primeFactor x = let p = firstPrimeDivisor x
                in p:primeFactor (x `div` p)

How does it look?


texts: List comprehension for reading lists of integers

texts:
As of reading the following input.txt file:

1 6 14
1 2 7
1 3 9
2 3 10
2 4 15
3 6 2
3 4 11
4 5 6
5 6 9

I wanted to make a list of lists containing each line as a list of integers

[[1, 6, 14],
 [1, 2, 7],
 [1, 3, 9],
 ...
 [5, 6, 9]]

I achieved that by doing the following

with open('input.txt', 'r') as f:
    # gets lines as list of strings [['1, 2, 3,', ...]]
    nodes_list = [n.split() for n in f.readlines()]
    # convert strings inside the lists to int's [[1, 2, 3], ...]
    nodes_list = [[int(y[0]), int(y[1]), int(y[2])] for y in nodes_list]

Is there any way that I can achieve the same with a single comprehension list, without the need of having two separated ones? If not, maybe some cleaner way of doing it?


texts: Using R to transform Excel files to be combined

texts:
I have 50+ excel files that I need to transform (and eventually combine) to use in analyses. I’ve written a code that transforms them into the format I need, but it is extremely slow for files with high species counts (the transformed output will have > 2 million rows). My first question: is there a way to speed up my function? My second question: once all the files are combined, there will be many millions of lines of data. Will I be able to manipulate (e.g. subset, statistically analyze) the data in R? Can R (and/or my laptop) handle that much data? I’ve only used R with several thousand lines and a hundred or so columns before, so I don’t know what’s possible.
The first part of the code below is to produce a data frame resembling what my files look like. In reality, my files are larger (45rows, 12-21 columns) and they are not all the same (different number of columns, and the Habitat column is in different locations with different names), thus some of the strange code in the function. I could clean up each file so they are the same before I use my function, if that would be faster.

Sample data

library(dplyr)
#library(readxl) #this isn't used here, but this is what I use to load the data files.

aa<-c('Jul','Jul','Jul','Oct','Oct','Oct')
bb<-c('MA1','MA2','MA3','MA1','MA2','MA3')
a<-c(NA,100:104) #when loaded, the data has both NA's and 0's
b<-seq(1,12,2)
c<-seq(0,35,6)
d<-c(NA,NA,2000,NA,200,0)
e<-c(1:6)
Chiro.1<-data.frame(aa,bb,a,b,c,d,e)
colnames(Chiro.1)<-c('Chironomidae','Habitat','0','0.5','1','2','3')
Chiro.1<-as_tibble(Chiro.1)
Chiro.1$Habitat<-as.character(Chiro.1$Habitat)
Chiro.1$Chironomidae<-as.character(Chiro.1$Chironomidae)

The function

Cedar.bs.fun<-function (x, scol,Hcol) {
  #x = dataframe
  #scol = column number data starts
  #Hcol = column habitat type is in
  spe.list<-list()
  pb <- txtProgressBar(min = 0, max = nrow(x), style = 3)
  for (i in 1:nrow(x)) for (j in scol:ncol(x)){ #not every file has the same number of rows and columns
    if (!is.na(x[i,j])) {
      dat <- as.data.frame(matrix(ncol=4, nrow=0))
      colnames(dat)<-c('Taxa','Habitat','Date','Size')
      if (x[i,j]> 0) {
        n<-round(sum(x[i,j]),0) #original files have some decimals
        for(k in 1:n) {
          dat[k,1] = as.character(colnames(x[,1]))
          dat[k,2] = as.character((x[i,Hcol]))
          dat[k,3] = as.character((x[i,1]))
          dat[k,4] = colnames(x[,j])
          setTxtProgressBar(pb, i)
        }
      }
      spe.list[[length(spe.list)+1]] <- dat
      spe.list.1<-do.call("rbind",spe.list)
    }
  }
  spe.list.1$Size<-as.numeric(as.character(spe.list.1$Size)) #the column headings of the original files are the beginnings of size bins (eg. 1 mm - 2 mm)
  spe.list.1$Size<-spe.list.1$Size+0.5 #I need the final size to be the middle of the bin
  spe.list.1$Size[spe.list.1$Size==0.5]<-0.25
  spe.list.1$Size[spe.list.1$Size==1]<-0.75
  close(pb)
  return(spe.list.1)
    }

Run the function

final<-Cedar.bs.fun(Chiro.1,scol=3,Hcol=2)
#combined.1<-rbind(final,final.2,final.3,etc.) #eventually I will be combining all 50 or so files into one data frame for further manipulation and statistical analysis

And yes, the original files are mine made long before I new much of anything about R and how to organize data. Now I'm paying for it. Still tons to learn.


texts: Two approaches to count occurrences of one char in a String in Java

texts:
I have two approaches:

First Approach:

int count =0;
for(int i = 0; i < text.length(); i++) {
    if(text.charAt(i) == charToCheck){
        count++;
    }
}
System.out.println(count);

Second Approach:

count = text.length() - text.replaceAll(
                             String.valueOf(charToCheck),"")
                            .length();
System.out.println(count);

Which one is fast w.r.t Time & Space Complexity? Why?

Are there any more approaches (which I am not aware of)? If yes, Please let me know.


texts:
I have built a shell function aimed to perform the following:

Given a string as first argument, perform safe expansions (i.e. those that cannot cause arbitrary code execution and only produce string output)
Save the output to a variable the name of which is provided as second argument, and can be considered safe for the purpose of this question

The code is as follows :

#
# Argument 1 : string to safely expand
# Argument 2 : name of the variable to which expanded value will be assigned
#
safeval()
{
local _v=$1
_v=${_v//\$\(/\$$'\1'}
_v=${_v//\$\[/\$$'\2'}
_v=${_v//'`'/$'\3'}
_v=${_v//\\ /$'\4'}
_v=${_v// /$'\5'}
eval printf -v _v %b "$_v" || return 1
_v=${_v//$'\1'/\(}
_v=${_v//$'\2'/\[}
_v=${_v//$'\3'/'`'}
_v=${_v//$'\4'/\\ }
_v=${_v//$'\5'/ }
printf -v "$2" %s "$_v"
}

This code aims to achieve its purpose by doing the following :

Replace all occurrences of $(, $[ and ` with (hopefully) safe strings.
Then perform eval (the remaining expansions are performed)
Then replace the other way around

This means that expansions that are not performed will be kept as is.  There may be cases where nested expansions have the outer expansion execute, but the inner expansion be blocked, which maybe could create incorrect output or failure; as long as it just fails without doing anything nasty from a security standpoint, this is OK for me, as I am going for safety first.

Here are example cases (function safeval assumed to be already loaded):

A=1
safeval '$A' B
echo "$B"   # Echoes "1" (without the double quotes)
safeval '$A$(ls /)$A' C
echo "$C"   # Echoes "1$(ls /)1" (without the double quotes)

Any feedback about the safety (or lack thereof) and potential failure modes that I have missed is especially welcome.

This function is intended to allow the use of values read from configuration files in which (safe) expansions and shell-type quoting would be allowed.

EDIT

I found a bug in handling of spaces and double quotes.  On the eval printf line, variable _v is expanded, and if it contains double quotes and spaces, printf sees many arguments (spaces are stripped due to word splitting).  To fixe this the additional code :

Replace already-escaped spaces with a non-printable character
Escape remaining spaces so that printf will see only one argument
At the end, put the escaped spaces back in


texts:
I have a need for a container that behaves like an unordered_map, but has a fixed capacity, and an eviction policy where the least recently inserted key-value pair is chosen to be evicted when an insertion is performed at capacity.

I've implemented this by creating a container which combines a regular unordered_map with a queue of iterators (implemented as a circular array). When a new item is inserted the iterator at the end of the queue is erased.

fixed_size_unordered_map

#include <array>
#include <unordered_map>

template<typename Key, typename U, std::size_t capacity>
class fixed_size_unordered_map {
    using iterator = typename std::unordered_map<Key, U>::iterator;
    using size_type = typename std::unordered_map<Key, U>::size_type;
    using value_type = typename std::unordered_map<Key, U>::value_type;

public:
    fixed_size_unordered_map() { iter_queue.fill(items.end()); }
    fixed_size_unordered_map(const fixed_size_unordered_map&) = default;
    fixed_size_unordered_map& operator=(const fixed_size_unordered_map&) = default;
    fixed_size_unordered_map(fixed_size_unordered_map&&) = default;
    fixed_size_unordered_map& operator=(fixed_size_unordered_map&&) = default;

    size_type count(const Key& key) const {
        return items.count(key);
    }

    const Key& at(const Key& key) const {
        return items.at(key);
    }

    std::pair<iterator, bool> insert(const value_type &v) {
        if(iter_queue[queue_idx] != items.end()){
            items.erase(iter_queue[queue_idx]);
        }
        const auto ret = items.insert(v);
        if(ret.second){
            iter_queue[queue_idx] = ret.first;
            queue_idx = (queue_idx + 1) % capacity;
        }
        return ret;
    }

    /* could implement more map<T, U> delegates as appropriate, the above are the ones
     * I actually need for my use case */

protected:
    std::unordered_map<Key, U> items;

    std::array<iterator, capacity> iter_queue;
    std::size_t queue_idx{0};
};

Example usage:

fixed_size_unordered_map<int, int, 10> m;
for(int i=0; i<=10; ++i){
    m.insert(std::make_pair(i, 2*i*i));
}
std::cout << m.at(10) << "\t" << m.at(1) << "\t" << m.count(0) << std::endl;


texts: Avoiding multiple hits to Sprite by shifting Sprite to separate group

texts:
Would appreciate any suggestions or improvements, I'm sure there are many. Especially so on the way I've avoided multiple hits by the missiles; shifting the asteroid into a separate group to enable the animation to continue without registering more hits and hence addition to the score.

P.S As it stands my game has a ship at the bottom of the screen which can move horizontally but not vertically. It can fire missiles at a horizontally moving asteroid sprite at the top of the screen. If the asteroid is hit by a missile sprite, it triggers an explosion animation and the sprite is removed. A new asteroid sprite is then spawned.

Sprite:

class MyAsteroid(pygame.sprite.Sprite):
    """ My sprite"""

    def __init__(self):
        super().__init__()
        self.height = 0
        self.width = 0
        self.vel_x = 5
        self.velocity_y = 0
        self.hit = False
        self.files = []
        self.images = []
        self.index = 0
        self.asteroid_explosion = pygame.mixer.Sound("explosion.wav")

        for i in range(1,10):
            file = "explosion0.bmp"
            new_file = file.replace("0", str(i))
            self.files.append(new_file)
        for file in self.files:
            self.images.append(load_image(file))

    def ast_hit(self):
        self.hit = True

    def update(self, missile_group, the_screen):
        super().update()
        self.X = self.X + self.vel_x
        if self.X < 0 or self.X > the_screen.width - self.width:
            self.vel_x = -(self.vel_x)
        if self.hit == True:
            self.vel_x = 0
            self.asteroid_explosion.play()
            self.image = self.images[self.index]
            self.index += 1
            if self.index >= len(self.images):
                missile_group.remove(self)

    def draw(self):
        super().draw()

    def load(self, image):
        self.image = image
        self.rect = self.image.get_rect()
        self.width, self.height = image.get_size()

    # X property
    def _get_x(self): return self.rect.x
    def _set_x(self, value): self.rect.x = value
    X = property(_get_x, _set_x)

    # Y property
    def _get_y(self): return self.rect.y
    def _set_y(self, value): self.rect.y = value
    Y = property(_get_y, _set_y)

    # position property
    def _get_pos(self): return self.rect.topleft
    def _set_pos(self, value): self.rect.topleft = value
    position = property(_get_pos, _set_pos)

Hit detection:

for asteroid in asteroid_group:
            asteroid_hit = False
            asteroid_hit = pygame.sprite.spritecollide(asteroid, missile_group,\
                                                       True)
            if asteroid_hit:
                asteroid.ast_hit()
                asteroid_group.remove(asteroid)
                hit_group.add(asteroid)
                #asteroid.hit = True
##                for missile in asteroid_hit:
##                    missile_group.remove(missile)
                score += 10


texts:
I'm new to JavaScript and new to jQuery plugin development. My plugin is really easy I just want to taggify a

    (function($) {
        var allTags;
        $.fn.taggify = function(options) {
            allTags = this;
            _create(allTags);
            return this;
        };

        function _create(theElement) {
            var inputWrapper = $('

');
            var input = $('<input></input>');
            input.attr('type', 'text');
            input.attr('autocomplete', 'off');
            input.css('border', 'none');
            input.css('outline', 'none');
            inputWrapper.html(input)

            allTags.append(inputWrapper);
            _event(input);
        }

        function _event(theText) {
            theText.keyup(function(e) {
                if(e.keyCode === 13) {
                    var aTag = $('

');
                    aTag.addClass('tag-choice');

                    var aSpan = $('');
                    aSpan.addClass('tag-label');

                    var tagText= theText.val();
                    aSpan.html(tagText);
                    aTag.html(aSpan);

                allTags.prepend(aTag);
                theText.val('');
            }
        });
    }

})(jQuery);


texts:
I need some improvements on my code. I did some validation by preg_match and functions.  I need some special characters restrictions every field.

<?php
$error='';
if(isset($_POST['submit']))
{
if(nameField($_POST['name'])=='')
{
    $error="Invalid Name";
}

if(numberField($_POST['phone'])=='')
{
    $error.="<br>Invalid Number";
}
if(nameField($_POST['address'])=='')
{
    $error.="Invalid Address";
}
if($error)
{
    echo $error;
}
else
{
    echo "Form submitted successfully";
}
}

function nameField($val)
{
if(preg_match("/([%\$#\*\'\"\()]+)/", $val)) //Not allowed some of the special characters
{
return false;
}
else
{
return true;
}
}
function numberField($val)
{
if(preg_match("/^[0-9]*$/", $val))
{
return true;
}
else
{
return false;
}
}
?>

<html>
<body>
<form method="post">
<input type="text" name="name"/>
<input type="text" name="phone">
<input type="text" name="address">
<input type="text" name="city">
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>


texts:
In this library:

text_data(val) translates val to computer data types
colorcode() returns the selected color in hex

Can you please tell me how I can make it better?

from tkinter.colorchooser import askcolor
def text_data(text):
    texti = []
    binary = []
    ordv = []
    hexadecimal = []
    octal = []
    i = 0
    while i < len(text):
        j = ord(text[i])
        k = bin(ord(text[i]))
        l = hex(ord(text[i]))
        m = oct(ord(text[i]))
        k = k[2:]
        l = l[2:]
        m = m[2:]
        print(text[i], " ", j, " ", k, "", l, "", m)
        binary.append(k)
        ordv.append(j)
        hexadecimal.append(l)
        texti.append(text[i])
        octal.append(m)
        i += 1
    print("\n")
    print(binary)
    print("\n")
    print(ordv)
    print("\n")
    print(hexadecimal)
    print("\n")
    print(octal)
def colorcode():
    return askcolor()[1]
print(colorcode())


texts:
I have a script, which updates my table's column and writes an id to it.

I need to check whether the column is empty or not.  If it is not, I add a ,.

$subs = mysql_fetch_array(mysql_query("SELECT subscribed_user_id FROM users WHERE user_id=".(int)$_GET['user']));

$subs_array = array();

$subs_array=explode(',', $subs['subscribed_user_id']);

if(!in_array($_COOKIE['user_id'], $subs_array))
{
    if($subs['subscribed_user_id']=='')
    {
        $add='';
    } else {
        $add = $subs['subscribed_user_id'].',';
    }
    mysql_query("UPDATE users SET subers=subers+1, subscribed_user_id='".$add.$_COOKIE['user_id']."' WHERE user_id=".(int)$_GET['user']);
}

I have an idea: always add ,.  But when I select it, I don't use the full length of the array.  But, for example array.length-2, I think that it is not OK and I need to know how I can improve this script.


texts: Find maximum distance between elements of an array

texts:
I have written a program in scala which actually does the below

  For every number between the maximum and minimum value of the array calculate the distance for each and every element in the array and find the element with maximum distance.

I want to master functional programming in scala. Trying to understand how I can use functional programming to this.

/*
* Author:
* Given an integer array find the distance find the index that ranges between
* minimum and maximum value of Array and that has the maximum distance from all
* the array elements.
*/

package com.scala.practice.basic

object CycleProblem {
  def main(args: Array[String]){
    val input:Array[Int]=Array(-1000,1000,-30,70,80,20,100,110,-120,-180,120)
    val minVal=input.reduceLeft(_ min _)
    val maxVal=input.reduceLeft(_ max _)
    var maxDistance=0
    var index=minVal-1;
    for(i<-minVal to maxVal){
      var distance =0
      for(j<-0 to input.length-1){
        distance=distance+Math.abs(i-input(j))
      }
      if(distance > maxDistance)
        {
        maxDistance=distance
        index=i
        }
    }
    println("Park the bicycle in this location:"+ index+ " the distance(maximum when compared to to other indices) from all other parked location is: "+maxDistance + "");

  }
}


texts: Which solution of the two is the most efficient? Is there a better one? (IP Address Defang)

texts:
I just started doing preparation for interviews, but im having trouble recognizing the optimal solution
Problem: For a given IP Address, replace every "." with "[.]"
Example:
Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"

My solutions:
First:
def defang(x):
    lst = []
    for i in x:
        if i == ".":
             lst.append("[" + i + "]")
        else:
            lst.append(i)
    return lst

adress = "255.100.50.0"
tmp = defrang(adress)
x=''
for i in tmp:
    x+=i
print(x)

Second:
adress = "255.100.50.0"
print("[.]".join(adress.split('.')))

Which one you think is better? The first doesnt rely on built-in methods but it creates a new list (more memory wasted?)
The second seems better but is it a problem that it relies on built-in methods?
In general idk what level of abstraction is requested by the interviewers, so any advice is welcome (regarding this specific solution or whatever else)


texts: Safe cracker string with all combinations

texts:
Imagine a safe with a 4-digit code, and accepting a continuous stream of code entries, such that when the 4 digits are seen in the right sequence, the safe opens. Generate a short string that contains all possible code combinations, so that when you feed it to the safe, it will inevitably open. The string should be as short as possible, and not contain the same code sequence twice.

As an exercise while learning Scala,
I implemented a general version of this logic using an arbitrary symbol alphabet and customizable code length.
For example, to generate a string for a 4-digit safe with numeric symbols,
you would call SafeCracker.genCrackerString("0123456789", 4).
I'm looking for a review of all aspects of this code,
and the unit tests too.

object SafeCracker {

  def genCrackerString(symbols: String, codeLength: Int) = {
    require(symbols.nonEmpty)
    require(codeLength > 0)

    val combinations = math.pow(symbols.length, codeLength)

    def cracker(prefix: String, used: Set[String]): String = {

      def findSuffixCombo(num: Int): (String, String) = {
        val suffix = getNth(symbols, num)
        val combo = (prefix + suffix).takeRight(codeLength)

        if (!used.contains(combo)) (suffix, combo)
        else findSuffixCombo(num + 1)
      }

      if (used.size == combinations) prefix
      else {
        val (suffix, combo) = findSuffixCombo(0)
        cracker(prefix + suffix, used + combo)
      }
    }

    val first = symbols(0).toString * codeLength

    cracker(first, Set(first))
  }

  def getNth(symbols: String, num: Int) = {
    val base = symbols.length

    def getNth(prefix: String, num: Int): String = {
      if (num == 0) {
        if (prefix.isEmpty) symbols(0).toString
        else prefix
      } else {
        val index = num % base
        val digit = symbols(index)
        getNth(digit + prefix, num / base)
      }
    }
    getNth("", num)
  }
}

Unit tests:

import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class SafeCrackerTest extends FunSuite {

  test("cracker invalid if no symbols") {
    intercept[IllegalArgumentException](genCrackerString("", 1))
  }

  test("cracker invalid if code length < 1") {
    intercept[IllegalArgumentException](genCrackerString("123", 0))
  }

  test("cracker 123, len=1") {
    assert("123" == genCrackerString("123", 1))
  }

  test("cracker 1, len=3") {
    assert("111" == genCrackerString("1", 3))
  }

  test("cracker 12, len=2") {
    assert("112122" == genCrackerString("12", 2))
  }

  test("cracker 12, len=3") {
    assert("111211221222" == genCrackerString("12", 3))
  }

  test("cracker 0123456789, len=4") {
    assert(10294 == genCrackerString("0123456789", 4).length)
  }

  test("getNth 0123456789abcdef, 255") {
    assert("ff" == getNth("0123456789abcdef", 255))
  }
}


texts: Algorithm that spans orthogonal vectors: Python

texts:
The code consists of three functions:

Spans arbitrary vector (takes dimension as an argument)
Spans vector orthogonal to the one passed in the argument
Finds cross product between two vectors.

The code is following:

def span_vector(n):
    '''n represents dimension of the vector.'''
    return [random.randrange(-1000,1000) for x in range(n)]

def span_orthogonal(vec):
    '''vec represents n-dimensional vector'''
    '''Function spans an arbitrary vector that is orthogonal to vec'''

    dimension = len(vec)
    orthogonal_vec = []
    for k in range(dimension-1):
        orthogonal_vec.append(random.randrange(-1000,1000))
    last_k = ((-1)*sum([vec[x]*orthogonal_vec[x] for x in range(dimension-1)]))/vec[-1]
    orthogonal_vec.append(last_k)
    return orthogonal_vec

def cross_product(v1,v2):
    return sum(v1[x]*v2[x] for x in range(len(v1)))

What can be improved?

EDIT The last function must read dot_product, but not cross_product. I made a mistake.