texts: Project Euler problem 3: Largest prime factor in JavaScript

texts:
I have created a soloution for Project Euler: Problem 3 - Largest Prime Factor in JavaScript:

function isPrime(value) {
    for (var i = 2; i < value; i++) {
        if (value % i == 0) {
            return false;
        }
    }
    return true;
}

function findFactors(value) {
    var array = [];
    for (var i = 2; i < value; i++) {
        if (value % i == 0) {
            array.push(i);
        }
    }
    return array;
}

function findPrimeFactors(value) {
    var array = [];
    for (var i = 0; i < findFactors(value).length; i++) {
        if (isPrime(findFactors(value)[i])) {
            array.push(findFactors(value)[i]);
        }
    }
    return array;
}

document.write("Answer: " + Math.max(...findPrimeFactors(600851475143)));

I would like to know if my code even works, as it is so slow, that even when I left it for 20 minutes it still didn't finish, and if so, I would like to know a quick way of doing it (If my code would actually give it) so I can mark it as completed.


texts:
I made a small function that is getting looped when an input is getting focus and stopping the loop when the input is losing focus. Now I would like to know if there is a better way to write this code.

 var timer;
  function Change () {
    if( !$('#eventurl').val() ) {

      $("#js-skipbutton").text('overslaan');
      console.log(0);
    }
    else{
      $("#js-skipbutton").text('ophalen');
      console.log(1);
    }
  };
  $('#eventurl').focus(function() {
    timer = setInterval(Change, 200);
  });
  $('#eventurl').focusout(function() {
    clearTimeout(timer);
    Change();
  });

This code is changing the text to "overslaan" on a span when the input is empty and to "ophalen" when the input is containing text.


texts:
there is my implementation for cross domain call using the requireJs text plug-in

htaccess file in the template folder of my cross-domain site

Header set Access-Control-Allow-Origin "*"

textremote.js

define(['text','module'],function (text, module) {

    // Load the cross-domain url from the config
    var remoteUrl         = module.config().remoteUrl;

    // Store the current parseName function into a var
    var originalParseName = text.parseName;

    // Redefine the parseName function
    text.parseName = function(name) {

        // Use the original parseName
        var parsed = originalParseName(name);

        // append the cross-domain url to parsed.moduleName
        parsed.moduleName = remoteUrl+parsed.moduleName;

        return parsed;
    }

    // Force CORS to be true
    text.useXhr = function () {
        return true;
    }
});

In the main config (I remove the non related config)

require.config(
    {
        textremote  : "libs/textremote",

        // this config will be accessible in textremote.js through the module parameters
        config : {
        "textremote" : {
            remoteUrl : "http://www.cross-domain-asset.com/template/"
        }
    },
    }
)

initialization

This ensure that textremote is load first and will ovveride the text.parseUrl and text.useXhr before any usage.

require(['textremote'],function(){
    require(['libs/app'], function(app){
        app.initialize();
    });
})

Usage example

text!demo.tpl will pass through textremote and text plugin and use
http://www.cross-domain-asset.com/template/demo.tpl

// Filename: app.js
define([
  'router', // Request router.js
  'backbone',
  'marionette',
  'underscore',
  'text!demo.tpl'
], function(Router,backbone,marionette,_, demoTemplate){
  var initialize = function(){
    // Pass in our Router module and call it's initialize function
    Router.initialize();

   /* ... */

  }

  return {
    initialize: initialize
  };
});

That it, So far this is working well for me. But I would like to improve it or know if better approach exists.

On a side note, I will add code to allow multiple cross-domain usage and caching.


texts:
I'm new to Ruby and don't know all the methods, so I was thinking there would probably be and easier way to do something like this. I'd love any input on how to refactor this.

   define_singleton_method(:delete) do |id|
        revised_words = []
        @@words.each do |word|
          if word.id() != id
            revised_words.push(word)
          else
            Definition.delete_by_word_id(id)
          end
        end
        @@words = revised_words
      end


texts: Create map query for each unique value in column

texts:
I have a Python 3.6.8 script that does the following:

Takes the unique values in a column in a spatial table.
Creates map queries/layers for each unique value.

Each query/layer has a where clause that isolates the unique values.

The script uses a proprietary/OOB Python site package called ArcPy.

Can the code be improved?
def DuplicateLayer(CopyLayer, field, uniquevalue):
    p = arcpy.mp.ArcGISProject("Current")
    m = p.listMaps("Map")[0]
    LayerToDup = m.listLayers(CopyLayer)[0]
    print(LayerToDup.name)
    m.addLayer(LayerToDup, "AUTO_ARRANGE")
    LayerToDup.name = str(CopyLayer)
    lyr = m.listLayers(CopyLayer)[0]
    lyr.definitionQuery = field + " = '" + uniquevalue + "'"
    lyr.name = uniquevalue
    print (lyr.definitionQuery)

def unique_values(layer, field):
    with arcpy.da.SearchCursor(layer, [field]) as cursor:
        return sorted({row[0] for row in cursor})

def ExplodeFC(layername,field):
    fieldvals = unique_values(layername,field)
    for value in fieldvals:
        DuplicateLayer(layername,field,value)

ExplodeFC("WORKORDER","CLASSIFICATIONID")


texts: High execution time of LCS length program in Python2

texts:
I was trying to solve the Longest Common Subsequence problem on a HackerRank exercise.
It's quite simple and straightforward, just print out the length of the LCS. I submitted this code:

s1 = raw_input()
s2 = raw_input()

lcs = [[0 for j in xrange(len(s2)+1)] for i in xrange(len(s1)+1)]
for i, x in enumerate(s1):
    for j, y in enumerate(s2):
        if x == y:
            lcs[i+1][j+1] = lcs[i][j] + 1
        else:
            lcs[i+1][j+1] = max(lcs[i+1][j], lcs[i][j+1])

print lcs[-1][-1]

I think the logic is fine. The maximum string length is 5000. The problem is with the execution time. Some test cases take more than 10 seconds and the program terminates.


texts:
I have looked at many different approaches to this game online, but as someone who isn't very experienced with Python, I may not be aware of what others are doing right.

import random

def RPS():
    print("You are playing Rock Paper Scisscors")
    comp_possible  = 1,2,3
    score = [0,0]
    flag = 0
    while True:
        print("Enter your choice:")
        while True:
            choice = input('->')
            if choice == 'r' or choice == 'R' or choice == 'Rock' or choice == 'rock' or choice == '1':
                choice_identifier  = 1
                break
            elif choice == 'S' or choice == 's' or choice == 'Scissors' or choice == 'sciccors' or choice == '2':
                choice_identifier =  2
                break
            elif choice == 'P' or choice == 'p' or choice == 'Paper' or choice == 'paper' or choice == '3':
                choice_identifier =  3
                break
            else:
                print('That\'s not an option in this game :)')
                print('Try again:')
                continue

        comp_choice = random.choice(comp_possible)
        if choice_identifier == comp_choice:
            print('It\'s a draw!')
            score[0] = score[0] + 1
            score[1] = score[1] + 1
        elif (choice_identifier == 1 and comp_choice == 2) or (choice_identifier == 2 and comp_choice == 3) or (choice_identifier == 3 and comp_choice == 1):
            print('You win!')
            score[0] = score[0] + 1
        else:
            print('You lose...')
            score[1] = score[1] + 1

        while True:
            answer = input('Play another round?')
            if answer == 'y' or answer == 'Y' or answer == 'yes' or answer == 'Yes' or answer == 'ye' or answer == 'Ye' or answer == 'sure' or answer == 'Sure':
                print(' Current score: You - ',score[0],' Computer - ',  score[1])
                flag = 0
                break
            elif answer == 'n' or answer == 'N' or answer == 'no' or answer == 'No' or answer == 'nah' or answer == 'Nah':
                print('Thanks for playing! Final score: You - ',score[0],' Computer - ',  score[1])
                flag = 1
                break
            else:
                print('Yay or nay...')
                continue
        if flag == 0:
            continue
        else:
            break

RPS()

What things in my code are, for example, horribly inefficient or are bad practices?


texts:
Please critique to help me learn:

int getNextInt(int* number)
{
    int value = *number;
    (*number)++;
    if (*number > 3)*number = 1;
    return value;
}

I want a function that will increment an external number by one, when it goes over than 3, then reset it to 1.

essentially when I repeatedly call this function I want the out to me 1,2,3,1,2,3,1,2,3


texts:
Is the set_cookie variable the correct way to signal that the cookie should be set? It does not seems pythonic to me:

cookie = request.COOKIES.get(TIMEZONE_COOKIE_NAME)
set_cookie = False
if cookie and cookie in pytz.all_timezones_set:
    timezone.activate(pytz.timezone(cookie))
elif request.ip:
    geo = GeoIP2()
    try:
        time_zone = geo.city(request.ip).time_zone
        if time_zone:
            timezone.activate(pytz.timezone(time_zone))
            set_cookie = True
    except GeoIP2Error:
        self.logger.warning('Could not determine time zone of ip address: %s', request.ip)

response = self.get_response(request)
if set_cookie:
    response.set_cookie(TIMEZONE_COOKIE_NAME, time_zone)
return response


texts:
I wrote the following code to merge two sorted lists. Is there a way I can improve it?

Possible ideas (not sure how to implement them):

Remove code duplication (setting the returning list node and moving to the next)
Avoid the use of the infinite loop
Avoid the use of panic!

This is the data structure:

type Link = Option<Box<Node>>;

pub struct Node {
    elem: i32,
    next: Link,
}

impl Node {
    fn new(elem: i32) -> Node {
        Node { elem, next: None }
    }
}

And this is the method:

fn merge_sorted_lists(list1: &Link, list2: &Link) -> Link {
    if list1.is_none() || list2.is_none() {
        return None;
    }
    let mut res = None;
    {
        let mut node3 = &mut res;
        let mut node1 = list1;
        let mut node2 = list2;
        loop {
            if let (Some(link1), Some(link2)) = (node1, node2) {
                if link1.elem > link2.elem {
                    *node3 = Some(Box::new(Node::new(link2.elem)));
                    node2 = &link2.next;
                } else {
                    *node3 = Some(Box::new(Node::new(link1.elem)));
                    node1 = &link1.next;
                }
                if let Some(link) = {node3} {
                    node3 = &mut link.next;
                } else {
                    panic!();
                }
            } else if let Some(link1) = node1 {
                *node3 = Some(Box::new(Node::new(link1.elem)));
                node1 = &link1.next;
                if let Some(link) = {node3} {
                    node3 = &mut link.next;
                } else {
                    panic!();
                }
            } else if let Some(link2) = node2 {
                *node3 = Some(Box::new(Node::new(link2.elem)));
                node1 = &link2.next;
                if let Some(link) = {node3} {
                    node3 = &mut link.next;
                } else {
                    panic!();
                }
            } else {
                break;
            }
        }
    }
    res
}


texts:
Inspired by this CR question, I decided to create my own queue! If you guys see anything taboo or have any improvements, please let me know. Ultimately I want it to be feature rich and bug free, with every possible case tested, so if there's anything else that can be added (like an iterator) and thoroughly tested, please mention it.

IDoublingQueue.java

public interface IDoublingQueue<E> {
    public boolean isEmpty();
    public int size();

    public void enqueue(E item);
    public E dequeue();
}

DoublingQueue.java

public class DoublingQueue<E> implements IDoublingQueue<E> {

    private E[] queue;
    private int size = 0;
    private int first = 0;

    public DoublingQueue() {
        queue = (E[]) new Object[2];
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public int size() {
        return size;
    }

    private void resize(int max) {
        assert max >= size;

        E[] temp = (E[]) new Object[max];

        for (int i = 0; i < size; ++i) {
            temp[i] = queue[(first + i) % queue.length];
        }

        queue = temp;
        first = 0;
    }

    @Override
    public void enqueue(E item) {
        // be sure no null items make it into the queue
        if (item == null) {
            throw new IllegalArgumentException("ERROR: Null elements cannot be inserted!");
        }

        if (size == queue.length) {
            resize(2 * queue.length);
        }

        queue[size++] = item;
    }

    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new RuntimeException("ERROR: Queue underflow");
        }

        E item = queue[first];

        queue[first] = null;
        size--;
        first++;

        if (first == queue.length) {
            first = 0;
        }

        // shrink the queue if necessary
        if (size > 0 && size == queue.length / 4) {
            resize(queue.length / 2);
        }

        return item;
    }
}

Tests

public class DoublingQueueTest {

    private final DoublingQueue<Integer> queue = new DoublingQueue();

    @Test(expected = IllegalArgumentException.class)
    public void enqueueNullTest() {
        queue.enqueue(null);
    }

    @Test(expected = RuntimeException.class)
    public void dequeueEmptyTest() {
        queue.dequeue();
    }

    @Test
    public void enqueueTest() {
        queue.enqueue(1);
        queue.enqueue(2);
        queue.enqueue(3);

        assertTrue(queue.size() == 3);
    }

    @Test
    public void dequeueTest() {
        queue.enqueue(1);
        queue.enqueue(2);
        queue.enqueue(3);

        int num = queue.dequeue();

        assertTrue(num == 1);
    }
}


texts: Program to check whether two strings are anagrams of each other

texts:
I have written this code and I am wondering if the code could be optimised.Please review.

 public class Anagram1{
   public static boolean check(char[] c1,char[] c2,int l1,int l2){

     /*if the lengths of the strings are not equal,they cannot be anagrams of each other */

    if(l1!=l2){
        return false;
    }

    int count = 0;

    //nested for loops to compare the characters of both strings.
    //if the characters match,then the strings are anagrams of each other.
    for(int i=0; i<l1; i++){
        for(int j=0; j<l2; j++){
            if(c1[i]==c2[j]){
                count++;
                break;      //"break" used so as to count only a single occurrence of a
            }               //character.
        }
    }
    if(count==l1 && count==l2){
        return true;
    }
    return false;
}

public static void main(String[] args) {

    String s1 = "abcd";

    String s2 = "acdb";

    char[] c1 = s1.toCharArray();

    char[] c2 = s2.toCharArray();

    int l1 = s1.length();

    int l2 = s2.length();

    System.out.println(check(c1,c2,l1,l2));
  }
}


texts:
I have a Drupal site with roughly the following in my template.php hook_init block:

function mytemplate_init() {
    if (request_path() == "widgets_json") {
        drupal_json_output(_get_widgets());
        exit;
    }
    if (request_path() == "people_json") {
        drupal_json_output(_get_people());
        exit;
    }
}

Are there any problems with this approach?

On the face of it, the two main problems are that it's going to break if URL's ever change, and it's impossible to theme the output of those functions using an appropriate page--widget_json.tpl.php or page--people_json.tpl.php template. On the other hand, adding a content type just for a few JSON output pages that are never going to change paths seems like overkill.

What do you think of this approach?


texts: What are the downsides of my Mergesort implementation?

texts:
Could I ask you to evaluate my implementation of mergesort?

I think that it's consistent with \$\mathcal{O}(n \log n)\$ complexity but has a downside that I create a new result array at each step of recursion.

How do you think it can be improved?

public int[] mergesort(final int[] input) {
    return mergesort(input, 0, input.length - 1);
}

private int[] mergesort(final int[] input, final int left, final int right) {
    final int[] result;
    if (left < right) {
        final int m = (right - left) / 2 + left;
        final int[] leftPart = mergesort(input, left, m);
        final int[] rightPart = mergesort(input, m + 1, right);
        result = new int[leftPart.length + rightPart.length];
        int i = 0, j = 0;
        while (i < leftPart.length && j < rightPart.length) {
            if (leftPart[i] <= rightPart[j]) {
                result[i + j] = leftPart[i++];
            } else {
                result[i + j] = rightPart[j++];
            }
        }
        while (i < leftPart.length) {
            result[i + j] = leftPart[i++];
        }
        while (j < rightPart.length) {
            result[i + j] = rightPart[j++];
        }
    } else {
        result = new int[]{input[left]};
    }
    return result;
}


texts:
Given a number represented as an array of digits, plus one to the
  number.

input                    expected

[8,9,9,9]                [9,0,0,0]

[1,0,0,0,0]              [1,0,0,0,1]

[9,8,7,6,5,4,3,2,1,0]    [9,8,7,6,5,4,3,2,1,1]

The following is my C++ code:

vector<int> plusOne(vector<int> &digits)
{
    vector<int> result;
    vector<int>::iterator it;
    int plus = 1;
    for (it = digits.end() - 1; it >= digits.begin(); --it)
    {
        int sum = *it + plus;
        if (sum > 9)
        {
            plus = 1;
            result.push_back(0);
        }
        else
        {
            result.push_back(sum);
            plus = 0;
        }
    }

    if (plus==1)
    {
        result.push_back(1);
    }

    reverse(result.begin(), result.end());
    return result;
}


texts:
I have to store some properties in a database properties table which looks like this:

CREATE TABLE `property` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `computer_name` varchar(64) NOT NULL,
  `name` varchar(64) NOT NULL,
  `value` varchar(1024) NOT NULL,
  PRIMARY KEY (`id`)
);

Sample data:

+----+---------------+-----------------+-------+
| id | computer_name | name            | value |
+----+---------------+-----------------+-------+
|  9 | PC002         | firewall_status | 3     |
| 10 | PC011         | firewall_status | 0     |
| 11 | PC011         | some_property   | 1     |

To access data in that table I have a getProperty($computerName, $propertyName) method in a repository, which finds the value of specified property for certain computer.
And in different parts of my application I call the method like this:

$computer = $repository->findComputer();
$firewallStatus = $repository->getProperty($computer->name, 'firewall_status');

What I don't like here is hard coded name of the property.
My solution was to put available property names to a model:

class ComputerModel
{
    const PROPERTY_FIREWALL_STATUS = 'firewall_status';
    const PROPERTY_SOME_PROPERTY   = 'some_property';
}

...

$computer = $repository->findComputer();
$firewallStatus = $repository->getProperty($computer->name, ComputerModel::PROPERTY_FIREWALL_STATUS);

We discussed storing property names as constants and decided that we have some trade-offs:

Good (mostly for code maintanance):

keep the value in one place which make it more simple to change it;
keep available property dictionary in one place (in the model);
make the code completion available in IDE instead of searching for correct property name to copy/paste it;

Not good (mostly for debugging):

by storing a literal values we create extra overhead by storing
variable names in new variables;
worsen debugging by add one more step to find the object containing debug information;
we need to support additional dictionary; possible data inconsistency if someone adds new value to database but forget to update it in the model.

Subjective:

improves/reduces code readability.

The question is: what is the best way to store such parameter names? Or maybe to use literals.


texts: Packing and unpacking two 32-bit integers into an unsigned 64-bit integer

texts:
Does this look good for combining/retrieving two 32 bit integers (a type and an index) into/from an unsigned 64 bit integer (a unique ID)?

The point is to hide in the API the composition of the unique ID and allow its calculation to change later without changing the API (e.g. possibility to change later to consecutive 64 bit ids without changing API).

#include <limits>

uint64_t combine(uint32_t low, uint32_t high)
{
     return (((uint64_t) high) << 32) | ((uint64_t) low);
}

uint32_t high(uint64_t combined)
{
    return combined >> 32;
}

uint32_t low(uint64_t combined)
{
    uint64_t mask = std::numeric_limits<uint32_t>::max();
    return mask & combined; // should I just do "return combined;" which gives same result?
}

Or would a union approach like below be better? Is this union guaranteed to fit into 64 bits (e.g. guarantee no padding in the struct)?

union Id
{
    struct
    {
       uint32_t index; // lower 32 bits
       uint32_t type;  // upper 32 bits
    } split;

    uint64_t unique_id;
};

Here is some code I used to test:

#include <iostream>
#include <assert.h>
#include <sstream>

template <typename T>
std::string bits(T num)
{
    const int num_bits = sizeof(num) * 8;

    T maxPow = T(1) << (num_bits - 1);

    std::stringstream ss;

    for(int i=0; i < num_bits; ++i)
    {
        // print last bit and shift left.
        ss << (num & maxPow ? 1 : 0);
        if ((i+1) % 8 == 0) ss << " ";
        num = num << 1;
    }

    return ss.str();
}

void test1()
{
    {
        int in_low = -3;
        int in_high = 99;
        uint64_t combined = combine(in_low, in_high);
        assert( bits(in_high) + bits(in_low) == bits(combined) );
        assert( in_low == low(combined) );
        assert( in_high == high(combined) );
    }

    {
        uint32_t in_low = 3;
        int in_high = -99;
        uint64_t combined = combine(in_low, in_high);
        assert( bits(in_high) + bits(in_low) == bits(combined) );
        assert( in_low == low(combined) );
        assert( in_high == high(combined) );
    }

    {
        uint32_t in_low = std::numeric_limits<uint32_t>::max();
        int in_high = std::numeric_limits<int32_t>::min();
        uint64_t combined = combine(in_low, in_high);
        assert( bits(in_high) + bits(in_low) == bits(combined) );
        assert( in_low == low(combined) );
        assert( in_high == high(combined) );
    }
}

void test2() {
    Id in; // would "Id in = {-3, 99};" be better? Is this legal C++03? Would a constructor be better?
    in.split.type = -3;
    in.split.index = 99;

    std::cout << in.unique_id << std::endl; // prints 18446744060824649827
    std::cout << bits(in.split.type) << bits(in.split.index) << std::endl;
    std::cout << bits(in.unique_id) << std::endl; // prints 11111111 11111111 11111111 11111101 00000000 00000000 00000000 01100011
    assert(bits(in.split.type) + bits(in.split.index) == bits(in.unique_id));

    Id out;
    out.unique_id = in.unique_id;
    std::cout << int(out.split.type) << ", " << out.split.index << std::endl; // prints -3, 99

    assert(in.split.type == out.split.type);
    assert(in.split.index == out.split.index);
}


texts:
I'm building a simple chatApp. The UI has just 3 interaction areas: input, submit and previous messages button.
But I'm not interested in reviewing the app architecture as much as the javascript ideas and general understanding/errors.
I've commented the code, and would like to see if you can point out any bad practice. I'm sure most of the code is bad, but still, the most important errors.
I've also included the UI as a runnable snippet.
Any edits to make it better for reviewers will be done.

<!doctype html>

    <title>Socket.IO chat</title>

    <button id="wantMore">More</button>

    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>

const prevMsgs = document.querySelector("button#wantMore")
const uri = "http://localhost:3000"

class Msg {
  constructor (msg, createdAt){
    this.msg = msg
    this.createdAt = createdAt
  }
static toHTML ({msg, createdAt}) {
// pass object, builds list item.
  try{
  //in case the date conversion fails.
    createdAt = (new Date(createdAt))
      .toTimeString()
      .substr(0,5)
  } catch(e){ console.log(e) }
  finally{ createdAt || "" }
return `<li><span>${msg}</span> &nbsp; <span>${createdAt}</span></li>`
}

static put (data) {
  $("#messages").prepend(this.toHTML(data))
}

static getMsgs (uri, skip, limit) {
  //returns a promise, errors are catch
  return fetch(`${uri}/messages/skip/${skip}/limit/${limit}`)
    .then(data => data.json())
    .then(items => items.forEach(item => this.put(item)))
}

static getLastMsgs (uri) { return this.getMsgs(uri, 0,10) }

}

$(function () { // $(document).ready(

  Msg.getLastMsgs(uri).catch(e => console.log(e))

  prevMsgs.addEventListener("click", () => {
      const msgLen = parseInt($("#messages").children().length)
      Msg.getMsgs(uri, msgLen, msgLen+10)
    })

  const socket = io(); //connects to / origin

  $('form').submit(function(e) {
    e.preventDefault(); // prevents page reloading

    const msg = new Msg($('#m').val(), new Date())

    //for the sender, append right away.
    $("#messages").append(Msg.toHTML(msg))
    // and emit, and broadcast
    socket.emit('chat message', msg);
    $('#m').val('');
    return false;
  });

  socket.on('chat message', data => {
    $("#messages").append(Msg.toHTML(data))
  })
})

```


texts:
Zombies are questions with no upvoted answers.
I came up with this SEDE query to find answers with zero votes on questions that have no accepted answer and no answers with greater than zero score.
In other words, answers on questions that show up on the Unanswered tab,
until the answer receives an upvote. (Latest version is here, FYI, not subject for review.)

DECLARE @username AS NVARCHAR(60) = ##DisplayName:string? ##;
DECLARE @userId AS INT = ##UserId:int?-1##;

SELECT TOP 100
  u.Id AS [User Link],
  a.Id AS [Post Link],
  a.CreationDate
FROM Posts a
  JOIN Users u ON a.OwnerUserId = u.Id
  JOIN (
    SELECT q.Id, MAX(a.Score) MaxAnswerScore
    FROM Posts q
    JOIN Posts a ON a.ParentId = q.Id
    WHERE q.AcceptedAnswerId IS NULL
    GROUP BY q.Id
  ) q
  ON a.ParentId = q.Id
WHERE
  (@username = '' OR u.DisplayName = @username)
  AND (@userId = -1 OR u.Id = @userId)
  AND a.Score = 0
  AND q.MaxAnswerScore = 0
ORDER BY a.CreationDate DESC

Is there a better way to write this?
Can it be improved?


texts:
What this function does it's to return an array of remaining dates that are e.g. Mondays. Is this really the best way to do that?

function range(start, count) {
    return Array.apply(0, Array(count))
                .map(function (element, index) {
                         return index + start;
                     });
}

function GetAllRemainingDaysOfTheWeek(day)
{
    var today = new Date();
    var last = new Date(today.getFullYear(), 11, 31);
    today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
    var diffInDays = (last.getTime() - today.getTime()) / (1000 * 3600 * 24);

    return range(1, diffInDays+1).map(function(x) {
       return new Date(today.getFullYear(), today.getMonth(), today.getDay()+x);
    }).filter(function(x){
       if(x.getDay() == 1) return true;
    });
}


texts:
I'm currently using a make shift INSERT on DUPLICATE UPDATE function that relies on a DB raw query from eloquent. I'm looking to improve the quality of the code and the speed. Please take a look

function bulkInsertBookTable($data)
{
    $inserts = [];
    foreach ($data as $item) {
        $inserts[] = implode(', ', ['"' . $item['book_id'] . '"', $item['isbn']]);
    }

    $inserts = Collection::make($inserts);

    $inserts->chunk(500)->each(function($ch) {
        $insertString = '';
        foreach ($ch as $element) {
            $insertString .= '(' . $element . '), ';
        }

        $insertString = rtrim($insertString, ", ");

        try {
            DB::insert("INSERT INTO book_datas (`book_id`, `isbn`) VALUES $insertString ON DUPLICATE KEY UPDATE `isbn`=VALUES(`isbn`)");
        } catch (\Exception $e) {
            print_r([$e->getMessage()]);
        }
    });
}

NOTE:

createOrUpdate function is only valid on model level and does not allow mass insert. Doing Model::insert() will allow to have a $data = [] inserted as long as fillable is used however it will reject if there is a duplicate key


texts:
I've been searching for methods to convert a bitarray into integer. Now I'm using this code:
def bin2int(bin_array):
    int_ = 0
    for bit in bin_array:
        int_ = (int_ << 1) | bit
    return int_

where bin_array is a bitarray randomly filled.
I'm curios about other methods that you know of, like functions from bitarray or numpy...


texts: Increase efficiency of card-ordering program

texts:
As mentioned in @rolfl comment. What this program does is that it "resequences the cards using a fixed system and count the number of times the resequencing happens before the output is the same as the input."

I was wondering how I could make this program faster or perhaps use less memory.  I thought about using dictionaries instead of lists as they have faster look ups. I'm not sure how to decrease the memory size of this program.

num_cards = input("Please enter the number of cards in the deck: ")

def num_of_round(num_cards):
    rounds = 0
    orig_order = range(1,num_cards + 1)
    card_list  = list(orig_order)
    table_list = []

    while 1:
        while len(card_list) > 0:
            table_list.append(card_list[0])     # STEP 1:   add top card to table
            card_list.remove(card_list[0])      #           remove top card from deck
            if len(card_list) == 0:
                break
            card_list.append(card_list[0])                  # STEP 2:   after removal of card, put top card on bottom of deck
            card_list.remove(card_list[0])                  #           update ordering of deck
        rounds += 1                                         # a round has passed
        table_list.reverse()
        card_list, table_list = table_list, card_list
        if card_list == orig_order:
            break
    print rounds

num_of_round(num_cards)


texts: Receive array of data and access employee info fields

texts:
This method receives an array of data and does some stuff in a database.  I need to get some reviews on it if possible.

public function doSomeStuff($arr = array())
{
    $id = $arr['Employee']['id'];
    $name = $arr['Employee']['name'];
    $status = $arr['Employee']['status'] == 'Disabled' ? 0 : 1;
    $user_id = $arr['Employee']['user_id'];
    $query = "update `mytable` set `status` = $status, `name`=$name   WHERE `user_id` = ?";
    self::_runthis($query, array($user_id));
}

I am looking to see if this is fool-proof for the data it will receive and will process it.


texts:
I made a game for children. This game tests the ability to count (i.e. compare numbers based on magnitude). First you must select the age of the child in the upper menu, then you need to select blocks with numbers in ascending order.

JSFIDDLE

document.addEventListener("DOMContentLoaded", ready);

let currNum;
let step;
let startContent = 'Это простейший тренажёр для детей, он проверяет способность считать. Предполагается, что: \

дети от 1 до 3 лет должны уметь считать до 5 \

дети от 4 до 5 лет должны уметь считать до 10 \

дети от 6 до 7 лет должны уметь считать до 30 \

дети от 7 до 9 лет должны уметь считать до 100 \

Чтобы проверить знания участнику предлагается последовательно в порядке возрастания выбрать кубики с цифрами \
';

function init() {
 currNum = -1;
 step = 0
 let startBtn = document.getElementById('start');
 startBtn.click();
};

function clearContent() {
 let contentInner = document.getElementById('contentInner');
 contentInner.innerHTML = '';
};

function deletePoint(id) {
 let pointEl = document.getElementById(id);
 pointEl.parentNode.removeChild(pointEl);
};

function createPoints(count) {
 let contentInner = document.getElementById('contentInner');

 for(let i = 0; i <= 2; i++) {
  let num_ = Math.random() * count;
  let num = Math.ceil(num_);

  let pointEl = document.createElement('div');
  pointEl.className = 'point';
  pointEl.id = 'point_' + i;
  pointEl.setAttribute('data-num', num);
  pointEl.innerHTML = num;

  contentInner.appendChild(pointEl);
 };
};

function ready() {
 let ulEl = document.getElementById('ul');
 let contentInnerEl = document.getElementById('contentInner');

 let menu = Rx.Observable.fromEvent(ulEl, 'click');
 let contentInner = Rx.Observable.fromEvent(contentInnerEl, 'click');

 let subscription = menu
 .map(e => e.target)
 .filter(t => t.className === 'start' || t.className === 'li')
 .subscribe(function (t) {
  clearContent();
    switch (t.className) {
      case 'start':
    document.getElementById('contentInner').innerHTML = startContent;
        break;
      case 'li':
    createPoints(t.getAttribute('data-count'));
        break;
    }
 });

 let subscription3 = contentInner
 .map(e => e.target)
 .filter(t => t.className === 'point')
 .subscribe(function (t) {
  let val = +document.getElementById(t.id).innerHTML;

  ++step;
  deletePoint(t.id);

  if(currNum > val) {
   alert('Not correct');
   init();
  } else {
   currNum = val;
   if(step > 2) {
    alert('Correct');
    init();
   }
  }
 });

 init();
};

1-3

4-5

6-7

7-9

start


texts: Occurrences (frequency count) - exercise 3 ch. 3 in "ansi common lisp"

texts:
Looking for hints on style and clarity re. below. While I'm not saying speed is irrelevant, it's less of a priority than style & avoiding bad habits at this point. Focus is on clean use of fundamentals of the language.

Summary of task:

  Take a list and return a list indicating the number of times each (eql)
    element appears, sorted from most common element to least common."

Example run with required output:

> (occurrences '(a b a d a c d c a))
((A . 4) (C . 2) (D . 2) (B . 1))

My solution:

(defun occurrences (lst)
  "Takes a list and returns a list indicating the number of times each (eql)
   element appears, sorted from most common element to least common."
  (occurrences2 lst (mapcar #'(lambda (x) (cons x 0))
                            (remove-dups lst))))

(defun occurrences2 (lst res)
  "Update res, an alist which already contains all needed entries with all
   values set to zero, with frequencies of occurrence as found in lst"
  (if (null lst)
      res ; todo: add a sort here on cdr of each element
      (occurrences2 (cdr lst)
                    (mapcar #'(lambda (x)
                            (if (eql (car x) (car lst))
                                (cons (car x) (+ (cdr x) 1))
                                x))
                         res))))

(defun remove-dups (lst)
  (if (null lst)
      nil
      (adjoin (car lst) (remove-dups (cdr lst)))))


texts: SQL query for adding column value to compare with other column

texts:
I have two tables

table_inventory
    List item
    inventory_rack_key(primarykey)
    node_key
    rack_id
    inventory_item_key
    in_coming_qty,locked_qty
    quantity

table_item
    inventory_item_key(primary key)
    item_id,product_zone

The table example are provided here DB TABLES
I need query to find out those items for which (net_qty) i.e difference b/w sum of in_coming_qty & quantity & locked_qty is negative. arranged by node_key,rack_id, item_id,net_qty

Note: each distinct set {node_key,rack_id, item_id,net_qty} will have only 1 row in output.
For ex :{node_key,rack_id, item_id} = {ABD101,RK-01,562879} has 4 rows in table_inventory
but in output net_qty= -78(single row) .

The query I made is giving me result but can we do it in some other way?

SELECT l.node_key,
       l.rack_id,
       i.item_id,
       ( SUM(l.quantity + l.in_coming_qty) - SUM(l.locked_qty) ) AS net_qty
FROM   table_inventory l,
       table_item i
WHERE  l.inventory_item_key = i.inventory_item_key
GROUP  BY l.node_key,
          l.rack_id,
          i.item_id
HAVING SUM(l.quantity + l.in_coming_qty) - SUM(l.locked_qty) < 0


texts:
Awhile ago I posted a Translator app that I have been in the process of making. I edited some features in it and I've decided to post it again.

My questions:

Is there anything I should add to this?
Is there any better (more easily readable) syntax for what I'm trying to do?
Say I wanted to make a GUI for this app. What language goes well with Ruby?

Here's the source code of the app:

require 'yaml'
require 'base64'
require 'digest'

def welcome_list
    puts """
    Welcome to Translation Center! Below you will find a list of available(so far) features, more feautures are being added as we speak! Have fun and enjoy!

    As of now Translation Center is able to translate from:

    1: Russian
    2: Spanish
    3: Arabic
    4: Pashto
    5: French

    Translation Center is also able to translate into:

    6: Base64
    7: Binary
    8: MD5

    Please choose from the list above by typing in the number in front of the language:
    """
    input = gets.chomp!
    case input.to_i
    when 1
        translate
    when 2
        translate
    when 3
        translate
    when 4
        translate
    when 5
        translate
    when 6
        base64
    when 7
        binary
    when 8
        md5
    else
        puts "Invalid input, redirecting..."
        return
    end
end

def translate
    translations = YAML.load_file 'words.yml'
    puts "Enter word or phrase to be translated to English, press 'Q' to quit:"
    input = gets.chomp
    if translations[input]
        puts "The translation of '#{input}' to English is: '#{translations[input]}'"
    elsif input =~ /q/i
        list
    else
        puts "Invalid word or phrase redirecting..."
        translate
    end
end

def binary
    puts "Enter your text you wanted translated to binary:"
    text = gets.chomp
    puts "#{text} in binary is: #{text.unpack('b*')}"
    binary if restart
end

def base64
    puts "Enter the text you want translated to Base64:"
    input = gets.chomp!.to_s
    new_string = "#{input}"
    puts "'#{input}' in Base64 is: #{Base64.encode64(new_string)}"
    base64 if restart
end

def md5
    puts "Enter text you want translated to MD5:"
    input = gets.chomp!.to_s
    input_string = Digest::MD5.new
    input_string.update(input)
    puts "'#{input}' translated to MD5: '#{input_string}'"
    md5 if restart
end

def restart
    puts "Would you like to [1]translate another, go back to the [2]main menu, or [3]quit?"
    input = gets.chomp!
     if input == "1"
        return true
    elsif input == "2"
        puts "Redirecting to Menu..."
        welcome_list
    else
        puts "Exiting system..."
        exit
    end
end
welcome_list

Sample words.yml file:

spanish:
a: to
abajo: down

arabic:
salam: Hi
ana min: I'm from...

russian:
А: A
В: V

french:
oui: Yes
non: No

pashto:
khe chare: Hello

japanese:
yaa: Hi
Yaa: Hi
Konbanw: Good evening


texts:
For a Django-Server I use several custom Error-Codes, error-titles and descriptions, possibly other fields might follow.
I'm using right now a basic global dictionary.
errordict = {'512':
    {
        'errorno': 512,
        'errordescr': "Database Down",
        'toDo': "Restart the database, Server: "+serveradr
    },
'513' : ....
}

And in the code something like:
def handleError(s_err):
   curerr=errordict[s_err]
   logging.error("Error "+s_err+" occurred: "+curerr['errordescr'])

The usage looks like this:
   try:
      findEntry(s_id)
   except NoSuchEntryEx as nsee:
      s_err="513"
      handleError(s_err)
      return HttpResponse(render_to_string('error.html', {
                'errorno':  s_err,
                'errordescr': mark_safe(str(nsee)
                                        + const.OUTPUT_NEWLINE),
                'toDo': errordict[s_err]['toDo']
            }))

I'm not happy with that and would rather define its own class - which would from the current perspective would just consist of this single, growing dict-object, which does not seem a great idea either.
It's of course a constant, every change there is hard-coded.


texts:
I have been following the FreeCodeCamp, and I am done with the basic algorithm challenges. The last one (CaesarsCipher) troubled me a bit, though I had done a similar one without much problem in C, for CS50 course.

Finally I made it work, but at the moment I am self-critical about "How?" I made it work and the quality of my code. I found the basic solution provided quite hard to understand and it looks way advanced than my code. I am posting my code here with the hope of receiving some feedback on it and finding out if am I doing something wrong/should be concerned about improving quality before moving on to new topics and challenges. (such as writing style or the functions i use/ the way I handle the problem)

function rot13(str) { // LBH QVQ VG!

  //defining an isAlpha function to skip the non alpha chars

  var isAlpha = function(char){
    return typeof char==="string" && char.length == 1 && char <= "Z" && char >="A";
   };

  //two empty arrays two use later

  var shifted = [];
  var decoded= [];

  /*transform the encoded chars to ascii numbers then shift by 13
  and copy the decoded char to another array
  */

  for(var i = 0; i < str.length; i++){

    if(isAlpha(str[i]) && str[i].charCodeAt() < 78) {

      shifted[i] = str[i].charCodeAt()+13;

      decoded.push(String.fromCharCode(shifted[i]));
    }

    else if(isAlpha(str[i]) && str[i].charCodeAt() >= 78){

      shifted[i] = str[i].charCodeAt() - 13;

      decoded.push(String.fromCharCode(shifted[i]));
    }

    else{

      decoded.push(str[i]);
    }
  }

  //lastly merge the decoded chars into a string

  var last = decoded.join("");

  return last;

}

// Change the inputs below to test
rot13("SERR PBQR PNZC");


texts:
I have a simple gallery that hides and shows images. It works fine, however, I am not satisfied with my approach, and my code seems redundant. Can you check my code and give a better idea on how I can improve it?

HTML

                <img src="<?= IMAGEPATH ?>front_page/phinfo/house_rentals/westgate/big_img_1.JPG" id="big_img_1" class="big_img">
                <img src="<?= IMAGEPATH ?>front_page/phinfo/house_rentals/westgate/big_img_2.JPG" id="big_img_2" class="big_img">
                <img src="<?= IMAGEPATH ?>front_page/phinfo/house_rentals/westgate/big_img_3.JPG" id="big_img_3" class="big_img">
                <img src="<?= IMAGEPATH ?>front_page/phinfo/house_rentals/westgate/big_img_4.JPG" id="big_img_4" class="big_img">
                <img src="<?= IMAGEPATH ?>front_page/phinfo/house_rentals/westgate/big_img_5.JPG" id="big_img_5" class="big_img">
                <img src="<?= IMAGEPATH ?>front_page/phinfo/house_rentals/westgate/big_img_6.JPG" id="big_img_6" class="big_img">

                <img src="<?= IMAGEPATH ?>front_page/phinfo/house_rentals/westgate/thumbnails/thumbs_img_1.jpg" id="thumbs_img_1" calss="thumbs_img">
                <img src="<?= IMAGEPATH ?>front_page/phinfo/house_rentals/westgate/thumbnails/thumbs_img_2.jpg" id="thumbs_img_2" calss="thumbs_img">
                <img src="<?= IMAGEPATH ?>front_page/phinfo/house_rentals/westgate/thumbnails/thumbs_img_3.jpg" id="thumbs_img_3" calss="thumbs_img">
                <img src="<?= IMAGEPATH ?>front_page/phinfo/house_rentals/westgate/thumbnails/thumbs_img_4.jpg" id="thumbs_img_4" calss="thumbs_img">
                <img src="<?= IMAGEPATH ?>front_page/phinfo/house_rentals/westgate/thumbnails/thumbs_img_5.jpg" id="thumbs_img_5" calss="thumbs_img">
                <img src="<?= IMAGEPATH ?>front_page/phinfo/house_rentals/westgate/thumbnails/thumbs_img_6.jpg" id="thumbs_img_6" calss="thumbs_img">

CSS

.big_img_wrapper, .big_img_wrapper img{
        width: 370px;
        height: 246px;
        /*display: none;*/
    }
    .thumbs_img_wrapper{
        padding:0;
    }
    .thumbs_img_wrapper img{
        width: 111px;
        height: 70px;
        margin: 14px 0 0 14px;
    }
    #thumbs_img_1, #thumbs_img_4{
        margin: 14px 0 0 0;
    }

jQuery

$(document).ready(function(){

    $('img.big_img').hide(); // Hides all big images
    $('img#big_img_1').fadeIn('slow'); // Serve as default image

    $('img#thumbs_img_1').click(function(){
        $('img.big_img').hide(); // Hides all big images
        $('img#big_img_1').fadeIn('slow'); //Slowly fades in selected image
    });

    $('img#thumbs_img_2').click(function(){
        $('img.big_img').hide(); // Hides all big images
        $('img#big_img_2').fadeIn('slow'); //Slowly fades in selected image
    });

    $('img#thumbs_img_3').click(function(){
        $('img.big_img').hide(); // Hides all big images
        $('img#big_img_3').fadeIn('slow'); //Slowly fades in selected image
    });
    $('img#thumbs_img_4').click(function(){
        $('img.big_img').hide(); // Hides all big images
        $('img#big_img_4').fadeIn('slow'); //Slowly fades in selected image
    });
    $('img#thumbs_img_5').click(function(){
        $('img.big_img').hide(); // Hides all big images
        $('img#big_img_5').fadeIn('slow'); //Slowly fades in selected image
    });
    $('img#thumbs_img_6').click(function(){
        $('img.big_img').hide(); // Hides all big images
        $('img#big_img_6').fadeIn('slow'); //Slowly fades in selected image
    });
});


texts: JavaScript function that flips brackets direction

texts:
I have these strings:
)hello(
this has ]some text[
flip }any{ brackets
even with )))]multiple[((( brackets

As you can see, the brackets are all in the wrong direction.
I have a function called flipBracketsDirection() to handle each scenario. Here is an example of input and output of the above strings:
flipBracketsDirection(')hello(');
// should return:  (hello)

flipBracketsDirection('this has ]some text[');
// should return:  this has [some text]

flipBracketsDirection('flip }any{ brackets');
// should return:  flip {any} brackets

flipBracketsDirection('even with )))]multiple[((( brackets');
// should return:  even with ((([multiple]))) brackets

Note: The direction is flipped at all times. So this is fine too:
flipBracketsDirection('flip (it) anyway');
// should return:  flip )it( anyway

Here is my solution.
function flipBracketsDirection(str: string) {
  return str
    // flip () brackets
    .replace(/\(/g, 'tempBracket').replace(/\)/g, '(').replace(/tempBracket/g, ')')

    // flip [] brackets
    .replace(/\[/g, 'tempBracket').replace(/\]/g, '[').replace(/tempBracket/g, ']')

    // flip {} brackets
    .replace(/\{/g, 'tempBracket').replace(/\}/g, '{').replace(/tempBracket/g, '}')
    ;
}

Is this the best way to create this function?


texts: Handle multiple menu click events in one Sub

texts:
I have multiple menus that will change languages in one Sub that will handle multiple events of the menus click, It is working for me right now, I'm just wondering if there is better way to do it... I'm using the menus name to call the process for each menus.

    Private Shared Sub CheckMenuItem(ByVal mnu As ToolStripMenuItem, ByVal checked_item As ToolStripMenuItem)

    For Each menu_item As ToolStripMenuItem In mnu.DropDownItems.OfType(Of ToolStripMenuItem)()
        menu_item.Checked = (menu_item Is checked_item)
    Next
End Sub

    Private Sub mnuEnglish_Click(sender As System.Object, e As EventArgs) _
    Handles mnuEnglish.Click, mnuFrench.Click, mnuDutch.Click, _
    mnuGerman.Click,mnuCroatian.Click, mnuCzech.Click, mnuHungarian.Click, _
    mnuIndonesian.Click, mnuItalian.Click, mnuPolish.Click, mnuSlovak.Click, _
    mnuSpanish.Click, mnuSwedish.Click, mnuTurkish.Click, mnuVietnamese.Click

    Dim item As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
    CheckMenuItem(mnuLanguage, item)

    Select Case item.Name
        Case "mnuEnglish"
            MsgBox("english")
        Case "mnuFrench"
            MsgBox("French")
        Case Else
            MsgBox("Other Languages")
    End Select
    End Sub


texts:
Is this algorithm good or can I improve it?

 static void QuickSort(int[] a)
    {
        QuickSort(a, 0, a.Length - 1);
    }

    static void QuickSort(int[] a, int start, int end)
    {
        if (start >= end)
        {
            return;
        }

        int num = a[start];

        int i = start, j = end;

        while (i < j)
        {
            while (i < j && a[j] > num)
            {
                j--;
            }

            a[i] = a[j];

            while (i < j && a[i] < num)
            {
                i++;
            }

            a[j] = a[i];
        }

        a[i] = num;
        QuickSort(a, start, i - 1);
        QuickSort(a, i + 1, end);
    }


texts: Sieve of Eratosthenes solution for CodeEval

texts:
The code below takes integer n as input, and delivers a list of all primes up to integer n using the Sieve of Eratosthenes.

My question is, could you please help me optimize this code? Is it considered poor code to use 'try' flow control? I'd like to optimize the code such that I don't need it.

def factorfinder(n):
    A = range(0,n+1)
    for i in xrange(0,int(math.sqrt(n))):
        if i == 0 or i == 1:
            A[i] = 0
            continue
        for j in xrange(0,n):
            try:
                A[i**2+j*i] = 0
            except IndexError:
                pass
    return filter(lambda x: x != 0, A)


texts:
What I mean by displacing an enumerable is skipping the first n items, then returning the next n items, then returning the first n items, then returning the rest of the enumerable.

What do you think?  Does this idea have any value?

using System.Collections.Generic;

public class EnumerableDisplacer
{
    public virtual IEnumerable<T> Displace<T>(IEnumerable<T> source, int displaceCount)
    {
        var enumerator = source.GetEnumerator();
        var counter = 0;
        var displacedItems = new LinkedList<T>();
        while (counter < displaceCount)
        {
            enumerator.MoveNext();
            ++counter;

            displacedItems.AddLast(enumerator.Current);
        }

        counter = 0;
        while (counter < displaceCount)
        {
            enumerator.MoveNext();
            ++counter;

            yield return enumerator.Current;
        }

        foreach (var di in displacedItems)
        {
            yield return di;
        }

        while (enumerator.MoveNext())
        {
            yield return enumerator.Current;
        }
    }
}


texts:
I'm trying to learn Clojure recently and I thought writing a simple web app would be a good way to dive in.

This function gets the list of alive threads from the API and reduces, filters and maps until I'm left with a list of image names (which I can append to "http://i.4cdn.org/wg/" to get the URL's.).

This is the first time I'm using defer/@ so I'm not that sure if I used them correctly.

Here is the code:

(defn scrape []
  (let
    [{:keys [status hey body error] :as resp}
      @(http/get "http://a.4cdn.org/wg/threads.json")]
    (->>
      (json/read-str (resp :body))
      (map #(%1 "threads"))
      (reduce concat [])
      (map #(%1 "no"))
      (map #(str "http://a.4cdn.org/wg/thread/" %1 ".json"))
      (map http/get)
      (map deref)
      (map #(%1 :body))
      (map json/read-str)
      (map #(%1 "posts"))
      (reduce concat [])
      (filter #(not (nil? (%1 "tim"))))
      (map #(str (%1 "tim") (%1 "ext")))
      (print))))


texts:
I was doing this particular problem AIBOHP and used a dp approach based on checking the ends of a substring of length i starting from 1. Although my time complexity is fine at O(n^2) but space is taking too much because of which I am getting RTE if I am declaring it dynamically or TLE if I am declaring it as global static which needs to be reduced because the dp size can be 6100*6100 . Any suggestions how to optimize my below code for this purpose .

The problem statement is:

  He now asks the doctors to insert the minimum number of characters
  needed to make S a  palindrome. Help the doctors accomplish this task.

  For instance, if S = "fft", the doctors should change the string to
  "tfft", adding only 1 character.

My code:

static int dp[6101][6101];
main()
{
    int tc;
    scanf("%d",&tc);
    while(tc--)
    {
        char s[6102];
        scanf("%s",s);
        int len=strlen(s);
        memset(dp,0,sizeof dp);
        for(int i=1;i<len;i++)
            for(int j=0,k=i;k<len;k++,j++)
                dp[j][k]=(s[j]==s[k])?dp[j+1][k-1]:min(dp[j][k-1],dp[j+1][k])+1;
        printf("%d\n",dp[0][len-1]);
    }
    return 0;
}


texts: Optimization of a "Sieve of Eratosthenes" in Java

texts:
I have created a simple Pseudo "Sieve of Eratosthenes," for a class in Java. I am looking for the most optimized option, or at least an option that is more optimized than current. If there is any other advice that you have to offer, I would be more than happy to hear that as well.

import java.util.*;

public class SieveOfErantosthenes {

    public static void main(String[] args) {
        int testerIndex = 0, numbersOnLine = 0;
        Vector<Integer> primes = new Vector<Integer>(1, 1);
        for (int i = 0; i < 1000; i++) {
            primes.add(i + 1);
        }
        primes.remove(0);
        while ((primes.get(testerIndex)) < 500) {
            for (int i = testerIndex + 1; i < 999; i++) {
                if (primes.get(i) % primes.get(testerIndex) == 0
                        && primes.get(i) != 0) {
                    primes.set(i, 0);
                }

            }
            do {
                testerIndex++;
            } while (primes.get(testerIndex) == 0);
        }
        while (primes.contains(0)) {
            primes.remove((Integer) 0);
        }
        testerIndex = 0;
        while(testerIndex < primes.size()){
            for(; numbersOnLine < 15 && testerIndex < primes.size(); testerIndex++, numbersOnLine++){
                System.out.print(primes.get(testerIndex) + "\t");
            }
            System.out.println();
            numbersOnLine = 0;
        }
    }

}


texts: Web Security with Authentication Key in Query String

texts:
What is the best way to authenticate using a key in a query string?

I have a web service that clients can consume if they provide a authentication key in the query string.  I also have a web front-end that consumes the web service as well.  I do not want to embed the authentication key in javascript where someone can actually see what the key is. My solution was to have my web client NOT provide the key and the server side code check to see if the request.header referrer is localhost (it resides on the same server) and if it is, don't require an auth key.

Are there issues with this?  Can someone modify the referrer in a request header?  Here is my server side code.  I am using CherryPy:

HOSTNAME_LOCAL = { "", "acme.com", "localhost" }

def _get_hostname(self):
    if "Referer" in cherrypy.request.headers:
        referer = cherrypy.request.headers["Referer"]

    if referer == None:
        hostname = ""
    else:
        ext = tldextract.extract(referer)
        if ext.suffix == "":
            hostname = ext.domain
        else:
            hostname = ext.domain + "." + ext.suffix
        return hostname
    raise ValueError("Error: referer in request.headers is None")

def authenticate(self, key=None):
    if key is None:
        hostname = self._get_hostname()
        if hostname in HOSTNAME_LOCAL:
            return True, "Authorization Key Not Required."

    return False, "Authorization Denied. Authorization Key Required."
secure, msg = self.data.authenticate(key)
return secure, msg


texts: Custom dictionary class for reading and writing json value to a file

texts:
Is my implementation good? The program works as planned, but I wonder if some parts of the code can be made cleaner or more efficient. The file output looks like this:

{
  "TestValue": {
    "Key": "Cat",
    "Description": "dog"
  },
  "testValue2": {
    "Key": "Cat2",
    "Description": "dog2"
  }
}

Here is the class that produces that output:

namespace review
{
 public class FileValue : Dictionary<string, TableValue>
    {

        private string path = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\Data\Values.json"));

        public void Add(string key, string data, string description)
        {
            TableValue value;
            value.data = data;
            value.description = description;
            Add(key, value);
        }

        /// <summary>
        /// This will create the file if it doesn’t exist, then add three values, the key, the data and description from a dictionary. If the file exist the values will be added properly for json formatting.
        /// </summary>
        public void WriteToFile()
        {
            if (!File.Exists(path))
            {
                string json = JsonConvert.SerializeObject(this, Formatting.Indented);
                File.AppendAllText(path, json);
            }

            else
            {
                string json = JsonConvert.SerializeObject(this, Formatting.Indented);
                json.Remove(json.Length - 1); // Remove the last } to add new data
                File.AppendAllText(path, Environment.NewLine + "," + json);
            }
        }

        /// <summary>
        /// This will read from a file and parse the data into a object
        /// </summary>
        /// <returns></returns>
        public FileValue ReadFromFile()
        {
            using (StreamReader file = File.OpenText(path))
            {
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    JObject jsonObj = (JObject)JToken.ReadFrom(reader);
                    FileValue dict = JsonConvert.DeserializeObject<FileValue>(jsonObj.ToString());
                    return dict;
                }
            }
        }
    }

    public struct TableValue
    {
        public string data;
        public string description;
    }
}


texts: Using pandas.io.pytables.TableIterator for several iterations

texts:
I'm writing method that takes a pandas iterator and then computes something based on that. The problem is that some of these computations require iterating twice over the data.

For example the normalized variance needs to first iterate over the data to compute the mean, and then iterate again to compute the (normalized) variance with that. I want to have the iterator as input because otherwise I'd need to compute the select() within the method which is quite some overhead I don't want to deal with.

However, I cannot reset tableIterator: it does not support seek(0). Therefore, I'm running with a generator right now. Here's how it looks:

def computeIterativeMean(iterator):
    # computes the mean given an iterator
    n, mean = 0, 0
    for chunk in iterator:
        nCurrent = len(chunk)
        meanCurrent = chunk.mean()
        mean = (n * mean + nCurrent * meanCurrent)/(n + nCurrent)
        n += nCurrent
    return mean

def computeIterativeMoment(iteratorGenerator, n=2):
    # computes some moment given iterator generator
    mean = computeIterativeMean(iteratorGenerator())

    iterator = iteratorGenerator()
    i, moment = 0, 0
    for chunk in iterator:
        iCurrent = len(chunk)
        momentCurrent = ((chunk - mean)**n).mean()
        moment = (i * moment + iCurrent * momentCurrent)/(i + iCurrent)
        i += iCurrent
    return moment

And the code is called from outside as

    movementsIteratorGenerator = lambda: store.select(
        'movements',
        where=where,
        columns=myCols,
        iterator=True,
        chunksize=chunksize
    )

    mean = computeIterativeMean(movementsIteratorGenerator())
    variance = computeIterativeMoment(movementsIteratorGenerator, n=2)


texts: Convert HTML input string to JavaScript Array literal

texts:
I am trying to accept JavaScript array literals in an HTML text input.

The problem is that HTML text inputs are captured as strings,  such that an input of ['name', 'who', 1] becomes "['name', 'who', 1]".

My intention is for the following samples to yield the corresponding outputs.

"['river',"spring"]"        //  ["river","spring"]

"[{key:'value'},20,'who']"  //  [{"key":"value"},20,"who"]

The way I worked around   the problem is by using  eval  in the code snippet below:

const form = document.querySelector('.form');
    const inputField = document.querySelector('.input');
    const btnParse= document.querySelector('.btn');
    const out = document.querySelector('.out');

    form.addEventListener('submit', (e)=> {
      e.preventDefault();

      try {
        parsed = eval(inputField.value);

        if(Array.isArray(parsed)) {
          out.textContent = JSON.stringify(parsed);
        } else throw new Error('input is  not a valid array' );
      } catch(err) {
        out.textContent = `Invalid input: ${err.message}`;
      }
    });
 <form class="form">
      <fieldset>
        <legend>Enter array to parse</legend>
        <input class="input" type="text">
        <input class="btn" type="submit" value="parse">
      </fieldset>
    </form>
    <div>
      <p class="out">
      </p>
    </div>

My solution, however, allows for the execution of any Javascript code inputted into the text field, which is a huge vulnerability.

 What alternative way is there to converting JavaScript array literal HTML text inputs into JS array objects without using eval?


texts:
Problem

I am loading things from the localStorage and this has to be saved as json, so it needs to have a simple Object structure to be possible to JSON.parse().

However, som methods do not accept <any> as parameter, because they want a concrete class or interface, but i want to send my object as parameter, so i have to convert it to a Map in order to have the same structure, but seen as it has a type, it is now accepted as parameter.

My problem lies within the conversion from Object to Map

Solution

public static convertObjectToMap<V>(obj: any, classOfV): Map<string, V> {
    let objectMap = new Map<string, V>();
    if (obj !== undefined && obj !== null) {
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          const initObject = new classOfV(obj[key]);
          objectMap.set(key, initObject);
        }
      }
    }
    return objectMap;
  }

I take an obj and the class which all values are going to be in the same type.

Example of usage

//This is purely for the example
const fibonacciObject:any = {"0": 1, "1": 1, "2": 2, "3": 3, "4": 5};

const fibonacciMap:Map<string, Number> = convertObjectToMap<Number>(fibonacciObject, Number);

fibonacciMap.get("0"); //1
fibonacciMap.get("4"); //5

Question

Is there a better way to do this conversion, i know about new () => V, but since i need it for each key, then it is not really feasible.

Also what Type would class of V be, i keep getting type errors when i try to give it a Type


texts: Simple JS OOP - Clicking the box to fetch and display object content

texts:
I'm relatively new to OOP with JS and want to find out:

If my code can be improved somehow, and
key question Identify how and where I can typically use OOP more in my job (as I can usually just use arrays and don't need objects)

I have built a basic demo that just stores some animal data as objects and displays them when clicking on the boxes.

Can anyone briefly review the code and spot any improvements? And more importantly, what are typical tasks that objects are better for rather than just using arrays? I'm a front-end developer and typically use arrays for tasks like storing html data and changing content with click events, hovers and other event listeners, and have never had to use objects although want to.

Thanks for any advice here. My code and CodePen URL are below:

let animals = document.querySelectorAll('.animal'),
    animalsObj = [],
    mainTitle = document.querySelector('#title'),
    mainDescription = document.querySelector('#desc');

class Animal {
  // constructor
  constructor (name, description) {
   this.name = name;
   this.description = description;
      animalsObj.push(this);
  }
}

for (let i = 0; i < animals.length; i++) {
  let name = animals[i].querySelector('.name').textContent,
      description = animals[i].querySelector('.description').textContent;

  // instantiate object
  new Animal(name, description);

  animals[i].addEventListener("click", () => {
    console.log('clicked on ' + animalsObj[i].name);
    mainTitle.textContent = animalsObj[i].name;
    mainDescription.textContent = animalsObj[i].description;
 });
}
.animals {
  display: flex;
}
.animal {
  border: 1px dashed grey;
  padding: 1em;
}
.animal:nth-of-type(odd) { background: #f0f0f0 }
.animal:nth-of-type(even) { background: #ccc }

Lion

A big cat.

Stoat

A weasel thing.

Chicken

Good to eat.

Animal

Description

Codepen: https://codepen.io/ns91/pen/qBWLYLp


texts: Shortening and optimizing diamond-printing code

texts:
I'm working through a Java textbook by Paul and Harvey Deitel and I have come across a review question (Chapter 2 - Intro to Java, Exercise 2.18 for those that have the book) which asks the user to create the following diamond:

    *
   * *
  *   *
 *     *
*       *
 *     *
  *   *
   * *
    *

I have the following code which does this but, as always, I can't help but think there's a better way to do this. Any suggestions on a shorter way?

// Prints the start and end of the diamond
private static void printStartEnd(int numLines, char sign, char filler) {
    int xPosition = numLines / 2;

    // Loop through
    for (int i = 0; i < numLines; i++) {
        if (i == xPosition) {
            System.out.print(sign);
        } else {
            System.out.print(filler);
        }
    }
}

// Prints the other lines
private static void printOtherLines(int numLines, int positionOne,
        int positionTwo, char sign, char fill) {
    int i = 0;

    // Loop through
    while (i < numLines) {
        if (i == positionOne || i == positionTwo) {
            System.out.print(sign);
        } else {
            System.out.print(fill);
        }
        i++;
    }
}

// Draw the diamond to the console
public static void drawDiamond( int numLines, char sign, char fill )
{
    // Diamonds can only be created for odd numbers
    if( numLines % 2 != 0 )
    {
        boolean limitReached = false;

        int halfWayPointMinus = numLines / 2 - 1;
        int halfWayPointPlus = numLines / 2 + 1;

        for( int i = 0; i < numLines; i++ )
        {
            if( i == 0 || i == numLines-1 )
            {
                printStartEnd( numLines, sign, fill );
            }
            else
            {
                printOtherLines( numLines,halfWayPointMinus,halfWayPointPlus,sign,fill );
                if( halfWayPointMinus == 0 || limitReached )
                {
                    limitReached = true;

                    // Invert values and move back in
                    halfWayPointMinus++;
                    halfWayPointPlus--;
                }
                else
                {
                    halfWayPointMinus--;
                    halfWayPointPlus++;
                }

            }
            // Move to next line
            System.out.println();
        }
    } else
    {
        System.out.println( "Sorry, the number of lines entered must be an odd number..." );
    }
}


texts:
My friend and I were doing an Eratosthenes Sieve implementation, it works, but I think there is a mistake with "n" and with the first for condition ("i<=n"). I think that condition can cause a segmentation fault as there's no criba[n], am I right? Any suggestion to make it faster?

#include <bits/stdc++.h>

using namespace std;

const long long int n=1000000;
bool criba[n+1];

void gencriba(){
    memset(criba,true,sizeof(criba));
    criba[0]=criba[1]=false;
    for(long long int i=2;i<=n;++i){ ///Aquí es donde usa <=
        if(criba[i]){
            for(long long int j=i;j<=n/i;++j){
                criba[j*i]=false;
            }
        }
    }
}

int main()
{
    gencriba();
    int c;
    cin>>c;
    cout<<criba[c]<<endl;
    return 0;
}

Edit: Decided to change the array size to n+1, so that there's no possibility of getting an error because of invalid memory address


texts: Simplifying a LINQ expression that finds the largest date smaller than another date

texts:
I have a LINQ 2 SQL query that needs to run a subquery in the where clause. The subquery just returns the largest date (from a date column) that is less than or equal to another date (an input to the function).

I originally had it like this (not this in the where clause of an outer query):

skew.CalibrationDate.Date == (from skew2 in db.Skew
                              where skew2.CalibrationDate.Date <= date.Date
                              select skew2.CalibrationDate).Max()

And then simplified it to:

skew.CalibrationDate.Date == db.Skew.Select(s => s.CalibrationDate.Date)
                                    .Where(s => s <= date.Date)
                                    .Max()

(note that the db.Skew table/object has multiple columns/properties but I'm only interested in the CalibrationDate for this clause and also that date is an input to the function that this is in, a regular DateTime variable).

Is it necessary for me to have all three of the Select(), Where() and Max() calls or is there some redundancy here? Could I put a lambda expression in the Max() call to get rid of one of the others?


texts:
I've written this snippet to extract a review request status from review-board in python. It works well but i'm very new to python and i would like to know if i could write this any better.
Should i put conn.close in it's own try statement ?

This script is supposed to run as part of a post-commit hook in mercurial.
If the review-board server is not responding i still want to be able to commit without any issues. If the commit is non existent then an empty string is ok.

import httplib
import json

def getReviewStatus(reviewboardUrl, id):
    try:
        conn = httplib.HTTPConnection(reviewboardUrl, 80)
        headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/json; charset=UTF-8'
        }
        conn.request("GET", "/api/review-requests/%s/" % id, headers=headers)
        return json.loads(conn.getresponse().read())['review_request']['status']
    except:
        return ""
    finally:
        conn.close()


texts: Efficient JavaScript/jQuery typewriter effect that handles HTML5, entities, and text

texts:
How should this code be improved? For instance:

How could it be shorter, clearer, deal with memory better, use a plugin/library, better prepared for web input?
I can break up and clarify the regex or jump calculation, but what is the simplest way?
Why don't I see setTimeout cleared in if blocks more or default return values in || inline? Am I dealing with the (potential) values properly?
Are there any other typewriter snippets or plugins accessible online that function with HTML5 rules and entities in a clearer way or is there a reason this is not often mentioned?

Description:

A typewriter effect outputs human readable characters one by one simulating actual typewriters. To ouput valid HTML5, entities, and text, sometimes we have to first output more than one character (like an entity or tag), and then output the rest of the tags in the block so that the A) outputted HTML snippet is not misread (according to its original state when output into the DOM), and B) so that the HTML in the snippet does not get read by the browser as part of any existing HTML on the page (in the DOM beneath the inserted snippet).

Usage:

customizeSnippet('homepage');

Input:

A paragraph in an html5 snippet with no end tag &amp; some text and entities.&#8482;
W3:paragraph

Output, base state:

//2013-03-18
//Output HTML snippet - A char one by one, and a tag or an entity all at once
//Output all upcoming tags to preserve DOM integrity
//Recurse
var showSnippet = (function (target, snippet, snippetL, i, interval) {
    var timeOut = 0,vis = '',tags = '',jump = [];
    if (i < snippetL) {
        if (snippet[i] === '<' || snippet[i] === '&') {
            jump = snippet.substring(i).match(/^<[^>]+>|^&#?[A-Za-z0-9]+(?:;|\s|$|\v|\f|(<))/m);
            i = i + (jump[0] || '1').length - 1 - (jump[1] || '').length;
        }
        vis = snippet.substring(0, i + 1) || '';
        tags = ((snippet.substring(i + 1).match(/(<[^>]+>)/img) || []).join('')) || '';
        $(target).html(vis + tags);
        ++i;
        timeOut = window.setTimeout(function () {
            showSnippet(target, snippet, snippetL, i, interval);
        }, interval);
    } else {
        clearTimeout(timeOut);
    }
});

//Get the widget html #pagenameSnippet and call showSnippet
//with the hardcoded div #showSnippet for output
var customizeSnippet = (function(page) {
    var snippet = '', snippetL = 0;
    snippet = $('div.'+page+'Snippet').html() || '';
    snippetL = snippet.length;
    if (snippetL > 0){
        window.setTimeout(function(){
          showSnippet("#showSnippet", snippet, snippetL, 0, 100);
        }, 100);
    }
});


texts:
For CS class, I had to reverse the digits of an integer from the input. This is my solution:

System.out.println(new StringBuilder(new Integer(new Scanner(System.in).nextInt()).toString()).reverse().toString());

My main question is this: is this too golfed?

Obviously I could simply add whitespace and comments, but is this level of directness practical?

Also, is there a better way to do this? Perhaps something like the following:

final String string = new Integer(new Scanner(System.in).nextInt()).toString();
for (int i = string.length(); i != -1; System.out.print((i-- != 0) ? string.charAt(i) : "\n"));


texts:
I think I put too much code in my controller that was supposed to go in the model.

This is a part of my controller, I'm not gonna paste everything since there is a lot of code.

  public function ajaxUsers() {
    if($_GET["action"] == "listUsers") {

        if(!isset($_POST["search"])) {
            $this->_data['Records'] = $this->_model->getUsers();
            $this->_data['Result'] = "OK";
            $this->_data['TotalRecordCount'] = $this->_model->countUsers();
        }
        else {
            foreach($_POST['fields'][0] as $key => $post) {
                if ($post != "" && $key != "reg_date") {
                    $searchTerms = explode(' ', $post);
                    foreach ($searchTerms as $term) {
                        $term = trim($term);
                        if (!empty($term)) {
                            $like[] = $key." LIKE '%".trim($term, '\'')."%'";
                        }
                    }

                }
                else if ($post != "" && $key == "reg_date") {
                    foreach ($post[0] as $key2 => $date) {
                        $datetofrom = strtotime($date);
                        $datetofrom = date('Y-m-d', $datetofrom);
                        if ($date != "" && $key2 == "datefrom") {
                            $like[] = "DATE_FORMAT(".$key.", '%Y-%m-%d') >= '".$datetofrom."'";

                        }
                        if ($date != "" && $key2 == "dateto") {
                            $like[] = "DATE_FORMAT(".$key.", '%Y-%m-%d') <= '".$datetofrom."'";
                        }
                    }
                }
            }

            ($like) ? $where_clause = "WHERE ". implode(' AND ', $like) : $where_clause = "";
            $this->_data['Records'] = $this->_model->filterUsers($where_clause);
            $this->_data['Result'] = "OK";
            $this->_data['TotalRecordCount'] = $this->_model->countfilterUsers($where_clause);
        }
        echo json_encode ($this->_data);
    }
}

And my model is mostly database queries:

  public function getUsers() {
    $data = $this->_db->select("SELECT * FROM ".PREFIX."users" . $this->_sort);
    return $data;
}

public function countUsers() {
    $data = $this->_db->select("SELECT count(*) as id FROM ".PREFIX."users");
    return $data[0]->id;
}

public function filterUsers($like_clause) {
    $data = $this->_db->select("SELECT * FROM ".PREFIX."users " .$like_clause. $this->_sort);
    return $data;
}
public function countFilterUsers($like_clause) {
    $data = $this->_db->select("SELECT count(*) as id FROM ".PREFIX."users ".$like_clause);
    return $data[0]->id;
}

Should I moved the foreach loops in the model?


texts: Data validation for to check required fields are mapped

texts:
Can I break the below foreach and IF statements into  LINQ expression. Also, performance wise which will be better. Please suggest.

foreach (var fieldMappingOption in collectionHelper.FieldMappingOptions
        .Where(fmo => fmo.IsRequired && !fmo.IsCalculated
         && !fmo.FieldDefinition.Equals( MMPConstants.FieldDefinitions.FieldValue)
         && (implicitParents || anyParentMappings
             || fmo.ContainerType == collectionHelper.SelectedOption.ContainerType)))
    {
        if (!collectionHelper.FieldMappingHelpers
                .Any(fmh => fmh.SelectedOption.Equals(fieldMappingOption)))
        {
            requiredMissing = true;
            var message = String.Format(
               "The MMP column {0} is required and therefore must be mapped to a {1} column.",
               fieldMappingOption.Label, session.ImportSource.CollectionLabel);
            session.ErrorMessages.Add(message);
        }
    }


texts:
An easy, terribly written but working, Caeasar (Monoalphabetic) cipher implementation, with a GUI (Graphical User Interface).

Cipher.java

class Cipher {

    static final String alphabet = "abcdefghijklmnopqrstuvwxyz";

    public static char shift(char ch, int amount) {
        return alphabet.charAt((alphabet.indexOf(ch) + amount) % alphabet.length());
    }

    public static String caesarCipher(String text, int amount) {
        String result = "";
        for (char ch : text.toCharArray()) {
            if (alphabet.indexOf(ch) >= 0) {
                result += shift(ch, amount);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        assert shift('a', 1) == 'b';
        assert shift('z', 2) == 'b';
        assert caesarCipher("abc", 2).equals("cde");
    }
}

Gui.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Gui {

    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("HelloWorldSwing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel body = new JPanel();

        final JTextField label = new JTextField("aaaaaaaaaaaaaaaaaaaaaaa");
        body.add(label);

        final JTextField key = new JTextField("1");
        body.add(key);

        final JTextField result = new JTextField("bbbbbbbbbbbbbbbbbbbbbb");

        JButton activationButton = new JButton("Encrypt");
        activationButton.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent ae)
            {
                String plainText = label.getText();
                String keyval = key.getText();
                result.setText(Cipher.caesarCipher(plainText, Integer.parseInt(keyval)));
            }
        });

        body.add(activationButton);

        body.add(result);

        frame.add(body);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}


texts: Animation of multiple text elements in sequence

texts:
I feel like this isn't the most effective nor efficient way of doing things:

line.stop(true, true).show('slide', {direction: whichway}, speed-150, function() {
  title.stop(true, true).fadeIn(speed-200, function() {
    sub.stop(true, true).show('slide', {direction: whichway}, speed-50, function() {
      subtext.stop(true, true).show();
      paragraph.stop(true, true).slideDown(speed);
    });
  });
});

whichway/speed are dynamic, but other than that it's all stuff that has to be in sync and queued up.

Is there a more efficient way of doing this?


texts: Parsing a string with regex to build JSON

texts:
I'm pretty sure the code is of mild quality but not entirely sure as I'm not much of a JavaScript programmer. Everything works as expected. A quick rundown of the code. It simply parses a string and builds some game data for saving into a database. One thing I'm not sure of is how I should handle data that doesn't conform to how it's expected.

// var diplo = `!report Game Type: Diplo Early Bird
// 1: <@12321321421412421>
// 2: <@23423052352342334>
// 3: <@45346346345343453>
// 4: <@23423423423523523>`

var diplo = `!report Game Type: Team Modded
Team: 1
    <@23452342359234534>
    <@34642342359232352>
Team: 2
    <@34534342359234879>
    <@58493457202345054>`

var report = {};

function gameType(game) {
    let data = {};
    let game_types = [{id: 1, name: 'Diplo'}, {id: 2, name: 'Always War'}, {id: 3, name: 'FFA'}
        , {id: 4, name: 'No Diplo'}, {id: 5, name: 'Team'}, {id: 6, name: 'Duel'}, {id: 7, name: 'No War'}];
    let o = {}
    let reType = /!report Game Type:[\s+]?(\d|\w+)\s?(\w+\s?(\w+)?)?\n/gi
    let match = reType.exec(game)
    if(match[1]){
        for (var j = 0; j < game_types.length; j++) {
            if ((game_types[j].name).toLowerCase() === (match[1]).toLowerCase()) {
                data.type = game_types[j].id;
                break;
            }
        }
    }
    if(match[2]){
        data.moddifier = match[2]
    }
    diplo = game.slice(reType.lastIndex);
    return (data)
}

function getPlayers(game) {
    let players = [];
    rePlayer = /(\d+):\s?<@(\d+)>[\s\S]?(\w+\s?\w+)?/gi;
        do {
            let o = {};
            player = rePlayer.exec(game);
            if (player) {
                o.position = player[1]
                o.discord_id = player[2]
                players.push(o);
            }
        } while (player);
        return players;
}

function getTeamPlayers(game) {
    let players = [];
    reTeam = /Team:\s(\d)[\s\S](\s+?<@(\d+)>)+/gi;
    rePlayer = /\s+?<@(\d+)>/gi;
    let i = 1;
    do {
        team = reTeam.exec(game);
        if(team){
            do {
                player = rePlayer.exec(team[0]);
                if(player){
                    let o = {};
                    o.team_id = i;
                    o.position = team[1];
                    o.discord_id = player[1];
                    players.push(o);
                }
            }while(player)
        }
        i++;
    }while(team)
    return players;
}

function main() {

    console.log("Reading game data...")
    try {
        report = gameType(diplo)
        if(report.type === 5){
            report.players = getTeamPlayers(diplo);
        }else{
            report.players = getPlayers(diplo);
        }
        console.log(report)
    } catch (err) {
        return 'Error Processing Report!';
    }
}

main();


texts: method to decide if two strings are anagrams

texts:
I'm studying with the Cracking the Code Interview book. I'm just looking for some feedback on this method:

C++

bool areAnagrams(const char*s1, const char*s2){
    unordered_map <char,int> m1,m2;

    for(size_t i = 0; i < strlen(s1); i++){
        m1[s1[i]] += 1;
    }
    for(size_t j = 0; j < strlen(s2); j++){
        m2[s2[j]] += 1;
    }
    for(auto i = m1.begin(); i != m1.end(); i++){
        if(m2[(*i).first] != (*i).second)
            return false;
    }
    return true;
}


texts: Download image links posted to reddit.com

texts:
This is a Python script to save imgur pictures posted to reddit.com forums. I'm looking for an assessment on the design of this script and any web security issues that might exist.

Obvious shortcomings: it only downloads image links http://i.imgur.com/xx.png not images from imgur pages http://imgur.com/page/ and lacks the ability to get image albums.

# purpose:   downloads images from imgur.com links posted to specified reddits
# platform:  python 3.2
# references:
#  - reddit JSON -- https://github.com/reddit/reddit/wiki/API:-info.json

import json
import urllib.request
import os, sys

def downloadPostsFrom(subreddit):
    "Returns reddit posts as JSON"
    try:
        f = urllib.request.urlopen("http://www.reddit.com/r/"+subreddit+"/.json");
        return json.loads(f.read().decode("utf-8"))["data"]["children"]
    except Exception:
        print("ERROR: malformed JSON response from reddit.com")
        raise ValueError

def parseImageURL_From(posts):
    "Returns tuple iterator (url, title)"
    for node in posts:
        post = node['data']
        # only accept links from imgur.com
        if post['domain'].endswith('imgur.com'):
            yield post["url"], post["title"]

def makeFileExt(content_type):
    "Return extension for specified content type"
    return {
        'image/bmp':'bmp',
        'image/gif':'gif',
        'image/jpeg':'jpg',
        'image/png':'png',
        'image/tiff':'tif',
        'image/x-icon':'ico'
        }.get(content_type, 'txt')

def makeFileName(title):
    "Compute valid file name from image title. Return file name or default.ext"
    title = title.strip(' .?:')
    file_name = title.translate(''.maketrans('\/:*?"<>|$@ ï»¿.','__.-_____S0___'))
    file_name = file_name.strip('_').replace('__','_').lower()
    return file_name + '.' if file_name else 'default.'

def makeSaveDir(save_dir):
    "Creates directory. Returns a valid directory name."
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    return save_dir + '/'

def downloadImagesIntoDir(save_dir, image_refs):
    "Download image files into specified directory."
    save_dir = makeSaveDir(save_dir)
    print('saving to:', save_dir)

    for url, title in image_refs:
        try:
            # open connection to image
            request = urllib.request.urlopen(url)
            if request.code == 200:
                content_type = request.headers.get_content_type()
                # filter in images
                if 'image' == content_type.split('/')[0]:
                    file_name = save_dir \
                            + makeFileName(title) + makeFileExt(content_type)
                    # download image to local file
                    print('  downloading:', title)
                    with open(file_name, "wb") as image_file:
                        image_file.write(request.read())
        except Exception:
            print("ERROR: bad request --", title)

def downloadRedditImages(subreddits):
    "Download imgur images from reddit. Returns None."
    for subreddit in subreddits:
        try:
            # reddit_posts: JSON
            reddit_posts = downloadPostsFrom(subreddit)
            image_urls = parseImageURL_From(reddit_posts)
            downloadImagesIntoDir(subreddit, image_urls)
        except Exception:
            pass

def main():
    "Use app as console program."
    if len(sys.argv) > 1:
        downloadRedditImages(sys.argv[1:]);
    else:
        # specify your default reddits here
        downloadRedditImages(['funny']);

if __name__ == '__main__':
    main()


texts: Convert total minutes into "Hours:minute:seconds" for marathon data

texts:
The point of the script below is to read in the 10th column which is the total number of minutes a runner took to finish the marathon and convert it into form of "hours:minutes:seconds".  Is there a better way?

require 'csv'

File.open('bostonmarathon-2012-results.txt', 'w') {  |f|
  skip = true
  CSV.foreach("bostonmarathon-2012-results.csv") do |row|
    if skip
      skip = false
    else
      total_seconds = row[10].to_f * 60
      seconds = total_seconds % 60
      minutes = (total_seconds / 60) % 60
      hours = total_seconds / (60 * 60)

      f.puts(format("%02d:%02d:%02d", hours, minutes, seconds))
    end
  end
}

Time starts as in total minutes in decimal format: 142.93

Example Data:

division,name,city,gender,age,official,bib,overall,state,genderdiv,net,country
4        / 26,"Soejima, Masazumi",Fukuoka City,M,41,83.45,W1,4        / 35,,4        / 26,83.45,JPN
14       / 4335,"Gebremariam, Gebregziabher",Tigray,M,27,142.93,2,14       / 21616,,14       / 12621,142.93,ETH
6        / 26,"Van Dyk, Ernst F.",Paarl,M,39,84.38,W2,6        / 35,,6        / 26,84.38,RSA
2        / 26,"Fearnley, Kurt H.",Hamilton,M,31,81.65,W3,2        / 35,,2        / 26,81.65,AUS
3        / 26,"Hokinoue, Kota",Iizuka,M,38,83.43,W4,3        / 35,,3        / 26,83.43,JPN


texts: Function to erase original element but also linked

texts:
I have a list of pointers to objects where some of the objects contain a pointer to another object.  When I remove an object in the list which has a linked object I need to remove them BOTH.  I also want to position the next iterator at a convenient position which will usually be just after the object in the list which is to be deleted.  Or if the linked item is next it will have to be just after the linked item.

There are peripheral issues such as why not using smart pointers etc.  But this is just a simple demo - so please ignore lifecycle issues.  I am looking for comments on the RemoveAllAssociated function.

   #include <iostream>
   #include <list>
   #include <algorithm>

   using namespace std;

   class A
   {
   public:
      A(int timestamp) : m_timestamp(timestamp), m_red(false), m_linkedmsg(0) {}
      virtual ~A() {}

      int gettimestamp() const { return m_timestamp; }

      A* getLinkedMsg() const { return m_linkedmsg; }
      void setLinkedMsg(A* linked) { m_linkedmsg = linked; }

      bool IsRed() const { return m_red; }
      void setRed(bool col = true) { m_red = col; }

   protected:
      int m_timestamp;
      bool m_red;
      A* m_linkedmsg;
   };

   class B : public A
   {
   public:
      B(int timestamp) : A(timestamp) { setRed(true); }
      virtual ~B() {}

   };

   //erase item and linked iterator if available and return next iterator
   std::list<A*>::iterator RemoveAllAssociated(std::list<A*>& thelist, A* item) {
      std::list<A*>::iterator it = find(thelist.begin(), thelist.end(), item);
      if(it != thelist.end()) {
         cout << "found original item in list with timestamp=" << (*it)->gettimestamp() << "\n";
         //we now want to delete linked as well as original
         //first delete linked
         A* linked = (*it)->getLinkedMsg();
         std::list<A*>::iterator found_it = find(thelist.begin(), thelist.end(), linked);
         if(found_it != thelist.end()) {
            cout << "found linked item with timestamp=" << (*found_it)->gettimestamp() << "\n";
            delete *found_it;
            std::list<A*>::iterator after_linked_it = thelist.erase(found_it);
         }

         //now erase item in list
         //Need to return next iterator.  Usually will be just after item
         //check a valid iterator returned
         //We want iterator to be positioned either just after
         delete *it;  //or could have done: delete item;
         return thelist.erase(it);
      } else
         cout << "original item not found in list\n";

      return thelist.end();
   }

   int main() {

      A* a1 = new B(0);
      A* a2 = new B(1);
      A* a3 = new B(2);
      A* a4 = new B(3);
      A* a5 = new B(4);
      A* a6 = new B(5);

      a2->setLinkedMsg(a1);

      //put them in a list
      std::list<A*> alist;
      alist.push_back(a5);
      alist.push_back(a6);
      alist.push_back(a1);
      alist.push_back(a2);
      alist.push_back(a3);
      alist.push_back(a4);

      std::list<A*>::iterator it = RemoveAllAssociated(alist, a2);
      if(it != alist.end())
         cout << "next item in list is " << (*it)->gettimestamp() << endl;

      //print out what is left to check correct items erased
      for(it = alist.begin(); it != alist.end(); ++it) {
         cout << "address=" << *it << " ts=" << (*it)->gettimestamp() << endl;
      }

      //cleanup
      it = alist.begin();
      while(it != alist.end()) {
         delete *it;
         it = alist.erase(it);
      }

      return 0;
   }


texts: Finding the difference in time between two events for a specific ID

texts:
Details about code:

Dataframe (x) shape: (20494463, 31)
In this Dataframe, each id shows up multiple times with different events and the event dates. What I'm looking for is the time between the first time event A occurs and the first time event B occurs for each id
feature_final.index.values is another Dataframe whose indexes are the id's I need to work with

def feature(x):
   times = []
   for j in feature_final.index.values:

     pat = x[x.id == j]
     min_dates_j = pat.groupby(["event_description"]).min()

     try:
         time = ((min_dates_j.loc["A","event_description"] -  min_dates_j.loc["B","event_description"]).days)
     except:
         #RX or DX not present
         time = np.NaN()

     times.append(time)

     return times


texts:
I need to create a commandword to be send to hardware and I'd like to make is as efficient as possible (without going to Assembler or similar).
The command is 16Bit long and has to be passed as an array of two bytes to the hardware interfacing library I use (wiringpi). The first four Bit are configuration Bits and the other 12 are the actual command.

My code currently looks like this:

// global variables
short prefix_A = 3 << (4+8);
short prefix_B = 11 << (4+8);
unsigned char dac_cmd[2];
short cmd;

// not thread safe but that's ok in this application
void send_cmd(bool A, short new_cmd){
  assert( new_cmd < 4096);
  cmd = (A?prefix_A:prefix_B) | new_cmd;
  dac_cmd[0] = cmd >> 8;
  dac_cmd[1] = cmd & (255);
  wiringPiSPIDataRW(0, dac_cmd, 2);
}

I especially don't like the additional copy from the short (cmd) to the uchar[2] (dac_cmd).


texts: Assertions about data in infrastructure code as unit tests

texts:
I have some Python tests I have written, but these are for making assertions about data in infrastructure code (AWS CloudFormation templates). I am using the Unittest framework.

I have code like this:

class TestData(unittest.TestCase):

    def testConfigStackYaml(self):

        bad_list = []
        for stack in glob('*/config'):

            stack_name = os.path.dirname(stack)
            expected_file = "%s/config/%s.yaml" % (stack_name, stack_name)

            if not os.path.isfile(expected_file):
                bad_list.append(expected_file)

        assert not bad_list, "Expected config/<stack_name>.yaml files to exist: %s" % bad_list

    def testStacksetMk(self):

        bad_list = []
        for stack in glob('*/config'):

            stack_name = os.path.dirname(stack)
            expected_file = "%s/stackset.mk" % stack_name

            if not os.path.isfile(expected_file):
                bad_list.append(expected_file)

        assert not bad_list, "Expected stackset.mk file to exist: %s" % bad_list

These are just two of my test cases. I have plenty more.

As can be seen, there is a problem with this code. The for loop for each test case is repeated for each test case, resulting in code duplication and inefficient code.

I have done it this way, however, because I want each test case to yield a helpful, specific message about what is wrong.

Can anyone see a cleaner way to implement this, so that I have the best of both worlds: duplication refactored out, but I still get to have a separate test case for each logical test?


texts: Count number of substrings which contains particular strings

texts:
I need to count the number of substrings of s which contains both the strings a and b.

This is what I did till now:

a = input().rstrip()
b = input().rstrip()
s = input().rstrip()
min_length = max(len(a), len(b))
n = len(s)
count = 0
for i in range(min_length, n+1):
    for j in range(n+1-i):
        temp = s[j:j+i]
        if (a in temp) and (b in temp):
            count += 1
print(count)

The above code works fine, but is slow. How can I optimise it?

For example:

Input:

ab
c
cabc

Output

3

Substrings of s, which contains both a and b as substring are cab , abc and cabc.


texts:
I'm refactoring an old gateway and came across the following method:

def apply_limit_and_offset(options)
  limit  = options[:limit]
  offset = options[:offset]

  @result = if offset
    @result.drop offset
  else
    @result
  end

  @result = if limit
    @result.first limit
  else
    @result
  end

  @result
end

@result is an Array of objects.

Any suggestions on how to refactor this?  It works just fine, but multiple if statements make me feel gross.