texts: Vue.js component for adding/removing items

texts:
Simple Vue.js component, where you can add a wrestler via an AJAX endpoint, and remove a wrestler from an AJAX endpoint.

Any notes on whether I’m doing this the “Vue.js way” or tips for improvement are greatly welcomed.

The HTML template portion of the component:

<template>

Loading&hellip;

                    <button type="button" class="btn btn-outline-danger" v-on:click.prevent="removeWrestler(wrestler, index)">
                        {{ wrestler.name }}
                        &times;
                    </button>

                    <input type="text" class="form-control" autocomplete="name" required ref="name" v-bind:disabled="busy" v-model="name" v-on:keydown.enter.prevent="addWrestler" />

                        <button type="button" class="btn btn-primary" v-on:click.prevent="addWrestler" v-bind:disabled="busy">

                        </button>

</template>

The JavaScript portion of the component:

const confirm = require('./../mixins/confirm.js');

export default {
    computed: {
        submitText() {
            return this.busy ? 'Submitting&hellip;' : 'Add wrestler';
        },
        wrestlersSortedByName() {
            return this.wrestlers.sort((a, b) => {
                return a.name.localeCompare(b.name);
            });
        }
    },
    data() {
        return {
            busy: false,
            loading: true,
            name: '',
            wrestlers: []
        };
    },
    methods: {
        addWrestler() {
            this.busy = true;

            axios.post(this.action, { name: this.name })
                .then((response) => {
                    this.wrestlers.push(response.data.data);
                })
                .catch((response) => {
                    alert('Error adding wrestler to video.');
                })
                .then(() => {
                    this.busy = false;
                    this.name = '';
                    this.$refs.name.focus();
                });
        },
        loadWrestlers() {
            axios.get(this.action).then((response) => {
                this.wrestlers = response.data.data;
                this.loading = false;
            });
        },
        removeWrestler(wrestler, index) {
            const message = `Are you sure you wish to remove ${wrestler.name} from this video?`;

            this.confirm(message, () => {
                axios.delete(`${this.action}/${wrestler.id}`)
                    .then((response) => {
                        this.wrestlers.splice(index, 1);
                    })
                    .catch((response) => {
                        alert('Error removing wrestler.');
                    });
            });
        }
    },
    mixins: [
        confirm
    ],
    mounted() {
        this.loadWrestlers();
    },
    props: {
        action: {
            required: true,
            type: String
        }
    }
}

And finally, the contents of ./mixins/confirm.js:

module.exports = {
    methods: {
        confirm(message, callback) {
            if (window.confirm(message)) {
                callback();
            }
        }
    }
};

Style notes: I’m aware of the @ shorthand for v-on:, but prefer the longer form as it looks more HTML-y to me.


texts:
At my work, I need to create a script that third-party webmasters could include in their pages without need to include something else. But this script had dependencies on jQuery and some amount of their plug-ins.

On the Internet, I have found libraries that have same functionality except for an important one: they don't check are needed library already exist on a page.

Yes, I could execute the needed libraries in local scope of my script, but I've decided to reduce the number of HTTP connections and traffic with this function:

var require = function (lib, obj, libs_obj) {
    // if obj is function than `require` called directly by user and we
    // must transform it to object. It's for reduce number of used
    // variables. When we call `require` recursively, we use this object
    // instead of function
    var lib_is_list = typeof(lib) === 'object';
    if (typeof obj === 'function') obj = { callback: obj, count: lib_is_list ? lib.length : 1 }
    if (lib_is_list) { // this is list of libs
        for (var i in lib) require(lib[i], obj, libs_obj);
        return;
    }
    var lib = libs_obj[lib];
    if (lib.callbacks === undefined) lib.callbacks = [];
    if (lib.check()) { if (obj.callback) obj.callback(); return; }
    lib.callbacks.push(obj);
    if (lib.pending) { return; }
    lib.pending = true;

    function ready() {
        function script_downloaded() {
            lib.pending = false;
            var obj;
            while (obj = lib.callbacks.pop()) {
                obj.count--; if (obj.count == 0) obj.callback();
            }
        }

        download_script(lib.link, script_downloaded);
    }

    function download_script(src, callback) {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.async = 'async';
        script.src = src;

        // Based on jQuery jsonp trick
        if (callback) {
            script.onload = script.onreadystatechange = function() {
                if (!script.readyState || /loaded|complete/.test(script.readyState)) {
                    script.onload = script.onreadystatechange = null;
                    callback();
                }
            };
        }
        document.getElementsByTagName('head')[0].appendChild(script);
    }

    var deps_count = lib.deps ? lib.deps.length : 0;
    if (deps_count < 1) { ready(); return; }
    var new_obj = { callback: ready, count: deps_count };

    require(lib.deps, new_obj, libs_obj);
};

This function work in IE6+ (and, of course, in other browsers) and written in pure JS.
To call this function, use syntax like this:

require(['list', 'of', 'libraries'], function () { alert 'All libs loaded'; }, libs_obj),

where libs_obj is object like this:

{
    list: {
        check: function() { return list_exist(); },
        // function to check whether the required functionality
        link: 'js/list_js_file.js',
        // link to script
        deps: ['libraries', 'of']
        // list of dependencies of current library
        // If not, library doesn't have dependencies
    },
    of: {
        check: function() { return of_exist_and_version_is('1.2.3'); },
        link: 'js/another_file.js',
    },
    libraries: {
        check: funcion() { return libraries_exist() || analog_exist(); },
        link: 'http://www.example.com/js/libraries.js',
        deps: ['of']
    }
}

Callback function are optional - if we don't need it, we can just type false or undefined.  Of course, this function must be called after all third-party scripts. Bottom of page is better place to script with this function.  Please tell me where I went wrong or give me useful advice.


texts:
I am still fairly new to go, and would appreciate any tips on style, best practices, etc, but am especially interested to know if this non-recursive cartesian product implementation can be made significantly faster (eg, when the number of results in the result set is on the order of 1e9).

I've played around with adding more goroutines, but parallelism doesn't seem to help much, if at all.  I may be missing a much better approach though.

https://play.golang.org/p/H-M6CbmeFoV

package main

import (
    "fmt"
)

// Given a mixed base, returns a function that:
//
// Increments a number, represented as a slice of digits, defined
// in that base.  For example, if our base is 2 3 2, we'll count
// like this:
//
// 0 0 0 ; 0 0 1; 0 1 0; 0 1 1; 0 2 0; 0 2 1;
// 1 0 0 ; 1 0 1; 1 1 0; 1 1 1; 1 2 0; 1 2 1;
func mixedBaseInc(bases []int) func(*[]int) {

    return func(digits *[]int) {
        ret := *digits
        i := len(ret) - 1
        for {
            base := bases[i]
            ret[i] = (ret[i] + 1) % base
            noCarry := ret[i] != 0

            if noCarry || i == 0 {
                return
            }
            i--
        }
    }
}

func pick(indexes []int, params [][]interface{}) []interface{} {
    ret := make([]interface{}, len(params))
    for i, x := range indexes {
        ret[i] = params[i][x]
    }
    return ret
}

func XProd(params ...[]interface{}) chan []interface{} {
    var paramLens, digits []int
    numElms := 1
    c := make(chan []interface{})

    for _, x := range params {
        paramLens = append(paramLens, len(x))
        numElms *= len(x)
        digits = append(digits, 0)
    }

    inc := mixedBaseInc(paramLens)

    go func() {
        defer close(c)
        for i := 0; i < numElms; i++ {
            c <- pick(digits, params)
            inc(&digits)
        }
    }()

    return c
}

func main() {
    for x := range XProd([]interface{}{1, 2, 3}, []interface{}{4, 5}) {
        fmt.Println(x)
    }
}


texts: Rock-Paper-Scissors game for learning purposes

texts:
I just want your opinions about my code. How could I improve it? Is there a better method to do it?

from sys import exit
from random import randint

print "Welcome to the PIN Game 1!"
print "Tell me your name"

user = raw_input('> ')

#asks the user for an entry and prints what he has chosen
def start():
    print "%s, choose one of the options: " % user

    print """
    1. Rock
    2. Paper
    3. Scissors
    """

    choice = 0
    cpu_choice = randint(1,3)

    while choice <= 0 or choice >= 4:

        choice = int(raw_input('> '))
        if choice == 1:
            print "You chose ROCK!"
        elif choice == 2:
            print "You chose PAPER"
        elif choice == 3:
            print "You chose SCISSORS"
        else:
            print "What is your problem? Try again, this time choose a number between 1 and 3!"
    cpu_decision(cpu_choice)
    result(choice, cpu_choice)

#random cpu input
def cpu_decision(cpu):
    if cpu == 1:
        print "Your opponent chose ROCK!"
    elif cpu == 2:
        print "Your opponent chose PAPER!"
    else:
        print "Your opponent chose SCISSORS"

#if user loses
def lose():
    print "Sorry, you lost the match"

#if user wins
def win():
    print "Congratulations! You beat your opponent!!"

#prints the result
def result(user, comp):
    if user == comp:
        print "Gee! You tied!"
    elif user == 1 and comp == 2:
        lose()
    elif user == 1 and comp == 3:
        win()
    elif user == 2 and comp == 1:
        win()
    elif user == 2 and comp == 3:
        lose()
    elif user == 3 and comp == 1:
        lose()
    elif user == 3 and comp == 2:
        win()

    again()

#ask if the user wants to play again
def again():
    print """
    Wanna play again?
    1 for YES
    Anything else to quit
    """

    again1 = int(raw_input('> '))

    if again1 == 1:
        start()
    else:
        exit()

start()


texts: Replace color in image measured by Euclidean distance

texts:
This script replaces the red hair in image to black color (replace one color to another)

Three major parts in this script

Not just replace color red to black, I hope the output image looks natural, so I will replace the color close to red to black. This "close" is measured by Euclidean distance.
And not just replace by black color, user can modify the red color's r, g, b value separately, like add more green.
Choose the area to be changed, rather than change the whole picture

Suggestions I am looking for:

I did some NumPy practice before, so any suggestions about NumPy are welcome.
I think the code to replace target area is not so elegant, I am not quite sure about this part:

(c1, r1), (c2, r2) = area
for i in range(r1, r2+1):
    l, r = i*h+c1, i*h+c2+1
    data[l:r,:k][D[l:r]] = modification(data[l:r,:k][D[l:r]])

Full code:

import numpy as np
from PIL import Image
from scipy.spatial.distance import cdist

def replace_corlor(image, original_corlor, modification, area=None, distance=1000, output="new_test.jpg"):
    print("[*] START Replace Color")
    img = Image.open(image)
    data = np.asarray(img, dtype="int32")
    w,h,k = data.shape
    data = np.reshape(data, (w*h,k))
    distMatrix = cdist(data, np.array([original_corlor]))
    D = distMatrix<=distance
    D = np.reshape(D,w*h)
    if area is None:
        data[:,:k][D] = modification(data[:,:k][D])
    else:
        (c1, r1), (c2, r2) = area
        for i in range(r1, r2+1):
            l, r = i*h+c1, i*h+c2+1
            data[l:r,:k][D[l:r]] = modification(data[l:r,:k][D[l:r]])
    data = np.reshape(data, (w,h,k))
    img = Image.fromarray(np.asarray(np.clip(data, 0, 255), dtype="uint8"), "RGB")
    img.save(output)
    print("[*] DONE Replace Color")

if __name__ == "__main__":
    def modification(color):
        return color * [2,0,0]
        # return [255,0,0]
    replace_corlor("test.jpg",(36,35,30),modification, ((0,0),(400,100)))


texts: Musical graph algorithm, with an inlined lookup helper function

texts:
I am working with bit strings in clojure. My question is less about performance and more about how one should go about it (in particular see the last inlined version)

The tonnetz-array represents an adjacency matrix.

(set! *warn-on-reflection* true)
(set! *unchecked-math* true)

(def ^:private ^ints tonnetz-array
  (int-array [952 1904 3808 3521 2947 1799 3598 3101 2107 119 238 476]))

get-tonnetz-connected can be thought of as a graph lookup.

(defn- get-tonnetz-connected
  "given packed binary notes representing a chord,
  returns packed notes that mark all notes that can be reached in
  the tonnetz graph. This function is used by tonnetz-connected? as
  a way of building a map / traversing a graph at a far faster
  rate than a graph search"
  [packed]
  (loop [mask (int 0)
         ^int bits packed]
    (if (= bits 0)
      mask
      (let [low-bit (Integer/lowestOneBit bits)]
        (recur
         (bit-or mask (aget ^ints tonnetz-array
                            ^int (Integer/numberOfTrailingZeros low-bit)))
         (bit-xor bits low-bit))))))

this is the main function.

(defn tonnetz-connected?
  "do the notes form a connected graph?"
  [packed]
  (let [low-bit (Integer/lowestOneBit packed)]
    (loop [mask (aget ^ints tonnetz-array
                      (Integer/numberOfTrailingZeros low-bit))
           unmatched (bit-xor packed low-bit)]
      (if (= 0 unmatched)
        true
        (let [matches (bit-and mask unmatched)
              masks (bit-or mask (get-tonnetz-connected matches))
              next-unmatched (bit-xor matches unmatched)]
          (if (= unmatched next-unmatched)
            false
            (recur masks next-unmatched)))))))

I have found that inlining has improved things a bit, and this thing is fast and it is fast enough, but I would like to understand how to properly get the most out of low level operations.

An inlined version where I have tried to make sure that ints are used all the way though.

(defn tonnetz-connected?-2
  "do the notes form a connected graph?"
  [packed]
  (let [low-bit (int (Integer/lowestOneBit (int packed)))]
    (loop [mask (int (aget ^ints tonnetz-array
                           (int (Integer/numberOfTrailingZeros low-bit))))
           unmatched (int (bit-xor (int packed) low-bit))]
      (if (= 0 unmatched)
        true
        (let [matches (int (bit-and mask unmatched))
              masks (loop [mask (int mask)
                           bits (int matches)]
                      (if (= bits (int 0))
                        mask
                        (let [low-bit (int (Integer/lowestOneBit bits))]
                          (recur
                           (int (bit-or mask (aget ^ints tonnetz-array
                                                   ^int (int (Integer/numberOfTrailingZeros low-bit)))))
                           (int (bit-xor bits low-bit))))))
              next-unmatched (int (bit-xor matches unmatched))]
          (if (= unmatched next-unmatched)
            false
            (recur (int masks) (int next-unmatched))))))))

A dirty test function

(defn testit [n f]
  (let [xs (repeatedly n #(+ 1 (rand-int 4094)))]
    (time (do (doall (map f xs)) nil))))

generally I am averaging (ran each about 10 times):

clj-music.core> (testit 100000 tonnetz-connected?)
"Elapsed time: 77.175712 msecs"

and for the inlined version

clj-music.core> (testit 100000 tonnetz-connected?-2)
"Elapsed time: 61.413721 msecs"

So the performance has improved, but now I just have (int ...) everywhere. This was mainly to silence warnings like:

core.clj:165 recur arg for primitive local: mask is not matching primitive, had: Object, needed: long
Auto-boxing loop arg: mask

Is this the correct way?


texts:
I wrote a small utility for searching our web app log files for certain strings. The idea is that if the search string is found somewhere in the entry, the entire entry should be printed.

The constraints are:

One log entry can have one to many lines (stacktraces for example)
Each log entry starts with an uppercase string specifying log type, followed by a pipe character ("ERROR|...")
Each log entry ends with a pipe character followed by an exclamation mark ("|!")
The utility should work much like a regular grep command, meaning that it takes input either from a list of files or from STDIN.

The script works as expected, but it is quite slow. Writing the same logic in an AWK script is about twice as fast when processing a large amount of data. Any suggestions on how to improve the performance?

logentrygrep.py

#!/bin/python2.7

from __future__ import print_function
import argparse
import fileinput
import re
import signal
import sys

# Disable printing stacktrace on KeyboardInterrupt
signal.signal(signal.SIGINT, lambda x,y: sys.exit(1))

# Parse arguments
parser = argparse.ArgumentParser(description='Tool for greping log entry contents')
parser.add_argument('pattern', help='Pattern to search for')
parser.add_argument('file', nargs='*', help='Files to search')
parser.add_argument('-i', '--ignore-case', dest="ignorecase", action='store_true', help='Case insensitive greping')
parser.add_argument('-v', '--verbose', dest="verbose", action='store_true', help='Print verbose messages')
args = parser.parse_args()

VERBOSE = args.verbose

if VERBOSE:
    print("Pattern to search for: " + args.pattern)
    print("File(s): " + (str(args.file) if args.file else "STDIN"))

class LogDataProcessor:
    entryHeadPattern = re.compile("^[A-Z]{3,}\|")
    entryTailPattern = re.compile("\|!$")

    totalLinesProcessed = 0
    lineBuffer = []
    matchFound = False

    def __init__(self, regex_pattern, ignorecase):
        if ignorecase:
            self.pattern = re.compile(regex_pattern, re.IGNORECASE)
        else:
            self.pattern = re.compile(regex_pattern)

    def process(self, indata):
        for line in fileinput.input(indata):
            self.processLine(line.rstrip())

    def processLine(self, line):
        self.totalLinesProcessed += 1

        if self.isEntryHead(line):
            # Flush in case previous entry did not terminate correctly
            self.flush()
            self.addToBuffer(line)

            # If it's a one-line entry (head and tail on the same line)
            if self.isEntryTail(line):
                self.flush()

        elif not self.isBufferEmpty():
            self.addToBuffer(line)

            if self.isEntryTail(line):
                self.flush()

    def flush(self):
        if self.matchFound:
            self.printBuffer()

        self.lineBuffer = []
        self.matchFound = False

    def printBuffer(self):
        for line in self.lineBuffer:
            print(line)

    def addToBuffer(self, line):
        if not self.matchFound and self.lineMatches(line):
            self.matchFound = True

        self.lineBuffer.append(line)

    def isBufferEmpty(self):
        return not self.lineBuffer

    def isEntryHead(self, line):
        return self.entryHeadPattern.match(line)

    def isEntryTail(self, line):
        return self.entryTailPattern.search(line)

    def lineMatches(self, line):
        return self.pattern.search(line)

processor = LogDataProcessor(args.pattern, args.ignorecase)
processor.process(args.file)

if VERBOSE:
    print("Lines searched: " + str(processor.totalLinesProcessed))


texts: Gathering response from a pagable service

texts:
I'm wondering how this code could be improved. I especially don't like the use of mutable Buffer but not sure what the best way to get it out cleanly.

  def find(service: Service): Traversable[Long] = {
    def loop(lastId: Option[Long])
            (acc: mutable.Buffer[Long])
            (quota: Int): Traversable[Long] = {
      val response = service.call(lastId.getOrElse(-1))
      if (response.size() > 0 && quota > 0) {
        loop(response.last.getId)(acc ++ response)(quota - 1)
      } else {
        (acc ++ response).toList
      }
    }
    loop(None)(mutable.Buffer())(3)
  }


texts: Calculate the number of moves requires for a knight chess piece

texts:
It's possible to work out the number of moves required to move from (0, 0) to (A, B) for a knight on an infinite chess board in O(1) time.

This is an attempt at a solution to do it in O(n) time, where n is the number of moves required.

#define ABS(a) ({ typeof (a) _a = (a); _a > 0 ? _a : -_a; })

int movesRequired(int A, int B) {
    int X = 0, Y = 0;
    int count = 0;
    if (!(((A-X) % 2) ^ ((Y-B) % 2)))
        return -1;
    while (X != A && Y != B) {
        int distX = A-X;
        int distY = B-Y;
        if (ABS(distX) > ABS(distY)) {
            X += distX>0?2:-2;
            Y += distY>0?1:-1;
        } else {
            X += distX>0?1:-1;
            Y += distY>0?2:-2;
        }
        count++;
    }
    return count;
}

It returns the minimum moves required, or -1 if it's not possible.

What I'm interested in:

As far as I am aware, this runs in O(n) time. However, I may not be correct. Does it?
Is there a way to improve my algorithm so it runs in O(n) time?


texts:
Please review my code as I'm wondering if there is a better way. Here is the question I'm trying to solve:

  Scrabble Score

  Given a word, compute the scrabble score for that word.

  Letter Values

  You'll need these:

```plain
Letter                           Value
A, E, I, O, U, L, N, R, S, T       1
D, G                               2
B, C, M, P                         3
F, H, V, W, Y                      4
K                                  5
J, X                               8
Q, Z                               10
```

  Examples

  "cabbage" should be scored as worth 14 points:

  3 points for C
  1 point for A, twice
  3 points for B, twice
  2 points for G
  1 point for E

  And to total:

  3 + 2*1 + 2*3 + 2 + 1
  = 3 + 2 + 6 + 3
  = 5 + 9
  = 14

  Extensions

  You can play a double or a triple letter.
  You can play a double or a triple word.

Here's my answer:

import java.util.HashMap;
import java.util.Map;

class Scrabble {

    private String word;

    Scrabble(String word) {
        this.word = word;
    }

    int getScore() {

        Map<Character, Integer> lettersMap = new HashMap<>();
        String lettersCap = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        for (int i = 0; i < lettersCap.length(); i++) {
            if (lettersCap.charAt(i) == 'A' || lettersCap.charAt(i) == 'E' ||
                    lettersCap.charAt(i) == 'I' || lettersCap.charAt(i) == 'O' ||
                    lettersCap.charAt(i) == 'O' || lettersCap.charAt(i) == 'U' ||
                    lettersCap.charAt(i) == 'L' || lettersCap.charAt(i) == 'N' ||
                    lettersCap.charAt(i) == 'R' || lettersCap.charAt(i) == 'S' ||
                    lettersCap.charAt(i) == 'T') {

                lettersMap.put(lettersCap.charAt(i), 1);
                lettersMap.put(lettersCap.toLowerCase().charAt(i), 1);
            }

            if (lettersCap.charAt(i) == 'D' || lettersCap.charAt(i) == 'G') {
                lettersMap.put(lettersCap.charAt(i), 2);
                lettersMap.put(lettersCap.toLowerCase().charAt(i), 2);
            }

            if (lettersCap.charAt(i) == 'B' || lettersCap.charAt(i) == 'C' ||
                    lettersCap.charAt(i) == 'M' || lettersCap.charAt(i) == 'P') {
                lettersMap.put(lettersCap.charAt(i), 3);
                lettersMap.put(lettersCap.toLowerCase().charAt(i), 3);
            }

            if (lettersCap.charAt(i) == 'F' || lettersCap.charAt(i) == 'H' ||
                    lettersCap.charAt(i) == 'V' || lettersCap.charAt(i) == 'W' ||
                    lettersCap.charAt(i) == 'Y') {
                lettersMap.put(lettersCap.charAt(i), 4);
                lettersMap.put(lettersCap.toLowerCase().charAt(i), 4);
            }

            if (lettersCap.charAt(i) == 'K') {
                lettersMap.put(lettersCap.charAt(i), 5);
                lettersMap.put(lettersCap.toLowerCase().charAt(i), 5);
            }

            if (lettersCap.charAt(i) == 'J' || lettersCap.charAt(i) == 'X') {
                lettersMap.put(lettersCap.charAt(i), 8);
                lettersMap.put(lettersCap.toLowerCase().charAt(i), 8);
            }

            if (lettersCap.charAt(i) == 'Q' || lettersCap.charAt(i) == 'Z') {
                lettersMap.put(lettersCap.charAt(i), 10);
                lettersMap.put(lettersCap.toLowerCase().charAt(i), 10);
            }

        }

        int totalValue = 0;

        for (int j = 0; j < word.length(); j++) {

            totalValue += lettersMap.get(word.charAt(j));
        }

        return totalValue;
    }

}


texts: Ramda - Forming a string based on array of word positions

texts:
I saw this question and wondered how it'd be best to accomplish this using Ramda.

I'm new to the library so I thought it'd be an interesting learning exercise.

I have a working solution but it seems overly complicated and verbose. I'd be grateful for any suggestions on what other ways it would be possible to achieve this output using Ramda.

I'm aware that this doesn't need a library; as I say, I approached it as a learning exercise.

Here's what I have:

const { addIndex, always, fromPairs, join, map, sort, toPairs, unnest } = R;

const song = {
  "99": [0, 7],
  "bottles": [1, 8],
  "of": [2, 9],
  "beer": [3, 10],
  "on": [4],
  "the": [5],
  "wall": [6]
};

const toSentence = join(' ');

const parsed = toSentence(
    map(
      ([_, word]) => word,
      sort(
        ([a, _], [b, __]) => a < b ? -1 : 1,
        unnest(
          map(
            ([word, indices]) => map(
              index => [index, word],
              indices,
            ),
            toPairs(song)
          )
        )
      )
    )
  )

console.dir(parsed)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>


texts: First non-repeated character in a string in c

texts:
Write an efficient function to find the first non-repeated character
  in a string. For example, the first non-repeated character in "total"
  is 'o' and the first non-repeated character in "teeter" is 'r'.

Please see my solution and give me some feedback and suggestions for improving and optimizing it if needed.

#include <stdio.h>
#define SIZE 100                /* max size of input string */
#define LIM 5                   /* max number of inputs */
char repeat_ch(const char *);   /* return first non-repeated character */
int main(void)
{
    char line[SIZE];
    int i = 0;
    char ch;

    while(i < LIM && gets(line))
    {
        ch = repeat_ch(line);
        if(ch != NULL)
            printf("1st non-repeated character: %c\n", ch);
        else
                printf("There is no unique character in a string: %s\n", line);
        i++;
    }

}

char repeat_ch(const char *string)
{
    char array[130] = {0};
    char *p = string;

    /* store each character in array, use ascii code as an index for character
     * increment each time the same character appears in a string
     */
    while(*p)                               // stop when '\0' encountered
    {
        array[*p]+=1;
        p++;
    }
    while(*string)
    {
        if(array[*string] == 1)
            return *string;         // stop when unique character found
        string++;
    }

    return *string;
}


texts:
So, I just wanted to post something on Rosetta Code, and I found this task of generating and plotting a Julia set: http://www.rosettacode.org/wiki/Julia_set. There was already one solution but it was quite inefficient and not Pythonic. Here is my attempt on this:

"""
This solution is an improved version of an efficient Julia set solver
from:
'Bauckhage C. NumPy/SciPy Recipes for Image Processing:
 Creating Fractal Images. researchgate. net, Feb. 2015.'
"""
import itertools
from functools import partial
from numbers import Complex
from typing import Callable

import matplotlib.pyplot as plt
import numpy as np

def douady_hubbard_polynomial(z: Complex,
                              *,
                              c: Complex):
    """
    Monic and centered quadratic complex polynomial
    https://en.wikipedia.org/wiki/Complex_quadratic_polynomial#Map
    """
    return z ** 2 + c

def julia_set(*,
              mapping: Callable[[Complex], Complex],
              min_coordinate: Complex,
              max_coordinate: Complex,
              width: int,
              height: int,
              iterations_count: int = 256,
              threshold: float = 2.) -> np.ndarray:
    """
    As described in https://en.wikipedia.org/wiki/Julia_set
    :param mapping: function defining Julia set
    :param min_coordinate: bottom-left complex plane coordinate
    :param max_coordinate: upper-right complex plane coordinate
    :param height: pixels in vertical axis
    :param width: pixels in horizontal axis
    :param iterations_count: number of iterations
    :param threshold: if the magnitude of z becomes greater
    than the threshold we assume that it will diverge to infinity
    :return: 2D pixels array of intensities
    """
    imaginary_axis, real_axis = np.ogrid[
                        min_coordinate.imag: max_coordinate.imag: height * 1j,
                        min_coordinate.real: max_coordinate.real: width * 1j]
    complex_plane = real_axis + 1j * imaginary_axis

    result = np.ones(complex_plane.shape)

    for _ in itertools.repeat(None, iterations_count):
        mask = np.abs(complex_plane) <= threshold
        if not mask.any():
            break
        complex_plane[mask] = mapping(complex_plane[mask])
        result[~mask] += 1

    return result

if __name__ == '__main__':
    mapping = partial(douady_hubbard_polynomial,
                      c=-0.7 + 0.27015j)  # type: Callable[[Complex], Complex]

    image = julia_set(mapping=mapping,
                      min_coordinate=-1.5 - 1j,
                      max_coordinate=1.5 + 1j,
                      width=800,
                      height=600)
    plt.axis('off')
    plt.imshow(image,
               cmap='nipy_spectral',
               origin='lower')
    plt.show()

I think it looks good, and it is definitely more efficient. There was just one thing that I was not sure about. I was thinking to take out creating a complex_plane to a separate function and pass it as a parameter to julia_set. But in this case the julia_set wouldn't be a pure function as it would mutate the complex_plane. And I prefer my functions not to have any side effects. So I decided to leave it as is.

Any comments on this matter or anything else are welcome.

Here are some examples of output:


texts: How to make a loop of nested if-statements to find the smallest number of something?

texts:
I'm a beginning programmer and wrote a little code for a mathematical question. There are 6 rounds where each time the pile of cupcakes is divided into five equal groups, with one extra cupcake (which is discarded). Then one fifth is taken away and the next round starts. I've written the code, but there must be a way to write this shorter, a loop instead of nested if-statements.
My code:
 import sys

getal = 1

while True:
    if getal % 5 == 1:
        a = (getal - 1)/5
        if (a*4) % 5 == 1:
            b = (a*4-1)/5
            if (b*4) % 5 == 1:
                c = (b*4-1)/5
                if (c*4) % 5 == 1:
                    d = (c*4-1)/5
                    if (d*4) % 5 == 1:
                        e = (d*4-1)/5
                        if (e*4) % 5 == 1:
                            print(getal)
                            sys.exit()
                        else:
                            getal = getal + 1
                    else:
                        getal = getal + 1
                else:
                    getal = getal + 1
            else:
                getal = getal + 1
        else:
            getal = getal + 1
    else:
        getal = getal + 1
        continue

Thanks in advance!
PS: getal is Dutch for number (the number of cupcakes at the start, which is the result of my question).


texts:
Consider a row of n coins of values v1 . . . vn, where n is even.  a player selects either the first or last coin from the row, removes it from the row permanently, and receives the value of the coin. Determine the maximum possible amount of money we can definitely win if we move first.
Let us understand the problem with few examples:
[8, 15, 3, 7] : The user collects maximum value as 22(7 + 15)

Does choosing the best at each move give an optimal solution?
Is there any way to improve this code?
def optimal_strategy_game(v):
    n = len(v)
    t = [[0 for x in xrange(n)] for x in xrange(n)]
    for gap in xrange(n):
        for i in xrange(n):
            j = i + gap
            if j<n:
                x =  0 if i+1 > j-1 else t[i+1][j-1]
                y = t[i+2][j] if i+2 <j else 0
                z = t[i][j-2] if i <= j-2 else 0
                t[i][j] = max(v[i]+min(x,y), v[j]+min(x,z))
    print t
    print t[0][n-1]

v = [8,15,3,7]
n = len(v)
print optimal_strategy(0,n-1,v)
optimal_strategy_game(v)


texts: Leetcode 102: Binary tree level-order traversal in Swift

texts:
102. Binary Tree Level Order Traversal

  Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

  For example:

  Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

  return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

This is my solution in Swift:

func levelOrder(_ root: TreeNode?) -> [[Int]] {
        guard let root = root else{
            return []
        }
        let nodes = recursiveVisit(root)
        let capacity = nodes.reduce([Int]()) {
            if $0.contains($1.0) == false {
                return $0 + [$1.0]
            }
            return $0
        }.count
        return nodes.reduce([[Int]](repeating: [], count: capacity), {
          var tmp = $0
            tmp[$1.0].append($1.1)
            return tmp
        })
    }

func recursiveVisit(_ node: TreeNode?) -> [(Int, Int)]{
        //  [(Int,  Int)]
        //  depth,      node.val

        guard let node = node else{
            return []
        }

        var nodes = [(Int, Int)]()
        nodes.append((0, node.val))

        let lhs = recursiveVisit(node.left).map {
            return ($0.0 + 1, $0.1)
        }

        let rhs = recursiveVisit(node.right).map {
            return ($0.0 + 1, $0.1)
        }
        nodes.append(contentsOf: lhs)
        nodes.append(contentsOf: rhs)
        return nodes
    }

The solution is very intuitive: collect the nodes' value and depth, then reduce to the answer.

It is not as well designed as the Java Solution, though.

My question is mainly on the Swift syntax.  Is there any other way to do it more lean? Combine the two reduce() calls to one, for example?


texts: Update database, reload page then show a success message

texts:
I have spent a long time trying to find a way to do the following:

Update a MySQL database with AJAX
Reload the Page to show changes
Show a success message

I think I have finally found a way!  Let me know of any improvements.

The method:

Make your Ajax call and reload on success
Set a session in your php code with a variable
Check the session is set and output the necessary message
Empty the session

The in-page AJAX call:

$(document).on("click",".active_button",function() {

    var articleID = $(this).attr("name");
    var active = $(this).val();

    $.ajax({
        type: "POST",
        url: "controllers/articlecontrol.php",
        data: { articleID: articleID, active:active },
        success: function(data){
            document.location.reload(true);
        }
    });
});

The PHP (articlecontrol.php):

// ACTIVATE / DEACTIVATE w/Button
if(isset($_POST['active'])) {
    $active = $_POST['active'];
    $articleID = $_POST['articleID'];
    if($active == 'YES') {
        $update = array('article_active' => '0');
        $where = array('article_id' => $articleID);
        $sql = $database->update('wcx_articles', $update, $where);
        if($sql) {
            $_SESSION['status'] = 'deactivated';
        }
    }
    if($active == 'NO') {
        $update = array('article_active' => '1');
        $where = array('article_id' => $articleID);
        $sql = $database->update('wcx_articles', $update, $where);
        if($sql) {
            $_SESSION['status'] = 'activated';
        }
    }
}

The success message (in same page as AJAX):

if(isset($_SESSION['status'])) {
    if($_SESSION['status'] == 'activated') {
        echo '
Activated Successfully
';
        $_SESSION['status'] = '';
    }
    if($_SESSION['status'] == 'deactivated') {
        echo '
Deactivated Successfully
';
        $_SESSION['status'] = '';
    }
}


texts:
I've been reading the security issue on logging out from a website system written in PHP, using sessions.

My current code is:

session_start();

if (isset($_SESSION["logged_in"])) {
    unset($_SESSION["logged_in"]);
    unset($_SESSION["ss_fprint"]);
    unset($_SESSION["alive"]);
    session_destroy();
    session_regenerate_id(true);
}
// NEW MODIFIED CODE
session_start();

if (isset($_SESSION["logged_in"])) {

$_SESSION = array();

if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

session_destroy();

header("Location: ../index.php");
die();
} else {
header("Location: ../online.php");
die();
}

I use this class.

The code from the class should ensure and protect against hijacking and capture and fixation.

I have generated a session with this code from the above link, and I want to logout properly.

I tried print_r() out all $_SESSION data, and it was empty after I ran my logout code.

Is my logout secure enough?

OBS:: This system I'm making is not for some big company with a huge big mega need for security, but the basics should be implemented.


texts: Concurrent AWS S3 copying of images listed in MySQL

texts:
I created the following one off script and it did the task quite well (1000s of requests / second with low CPU usage - outperformed the previous python script in every aspect). But I am wondering if there are more "gophonic" ways to accomplish this in Golang? (the word for pythonic in Go? :p )  The code was gofmt'd and golint'd.

The result set is variable but in the range between 100k and 20M rows (as such so many copy requests to AWS has to be done).

After some helpful comments I already edited the code once to rename the concurrency flag to reflect the intend of the current (original) implementation better (numberChannels -> numberGoRoutinesForCopy).

My main concern for this review is to have optimal efficiency with large number of concurrent invocations of copyKey independent of where the data came from, resp. what exactly the copying does.

import (
    "flag"
    "log"
    "os"

    "database/sql"
    _ "github.com/go-sql-driver/mysql"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/s3"
)

var (
    from = flag.String(
        "from", "2011-01-01 00:00:00",
        "From Date.",
    )
    to = flag.String(
        "to", "2011-12-31 23:59:59",
        "To Date.",
    )
    region = flag.String(
        "aws.region", "us-east-1",
        "AWS region.",
    )
    numberGoRoutinesForCopy = flag.Int(
       "concurrency", 250,
       "Concurrent Requests.",
    )

    sizes = [11]string{
        "catalog",
        "catalog-m",
        "cart",
        "product",
        "product-m",
        "gallery",
        "zoom",
        "related",
        "list",
        "feed",
        "progressproduct",
    }
)

type imageMetaData struct {
    ID    string
    Sku   string
    Image string
    Size  string
}

func main() {
    log.SetOutput(os.Stdout)
    flag.Parse()
    done := make(chan bool)

    sess := session.Must(session.NewSession())

    svc := s3.New(sess, aws.NewConfig().WithRegion(*region))

    ch := make(chan imageMetaData)
    go getData(*from, *to, ch)

    log.Println(*numberGoRoutinesForCopy)
    for i := 0; i < *numberGoRoutinesForCopy; i++ {
        go func(messages <-chan imageMetaData) {
            for data := range messages {
                copyKey(data, svc)
            }
            close(done)
        }(ch)
    }

    <-done
    log.Println("done")
}

func getData(from string, to string, ch chan imageMetaData) {

    var (
        id    string
        sku   string
        image string
    )

    db, err := sql.Open("mysql", "database_conn")
    db.SetMaxIdleConns(0)
    if err != nil {
        // we won't stop on error
        log.Println(err.Error())
    }
    defer db.Close()

    rows, err := db.Query("SELECT some_big_sql_left_out_for_brevity")
    if err != nil {
        // we won't stop on error
        log.Println(err)
    }
    defer rows.Close()

    for rows.Next() {
        err := rows.Scan(&id, &sku, &image)
        if err != nil {
            // we won't stop on error
            log.Println(err)
        }

        for _, size := range sizes {
            ch <- imageMetaData{
                Id:    id,
                Sku:   sku,
                Image: image,
                Size:  size,
            }
        }
    }

    close(ch)
}

func copyKey(ImageData imageMetaData, svc *s3.S3) {

    var keyName = getKeyName(ImageData)
    params := &s3.CopyObjectInput{
        Bucket:     aws.String("some_bucket"),
        CopySource: aws.String("some_other_bucket/" + keyName),
        Key:        aws.String(keyName),
    }

    _, err := svc.CopyObject(params)

    if err != nil {
        log.Println(err)
    }

    log.Println(keyName + " copied")
}

func getKeyName(ImageData imageMetaData) string {
    runes := []rune(ImageData.Id)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes) + "/" + ImageData.Image + "-" + ImageData.Size + ".jpg"
}


texts: Converting numbers to words - JavaScript

texts:
I recently worked on this problem that converts numbers to words. I was wondering if there is a better way to do it than mine, And I will really appreciate any reviews to my version of the solution and on how to make it better

/**
 * Converts a given number into words
 * @param {integer} , num, the number to be converted into words
 * @return {string} , the coverted number in words
 */
function numToEng(num){
  let numInWords = '';

  // will be using this as a number that will be reduced by 1000
  let tempNum = num;

  const wordsForConstruction = {
    0: 'zero',
    1: 'one',
    2: 'two',
    3: 'three',
    4: 'four',
    5: 'five',
    6: 'six',
    7: 'seven',
    8: 'eight',
    9: 'nine',
    10: 'ten',
    11: 'elleven',
    12: 'twelve',
    13: 'thirteen',
    14: 'fourteen',
    15: 'fifteen',
    16: 'sixteen',
    17: 'seventeen',
    18: 'eighteen',
    19: 'nineteen',
    20: 'twenty',
    30: 'thirty',
    40: 'fourty',
    50: 'fifty',
    60: 'sixty',
    70: 'seventy',
    80: 'eighty',
    90: 'ninety',
  }

  const wordsToAdd = [
    'thousand',
    'million',
    'trillion',
  ]

  if(num >= 0 && num <= 19){
    return `${wordsForConstruction[num]}`;
  }

  let hundreds;
  let tens;
  let ones;

  for(let i = 0; tempNum; i++){

    hundreds = tempNum % 1000;
    tempNum = (tempNum-hundreds)/1000;

    // construct words for hundred only if it is not a zero
    if(hundreds){

      // If the loop runs the second time, this will add the words
      // thousand, million, trillion, and so on, depending on the num
      // of words in the wordsToAdd[] Array
      if(i){
        numInWords = wordsToAdd[i-1] + " " + numInWords;
      }

      tens = hundreds % 100;
      hundreds = (hundreds - tens)/100;

      // construct words for tens only if it is not a zero
      if(tens){

        // is tens is a property of the wordsforconstruction then
        // just pull the word from the object
        if(wordsForConstruction.hasOwnProperty(tens)){
          numInWords = wordsForConstruction[tens] + " " + numInWords;
        }else{
          ones = tens%10;
          tens = tens-ones;
          if(ones){
            numInWords = wordsForConstruction[ones] + " " + numInWords;
          }
          numInWords = wordsForConstruction[tens] + " " + numInWords;
        }
      }

      if(hundreds){
        numInWords = wordsForConstruction[hundreds] + " hundred " + numInWords;
      }
    }
  }

  return numInWords;
}

/**
 * Initiates the program and runs the test cases
 */
function main(){
  const testCases = [
    0,
    101,
    100234,
    909,
    1000000,
    1000,
    9999999,
    90909090,
  ]

  testCases.map(tCase => {
    console.log();
    console.log(`numToEng(${tCase}) ➞ ${numToEng(tCase)}`);
  })
}

main();

Also if you find any bugs or issues with the solution please feel free to reply to this thanks in advance.


texts:
Problem Statement

This problem is a programming version of Problem 3 from projecteuler.net

  The prime factors of 13195 are 5, 7, 13 and 29.

  What is the largest prime factor of a given number N?

  Input Format First line contains T, the number of test cases. This is followed by T lines each containing an integer N.

  Output Format

  For each test case, display the largest prime factor of N.

  Constraints

  \$1 \le T \le 10\$

  \$10 \le N \le 10^{12}\$

#include<stdio.h>  //C language
int main()
{
long long  number; //Declaring Variables
int cases;
scanf("%d",&cases);
while(cases--)
{
    scanf("%lld",&number);
    long long div=2, ans = 0, maxFact;
    while(number!=0)
        {
            if(number % div !=0)
                div = div + 1;
            else
            {
                maxFact  = number;
                number = number / div;

                if(number == 1)
                    {
                        printf("%lld\n",maxFact);
                        ans = 1;
                        break;
                    }
            }
        }
 }
 return 0;
}

How can the speed be increased? This code gives me timeout error in the last test case of HackerRank.


texts:
This sequence properly shows whether the TouchpadOff option for synclient is on or not (outputs either a 0 or a 1):

synclient | grep 'TouchpadOff' | tail -n 1 | awk '{print substr($3, 1)}'

Trying to make a keyboard shortcut to toggle the touchpad with a basic script based on that line, I wrote this:

#!/bin/bash

PADOFF=$(synclient | grep 'TouchpadOff' | tail -n 1 | awk '{print substr($3, 1)}')
if [ "$PADOFF" == "0" ]
then
    synclient TouchpadOff=1
else
    synclient TouchpadOff=0
fi.


texts:
I have a function that I need to optimize:

def search(graph, node, maxdepth = 10, depth = 0):
    nodes = []
    for neighbor in graph.neighbors_iter(node):
        if graph.node[neighbor].get('station', False):
            return neighbor
        nodes.append(neighbor)
    for i in nodes:
        if depth+1 > maxdepth:
            return False
        if search(graph, i, maxdepth, depth+1):
            return i
   return False

graph should be a networkx graph object. How can I optimize this?  This should find the closest node in the network with 'station' attribute to True.


texts: Store a hash in a cookie to identify the user's account to keep logged in after close browser

texts:
I made a option to user choose to stay logged in even after he closes the browser. It's really simple to implement, but i'm not sure about the hash i used to identify the user that is stored in a cookie.

To generate the hash i used bin2hex(random_bytes(59/2)) this function generate a string like this one:

118f9bc738e28b5079cf04bc3c88b2754f8ae04c9f1e1127d020389c49

To make sure that it's unique for each user, before register new accounts i check all hashes that i already have in my database.

I only use this hash to identify the user using the cookie, is it safe? The lenght of the hash is good enough to a Brute force attack be impossible, right?

What do you guys think about my code?

register.php

$hash = bin2hex(random_bytes(59/2));

login.php

##
## Get data from database using $_POST variable from <form>
##
if(!empty($_POST['stay_loggedIn'])){
  setcookie('stay_loggedIn', $fetch_data['hash'], strtotime('+14 days'), '/');
}

index.php

if(!empty($_COOKIE['stay_loggedIn']) && empty($_SESSION['logged_cookie'])){

    ## Set this session variable to run this code only one time
    $_SESSION['logged_cookie'] = 1;

    $hash = $_COOKIE['stay_loggedIn'];
    $logeIn = $conn->prepare("SELECT * FROM users WHERE `hash` = :hash");
    $logeIn->bindValue(':hash', $hash, PDO::PARAM_STR);
    $logeIn->execute();
    $user_data = $logeIn->fetch(PDO::FETCH_ASSOC);
    ##
    ## Set session variables
    ##
}

logout.php

$params = session_get_cookie_params();
setcookie('stay_loggedIn', '', time() - 3600, $params['path'], $params['domain'], $params['secure'], isset($params['httponly']));


texts: Collaboration of the two functions through multithreading

texts:
I'm going to turn them (multi-threading) to the first function after the end of the operation to notify the second function that has already finished work and the second function it received through multi-threading.

#include "stdafx.h"
#include <cstdint>
#include <iostream>
#include <mutex>
#include <queue>
#include <condition_variable>
#include <fstream>
#include <sstream>
#include <algorithm>
std::mutex mutex;
std::queue<std::string> queue;
std::condition_variable conditionVariable;

void ProduceData()
{
   const char* pathToFile = "D:\\text.txt";
   std::ifstream stream(pathToFile);
   if (!stream)
   {
      std::cout << "Can not open file\n";
      return;
   }

   const std::uint8_t maxWordCount = 5;
   std::string word;
   while (stream >> word)
   {
      std::lock_guard<std::mutex> lockGuard(mutex);
      for (std::uint8_t count = 0; (count < maxWordCount) || (count != '\0'); ++count)
        queue.push(word);
      conditionVariable.notify_one();
   }
 }

 void ConsumeData()
 {
   while (true)
   {
    std::unique_lock<std::mutex> uniqueLock(mutex);
    conditionVariable.wait(uniqueLock, [] {return !queue.empty(); });
    while (!queue.empty())
    {
        const std::string& str = queue.front();
        std::size_t numVowels = std::count_if(str.begin(), str.end(), isVowel);
        std::cout << str << "-" << numVowels;
        queue.pop();
    }
    uniqueLock.unlock();
   }
}

int main()
 {
std::thread t1(ProduceData);
std::thread t2(ConsumeData);
t1.join();
t2.join();

  return 0;
 }


texts:
I've been just getting started with Agda. I tried to prove, as exercise, evenness.

even : ℕ → Bool
even 0             = true
even 1             = false
even (suc (suc x)) = even x

x : even 12 ≡ true
x = refl

But asserting truth using _≡_ seems like a really bad way. What would be the best way of doing the same thing?


texts: Storing and processing large arrays to compute dot products

texts:
Problem Statement (from HackerRank)

  We have two arrays \$a\$ and \$b\$ of length \$N\$, initially all values equals to
  zero. We have \$Q\$ operations. Let's define three types of operations on
  this arrays:

  1 l r c: Increase \$a_l, a_{l+1}, \ldots, a_r\$ by \$c\$.
  2 l r c: Increase \$b_l, b_{l+1}, \ldots, b_r\$ by \$c\$.
  3 l r: Print \$a_l\cdot b_l + a_{l+1}\cdot b_{l+1} +\ldots+ a_r\cdot b_r\$ in modulo \$1000000007\$.

  Input Format

  First line of the input consists of \$N\$ and \$Q\$. Next \$Q\$ lines contain one of the three types of operations.

  Constraints

  \$1 \le N \le 10^9\$
  \$1 \le Q \le 200000\$
  \$1 \le c \le 10000\$
  \$1 \le l \le r \le N\$

  Output Format

  Whenever you get a type 3 operation, you should print the answer in a
  new line.

  Sample Input 1

5 3
1 1 5 5
2 2 4 2
3 3 4

  Sample Output 1

20

  Sample Input 2

10 20
1 9 9 6768
2 5 5 2202
3 7 7
2 3 9 1167
2 1 7 8465
3 1 5
2 1 1 1860
3 9 9
2 5 5 2153
1 5 7 749
3 1 1
2 8 10 3129
3 1 1
1 2 10 2712
2 1 8 79
1 1 6 4645
1 7 7 1358
3 2 10
1 9 9 8677
3 8 10

  Sample Output 2

0
0
7898256
0
0
506356461
98353320

How can I efficiently store and process data for this problem?

#include<stdio.h>
#include<string.h>
int main()
{
    long n,q,ch,l,r,c,i,j;
    /* n, q, l, r, c works as per problem statement.
       ch is used to scan the first digit of operation.
       i and j are used to control the loops. */
    scanf("%ld %ld",&n,&q);
    long a[n],b[n];
    memset(&a, 0, sizeof a);
    memset(&b, 0, sizeof b);
    for(i=0;i<n;i++)    //Init to 0
    {
        a[i]=0;
        b[i]=0;
    }
    for(i=0;i<q;i++)
    {
        scanf("%ld ",&ch);  //Look for the first digit
        switch(ch)
        {
            case 1:
                scanf("%ld %ld %ld",&l,&r,&c);
                l--;
                for(j=l;j<r;j++)
                    a[j]+=c;    //Adds c to every element of a
                break;
            case 2:
                scanf("%ld %ld %ld",&l,&r,&c);
                l--;
                for(j=l;j<r;j++)
                    b[j]+=c;    //Adds c to every element of b
                break;
            case 3:
                scanf("%ld %ld",&l,&r);
                l--;
                c=0;
                for(j=l;j<r;j++)
                    c+=a[j]*b[j];   //Adds the product
                printf("%ld\n",c%1000000007);   //Prints the value after using mod
                break;
        }
    }
}


texts:
I've added decimal (floating point) functionality to my calculator implementation; it's working but I'm having trouble making it more concise and less ugly.

I'm trying to use the same method to handle both number keys and the decimal point, and whichever way I look at it, I either have to check for the button being pressed and then whether the user is just starting a new entry, or the other way around. I've even drawn a flowchart to see how could this be condensed with nested logical operators (||, &&) but couldn't get it to work.

Obviously I could write a separate method for the decimal key, but then I'd get to repeating the isTyping verification there instead. Is there a simple way to do this or is code repetition inevitable at some point or another?

@IBAction func buttonDigit(sender: UIButton) {
    let digit = sender.currentTitle!

    if isTyping {
        if digit == "." {
            if !hasDecimal {
                display.text = display.text! + digit
                hasDecimal = true
            }
        } else {
            display.text = display.text! + digit
        }
    } else {
        if digit == "." {
            display.text = "0" + digit
        } else {
            display.text = digit
        }
        isTyping = true
    }
}


texts: Comma Code (project from "Automate the Boring Stuff with Python")

texts:
I'm currently learning Python using the book mentioned in the title. I just finished reading about lists, tuples, functions and methods, and one of the projects following this chapter is to create a program which takes in a list as an input and outputs a corresponding string, as the following example showcases:

Input:  ['apples', 'bananas', 'tofu', 'cats']

Output: apples, bananas, tofu, and cats

This should of course work for any list. So I've come up with the following code:

def listToString(someList):
    for i in range(len(someList)):
        newString = str(someList[i])

        if i == (len(someList)-1):
            print('and ' + str(someList[i]))
        else:
            print(newString, end=', ')

someList = ['apples','bananas','tofu','cats']
listToString(someList)

I feel like I haven't used everything (for example, some methods) which were taught in the chapter to solve the problem. Is there a more efficient way to code this project?


texts:
I wrote this simple linked list in JavaScript. Feedback is welcome.

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

function LinkedList()
{
    this.length = 0;
    this.head = null;

    // add node with given value to the list.
    this.add = function (value)
    {
        var node = new Node(value);

        var temp;

        if(this.length == 0)
        {
            this.head = node;
            this.length++;
            return;
        }

        temp = this.head;

        // Move to the position where we can perform addition
        // This logic is slightly different when we for example need to do search.
        while(temp.next)
        {
            temp = temp.next;
        }

        temp.next = node;
        this.length++;

        return;

    }

    // Search for node with given value.
    this.search = function (value)
    {
        // index where the node was found
        var index = 0;

        // If the list is empty there is no point in searching.
        if(!this.head)
        {
            console.log("List is empty");
            return;

        }

        var temp = this.head;

        while(temp)
        {
            if(temp.data == value)
            {
                console.log("Found at: "  + index);
                return;
            }

            // move to next node
            temp = temp.next

            index++;
        }

        console.log("Node not found");

    }

    // Dump whole list
    this.print = function()
    {
        if(!this.head)
        {
            console.log("List is empty");
            return;

        }

        var temp = this.head;

        while(temp)
        {
            console.log(temp.data);
            temp = temp.next
        }

    }

    // Remove node at index. Index starts from 0.
    this.removeAtIndex = function (index)
    {
        var i = 0;

        if(index < 0 || index >= this.length)
            throw "Wrong index";

        var temp = this.head;

        if(!this.head)
            return;

        if(index == 0)
        {
            this.head = this.head.next;
            this.length--;
            return;
        }

        // Move to the position where we can perform delete.
        for(i = 0; i < index  - 1; i++)
        {
            temp = temp.next;
        }

        temp.next = temp.next.next;
        this.length--;
        return;

    }
}

var x = new LinkedList();
x.add(200);
x.add(100);
x.add(300);
x.add(400);
x.print();
x.search(400);
x.removeAtIndex(2);
x.print();
x.search(400);


texts:
I am using an array_count_values function since I have translated the code from php to javascript and javascript does not have this function, but not sure on the performance of it. I'm sure it can be faster. It currently takes 50ms for 32000 iterations each time it is called.

I have one that returns a simple array:

function array_count_values(arr) {//returns array
    let a = [], prev;
    arr.sort();
    for ( let i = 0; i < arr.length; i++ ) {
        if ( arr[i] !== prev ) {
            a.push(1)
        } else {
            a[a.length-1]++;
        }
        prev = arr[i];
    }
    return a;
}

And another that returns an object:

function array_cnt_values(arr) {//returns object
    let a = [], prev;
    arr.sort();
    for ( let i = 0; i < arr.length; i++ ) {
        if ( arr[i] !== prev ) {
            a[arr[i]] = 1
        } else {
            a[arr[i]]++;
        }
        prev = arr[i];
    }
    return a;
}


texts: Saving away URL query parameters in an analytics application

texts:
We are trying to use NodeJS for analytics. The following code gets the parameter from a URL and dumps it into a flat file. Is there any way to optimize it to get better response time?

var http = require("http");
var url = require("url");
var cluster = require('cluster');
var fs = require('fs');
var numCPUs = require('os').cpus().length;
var stream = [];
if (cluster.isMaster) {
        for (var i = 0; i < numCPUs; i++) {
                cluster.fork();

        }
        cluster.on('death', function(worker) {
                console.log('worker ' + worker.pid + ' died');
        });
}
else{
    var server = http.createServer(function(request, response) {
        response.end();
    });
    stream = fs.createWriteStream("nodejsCluster"+cluster.worker.id+".txt");
    stream.once('open', function(fd) {
        server.listen(8084);
    });
    server.on('request', function(request, response){
            var parsedUrl = url.parse(request.url, true, true);
            var queryAsObject = parsedUrl.query;
            stream.write( ( new Date()  )+'This is the content to write into file '+queryAsObject.test+"\n");
    });
    console.log("Server is listening"+cluster.worker.id);
}


texts: An interesting use of the reduce function to convert tab-delimited data into JSON

texts:
I am learning functional programming in JavaScript. This is some code from a video tutorial by funfunfunction. I am particularly concerned about the way the existence of the customer key is checked in the customers object.

Is it weird to do it this way? Is there any other way? Also, if you switch the order of the OR statement operands, the object is overwritten. Does order matter in an OR statement?

The function:

var fs = require('fs')

var output = fs.readFileSync('data2.txt', 'utf8')
  .trim()
  .split('\r\n')
  .map(function(line) {
    return line.split('\t')
  })
  .reduce(function(customers, line) {
    customers[line[0]] = customers[line[0]] || []
    customers[line[0]].push({
      item: line[1],
      quantity: line[2],
      price: line[3],
    })
    return customers
  }, {})

console.log('output', JSON.stringify(output, null, 2));

The data:

Marry Poppins red bicycle 80  2
Marry Poppins glass vase  20  8
Abe Lincoln   gold ring   1   100
Marry Poppins umbrella    5   50
Steve Rogers  video camera    1   100
Abe Lincoln   president chair 1   1000
Marry Poppins blue dress  2   200


texts:
I am looking for feedback to improve code readability and improve the algorithm's efficiency. I have already posted a question on code review about this. The feedback was helpful, and I did rethink the data structures.
Link to the previous question: Job Scheduling Algorithm
Info about classes:
Item is the item the machines work on.
Machine is a single machine that can be used from start time to end time.
A single task is a single item on a machine.
Job is a complete job, and can have more than one task.
The algorithm schedules the tasks, re-orders them for the specific machine, and adds to total profit is a job is finished within the schedule.

class ItemModel:
    def __init__(self, name:str, starts:int, ends:int)->None:
        self.name = name
        self.start = start
        self.ends = ends

class JobModel:
    def __init__(self, tasks_needed:int, tasks_done:int, profit:int)->None:
        self.tasks_needed = tasks_needed
        self.tasks_done = tasks_done
        self.profit = profit

class MachineModel:
    def __init__(self, starts:int, ends:int)->None:
        self.starts = starts
        self.ends = ends

class View:
    def output_profit(profit:int)->None:
        print("profit: " + str(profit), end = "\n")

    def output_sublist(sublist:[int])->None:
        for item in sublist:
            print(str(item), end = " ")
        print('\n')

def algorithm(items:[ItemModel], jobs:[JobModel], machines:[MachineModel])->(int, [ItemModel]):
    total_profit = 0
    for start in range(len(items)):
        for end in range(len(items)):
            for job_row in range(len(jobs)):
                if (time >= jobs[job_row].start_time) and (time <= jobs[job_row].end_time):
                    jobs[job_row].task_done += 1

            profit = 0
            for job_row in range(len(jobs)):
                if jobs[row].tasks_needed == jobs[row].tasks_done:
                    profit += jobs[row].profit

            yield (profit, sublist)

def main():
    items = [ItemModel("a", 0, 2), ItemModel("b", 3, 4)]
    jobs = [JobModel(0, 0, 12), JobModel(0, 0, 10)]
    machines = [MachineModel(0, 1), MachineModel(0, 7)]
    View view = View()
    for pair in algorithm(items, jobs, machines):
        view.output_profit(pair[0])
        view.output_sublist(pair[1])

if __name__ == "__main__":
    main()
 ```


texts:
I'm trying to print a diamond of asterisks of an arbitrary size. I'm new to F#, so I'm interested in virtually any feedback, but especially adherence to idioms, convention, and functional orientation.

module Diamond
open System

let rangeWithInverse (max) =
    List.zip [ 1 .. max ] [ max .. -1 .. 1]

let listAscDesc (list) =
    list @ (list |> List.rev |> List.skip 1)

let starsAndSpacesString (stars: int, spaces: int): string =
    String.replicate spaces " " + String.replicate ((stars * 2) - 1) "*"

let diamond =
    rangeWithInverse 18
        |> listAscDesc
        |> Seq.map starsAndSpacesString
        |> Seq.reduce (fun a b -> a + "\n" + b)

[<EntryPoint>]
let main argv =
    diamond |> printfn "%s"
    0


texts:
I want to find a quick way to see if a matrix M has at least one value that is, say, 2. In R, I would use any(M==2). However, this computes first M==2 for all values in M, then use any(). any() will stop at the first time a TRUE value is found, but that still means we computed way too many M==2 conditions.

I thought one could find a more efficient way, computing M==2 only as long as it is not satisfied. I tried to write a function to do this (either column-wise check, or on each element of M, check_2), but it is so far much slower. Any idea on how to improve this?

Results of benchmark, where the value Val is rather at the end of the matrix:

|expr               |mean time |
|:------------------|---------:|
|any(M == Val)      |  14.13623|
|is.element(Val, M) |  17.71230|
|check(M, Val)      |  18.20764|
|check_2(M, Val)    | 486.65347|

Code:

x <- 1:10^6
M <- matrix(x, ncol = 10, byrow=TRUE)

Val <- 50000

check <- function(x, Val) {
  i <- 1
  cond <- FALSE
  while(!cond & i <= ncol(x)) {
    cond <- any(M[,i]==Val)
    i <- i +1
  }
  cond
}

check_2 <- function(x, Val) {
  x_c <- c(x)
  i <- 1
  cond <- FALSE
  while(!cond & i <= length(x_c)) {
    cond <- x_c[i]==Val
    i <- i +1
  }
  cond
}

check_2(x=M, Val)
check(M, Val)

library(microbenchmark)

comp <- microbenchmark(any(M == Val),
               is.element(Val, M),
               check(M, Val),
               check_2(M, Val),
               times = 20)

comp


texts:
I was disappointed using GCM, so I'll use long polling for crucial parts. Following my approach:

protected void onCreate(Bundle savedInstanceState) {
    new LongPolling().execute();
}

private class LongPolling extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        HttpClient hclient = new DefaultHttpClient();
        HttpPost httpr = new HttpPost(new URL("http://10.0.2.2/page.php").toURI());
        HttpResponse response = hclient.execute(httpr);
        String result = EntityUtils.toString(response.getEntity());
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        new LongPolling().execute();
    }

}

Is it the right approach for the long polling, or do you want to suggest a better approach? Also, a IntentService starts when you turn on the phone to run that code, would be better to use a Service?


texts: Saving class including a container with pickle

texts:
I am writing a program that has a 'base' class called Group. The class will have only one instance. Aside from some properties and methods, it needs to keep track of a variable amount of group_companies.
After working with the program (that may involve adding or deleting group_companies), I want to save the current state of my work to a file, which can be imported in the next session. I read that pickle can be used for that and even for 'pickling' classes. I have seen similar questions but none answering my question, or yet too complicated for me to be understood.
I came up with the following solution hereunder that seems to work.
Is there a better approach than my solution? I tried to define the group_companies as a class variable, but then it won't 'unpickle' (the group_companies dictionary remains empty).
The next step will involve changing the group_companies from dictionaries to classes themselves. Will that still work?
That you for your help and insights.
import pickle

class Group():
    """ Creates a group, its metadata and its methods. """

    def __init__(self, name, rates):
        self.name = name
        self.rates = rates

    def add_group_company(self, name, descriptor):
        try:
            self.group_companies[name] = descriptor
        except Exception:
            self.group_companies = {}
        self.group_companies[name] = descriptor

    def __repr__(self):
        return "This is group {}".format(self.name)

# Initialize some variables
group_name = 'XYZ'
rates = {'EUR': 1.0000,
         'USD': 1.2364,
         'NOK': 8.3254,
         }

# Create a group and add some group_companies
group = Group(group_name, rates)
group.add_group_company('ABC', 'some data')
group.add_group_company('DEF', 'moar data')

# pickle the class
with open('data', 'wb') as f:
    pickle.dump(group, f)

# Delete class instance and test if succesfully deleted
del(group)
try:
    print(group)
except Exception:  # catchall
    print("Variable appears no longer to exist.")

# Unpickle my class
with open('data', 'rb') as f:
    group = pickle.load(f)

# Test the results (satisfactory)
print(group)
print(group.group_companies)


texts: Using GetTempFileName api function to check write access to a directory

texts:
On windows, to find out if I have write access to a directory, I found that it is easiest to just create a file in that directory.

In order to do so, I found GetTempFileName() API function to get an almost(?) unique file name in the desired directory, then I was going to create a file with that name. so if everything goes well, I have the write access and everything is fine.

Then I found two behavior from the mentioned API call:

If I have write access, it creates the temporary file and returns the path through its output parameter, named lpTempFileName
When I don't have write access, it just clear out the buffer, and literally returns an empty string as temp file name (lpTempFileName).

I can't find this bit of information in documents. Is this always valid? If so I can rely on it and just decide based on if the returned string is empty or not, instead of calling CreateFile and Closing the Handle afterwards.

Here is what I'm doing now:

bool is_writable = true;

try
{
    CString tmp_file_name;
    ::GetTempFileName(folder_path, "ttt", 0, tmp_file_name.GetBuffer(MAX_PATH));
    HANDLE file = CreateFile(tmp_file_name, GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
    if ( file == INVALID_HANDLE_VALUE )
    {
        is_writable = false;
    }
    else
    {
        CloseHandle( file );
        DeleteFile( tmp_file_name );
        is_writable = true;
    }
}
catch (...)
{
    is_writable = false;
}

But here is what I can do if the above assumption is correct:

bool is_writable = true;

try
{
    CString tmp_file_name;
    ::GetTempFileName(folder_path, "ttt", 0, tmp_file_name.GetBuffer(MAX_PATH));

    if ( tmp_file_name.IsEmpty() )
    {
        is_writable = false;
    }
    else
    {
        DeleteFile( tmp_file_name );
        is_writable = true;
    }
}
catch (...)
{
    is_writable = false;
}

Certainly, two less API calls.

So is my finding always stands correct? can I rely on the second snippet?