texts: Checking if a number is a perfect square by recursive sum of its digits

texts:
I was solving this question on an online judge.

The problem boils down to the following:

  Given a number \$n\$, where \$1 \le n \le 10^{18}\$, we need to check if it contains odd number of divisors.

I have used following facts in my code:

only perfect squares have an odd number of divisors
the recursive sum of digits of perfect squares is always 1,4,7 or 9

A possible solution is:

Find the recursive sum of the digits of the given number
Check if the recursive sum is 1 or 4 or 7 or 9. ( as the recursive sum of digits of perfect squares is always 1,4,7 or 9 )

Here is my code for it.  It gives the correct answer for small values, but when submitted to the online judge, it shows "Wrong Answer", which means there is some bug in the code.
Can anyone explain why this is happening ?

#include<bits/stdc++.h>
using namespace std;

 long long recursiveSum(long long num){
 long long sum = 0;
 while(num != 0){
 sum = sum + num%10;
 num = num/10;
 }
 if(sum/10 != 0){
    return recursiveSum(sum);
 }
 else{
     return sum;
 }

 }

int main()
{
long long t,r;
long long n;
cin>>t;     //   t is the number of test cases
for(long long p=1;p<=t;p++)
{
    cin>>n;

    r=recursiveSum(n);

    if(r==1 || r==4 || r==7 || r==9) cout<<"Case "<<p<<": Yes\n";

    else cout<<"Case "<<p<<": No\n";

}

}


texts: Efficient data-driven finite state machine

texts:
In creating this answer to a recent question, I thought I might write a fully worked example that implements a finite state machine in C.

The purpose is to implement the following function:

  Given a const char *, search for a string conforming to the pattern WWWDD where WWW is one of { "Mon", "Tue", "Wed, "Thu", "Fri", "Sat", "Sun" } and DD is an integer in the range \$[1, 31]\$ (inclusive).  If the pattern exists within the string, return the offset; otherwise return -1.

I implemented this state machine: using simple table structure.  This is the code, which includes a simple driver with test vectors.

#include <string.h>
#include <stdlib.h>
#include <ctype.h>

static const struct fsmNode {
    const char target;
    const struct fsmNode *next;
} fsm[] = {
    { 'T' , &fsm[6] },    // 0
    { 'M' , &fsm[9] },    // 1
    { 'S' , &fsm[11] },   // 2
    { 'W' , &fsm[12] },   // 3
    { 'F' , &fsm[14] },   // 4
    { '\0' , NULL },      // 5
    // second letter
    { 'h' , &fsm[18] },   // 6
    { 'u' , &fsm[20] },   // 7
    { '\0' , NULL },      // 8
    { 'o' , &fsm[22] },   // 9
    { '\0' , NULL },      // 10
    { 'a' , &fsm[24] },   // 11
    { 'u' , &fsm[22] },   // 12
    { '\0' , NULL },      // 13
    { 'e' , &fsm[26] },   // 14
    { '\0' , NULL },      // 15
    { 'r' , &fsm[27] },   // 16
    { '\0' , NULL },      // 17
    // third letter
    { 'u' , &fsm[30] },   // 18
    { '\0' , NULL },      // 19
    { 'e' , &fsm[30] },   // 20
    { '\0' , NULL },      // 21
    { 'n' , &fsm[30] },   // 22
    { '\0' , NULL },      // 23
    { 't' , &fsm[30] },   // 24
    { '\0' , NULL },      // 25
    { 'd' , &fsm[30] },   // 26
    { '\0' , NULL },      // 27
    { 'i' , &fsm[30] },   // 28
    { '\0' , NULL },      // 29
    // first digit
    { '0' , &fsm[36] },   // 30
    { '1' , &fsm[35] },   // 31
    { '2' , &fsm[35] },   // 32
    { '3' , &fsm[46] },   // 33
    { '\0' , NULL },      // 34
    // second digit
    { '0' , NULL },       // 35
    { '1' , NULL },       // 36
    { '2' , NULL },       // 37
    { '3' , NULL },       // 38
    { '4' , NULL },       // 39
    { '5' , NULL },       // 40
    { '6' , NULL },       // 41
    { '7' , NULL },       // 42
    { '8' , NULL },       // 43
    { '9' , NULL },       // 44
    { '\0' , NULL },      // 45
    { '0' , NULL },       // 46
    { '1' , NULL },       // 47
    { '\0' , NULL },      // 48
};

int findWeekdayDate(const char *str) {
    const struct fsmNode *state = fsm;
    const char *curr;
    for (curr = str ; *curr; ++curr) {
        for ( ; state->target && *curr != state->target; ++state)
        { /* do nothing */ }
        if (state->next == NULL) {
            if (state->target) {
                // found a valid string
                return curr-str-4;
            } else {
                state = fsm;
            }
        } else {
            state = state->next;
        }
    }
    return -1;
}

// Test code follows...
static const struct test_s {
    const char *string;
    int expected;
} test[] = {
    { "abcSun24Def", 3},
    { "abcMun24Def", -1},
    { "abcSun091", 3},
    { "MON31", -1},
    { "Mon31", 0},
    { NULL, -1 }    // last item
};

#include <stdio.h>

#define RED    "\033[31m"
#define GREEN  "\033[32m"
#define WHITE  "\033[39m"

int main() {
    for (size_t i=0; test[i].string != NULL; ++i) {
        int val = findWeekdayDate(test[i].string);
        printf("%s: \"%s\", expected %d, got %d\n",
            (val == test[i].expected ? GREEN " OK" WHITE: RED "BAD" WHITE),
            test[i].string, test[i].expected, val
            );
    }
}

Comments on efficiency, style, performance, data structure choice and implementation are all of interest.


texts: MySQL select statement for retrieving user role permissions

texts:
I have a java project that I'm working on and I'm trying to implement in my application role-based authentication.
 So for example when a user is logging and he is an admin he will have access to some extra methods then a normal user has access to.

In order to do that I've mapped my database in the following way.

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";

--
-- Table structure for table `data`
--

USE DB;
DROP TABLE IF EXISTS `data`;
CREATE TABLE IF NOT EXISTS `data` (
  `id_u` int(11) NOT NULL AUTO_INCREMENT,
  `Username` varchar(30) NOT NULL,
  `Password` varchar(64) NOT NULL,
  `Salt` varchar(64) NOT NULL,
   `Role` int(30)  NOT NULL,
    PRIMARY KEY (`id_u`)
);

--
-- Dumping data for table `data`
--

INSERT INTO `data` (`id_u`,`Username`, `Password`, `Salt`,`Role`) VALUES
(1,'Mike', 'TzBql1WR9wZjN0LoKr2OBk2majc=', '4NWwJULan8U=','1'),
(2,'John', 'JcQnEVl0af8EwrPkmc6EGG+fLfs=', '2MWwJULan8U=','1'),
(3,'Alice', 'BaN+yn8W0SYZiUkaOHSZxDKTLMg=', '4NWSJULgn8U=','2'),
(4,'Bob', 'V1TtSe0GFYuHFJrA1l1lDIwdfKA=', '4NWwJILan9U=','2'),
(5,'Charlie', 'X40Xv/MntGoeqwif8hhFEOIrK8Q=', '4NWwFULan8X=','2');
COMMIT;

--
-- Table structure for table `Roles`
--

DROP TABLE IF EXISTS `Roles`;
CREATE TABLE IF NOT EXISTS `Roles` (
  `id_r` int(11) NOT NULL AUTO_INCREMENT,
  `Role_type` varchar(30) NOT NULL,
  `Role_code` int(30) NOT NULL,
   PRIMARY KEY (`id_r`),
   CONSTRAINT FK_UsersRoles FOREIGN KEY (Role_code)
   REFERENCES Roles(Role),
   CONSTRAINT FK_PermissionsRoles FOREIGN KEY (Role_code)
   REFERENCES Permissions(Permission)
)ENGINE=MyISAM AUTO_INCREMENT=22 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `Roles`
--

INSERT INTO `Roles` (`id_r`, `Role_type`, `Role_code`) VALUES
(1, 'admin', 1),
(2, 'normaluser', 2),
(3, 'guest', 3);
COMMIT;

--
-- Table structure for table `Permissions`
--

DROP TABLE IF EXISTS `Permissions`;
CREATE TABLE IF NOT EXISTS `Permissions` (
  `id_p` int(11) NOT NULL AUTO_INCREMENT,
  `Function` varchar(30) NOT NULL,
  `Permission` int(30) NOT NULL,
   PRIMARY KEY (`id_p`)
) ENGINE=MyISAM AUTO_INCREMENT=22 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `Permissions`
--

INSERT INTO `Permissions` (`id_p`, `Function`, `Permission`) VALUES
(1, 'newPrintJob', 0),
(2, 'print', 3),
(3, 'start', 3),
(4, 'read config', 2),
(5, 'set config', 1),
(6, 'queue', 2),
(7, 'top queue',2 ),
(8, 'stop', 2),
(9, 'restart', 2),
(10, 'status', 3),
(11, 'createUser', 1);
(12, 'createUser', 2);

Now my questions are, does the database have the correct structure in order to retrieve the name of the function in the Permission table?

How can I write a select statement that will retrieve a list of the certain functions from table Permission that a certain user has?
Any other feedback would be much appreciated.

Thank you!


texts:
This was too slow for my computer:

int f(unsigned int x)
{
    if(x <= 1) return 1;
    else return f(x-1)+f(x-2);
}

/* main */
int main()
{
    for(int i = 0; i < 50; i++) cout << f(i) << endl;
    return 0;
}

So I've made a faster implementation. It works, but is it well-written? Is there some way to improve it?

void f(unsigned long now)
{
    static int counter = 0;
    static unsigned long last = 0, tmp = last;
    if(counter++ == 50)
    {
        last = tmp = counter = 0;
        return;
    }
    std::cout << last + now << std::endl;
    tmp = last;
    last = now;
    f(now+tmp);
}

// calling f(1); in main


texts: Determine whether a number and its square are both the sum of two squares

texts:
Code gets timed out and needs to be simplified.
To ensure that n = sum of squares
, To determine if n^2 = sum of squares
, I need to input 4 integers : 5881, 2048, 2670, 3482
#To define the sum of squares
    def sumSquare(n) :
        i = 1
        while i * i <= n :
            j = 1
            while(j * j <= n) :
                if (i * i + j * j == n) :
                    return True
                j = j + 1
            i = i + 1

        return False

#To define that the square of n is equals to the square of i added to the square of j
    def Squared(n):
        i = 1
        while i * i <= n * n:
            j = 1
            while (j * j <= n * n):
                if(i * i + j * j == n * n):
                    return True
                j = j + 1
            i = i + 1

        return False

    T = int(input())
    while T>0:
        T-=1
        n = int(input())
        if ((sumSquare(n)) and (Squared(n))):
            print ("Yes")
        else:
            print("No")


texts: Printing all the prime numbers between two bounds

texts:
I keep getting a time limit exceeded for this solution to SPOJ Prime1.  I need to print all primes within a given interval (with intervals as large as 105, and numbers as large as 109).

I've tried everything I could think of to get this code to be faster but nothing works. What can I do?

#include <iostream>

bool isprime(int n) {
    if (n < 2) return false;
    for (int i = 2; i < n; ++i) {
        if (n % i == 0) return false;
    }
    return true;
}

int main() {
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(0);
    // Code to to print all the prime numbers between two bounds. n is the
    // number of test cases.
    int n, j, k;
    std::cin >> n;

    for (int i = 0; i < n; ++i) {
        std::cin >> j >> k;
        while (j-- != k) {
            if (isprime(j)) std::cout << j << '\n';
        }
    }
}


texts: Two bidirectional Software UARTs with AT89S52 microcontroller

texts:
I have learned one way to read from a serial port via software UART is via timer interrupts. I have made an implementation of receiving data from one serial port below. I haven't tested it yet because I now also need a way to efficiently transmit data as well without causing bad timings since UART is a timer sensitive protocol. If possible, I want to use one timer to manage both UARTs.

The speed I'm aiming for is 9600bps, and my microcontroller has a crystal speed of 22.1184Mhz. Also, is my code optimized or could I optimize it further so that fewer clock cycles are required for serial processing?

  RX equ P3.0 ;receive bit
  TX equ P3.1 ;xmit bit
  sermode equ 23h ;serial mode.
  SWBUF equ 22h     ;stored data
  SWTBUF equ 24h    ;stored data temporarily
  SWI bit 0h    ;1=received valid data

  org 0000h ;machine start
  ljmp startapp

  org 000Bh ;Timer interrupt
  ljmp timerint

  org 0030h

  timerint:
push PSW
mov C,RX ;get bit asap
push ACC
mov TH0,#0FFh ;reset high timer byte
mov A,sermode
jnz serhalfbit
  ;entered every half bit time if sermode=0
  ;do nothing till bit is zero
  jc nostart
    ;set mode to 1
    inc sermode
    ;set access speed to slow
    mov TL0,#040h
    ;prepare to exit
    sjmp extimerint
  nostart:
serhalfbit:
jz serfullbit
  ;this is entered every full bit time if sermode > 0
  jnb ACC.0,noend
    jnb ACC.3,noend
      ;if sermode=9, reset it...
      mov sermode,#0h
      ;set usable buffer to temporary buffer value
      mov SWBUF,SWTBUF
      ;set SWI to stop bit value. 1=valid data...
      mov SWI,C
      ;set access speed to fast
      mov TL0,#0A0h
    sjmp extimerint
  noend:
  ;if sermode=1 to 8, get bit into a buffer and increment mode
  mov A,SWTBUF
  RRC A
  mov SWTBUF,A
  inc sermode
serfullbit:
extimerint:
;common exit from interrupt
pop ACC
pop PSW
  reti

  startapp:
mov P1,#0FFh        ;reset GPIO
mov P3,#0FFh
mov sermode,#0h ;start at beginning
mov TH0,#0FFh
mov TL0,#0A0h   ;9.6kbps half bit time
mov TMOD,#11h   ;16-bit timers
setb PT0        ;timer 0=high priority
setb TR0        ;timer 0 on
mov IE,#81h         ;en Timer 0 int

bigloop:
; --async function here--
jnb SWI,novalid
  clr SWI
  mov A,SWBUF
  ; A=received serial data
novalid:
sjmp bigloop


texts:
I'm working on a Game Of Life clone as my first project. I'm still relatively new to programming, so my code is probably not really optimised.

The biggest bottleneck is in my Start() method, but that contains a lot of Unity3D specific methods which most people here probably don't know about. That's why I'm leaving that out.

My second bottleneck is somewhere in my Update() method. In here, I'm looping through my array which is currently 100 by 100 large, 10.000 in total.

I've been checking with the built-in profiler of Unity3D, and this reports that the biggest bottleneck is the garbage collection.

I also tried to put half of the loop in another thread, but that didn't work out properly, because it needs to look up cells in the other half.

If you see any other ways to improve my code, and not just the performance, feel free to let me know. But please, keep it simple, as I'm still relatively new to programming.

The relevant code:

void Update()
{
    timeElapsed += Time.deltaTime;                  // this will add deltaTime to timeElapsed,
    if (timeElapsed >= timeBetween)                 // until timeElapsed exceeds timeBetween,
    {                                               // which allows a new generation to be calculated
        timeElapsed -= timeBetween;
        if (gameState == GameState.Game_Playing)
        {
            grid = CheckAdjacent(grid);             // draw new generation
            UpdateInformation();                    // update information variables
        }
    }
}

public static void DrawGeneration(bool[,] grid)
{
    for (int x = 0; x < gridX; x++)
    {
        for (int y = 0; y < gridY; y++)
        {
            cubeGrid[x,y].renderer.enabled = grid[x,y]; // enables the renderer for active cells.
        }
    }
}

private void UpdateInformation()
{
    generation++; //counts the generations
}

public static int GetAliveCells ()
{
    int i = 0;
    for (int x = 0; x < gridX; x++)
    {
        for (int y = 0; y < gridY; y++)
        {
            if (grid[x, y]) // counts the number of alive cells
                i++;
        }
    }
    return i;
}

bool IsCellAlive(int adjacentCount, bool isAlive)
{
    if (isAlive)
        return liveRule.Contains(adjacentCount);
    else
        return becomeAliveRule.Contains(adjacentCount);
}

private bool[,] CheckAdjacent(bool[,] grid)
{
    int adjacentSquares = 0;
    bool[,] newGrid = new bool[gridX, gridY];

    for (int x = 0; x < gridX; x++)
    {
        for (int y = 0; y < gridY; y++)
        {
            adjacentSquares = 0;

            if (grid[calcX(x - 1), calcY(y - 1)])
                adjacentSquares++;
            if (grid[calcX(x), calcY(y - 1)])
                adjacentSquares++;
            if (grid[calcX(x + 1), calcY(y -1)])
                adjacentSquares++;

            if (grid[calcX(x - 1), calcY(y)])
                adjacentSquares++;
            if (grid[calcX(x + 1), calcY(y)])
                adjacentSquares++;

            if (grid[calcX(x - 1), calcY(y + 1)])
                adjacentSquares++;
            if (grid[calcX(x), calcY(y + 1)])
                adjacentSquares++;
            if (grid[calcX(x + 1), calcY(y + 1)])
                adjacentSquares++;

            newGrid[x,y] = IsCellAlive(adjacentSquares, grid[x,y]);
        }
    }
    return newGrid;
}

private int calcX(int x)
{
    x += gridX;
    return (x % gridX);
}

private int calcY(int y)
{
    y += gridY;
    return (y % gridY);
}


texts: Longest Alternating Substring Code Challenge

texts:
I'm still new to C++ and tried one of the harder challenges on a coding practice/challenge website.
The challenge was the following:

Given a string of digits, return the longest substring with alternating odd/even or even/odd digits. If two or more substrings have the same length, return the substring that occurs first.

I was able to solve it in ~ 50 minutes, but I feel like my code is really sloppy. Can anyone give me tips on how to simplify this? I find myself falling into very complex ways of solving things often.

std::string longestSubstring(std::string digits) {
    std::string strOddEven{};
    std::vector<std::string> vecOddEven{};
    bool next{};
    int maxSize{};

    for (int i = 0; i < digits.size() - 1; ++i)
    {
        if ((digits.at(i) % 2 == 0 && digits.at(i + 1) % 2 != 0) ||
            (digits.at(i) % 2 != 0 && digits.at(i + 1) % 2 == 0))
        {
            strOddEven += digits.at(i);
            next = true;
            if (i == digits.size() - 2)            // add to strOddEven and push_back
            {                                      // in case of longest string being at end
                strOddEven += digits.at(i + 1);
                vecOddEven.push_back(strOddEven);
            }
        }
        else if (next)
        {
            strOddEven += digits.at(i);
            vecOddEven.push_back(strOddEven);
            strOddEven = "";
            next = false;
        }
    }

    for (auto& i : vecOddEven)
        if (i.size() > maxSize)
            maxSize = i.size();

    for (auto& i : vecOddEven)
        if (i.size() == maxSize)
            return i;
}


texts: Functor to compare two floats with tolerance

texts:
What do you think about this implementation of 2 floats comparison functor considering how tolerance is introduced?

class Less
{
private:
    float m_tolerance;

public:
    Less(const float tolerance)
        : m_tolerance(tolerance)
    {

    }

    bool operator()(const float f1, const float f2) const
    {
        const bool toCloseToCompareSmaller = (std::abs(f2 - f1) < m_tolerance);
        const bool isSmaller = (f1 < f2);
        return !toCloseToCompareSmaller && isSmaller;
    }

    ~Less()
    {
    }
};


texts:
I am developing a workflow to perform a variety of operations on raster dataset using rasterio. My previous workflow involved lots of I/O when performing such operations on raster files. I would like to change the workflow so to process raster data in-memory. I am using rasterio.MemoryFile() class to achieve that. Here some of my code:
@contextmanager
def mem_file(arr, metadata, *to_del_arr):
    """
    Create and yield a Datareader using a numpy array
    and raster metadata
    """
    with rasterio.MemoryFile() as memfile:
        with memfile.open(**metadata) as src: # Open as DatasetWriter
            if arr.ndim == 2:
                src.write_band(1, arr)
            else:
                src.write(arr.astype(metadata['dtype']))
            for arr in to_del_arr:
                del arr

        with memfile.open() as src:  # Reopen as DatasetReader
            yield src

@contextmanager
def resample_raster(src, scale=2):
    """
    resample raster
    """
    t = src.transform

    # rescale the metadata
    transform = rasterio.Affine(t.a / scale, t.b, t.c, t.d, t.e / scale, t.f)
    height = src.height * scale
    width = src.width * scale

    new_meta = copy.deepcopy(src.meta)
    new_meta.update(transform=transform, driver='GTiff', height=height,
                    width=width)

    # resampling
    arr = src.read(resampling=rasterio.enums.Resampling.nearest)
    return mem_file(arr, new_meta, arr)

@contextmanager
def create_raster_mask(src, vals):
    """
    create a raster mask

    """
    arr = src.read()
    mask_arr = np.ma.MaskedArray(arr, np.in1d(arr, vals))
    new_meta = copy.deepcopy(src.meta)
    new_meta.update(driver='GTiff', nbits=1)
    return mem_file(mask_arr.mask, new_meta, arr, mask_arr)

@contextmenager
def another_operation(src):
    pass

The idea is to chain this operations together to build a workflow. Right now I can do that like so:

if __name__ == "__main__":
    with rasterio.open("tests/T37MBN_20190628T073621_SCL_20m.jp2") as src:
        print(src.meta)
        with resample_raster(src) as resampled:
            print(resampled.meta)
            with create_raster_mask(resampled, [3,7,8,9,10]) as mask:
                print(mask.meta)

But I would like to avoid such nested structure and have something more like:
if __name__ == "__main__":
    with rasterio.open("tests/T37MBN_20190628T073621_SCL_20m.jp2") as src:
        final = create_raster_mask(resample_raster(src))
        print(final.meta)

Is there a way I can achieve that?
Thanks


texts: Project Euler 7: 10001 Prime in Functional Programming (FP)

texts:
I wanted to practice functional programming (fp) without using any library but using vanilla JS only. So I took a problem from Project Euler:

  By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can
  see that the 6th prime is 13.

  What is the 10 001st prime number?

This is my solution:

(function () {
  'use strict';

  function* checkForPrime(n) {
    let m = Math.floor(Math.sqrt(n) + 1);
    while (true) {
      if (n < 2) {
        yield false;
        return;
      }
      if (m < 2 || n === 2 || n === 3) {
        yield true;
        return;
      }
      if (n % m === 0) {
        yield false;
        return;
      }
      m--;
    }
  }

  const isPrime = n => checkForPrime(n)
    .next();

  function* searchForPrimeNumbers(max) {
    let primeCounter = 0;
    let newPrimeNumber = 1;
    let runningNumber = 1;
    while (true) {
      if (primeCounter === max) {
        yield newPrimeNumber;
        return newPrimeNumber;
      }
      if (isPrime(runningNumber)
        .value) {
        newPrimeNumber = runningNumber;
        primeCounter = primeCounter + 1;
      }
      runningNumber++;
    }
  }

  const finalsolution = searchForPrimeNumbers(1e4 + 1);

  const findPrimeTill10001 = () => {
    return finalsolution.next()
      .value ? finalsolution.next()
      .value : findPrimeTill10001();
  };

  const solution = findPrimeTill10001();
  console.log(solution);
})();

As you can see, it is not consistent with the idea of FP. First I wanted to write it using recursion but I hit the stack limit. Therefore I used generators (and loops). That was the only solution I could come up with that resembles FP.

Any suggestions how to write in FP without any additional FP-Library (i.e. in pure JS only) is much appreciated.


texts:
I saw this interview question in the book Cracking the Coding Interview:

  Implement an algorithm to determine if a string has all unique characters

The authors solution uses bit-shifting for a pretty efficient solution.

I wanted to give it a shot to discover some new things and practice some. I'd like for this to be a discussion of how I can improve my programming and also, what the correct answer may be. Did I leave out any edge-cases? Is there a more efficient way of doing this?

#include <iostream>
#include <string>
#include <map>

using namespace std;

// Uses an iterator to display the map.
void displayMap(map<char, int> displayCharacters)
{
    for (map<char, int>::iterator itr = displayCharacters.begin(), end = displayCharacters.end(); itr != end; ++itr)
    {
        cout << itr->first << " --> " << itr->second << endl;
    }
}

// Checks for uniqueness for a given string and returns a boolean.
bool isUnique(int stringLength, string alphabet, map<char, int> uniqueCharacters)
{
    for (int i = 0; i < stringLength; i++)
    {
        if (uniqueCharacters[alphabet[i]] == 1)
        {
            return false;
        }

        uniqueCharacters[alphabet[i]]++;
    }

    return true;
}

// Maps individual characters found in stringRead and sets a value to them.
// Returns the mapped map.
map<char, int> readString(string stringRead, map<char, int> uniqueCharacters)
{
    for (int i = 0, strLen = stringRead.length(); i < strLen; i++)
    {
        uniqueCharacters[stringRead[i]] = 0;
    }

    return uniqueCharacters;
}

int main()
{
    // Create a map to store a key character and value int.
    // Create a string to hold a variable string to test.
    map<char, int> uniqueCharacters;
    string testString = "aaabbbccc";
    int stringLength = testString.length();

    // uniqueCharacters is mapped to the above string and the displayed using displayMap.
    uniqueCharacters = readString(testString, uniqueCharacters);
    displayMap(uniqueCharacters);

    if (isUnique(stringLength, testString, uniqueCharacters))
    {
        cout << "Unique string!\n";
    }
    else
    {
        cout << "Not unique!\n";
    }

    cin.ignore();
    cin.get();
}


texts:
How could I simplify the onCreate() method? Maybe via compact and properly-named methods?

public class FilterActivity extends FragmentActivity {
    private Bundle args;
    private FilterFragment filterFragment;

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

        if (savedInstanceState == null) {
            args = getIntent().getExtras();
        } else {
            args = savedInstanceState.getBundle(Keys.args);
        }

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        filterFragment = new FilterFragment();
        filterFragment.setArguments(args);
        if (savedInstanceState == null) {
            fragmentTransaction.add(R.id.containerOfFilterFragment, filterFragment);
        } else {
            fragmentTransaction.replace(R.id.containerOfFilterFragment, filterFragment);
        }
        fragmentTransaction.commit();

        filterFragment = (FilterFragment)
                getSupportFragmentManager().findFragmentById(R.id.containerOfFilterFragment);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBundle(Keys.args, args);
    }
}


texts: Setting a page number from the URL, with fallbacks

texts:
I have the following code, but it somehow looks a bit redundant.
As I am new to ColdFusion, I am not sure how to optimize it. Can someone suggest an alternative?

<cfparam name="url.idInfopage" default="0">
<cfif  not isNumeric(url.idInfopage)><cfset url.idInfopage= 0></cfif>

<cfif isDefined("stElement.idInfopage") and isNumeric(stElement.idInfopage)>
    <cfset idInfopage= stElement.idInfopage>
    <cfif  idInfopage is ""><cfset idInfopage= 0></cfif>
<cfelse>
    <cfset idInfopage= url.idInfopage>
</cfif>


texts: Smooth sidebar toggle animation with vuejs and tailwind

texts:
I'm making a slide sidebar with vuejs and tailwind. It works but feels kind of sluggish. Is there a way to make it smoother ?
working example: https://codepen.io/tuturu1014/pen/oNzRXeW
<button @click="isOpen = !isOpen" class="bg-blue-200 p-5">
  Open
  Close
</button>

  <transition name="slide">

sidebar

  </transition>

    content


texts:
This question is NOT about passing a Comparison to a Sort.

The question is how to pass a Comparison to an object for object to object  (1:1) Comparison.   Some users must be able to pass in a Comparison.  They want 2 as want be able to tell when they give different comparison.

The way this solution approaches it is to pass a Comparison delegate to the constructor.

static int CompareMotorPrice(Motorcycle motorcycle1, Motorcycle motorcycle2)
{
    return motorcycle1.Price.CompareTo(motorcycle2.Price);
}
static int CompareMotorSpeed(Motorcycle motorcycle1, Motorcycle motorcycle2)
{
    return motorcycle1.Speed.CompareTo(motorcycle2.Speed);
}
public class Motorcycle : IComparable
{
    public string Name { get; }
    public int Speed { get; set; }
    public int Price { get; set; }
    public Comparison<Motorcycle> CompareDelegate { get; set; }
    public Comparison<Motorcycle> CompareDefault { get; set; }
    public int CompareViaDelegate(Motorcycle motorcycle2)
    {
        if (CompareDelegate == null || motorcycle2 == null)
        {
            throw new ArgumentNullException();
        }
        return (CompareDelegate(this, motorcycle2));
    }
    public int CompareTo(object obj)
    {
        if (obj == null) return 1;

        Motorcycle otherMotorcycle = obj as Motorcycle;
        if (otherMotorcycle != null)
        {
            if (CompareDefault == null)
            {
                return (this.Name.CompareTo(otherMotorcycle.Name));
            }
            else
            {
                return CompareDefault(this, otherMotorcycle);
            }
        }
        else
        {
            throw new ArgumentException("Object is not a otherMotorcycle");
        }
    }
    public Motorcycle(string name, int price, int speed, Comparison<Motorcycle> compareDefault = null, Comparison<Motorcycle> compareDelegate = null)
    {
        Name = name;
        Price = price;
        Speed = speed;
        CompareDelegate = compareDelegate;
        CompareDefault = compareDefault;
    }
}

test:

Motorcycle motorcycle1 = new Motorcycle("harley", 1000, 120, CompareMotorSpeed, CompareMotorPrice);
Motorcycle motorcycle2 = new Motorcycle("yamaha", 1900, 130, CompareMotorSpeed, CompareMotorPrice);
Motorcycle motorcycle3 = new Motorcycle("susuki", 1800, 150, CompareMotorSpeed, CompareMotorPrice);
Debug.WriteLine(motorcycle1.CompareViaDelegate(motorcycle2));
List<Motorcycle> Motorcycles = new List<Motorcycle>() { motorcycle1, motorcycle2, motorcycle3 };
foreach (Motorcycle m in Motorcycles)
{
    Debug.WriteLine($"name {m.Name}   price {m.Price}   speed {m.Speed}");
}
Motorcycles.Sort(CompareMotorPrice);
foreach (Motorcycle m in Motorcycles)
{
    Debug.WriteLine($"name {m.Name}   price {m.Price}   speed {m.Speed}");
}
Motorcycles.Sort();
foreach (Motorcycle m in Motorcycles)
{
    Debug.WriteLine($"name {m.Name}   price {m.Price}   speed {m.Speed}");
}


texts:
I have tried to create a stopwatch and I have done but I don't know how to improve it, and I want the user control the stopwatch whether it (Start) or (Stop), I'll be thankful if you tell me what I can do to improve my code.

StopWatch.cs

public class StopWatch
{
    private DateTime _startTime;
    private DateTime _stopTime;
    private bool _timeRunning = false;

    public void Start(DateTime Start)
    {
        if (!_timeRunning)
        {
            _startTime = Start;
            _timeRunning = true;
        }
        else
            throw new InvalidOperationException("Stopwatch is already running!");
    }

    public void Stop(DateTime Stop)
    {
        if (_timeRunning)
        {
            _stopTime = Stop;
            _timeRunning = false;
        }
    }

    public TimeSpan GeTime()
    {
        var duration = _stopTime - _startTime;
        return duration;
    }
}

Program.cs

class Program
{
    static void Main(string[] args)
    {
        var stopwatch = new StopWatch();

        stopwatch.Start(DateTime.Now);

        for (int i = 0; i < 1000; i++)
        {
            Thread.Sleep(10);
        }

        stopwatch.Stop(DateTime.Now);

        Console.WriteLine(@"Time Elapsed : {0:hh\:mm\:ss}", stopwatch.GeTime());
    }


texts:
I am creating routes from an array of menuItems. I have written a recursive function, which works fine but I think the code can be improved. So, I need you guys to review my code and suggest me some changes.

Here is the code:

const accumulator = [];
const renderRoutes = (_menuItems) => {
  _menuItems.forEach((menuItem) => {
    accumulator.push(
      <Route
        exact
        path={menuItem.path}
        render={props => (
          <Scene
            {...props}
            menuItem={menuItem}
          />
        )}
      />,
    );
    if (menuItem.children) {
      renderRoutes(menuItem.children);
    }
  });
  return accumulator;
};


texts:
I need to create variable-length strings of dots/periods/full-stops to add to some text content, in a way that is similar to a formatted table-of-contents:

Chapter 1 .................................... 1
  Section 1.1 ................................ 1
  Subsection 1.1.2 .......................... 12

I know that things like String.format exist, but that is not suitable for formatting periods this way.

The code is complicated by the need for there to be many threads doing similar work at the same time.

I have written this utility class that caches a 'base' string in a Thread-local, and uses that to supply the required data.

Are there any alternatives, improvements, or other recommendations you have?

public final class DotPadding {

    private static final ThreadLocal<String> PAD_BASE = new ThreadLocal<String>() {
        @Override
        protected String initialValue() {
            return "................";
        }
    };

    public static final String getPadding(final int length) {
        if (length <= 0) {
            return "";
        }
        String base = PAD_BASE.get();
        if (base.length() >= length) {
            return base.substring(0, length);
        }
        while (base.length() < length) {
            base = base.concat(base);
        }
        PAD_BASE.set(base);
        return base.substring(0, length);
    }

}

As an example usage, this is one of the ways that the above code is used. There are other places too:

String description = getFormattedDescription(title);
String index = getFormattedIndex(page);
String line = description
            + " "
            + DotPadding.getPadding(width - (2 + description.length() + index.length()))
            + " "
            + index;
System.out.println(line);


texts: Compressing a stream asynchronously, and returning a byte[]

texts:
Assuming I have to leave the contract intact (take byte[] and return byte[]), what's the correct way to structure this asynchronous method?

Will this deadlock running in ASP.NET in a web server thread?

public async Task<byte[]> CompressAsync(byte[] buffer)
{
    using (var outStream = new MemoryStream())
    {
        using (var tinyStream = new GZipStream(outStream, CompressionMode.Compress))
        using (var stream = new MemoryStream(buffer))
        {
            await stream.CopyToAsync(tinyStream);
        }

        return outStream.ToArray();
    }
}


texts: Performing redirects based on taxonomy terms associated with nodes

texts:
This code performs 301 redirects based on the taxonomy terms associated with the node, as 301 redirects can adversely effect page load time. How could this be best optimized?

 <?php
    /**
     * Implementation of hook_init().
     *calling this hook causes the code below to execute before the page is loaded
     */

    function region_filter_init() {}
     //hook "nodeapi" is called when we are doing something to the node, in this "case" we are "viewing" the node.

    function region_filter_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {

      switch ($op) {

        case 'view':

            if( (arg(1) == 0)){ } //do not execute on homepage. if there are no aruments after the base url in arument one is thedelimagazine.com/argument1, if this is 0 then do nothing.

          else {

            $region = getRegion(); //get current region from deli.mmodule

            $national = 'national'; //store string 'national' in variable

            $count = count($node->taxonomy);//nstores number of key/value pairs in array,  if two terms are selected with the node/post then count == 2

            $terms = array();//initialize terms to array
            foreach($node->taxonomy as $term) {
              $terms[$term->name] = $term->name; //prints array of individual terms

            }

        /*case 1 new england*/

        //if there are less than 9 terms  and more than 2 and new england is in the array redirect to new england
        if( $count < 9 &&  $count > 2 && in_array('newengland', $terms) && $region != 'newengland')
        {
          $link = 'http://newengland.thedelimagazine.com/' . drupal_get_path_alias("node/$node->nid", $path_language = '');
              drupal_goto($link, $query = NULL, $fragment = NULL, $http_response_code = 301);
        }
        /*END case 1 new england*/

          /*case 2*/
              if($count == 2 && in_array('national', $terms) && is_numeric(arg(1))) { //if there are 2 terms in taxonomy && national is one of them & the first argument in url is a number such as thedelimagazine.com/12345 (before alias redirect)
              unset($terms['national']);        //remove national from array
              $value = array_shift($terms) ;//set value to the other term left. in array
              if($value == 'los angeles') {//fix for los angelas, because in deli module taxonomy term and subdomain are different only for los angeles
                $value = 'la';
              }

              if($region != $value) { //if region does not already = term (would cause redirect loop)

                  $link = 'http://' . $value . '.thedelimagazine.com/' . drupal_get_path_alias("node/$node->nid", $path_language = '');//go to term left in $value

                  drupal_goto($link, $query = NULL, $fragment = NULL, $http_response_code = 301);//drupal redirect function
              }
            }

            /* ++ END case 2++*/

            /* ++case 3 national+++*/
            else {

        if($count > 10  && in_array('national', $terms)  && $region != 'national' ) {    //if there are moer than 10 terms and national is in the array $terms, and the current region does not already =national
              $link = 'http://national.thedelimagazine.com/' . drupal_get_path_alias("node/$node->nid", $path_language = '');//then set $link to national.thedelimagazine.com.  drupl get path alias gets the path to the node and node id and converts it to clean readable urls that i implemented last year.
              drupal_goto($link, $query = NULL, $fragment = NULL, $http_response_code = 301);     //go to the $link
        }
             /* ++ END case 3 national++*/

             }
         }
          break;
      }
    }


texts:
I recently created one of my first hover effects using HTML and SASS.  Since it is my first hover effect, I'm almost positive that is it horribly inefficient.  I'm sure there's a way to do this effect using half the number of lines of code, but I can't figure out any ways to do it.  The hover effect in question is for the "envelop" logo at the top left.

Here's a codepen of my page so far.

HTML

(

envelop

)

finish navbar, mobile version formatting is still fucked up....

CSS (SASS)

$green: #4ede96;
$logoAnimationTime: 0.2s;

@mixin mLogoEffect_pre
{
    color: white;
    font-size: 48px;
    display: inline-block;
    transition: $logoAnimationTime 0 ease;
    opacity: 0;
}

header
{
    height: 100px;
    width: 100%;
    background: $green;
    position: fixed;
    top: 0;
    @media only screen and (min-device-width : 320px) and (max-device-width : 480px)
    {
        height: 200px;
    }

    .logocontainer
    {
        @media only screen and (min-device-width : 320px) and (max-device-width : 480px)
        {
            margin-left: 35%;
            display: block;
        }
        padding-top: 15px;
        display: inline-block;

        > a
        {
            text-decoration: none;

            .logo
            {
                margin-top: 0;
                font-family: 'Merriweather', serif;
                font-size: 48px;
                padding: 0 50px;
                color: white;
                display: inline-block;

            }

            .logoeffect-left
            {
                @include mLogoEffect_pre;
                margin-left: 70px;
                margin-right: -80px;
                margin-top: 0;
                margin-bottom: 0;
            }

            .logoeffect-right
            {
                @include mLogoEffect_pre;
                margin-left: -80px;
                margin-top: 0;
                margin-bottom: 0;
            }

            &:hover
            {
                .logoeffect-left
                {
                    transition: $logoAnimationTime 0 ease;
                    margin-right: -50px;
                    margin-left: 40px;
                    opacity: 1;
                    @media only screen and (min-device-width : 320px) and (max-device-width : 480px)
                    {
                        //dont change anything (hide animation)
                        @include mLogoEffect_pre;
                        margin-left: 70px;
                        margin-right: -80px;
                        margin-top: 0;
                        margin-bottom: 0;
                    }
                }
                .logoeffect-right
                {
                    transition: $logoAnimationTime 0 ease;
                    margin-left: -50px;
                    opacity: 1;
                    @media only screen and (min-device-width : 320px) and (max-device-width : 480px)
                    {
                        //dont change anything (hide animation)
                        @include mLogoEffect_pre;
                        margin-left: -80px;
                        margin-top: 0;
                        margin-bottom: 0;
                    }
                }
            }
        }

    }

}


texts:
I have an input[type=range] element which is customized using CSS to look more modern.

I'm unhappy with my CSS because of the need to use position:relative on the wrapping element and position:absolute on an invisible range input.

I'm wondering if I made this logic unnecessarily convoluted. Is there a way to achieve the same presentation in a simpler manner? Maybe just by customize the input itself instead of hiding and emulating it?

Here's a JSFiddle and here is the accompanying CSS and HTML:

        01:47

        <input class="time-range" type="range" />

        03:36

*, *:before, *:after {
    box-sizing: border-box;
}

input:focus, button:focus {
    outline: none
}

.time-progress {
    display: flex;
    align-items: center;
    width: 300px;
    margin-top: 30px;
    margin-left: 30px;
}

.time-label {
    margin: 0 5px;
}

.time-slider {
    background: #ebebeb;
    height: 3px;
    flex: 1;
    margin: 0 10px;
    position: relative;
}

.progress {
    background: #4ea6ea;
    height: 100%;
}

.time-range {
    bottom: -1px;
    position: absolute;
    width: 100%;
}

input[type=range] {
    -webkit-appearance: none;
    background: transparent;
    height: 1px;
}

input[type=range]::-webkit-slider-thumb {
    -webkit-appearance: none;
    box-shadow: 0 0 5px #666666;
    background: #666666;
    border-radius: 100%;
    height: 10px;
    width: 10px;
}


texts: Finding shortest distance between a point and a surface using Lagrange Multipliers

texts:
I am new to Matlab. Now I need to find the shortest distance between a given point to a surface, which is describe with a function.

I am planing to implement the method described in the link below with Lagrange Multipliers, and have writen my code to do that. However, I found my code runs slowly.

https://math.stackexchange.com/questions/175624/finding-shortest-distance-between-a-point-and-a-surface

My code is as following:

% the function return the points with their distances to the surface (fun), and the corresponding points on the surface
function [ points_and_distance ] = getPoints( fun, var )
% m is the number of given points
m = 100;
% n is the dimension of variables, such as x, y, z, in my code I use x1, x2, x3, etc.
n = 3;
% given points are generated randomly, and this step is not the bottleneck
points = gen_points(m, n);
% l is used as the Lagrange Multiplier, an extra variable
syms l
fun_l = l * fun;
%expand var
var(n+1) = l;
% Each row of points_and_distance is the given point and the corresponding point on the surface with a shortest distance to the given point, and their distance, so the column number is 2*n+1
points_and_distance = zeros(m, 2*n+1);
tb=clock;
for i=1:m
    p = points(i, :);
    % Construct the Lagrangian function based on a given point
    for j=1:n
        fun_l = fun_l + (var(j) - p(j))^2;
    end
    tic;
    points_and_distance(i, :) = getDistance(fun_l, n+1, var, p);
    ct_each = toc;
    disp(['Get distance for ',num2str(i),'th point consumes: ',num2str(ct_each), 's']);
end
comsumedtime = etime(clock, tb);
disp(['Get distance for ',num2str(m),' points consumes totally: ', num2str(comsumedtime), 's']);
% sorting the result based on the distance column
points_and_distance = sortrows(points_and_distance, 4);
end

The definition of getDistance is as follows:

function [ rst ] = getDistance( func, n, x, x0 )
% Return Top-K records with shortest distance to given surface, which is described with func.
%
% input:
% Function func: the surface
% n: Number of variables in func
% x: Array of variables
% x0: given point
% Get Differentiation of each variable x(i)
% Each partial differentiation is stored in an array of functions
for i = 1:n
    eqs(i) = diff(func, x(i));
end
% Slove the equations
sol = solve(eqs, x);
% There may be multiple solutions. For each row of solutions, calculating the distance to x0
cur_sol = zeros(1, 4);
for r = 1:size(sol.x1, 1)
    min_dis = 0;
    t_dis = sqrt((sol.x1(r) - x0(1))^2 + (sol.x2(r) - x0(2))^2 + (sol.x3(r) - x0(3))^2)
    if min_dis == 0 || min_dis > t_dis
        % here I use n = 3, so there are three variables in func, which are represented with x1, x2, and x3.
        % In the fact, I did not find the way to return the solution of arbitrary variable, which may be represent as
        % sol.x(i) or something like that, where x is the array of symbolic variables. I have to hard code to use sol.x1, sol.x2.
        cur_sol(1) = double(sol.x1(r));
        cur_sol(2) = double(sol.x2(r));
        cur_sol(3) = double(sol.x3(r));
        min_dis = t_dis;
        cur_sol(4) = double(min_dis);
    end
end
% record the solution, i.e. the closest point on the surface, the distance to the given point x0, and x0
rst(1:4) = cur_sol(:);
rst(5:7) = x0(:);
end

I run the code hundreds of times, when m = 100 and n = 3, the average time consumed is about 300ms, when m = 100 and n = 10, the time can be 30s, which is too slow and not expected. I thought my code could be optimized to run faster. Since this is my first Matlab project and I have looked into the way to reduce loop, but still cannot improve it.


texts:
This is my first time using C++ Templates to make a data structure. I have written a program to implement a stack of up to 5 items.

#include<iostream>
#include<iomanip>

using namespace std;

template<class T>
class Queue{
private:
    T arrays[5];
    int i; //empty stack
public:
    Queue()
    {
        arrays[5] = {0}; //Empty stack
        i = -1; //Setting stack to be empty
    }
    T PUSH(T item)
    {
        if(i == 4)
        {
            cout << "Stack is full" << endl;
        }
        else
        {
        i++;
        arrays[i] = item;
        }
    }
    T POP()
    {
        if(i == -1)
        {
            cout << "Stack is empty" << endl;
        }
        else
        {
        cout << arrays[i] << " has been popped" << endl;
        i--;

        }
    }
    T TOP()
    {
        if(i == -1)
        {
            cout << "Stack is empty" << endl;
        }
        else
        {
        cout << "Element at top of stack is " << arrays[i] << endl;
        }
    }

};

int main()
{
    Queue <int> Q;
    int option,push;
    do{
    cout << "Select any of the following option" << endl;
    cout << "1.Push\n2.Pop\n3.Top\nPress any other button to exit" << endl;
    cin >> option;

    switch(option)
    {
        case 1:
            cout << "Which element to push" << endl;
            cin >> push;
            Q.PUSH(push);
            break;
        case 2:
           Q.POP();
            break;
        case 3:
           Q.TOP();
            break;
        default:
            cout << "Error!" << endl;
            break;

    }
    }while(option < 4);
return 0

}

Though I have got the program working. I would like to ask if there is any way I can improve on the code.


texts: Part 1: Create or update record via HTTP request

texts:
Update:
This is an older version of the question/script. The new version can be found here: Part 2: Create or update record via HTTP request

I have an external system that sends an HTTP request to a Jython script (in IBM's Maximo Asset Management platform).
The Jython 2.7.0 script does this:

Accepts an HTTP request: http://server:port/maximo/oslc/script/CREATEWO?_lid=wilson&_lpwd=wilson&f_wonum=LWO0382&f_description=LEGACY WO&f_classstructureid=1666&f_status=APPR&f_wopriority=1&f_assetnum=LA1234&f_worktype=CM
Loops through parameters:

Searches for parameters that are prefixed with f_ ('f' is for field-value)
Puts the parameters in a list
Removes the prefix from the list values (so that the parameter names match the database field names).

Updates or creates records via the parameters in the list:

If there is an existing record in the system with the same work order number, then the script updates the exiting record with the parameter values from the list.
If there isn't an existing record, then a new record is created (again, from the parameter values from the list).

Finishes by returning a message to the external system (message: updated, created, or other (aka an error)).

Can the script be improved?

from psdi.mbo import SqlFormat
from psdi.server import MXServer
from psdi.mbo import MboSet

params = list( param for param in request.getQueryParams() if param.startswith('f_') )
paramdict={}
resp=''
for p in params:
    paramdict[p[2:]]=request.getQueryParam(p)

woset = MXServer.getMXServer().getMboSet("workorder",request.getUserInfo())

#Prevents SQL injection
sqf = SqlFormat("wonum=:1")
sqf.setObject(1,"WORKORDER","WONUM",request.getQueryParam("f_wonum"))

woset.setWhere(sqf.format())

woset.reset()
woMbo = woset.moveFirst()

if woMbo is not None:
    for k,v in paramdict.items():
        woMbo.setValue(k,v,2L)
    resp = 'Updated workorder ' + request.getQueryParam("f_wonum")
    woset.save()
    woset.clear()
    woset.close()
else:
    woMbo=woset.add()
    for k,v in paramdict.items():
        woMbo.setValue(k,v,2L)
    resp = 'Created workorder ' + request.getQueryParam("f_wonum")
    woset.save()
    woset.clear()
    woset.close()
responseBody = resp

Note 1: Previously, there was an SQL injection vulnerability in the code. This issue has been resolved via the SQLFormat java class. The code has been updated.
Note 2: Unfortunately, I'm not able to import Python 2.7.0 libraries into my Jython implementation. In fact, I don't even have access to all of the standard python libraries.
Note 3: The acronym 'MBO' stands for 'Master Business Object' (it's an IBM thing). For the purpose of this question, a Master Business Object can be thought of as a work order record. Additionally, the constant 2L tells the system to override any MBO rules/constraints.


texts: Extract last record inserted for each key identifier

texts:
I have a table with this schema

ID, int primary key
PathKey, string not null
InsertDate, datetime not null
Value, int not null

In the table there are a medium-large number of records. 1632 different pathkey and 645627 total records
The PathKey is not unique (because I store also the old values).
You can identify a record with the ID or a PathKey with the
InsertDate.

I am developing a query to extract the last record for each path key, and this is the query I am using but is ugly and incredible slow.

SELECT *
FROM ArchiveData
WHERE ID IN (
        SELECT (
                SELECT TOP 1 ID
                FROM ArchiveData
                WHERE PathKey = AD.PathKey
                ORDER BY [InsertDate] DESC
                ) AS ArchiveDataID
        FROM ArchiveData AS AD
        GROUP BY PathKey
        )
ORDER BY PathKey

Any suggestions to improve, at least, the performance?


texts:
I'm quite new to JavaScript, and I'd like a review of the code structure and syntax. It serves this little online regexp test (still a work in progress).

The whole code (JavaScript, CSS & HTML) is on GitHub.

application.js:

function update_result_for(input, regexp_value) {
  var input_value   = input.val();
  var result_spans  = input.parent().children('span');
  if(!input_value || !$('#regexp').val()) {
    result_spans.hide();
  } else {
    var regexp = new RegExp(regexp_value);
    var result = regexp.exec(input_value);
    if(result) {
      var matched_string = result.shift();

      var submatches_list_string = jQuery.map(result, function(submatch, index) {
        return '$' + (index + 1) + ' = ' + submatch;
      }).join('; ');

      var regexp_to_highlight_matched_string          = new RegExp('(.*)' + matched_string + '(.*)');
      var regexp_to_highlight_matched_string_result   = regexp_to_highlight_matched_string.exec(input_value);
      var before_matched_string                       = regexp_to_highlight_matched_string_result[1];
      var after_matched_string                        = regexp_to_highlight_matched_string_result[2];
      var input_value_with_matched_string_highlighted   = 'matched: ' + before_matched_string + '' + matched_string + '' + after_matched_string;

      result_spans.filter(".submatches").text(submatches_list_string);
      result_spans.filter(".match").html(input_value_with_matched_string_highlighted);
      result_spans.filter(".ok").show('fast');
      result_spans.filter(".not_ok").hide();
    } else {
      result_spans.filter(".not_ok").show('fast');
      result_spans.filter(".ok").hide();
    }
  }
}

// from http://www.scottklarr.com/topic/126/how-to-create-ctrl-key-shortcuts-in-javascript/
var isCtrl = false;
$(document).keyup(function (e) {
    if(e.which === 17) isCtrl=false;
}).keydown(function (e) {
    if(e.which === 17) isCtrl=true;
    if(e.which === 69 && isCtrl) {
    $('#regexp').focus();
        return false;
    }
});

$(document).ready(function() {
  $('#regexp').focus();
  $('span.result').hide();
  $('input:not(#regexp)').live("keyup", function() {
    update_result_for($(this), $('#regexp').val());
  });
  $('input#regexp').keyup(function() {
    $('input:not(#regexp)').each(function(i) {
      update_result_for($(this), $('#regexp').val());
    });
  });
  $('a.add_example').click(function() {
    new_example = $('div#examples p:last').clone();
    new_example.children('input').attr('value', '');
    new_example.children('span').hide();
    new_example.insertBefore($(this));
    new_example.children("input").focus();
  });
});


texts: Can I improve this code for readability and/or performance?

texts:
I have some data that logs kWh. I want to be able to collect the data and produce a bar chart (I'm using the Microsoft ASP.Net Chart control). I have written code that works, but it looks a little clunky to me and I wondered if somebody could point out a method that may be easier to read and/or more efficient.

The data should normally constantly increase in value though it can be reset. As it is an accumulative value if the values from one period are the same as the previous period then I need to display zero for that time period. Then, when the value does increase, I need to display it as the difference between this period and the last period with a value.

I have the following code to collect the data at hourly intervals only:

      myValues = (from values in myEntities.PointValues
                      where
                        values.PointID == dataValue &&
                        SqlFunctions.DatePart("n", values.DataTime) == 0
                      orderby values.DataTime
                      select new BarChart
                        {
                          Time = values.DataTime,
                          Value = values.DataValue
                        }).ToList();

I then use the following code to set the values that are identical in consecutive periods to 0, though, of course, maintaining the first occurrence at its original value:

for (var i = 0; i < myValues.Count - 1; i++)
      {
        var j = 0;
        while (Math.Abs(myValues[i].Value - myValues[i + 1].Value) < double.Epsilon)
        {
          i++;
          j++;
          if (i == myValues.Count - 1) break;
        }
        while (j > 0)
        {
          myValues[i + 1 - j].Value = 0;
          j--;
        }
      }

Finally, I apply the following code to get the difference in values (difference between value this period and the last period with a positive value).

var subValue = double.MaxValue;
foreach (var t in myValues)
{
  if (t.Value > 0 && t.Value < subValue) subValue = t.Value;
  if (Math.Abs(t.Value - subValue) > double.Epsilon && Math.Abs(t.Value - 0) > double.Epsilon)
  {
    var j = t.Value;
    t.Value = t.Value - subValue;
    subValue = j;
  }
}

Which produces my final data.

As I say, this code works fine but if anyone can help with some optimizing/readability, it would be greatly appreciated.

EDIT:
For some images see:

https://stackoverflow.com/questions/14425230/can-anyone-assist-with-some-code-optimization


texts: C - Learning Linked Lists, Pointer Manipulation - Store some ints, print and free memory

texts:
I'm learning C, and wrote this program outside of my assignments in order to practice pointer manipulation and data structures, step by step. I want to ensure that this program follows well known conventions, has excellent style and readability, and uses pointers as efficiently as possible, before I move on to more complex structs.

I am aware I am not doing any error checking or type checking. I don't intend to export this code as-is, my intention is to practice with pointers. I found it easiest for now to keep the code as simple as possible and remove checking. This is also why I created the additional functions, just to help isolate parts of the code.

If appropriate, I'm also interested in modifying the freelist() function to work recursively, freeing the last node first. Currently, if the node order is {1,2,3}, 1 is freed first. I haven't been able to successfully call the function recursively to instead free the nodes from 3 then 2 then 1.

// This program stores N integers from user input into a
// linked list, prints the list, and then frees each node.

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

#define N 5

typedef struct _node {
    int value;
    struct _node *next;
} NODE;

int getinteger(void);
void printlist(NODE **head);
void freelist(NODE *head);

int main(void)
{
    NODE *start = NULL;

    for (int i = 0, n = 0; i < N; i++)
    {
        n = getinteger();

        NODE *newnode = (NODE *) malloc(sizeof(NODE));
        newnode->value = n;
        newnode->next = NULL;

        if (start == NULL)
        {
            start = newnode;
        }
        else
        {
            NODE *p = NULL;
            for (p = start; p->next != NULL; p = p->next)
                ;
            p->next = newnode;
        }
    }

    printlist(&start);
    freelist(start);
}

int getinteger(void)
{
    int n = 0;
    printf("Enter integer: ");
    scanf("%i", &n);
    return n;
}

void printlist(NODE **head)
{
    NODE **tracer = head;
    while ((*tracer) != NULL)
    {
        printf("%i\n",(*tracer)->value);
        tracer = &(*tracer)->next;
    }
}

void freelist(NODE *head)
{
    NODE *p = head;
    while (p != NULL)
    {
        NODE *next = p->next;
        free(p);
        p = next;
    }
}


texts: Which is better practice for this if elif… else statement?

texts:
If below piece of code has to be restructured to use but one single if-elif block, which is better? 1. or 2.?

A = int(input("Enter an integer(1~30): "))

if A % 6 == 0:
    print("A is even")
    print("A is even and a multiple of 6 (6, 12, 18, 24, 30).")
elif A % 10 == 0:
    print("A is even")
    print("A is even and a multiple of 10 (10, 20).")
elif A % 2 == 0:
    print("A is even")
    print("A is even and a number out of 2, 4, 8, 14, 16, 22, 26, 28.")
elif A % 3 == 0:
    print("A is odd")
    print("A is odd and a multiple of 3 (3, 9, 15, 21, 27).")
else:
    print("A is odd")
    print("A is 1 or a number out of 1, 5, 7, 11, 13, 17, 19, 23, 25, 29.")

if A % 2 == 0 and A % 3 == 0:
    print("A is even")
    print("A is even and a multiple of 6 (6, 12, 18, 24, 30).")
elif A % 2 == 0 and A % 5 == 0:
    print("A is even")
    print("A is even and a multiple of 10 (10, 20).")
elif A % 2 == 0 and A % 3 != 0 and A % 5 != 0:
    print("A is even")
    print("A is even and a number out of 2, 4, 8, 14, 16, 22, 26, 28.")
elif A % 2 != 0 and A % 3 == 0:
    print("A is odd")
    print("A is odd and a multiple of 3 (3, 9, 15, 21, 27).")
else:
    print("A is odd")
    print("A is 1 or a number out of 1, 5, 7, 11, 13, 17, 19, 23, 25, 29.")

This is part of a question in a school assignment and the problem is to reformat some code into the structure of
if
    …
elif
    …
elif
    …
else
    …

There are obviously better structures to avoid multiplicating print("A is even") but the question is to format it in the structure above.
So if the two above are the only options which is better and why?


texts:
I'm pretty new to the world of lock-free programming and would love some feedback on this code. I have been testing the queue with multiple producers and consumers, and with no unexpected output (yet). Is there anything I could have missed or should improve?

template <typename Type, std::size_t Capacity = 100>
struct concurrent_queue
{
    static_assert(Capacity > 2, "not enough room in queue!");

    bool try_push(Type const & object) const
    {
        auto past_writer = writer.load();
        auto next_writer = increment(past_writer);

        if (next_writer != reader.load())
        {
            if (writer.compare_exchange_weak(past_writer, next_writer))
            {
                array[past_writer] = object;

                return true;
            }
        }

        return false;
    }

    bool try_push(Type & object) const
    {
        auto past_writer = writer.load();
        auto next_writer = increment(past_writer);

        if (next_writer != reader.load())
        {
            if (writer.compare_exchange_weak(past_writer, next_writer))
            {
                array[past_writer] = std::move_if_noexcept(object);

                return true;
            }
        }

        return false;
    }

    bool try_pop(Type & object) const
    {
        auto past_reader = reader.load();
        auto next_reader = increment(past_reader);

        if (past_reader != writer.load())
        {
            if (reader.compare_exchange_weak(past_reader, next_reader))
            {
                object = std::move_if_noexcept(array[past_reader]);

                return true;
            }
        }

        return false;
    }

    bool empty() const
    {
        return reader.load() == writer.load();
    }

private:

    std::size_t increment(std::size_t index) const
    {
        return (index + 1) % Capacity;
    }

    mutable std::atomic_size_t reader { 0 };
    mutable std::atomic_size_t writer { 0 };

    mutable std::array<Type, Capacity> array;
};


texts: Largest palindrome made from the product of 3-digit numbers

texts:
I am given a task to write a program to find the largest palindrome made from the product of two 3-digit numbers. How can I improve this code?

def check_palindrome(s):
     """Checks whether the given string is palindrome"""

     if s == s[::-1]:
        return True

product_pal = []
for i in range (999,900,-1):
    for j in range (999,900,-1):
        product = i * j
        if check_palindrome(str(product)):
            product_pal.append(product)
            print"i =" , i , "j = ",j, "for", product
print max(product_pal)


texts: JavaScript circular linked list compatriot game

texts:
I found this question in O'Reilly Data Structure and Algorithm in Javascript:

  According to legend, the first-century Jewish historian Flavius
  Josephus was about to be captured along with a band of 40 compatriots
  by Roman soldiers during the Jewish-Roman War. The Jewish soldiers
  decided that they preferred suicide to being captured and devised a
  plan for their demise. They were to form a circle and kill every third
  soldier until they were all dead. Josephus and one other decided they
  wanted no part of this and quickly calculated where they needed to
  place themselves so they would be the last survivors.

  Write a program that allows you to place n people in a circle and
  specify that every mth person will be killed. The program should
  determine the number of the last two people left in the circle. Use a
  circularly linked list to solve the problem.

This is my solution:

function Node(element) {
    this.element = element;
    this.next = null;
}

function LList() {
    this.head = new Node("head");
    this.head.next = this.head;
    this.find = find;
    this.insert = insert;
    this.display = display;
    this.findPrevious = findPrevious;
    this.remove = remove;
    this.advance = advance;
    this.count = count;
}

function remove(item) {
    var prevNode = this.findPrevious(item);
    if (!(prevNode.next == this.head)) {
        prevNode.next = prevNode.next.next;
    }
}
function findPrevious(item) {
    var currNode = this.head;
    while (!(currNode.next == this.head) &&
        (currNode.next.element != item)) {
        currNode = currNode.next;
    }
    return currNode;
}
function display() {
    var currNode = this.head;
    while (!(currNode.next == this.head)) {
        print(currNode.next.element);
        currNode = currNode.next;
    }
}
function count() {
    var currNode = this.head;
    var count = 0;
    while (!(currNode.next == this.head)) {
        count++
        currNode = currNode.next;
    }
    return count;
}
function find(item) {
    var currNode = this.head;
    while (currNode.element != item) {
        currNode = currNode.next;
    }
    return currNode;
}
function insert(newElement, item) {
    var newNode = new Node(newElement);
    var current = this.find(item);
    newNode.next = current.next;
    current.next = newNode;
}

function advance(item, n) {
    var currNode = this.find(item);
    for (let i = n; i > 0; i--) {
        currNode = currNode.next;
    }
    return currNode;
}

function survivor(number, position) {
    //40 compatriots
    //kill every third soldier. advance by 3
    //last two survivors

    //place n people in a circle
    var compatroits = new LList();
    var currNode = compatroits.head;

    for (let i = 1; i <= number; i++) {
        compatroits.insert(i, currNode.element);
        currNode = currNode.next;
    }

    //kill every mth person in the circle
    //start from head
    var currItem = compatroits.head.element;
    while (compatroits.count() > 2) {
        //advance mth person
        var killNode = compatroits.advance(currItem, position);

        //set new start point to m.next node
        currItem = killNode.next.element;

        //remove mth person
        compatroits.remove(killNode.element);
    }

    //determine the last two people in the circle
    return compatroits.display();
}

Does anyone have a more efficient way to solve this problem?


texts:
I am currently using an enum in my Android application to display time periods:

Weekly
Bi-Weekly
Monthly
Quarterly
Yearly

I created the enum like this, because I wanted to know the description, and (roughly) number of days:

public enum SpendingPeriods {
    WEEKLY("Weekly", 7),
    BIWEEKLY("Bi-Weekly", 14),
    MONTHLY("Monthly", 30),
    QUARTERLY("Quarterly", 120),
    YEARLY("Yearly", 365);

    private final String description;
    private final int numDays;

    SpendingPeriods(String description, int numDays){
        this.description = description;
        this.numDays = numDays;
    }

    public String getDescription(){
        return description;
    }

    public int getNumDays(){
        return numDays;
    }
}

Now, I would like to localize the enum, and so far my only solution has been to remove the description from the constructor, and check Locale and switch based on number of days:

SpendingPeriods(int numDays){
        this.numDays = numDays;
        if(Locale.getDefault().getLanguage().equals("fr")){
            switch(numDays){
                case 7:
                    this.description = "Hebdomadaire";
                    break;
                case 14:
                    this.description="Bimensuel";
                    break;
                case 30:
                    this.description="Mensuel";
                    break;
                // Others
            }
        } else{
            // Fall back to English for unsupported languages
            switch(numDays){
                case 7:
                    this.description = "Weekly";
                    break;
                case 14:
                    this.description = "Bi-Weekly";
                    break;
                case 30:
                    this.description = "Monthly";
                    break;
                // Others
            }
        }
    }

I was hoping there would be a way to do this using a string-array in an XML file, but I can't seem to find anything like that. Is this okay practice? Is there a better way?


texts:
This is my first foray into the wild world of jQuery plugin development. The plugin "ajaxifies" forms, which isn't particularly spectacular:

It gets the basics (action, method) from the form itself, serializes the form's fields, and sends the request.
Users can provide (via its options) callback functions for the local ajax events (beforeSend, complete, success and error).
The dataType can also be set from a custom data attribute, which - if present - takes precedence.

Everything seems to be working as expected (repo, with a simple demo). Since this is my first plugin, I'd be particularly interested in critiques of its structure. That said, as always in reviews, any aspect of the code is fair game for criticism.

The plugin code:

(function ($) {

    $.fn.ajaxForm = function (options) {

        var settings = $.extend({}, $.fn.ajaxForm.defaults, options);

        return this.each(function () {
            var $form = $(this);

            dataType = $form.attr("data-dataType");
            if (typeof dataType != "undefined") dataType = settings.dataType;

            $form.on("submit", function (event) {
                event.preventDefault();

                $.ajax({
                    type: $form.attr("method"),
                    url: $form.attr("action"),
                    data: $form.serialize(),
                    cache: false,
                    dataType: dataType,
                    beforeSend: function () {
                        $form.addClass("ajaxForm-loading");

                        if (typeof settings.beforeSend == "function") settings.beforeSend.call($form);
                    },
                    complete: function () {
                        $form.removeClass("ajaxForm-loading");

                        if (typeof settings.complete == "function") settings.complete.call($form);
                    },
                    success: function (response) {
                        if (typeof settings.success == "function") settings.success.call($form, response);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        if (typeof settings.error == "function") settings.error.call($form, XMLHttpRequest, textStatus, errorThrown);
                    }
                });
            });
        });
    };

    $.fn.ajaxForm.defaults = {
        dataType: "json",
        beforeSend: function () {},
        complete: function () {},
        success: function () {},
        error: function () {}
    };

})(jQuery);

Initialization:

$(document).ready(function () {
    $("form").ajaxForm({
        dataType: "html",
        success: function (response) {
            console.log(response);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("Oops: " + errorThrown);
        }
    });
});


texts: Basic linked list stack implementation with go

texts:
Here goes my first stack implementation with go

New to the go language and it's been ages since I implemented a stack

Would love to discuss the data structure implementation itself and how "goish" the code looks.

package stack

import "errors"

var (
    errEmptyStack = errors.New("Stack is empty")
)

type node struct {
    next  *node
    Value interface{}
}

// Stack implementation
type Stack struct {
    head  *node
    Count int // O(1) count
}

// Push value at the top of the stack
func (stack *Stack) Push(value interface{}) {
    var node = node{Value: value}
    if stack.head == nil {
        stack.head = &node
    } else {
        node.next = stack.head
        stack.head = &node
    }

    stack.Count++
}

// Pop value from the top of the stack
func (stack *Stack) Pop() (value interface{}, err error) {
    if stack.head == nil {
        return nil, errEmptyStack
    }

    var node = stack.head
    stack.head = node.next

    stack.Count--
    return node.Value, nil
}

// Peek element at the top of the stack without changing the stack
func (stack *Stack) Peek() (value interface{}, err error) {
    if stack.head == nil {
        return nil, errEmptyStack
    }

    return stack.head.Value, nil
}


texts:
On my website I want to offer some PDFs, ZIP files and images for download. They are all in the same folder and I could simply link to them like download file. But instead I want to invoke a download dialog by sending an attachment header via php. The link would change into download file:

<?php
/***
 * download/load.php
 * Simple file downloader including mime type
 *
 * @param string $f  name of file in download folder
 * @return file with corresponding HTTP header
 */

// check whether parameter was sent
if ( !isset($_GET['f']) ||
// check whether it is not `load.php` (this file)
     $_GET['f'] === "load.php" ||
// check whether file exists
     !is_readable($_GET['f']) ||
// make sure file is in the current directory
     strpos($_GET['f'], '/') ) {
    header("HTTP/1.0 404 Not Found");
    die();
}

$file = $_GET['f'];

// check mime type
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file);
finfo_close($finfo);

// send mime type
header('Content-type: ' . $mime);

// invoke download dialog
header('Content-Disposition: attachment; filename=' . $file);

// send file
readfile($file);
?>

Is this script okay or does it have security vulnerabilities? If so, how could I improve it?


texts: Correct way of doing transactional queries

texts:
I am trying to do multiple queries in one call, so I organized my code as below:
try{
    $query = $this->conn->begin_transaction();

    $query = $this->conn->prepare("INSERT INTO table1(xx, xxx, xxxx, xxxxx, xxxxxx, xxxxxxx, xxxxxxxx, xxxxxxxxx, xxxxxxxxxx, xxxxxxxxxxx, xxxxxxxxxxx)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

    $query->bind_param("sssssssssss", $var1, $var2, $var3, $var4, $var5, $var6, $var7, $var8,  $var8,  $var9, $var10);
    $result1 = $query->execute();

    $var1= $xxx- $xxxx;
    $query = $this->conn->prepare("UPDATE table2 set xxx = ? WHERE xxxx = ?");
    $query->bind_param("ss", $var1, $var2);
    $result2 = $query->execute();

    $query = $this->conn->prepare("INSERT INTO table3 (xx, xxx, xxxx, xxxxx, xxxxxx, xxxxxxx)
    VALUES (?, ?, ?, ?, ?, ?) ");
    $query->bind_param("ssssss", $var1, $var2, $var3, $var4, $var5, $var6);
    $result3 = $query->execute();

    $query = $this->conn->commit();

    if($result1 == true AND $result2 == true AND $result3 == TRUE){
        return "Success";
    }
    exit();
}catch (Exception $e){
    $this->conn->rollback();
    throw $e;
}

Not sure if this is the correct way of doing it, but I don't want to insert/update records in the database if all queries are not true. It would help me a lot if someone can go through the code and tell me his thoughts, this works fine but I am not sure if this is a good approach.


texts:
I have written a C++ program to convert an infix expression to postfix expression using recursion. I would like to know if it can be improved if possible. Can we improve it by not using a stack? I am using a vector<char> as a stack here.

#include <iostream>
#include <vector>
std::string inp;
int i, len;

std::vector<char> ops;
void convert()
{
    char ch = inp[i];
    if (i > len)
        return;
    else if (ch == '(')
    {
        i++;
        convert();
    }
    else if (ch == ')')
    {
        std::cout << ops[ops.size()-1];
        ops.pop_back();
        i++;
        convert();
    }
    else if (isdigit(ch))
    {
        i++;
        std::cout << ch;
        convert();
    }
    else if ((ch == '+') || (ch == '*'))
    {
        i++;
        ops.push_back(ch);
        convert();
    }
}

int main()
{
    std::cout << "Infix to postfix conversion using recursion" << std::endl;
    i = 0;
    inp = "(5+5)";
    len = inp.length();
    convert();
    std::cout << "\n";
    ops.clear(); i = 0;
    inp = "((5+5)*(6+6))";
    len = inp.length();
    convert();
    std::cout << "\n";
    ops.clear(); i = 0;
    inp = "((4+8)*((5+5)*(6+6)))";
    len = inp.length();
    convert();
    std::cout << "\n";
    return 0;
}


texts: Operator-based switch for a database query filter

texts:
I am currently working on a method, that can search based on a value and an operator.

Currently I check which operator was supplied to the the method in a switch, and do operations accordingly to it.

This is the current code:

switch (enumOperator)
{
    case Operator.Equal:
        tmpResult = tmpResult.Where(a => a.NUMERIC_VALUE == value);
        break;
    case Operator.Less:
        tmpResult = tmpResult.Where(a => a.NUMERIC_VALUE < value);
        break;
    case Operator.LessOrEqual:
        tmpResult = tmpResult.Where(a => a.NUMERIC_VALUE <= value);
        break;
    case Operator.More:
        tmpResult = tmpResult.Where(a => a.NUMERIC_VALUE > value);
        break;
    case Operator.MoreOrEqual:
        tmpResult = tmpResult.Where(a => a.NUMERIC_VALUE >= value);
        break;
    case Operator.NotEqual:
        tmpResult = tmpResult.Where(a => a.NUMERIC_VALUE != value);
        break;
}

Is there a better/more succinct way to represent the previous switch in c#?

Additional info

The previous piece of code is used to search in a database based on the parameter(the field to be searched by), the value and operator.

So the previous code is copied for each field (a => a.X, a => a.Y ...).

As some of the fields are of different type, the "ugly" code is a bit changed and copied again.

Besides of the big switch (which by @unholysampler answer) will be nicer, the code a => a.X == value will be repeated many times(3).

Would it be also possible to save predicates where a => a.X == value, X is yet to be specified?


texts: Echoing back input in uppercase over a socket with Hy, a Python Lisp dialect

texts:
I think I'd like to learn Clojure eventually, but at the moment am having fun with Hy, a "dialect of Lisp that's embedded in Python."

(import socket)

(defn echo-upper (sock)
  (.send c (.upper (.recv c 10000)))
  (.close c)
)

(def s socket.socket)
(.bind s (tuple ["" 8000]))
(.listen s 5)
(while True
  (echo-upper (.__getitem__ (s.accept) 0))
)

Python generated from ABS with astor:

import socket

def echo_upper(sock):
    c.send(c.recv(10000).upper())
    return c.close()
s = socket.socket
s.bind(tuple([u'', 8000]))
s.listen(5)
while True:
    echo_upper(s.accept().__getitem__(0))

I'm not worried about not dealing with connections properly etc, I'd just like feedback on using lispy syntax. I'm tempted to do things like ((getattr s "bind") (tuple ["" 8000])) because it looks more like simple Scheme, the only lisp I have a little experience with.

Any thoughts on syntax and style? Any guidelines for dealing with Python APIs in a lispy way, something that apparently happens a lot in Clojure with Java?


texts:
I'm trying to implement a highly efficient limited memory priority queue. The interface is the same as a std::priority_queue.

Can anyone suggest any performance improvements on my attempt?

limited_queue.h

#include <array>
#include <algorithm>

template<typename T, std::size_t N>
class LimitedPriorityQueue
{
public:
    LimitedPriorityQueue() {}

    void push(T item)
    {
        if (next != items.end()) {
            *next = item;
            ++next;
            std::push_heap(items.begin(), next);
        } else {
            std::sort_heap(items.begin(), items.end());
            if (items.front() < item) {
                items[0] = item;
            }
            std::make_heap(items.begin(), items.end());
        }
    }

    T top()
    {
        return items.front();
    }

    void pop()
    {
        std::pop_heap(items.begin(), next);
        --next;
    }

    bool empty()
    {
        return size() == 0;
    }

    std::size_t size()
    {
        return next - items.begin();
    }

private:
    std::array<T, N> items;
    T* next = items.begin();
};

main.cpp

#include "limited_queue.h"

int main()
{
    LimitedPriorityQueue<int, 10> queue;

    for (int i = 20; i >= 0; --i) {
        queue.push(i);
    }

    while (!queue.empty()) {
        std::cout << queue.top() << std::endl;
        queue.pop();
    }
}

Also, I wasn't quite telling the truth when I said the interface is the same as a std::priority_queue; I'm missing an emplace. I'm not sure if this is possible using an underlying std::array?


texts:
This question is about improving my C++ coding skills. I was asked to implement a simple static integer stack in C++ as an assignment. I've come up with the following code:

class myStaticIntStack
{

    int stackSize;
    int storedElements;
    int *elements;

public:

    myStaticIntStack();
    myStaticIntStack( int aNumber );

    ~myStaticIntStack();

    int peek();

    int pop();

    void push( int element );

};

myStaticIntStack::myStaticIntStack()
{
    this->stackSize = 1;
    this->elements = new int(0);
    this->storedElements = 0;
}

myStaticIntStack::myStaticIntStack( int stackSize )
{
    this->stackSize = stackSize;
    this->elements = new int[ stackSize ];
    this->storedElements = 0;
}

myStaticIntStack::~myStaticIntStack()
{
    if( this->elements != NULL )
    {
        if( stackSize > 1 )
            delete[] this->elements;
        else
            delete this->elements;
    }

}

void myStaticIntStack::push( int newElement )
{
    if( this->storedElements == this->stackSize )
        cout << "Stack is full, you must POP an element before PUSHing a new one!" << endl;
    else
    {
        this->elements[ (this->stackSize - 1) - this->storedElements ] = newElement;
        this->storedElements++;
    }
}

int myStaticIntStack::pop()
{
    if( this->storedElements == 0 )
    {
        cout << "Stack is empty, you must PUSH an element before POPping one!" << endl;
        return -1;
    }
    else
    {
        storedElements--;
        return this->elements[ (this->stackSize - 1) - this->storedElements ];
    }
}

int myStaticIntStack::peek()
{
    if( this->storedElements == 0 )
    {
        cout << "Stack is empty, you must PUSH an element before PEEKing one!" << endl;
        return -1;
    }
    else
    {
        return this->elements[ this->stackSize - this->storedElements ];
    }
}

int main()
{
    myStaticIntStack aStack(3);

    cout << "Popped Element: " << aStack.pop() << endl;

    aStack.push(1);
    cout << "Stack Top is: " << aStack.peek() << endl;
    aStack.push(2);
    cout << "Stack Top is: " << aStack.peek() << endl;
    aStack.push(3);
    cout << "Stack Top is: " << aStack.peek() << endl;
    aStack.push(4);
    cout << "Stack Top is: " << aStack.peek() << endl;

    cout << "Popped Element: " << aStack.pop() << endl;
    cout << "Stack Top is: " << aStack.peek() << endl;
    cout << "Popped Element: " << aStack.pop() << endl;
    cout << "Stack Top is: " << aStack.peek() << endl;
    cout << "Popped Element: " << aStack.pop() << endl;
    cout << "Stack Top is: " << aStack.peek() << endl;

    return 0;
}

The code is compiling and running correctly, this is standard output:

Stack is empty, you must PUSH an element before POPping one!
Popped Element: -1
Stack Top is: 1
Stack Top is: 2
Stack Top is: 3
Stack is full, you must POP an element before PUSHing a new one!
Stack Top is: 3
Popped Element: 3
Stack Top is: 2
Popped Element: 2
Stack Top is: 1
Popped Element: 1
Stack is empty, you must PUSH an element before PEEKing one!
Stack Top is: -1

However I was given a B due to the following reasons:

There was a better way of implementing it.
I didn't manage well the case in which I'm trying to POP an element from an empty stack, since it's confusing that pop() returns a value even if Stack is empty.

Can you please help me understand how I could improve my code?


texts: Generating 10-character passwords, with 3-6 digits and 3-6 uppercase letters, in C++

texts:
In response to a question on Information Security on brute-forcing passwords, I wrote code that helped solve the problem:

  Generate a password list of 10 character passwords containing only a combination of 3 - 6 numbers and 3 - 6 uppercase letters.

I'd like a code review done of the snippet I wrote.  I don't know really anything about optimizing software. I can write it (self-taught) but I don't have the deep insights needed to improve already working software, so I've started posting code snippets in here for you guys to give me insights. I really think this channel is great and without further ado, I'll get to it.

#include <iostream>
#include <vector>
#include <random>
#include <string>

const char charset[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','8','9'};
int main()
{

    std::cout << "Please enter the number of passwords to generate here: ";
    int num_pass;
    std::cin >> num_pass;
    std::random_device dev;
    std::mt19937_64 rng(dev());
    std::vector<std::string> passwds;
    std::uniform_int_distribution<std::mt19937_64::result_type> dist(0, sizeof(charset) - 1);

    for (int i = 0; i < num_pass; ++i) {
        std::string pass = "";
        int num_nums = 0, num_chars = 0;
        while (pass.length() < 10) {
            char c = charset[dist(rng)];
            if (isdigit(c) && num_nums < 6) {
                pass += c;
                num_nums++;
            }
            else if (isalpha(c) && num_chars < 6) {
                pass += c;
                num_chars++;
            }
        }
        passwds.push_back(pass);
        std::cout << pass << std::endl;
    }
    std::cin.get();
}
```


texts: Fastest way to find if N numbers are even or odd

texts:
I want to find if 'N' numbers are even or odd in the fastest way possible.

Here's the following code which produces the desired output, but I do not know how efficient it is.

int main() {
int N,x;
scanf("%d",&N);
while(N--){
   scanf("%d",&x);
    x&1 ? cout << "No" << endl : cout << "Yes" << endl;
}
return 0;

Can this code be improved in any way to get faster results?


texts:
I have a function whose responsibility is to send a push notification to a user. I call this function from a view in flask framework.

I have read multiple articles around refactoring and good designs but I want to know from those who have been doing this for a while what I can improve.

Here is the function.

 def send_push(api_key, cid, username,request_signature):

        ## ---> DB CALLS
        master_db = get_db('master_db')
        cname = master_db.companies.find_one({'company_id': cid})['company_name']
        company_db = get_db(cname)
        application = company_db.applications.find_one({'app_config.api_key':api_key})

        if not application:
            #error_log_writer(cid=cid, error='API Key is invalid')
            raise InvalidApiKey('The API Key is incorrect.')

        appname = application['app_name']

        # application = company_db.applications.find_one({'app_name': appname})
        username_appname = username + '_' + appname
        redis_db = get_redis()

        ## DB CALLS
        if redis_db.hgetall(username_appname):
            # error_log_writer(cid=cid, error='The PUSH request is already in process', appname=appname)
            raise SomeCustomException(' The request is already in process.')

        auth_id = generate_random_alphanumeric(10)

        from pyfcm import FCMNotification

        push_service = FCMNotification(
            api_key="xxxxx"
            )

        ## DB CALLS
        user = company_db.users.find_one({"_id": username})

        if not user:
            raise UserNotFound

        ## DB CALLS
        registration_id = company_db.users.find_one({"_id": username})['device_token']

        data_message = {
            "Nick" : "Mario",
            "body" : "great match!",
            "app_name": appname,
            "cid": cid,
            "username":username,
            "auth_id" : auth_id,
            "api_key": api_key,
            "request_signature":request_signature
        }
        message_body = "authenticate app?"
        username_appname = username + '_' + appname
        username_appname_response = username_appname + 'response'

        ## DB CALLS
        redis_db.setex(name=username_appname_response, value='waiting', time=180)
        redis_data = {'auth_id': auth_id, 'ts': datetime.datetime.now().strftime('%s')}
        redis_db.hmset(username_appname, redis_data)
        redis_db.expire(username_appname, 180)

        result = push_service.notify_single_device(registration_id=registration_id,  data_message=data_message)

I think this has many code smells. Ideally, I would like to refactor it so that I get

Easy unit testing
Avoiding mocks for unit testing where necessary
Minimal side effects
Readable code.

Current issues that I think are there:

Lots of database calls scattered around the core business logic.
Unit testing is difficult as lots of db calls requires mocking
them. This tightly couples the test to my implementation rather than
behaviour of the function.
Lots of indirection to logic is introduced because of scattered calls
to mongo db & redis.

Possible solutions:

pass db objects to function rather than creating them inside the
function that handles business logic(but this will just defer the
object creation to a higher level so db calls will have to be mocked
anyways)

How would you refactor this function considering best practices?

Is it a general practice while developing CRUD app to have multiple mocks on average for every function?


texts:
I worked up a quick diamond program that takes only odd numbers while returning an error with even numbers or 0.

The code looks rather ugly to me, especially with the recurring int(). I haven't found out how to clean that up with my ENTER to quit.

while True:
    number = raw_input("Enter an odd number or hit ENTER to quit program: ")
    if number == "":
        print "\nQuitting program...\n"
        break
    elif int(number) == 0:
        print "\nCannot print symbols for a zero value, try again.\n"
    elif int(number) % 2 == 0:
        print "\nThat's an even number, try again.\n"
    else:
        for i in range((int(number))+1):
            if i % 2 == 0:
                None
            else:
                print ("*" * i).center(int(number))

        for i in range((int(number))-1):
            if i % 2 == 0:
                None
            else:
                print ("*" * ((int(number)) - (i + 1))).center(int(number))


texts: Print numbers from video frames to console using pytesseract

texts:
This is my first ever Python program. It checks every frame of a video file with Tesseract then uses OCR to recognise numbers in that frame and prints it to the console.

import pytesseract
import os
import cv2
import openpyxl
from numpy import interp
import numpy as np

# Video URL
TEST_VID = cv2.VideoCapture("VET2.mp4")
READING, IMG = TEST_VID.read()

# Frame Number
INDEX = 0

# Colours
black = [0, 0, 0]

while READING:

    TEST_VID.set(1, INDEX)
    READING, IMG = TEST_VID.read()
    RET, FRAME = TEST_VID.read()

    # If I want to print images
    # print("new frame: ", READING)
    # if not RET:
    #     break

    # # Assign a name for the file
    # NAME = "./image_frames/frame" + str(INDEX) + ".png"

    # # Assign the print statement
    # print("Extracting frames..." + NAME)
    # cv2.imwrite(NAME, FRAME)

    pixel = FRAME[2100, 1800]

    # If a pixel is black, use these values
    if np.all(pixel == black):

        # Image coordinates [y1:y2, x1:x2]
        speed = FRAME[2775:2883, 1199:1486]
        rpm = FRAME[2948:3014, 1190:1500]
        gear = FRAME[3187:3248, 1359:1415]

    # Tesseract directory
    pytesseract.pytesseract.tesseract_cmd = (
        r"C:\Program Files\Tesseract-OCR\tesseract.exe"
    )

    # Print KPH to console
    print(
        "Speed = "
        + pytesseract.image_to_string(
            speed,
            lang="formula1",
            config="--psm 7 -c tessedit_char_whitelist=0123456789",
        )
    )
    # cv2.imshow("speed", speed)
    # cv2.waitKey(0)

    # Print RPM to console
    print(
        "RPM = "
        + pytesseract.image_to_string(
            rpm,
            lang="formula1",
            config="--psm 7 -c tessedit_char_whitelist=0123456789",
        )
    )
    # cv2.imshow("rpm", rpm)
    # cv2.waitKey(0)

    # Print Gear to console
    print(
        "Gear = "
        + pytesseract.image_to_string(
            gear,
            lang="formula1",
            config="--psm 7 -c tessedit_char_whitelist=0123456789",
        )
    )

    # cv2.imshow("gear", gear)
    # cv2.waitKey(0)

    print(INDEX)
    INDEX += 1


texts:
Greg Beech says here that he asks C# candidates to produce a formula that calculates PI Given that Pi can be estimated using the function \$4 * (1 - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + \dots)\$.

I'm far from C# interview ready, but I like the challenge. Here is my attempt at the formula. Let me know if there is a better way to do it.

using System;

class MainApp
{
    static void Main ()
    {
        double number = 0;
        double pi;
        int i = 1;

        do
        {
            if ((i/2) % 2 == 0)
            {
                number += (double)(1) / i;
            }
            else
            {
                number -= (double)(1) / i;
            }
            pi = 4 * number;
            i += 2;
        } while (Math.Round(pi,5) != 3.14159);

        Console.Clear();
        Console.WriteLine("Pi can be found using the formula 4 * (1 - 1/3 + 1/5 - 1/7 + ...) with {0} iterations.\n" +
        "At this point 4 is multiplied by: {1} to get {2}\n" +
        "This Rounds up to: {3}",i,number,pi,Math.Round(pi,5));
        Console.ReadKey();
    }
}


texts: My approach on nested properties that bind to XAML

texts:
Here is my simple model.
public class Product
{
    public String Name { get; set; }
    public int Price { get; set; }
    public String Info { get; set; }
}

When I use this in viewmodel as following:
    public MainViewModel()
    {
        Item = new Product() { Name = "Coffee", Price = 4, Info = "Coffe is hot" };
    }

    protected Product _item;
    public Product Item
    {
        get { return _item; }
        set
        {
            _item = value;
            NotifyPropertyChanged("Item");
        }
    }

In my XAML, I am binding to the nested properties.
<StackPanel>
    <TextBox Text="{Binding Item.Name}"/>
    <TextBox Text="{Binding Item.Price}"/>
    <TextBox Text="{Binding Item.Info}"/>
    <Button Content="Change Item" Click="Change_Item_Clicked"/>
</StackPanel>

I change only nested property in the click event:
    private void Change_Item_Clicked(object sender, RoutedEventArgs e)
    {
        MainViewModel vm = DataContext as MainViewModel;

        vm.Item.Name = "Donut";
    }

This obviously doesn't update the UI since the parent property implements INotifyPropertyChanged but not the nested one.
So I came up with the following solution and it does then update the UI fine.
I am essentially creating viewmodel version of the Product class as below that implments INotifyPropertyChanged.
   public class ProductVM : Notifier
    {
        protected Product _p;
        public ProductVM(Product p)
        {
            _p = p;
        }

        public String Name
        {
            get { return _p.Name; }
            set
            {
                _p.Name = value;
                NotifyPropertyChanged("Name");
            }
        }

        public int Price
        {
            get { return _p.Price; }
            set
            {
                _p.Price = value;
                NotifyPropertyChanged("Price");
            }
        }

        public String Info
        {
            get { return _p.Info; }
            set
            {
                _p.Info = value;
                NotifyPropertyChanged("Info");
            }
        }
    }

Now the viewmodel use its version of the Product class as defined above that has ability to notify on changes.
    class MainViewModel : Notifier
    {
        public MainViewModel()
        {
            Item = new ProductVM( new Product() { Name = "Coffee", Price = 4, Info = "Coffe is hot" });
        }

        protected ProductVM _item;
        public ProductVM Item
        {
            get { return _item; }
            set
            {
                _item = value;
                NotifyPropertyChanged("Item");
            }
        }
    }

This works great but what do you guys think of this approach? If we are going to bind to a property (nested or top level), wouldn't it be best for all these properties to implment the INotifyPropertyChanged?
What naming conversion can I use to name ProductVM better? Is there a less cody way to achieve this?