texts: Simplified board for X's and O's using Tkinter

texts:
Recently I am learning to program in Python and in order to practice I tried to program a little game which consists in a board with 9 cells. In this board each player draw an 'X' or 'O' with left or right mouse button. The next code is a simplification with only 3-cell board.
Code 1: View
from tkinter import *
import numpy as np
from line3 import *

juego = Tablero()

root = Tk()

def leftClick1(event):
    canvas1.create_line(0,0,50,50)
    canvas1.create_line(0, 50, 50, 0)
    juego.ponerFicha(0,0,1)

def leftClick2(event):
    canvas2.create_line(0,0,50,50)
    canvas2.create_line(0, 50, 50, 0)
    juego.ponerFicha(0,1,1)

def leftClick3(event):
    canvas3.create_line(0,0,50,50)
    canvas3.create_line(0, 50, 50, 0)
    juego.ponerFicha(0,2,1)

def rightClick1(event):
    create_circle(24, 24, 20, canvas1)
    juego.ponerFicha(0,0,2)

def rightClick2(event):
    create_circle(24, 24, 20, canvas2)
    juego.ponerFicha(0,1,2)

def rightClick3(event):
    create_circle(24, 24, 20, canvas3)
    juego.ponerFicha(0,2,2)

topFrame = Frame(root)
topFrame.pack()
middleFrame = Frame(root)
middleFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack()

canvas1 = Canvas(topFrame, width=50, height=50)
canvas2 = Canvas(topFrame, width=50, height=50)
canvas3 = Canvas(topFrame, width=50, height=50)

canvas1.bind("<Button-1>", leftClick1)
canvas2.bind("<Button-1>", leftClick2)
canvas3.bind("<Button-1>", leftClick3)

canvas1.bind("<Button-3>", rightClick1)
canvas2.bind("<Button-3>", rightClick2)
canvas3.bind("<Button-3>", rightClick3)

canvas1.pack(side=LEFT)
canvas2.pack(side=LEFT)
canvas3.pack(side=LEFT)

canvas1.create_line(50,50,0,50)
canvas1.create_line(50,50,50,0)
canvas2.create_line(50,50,0,50)
canvas2.create_line(50,50,50,0)
canvas3.create_line(50,50,0,50)
canvas3.create_line(50,50,50,0)

root.mainloop()

Code 2: Classes and utils
import numpy as np

class Tablero:
    def __init__(self):
        self.tablero = np.zeros((3,3))

    def ponerFicha(self, x, y, tipoFicha):
        if (self.tablero[x][y] == 0):
            self.tablero[x][y] = tipoFicha
            print(self.tablero)

# Taken from StackOverFlow question
def create_circle(x, y, r, canvasName): #center coordinates, radius
    x0 = x - r
    y0 = y - r
    x1 = x + r
    y1 = y + r
    return canvasName.create_oval(x0, y0, x1, y1)

I feel I am repeating a lot of code when I programmed two events for each cell.

Is it possible to have one listener for all the cells?
How could I avoid repeat so much code?


texts:
Problem : A binary tree is given as an input, each node of binary tree contains one integer value. Find the maximum sum of collection of nodes such that following two conditions are met.

if node's parent node is considered for sum, then node cannot be considered.
if node's either of child is considered for sum, then node cannot be considered.

For example :

For a binary tree

             15
      20            25
   5      15      5

The max sum we can get is considering [20, 25] which is 45.

To implement this I used O(n^2) approach and code is here.

I am trying to optimize it and looking for feedback on improving algorithm, code efficiency and cleanliness

tree is String representation of tree, given in BFS manner. _ is present in place of null element. _ is not given for the deepest level's element's null representation.

the above tree would be represented as 15 20 25 5 15 5 _

static int findMaxSum(String tree) {
    String[] tokens = tree.split(" ");
    int max = 0;
    for (int i = 0; i < tokens.length; i++) {
        if (!isValidToken(tokens[i])) {
            continue;
        }
        Set<Integer> set = new HashSet<>();
        //wildcard entry
        set.add(i);
        int sum = Integer.parseInt(tokens[i]);
        for (int j = 0; j < tokens.length; j++) {
            if (isValidToken(tokens[j])) {
                if(!set.contains(j) && !set.contains(getParentIndex(j))){
                    if (!set.contains(getLeftChildIndex(j)) && !set.contains(getRightChildIndex(j))) {
                        set.add(j);
                        sum += Integer.parseInt(tokens[j]);
                    }
                }
            }
        }
        max = Math.max(max,sum);
    }

    return max;
}

static boolean isValidToken(String token) {
    return !"_".equals(token);
}

static int getLeftChildIndex(int parentIndex) {
    return parentIndex * 2 + 1;
}

static int getRightChildIndex(int parentIndex) {
    return parentIndex * 2 + 2;
}

static int getParentIndex(int childIndex) {
    return (childIndex - 1)/2;
}

Note: this code works but it is not efficient. I am looking for ideas on how to improve it.


texts:
I threw together this C program today to handle a bioinformatics data processing task. The program seems to work correctly, but I wanted to know if anyone has suggestions regarding how the input data are parsed and how I've used control structures in the main processing loop.

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

#define BUFFERSIZE 1024

FILE *fileopen(const char *filename, const char *mode)
{
  FILE *fh = fopen(filename, mode);
  if(fh == NULL)
  {
    fprintf(stderr, "error: unable to open file '%s'\n", filename);
    exit(1);
  }
  return fh;
}

void *memalloc(size_t size)
{
  void *memory = malloc(size);
  if(memory == NULL)
  {
    fprintf(stderr, "error: unable to allocate memory\n");
    exit(1);
  }
  return memory;
}

int main(int argc, const char **argv)
{
  // Parse command line arguments
  char seqbuffer1[BUFFERSIZE];
  char seqbuffer2[BUFFERSIZE];
  char qualbuffer1[BUFFERSIZE];
  char qualbuffer2[BUFFERSIZE];
  char *seqbufferout;
  FILE *seqinfile;
  FILE *seqoutfile;
  FILE *qualinfile;
  FILE *qualoutfile;
  int seqlength;
  if(argc != 6)
  {
    fprintf(stderr, "error: 5 arguments required, %d provided\n", argc - 1);
    exit(1);
  }
  seqinfile   = fileopen(argv[1], "r");
  qualinfile  = fileopen(argv[2], "r");
  seqoutfile  = fileopen(argv[3], "w");
  qualoutfile = fileopen(argv[4], "w");
  seqlength   = atoi(argv[5]);
  assert(seqlength > 0);

  // Process reads
  seqbufferout = (char *)memalloc( sizeof(char) * (seqlength + 1) );
  seqbufferout[seqlength] = '\0';
  while(fgets(seqbuffer1, BUFFERSIZE, seqinfile))
  {
    if(strlen(seqbuffer1) > 0)
    {
      int ambiguous;
      int i;

      assert(strncmp(seqbuffer1, ">", 1) == 0);
      if(fgets(seqbuffer2, BUFFERSIZE, seqinfile) == NULL)
      {
        fprintf(stderr, "error: file ends with a fasta header\n");
        exit(1);
      }

      if( fgets(qualbuffer1, BUFFERSIZE, qualinfile) == NULL ||
          fgets(qualbuffer2, BUFFERSIZE, qualinfile) == NULL )
      {
        fprintf(stderr, "error: no quality entry corresponding to sequence '%s'\n", seqbuffer1);
        exit(1);
      }

      ambiguous = 0;
      for(i = 0; i < seqlength; i++)
      {
        if(seqbuffer2[i] == '.')
        {
          ambiguous = 1;
          break;
        }
        seqbufferout[i] = seqbuffer2[i];
      }

      if(!ambiguous)
      {
        fprintf(seqoutfile,  "%s%s\n", seqbuffer1, seqbufferout);
        fputs(qualbuffer1, qualoutfile);

        i = 0;
        char *tok = strtok(qualbuffer2, " ");
        while(tok != NULL && i < seqlength - 1)
        {
          if(i > 0)
            fputs(" ", qualoutfile);
          fputs(tok, qualoutfile);
          tok = strtok(NULL, " ");
          i++;
        }
        fputs("\n", qualoutfile);
      }
    }
  }

  fclose(seqinfile);
  fclose(qualinfile);
  fclose(seqoutfile);
  fclose(qualoutfile);
  free(seqbufferout);

  return 0;
}


texts:
The ElectricalEngine class responds to the horsepower message. Because efficiency is calculated in percent a programmer can mistakenly initialize it with an integer instead of a float.

class ElectricalEngine
  attr_reader :volts, :current, :efficiency

  def initialize(volts, current, efficiency)
    @volts, @current, @efficiency = volts, current, efficiency
  end

  HP_IN_WATTS = 746
  def horsepower
    (volts * current * efficiency) / HP_IN_WATTS
  end
end

puts ElectricalEngine.new(240, 90, .6).horsepower # correct
puts ElectricalEngine.new(240, 90, 60).horsepower # buggy

How would you handle this scenario?

Do nothing. It's the programmers responsibility to know the right datatype.
Rename efficiency to efficiency_as_float to make it clearer.
Rename efficiency to efficiency_as_percent and adjust horsepower's calculation.
Write a custom efficiency method to check the datatype and convert it accordingly.
Check efficiency type and raise an error if it's not a float.
Other

Solution four might look like this. Of course this conversion can happen in the initialize method too, but I think this is cleaner.

def horsepower
  (volts * current * efficiency_as_float) / HP_IN_WATTS
end

def efficiency_as_float
  if efficiency.is_a?(Integer) # what if 1 is passed in instead of 1.0?
    efficiency / 100.to_f
  else
    efficiency
  end
end

Solution 5 would look something like this:

def initialize(volts, current, efficiency)
  raise "Efficiency must be a float" unless efficiency.is_a?(Float)
  @volts, @current, @efficiency = volts, current, efficiency
end

Should ElectricalEngine own the responsibility of converting incorrect datatypes?


texts: Getting images and saving them to localstorage

texts:
The code in this project accepts an image URL and creates an  tag dynamically, using the image URL as the src attribute value. The image *name *and URL are then saved to localStorage. The page can be viewed here.

I really want to improve this code. I can't say if it's a good approach. I can't really think of anything else on how to accomplish this but it works. What I really want to know is if I can make this simpler. I think I kind overdid it. Did I?

/*jshint esversion: 6 */

function saveImages(name, value) {
    if (typeof(Storage) !== undefined) {
        localStorage.setItem(name, value);
    }
    else {
        alert("LocalStorage is not supported on your browser");
    }
}

function loadStorage() {
    const container = $(".images-container");
    let elem;
    var keys = Object.keys(localStorage),
        i = 0,
        key;
    for (; key = keys[i]; i++) {
        elem = "";
        $(container).append(elem);
        let thisImg = document.getElementById(key);
        let source = localStorage.getItem(key);
        $(thisImg).attr('src', source);
    }
}

$(function() {
    "use strict";
    loadStorage();
    const create_btn = $("#createImage");
    const save_btn = $("#saveImages");
    const inputUrl = $("#ImageUrl");
    const inputName = $("#imageName");
    const container = $(".images-container");

    var createThisImage = function(name, url) {
        if ((name === "" && url === "") || (url === "")) {
            alert(" - expected input");
        }
        else if (name === "" || document.getElementById(name)) { //if name exists or name is empty then create a random name
            name = guid();
            name = new Image(url, name);
            name.createImage();
        }
        else {
            name = new Image(url, name);
            name.createImage();
        }

    };

    $(create_btn).on('click', function() {
        var new_image = inputName.val();
        var source = inputUrl.val();
        createThisImage(new_image, source);
    });

    $('img').on('click', function() {
        const identity = $(this).attr('id');
        const isValidDeletion = confirm("Delete " + identity + "?");
        if (isValidDeletion) {
            localStorage.removeItem(identity);
            window.location.reload(true);
        }
    });

    function Image(url, name) {
        this.img_url = url;
        this.img_name = name;
    }

    Image.prototype.createImage = function() {
        let id = this.img_name;
        let elem = "";
        $(container).append(elem);
        let thisImg = document.getElementById(id);
        thisImg.src = this.img_url;
        saveImages(this.img_name, this.img_url);
        window.location.reload(true);
    };

});

//Code from https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
function guid() {
    return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
        s4() + '-' + s4() + s4() + s4();
}

function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
        .toString(16)
        .substring(1);
}


texts: Showing/hiding deletion buttons in a grid view

texts:
I want to perform some operations on the gridview (asp.net 4.0). So, to achieve this i have written a jquery function which i am calling on pageload but, because this function takes some time for execution my grid performance degrades (IE 8). Can i optimize it someway?

     $.each($("#divTab2GridInquiries").find("tr").not(":first"), function () {
            var tr = $(this);
            var val = tr.find("input[id*='hdnLineStatus']").val();
            var btnDelete = tr.find("div[id='divBtnDelete']");
            var btnTobeDeleted = tr.find("div[id='divBtnTobeDeleted']");
            if (val == "N") {
                btnDelete.hide();
                btnTobeDeleted.hide();
            }
            if (val == "S") {
                tr.css("background-color", "#99FF99");
                tr.find("input").css("background-color", "#99FF99");
                btnDelete.show();
                btnTobeDeleted.hide();
            }

            if (val == "D") {
                tr.css("background-color", "#FFFF99");
                tr.find("input").css("background-color", "#FFFF99");
                btnDelete.show();
                btnTobeDeleted.hide();
            }

            //From user rights
            if ($("input[id*='hdnTab2ShowDelete']").val() != "Y") {
                btnTobeDeleted.hide();
                //btnDelete.show();
            }
        });


texts: Loop through object and send analytics code based on objects properties value

texts:
The code I have now is currently working, but I'm looking for ways to optimize it, and really, to just get any feedback.

I'm implementing this code through Ensighten (a tag management platform) as a custom javascript tag. Ensighten works by injecting tags either sync or async scripts on to a page. I've set this tag to fire after the DOM is ready.

What it does is creates a namespace, and then sets a function in that namespace to main (see main.js). The main function takes one argument, an object (see lookupTable.js), in which it takes that object, loops through the object, and if the object contains the correct key, it sets that key's value equal to campaignCode.

Next, the function looks to see if the campaignCode is not falsey, it then looks at the path (window.location.path) to see if it's either a courses or a topics page. If it's a topics page it fires the analytics code. If it's a courses page, it listens for a message from an iframe that a video was clicked. If the message from that iframe equals play button clicked then it fires the other analytics code.

The main function is called from the the lookupTable.js. Like so:

window.analytics.campaign.main(window.analytics.campaign.lookupTable);

Questions:

Should I be checking if the main function's argument is an object?
Is there a way I wouldn't have to check if the campaignCode is falsy? Could I check it in the if statement of the for loop?
Am I declaring the analyticsTrack function in the correct way?

main.js

/*jslint browser:true*/
/*globals Bootstrapper*/

window.analytics = window.analytics || {};
window.analytics.campaign = window.analytics.campaign || {};

window.analytics.campaign.main = function (lookupTable) {
    var path = window.location.pathname,
        campaignCode = '',
        prop;

    function analyticsTrack (id) {
        return Bootstrapper.insertScript('//www.example.com/click/services/Tracking/Click.ashx?CR_EAC=' + id);
    }

    for (prop in lookupTable) {
        if (lookupTable.hasOwnProperty(prop) && path === prop) {
            campaignCode = lookupTable[prop];
        }
    }

    // check campaignCode
    if (campaignCode) {

        // if it's a topic page, fire a RIO tag onload
        if (path.indexOf('topics') > -1) {
            analyticsTrack(campaignCode);
        }

        // if it's a courses page
        if (path.indexOf('courses') > -1) {

            // listen for a message from the iframe
            $(window).on('message', function (e) {

                // check the message from the iframe, fire a RIO tag
                if (e.originalEvent.data === 'play button clicked') {
                    analyticsTrack(campaignCode);
                }
            });
        }
    }
};

lookupTable.js

window.analytics = window.analytics || {};
window.analytics.campaign = window.analytics.campaign || {};

var campaign = window.analytics.campaign;

campaign.lookupTable = {
    '/topics/123456':    '300257956',
    '/courses/234567':   '300257957',
    '/courses/34567':    '300257958',
    '/courses/15677789': '300257959',
    '/topics/123457':    '300257970'
};

campaign.main(campaign.lookupTable);


texts:
Create a program to find all the prime numbers between 1 and 100.

  One way to do this is to write a function that will check if a number is prime (i.e., see if the number can be divided by a prime number smaller than itself) using a vector of primes in order (so that if the vector is called primes, primes[0]==2, primes[1]==3, primes[2]==5, etc.). Then write a loop that goes from 1 to 100, checks each number to see if it is a prime, and stores each prime found in a vector. Write another loop that lists the primes you found. You might check your result by comparing your vector of prime numbers with primes. Consider 2 the first prime.

Do you think my codes are short, simple, efficient, and easy to understand?

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

int main()
{
    std::vector<int> primes = { 2 };
    for (int i = 2; i <= 100; ++i)
        for (int j = 2; j < i; ++j) {
            if (i % j == 0)
                break;
            if (j == i - 1)
                primes.push_back(i);
        }
    for (int x: primes)
        std::cout << x << ' ';
    return 0;
}


texts:
I have to do a Bruteforce script, so mine is working, but is also very very low.
My teacher gave me a small Shadow file and from the shadow file I have to find the original password (MD5 used here). I know that my code is working but I'm looking for tips and tricks to improve it.

import hashlib
import itertools

#possible characters in user password
Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_.;#@")
#minimum password value
CharLength = 6

#getting passwords and username from shadow file
with open("shadow_test", "r") as ins:
    array = []
    users = []
    passwd = []
    #getting everyline from shadow file into an array
    for line in ins:
        array.append(line)
    #saving only username and passwords
    for pw in array:
        str(pw)
        r= pw.split(":")
        users.append(r[0])
        passwd.append(r[1])
    # print(users)
    # print(passwd)

    list = []
    #removing passowrd with * or !
    for mdp in passwd:
        if mdp != '*' and mdp != '!':
            str(mdp)
            list.append(mdp)
            # trying to Bruteforce
            for _ in range(12):
                passwords = (''.join(word) for word in itertools.product(Alphabet, repeat=CharLength))

                #print(*passwords)
                for pswd in passwords:
                    hash_object = hashlib.md5(str.encode(pswd)).hexdigest()
                    # hash_object.update(*passwords.encode('utf-8'))
                    generatedpassword = '$1$' + hash_object
                    # print(generatedpassword)

                    for compare in list:
                        for user in users:
                            #print('on cherche le Mot de passe : ' + compare +' pour ' +user)
                            #print('mot de passe MD5 généré : ' +generatedpassword)
                            #print('mot de passe clair généré : ' +pswd)

                            if generatedpassword == compare:
                                print('Le Mot de passe pour' + user + ' est : ' + pswd)


texts: CMakeLists and Clang sanitization options for an ncurses program

texts:
I would like some feedback on a CMakeLists.txt file I created for compiling my project. I have pasted the CMakeLists as well as my source code below. One thing I would specifically appreciate feedback on the sanitization options I have enabled. Are there more I should enable, and/or should I should reduce? I know -fsanitize=address, -fsanitize=thread, and -fsanitize=memory groups can't be used with others (according to the clang documentation). Would one of the other groups be better preferred to use on a first-pass rather than the one I chose (address)?

Also - the blob feature I am using, I have based on a StackOverflow answer I read - I understand that this doesn't detect new C source files and I'm fine with that, but besides that subtle detail is this an okay practice to follow?

CMakeLists.txt

cmake_minimum_required(VERSION 3.13)
project(FirstProject C)

find_package(Curses REQUIRED)
include_directories(${CURSES_INCLUDE_DIR})

set(CMAKE_C_COMPILER clang)
set(CMAKE_C_STANDARD 99)
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Weverything -fsanitize=undefined,integer,implicit-conversion,nullability,address,leak,cfi -flto -fvisibility=default")

FILE(GLOB Sources *.c)
add_executable(${CMAKE_PROJECT_NAME} ${Sources})
target_link_libraries(${CMAKE_PROJECT_NAME} ${CURSES_LIBRARIES})

main.c (Code comes from here)

#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <limits.h>
#include <ncurses.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

// Generous estimate of the maximum number of digits
// https://stackoverflow.com/a/10536254
#define ULL_DIGITS (3 * sizeof(unsigned long long))
#define ERR_MSG_MAX_LENGTH 32
#define NUL '\0'
#define NUL_SIZE 1

int ask_ull(unsigned long long *result, const char *prompt);

/**
 * Prints a prompt then reads an unsigned long long, using ncurses.

 * Returns 0 on success.  Returns errno on failure, which is set to

 * ERANGE, EDOM, or EIO.
 */
int ask_ull(unsigned long long *result, const char *prompt) {
    char buf[ULL_DIGITS + NUL_SIZE];
    char *endptr;
    printw("%s", prompt);
    getnstr(buf, ULL_DIGITS);
    *result = strtoull(buf, &endptr, 10);
    if (errno == ERANGE) {
        // Overflow or underflow
        return errno;
    }
    if (endptr == buf || strchr(buf, '-')) {
        // Unsuccessful conversion
        errno = EDOM;
        return errno;
    }
    while (isspace(*endptr)) endptr++;
    if (*endptr) {
        // Trailing junk
        errno = EIO;
        return errno;
    }
    errno = 0;
    return errno;
}

int main(void) {
    unsigned long long height, width, length;
    height = width = length = 0;

    char errmsg[ERR_MSG_MAX_LENGTH];
    errmsg[0] = NUL;

    initscr();
    printw("--- Volume Calculator --\n");
    if (!ask_ull(&length, "Enter length: ")) {
        sscanf(errmsg, "%s", "Unable to scan length");
    }
    if (!ask_ull(&width, "Enter width: ")) {
        sscanf(errmsg, "%s", "Unable to scan width");
    }
    if (!ask_ull(&height, "Enter height: ")) {
        sscanf(errmsg, "%s", "Unable to scan height");
    }

    if (errmsg[0] != NUL) {
        refresh();
        endwin();
        perror(errmsg);
        return errno;
    }

    unsigned long long volume = length * width * height;
    printw("Volume: %llu", volume);
    refresh();
    getch();
    endwin();
}


texts:
I'm trying out different sorting algorithms for learning purposes, here I'm doing a "type-agnostic" bubbleaort.

I modeled the function signature after the standard library's qsort. I know the bubblesort algorithm in general is not that fast, but I'm looking for a review in particular about the memory management.

In my implementation I'm accepting a void pointer to an array, the size of the array, the size of the single elements and the pointer to the comparison function. Then I convert the void pointers to char pointers, and I do manually the pointer arithmetics (I avoided nonstandard arithmetics on void *).

The part I'm not very happy about is the need for a buffer (dynamically allocated), and the use of memcpy to swap the memory of the two elements. I'd love to know if that part can be improved even slightly.

I'm using a pointer to the beginning and the end of the array, instead of using indexes with [] bracket notation.

Also, what about the if (buffer == NULL) check and "halting" with exit()? Is there a more elegant way to fail here?

I also could use one variable instead of two (current and left), but doing one more pointer arithmetic in the inner loop.

Here's my current bubblesort implementation:

/**
 * Bubblesort algorithm. Compatible with any data type.
 * @param base A void pointer to the array's first element.
 * @param num The number of elements in the array.
 * @param size The size of the data type.
 * @param compar A pointer to the comparison function.
 */
void bubblesort(void* base, size_t num, size_t size,
    int (*compar)(const void*, const void*)
) {
    const char *arr = (const char *) base;
    char *buffer, *left, *current, *right;

    if (arr != NULL && size > 0 && num > 1) {
        buffer = (char *) malloc(size);

        if (buffer == NULL) {
            fprintf(stderr, "Out of memory.");

            exit(EXIT_FAILURE);
        }

        right = (char *) arr + num * size;
        while (right > arr) {
            left = (char *) arr;
            current = left + size;

            while (current < right) {
                // Compare the two elements and move the bigger to the right
                if (compar(left, current) > 0) {
                    memcpy(buffer, left, size); // Temporary variable
                    memcpy(left, current, size); // Swap pt.1
                    memcpy(current, buffer, size); // Swap pt.2
                }

                left += size;
                current += size;
            }

            right -= size;
        }

        free(buffer);
    }
}


texts: Storing global constants in app delegate or singleton

texts:
I am converting a non ARC projecs to ARC. I just found that after login in my old app, the data is stored in app delegate objects, like Home_DataArray, various flags and some other objects.

I am bit confused at it, because my app delegate is looking like constant class and BoolDidFinishLaunch looks like parent of various code.

Old app Delegates.h:

@property (nonatomic, copy) void(^backgroundTransferCompletionHandler)();

@property(nonatomic)BOOL activatedFromBackground;
@property(nonatomic,strong)IBOutlet UIViewController *SplashViewController;
@property(nonatomic,strong)IBOutlet UIViewController *AppCodeViewController;
@property(nonatomic,strong)IBOutlet UINavigationController *navControl;
@property(nonatomic,strong)NSMutableArray *arrHomeProducts;
@property(nonatomic,strong)NSMutableArray *arrayDownloadProducts;
@property(nonatomic,strong)NSString *AppNIB;
@property(nonatomic,strong)NSBundle* languageBundle;
@property(nonatomic,strong)UIViewController* loginVC;
@property(nonatomic,assign)BOOL acceptedMessage_Status;

@property(nonatomic,strong)NSIndexPath *selectedWebsiteIndex;
@property(nonatomic,strong)NSString *selectedWebsiteID;
@property(nonatomic,strong)NSString *userID;
@property(nonatomic,strong)NSString *partID;
@property(nonatomic,strong)NSString *websiteID;
@property(nonatomic,strong)NSString *BrandName;
@property(nonatomic,strong)NSString *driverSide;
@property(nonatomic,strong)NSString *str_bundle;
@property(nonatomic,strong)NSString *str_BundleCost;
@property(nonatomic,assign)BOOL isCalledFromSafariBrowser;
-----------------------------------------------------------
------------------------------so on ---------------------------

and in similar allocation of array in didfinish launch.

I did same things and code is working but is it the right way of using objects in app delegate.

Please suggest how I should opt a singleton-based approach to declare, alloc and store various objects for various view controllers or something else.


texts:
I wrote this jQuery code as I could for a dropdown menu.

But I'm sure there is a way to make this code shorter.

$(document).ready(function() {
    $('#show-menu-1').on('click touch', openSubMenu);
    $('#close-menu-1').on('click touch', closeSubMenu);

    $(document).on('click touch', function(event) {
        if (!$(event.target).closest('#menu-1').length) {
            $('#menu-1 > .main-menu__submenu').removeClass('main-menu__submenu--active');
            $('#menu-1').removeClass('main-menu__item--active');
        }
    });

    function openSubMenu() {
        $('#menu-1 > .main-menu__submenu').addClass('main-menu__submenu--active');
        $('#menu-1').addClass('main-menu__item--active');
    };

    function closeSubMenu() {
        $('#menu-1 > .main-menu__submenu').removeClass('main-menu__submenu--active');
        $('#menu-1').removeClass('main-menu__item--active');
    };
});

$(document).ready(function() {
    $('#show-menu-2').on('click touch', openSubMenu);
    $('#close-menu-2').on('click touch', closeSubMenu);

    $(document).on('click touch', function(event) {
        if (!$(event.target).closest('#menu-2').length) {
            $('#menu-2 > .main-menu__submenu').removeClass('main-menu__submenu--active');
            $('#menu-2').removeClass('main-menu__item--active');
        }
    });

    function openSubMenu() {
        $('#menu-2 > .main-menu__submenu').addClass('main-menu__submenu--active');
        $('#menu-2').addClass('main-menu__item--active');
    };

    function closeSubMenu() {
        $('#menu-2 > .main-menu__submenu').removeClass('main-menu__submenu--active');
        $('#menu-2').removeClass('main-menu__item--active');
    };
});


texts: Define cd so that it changes a variable (as it does already with PWD, OLDPWD, ...)

texts:
My target is to have an environment variable being set to a leading substring of $PWD and to be unset when $PWD does not start with that substring.
So I decided to override cd like this (here I'm assuming the substring is just my home directory /home/enrico, but in general is fine for me that it be an hardcoded regex):
cd() {
    command cd "$@"
    export MYVARIABLE=$(<<< $PWD sed -E 's!(/home/enrico)(/?$|.*)!\1!')
    if [[ $MYVARIABLE == $PWD ]]; then
        unset MYVARIABLE
    fi
}

This seems to work fine, but I'd like to have some different point of view on it.
(Btw, if there are appropriate tags to add, please do, as I haven't found any more than bash.)


texts:
I'm starting with make, and I made my first makefile to build my project. I don't know if it's the best way to do it or not, so I share with you my makefile to get your opinion on it:

Directory structure:

├── LICENSE
├── Makefile
├── objs
│   └── parser.o
├── out
│   ├── libsip.a
│   └── parser.h
├── README.md
├── src
│   ├── parser.c
│   ├── parser.d
│   └── parser.h
└── tests
    ├── a.out
    ├── config.ini
    ├── libsip.a
    ├── parser.h
    └── test.c

Makefile:

SHELL = /bin/sh

CC := gcc
CFLAGS := -Wall

SRCSDIR := src
OBJSDIR := objs
OUTDIR := out

SRCS := $(wildcard $(SRCSDIR)/*.c)
OBJS := $(SRCS:$(SRCSDIR)/%.c=$(OBJSDIR)/%.o)

$(OUTDIR)/libsip.a : $(OBJS)
    @mkdir -p $(@D)
    ar cr -o $@ $^
    cp -f src/parser.h $(OUTDIR)

$(OBJSDIR)/%.o : $(SRCSDIR)/%.c
    @mkdir -p $(@D)
    $(CC) $(CFLAGS) $< -c -o $@
    $(CC) -MM $< > $(patsubst %.c, %.d, $<) && \
    sed -i \ '1s|^|$(@D)/|' $(patsubst %.c, %.d, $<)
# use sed to add path to object dependencies

.PHONY : clean
clean :
    rm -rf $(OBJSDIR) $(OUTDIR)

-include $(SRCS:%.c=%.d)


texts:
I'm making a game and I want to establish a network connection between 2 players through a server(so the players are clients).

So far all I have is:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server extends Thread {

public ServerSocket s;
public Socket p1, p2;
public PrintWriter bis1, bis2;
public BufferedReader bos1, bos2;

public Server() {
    try {
        s = new ServerSocket(5_000, 1714);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void run() {
    try {
        p1 = s.accept();
        p2 = s.accept();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        bis1 = new PrintWriter(p1.getOutputStream());
        bis2 = new PrintWriter(p2.getOutputStream());
        bos1 = new BufferedReader(new InputStreamReader(p1.getInputStream()));
        bos2 = new BufferedReader(new InputStreamReader(p2.getInputStream()));
    } catch (IOException e) {
        e.printStackTrace();
    }

    while (p1.isClosed() || p2.isClosed()) { // if one of the players disconnect, the match will end.
        try {
            String p1 = bos1.readLine(); // what p1 says
            String p2 = bos2.readLine(); // what p2 says

            if (!p1.equalsIgnoreCase("")) { // if what p1 says is something
                if(p1.startsWith("my position x=")) {
                    p1 = p1.substring(15);
                    float x = Float.parseFloat(p1);
                    bis2.write("his position x=" + x);
                } else if(p1.startsWith("my position y=")) {
                    p1 = p1.substring(15);
                    float y = Float.parseFloat(p1);
                    bis2.write("his position y=" + y);
                }
            }

            if (!p2.equalsIgnoreCase("")) { // if what p1 says is something
                if(p2.startsWith("my position x=")) {
                    p2 = p2.substring(15);
                    float x = Float.parseFloat(p2);
                    bis1.write("his position x=" + x);
                } else if(p2.startsWith("my position y=")) {
                    p2 = p2.substring(15);
                    float y = Float.parseFloat(p2);
                    bis1.write("his position y=" + y);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

}

This is meant to send update of the players x and y to each other.

I'll implement other data of the game later but I want to know if I'm going to a good way.


texts: Dynamically-resizable array implementation, for use in a game-dev-related library

texts:
I've been working on a library that includes a list-like structure, which I use internally multiple times to store different types of structs. However, I'm not entirely confident with my ability to safely manage memory in C yet, so I'd appreciate if someone could let me know if there's anything wrong with my code (it seems to work just fine.)

This is the code for the list structure (with some bits from the associated header put at the top for simplicity.)

// Put this at the top of structs to make it possible to use them in a cg_mem_list
#define CG_ITEMIZABLE int cg_index;

// Free extra spaces after this many exist
#define CG_MEM_EXTRAS 10

typedef struct cg_mem_item {
    CG_ITEMIZABLE
} cg_mem_item;

typedef struct cg_mem_list {
    cg_mem_item** items;
    int num, capacity, itemsize;
} cg_mem_list;

void
cg_new_mem_list (cg_mem_list* list, int itemsize)
{
    list->items = 0;
    list->num = 0;
    list->capacity = 0;
    list->itemsize = itemsize;
}

cg_mem_item*
cg_mem_list_add (cg_mem_list* list)
{
    cg_mem_item* mitem = malloc (list->itemsize);

    if (list->capacity - list->num < 1) {
        list->capacity++;
        list->items = realloc (list->items, list->capacity * sizeof (cg_mem_item*));
    }

    mitem->cg_index = list->num;

    list->items[list->num++] = mitem;

    return mitem;
}

void
cg_mem_list_remove (cg_mem_list *list, cg_mem_item *item)
{
    list->num--;

    int index = item->cg_index;

    if (index < list->num) {
        list->items[index] = list->items[list->num];
        list->items[index]->cg_index = index;
    }

    if (list->capacity - list->num > CG_MEM_EXTRAS) {
        list->capacity = list->num;
        list->items = realloc (list->items, list->capacity * sizeof (cg_mem_item*));
    }

    free (item);
}

void
cg_destroy_mem_list (cg_mem_list* list)
{
    free (list->items);
}

This is how I use it:

// The struct being stored in the list
typedef struct some_data_type {
    CG_ITEMIZABLE
    int random_data;
} some_data_type;

int main (void) {
    // Declare and define the list
    cg_mem_list data_list;
    cg_new_mem_list (&data_list, sizeof(some_data_type));

    // Allocates a new item and sets it up
    some_data_type* first_item = (some_data_type*)cg_mem_list_add(&data_list);
    first_item->random_data = 12;

    // <More additions and operations>

    // This frees the item
    cg_mem_list_remove(&data_list, (cg_mem_item*)&first_item);
}

I'd also like to note that I didn't implement any checks malloc or realloc because this is in a game-dev-related library, and I figure if it can't allocate any new memory it's probably gonna crash and burn either way. If you have any suggestions for how to gracefully handle this (other than just straight-up throwing an error and aborting, which is pretty much the same as crashing anyways for this sort of application honestly) I'd appreciate it.


texts: Private methods and properties in jQuery "lightweight start" pattern

texts:
For non-plugin code, I generally use the module pattern, but I'm working on a jQuery plugin and decided to try out the "lightweight start" pattern. The problem is, I find myself needing $.proxy when calling private methods to ensure the this context.

Is there a better way to structure the code in order to avoid $.proxy, while ensuring the private methods have access to the init() method's this context? Where exactly should I define private properties?

Jsfiddle example without $.proxy ... also have a jsfiddle example using $.proxy

(function($, window, document, undefined) {
var pluginName = "myPlugin",
    defaults = {
        opt1: "#opt1",
    };

function Plugin(element, options) {
    this.element = $(element);
    this.options = $.extend( {}, defaults, options);
    this._defaults = defaults;
    this._name = pluginName;
    this.init();
}

Plugin.prototype.init = function() {
    this.counter = 1;
    $("div").each(privateMethod1);
    $("body").on("click", this.options.opt1, event1);
};

function privateMethod2(i, div) {
    // "this" context is Window, not Plugin
    $(div).append(i);
    this.element.append(this.counter);
};

function privateMethod1(i, el) {
    // "this" context is Window, not Plugin
    this.counter += 1; // undefined, but defined in init()
    privateMethod2(i, el);
};

function event1(ev, el) {
    this.counter += 1; // undefined, but defined in init()
    privateMethod1(this.counter, el);
};

$.fn[pluginName] = function(options) {
    return this.each(function() {
        if (!$.data(this, "plugin_" + pluginName)) {
            $.data(this, "plugin_" + pluginName, new Plugin(this, options));
        }
    });
};
}(jQuery));

Edit:

What I learned. This pattern appears to actually make all methods private. This is because the if (!$.data(this, "plugin_" + pluginName)) { has no else block to handle elements that already have a reference to the plugin. To allow a method to be called, check out https://stackoverflow.com/a/14128485/536734.


texts:
Here's my code and I want to know if there's a better method for doing so. While the question has stated two stacks I wonder if we could do only with one as well?

/**
 * Created by mona on 5/26/16.
 */
import java.util.Stack;
//Implement queue using two stacks
public class QueueViaStacks {

    private int size=0;
    private Stack<Integer> firstStack = new Stack<>();
    private Stack<Integer> secondStack = new Stack<>();

    public void add(int item) {
        while (!firstStack.isEmpty()) {
            secondStack.push(firstStack.pop());
        }
        secondStack.push(item);
        while (!secondStack.isEmpty()) {
            firstStack.push(secondStack.pop());
        }
        size++;
    }

    public int remove() {
        size--;
        return firstStack.pop();

    }

    public int size() {
        return size;
    }

    public static void main(String[] args) {
        QueueViaStacks queue = new QueueViaStacks();
        queue.add(1);
        queue.add(2);
        queue.add(3);
        queue.add(4);
        queue.add(5);
        System.out.println(queue.remove());
        System.out.println(queue.size());
        System.out.println(queue.remove());
        System.out.println(queue.size());
    }

}


texts:
I was trying to solve the Median challenge at Interviewstreet.com.

I wasn't able to pass most of the test cases. But according to my understanding my code should work fine.

Here is the question:
https://www.interviewstreet.com/challenges/dashboard/#problem/4fcf919f11817

Here is my code:

    /* Sample program illustrating input and output */

    import java.util.*;

    class Solution{
public static void main( String args[] ){

     // helpers for input/output

    Scanner in = new Scanner(System.in);

    int N;
    N = in.nextInt();

    String s[] = new String[N];
    int x[] = new int[N];
    ArrayList<Integer> items=new ArrayList<Integer>();
    float result[]=new float[N];
    //int itemindex=-1;
    for(int i=0; i<N; i++){
        s[i] = in.next();
        x[i] = in.nextInt();

        switch(s[i].charAt(0))
        {

        case 'r':
            if(items.size()<=1)
            {
                result[i]=-1;

            }
            else
            {
                items.remove((Integer)x[i]);
                int itemindex=items.size();
                Collections.sort(items);
                if((itemindex)%2==0)
                {
                    result[i]=(float)         ((items.get((itemindex/2))+items.get(((itemindex)/2)-1))/2.0);

                }
                else
                {
                    result[i]=items.get((itemindex-1)/2);
                }

            }
            break;

        case 'a':
            items.add(x[i]);
            int itemindex=items.size();
            Collections.sort(items);
            if((itemindex)%2==0)
            {
                result[i]=(float)((items.get((itemindex/2))+items.get(((itemindex)/2)-1))/2.0);

            }
            else
            {
                result[i]=items.get((itemindex-1)/2);
            }

            break;

        }

    }

    for(int j=0;j<N;j++)
    {
        if(result[j]==-1)
        {
            System.out.println("Wrong!");
        }
        else
        {
            if((result[j]*10)%10==0)
            {
            System.out.println((int)(result[j]));
            }
            else
            {
                System.out.println(result[j]);
            }
        }

    }

}
    }

I would highly appreciate if someone could help me find out the test cases which will fail  for my code.

Thanks.


texts:
I have some .csv files compressed in .bz2 format. I need to take a subset of the records (and data) and switch to .gz.

I am not happy with the performance. Is there a more efficient way to do it?

//For each file in a folder:
try (BufferedReader br = new BufferedReader(new InputStreamReader(
        new BZip2CompressorInputStream(new FileInputStream(fileIn))));
     BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
        new GZIPOutputStream(new FileOutputStream(fileOut))))) {

    String line;
    while ((line = br.readLine()) != null) {
        String[] parts = line.split(',');
        if(isLineToSkip(parts[0])) {
            continue;
        }
        String outLine = parts[0] + "," + parts[3];

        writer.append(outLine);
        writer.newLine();
    }
} . . .


texts: Merge two sorted arrays, make more efficent (O(a+b))

texts:
Problem :Given two sorted arrays, merge them to form a new array of unique items.

  If an item is present in both arrays, it should be part of the resulting array if and only if it appears in both arrays the same number of times.

  e.g.: a = [1, 3, 40, 40, 50, 60, 60, 60] and b = [2, 40, 40, 50, 50, 65],
    should return [1, 2, 3, 40, 60, 65]

  a = [2,2,2,2,40,40,50] and b = [40,40,60] should return [2,40,50,60]

  a = [5,5] and b = [5,5,5] should return []

My problem is that my function is not efficient enough (runtime takes too long), is it possible to may it more efficient? Possibly O(a+b)

  function mergeArrays(a, b) {

      function countInArray(array, array2, what) {
          var count = 0;
          var count2 = 0;

          for (var i = 0; i < array2.length; i++) {
              if (array2[i] === what) {
                  count2++;
              }
          }
          for (var i = 0; i < array.length; i++) {
              if (array[i] === what) {
                  count++;
              }
          }
          return count === count2;
      }

      var arr = []
      for (x = 0; x < b.length; x++) {
          if (!a.includes(b[x]) && !arr.includes(b[x]))
              arr.push(b[x])
      }

      for (i = 0; i < a.length; i++) {
          if (countInArray(a, b, a[i]) && !arr.includes(a[i])) {
              arr.push(a[i])
          } else {
              if (!arr.includes(a[i]) && !b.includes(a[i]))
                  arr.push(a[i])
          }
      }

      console.log(arr)
      return arr.sort(function(a, b) {
          return a - b
      });
  }


texts: Correct practice for Python properties that depend on other attributes

texts:
When a property is essentially a boolean value for whether or not an attribute exists or is set a certain way, is it more appropriate to create an object that does not list the option attribute in its __init__() call, or is it better to simply create the object with the 'falsiest' version of that attribute?

Consider the following class:

class RectLikeObj(object):
    def __init__(self, x, y, w, h, pinned=None):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.pinned = pinned or ()

    ###series of property getter/setters for attributes that are
    ###derived from the above
    @property
    def topleft(self):
        return (self.x, self.y)

    @topleft.setter
    def topleft(self, value):
        self.x, self.y = value

    ###and so on for all corners and center, etc

    @property
    def is_pinned(self):
        if not self.pinned:
            return False
        return True

    def pin_corner(self, corner, xy):
        self.pinned = (corner, xy)

Alternatively the object may not ever have the self.pinned attribute and the property is instead looking for the attribute.

class RectLikeObj(object):
    def __init__(self, x, y, h, w):
        self.x = x
        self.y = y
        self.w = w
        self.h = h

    ###same getters/setters as above

    @property
    def is_pinned(self):
        if getattr(self, 'pinned', False):
            return True
        return False

    def pin_corner(self, corner, xy):
        self.pinned = (corner, xy)

Now it could be done to use a try/except, only there's nothing exceptional about this behavior; it's quite binary, either the Rect object is pinned to a particular corner and xy coordinates or it isn't. So I don't know that using eafp is the most correct choice here.

Is it better to use a 'falsy' attribute such as self.pinned = () in the __init__() method, or is it better to leave it to be set later by the self.pin_corner() method and then use the property to check for its existence?


texts:
I'm at uni and working on an assignment in c# that takes some user input (from they keyboard via console).

The input validation required:

numbers must be within range (range will vary depending on which menu they're in)
strings must not be empty/null
string must be no longer than 30 characters in length

So I've chosen to write just one method (will be a static method of a 'validator' class) that can handle validation for both and am unsure if this is a good idea - having a method that essentially does more than one thing.

The method:

public static bool isValid(string input, string type, int min = 0, int max = 0)
  {
     if (String.IsNullOrEmpty(input))
        return false;
     else
     {
        switch (type.ToLower())
        {
           case "integer":
              int i;
              if (Int32.TryParse(input, out i))
                 return ((i >= min) && (i <= max));
              else
                 return false;
           case "string":
              return input.Length < charLimit; // charLimit defined as 30 above
           default:
              return false;
        }
     }
  }

And a sample call:

if(isValid(userInput, "integer", 0, 5)
{
   // do something awesome
}

I've run some tests to check the edge cases and passing in empty strings etc and it passed them, but for some reason this feels kind of wrong.

Should I separate string and integer validation into separate methods?


texts: How can I make a shorter binary rule in haskell?

texts:
Here is a code I experimented with recently:
let br = [0]:[n:(concat $ take n br) | n <- [1..]] in concat br

This code produces the binary rule 0 1 0 2 0 1 0 3 ...
Here is the idea of how it works:

create a list starting with [0]

each step, concatenate all the current elements in the list, put the next number at the begining and add at the end.

[[0] ...]
[[0], [1, 0] ...]
[[0], [1, 0], [2, 0, 1, 0]...]
[[0], [1, 0], [2, 0, 1, 0], [3, 0, 1, 0, 2, 0, 1, 0] ...]
...

My question now is: is there a shorter/smarter one-liner to get this infinite lazy binary-rule ?
Edit:
I found another way to do the same thing:
let f n = if n==0 then [0] else n:([0..n-1] >>= f) in [0..]>>= f

The extra question would be: wich one of the 2 version is more readable for an haskell programmer, and why ?


texts:
I'm relatively new to JavaScript OOP and would like to know the best practice when doing a simple object such as a Model.

Here's a piece of code representing class named Child:

What I'm asking for is:

The usage of this (and the weak reference I'm doing which I name self)
The global shape of the code (methods in prototype etc)
Declaring a class as a function, or with JSON semantics

var Child = function( json ) {
    var self = this;
    // Properties
    this.id = 0;
    this.firstname = "";
    this.moneyCurrent = 0;
    this.moneyDue = 0;
    this.missionsPlay = 0;
    this.missionsWait = 0;
    this.missionsStop = 0;

    this.missions = [];

    this.initialize( json );
}

Child.prototype = {
    initialize: function( json ) {
        var self = this;
        self.id = json.id_child;
        self.firstname = json.firstname;
        self.moneyCurrent = parseFloat(json.already_paid) + parseFloat(json.to_pay) - parseFloat(json.spent_money);
        self.moneyDue = parseFloat(json.to_pay);
        self.missionsPlay = json.nb_missions.in_progress;
        self.missionsWait = json.nb_missions.waiting;
        self.missionsStop = json.nb_missions.completed;
    },

    getMissions: function( type, callback ) {
        var self = this;
        session.requestServer( "parent_getChildMissionList", {
            sid: session.sid,
            id_child: self.id,
            status: type ? type : "",
            strict_status: false,
            page: 0
        }, function( data ){
            var missions = [];
            $(data.missionList).each(function(){
                self.missions.push(new Mission(this));
                missions.push(self.missions[self.missions.length-1]);
            });
            callback( missions );
        });
    },
};

Classic way to declare a class:

var obj = function() {
    var attribut = "foo";
    this.metho = function(parameter1, parametre2) {
        alert("parameters: " + parameter1 + ", " + parameter2);
    }
}

JSON way to declare a class:

var obj = {
    attribut: "foo",
    method: function(parameter1, parameter2) {
        alert("parameters: " + parameter1 + ", " + parameter2);
    }
}


texts:
This jQuery code submits a form using AJAX. The server response should return JSON.

addNewOutreach = function(node)
    {
    var form = node.find('form');
    var data = form.serialize();

    $.post('ajax.php',
    {action:'addNewOutreach',string:data},
    function(response) {
        if(response!=null && response.status=='success')
            {
            message_return('success',response.message);
            unfreezeModal(node);
            node.modal('hide');
            }
        else if(response!=null && response.status=='error')
            {
            message_return('error',response.message);
            unfreezeModal(node);
            }
        else
            {
            message_return('error','Error saving outreach.');
            unfreezeModal(node);
            }
        },'json');
    }

message_return() is a function that displays feedback on the page.

unfreezeModal() is a function that locks the form (avoiding double submits) until the request is finished.

Where this code lacks:

What if the server does not respond with valid JSON?
What if the AJAX request keeps hanging?
The function(response) block can probably be isolated from this block so it can be used in other AJAX request
Can probably be written cleaner with Promises


texts: Adding some properties to an Active Directory user

texts:
I was writing the below section of code which adds some user properties to an Active Directory user, and got wondering - surely we can improve the readability of this :

var firstname = newUser.FirstName;
var lastname = newUser.LastName;
var email = firstname + lastname + "@mydomain.com";
var dotname = $"{firstname}.{lastname}";
var fullname = $"{ firstname} { lastname}";

// Create the new user
var user = myLdapConnection.Children.Add($"CN={firstname} {lastname}", "user");
// Add properties
user.Properties["userprincipalname"].Add(email);
user.Properties["samaccountname"].Add(dotname);
user.Properties["sn"].Add(lastname);
user.Properties["givenname"].Add(firstname);
user.Properties["displayname"].Add(fullname);
user.Properties["description"].Add(newUser.JobTitle);
user.Properties["mail"].Add(email);
user.Properties["homedirectory"].Add($@"\\File\Home$\{dotname}");
user.Properties["homedrive"].Add("H:");
user.CommitChanges();

So I added some tabs after my property-name calls like so :

// Add properties
user.Properties["userprincipalname"].Add(email);
user.Properties["samaccountname"]   .Add(dotname);
user.Properties["sn"]               .Add(lastname);
user.Properties["givenname"]        .Add(firstname);
user.Properties["displayname"]      .Add(fullname);
user.Properties["description"]      .Add(newUser.JobTitle);
user.Properties["mail"]             .Add(email);
user.Properties["homedirectory"]    .Add($@"\\File\Home$\{dotname}");
user.Properties["homedrive"]        .Add("H:");
user.CommitChanges();

Now I think that makes the code a lot more readable, but I have not seen many people take this approach when formatting. Is there any reason for this? I generally do this in both PowerShell and C#, but are there any languages where this is not acceptable for reasons other than the code wont run?


texts: Multiview for inserting and editing users

texts:
I have a multiview to insert and edit users. Users are listed in a gridview. In selectedindexchanged event of gridview I've placed this code:

protected void GrvList_SelectedIndexChanged(object sender, EventArgs e)
{
    // EditView
    FrmaddEditUsers.ActiveViewIndex = 1;
    // Get Username
    UserName.Text = GrvList.DataKeys[GrvList.SelectedIndex].Value.ToString();
}

I wonder if it's necessary to change it as below, being afraid of values are changed by bad users:

protected void GrvList_SelectedIndexChanged(object sender, EventArgs e)
{
    // change to EditView
    FrmaddEditUsers.ActiveViewIndex = 1;
    // Get Username from gridview and display in txtbox
    string ToBeEditedUser = GrvList.DataKeys[GrvList.SelectedIndex].Value.ToString();
    UserName.Text = HttpUtility.HtmlEncode(ToBeEditedUser);
}


texts:
I am studying JavaEE and I have made my project for the learning experience.

I want to understand how best to write code from the point of view of architecture and use of relevant technologies.  I am particularly interested to hear about the implementation of the REST-layer.

The purpose of this is the backend to the Android application.
Uses postgres, wildfly(EJB) and REST.

This is one from many methods in REST layer.

@POST
@Path("/reg")
@Produces(MediaType.APPLICATION_JSON)
public Response create(@QueryParam("email") String email, @QueryParam("pass") String pass) {
    log.info("create user");
    log.debug("create user: email=" + email + " pass=" + pass);
    Response response;
    try {
        response = Response.ok().entity(userM.reg(email, pass)).build();
        log.info("reg ok");
    } catch (Exception e) {
        AppException err = new AppException(e);
        response = Response.serverError().status(err.getCode()).entity(err).build();
        log.info("reg fail");
    }

    return response;
}


texts: Given any positive range, count the values that are complete squares

texts:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please choose the minimum of your range: ");
        double minimum = scanner.nextInt();
        System.out.println("Please choose the maximum of the range: ");
        double maximum = scanner.nextInt();
        List<Double> list = new ArrayList<>();
        List<Double> doubles = new ArrayList<>();
        int sum = 0;
        for (double x = minimum; x <= maximum; x++) {
            list.add(x);
        }
        for (int i = 0; i < list.size(); i++) {
            double sqrt = Math.sqrt((i));
            doubles.add(sqrt);
        }
        for (Double value : doubles) {
            if (value.doubleValue() == value.intValue()) {
                sum += 1;
            }
        }
        System.out.println(sum);
    }
}


texts: How many chores can you accomplish in a set time?

texts:
I am learning java and doing some practice problems. My code works, but I feel like I used a workaround sort of way to accomplish it. Is there another way to express what I want the program to do?

Question: Problem J4: Time on task

  Input specification:

    First line is the total number of minutes to accomplish the chores.

    Second line is number of chores to choose from

    The next 'n' lines are how long each chore takes to complete.

  Output specification:

    The total amount of chores one can do given the amount of time

My code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Time {

public static void main(String args[]) {
    try {
        BufferedReader input = new BufferedReader(new InputStreamReader(
                System.in));

        //get the amount of time
        int maxMins = Integer.parseInt(input.readLine());
        //get the total amount of chores
        int totalChores = Integer.parseInt(input.readLine());
        //create an array to store each chore and how long it takes to complete it
        int[] list = new int[totalChores];

        for (int i = 0; i < totalChores; i++) {
            list[i] = Integer.parseInt(input.readLine());
        }
        Arrays.sort(list);

        //initialize counters, one for minutes and the other for chores done
        int totalMins = 0;
        int chores = 0;

        //I don't like the below part, not quite sure how to change it
        for (int j = 0; totalMins < maxMins; j++) {
            totalMins = totalMins + list[j];
            if (totalMins <= maxMins) {
                chores++;
            }
        }

        System.out.println(chores);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

}


texts: Generating variables to be named, filled in and operated on the fly in Python

texts:
I am very new to Python and trying to refactor my code which is ripe for error.

Currently, I manually name a bunch of arrays:

open_cost_mat_train = np.array([])
closed_cost_mat_train = np.array([])
open_cost_mat_train_1 = np.array([])
closed_cost_mat_train_1 = np.array([])
open_cost_mat_train_2 = np.array([])
closed_cost_mat_train_2 = np.array([])

I then pass them to a function that fills the arrays in differently according to their number (e.g. _1, _2, and also if their name contains open or closed):

for i in xrange(10):
    open_cost_mat_train = np.append(open_cost_mat_train,i)
    open_cost_mat_train_1 = np.append(open_cost_mat_train_1,i/3))
    open_cost_mat_train_2 = np.append(open_cost_mat_train_2,i*64))
    closed_cost_mat_train = np.append(closed_cost_mat_train,i*3)
    closed_cost_mat_train_1 = np.append(closed_cost_mat_train_1,i/5))
    closed_cost_mat_train_2 = np.append(closed_cost_mat_train_2,i*102))

I then generate output file paths which corresponds with those matrices:

open_cost_category_path = "openCostClassifier.dat"
closed_cost_category_path = "closedCostClassifier.dat"
open_cost_category_path_1 = "openCostClassifier_1.dat"
closed_cost_category_path_1 = "closedCostClassifier_1.dat"
open_cost_category_path_2 = "openCostClassifier_2.dat"
closed_cost_category_path_2 = "closedCostClassifier_2.dat"

And finally I pass those variables to a new function (not necessary to show this for sake of question:

csoaa_open = example(open_cost_mat_train,open_cost_category_path)
csoaa_closed = example(closed_cost_mat_train,closed_cost_category_path)
csoaa_open_1 =example(open_cost_mat_train_1,open_cost_category_path_1)
csoaa_closed_1 = example(closed_cost_mat_train_1,closed_cost_category_path_1)
csoaa_open_2 = example(open_cost_mat_train_2,open_cost_category_path_2)
csoaa_closed_2 = example(closed_cost_mat_train_2,closed_cost_category_path_2)

What am I doing wrong with my code and how can I improve how I do things? Because this is the way I have written a lot of my code and getting one variable wrong. Doing this, for instance, will mess up the whole of my code:

csoaa_closed_1 = example(closed_cost_mat_train_2,closed_cost_category_path_1)


texts: Using chartJS in Angularjs to plot IOT data

texts:
I am a Javascript and AngularJS beginner.

Below is the code inside my chartController. What this does is get IOT data from a back-end call and display it in my front-end with a chart. There are two helper functions for the  chart: addData() and remove() to add and remove data. These functions make it so that the chart gets new data to the right of the chart and removes data on the left. This is what I have so far.
It would be appreciated if someone would give me tips on how:

to make my controller less stacked, get data -> draw chart -> update chart.
to make the get method more generic. The URL is now hardcoded.

var vm = this;
vm.content = [];
vm.dataContent = [];

$http({
  method: 'GET',
  url: 'http://localhost:8080/data/Living Room'
})
  .then(function successCallback(response) {

    JSON.stringify(response.data);

    angular.forEach($scope.content, function (value) {
      vm.dataContent.push(value.inputData);

    });

    $scope.content = response.data;

    var canvas = document.getElementById("myChart");
    var ctx = canvas.getContext("2d");

    var dataChart = {
      labels: ["January", "February", "March", "April", "May", "June", "July"],
      datasets: [{
        label: "Testing my Set",
        data: vm.dataContent
      }]
    };;

    var settings = {
      type: "line",
      data: dataChart
    };

    var myNewChart = new Chart(ctx, settings);

    function addData(chart, data, label) {
      chart.data.labels.push(label);
      chart.data.datasets.forEach(function (dataset) {
        dataset.data.push(data);
      });
      chart.update();

    }

    function remove(chart) {
      chart.data.labels.shift();
      chart.data.datasets.forEach(function (dataset) {
        dataset.data.shift();
      });
      chart.update();
    }

    setInterval( function(){

      addData(myNewChart, 16,  'working on it');

      // Remove the first point so we dont just add values forever
      remove(myNewChart);
    }, 5000);

  }, function errorCallback(response) {
    return alert(response.status)
  });


texts: Implementation of Vertex Similarity algorithm (Blondel's Similarity Measure)

texts:
I am implementing the vertex similarity algorithm in this paper. The adjacency matrices I will be dealing with, however, will be very large, on the order of 30k vertices (I provided sample matrices in the main method).

The algorithm is to calculate S(k+1) as an iterative matrix. The algorithm is given on page 2 of the paper (listed as 114).

According to the paper, the implementation below is correct. What I want feedback on is memory efficiency, to not make new matrices as much as possible.

public class Matrix {
private final int M, N;
private final double[][] data;

public Matrix(int M, int N) {
    this.M = M;
    this.N = N;
    data = new double[M][N];
}

public Matrix(double[][] data) {
    M = data.length;
    N = data[0].length;
    this.data = new double[M][N];
    for (int i = 0; i < M; i++)
        for (int j = 0; j < N; j++)
                this.data[i][j] = data[i][j];
}

public Matrix transpose() {
    Matrix A = new Matrix(N, M);
    for (int i = 0; i < M; i++)
        for (int j = 0; j < N; j++)
            A.data[j][i] = data[i][j];
    return A;
}

public Matrix plus(Matrix B) {
    Matrix A = this;
    assert B.M != A.M || B.N != A.N;
    Matrix C = new Matrix(M, N);
    for (int i = 0; i < M; i++)
        for (int j = 0; j < N; j++)
            C.data[i][j] = A.data[i][j] + B.data[i][j];
    return C;
}

public Matrix times(Matrix B) {
    Matrix A = this;
    assert A.N == B.M;
    Matrix C = new Matrix(A.M, B.N);
    for (int i = 0; i < C.M; i++)
        for (int j = 0; j < C.N; j++)
            for (int k = 0; k < A.N; k++)
                C.data[i][j] += (A.data[i][k] * B.data[k][j]);
    return C;
}

@Override
public String toString() {
    StringBuilder s = new StringBuilder();
    for (int i = 0; i < M; i++) {
        for (int j = 0; j < N; j++) {
            s.append(data[i][j]).append(" ");
        }
        s.append("\n");
    }
    return s.toString();
}

public static void main(String[] args) {
    // Sample matrices
    double[][] a = {
            {0,1,0,1},
            {1,0,1,0},
            {0,1,0,0},
            {1,0,0,0}
    };
    double[][] b = {
            {0,0,1,1,0,0},
            {0,0,0,1,0,1},
            {1,0,0,0,1,1},
            {0,0,0,0,0,0},
            {0,0,0,0,0,0},
            {1,0,1,1,0,0}
    };
    // Xk is the iteration of the algorithm matrix.
    double[][] xk = new double[b.length][a[0].length];
    for (int i = 0; i < xk.length; i++) {
        for (int j = 0; j < xk[0].length; j++) {
            xk[i][j] = 1;
        }
    }
    Matrix X = new Matrix(a);
    Matrix Y = new Matrix(b);
    Matrix Sk = new Matrix(xk);
    int n = 10; // number of iterations of algorithm
    for (int i=0; i<n; i++) {
        // This is the actual algorithm.
        Matrix firstProduct = Y.times(Sk).times(X.transpose());
        Matrix secondProduct = Y.transpose().times(Sk).times(X);
        Matrix totalProduct = firstProduct.plus(secondProduct);
        double[][] data = totalProduct.transpose().data;
        Sk = new Matrix(normalizeByRows(data)).transpose();
        System.out.println(Sk);
        System.out.println("------------");
    }
    // This is to calculate the average value in Sk.
    double[][] data = Sk.data;
    double sum = 0.0;
    int count = 0;
    for (double[] j : data) {
        for (double l : j) {
            count++;
            sum += l;
        }
    }
    sum /= count;
    System.out.println(sum);
}

private static double[][] normalizeByRows(double[][] data) {
    for (int k=0; k<data.length; k++) {
        double[] row = data[k];
        double max = 0;
        for (double l : row) {
            max += l;
        }
        for (int l = 0; l < data[k].length; l++) {
            data[k][l] /= max;
        }
    }
    return data;
}
}


texts:
This works but feels clunky - any suggestions for improvement?

public static <T extends View> T findViewByClassReference(View rootView, Class<T> classReference){
  if(classReference.isInstance(rootView)){
    return classReference.cast(rootView);
  }
  if(rootView instanceof ViewGroup){
    ViewGroup viewGroup = (ViewGroup) rootView;
    for(int i = 0; i < viewGroup.getChildCount(); i++){
      View child = viewGroup.getChildAt(i);
      View match = findViewByClassReference(child, classReference);
      if(match != null){
        return classReference.cast(match);
      }
    }
  }
  return null;
}


texts: Using >= even though it's impossible for > to be true

texts:
I can't find an answer to this question either because it doesn't exist or because I am incapable of searching for it correctly.
Consider this code which prints out the numbers from 1 to 12 ad infinitum:
month = 1
while True:
    print(month)
    month += 1

    if month == 13:  # month >= 13 ? month > 12 ?
        month = 1

Is there any reason that the line if month == 13 shouldn't be written as if month > 12, you know, "just in case?" I feel like it's "safer" to write if month > 12 or if month >= 13, but I know that month > 13 will never be true. Is there any agreed-upon best practice in a situation like this?
To be clear, I'm not looking for a way to improve this specific code. I'm looking for guidance on what I should do in this situation (and others like it).


texts:
I got sick of manually xrandering things on my computers (especially since I always just sequence monitors from left to right and set each at the highest resolution) so I wrote this:

#!/usr/bin/ruby

def xrandrPairs (xList)
## Takes a split list of xrandr output and returns [[<display name>, <max-resolution>], ...]
  pairs = [[matchDisplay(xList[0]), matchOption(xList[1])]]
  (2..xList.length-1).to_a.each do |i| # kind of hacky, but I need to reference car and cadr here, so a call to .map won't do it
    if xList[i] =~ /^\S/
      pairs.push([matchDisplay(xList[i]), matchOption(xList[i+1])])
    end
  end
  pairs
end

def matchDisplay (dispString)
## Matches a display name
  dispString.match(/^([^\s]*)/)[1]
end

def matchOption (optString)
## Matches a resolution string (since they have whitespace preceding them)
  optString.match(/^\s*([^\s]*)/)[1]
end

def xrandrString (xPairs)
## Takes [[<display name>, <max-resolution>] ...] and returns an xrandr command string
  s = "xrandr --output #{xPairs[0][0]} --mode #{xPairs[0][1]}"
  if xPairs.length >= 2
    (1..xPairs.length-1).to_a.each do |i| # same as above
      s += " --output #{xPairs[i][0]} --mode #{xPairs[i][1]} --right-of #{xPairs[i-1][0]}"
    end
  end
  s
end

exec xrandrString(xrandrPairs(`xrandr`.split("\n")[1..-1]))

The key is that each computer I use has different displays (they're named differently and they have different maximum resolutions), so as far as I know, I have to either parse xrandr output or write a different script for each machine.

I don't care that it's inefficient (traversing the xrandr output multiple times and doing some looped string formatting) because it only runs once at startup time, and deals with a list of 30 elements at the outside. I'm using Ruby 1.8.7 straight out of the Squeeze repos for ease of installation (this is also why I wouldn't mind being shown how this works in Python/Perl; those come with the system).

Can I get some comments on it?


texts:
There's a lot of place in my code where I need to do something like this

public static void read(DataInputStream stream) throws IOException
{
  try
  {
      Object thing = getById(stream.readInt());
  }
  catch(IllegalArgumentException ex)
  {
      throw new IOException(ex); // do not throw IllegalArgumentException if the corrupted data points to invalid things
  }
}

public static Object getById(int id)
{
    for(Object thing : things)
        if(thing.getId() == id)
            return thing;

  throw new IllegalArgumentException("Thing with id " + id + " does not exist!");
}

I like the fact that read() only throws IOExceptions and wrap any detail of internal failure with IOException as having those failures are caused by having corrupted data from the stream. (And corrupted data should return IOException, could return something else but the idea is the same).

What I really don't like is the tedious process of wrapping all my exceptions everytime and incrementing the number of indents I have just to indicate that IllegalArgumentException becomes IOException. An annotation like this

@WrapExcept(IllegalArgumentException.class, ex -> new IOException(ex))
public static void read(DataInputStream stream) throws IOException
{
  Object thing = getById(stream.readInt());
}

would be perfect but I have no idea how it could be possible. The best I could come up with is something along the lines of

@FunctionalInterface
public interface ThrowingCall<R, E extends Throwable>
{
    R call() throws E;
}

public static <R, W extends Throwable, E extends Throwable, T extends Throwable>
R wrapExcept(ThrowingCall<R, T> call, Class<W> exType, Function<W, E> wrapper) throws E, T
{
    try
    {
        return call.call();
    }
    catch(Throwable t)
    {
        if(exType.isInstance(t))
            throw wrapper.apply(exType.cast(t));
        throw t;
    }
}

public static void read() throws IOException
{
    Object thing = wrapExcept(() -> getById(3), IllegalArgumentException.class, ex -> new IOException(ex));
}

Any idea to make this code look likes less verbose? Obviously what I want to improve is the read() call's readability. Also I'm not sure how ThrowingCall could be replaced by something more standard.


texts:
This is my current code:

def search(word,source):
    places = []
    for x in range(0,len(source)):
        if source[x] == word[0]:
            if source[x:x+len(word)] == word:
                places.append(x)
    return places

How would I optimize this without using regular expressions?


texts: Print every character in a line if it's greater than 80 characters

texts:
How can I improve this program?

#include <stdio.h>
#define MIN 80

int main(void)
{
    char line[MIN];
    int i, c;

    for (i = 0; (c = getchar()) != EOF && c != '\n'; ++i)
    {
        if (i < MIN - 1)
            line[i] = c;
        else
        {
            if (i == MIN - 1)
                printf("%s", line);

            printf("%c", c);
        }

    }

    return 0;
}


texts: Search a string for barcodes but ignore certain characters

texts:
I had to write a string search function that would search for barcodes, and be forgiving of minor formatting differences. For example, the barcode may be entered as YF 1942-AB in the customer's database, but a barcode scanner may read the barcode as YF1942AB.

The goal is to get the correct substring indices (range) for highlighting the text on an element, such as:

let text = "Serial: YF 1942-B (Scanned)"
let range = text.rangeOfStringWithIgnoredCharacterSet("YF1942B")
print(range) // (8, 16)

The approach I took was to do a regular string search but just ignore certain characters, and "sanitize" the search string before doing the search in earnest.

import Foundation

extension String {

    subscript (i: Int) -> Character {
        return self[self.startIndex.advancedBy(i)]
    }

    subscript (i: Int) -> String {
        return String(self[i] as Character)
    }

    subscript (r: Range<Int>) -> String {
        let start = startIndex.advancedBy(r.startIndex)
        let end = start.advancedBy(r.endIndex - r.startIndex)
        return self[Range(start ..< end)]
    }

    func rangeOfStringWithIgnoredCharacterSet(search: String, ignoredCharacterSet: NSCharacterSet = NSCharacterSet.alphanumericCharacterSet().invertedSet, options: NSStringCompareOptions = .CaseInsensitiveSearch) -> Range<String.Index>? {
        let newSearch = search.componentsSeparatedByCharactersInSet(ignoredCharacterSet).joinWithSeparator("")
        if newSearch.isEmpty {
            return nil
        }
        var i = 0
        while i < self.characters.count {
            if newSearch.characters.count > self.characters.count - i {
                break
            }
            var startIndex = -1
            var endIndex = 0
            var j = 0
            while j < newSearch.characters.count {
                let k = i + j
                if k >= self.characters.count {
                    break
                }
                let c: String = self[k]
                if c.rangeOfCharacterFromSet(ignoredCharacterSet) != nil {
                    i += 1
                } else if c.compare(newSearch[j], options: options) == .OrderedSame {
                    if startIndex == -1 {
                        startIndex = k
                    }
                    endIndex = k
                    j += 1
                } else {
                    break
                }
            }
            if j == newSearch.characters.count && startIndex >= 0 {
                return self.startIndex.advancedBy(startIndex)...self.startIndex.advancedBy(endIndex)
            }
            i += 1
        }
        return nil
    }
}

It all works properly, but it definitely feels a bit bolted together, since I'm using Int indices as well as dealing with String.Index types. I'd prefer to use String.Index exclusively, if possible, but Swift doesn't appear to have the equivalent of std::iterator<T>::end from the C++ STL, so I'm not sure if this is even possible.


texts: ASP.NET MVC website that display blogs from the database by AJAX

texts:
The problem is, I have to limit the results to only 10 by default and add a "Load More" button to display 10 more results each time when user click the button. But I'm worried about users having their JavaScript disabled, because in that case, users won't be able to see more blogs.

But I can also use MVC Razor Syntax codes to display more results by requesting the URL parameters by a button inside a form and it's also works fine and it's only a few lines of codes, but the only problem is the URL parameters showing in the address bar and I don't want them to be showing up.

Now I'm putting my MVC Razor Syntax codes to inside a  tag for JavaScript Backup and it's working perfectly.

What I want to know is there any disadvantage of doing this or if there is any better solution to achieve this. I don't know much about the NoScript tags or how that works with Razor Syntax codes.

.cshtml

    @{
        var rowsNumb = 10;
        var db = Database.Open("Northwind");
        rowsNumb = Request["lastRec"].AsInt() + 10;
        var maxRecs = db.QueryValue("SELECT COUNT([Product Id]) FROM Products");
        var sql = @"SELECT * FROM Products ORDER BY [Product Id] OFFSET 0 ROWS FETCH NEXT @0 ROWS  ONLY";
        rowsNumb = (rowsNumb > maxRecs ? maxRecs : rowsNumb);
        var result = db.Query(sql, rowsNumb);
    }

        @foreach(var row in result){

                @row["Product Name"]
                @row["English Name"]
                @row["Unit Price"]

        }

    <form>
        <input type="hidden" name="lastRec" value="@rowsNumb" />
        <button type="submit">Load More</button>
    </form>


texts:
I am a beginner to PHP programming.  I wanted to make a 2D array that would store the values of a table into the array. Below is the Frankenstein code I created (every time I wanted to achieve a task I researched a solution, so this is a bunch of solutions plus my own doing put together).

I would be really grateful if anyone could offer any improvements to my code. One thing I am slightly unsure of is the use of the unset function. I understand that it 'destroys' a variable to free up memory(?), but I am not entirely sure where/ if to use it.

<?php
$sql = "DESCRIBE $table"; // get a list of all fields and datatypes (ignore the latter)
$retval = mysqli_query($conn, $sql);
$iii = 0; // counter variable
while ($tableHead = mysqli_fetch_array($retval, MYSQLI_ASSOC))
{
    $colNames[$iii] = $tableHead["Field"]; // store each column name in array
    $iii++;
}
unset($iii);

$sql = "SELECT * FROM $table"; // get a list of all fields and datatypes (ignore the latter)
$retval = mysqli_query($conn, $sql);
$iii = 0; // counter variable
while ($row = mysqli_fetch_array($retval, MYSQLI_ASSOC))
{
    // create a 2D array, $iii for x and $jjj for y
    for ($jjj = 0; $jjj < $colCount; $jjj++)
    {
        $tableContent[$iii][$colNames[$jjj]] = $row[$colNames[$jjj]];
    }
    $iii++; // move onto next row
}
unset($iii, $jjj);
?>

EDIT: I have attached some pictures of what I have created. The quick report just reads the ID and returns any ID that is not found in the database or in the CSV. The full report is not yet developed but will check in more depth by checking each field one at a time and reporting the differences to the user.

The CSV looks like this:

1,a
2,b
3,c
4,d
5,e
6,f
7,g
8,h
9,i

The front page:

The result:


texts:
Here is something I've been working on today..

I been trying to determine how to build a website, that has a form, and that form allows a user to make a simple URL to give out. In the future it will also create a website, or possible websites (based off of varying templates that I have built for it).

I just started trying to understand this today, so bear with me...

So far, as far as I am aware, all of the code works and accomplishes the following:

Allows a user to input a Website name.. I keep both a version with spaces, and a version without spaces.
It creates a directory for that name with no spaces, and it creates a index.php in that directory.
It then displays the link to said directory(will not work on this code because I use a generic primary domain name).

Example Test Domain:

  www.PrimaryDomain.com/Test/

Example User Input:

$_POST['Dir'] = 'Test User Domain';

<?php
//Make sure server is in post mode
if($_SERVER['REQUEST_METHOD'] != 'POST')
    {
        //display form
        echo'<form name="" action="" method="post" class="wpcf7-form" >';
            echo'<input name="Dir" type="text" placeholder="Username" required autofocus>';
            echo'<input type="submit" value="Start" class="wpcf7-form-control wpcf7-submit">';
        echo'</form>';
    }
else
{
    //Specify the URL
    $Name = mysql_real_escape_string($_POST['Dir']); //form data
    $CurrentDir = getcwd(); //current directory
    $URL = ''.$CurrentDir.'/'.$Name.'/'; //New url to create

    //Speciy the file to create
    $Index_file = ''.$URL.'index.php'; //location of new index.php file

    //Remove the spaces, and make each it's own variable
    $Index_file = str_replace(' ', '', $Index_file); //the location of index.php
    $Dir_No_Space = str_replace(' ', '', $URL); //the main directory
    $Name_No_Space = str_replace(' ', '', $Name); //the form data the user entered

    mkdir('/'.$Dir_No_Space.'', 0777, true); //make the directory
    $handle = fopen($Index_file, 'w') or die('Cannot open file:  '.$Index_file); //Create the index.php File

    //Source code of the File: index.php
    $index_data = '

This is an example

    ';

    fwrite($handle, $index_data); //write the source code to the index.php file

    //Check the Document Creation
    if(!fwrite)//if error
        {
        echo'Error
';
        echo mysql_error(); //debugging
        }

    else//if not error
        {
        //tell the user how to access the new page
        echo'
This is a test in progress for '.$Name.' View @ www.PrimaryDomain.com/Test/'.$Name_No_Space.'/.';
        }
}
?>

What do you guys/gals think? Is there a better method for this?


texts: Infinite producer using BlockingCollection

texts:
Please have a review of this Code chunk and let me know whether it is a good way for infinite Producer?

UniqueStrings = new BlockingCollection<string>(10);
        Task.Run(() =>
        {
            while (true)
            {
                try
                {
                    UniqueStrings.Add(GetNextUniqueStringNumber("RCH04"));
                }
                catch (OperationCanceledException e)
                {
                    Console.WriteLine("ERROR_UNIQUE_STRING_ADD: {0}", e.Message);
                }
            }
        });

Where GetNextUniqueStringNumber("RCH04") gives unique string every time. In other words, I want Unique string readily available every time Consumer takes from it.

EDIT:

public void Process()
    {
        while (!ProcessedCollection.IsCompleted)
        {
            try
            {
                string stringId = UniqueStrings.Take();
                Console.WriteLine("Unique String: {0}", stringId);
                // TODO - Use this String Id for further processing
            }
            catch (OperationCanceledException e)
            {
                Console.WriteLine("DATABASE_MANAGER: Operation Canceled. " + e.Message);
            }
        }
    }


texts: Lots of Continues in an Inner Loop and Dictionary of Actions

texts:
I'm using ABCPDF (Version 8) to update an existing PDF document and I believe its API is hurting me in this situation and was curious whether anyone had any comments on how this looks as it appears ugly to me.

The situation: I am replacing pages in PDF documents that are all generated by an in-house process so I can rely on their format being consistent and the following code is tasked with updating annotation links on the Table of Contents page(s) to point to the replace pages instead of the old pages. Since there can be multiple replacement operations, I decided to put the collection of these link annotations into a dictionary instead of looping through all of them for each replacement operation.

As my comments in the code mention, I only was able to piece this together by debugging a lot and examining the properties of different ABCPDF objects.

Here's the relevant code:

//use less than or equal to here because a one page TOC will have a matching start and end page number
private Dictionary<int, Action<int>> _linkUpdates;
WebSuperGoo.ABCPDF8.Doc pdfDoc;
for (var pageNumber = startPageNumber; pageNumber <= endPageNumber; pageNumber++)
{
    pdfDoc.PageNumber = pageNumber;
    var annotCount = pdfDoc.GetInfoInt(pdfDoc.Page, "Annot Count");

    //this is really ugly code that looks for link annotations (i.e. links in the TOC) that reference our old page Id
    //it depends on some nasty PDF data structures in ABCPDF and assumes they will always appear the same way
    //it took me a few hours of debugging to figure out how to get at this stuff and modify it, not pleasant
    for (var i = 1; i <= annotCount; i++)
    {
        //if at any level we come up empty, just get out of this annotation and try the next one
        var annotId = pdfDoc.GetInfoInt(pdfDoc.Page, string.Format("Annot {0}", i));
        var annotationMaster = (Annotation)pdfDoc.ObjectSoup[annotId];
        if (annotationMaster.SubType != "Link")
        {
            continue;
        }
        var annotItem = annotationMaster.Resolve(Atom.GetItem(annotationMaster.Atom, 0)) as DictAtom;
        if (annotItem == null)
        {
            continue;
        }
        var destination = annotItem["D"] as ArrayAtom;
        if (destination == null)
        {
            continue;
        }
        var destinationPage = destination[0] as RefAtom;
        if (destinationPage == null)
        {
            continue;
        }
        _linkUpdates.Add(destinationPage.ID,
            updatedPageId =>
            {
                destinationPage.ID = updatedPageId;
                Atom.SetItem(destination, 0, destinationPage);
            }
        );
    }
}

I included the declarations of _linkUpdates and doc for reference. So after I have this collection populated, when I have an update to make, I can simply do this:

if (_linkUpdates.ContainsKey(oldPageId))
{
     _linkUpdates[oldPageId](newPageId);
}

I fully understand that this logic is heavily dependent on an understanding of how ABCPDF works, but since there's a fairly active community on SO, I figured this might get some responses, perhaps from somebody who knows of an easier way of getting at/updating these link annotations.

So, to summarize the areas I am interested in feedback on are:

The prevalence of continues in my inner for loop
The choice of using a dictionary with an Action value to update the related ABCPDF object

This does work fine, and I am operating in an environment where I will have at most 70 possible link annotations to consider.


texts: Zero pad function trim extra leading zeros

texts:
Here is a zero pad function I have:

''' <summary>
''' Take a number string and zero pad it to the specified length.
''' </summary>
''' <param name="Number">The string representation of the value that will be zero-padded.</param>
''' <param name="ToLength">The length of the string that will result after the zero-padding.</param>
''' <param name="TrimExtraZeroes">An optional boolean which, when true, indicates that any
''' extra leading zeroes that make the string longer than the desired length should be removed.</param>
''' <returns>A value which is the same as <paramref name="Number" /> but zero padded to the length specified by <paramref name="ToLength" />.</returns>
''' <remarks></remarks>
Friend Function ZeroPad(ByVal Number As String, ByVal ToLength As Integer, Optional ByVal TrimExtraZeroes As Boolean = False) As String
    Const ZeroChar = "0"c

    Select Case Number.Length
        Case Is < ToLength
            Return New String(ZeroChar, ToLength - Number.Length) & Number
        Case Is = ToLength
            Return Number
        Case Is > ToLength
            ZeroPad = Number

            If (TrimExtraZeroes) Then
                Do While ZeroPad.StartsWith(ZeroChar) AndAlso ZeroPad.Length > ToLength
                    ZeroPad = ZeroPad.Substring(1)
                Loop
            End If
        Case Else
            'This case can never occur, but it's here to suppress compiler warning.
            Throw New InvalidOperationException(String.Format("Unknown number length: {0}", Number.Length))
    End Select
End Function

Now, focusing on just one portion of it -- the part that trims leading zeros:

Do While ZeroPad.StartsWith(ZeroChar) AndAlso ZeroPad.Length > ToLength
    ZeroPad = ZeroPad.Substring(1)
Loop

is there a more efficient, cleaner, or "slick" way to do this other than looping?


texts: Searching a 2D matrix for a consecutive sequence

texts:
I've been solving problems on checkio (and trying to digest other's code) in order to improve my Python.

My main goals are to learn to write more idiomatic Python and to explore the language more fully ("batteries included" is no joke!).  I'd like critiques on the following (working) code in terms of pythonic-ness and in terms of my choice of tools/solution method:

def checkio(matrix):

    def four_consecutive(group):
        for number in set(group):
            if str(number)*4 in ''.join(map(str,group)): return True
        return False

    def search(generators):
        for generator in generators:
            while True:
                try:
                    if four_consecutive(next(generator)): return True
                except StopIteration: break
        return False

    horizontal = (row for row in matrix)
    vertical  = ([matrix[i][j] for i in range(len(matrix[j]))] for j in range(len(matrix)))
    diagonal1 = ([matrix[j+i][j] for j in range(len(matrix)-i)] for i in range(len(matrix)-3))
    diagonal2 = ([matrix[j][j+i] for j in range(len(matrix)-i)] for i in range(1,len(matrix)-3))
    diagonal3 = ([matrix[-1*(j+1)][j+i] for j in range(len(matrix)-i)] for i in range(len(matrix)-3))
    diagonal4 = ([matrix[-1*(j+i+1)][j] for j in range(len(matrix)-i)] for i in range(1,len(matrix)-3))

    if search((horizontal,vertical,diagonal1,diagonal2,diagonal3,diagonal4)): return True
    return False

Matrices in this problem are always square, contain integers 1-9, and the specification asks for a return value of true if 4 consecutive equal integers are in a line horizontally, vertically, or diagonally, and false otherwise. Core Python modules were available for import.

My main goal lately has been to get more comfortable with generators and list comprehensions, and to write shorter code.


texts: Simple Java ArrayList stores and shows not repeated elements entered by user

texts:
Is this good code? I do believe I improved quite a lot since last year, still I would really appriciate some feedback :)

import javax.swing.JOptionPane;
import java.util.ArrayList ;

public class IfNotRepeated {

    /*
     *  7.12 (Duplicate Elimination) Use a one-dimensional array to solve the following problem:
        Write an application that inputs five numbers, each between 10 and 100, inclusive. As each number
        is read, display it only if it’s not a duplicate of a number already read. Provide for the “worst case,”
        in which all five numbers are different. Use the smallest possible array to solve this problem. Display
        the complete set of unique values input after the user enters each new value.
     */

    final static int ELEMENTS = 5 ;
    final static int UPPER_BOUND = 100 ;
    final static int LOWER_BOUND= 10 ;

    public static void main(String[] args) {

        int number = 0; //user's input

        while ( true ) //allows the input of numbers which are bounded between 10 and 100 encompass,
            //whenever this boundary is violated, the program ends, without showing any information.
        {

            ArrayList <Integer> vector = new ArrayList <Integer> (5) ; //Array of not repeated user inputs', I need to get a new one
            //every time the user had the chance to input ELEMENTS numbers

            for ( int i = 0 ;
                    i < ELEMENTS
                    && ( number = gimmeValue() ) >= LOWER_BOUND
                    && number <= UPPER_BOUND
                            ; i++ ) // iterates as long as there are less than ELEMENTS numbers per array, and the boundary is respected
            {

                if ( !vector.contains(number) )
                    vector.add(number) ; //adds a number if the legit value entered hasn't been previously entered (in this serie).

                String elements = "" ;

                for ( int notRepeatedElement : vector )
                    elements += String.valueOf(notRepeatedElement) + '\n' ; //concatenates not repeated elements leaving a new line at the end

                JOptionPane.showMessageDialog(null, elements); //show every non-repeated element

            }
            if ( number < LOWER_BOUND || number > UPPER_BOUND )
                break ; // if out bounds, exit program
        }
    }

    public static int gimmeValue () //shows an input dialog for the user to enter a number and returns that value as an Int
    {

        String number = JOptionPane.showInputDialog("Enter a number between 10 and 100 encompass:") ;
        return Integer.valueOf(number) ;

    }
}


texts:
With this algorithm I update an automatically generated verilog-file. The update within this file is done by commenting the assigned wires to specific ports of module instances.

Is there a better, more elegant or more optimized way to do this than with this algorithm?

file_name = "test.v"    # name of the verilog file
test = ".test"          # port name 1
tezt = ".tezt"          # port name 2
dummy = []              # buffer for the updated string

with open(file_name, "r+") as f:
    lines = f.readlines()
    f.seek(0)
    f.truncate()                                 # clear the file
    for line in lines:
        if test in line or tezt in line:         # check if one of the ports is in the line
            if line[line.index('(')+1] != '/':   # check if the assigned wire is already is commented
                 for c in line:                  # update the line and comment the wire name within the brackets
                    if c == ')':
                        dummy.append("*/")
                    dummy.append(c)
                    if c == '(':
                        dummy.append("/*")
                 line = line.replace(line, "".join(dummy))    # replace the old line with the new string
                 dummy.clear()
        f.write(line)
    f.close()


texts:
I'm making a pong game with SFML and in the process made a function that takes a Time, Speed, Angle of movement, buffer for the movement on the X axis, and buffer for the movement on the Y axis.

I then implemented this function into my custom mySprite class, more specifically into its update() function which updates its Position using the above function to calculate its new position.

However, I'm worried that giving the function the FrameTime() of the Window (the time since the frame was last updated) is not the best choice as the sprites might start jumping around if there's lag between frame updates or other problems.

Finally I would like to know about my organization, planning, etc.

#include<SFML/Graphics.hpp>
#include<SFML/System.hpp>
#include<cmath>
#include<vector>
#    define M_PI 3.14159265358979323846

sf::RenderWindow Window;

template<typename T>
void CalculateMove(T Time, T Speed, T Angle, T& buffX, T& buffY)
{   //determine what quadrant of circle we're in
    unsigned int  Quadrant= 1;
    if(Angle>90)  Quadrant= 2;
    if(Angle>180) Quadrant= 3;
    if(Angle>270) Quadrant= 4;

    //anything above 90 would be impossible triangle
    Angle= (float)(Angle-(int)Angle)+(float)((int)Angle%90);

    // calculates x and y based on angle and Hypotenuse.02433
    if((int)Angle!=0){
        buffX= sin(Angle / 180 * M_PI)/ (1.f/(Speed*Time));
        buffY= sin((180-Angle-90)/ 180 * M_PI)/ (1.f/(Speed*Time));}

    else{// Movement is a straight line on X or Y axis
        if(Quadrant==0 || Quadrant==2) buffX= Speed*Time;
        if(Quadrant==1 || Quadrant==4) buffY= Speed*Time;}

    //Quadrant Factor (positive or negative movement on the axis)
    switch(Quadrant){
    case 1: break;
    case 2: buffX=-buffX; break;
    case 3: buffX=-buffX; buffY=-buffY; break;
    case 4: buffY=-buffY; break;}
};

/////////////////////////////////////////   Mysprite    ////////////////////////////////
class mySprite : public sf::Sprite
{
private:
    float velocity;
    float angle;

public:
    // all the values needed by the base class sprite();
    mySprite(
        const sf::Image& Img,
        const sf::Vector2f& Position = sf::Vector2f(0, 0),
        const sf::Vector2f& Scale = sf::Vector2f(1, 1),
        float Rotation = 0.f,
        const float Angle= 0.f,
        const float Velocity= 0.f,
        const sf::Color& Col = sf::Color(255, 255, 255, 255)):
      Sprite(Img, Position, Scale, Rotation, Col){
        angle= Angle;
        velocity= Velocity;};

    float Velocity(){return velocity;};
    void SetVelocity(float newVelocity){velocity=newVelocity;};
    float Angle(){return angle;};
    void SetAngle(float newAngle){angle=newAngle;};

    void Update(){
        float frameTime= Window.GetFrameTime();
        float X=0,Y=0;
        CalculateMove(frameTime,velocity,angle,X,Y);
        Move(X,-Y);
    };

    void Reflect(float CollAngle){
        SetRotation(-GetRotation());
        angle=-angle;
        //TODO: factor in the collision angle
    };
};