texts:
Below is a script I've written that uses AJAX to check if all links on the page are alive or dead. Could this be modified to be more efficient in any way? Thank you very much.

$(document).ready(function() {
    var liveLinks = [];
    var deadLinks = [];

    function updateLive() {
        $live = Number($('#liveLinkCount').text()) + 1;
        $('#liveLinkCount').text($live);
    }

    function updateDead() {
        $dead = Number($('#deadLinkCount').text()) + 1;
        $('#deadLinkCount').text($dead);
    }

    $('body').prepend("
Hide<button id='checkLinks'>Check Links</button>
Live: 0 - Dead: 0
");
    $('#linkChecker').css({
        "width": "130px",
        "border": "1px solid black",
        "text-align": "center"
    });
    $('#hideChecker').css({
        "text-decoration": "underline",
        "float": "right",
        "padding": "1px",
        "cursor": "pointer"
    });
    $('body').on('click', '#checkLinks', function() {
        $('#linkChecker').append("
<button id='logReport'>Log Report</button>");
        $('a').each(function(i) {
            var self;
            self = this;
            $.ajax({
                type: "post",
                url: $(self).prop('href'),
                success: function() {
                    liveLinks.push($(self).prop('href'));
                    updateLive();
                    $(self).css({
                        "color": "green"
                    });
                },
                error: function() {
                    deadLinks.push($(self).prop('href'));
                    updateDead();
                    $(self).css({
                        "font-weight": "bold",
                        "color": "red"
                    });
                }
            });
        });
    });
    $('body').on('click', '#logReport', function() {
        console.log(new Array(24 + 1).join('\n'));
        console.log("Live Links:");
        for (var i in liveLinks) {
            console.log("  " + liveLinks[i]);
        }
        console.log("Dead Links:");
        for (var i in deadLinks) {
            console.log("  " + deadLinks[i]);
        }
    });
    $('body').on('click', '#hideChecker', function() {
        $('#linkChecker').fadeOut();
    });
});


texts: Infix to postfix implementation using a stack

texts:
I have implemented a "infix-to-postfix" function that takes as input a list representing the parsed expression, resulted from applying a certain regular expression to an expression, and I would like to have your opinion regarding its correctness and efficiency. Good suggestions are of course more than well-accepted!

For making you able also to test directly my algorithm, I decided to include also the regular expression and other important details.

import re

# higher number => higher precedence
OPERATORS  = {
    "+": 1,
    "-": 1,
    "*": 2,
    "/": 2,
    "%": 2,
    "^": 3
}

PARENTHESIS = set(["(", ")"])

REGEX = "(\d+|\w+|[()\-+*/^%])"

def parse(e):
    """Parses a string expression e to a infix represation list."""
    return re.findall(REGEX, e)

def infix_to_postfix(infix):
    stack = []
    postfix = []

    for c in infix:
        if c in OPERATORS:

            if len(stack) > 0:
                top = stack[-1]

                if top in OPERATORS.keys():
                    if OPERATORS[c] > OPERATORS[top]:
                        stack.append(c)
                    else:
                        while top in OPERATORS.keys() and OPERATORS[top] >= OPERATORS[c]:
                            op = stack.pop()
                            postfix.append(op)

                            if len(stack) > 0:
                                top = stack[-1]
                            else:
                                break
                        stack.append(c)
                else:
                    stack.append(c)
            else:
                stack.append(c)

        elif c in PARENTHESIS:

            if c == ")":
                if len(stack) > 0:
                    top = stack[-1]

                    while top != "(":
                        try:
                            # pop throws an IndexError if the list is empty
                            r = stack.pop()
                            postfix.append(r)  # Adding what's in between ( ) to the postfix list
                            top = stack[-1]
                        except IndexError:
                            raise ValueError("'(' not found when popping")

                    stack.pop()  # Removes ( from the top of the stack
                else:
                    raise ValueError("')' cannot be added to the stack if it is empty")
            else:
                stack.append(c)  # c == '('
        else:

            postfix.append(c)

        #print("Stack:", stack)
        #print("Postfix:", postfix)

    while len(stack) > 0:
        top = stack.pop()

        if top in OPERATORS.keys():
            postfix.append(top)

    return postfix

Please, don't tell me anything about the docstrings, because I actually removed them from my code to make it clearer.

In general, I prefer efficiency to clarity, so I am not so interested in list or generator comprehensions if they don't make the code more efficient. Anyway, you could also suggest them, if you feel that they would turn the code more "pythonic".


texts: Preg_match pattern for user input filtering

texts:
My users may need to supply a 'disease category' to my site. I need to let them use all alphanumeric characters, hyphens and single quotes. Would someone review this to see if they feel it's reasonable safe?  I'm very happy for suggestions to make it tighter,

      $disease_category = "some user input";
      $reg = "#[^'a-z0-9\s-]#i";
      preg_match($reg,$disease_category);


texts:
My friend and I are making a node.js game, and we have been testing CPU. After profiling, it was determined that this process called zlib is sucking most of the CPU/RAM.

3 clients connected to a game is fine, but when 12~13 players are connected it uses 58% where zlib is using about 30% of this CPU.

inclusive      self           name
ticks   total  ticks   total
64775   58.5%  64775   58.5%  /lib/x86_64-linux-gnu/libc-2.19.so
25001   22.6%    224    0.2%  LazyCompile: *callback zlib.js:409
//this one is a different zlib
7435    6.7%     82    0.1%  LazyCompile: ~callback zlib.js:409

Is there any way to decrease the CPU usage from this? Or is there a reason why it is increasing so much?

I have done some reading and I am told it is from socket.io, so here is our section of socket sending most of the data:

for (var i = 0; i < users.length; i++) {
    if (u.room == users[i].room && users[i].x + users[i].radius >= u.x - u.screenWidth / 2 - 20 && users[i].x - users[i].radius <= u.x + u.screenWidth / 2 + 20 && users[i].y + users[i].radius >= u.y - u.screenHeight / 2 - 20 && users[i].y - users[i].radius <= u.y + u.screenHeight / 2 + 20) {
        if (users[i].id == u.id) {
            visiblePlayers.push({
                x: users[i].x,
                y: users[i].y,
                angle: users[i].angle,
                hue: users[i].hue,
                radius: users[i].radius,
                squeeze: users[i].squeeze,
                name: users[i].name,
                dead: users[i].dead,
                isPlayer: true,
                kills: users[i].kills
            });
        } else {
            visiblePlayers.push({
                x: users[i].x,
                y: users[i].y,
                angle: users[i].angle,
                hue: users[i].hue,
                radius: users[i].radius,
                squeeze: users[i].squeeze,
                name: users[i].name,
                dead: users[i].dead
            });
        }
        // SEND DYING INFO: (FOR OFFLINE ANIMATION):
        if (users[i].dying) {
            visiblePlayers[visiblePlayers.length - 1].dying = true;
        }
    }
}
var visibleEnergy = [];
for (var i = 0; i < energies.length; i++) {
    if (u.firstSend || (energies[i].updated && energies[i].room == u.room)) {
        var anim = energies[i].animate;
        if (u.firstSend)
            anim = true;
        visibleEnergy.push({
            x: energies[i].x,
            y: energies[i].y,
            radius: energies[i].radius,
            index: i,
            animate: anim,
            hue: energies[i].hue,
            room: energies[i].room
        });
    }
}

// SEND PLAYER UPDATES TO CLIENTS:
sockets[u.id].emit('serverTellPlayerMove', visiblePlayers,
    visibleEnergy);


texts: Producer/consumer implementation using Tasks and BlockingCollections

texts:
I'm implementing a Producer/Consumer but the generic interface doesn't require any knowledge of blocking collections or tasks.

public interface IReader
{
    IEnumerable<Data> Read();
}

Is it okay if my implementation of the IReader launches a task asynchronously and returns the consuming enumerable?

public IEnumerable<Data> IReader.Read()
{
    var t = Task.Factory.StartNew(() =>
    {
        BlockingCollection<Data> data = new BlockingCollection();
        DoRead(data);
        return data.GetConsumingEnumerable();
    });

    return t.Result;
}

My concerns are:

Performance.  Is there any negative effect from having the
BlockingCollection on a different thread than the consumer?
Is it bad practice to not indicate that the method is executing asynchronously?


texts:
I'm in need to make a byte[] -> T extension method and need it to be fast (no need for it being pretty)

This function will be called 100's of 1000's of times in very short succession in an absolute performance critical environment.

We're currently optimizing on "ticks" level, every tick translates to a couple milliseconds higher in the callstack, thus the need of raw speed over maintainability (not how I like to design software, but the reasoning behind this is out of scope).

Consider the following code, it's clean and maintainable, but it's relatively slow (probably due to boxing and unboxing), Can this be optimized to be faster?

public static T ConvertTo<T>(this byte[] bytes, int offset = 0)
{
    var type = typeof(T);
    if (type == typeof(sbyte)) return bytes[offset].As<T>();
    if (type == typeof(byte)) return bytes[offset].As<T>();
    if (type == typeof(short)) return BitConverter.ToInt16(bytes, offset).As<T>();
    if (type == typeof(ushort)) return BitConverter.ToUInt32(bytes, offset).As<T>();
    if (type == typeof(int)) return BitConverter.ToInt32(bytes, offset).As<T>();
    if (type == typeof(uint)) return BitConverter.ToUInt32(bytes, offset).As<T>();
    if (type == typeof(long)) return BitConverter.ToInt64(bytes, offset).As<T>();
    if (type == typeof(ulong)) return BitConverter.ToUInt64(bytes, offset).As<T>();

    throw new NotImplementedException();
}

public static T As<T>(this object o)
{
    return (T)o;
}

And yes it needs to be generic, sadly


texts:
I would like to connect this "JS" to Bugzilla (example: bugzilla.mozilla.org or landfill.bugzilla.org).

I started to learn JS language today and I would like to ask you:

How can I not do bad things in global scope?
How should I use functions (in var or not)?

quicksearch = document.getElementById('quicksearch_top');
comment = document.getElementById('comment');

severity = document.getElementById('bug_severity');
priority = document.getElementById('priority');

commit_top = document.getElementById('commit_top');
commit = document.getElementById('commit');

function focusonload() {
// may be it should be
// in next function?

    function cursorfocus(s) {
        x = window.scrollX;
        y = window.scrollY;
        s.focus();
        window.scrollTo(x, y);
    }

    if (comment !== null) {
        cursorfocus(comment)
    } else {
        quicksearch.focus();
    }
}

function navigation(keypressed) {

    keypressed = keypressed || window.event;

    function selectelement(w, select) {
        w.value = select;
    }

    keyCode = keypressed.keyCode || keypressed.which,
    kn = {
        enter: 13,
        save: 83,
        down: 40,
        up: 38,
        p1: 49,
        p2: 50,
        p3: 51,
        p4: 52,
        p5: 53,
    };

    if (keypressed.altKey) {
        if (keyCode == nk.save && commit_top!==null){
            commit_top.click();
        }

        var key_str;
        if (priority!==null){
            switch (keyCode) {
                case kn.p1: key_str = "P1"; break;
                case kn.p2: key_str = "P2"; break;
                case kn.p3: key_str = "P3"; break;
                case kn.p4: key_str = "P4"; break;
                case kn.p5: key_str = "P5"; break;
            }
        }
        selectelement(priority, key_str);
        severity.focus();

    } else if (keypressed.ctrlKey) {
        switch (keyCode) {
            case kn.enter:
                if (commit!==null&&comment.value!=="") {
                    commit.click();
                }
                break;
            case kn.up:
                if (quicksearch!==null) {
                    quicksearch.focus();
                }
                break;
            case kn.down:
                if (comment!==null) {
                    comment.focus();
                }
                break;
        }
    }
}

focusonload();
document.onkeydown = navigation;
// how to call this functions when page
// would be loaded at all (with window.onload)


texts:
I have to generate the unique key having a length of 8, which should be comprised of some set of characters:

{B,C,D,F,G,H,J,K,L,M,N,P,Q,R,S,T,V,W,X,Y,Z,2,3,4,5,6,7,8,9}

Now I have written a program that will generate it, but I am not sure it will generate the unique key.  Could you please review it?.

static string[]  unicode = {"66","67","68","70","71","72","74","75","76","77","78","80","81","82","83","84","86","87","88","89","90","50","51","52","53","54","55","56","57"};

These are the ASCII representation of above character:

long k=5050505050505050; // this initially starts from 5050505050505050

List<string> lst=new List<string>();
void Main(){
    while(lst.Count()<1000000 && k!=9090909090909090)
    {

        var NoSet=Split(k.ToString(),2);

        if(NoSet.Count()==8){

            var no=string.Join("",NoSet.Select(x=>(char)(Convert.ToInt32(x))));
            lst.Add(no);

        }

        k++;
    }
}

Finally, store the last value of K variable to generate the next 1000000 unique key:

static IEnumerable<string> Split(string str, int chunkSize){
return Enumerable.Range(0, str.Length / chunkSize)
    .Select(i => str.Substring(i * chunkSize, chunkSize)).Where(x=>unicode.Contains(x)).Select(x=>x);}

Output from the list:

  22222222

  22222223

  22222224

  22222225

  22222226

  22222227

  22222228

  22222229

  2222222B

  2222222C

  2222222D


texts: SSMTP configuration in Ubuntu 18.04 with Bash in my own system (one user)

texts:
This is how I configure the utility SSMTP that allows me to send mail via smtp protocol through a Google-Gmail proxy instead I'll have to manually configure an "heavier" Postfix bi-directional email server on my environment. I configure it in my own server environment that only I uses.

#!/bin/bash

myHostName="$HOSTNAME"
read -sp "Please paste your Gmail proxy email address (due to pasting, no verfication needed): " gmail_proxy_email_address  && echo
read -sp "Please paste your Gmail proxy email password (due to pasting, no verfication needed):" gmail_proxy_email_password && echo

cat <<-EOF > /etc/ssmtp/ssmtp.conf
    root=${gmail_proxy_email_address}
    AuthUser=${gmail_proxy_email_address}
    AuthPass=${gmail_proxy_email_password}
    hostname=${myHostName}
    mailhub=smtp.gmail.com:587
    rewriteDomain=gmail.com
    FromLineOverride=YES
    UseTLS=YES
    UseSTARTTLS=YES
EOF

Would you do this even otherwise? Something to shorten? Some alternative utility maybe?


texts: Are my one-method (and a couple attribute) classes overkill?

texts:
I saw a talk by Jack Diederich a few weeks ago titled "Stop Writing Classes" and noticed that some of my code perhaps echoes what he argues against (to the effect of "classes with two methods, one of which is __init__") in my code. For some parser that needed to run through a bunch of data, I created a couple classes that implement a single method to extract the salient information and tack it on to the end.

class DataFrameBuilder(object):
    column_order = None
    def __init__(self):
        self.data = []

    def render(self):
        return pd.DataFrame(self.data, columns=self.column_order)

class BoundsBuilder(DataFrameBuilder):
    data_type = 'bounds'
    column_order = ['bid', 'x_min', 'x_max', 'y_min', 'y_max']

    def append(self, bid, blob):
        centroid_x, centroid_y = zip(*blob['centroid'])
        self.data.append({'bid': bid,
                'x_min': min(centroid_x), 'x_max': max(centroid_x),
                'y_min': min(centroid_y), 'y_max': max(centroid_y),
            })
...

def summarize(experiment):
    builders = [BoundsBuilder(), TerminalsBuilder(), SizeBuilder()]

    for bid, blob in experiment.blobs():
        for builder in builders:
            builder.append(bid, blob)

    return {builder.data_type: builder.render() for builder in builders}

I could do the same thing with a couple of dictionaries to store my results and attributes, along with bare functions I pass said dictionary (or value within it), it might even be a few less lines, so I don't know if I'm over-using classes here or not.

My example here is fairly small, but that's why it's here, because they are my smallest classes and perhaps on the edge of usefulness/overkill.


texts: Reset password implementation using JWT for easier code invalidation/expiration?

texts:
This is the first time I had to implement forget password meant for real-use so I had to cover code expiration.
My questions are:

Is using jwt here bad in any way other than it's not the best?
If the above is yes: What cases does it not cover?
If the above is no: What would be the better way to go about it?

Validations are done by validateRequest middleware and yup schema as an argument
app.post("/users/send_verification_code", validateRequest(post_send_verification_code), async (req,res) => {
    let { email } = req.body;
    let code = Math.floor(100000 + Math.random() * 900000);
    let token = createToken(null, { code, email  }, "5h")
    try {
        await patchUser(email, { verification_token: token })
    } catch (err) {
        if (err.message === "The resource you tried to update does not exist") {
            console.log("PASSING: The resource you tried to update does not exist")
        }
        else throw err
    }
    console.log("Valid for 5 hours, Your code is: ", code)
    console.log("DEV: token is: ", token)
    return res.json({
        message: "success",
        code: 201
    })
})

app.post("/users/reset_password", validateRequest(post_reset_password), async (req, res) => {
    let { email, code, new_password } = req.body;
    let user = await findUserByEmail(email,"withVerificationCode")
    if (!user) throw new ErrorHandler(404, "User not found");
    let decoded;
    try {
        decoded = jwt.verify(user.verification_token, JWT_SECRET)
    } catch (err) {
        if (err.name === "TokenExpiredError")
            throw new ErrorHandler(401, "Code has expired", [ "Verification code has expired."])
    }
    if (decoded.code !== code) throw new ErrorHandler(401,"Code is invalid");
    await patchUser(user.id, { password: new_password })
    return res.json({
        message: "success",
        code: 201
    })
})

Use case example:
POST /users/send_verification_code with
{
    "email": "john_doe@example.com"
}

POST /users/reset_password with
{
    "email": "john_doe@example.com",
    "new_password": "example123",
    "confirm_new_password": "example123",
    "code": 123456
}

Note:

Only one verification code is valid at one time or none ( if expired or never called send_verification_code )


texts: Scraping symfonycasts.com using BeautifulSoup

texts:
I'm learning python 3.x and I'm still feeling like a newbie.

The program below scrape a given course in https://symfonycasts.com/ and creates a file containing all the dynamics download links to all the videos in that course.

General programming-related tips and better ways to use beautifulsoup would be great.

import requests
from bs4 import BeautifulSoup

agents = {
    'mozilla':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0'
}

download_suffix = '/download/video'

base_url = 'https://symfonycasts.com'
course_url = '/screencast/rest-ep2/serializer'

def get_page_dom():
    url = base_url + course_url
    headers = {'user-agent': agents['mozilla']}
    r = requests.get(url=url,headers=headers)
    return r.text

def get_links(html):
    chapter_list = html.find('div',class_='chapter-list')
    chapter_list_item = chapter_list.find_all('li')
    for item in chapter_list_item:
        yield item.div.div.a['href']

def generate_download_link(dl):
    for i in dl:
        yield base_url + i + download_suffix

def save_to_file(links):
    links = generate_download_link(links)

    with open('links.txt', 'w') as f:
        for i in links:
            f.write(i + '\n')

def Main():
    html = BeautifulSoup(get_page_dom(), 'html.parser')
    download_links = get_links(html)

    save_to_file(download_links)

if __name__ == '__main__':
    Main()


texts:
I've just coded a hex to integer converter in C and want my code criticized. I did not cover switch statements so I know that can be improved.  I am also planning to truncate "0x" in the beginning of the input if the user enters that.

#include <stdio.h>
#include <ctype.h>
#include <math.h>

#define MAXCHAR 100

int htoi(char hexArray[], int srraySize);

int main(void){
    int userInput;
    int i = 0;
    char hexArray[MAXCHAR];

    while((userInput = getchar()) != EOF){
        if(userInput >= '0' && userInput <= '9'){
            hexArray[i] = userInput;
            ++i;
        }

        if((userInput >= 'a' && userInput <= 'f') || (userInput >= 'A' && userInput <= 'F')){
            hexArray[i] = userInput;
            ++i;
        }
    }

    hexArray[++i] = '\0';

    int ans = htoi(hexArray, i);

    printf("%d\n", ans);

    return 0;
}

int htoi(char hexArray[], int arraySize)
    typedef enum{ a = 10,
        b,
        c,
        d,
        e,
        f
        } hexValues;

    int intArray[MAXCHAR] = { 0 };
    int i, j;
    int finalAns = 0;

    for(i = 0; i < arraySize; ++i){
        if(hexArray[i] >= 'A' && hexArray[i] <= 'F'){
            hexArray[i] = (char)tolower((int)hexArray[i]);
        }
    }

    for(i = 0; i < arraySize; ++i){
        if(hexArray[i] >= '0' && hexArray[i] <= '9'){
            intArray[i] = hexArray[i];

        } else if(hexArray[i] >= 'a' && hexArray[i] <= 'f'){
            if(hexArray[i] == 'a'){
                intArray[i] = a;
            } else if(hexArray[i] == 'b'){
                intArray[i] = b;
            } else if(hexArray[i] == 'c'){
                intArray[i] = c;
            } else if(hexArray[i] == 'd'){
                intArray[i] = d;
            } else if(hexArray[i] == 'e'){
                intArray[i] = e;
            } else if(hexArray[i] == 'f'){
                intArray[i] = f;
            }
        }
    }

    j = arraySize-2;

    for(i = 0; i < arraySize-1; ++i){
        printf("J = %d\n", j);
        printf("Initial Value: %d\n", intArray[i]);
        intArray[i] = (intArray[i] * (pow(16, j)));
        printf("Processed Value: %d\n", intArray[i]);
        finalAns = finalAns + intArray[i];
        --j;
    }

    return finalAns;
}


texts:
I have written below class to manage Memcache keys.

My Memcache keys structure are like:

product_details_#{product_id} => product_details_2
designer_info_#{designer_id}_#{type} => designer_info_10_2

Methods which will be defined are:

MemcacheUtil.product_details(product_id)
MemcacheUtil.designer_info(designer_id, type)

class MemcacheUtil

  # The following hash manages entity wise memcache keys

  KEYS = {

      :product_details => {:key => 'product_details', :defined => false},

      :designer_info => {:key => 'designer_info', :defined => false},

      :product_permalink => {:key =>'product_permalink', :defined => false}
  }.freeze

  class << self

    KEYS.each do |method_name, hash_map|
      if !hash_map[:defined]
        define_method method_name.to_s do |*args|
          "#{hash_map[:key]}_#{args.join('_')}"
        end
      end
    end
end

What are your thoughts?


texts:
Why is this code "bad"? In all of the selection sort codes I am learning from, they do it much differently. I will learn the proper code from the book, but I would love to know why this particular code is bad.

public class Main {
    public static void main(String[] args) {
        int[] array = {8, 3, 5, 7, 9, 2, 4, 6, 8, 0};
        System.out.println("The sorted array is: ");
        displayArray(selectionSort(array));
    }

    public static int[] selectionSort(int[] list) {
        int[] result = list;

        for (int i = 0; i < result.length - 1; i++) {
            for (int j = i + 1; j < result.length; j++) {
                if (result[i] > result[j]) {
                    int temp = result[i];
                    result[i] = result[j];
                    result[j] = temp;
                }
            }
        }
        return result;
    }

    public static void displayArray(int[] list) {
        for (int i = 0; i < list.length; i++) {
            if ((i + 1) % 5 == 0)
                System.out.println(list[i]);
            else
                System.out.print(list[i] + " ");
        }
    }
}


texts: Modeling a temperature recording device in Rails

texts:
The app will allow users to login and upload a CSV file that contains temperature data from a device. This data will be stored and the user can view all these downloads and select one from a list to view using Highcharts.

Where I am getting hung up is with the temperature recorder device model. Each device has a unit serial number that the user would enter and contains roughly 200 time/temp data points. There could be 150-200 of these files uploaded each day. Given that potential volume of downloads a table for one company's temp recorders could grow by 30000 rows each day. I wasn't sure if in the long run this would be a black eye for performance.

The following schema works in my application. The user is able to upload and view the data I just don't think it is practical with a larger volume of CSV files being uploaded.

I'm relatively new to Rails and would like your thoughts on how to best model data for my practice app.

create_table "temp_data", force: :cascade do |t|
    t.integer  "point"
    t.datetime "date"
    t.float    "temp"
    t.string   "alarm"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string   "serial"
  end

I'm not sure if I should have two tables with serial_numbers that has_many :data_points and data_points that belongs_to :serial_numbers.


texts: Promisifying a third-party JS library with minimal code overhead

texts:
Context and Existing Code

I am trying to "promisify" a third-party authentication library (auth0-js) written in JavaScript. Right now it uses callback functions and there are no plans to expose an async/await friendly API. So, I'm writing a wrapper, to avoid callback hell in my own code.

Here's a callback factory function cb which is actively used for creating Promises.

import * as a0 from "auth0-js";

export function cb<TResult>(
  resolve: (reason: TResult) => void,
  reject: (reason: a0.Auth0Error) => void,
): a0.Auth0Callback<TResult> {
  return (error, result) => error ? reject(error) : resolve(result);
}

And here's an example of a wrapper class.

import * as a0 from "auth0-js";
import { cb } from "./cb";

export class Authentication {

  /**
   * Wraps the Auth0-js' `Authentication` object and exposes Promise-based methods.
   * @param wa Wrapped `Authentication` object.
   */
  constructor(private wa: a0.Authentication) { }

  public get dbConnection(): DbConnection {
    return new DBConnection(this.wa.dbConnection);
  }

  public buildAuthorizeUrl(options: any): string {
    return this.wa.buildAuthorizeUrl(options);
  }

  public loginWithDefaultDirectory(options: a0.DefaultDirectoryLoginOptions): Promise<any> {
    return new Promise((resolve, reject) => this.wa.loginWithDefaultDirectory(options, cb(resolve, reject)));
  }

  public login(options: a0.DefaultLoginOptions): Promise<any> {
    return new Promise((resolve, reject) => this.wa.login(options, cb(resolve, reject)));
  }

  public oauthToken(options: any): Promise<any> {
    return new Promise((resolve, reject) => this.wa.oauthToken(options, cb(resolve, reject)));
  }

  public loginWithResourceOwner(options: a0.ResourceOwnerLoginOptions): Promise<any> {
    return new Promise((resolve, reject) => this.wa.loginWithResourceOwner(options, cb(resolve, reject)));
  }

  public getSSOData(withActiveDirectories: boolean, options: a0.DelegationOptions): Promise<any> {
    return new Promise((resolve, reject) => this.wa.getSSOData(withActiveDirectories, cb(resolve, reject)));
  }

  public userInfo(accessToken: string): Promise<a0.Auth0UserProfile> {
    return new Promise((resolve, reject) => this.wa.userInfo(accessToken, cb(resolve, reject)));
  }

  public delegation(options: a0.DelegationOptions): Promise<a0.Auth0DelegationToken> {
    return new Promise((resolve, reject) => this.wa.delegation(options, cb(resolve, reject)));
  }

  public getUserCountry(): Promise<{ countryCode: string; }> {
    return new Promise((resolve, reject) => this.wa.getUserCountry(cb<{ countryCode: string; }>(resolve, reject)));
  }
}

Question

While I'm always open to any constructive feedback, there are a few specific aspects I'll be particularly thankful for.

I'm a C# developer and still know too little about JavaScript/TypeScript. If you know how to make this code look more JS-idiomatic, I'm all ears. Or I can paraphrase the question as "am I going the right/common route?"
You can see that there is a lot of structural repetition in the code that creates Promises from callbacks (e.g. loginWithDefaultDirectory(...), login(...), oauthToken(...) functions). Not nice. Is there a way to apply functional programming ideas here? I have a feeling that functional composition may get handy here, but I don't know how to apply it (a sign, I haven't grasp the concept yet)
Resolved It's also easy to notice that buildAuthorizeUrl(...) is a pass-through. No callbacks here. There must be an easier way to bind one object's function to another object's function, which I don't know how to do. Very similarly, get dbConnection() accessor is a supposed to be a pass-through.

Update 1

I figured the pass-through members can be coded very easily (one line per member):

 public buildAuthorizeUrl = this.wa.buildAuthorizeUrl;

So, point 3 is now out of question.


texts: Arcpy script to check for TIFF files and add them to different lists

texts:
My script goes through sub folders in my main directory and based on a wildcard checks if a tiff file exists or not, if it exists then the file path is appended to the corresponding list. For example, all the tiff files with "*CRP.tif" wildcard, in all the sub folders, go into CRP_List = []. My current code is partially hard-coded, is there a way to make my code more generic? The individual lists i.e. the tiff path names are inputs to a raster mosaic tool which merges all the tiffs/rasters together..

import arcpy, os

#Raster Lists
CRP_List = []
FOR_List = []
INR_List = []
IR_List = []
MO_List = []
PAS_List = []
TCI_List = []
TCT_List = []
TG_List = []
WAT_List = []
WLF_List = []
WLO_List = []
WLT_List = []

arcpy.env.workspace = "D:/A__P6_FINAL_TIFFs"

for folder in arcpy.ListWorkspaces("*"):
    folder_basename = os.path.basename(folder)
    CoName = folder_basename.rsplit('_',1)[0]
    env.workspace = os.path.join("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL")

    for raster in arcpy.ListRasters("*_CRP.tif"):
        if arcpy.Exists(raster):
            CRP_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*FOR.tif"):
        if arcpy.Exists(raster):
            FOREST_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_INR.tif"):
        if arcpy.Exists(raster):
            INR_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_IR.tif"):
        if arcpy.Exists(raster):
            IR_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_MO.tif"):
        if arcpy.Exists(raster):
            MO_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_PAS.tif"):
        if arcpy.Exists(raster):
            PAS_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_TCI.tif"):
        if arcpy.Exists(raster):
            TCI_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_TCT.tif"):
        if arcpy.Exists(raster):
            TCT_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_TG.tif"):
        if arcpy.Exists(raster):
            TG_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_WAT.tif"):
        if arcpy.Exists(raster):
            WAT_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_WLF.tif"):
        if arcpy.Exists(raster):
            WLF_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_WLO.tif"):
        if arcpy.Exists(raster):
            WLO_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)

    for raster in arcpy.ListRasters("*_WLT.tif"):
        if arcpy.Exists(raster):
            WLT_List.append("D:/A__P6_FINAL_TIFFs/" + CoName + "_FINAL/" + raster)


texts: TranslateIt class using the Yandex translation service

texts:
I wrote a class TranslateIt for translating text files with Yandex.Translate service. I feel the code is rather bulky. Is it better to decompose it to several methods? I'm eager to know opinions of experienced people.

import requests
import os
import chardet

class TranslateIt(object):
    """
    methods
    translateit (source, **kwargs)
    translateit - translates source into output
    source - txt file to be translated
    froml - source language, if not specified, yandex tries to autodetect
    tol - translation language, default is ru
    output - translayed txt file

    attributes
    params - parameters dict for yandex api
    encoding - encoding of source file detected by _checkEncoding method
    source_name, output_name - absolute paths of source and output files respectively
    code - result of translation
    message - error message if translation failed
    translated = translated text if succeeded

    constants
    MAX_SIZE - maximum size of a source file according to yandex api
    """

    key = 'trnsl.1.1.20170331T021116Z.53a353fef9d94e08.9617ecfdaf7fbe170972c4107aac8780e53dd21f'
    api_url = 'https://translate.yandex.net/api/v1.5/tr.json/translate'
    MAX_SIZE = 10000
    yandex_string = "\nTranslated by Yandex.Translate service, 'http://translate.yandex.ru/'" #added to translation result according to licence requirements

    #check the encoding of a source file
    def _checkEncoding(self, file_name):
        result = chardet.detect(open(file_name, "rb").read())
        open(file_name).close()
        return result['encoding']

    #translates source to output
    def translateIt(self, source, **kwargs):
        self.params = {'key': TranslateIt.key}
        #check if kwargs are valid
        kwargs_tuple = ('output', 'froml', 'tol')
        if not all([key in kwargs_tuple for key in kwargs.keys()]):
            raise NameError ('Invalid named parameter')
        # check if source file exists
        if os.path.exists(source) and source.endswith('.txt'):
            self.encoding = TranslateIt._checkEncoding(self, source)
            self.source_name = os.path.abspath (source)
            # if source exists, assign it's content to text parameter
            with open(self.source_name, 'r', encoding=self.encoding) as f:
                text = f.read()
                if len (text) < TranslateIt.MAX_SIZE:
                    self.params['text'] = text
                else:
                    raise ValueError('File size can not be more than {} symbols'.format(TranslateIt.MAX_SIZE))
        else:
            raise FileNotFoundError('No data source file found')

        #create translation pair
        if 'tol' not in kwargs.keys():
            kwargs['tol'] = 'ru'
        if 'from' not in kwargs.keys():
            self.params['options'] = 1
            self.params['lang'] = kwargs['tol']
        else:
            self.params['lang'] = kwargs['froml'] + '-' + kwargs['tol']

        #create output file:
        if 'output' in kwargs.keys():
            self.output_name = os.path.abspath(kwargs['output']) if kwargs['output'].endswith('.txt') else os.path.abspath(kwargs['output'] +'.txt')
        else:
            self.output_name = os.path.abspath('translated_' + self.params['lang'] + '_' + os.path.split(self.source_name)[-1])

        #translate, save result in output file if succeeded
        response_result = requests.get(TranslateIt.api_url, params=self.params).json()
        self.code = response_result['code']
        if self.code != 200:
            self.message = response_result['message']
            print ('Translation failed\n Error code: {0}, error message: {1}'.format(self.code, self.message))
        else:
            self.translated = response_result['text'][0] + TranslateIt.yandex_string
            with open(self.output_name, 'w', encoding='utf8') as f:
                f.write(self.translated)
            print ('Translation successful, result saved in {0}'.format(self.output_name))


texts:
I'm a novice to programming completely. I'm trying to teach myself C++. I want to write code to create two vectors and read their elements from input.

vector<int> v1, v2;
/*Reading vector values*/
cout << "Enter the elements of 1st vector" << endl;
int ele;
while (cin >> ele)
    v1.push_back(ele);
cout << "enter the elements of 2nd vector" << endl;
while (cin >> ele)
    v2.push_back(ele);

Though it basically does what I coded it for, I want to have some improvements.

When I input elements into a vector, I would like Enter key to mean that I'm done entering the vector, while a space key says I'm entering the next element.
How can I write a loop for vector 1 and vector 2, as the code for entering elements is the same for both the vectors? (I want to write a loop for reading the two vectors.)


texts: JS PHP insert data in database - is it secure enough?

texts:
I'm working on a webapp and I'm using js/php (php and jquery latest versions).

Is there anything I should do to improve security?

I'm not super worried about safety as the current users are using a very buggy (pretty much every exploit works) and outdated (php 4) platform and never attempted anything.

But better be safe than sorry and learn in the process.

IN JS SIDE I HAVE THIS:

a function to insert data

function insertItem() {

First i do some js validation for empty fields (will check again in php side)

 var valErrors = 0;
  if (!$('#addName_input').val()) {
    $('#addName_input').addClass("inputError");
    valErrors++;
  }
  if (valErrors>0) {
    new Noty({
      type: 'error',
      layout: 'topCenter',
      timeout: '2000',
      progressBar: 'true',
      overlay: 'true',
      text: 'The name is empty'
    }).show();
    return false;
  }

I also use a js regex plugin to help me limit what users can type on inputs that have important data. That way i can prevent from inserting letters in input designed for numbers, etc (but i also check that later on php side)

Then i serialize the form data

var data = $("#newForm").serialize();

i send it using ajax:

$.ajax({
        type: 'POST',
        url: 'modules/' + moduleFolder + '/funcs/insert.php',
        data: data,
        dataType: 'json',
        success: function(response) {

now on the PHP side (insert.php)

if the request method is not post i redirect

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: ../../../.");
    exit();
}

then i fetch the request data:

$name   = isset($_POST['addName_input']) ? $_POST['addName_input'] : '' ;

then i do some validations

if (empty($name)) { }

and check with a validation class if the string "hasSomething()" i dont want:

if (hasNumbers($name) || hasSpecialChars($name))

then i filter_sanitize all the vars

$name  = filter_var($name, FILTER_SANITIZE_STRING);

and finally use a database class (with prepared statements) to insert the data

$insert = $db->query('INSERT INTO zapp_list_tablename (id,name) VALUES (?,?,?)', NULL, $name);


texts:
This is a code automatically converted from VB 6.0 to C#.net
What is a safe and correct way to get rid of that GOTO statement?

public bool IsDirty(bool checkChildrenInd)
{
    bool result = false;
    //Determine if this object is 'dirty', or has been updated since it was created.

    if (Parent.NewInd)
    {
        return true;
    }

    if (backup == null)
    {
        goto CheckChildren; //Check any child lists
    }

    if (!String.Equals(MissingDataValue, backup.MissingDataValue))
    {
        return true;
    }

    if (!String.Equals(PreviewDataValue, backup.PreviewDataValue))
    {
        return true;
    }

    if (FieldOption != backup.FieldOption)
    {
        return true;
    }

CheckChildren:
    if (!checkChildrenInd)
    {
        return result;
    }
    return result;
}


texts:
For an assignment, I had to loop through a text file, and report any positions that a user entered sequence was found. Is there any way I can make this code more efficient, because it seems like I'm writing a lot of nested loops, which I've learned can be dangerous/complicated. Any and all help is appreciated!

import os #OperatingSystem
import sys #System
import re #Regex (Regular Expressions)

def checkSequenceCharacters(seq):
    for c in seq:
        if c != 'A' and c != 'G' and c != 'T' and c != 'C':
            print("[!] ERROR: Not a valid sequence (A/G/T/C ONLY)")
            sys.exit(0)

def checkSequenceLength(seq):
    if len(seq) != 5:
        print("[!] ERROR: Has to be exactally 5 letters long!")
        sys.exit(0)

seq = raw_input("Enter a 5 basepair sequence using only A,G,T,C: \n")

checkSequenceCharacters(seq)
checkSequenceLength(seq)

input_file_path = os.getenv("HOME") + "/Desktop/sequencer/inputfile.txt"
output_file_path = os.getenv("HOME") + "/Desktop/sequencer/output/" + seq + ".txt"

try:
    input_file = open(input_file_path)
    output_file = open(output_file_path, 'w')
    count = 0
    line_location = 0
    lines = []
    for line in input_file:
        line_location = line_location + 1
        arr = re.findall(seq,line)
        if arr:
            x = arr[0]
            if x == seq:
                count = count + 1
                lines.append(line)
                print("[+] Sequence found at line " + str(line_location))
                output_file.write("Line " + str(line_location) + ": " + line + "\n")
    if count != 0:
        print("[*] Matches: " + str(count))
        print("[*] FILE CREATED AT: " + output_file_path)
    else:
        print("[!] ERROR: No matches found!")
finally:
    input_file.close()
    output_file.close()


texts: Comments on my Java pattern for Mutable turned Immutable objects

texts:
Commenting omitted to give you the idea.  I've been toying with this recently as a variant of the Builder pattern.  I've recently fallen in love with immutable objects for the benefits they give in larger concurrent systems.

Questions:

Is there a way to do this without having to instantiate two Objects? (ie. Something.Mutable extends Something but adds setters, while preserving final on the underlying fields once the object gets finalized?

If I have to instantiate two Objects, can I keep final on their somehow and not repeat myself in the contained Builder Object?

public class Something {
    private final int someInteger;
    private final String someString;
    public Something(int someInteger, String someString) {
        this.someInteger = someInteger;
        this.someString = someString;
    }
    public int getSomeInteger() { return someInteger; }
    public String getSomeString() { return someString; }

    public static class Mutable {
        private int someInteger;
        private String someString;
        public Something.Mutable() {}
        public int getSomeInteger() { return someInteger; }
        public String getSomeString() { return someString; }

        public Something.Mutable setSomeInteger(int someInteger) {
            this.someInteger = someInteger;
            return this;
        }
        public Something.Mutable setSomeString(String someString) {
            this.someString = someString;
            return this;
        }

        public Something build() {
            return new Something(someInteger, someString);
        }
    }
}

Here is an example of me using it:

Something something = new Something.Mutable()
        .setString("hi")
        .setInteger(42)
        .build();


texts: PHP and MySQLi login script - is it secure / am I doing something wrong?

texts:
Below is the code for my login page. I haven't really used MySQL (especially OOP) before, so I'd like to know if I'm doing something inherently wrong. The code is working as expected, but I don't trust my knowledge of SQL so much that I'd use this code publicly before asking someone to review it.

So please, tell me any and all problems you find within.

$link = new mysqli('host', 'user', 'pass', 'database');

if($link->error)
    die('Couldn\'t connect to the database. Error: '.$link->error);

if(isset($_POST['username']))
{
    if(!$stmt = $link->prepare('SELECT password FROM accs WHERE username = ?'))
    {
        echo 'Couldn\'t prepare the database query.';
        if($link->error)
            die(' Error: '.$link->error);
    }

    if(!$stmt->bind_param('s', $_POST['username']))
    {
        echo 'Couldn\'t bind parameters to the query.';
        if($stmt->error)
            die(' Error: '.$stmt->error);
    }

    if(!$stmt->execute())
    {
        echo 'Couldn\'t execute the query.';
        if($stmt->error)
            die(' Error: '.$stmt->error);
    }

    if(!$stmt->bind_result($result))
    {
        echo 'Couldn\'t bind the query results.';
        if($stmt->error)
            die(' Error: '.$stmt->error);
    }

    switch($stmt->fetch())
    {
        case NULL:
            die('Username not found.');
            break;

        case FALSE:
            echo 'Couldn\'t fetch the results.';
            if($stmt->error)
                die(' Error: '.$stmt->error);

            break;

        case TRUE:
            // I don't actually store the password in plaintext.
            if($_POST['password'] === $result)
                echo 'Logged in';
            else
                echo 'Wrong password';

            break;
    }
    $stmt->close();
}
else
    die('Error, no username specified.');

$link->close();

The only thing I could think of myself is that I should make a function for the $link->prepare(), $stmt->bind_param(), $stmt->execute() and $stmt->bind_result() conditionals, but that's not too big of a problem, just a design-quirk.

Oh, and if in the future I want to get more than one result from a query (i.e. a whole table) how would I know how many arguments to put into $stmt->bind_result()?

Also, is the way I handled errordetection and -notification optimal from a security and user-friendliness standpoint?


texts: Extract the data from Dicom files in an time efficient way

texts:
I am trying to extract and save images from a Dicom dataset. It is taking approximate 4-5 hours to process 1000 files. (Also, I am reading and saving files in an external hard drive so there is a time lag due to this factor too)
Is there a way to expedite the program as I have more than 10k files and it'll take me forever to just extract the images.
Also, if there is any other suggestion or improvements, anyone could suggest then it is hugely appreciated as I am not from Computer Science background.
Below is my code -
import pandas as pd
import shutil
import os
import glob
import numpy as np
import pathlib
import torch
import random
import shutil
import pydicom
import matplotlib.pyplot as plt
from skimage.io import imread, imsave,imshow

data_dir = 'Path_to_dicom_files'
files = glob.glob(os.path.join(data_dir,'*.dcm'))
folders = []
counter = 1
Destination_path = 'Path_to_destination_folder_where_images_will_be_saved'
root_dirs = 'Path_from_where_files_are_being_read'
for i in files:
    print(i)
    dcm = pydicom.dcmread(i)
    name = dcm.AccessionNumber
    dest = os.path.join(Destination_path,name)
    if dcm.Modality == "XC":
        if os.path.isdir(dest):
            img = dcm.pixel_array
            name = dcm.AccessionNumber+'_'+str(counter)+'.png'
            counter+=1
            #img.save(name)
            imsave(name,img)
            shutil.move(os.path.join(root_dirs,name),dest)
        else:
            os.mkdir(dest)
            img = dcm.pixel_array
            name = dcm.AccessionNumber+'_0.png'
            #img.save(name)
            imsave(name,img)
            shutil.move(os.path.join(root_dirs,name),dest)


texts:
Here, I am reading in a newline delimited file that can be millions of repeating lines that looks like this:

TGATAGTTAGTCATATGAAAGCATCATTAGTAAACCACATTGCTTATTATATTGAACAGT
TACATCTGGCTTATTATACAAAGAGAAAACCATACTATTCATACTATTCTCTTTTTGATC
TTCTCAATCTTCTGTTGTTAGATATTCTATTCCTTGCTCACCATATATACTACTTATGTC
etc.

The goal is to count the number substring instances within this file, including those substrings that span two lines.

The challenge I have is that the input files can be large, so speed is very desirable. So, I am looking for any good suggestions to improve speed here.

My header:

package main

import ("fmt";"os";"bufio";"compress/gzip";"strings";"time")

This function reads the input file into memory as an array. This takes about 5s on my machine. The input file is newline delimited, so this function iterates through each line of the file and adds each line as a value in the genome array.

func input_file(loc string) []string {
    var genome []string

    // my file is zipped because it can be pretty large
    file, err := os.Open(loc)
    f, err := gzip.NewReader(file)
    check(err)

    // a scanner is a convenient interface to read newline-delimited files
    scanner := bufio.NewScanner(f)
    for scanner.Scan() {
        genome = append(genome, scanner.Text())
    }

    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "reading standard input:", err)
    }

    f.Close()
    return genome
}

The above function uses this check for read errors.

func check(e error) {
    if e != nil {
        panic(e)
    }
}

Here I iterate through the array that contains all of the strings read in from the file. This takes about 4s on my machine. It is a bit unfortunate that I am iterating through the file to read it, then iterating through the data a second time to search for substrings. The reason I did this is so that I could reuse the file reading code so, I didn't want it to do anything other than read in the data. I'm sure there is a better way of handling this though.

func search (genome []string, kmers map[string]int64) map[string]int64 {
    left := ""
    right := ""
    full_seq := ""

    // iterate through data pulled from file
    for _, seq := range genome {

        /* maybe not really necessary to understand why i'm doing this but
        the input file is newline delimited and so i am merging lines
        together in case a substring overlaps a newline. */
        left = right
        right = seq
        full_seq = left + right

        kmers = contain_kmer(full_seq, kmers) // check for substring
    }
    return kmers
}

This function is called by the search function and looks for all substrings and if they are found, are counted.

func contain_kmer (seq string, kmers map[string]int64) map[string]int64 {
    for k := range kmers {
        if strings.Contains(seq, k) {
            kmers[k] += 1 // if found, add to total count
        }
    }
    return kmers
}

Here is the main function which points to the input file location, reads the file into memory using the input_file function and then searches for substrings using the search function. On my machine, the code takes about 7s to run.

func main() {
    start := time.Now()
    loc := "./myFile.gz" // input file location

    genome := input_file(loc) // read file into memory

    // counts of substrings to be located within input file
    kmers := map[string]int64 {
        "TATTC":0,
        "GTAAACCACATTGCTTATTA":0,
    }

    // locate the substrings
    kmers = search(genome, kmers)
    end := time.Now()

    fmt.Println(kmers) // display counts
    fmt.Println(end.Sub(start))
}


texts:
I used some web resources to find how to make a web page with javascript validator for fractional numbers. What do you think about it? How it can be improved and still look like a web page? Your help will be highly apreciated. Thank you very much!!

<title>
JavaScript fractional numbers validator
</title>

<form name="form1">

   Enter Decimal Number: <input id="Text1" type="text" />

<input id="Button1" type="button" value="Check" onclick="checkDecimal();" />

</form>

It will be great if the code is shorter and eventually possible to have maximum symbols length for the whole part that is different (let's say double) from the fraction part.


texts: Write a typo correction program with Levenshtein distance algorithm

texts:
I'm building a typo correction program. This is the function, which compute the levenshtein distance between two words (a dictionnary word and an input word). I will call this function many times, so it should be fast. I'm looking for therefore some optimizations. I've seen some faster algorithms, but I don't know how to implement them correctly.

static size_t compute_levenshtein_distance
    (char const *const s,
     size_t const ns,
     char const *const t,
     size_t const nt)
{
#define swap(d1, d2)    \
size_t *tmp = (d1);     \
(d1) = (d2);            \
(d2) = tmp

#define max(a, b)       \
((a) > (b) ? (a) : (b)  \

#define min2(a, b)      \
((a) < (b) ? (a) : (b)) \

#define min3(a, b, c)   \
(min2(min2(a, b), c))

    size_t t1[ns+1], t2[ns+1];
    size_t *d1 = t1, *d2 = t2;

    for (size_t i = 1UL; i <= ns; ++i)
        d1[i] = i;

    for (size_t i = 1UL; i <= nt; ++i) {
        char const cCol = t[i-1];
        d2[0UL]         = i;

        for (size_t j = 1UL; j <= ns; ++j) {
            int    const nCost = s[j-1] != cCol;
            size_t const i1    = d1[j  ] + 1;
            size_t const i2    = d2[j-1] + 1;
            size_t const i3    = d1[j-1] + nCost;
            d2[j] = min3(i1, i2, i3);
        }
        swap(d1, d2);
    }
    return d1[ns];

#undef swap
#undef max
#undef min2
#undef min3
}

Do you have any ideas ?
Thanks.


texts:
I have a dedicated stylesheet <style id="dynamicStyles"></style> for my page's dynamic styles. They are controlled by this JavaScript:

function style(className, sty) {
    var sheet = document.getElementById('dynamicStyles').sheet;
    sheet.insertRule('.' + className + ' {' + sty + '}');
}

// No validation, do not pass tainted content.
function unstyle(className, sty) {
    var sheet = document.getElementById('dynamicStyles').sheet;
    var rules = sheet.cssRules;
    var regex = new RegExp('\\.' + className);
    for (var i = 0; i < rules.length; i++) {
        if (rules[i].cssText.match(regex)) {
            sheet.deleteRule(i);
            return;
        }
    }
}

function styleRule(className, that, sty) {
    if (that.checked) {
        style(className, sty);
    } else {
        unstyle(className);
    }
}

This is called, for example, like this:

<input type=checkbox onClick="styleRule('someClass', this, 'border: 1px #a00 dashed')">

There are maybe 10 or 20 inputs with similar code. The number of elements to be styled is large, hundreds or thousands, so I don't want to re-style each of them.

In addition to a general style review, I'm looking to see if there is a more elegant way to do the lookup in unstyle.


texts:
I seek the assessment of which code block is more efficient in Java at detecting the byte sequence of

00 00 00 01

and

00 00 01

in a byte array.

Version 1

for (int i = 0; i < frame.length - 4; i++) {
        if (frame[i] == 0) {
            if (frame[i + 1] == 0) {
                if (frame[i + 2] == 0) {
                    if (frame[i + 3] == 1) {
                        // found marker 00 00 00 01
                        // do work here
                    }
                } else {
                    if (frame[i + 2] == 1) {
                        // found marker 00 00 01
                        // do work here
                    }
                }
            }
        }
    }

Version 2

    for (int i = 0; i < frame.length - 4; i++) {
        if (frame[i] == 0 && frame[i + 1] == 0 && frame[i + 2] == 0 && frame[i + 3] == 1) {
            // found marker 00 00 00 01
            // do work here
        } else if (frame[i] == 0 && frame[i + 1] == 0 && frame[i + 2] == 1) {
            // found marker 00 00 01
            // do work here
        }
    }

Application repo


texts:
The following is a solution to the knapsack problem and supposed to be my entry to this weeks perl challenge. I wonder if this is a good use of dynamic variables or is it too confusing?

I use them so I don't have to put the variables  $n, @things and @result in all the signatures of the multi-subs and carry them through the recursion.

sub MAIN()
{
    my @data =
        { thing => 'R', weight =>  1, amount =>  1 },
        { thing => 'B', weight =>  1, amount =>  2 },
        { thing => 'G', weight =>  2, amount =>  2 },
        { thing => 'Y', weight => 12, amount =>  4 },
        { thing => 'P', weight =>  4, amount => 10 }
    ;

    my ( $v, $w, @t ) = knapsack( 15, 5, @data );

    say "Value: $v, Weight: $w";
    say "Taken: ", join ",", @t.map: *<thing>;
}

multi sub knapsack( Int $total-weight, Int $*n, @*things )
{
    my @*results;
    my Int $optimal-value  = my Int $current-value  = knapsack( $total-weight, 0 );
    my Int $optimal-weight = my Int $current-weight = @*results[0].pairs.first({ .value eqv $optimal-value }).key // -1;

    return $optimal-value, $optimal-weight, |gather
    {
        # walk the results and find the good ones
        for ^$*n -> $i
        {
            my %d           = @*things[ $i ];
            my $next-weight = $current-weight - %d<weight>;
            my $next-value  = @*results[ $i + 1; $next-weight ];

            with $next-value
            {
                if $next-weight >= 0 && $next-value == $current-value - %d<amount>
                {
                    take @*things[ $i ];
                    $current-value -= %d<amount>;
                    $current-weight -= %d<weight>;
                }
            }
        }

        take @*things[ $*n - 1 ]
                if $current-value > 0;
    };
}

multi sub knapsack( Int $weight, Int $i where @*results[ $i ; $weight ].defined ) { @*results[ $i ; $weight ] }
multi sub knapsack( Int $weight, Int $i where $i >= $*n ) { 0 }
multi sub knapsack( Int $weight, Int $i where $i < $*n )
{
    my $leftover-weight = $weight - @*things[ $i ]<weight>;
    my $current-value   = knapsack( $weight, $i + 1 );

    my $next-value = $leftover-weight >= 0
        ?? ( @*things[ $i ]<amount> + knapsack( $leftover-weight, $i + 1 ) )
        !! 0;

    @*results[ $i ; $weight ] = ( $current-value, $next-value ).max
}


texts:
I am specifically looking for input on naming ModifierCalculator and Modifiers. I would also appreciate input on whether ModifierCalculator should extend EnumMap instead of having it as a field.

These classes are for modifying the status of units. The StatType enum contains different types of ..stats, such as "life", "armor", "weapon damage", etc.

StatModifier objects' purpose is to modify a unit's stat. This kind of modification can be a flat bonus, a percentage increment or a multiplication, using the formula

total = (base + flat)*(1 + percent_increments)*(1 + mult_1)*(1 + mult_2)*... *(1 + mult_n)

ModifierCalculator puts all three kinds of modifiers in a map of Modifiers data structures with StatType serving as keyword.

public enum StatType
{
    //code is trivial to the problem
}

public enum StatModifierType
{
    FLAT, PERCENTAGE, MULTIPLICATIVE;
}

public class StatModifier
{
    private StatType statType;
    private double magnitude;
    private StatModifierType modType;

    public StatModifier(StatType statType, double magnitude, StatModifierType modType)
    {
        this.statType = statType;
        this.magnitude = magnitude;
        this.modType = modType;
    }

    public StatType getStatType()
    {
        return statType;
    }

    public double getMagnitude()
    {
        return magnitude;
    }

    public StatModifierType getModifierType()
    {
        return modType;
    }
}

public class Modifiers
{
    public double flat = 0;
    public double percentage = 0;
    public final ArrayList<Double> multipliers = new ArrayList<Double>();
}

public class ModifierCalculator
{
    private EnumMap<Stat, Modifiers> statToModifiers
          = new EnumMap<Stat, Modifiers>(Stat.class);

    public ModifierCalculator()
    {
        for (StatType s : Stat.values())
            statToModifiers.put(s, new Modifiers());
    }

    public void evaluate(ArrayList<StatModifier> modifiers)
    {
        for (StatModifier modifier : modifiers)
            evaluate(modifier);
    }

    public void evaluate(StatModifier modifier)
    {
        double magnitude = modifier.getMagnitude();
        Modifiers mods = statToModifiers.get(modifier.getStat());
        switch (modifier.getModifierType())
        {
        case FLAT:
            mods.flat += magnitude;
            break;
        case PERCENTAGE:
            mods.percentage += magnitude;
            break;
        case MULTIPLICATIVE:
            mods.multipliers.add(1 + magnitude);
            break;
        }
    }

    public Modifiers getStatModifiers(StatType statType)
    {
        return statToModifiers.get(statType);
    }
}


texts: Using Python to search a sorted 2D Matrix

texts:
Code

Problem

class Solution:
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """

        if len(matrix) == 0 or len(matrix[0]) == 0:
            return False

        height = len(matrix)
        width = len(matrix[0])

        row = height - 1
        col = 0

        while col < width and row >= 0:
            if matrix[row][col] > target:
                row -= 1
            elif matrix[row][col] < target:
                col += 1
            else:
                return True

        return False

Any improvements you could make to this? Runtime is O(Len(row) + len(col)), space is constant.

I looked at other solutions and a lot of them used binary search, but that is O(len(col) * log(len(row)) so I don't think that's an improvement.


texts: Sort a list of objects to put parents first

texts:
I have a class which contains a reference to a parent of the same type( or null if it has no parent).

class MyObject{
    private MyObject parent;
    public MyObject getParent(){ return parent};
    …
}

I have a list of MyObject, and need to order it so that every object comes after its parent in the list (the parent will always be in the list).

void orderList(List<MyObject> toSort){
    List<MyObject> tmp = new ArrayList<>();
    while(!toSort.isEmpty()) {
        for(MyObject obj: toSort){
            if(obj.getParent() == null) {
                tmp.add(obj);
            }else {
                if(tmp.contains(obj.getParent())) {
                    tmp.add(obj);
                }
            }
        }
        toSort.removeAll(tmp);
    }
    toSort.addAll(tmp);
}

Is there a way to make this function more efficient and readable ?


texts:
By browser unknown, i mean i don't know how far back support goes for this.

Also, I'm wondering when I can delegate to typeof.

I've heard typeof is faster but the method below is more widely supported and also mentioned in ES5.

/*isType
**  dependencies - none
**  browser - unknwon
**
*/
NS.isType = function (type, o) {
    return (Object.prototype.toString.call(o).slice(8,1) === type);
};

/*getType
**  dependencies - none
**  browser - unknown
**
*/
NS.getType = function (o) {
    return (Object.prototype.toString.call(o).slice(8,1);
};

Clarification:

Not interested in detecting array like objects....just the language objects defined in ES 5.


texts: Is this a right and effcient way of checking AND in a for loop

texts:
Just saw this at work in a code review and was wondering if this style of coding - for loop, doing && like that, seems fine to you or is there a better way of doing the same?

for (int j = 1; j <= ETtop; j++)
{
    // Check everything.
    int k = ET[j].PriIdx;
    for (int z = 1; z <= ET[k].ArgTop; z++ )
    {
        // Check to make sure every Argument in the equation is valid.
        // If it's a calc this is only true if it's been evaluated.
        ready = ready && ET[k].Arg[z].Valid;
    }
}


texts:
A friend gave this puzzle:

Find 3 numbers (say, A B C) such that

  \$ABC+ABC+ABC = CCC\$

ABC means \$((A*100) + (B*10) + C)\$. Also, these 3 digits must be distinct.

I wrote a quick code to find out the answer:

int main(void) {
    // your code goes here
    int hun,dec,unit;
    int final_num = 0;
    int temp_num = 0;
    for(hun = 0; hun <10; hun++)
    {
        for(dec = 0; dec < 10; dec++)
        {
            for(unit = 0; unit < 10; unit++)
            {
                // Calculate the number which would be formed with this unit place
                final_num = (unit *100) + (unit * 10) + (unit);

                // Values should not be same
                if((unit!=dec) && (unit != hun) &&( dec != hun))
                {
                    // Number with current combo of ABC
                    temp_num = ((hun * 100) + (dec * 10) + unit) * 3;
                    if(temp_num ==final_num )
                    {
                        printf("Number is %d \n",temp_num);
                        printf(" Hun %d Dec %d Unit %d",hun,dec,unit);
                    }
                }
            }
        }
    }
    printf("\nEnd of File ");
    return 0;
}

And the Answer was 185 (185 + 185 + 185 = 555).

That was very amateur code. Upon thinking, I realized I could have implemented equation \$300A + 30B + 3C = 111C\$. But still couldn't avoid for loop.
What could be the better way to implement this? I know only C so I solved it with C.


texts:
The goal is readabilty. Performance is not much of a concern, since it's not going to be used with large amount of data.
Except for degenerate case when the length of the incoming byte array is zero, the dump does not end with a new line character. This is regardless whether ASCII part of the dump is shown or not. The code is also careful not to put any trailing spaces in dump lines, since the dump is intended to be copy-pasted and used as part of other texts.

Code:

class Hex
{
    private readonly byte[] _bytes;
    private readonly int _bytesPerLine;
    private readonly bool _showHeader;
    private readonly bool _showOffset;
    private readonly bool _showAscii;

    private readonly int _length;

    private int _index;
    private readonly StringBuilder _sb = new StringBuilder();

    private Hex(byte[] bytes, int bytesPerLine, bool showHeader, bool showOffset, bool showAscii)
    {
        _bytes = bytes;
        _bytesPerLine = bytesPerLine;
        _showHeader = showHeader;
        _showOffset = showOffset;
        _showAscii = showAscii;
        _length = bytes.Length;
    }

    public static string Dump(byte[] bytes, int bytesPerLine = 16, bool showHeader = true, bool showOffset = true, bool showAscii = true)
    {
        if (bytes == null)
        {
            return "<null>";
        }
        return (new Hex(bytes, bytesPerLine, showHeader, showOffset, showAscii)).Dump();
    }

    private string Dump()
    {
        if (_showHeader)
        {
            WriteHeader();
        }
        WriteBody();
        return _sb.ToString();
    }

    private void WriteHeader()
    {
        if (_showOffset)
        {
            _sb.Append("Offset(h)  ");
        }
        for (int i = 0; i < _bytesPerLine; i++)
        {
            _sb.Append($"{i & 0xFF:X2}");
            if (i + 1 < _bytesPerLine)
            {
                _sb.Append(" ");
            }
        }
        _sb.AppendLine();
    }

    private void WriteBody()
    {
        while (_index < _length)
        {
            if (_index % _bytesPerLine == 0)
            {
                if (_index > 0)
                {
                    if (_showAscii)
                    {
                        WriteAscii();
                    }
                    _sb.AppendLine();
                }

                if (_showOffset)
                {
                    WriteOffset();
                }
            }

            WriteByte();
            if (_index % _bytesPerLine != 0 && _index < _length)
            {
                _sb.Append(" ");
            }
        }

        if (_showAscii)
        {
            WriteAscii();
        }
    }

    private void WriteOffset()
    {
        _sb.Append($"{_index:X8}   ");
    }

    private void WriteByte()
    {
        _sb.Append($"{_bytes[_index]:X2}");
        _index++;
    }

    private void WriteAscii()
    {
        int backtrack = ((_index-1)/_bytesPerLine)*_bytesPerLine;
        int length = _index - backtrack;

        // This is to fill up last string of the dump if it's shorter than _bytesPerLine
        _sb.Append(new string(' ', (_bytesPerLine - length) * 3));

        _sb.Append("   ");
        for (int i = 0; i < length; i++)
        {
            _sb.Append(Translate(_bytes[backtrack + i]));
        }
    }

    private string Translate(byte b)
    {
        return b < 32 ? "." : Encoding.GetEncoding(1252).GetString(new[] {b});
    }
}

Usage:

Console.OutputEncoding = Encoding.GetEncoding(1252);
byte[] example = Enumerable.Range(0, 256).Select(x=>(byte)x).ToArray();
Console.WriteLine(Hex.Dump(example));

Sample output:


texts:
I have implemented a min heap and looking for a simpler solution.

Is there anyone for suggesting a simpler solution for this?

Thanks.

import com.sun.org.apache.xalan.internal.xsltc.dom.MultiValuedNodeHeapIterator;

import java.util.Arrays;

public class MinHeap {

    private int capacity = 10;
    private int size = 0;

    int[] items = new int[capacity];

    private int getLeftChildIndex(int parentIndex) { return 2 * parentIndex + 1 ;}
    private int getRightChildIndex(int parentIndex) { return 2 * parentIndex + 2 ;}
    private int getParentIndex(int childIndex) { return (childIndex -1) / 2 ;}

    private boolean hasLeftChild(int index) { return getLeftChildIndex(index) < size; }
    private boolean hasRightChild(int index) { return getRightChildIndex(index) < size; }
    private boolean hasParent(int index) { return getParentIndex(index) >= 0; }

    private int  leftChild(int index) { return items[getLeftChildIndex(index)]; }
    private int  rightChild(int index) { return items[getRightChildIndex(index)]; }
    private int  parent(int index) { return items[getParentIndex(index)]; }

    private void swap(int indexOne, int indexTwo){
        int temp = items[indexOne];
        items[indexOne] = items[indexTwo];
        items[indexTwo] = temp;
    }

    private void ensureExtraCapacity() {
        if (size == capacity) {
            items = Arrays.copyOf(items, capacity * 2);
            capacity *= 2;
        }
    }

    private int peek() {
        if (size == 0) throw new IllegalStateException();
        return items[0];
    }

    private int poll() {
        if (size == 0) throw new IllegalStateException();
        int item = items[0];
        items[0] = items[size - 1];
        size--;
        heapifyDown();
        return item;
    }

    public void add(int item) {
        ensureExtraCapacity();
        items[size] = item;
        size++;
        heapifyUp();
    }

    public void heapifyUp() {
        int index = size - 1;
        while ( hasParent(index) && parent(index) > items[index] ) {
            swap (getParentIndex(index),index);
            index = getParentIndex(index);
        }
    }

    public void heapifyDown() {
        int index = 0;
        while ( hasLeftChild(index) ) {
            int smallerChildIndex = getLeftChildIndex(index);
            if (hasRightChild(index) && rightChild(index) < leftChild(index)) {
                smallerChildIndex = getRightChildIndex(index);
            }

            if (items[index] < items[smallerChildIndex]) {
                break;
            } else {
                swap(index, smallerChildIndex);
            }
            index = smallerChildIndex;
        }
    }

}


texts: Laravel controller Single Responsibility principle

texts:
I have a method in Laravel controller. How can I improve this code? How can I implement single responsibilty here or maybe there are some other tips I can use in this code? I know that controller methods should be kept as small as possible,but I don't know if it's better idea to split this code in separate methods.

public function displayData(CityRequest $request)
    {
        if (isset($request->validator) && $request->validator->fails()) {
            return redirect()->back()->withErrors($request->validator->messages());
        }
        else {
            $cityName = $request->city;
            $cityName = str_replace(' ','-',$cityName);
            $cityName = iconv('UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', $cityName);
            $response = $this->guzzle->request('GET', asset("/api/products/recommended/" . $cityName));
            $response_body = json_decode($response->getBody());
            if(isset($response_body->error))
            {
                return redirect()->back()->withErrors(['city'=>$response_body->error]);
            }
            $city = $response_body->city;
            $condition = $response_body->current_weather;
            $products = $response_body->recommended_products;
            return back()->with(['city' => $city, 'condition' => $condition, 'products' => $products]);
        }
    }


texts: Game of Life with Scala and Functional Programming

texts:
I have been doing OOP and imperative programming my whole career but I wanted to dabble in Scala along with functional programming. Rather than writing Java like code in Scala I wanted to try a more functional approach. I decided to try a simple Kata with Scala, Game of Life. The following is what I came up with. I admit I am very much stuck in OOP/imperative mindset. I am not sure if this is the best approach for Scala, or functional programming. I avoided functions that mutate objects, and favor returning a new copy. I was unsure what the best approach is with functional programming to ensure objects can't be created in an invalid state. Is there a way I can make my code more aligned with idiomatic Scala and functional programming.

package io.jkratz.katas.gameoflife

import scala.util.Random

case class Board(grid: Array[Array[Int]]) {

  require(grid != null, "grid cannot be null")
  require(!isJagged(grid), "grid cannot be jagged")
  require(isValid(grid), "grid contains invalid values, 0 and 1 are the only valid values")

  val rows: Int = {
    grid.length
  }

  val columns: Int = {
    grid(0).length
  }

  def evolve(): Board = {

    val newGrid = Array.ofDim[Int](rows, columns)
    for (i <- grid.indices) {
      for (j <- grid(0).indices) {
        newGrid(i)(j) = getNextCellState(i,j)
      }
    }

    Board(newGrid)
  }

  private def getNextCellState(i:Int, j: Int): Int = {
    var liveCount = 0
    val cellValue = grid(i)(j)
    for (x <- -1 to 1; y <- -1 to 1) {
      if (i + x < 0 || i + x > (this.rows - 1) || y + j < 0 || y + j > (this.columns - 1)) {
        // do nothing, out of bounds
      } else {
        liveCount += grid(i + x)(j + y)
      }
    }
    liveCount -= cellValue

    if (cellValue.equals(Board.CELL_ALIVE) && (liveCount < 2 || liveCount > 3)) {
      Board.CELL_DEAD
    } else if (cellValue.equals(Board.CELL_DEAD) && liveCount == 3) {
      Board.CELL_ALIVE
    } else {
      cellValue
    }
  }

  private def isJagged(grid: Array[Array[Int]]): Boolean = {
    var valid = true
    val size = grid(0).length
    grid.foreach(row => if (row.length.equals(size)) valid = false)
    valid
  }

  private def isValid(grid: Array[Array[Int]]): Boolean = {
    var valid = true
    for (i <- grid.indices; j <- grid(0).indices) {
      val x = grid(i)(j)
      if (x != 0 && x != 1) {
        valid = false
      }
    }
    valid
  }
}

object Board {

  val CELL_DEAD = 0
  val CELL_ALIVE = 1
  val DEFAULT_ROWS = 10
  val DEFAULT_COLUMNS = 10

  def random(rows: Int = DEFAULT_ROWS, columns: Int = DEFAULT_COLUMNS): Board = {
    val grid = Array.ofDim[Int](rows, columns)
    for (i <- grid.indices) {
      for (j <- grid(0).indices) {
        grid(i)(j) = Random.nextInt(2)
      }
    }
    Board(grid=grid)
  }

  def prettyPrint(board: Board): Unit = {
    val grid = board.grid
    for (i <- grid.indices) {
      for (j <- grid(0).indices) {
        if (grid(i)(j) == 0) print(" - ") else print(" * ")
      }
      println()
    }
  }
}

And my main entry point.

package io.jkratz.katas.gameoflife

object Life {

  def main(args: Array[String]): Unit = {

    val state0 = Board.random(5,5)
    println("State 0")
    Board.prettyPrint(state0)

    val state1 = state0.evolve()
    println("State 1")
    Board.prettyPrint(state1)
  }
}


texts: Deserializing JSON in an expression-bodied member

texts:
All of these if conditions in the below method have similar pattern, Any ideas to come up with a common method to reduce the duplication in this method?

some case we want all the version, and in some case we want only specific version.

I tried with switch case.

public override Func<JObject, dynamic, string> VersionMethod => (jobject, parameters) =>{
        bool hasValidObject = false;

        if (jobject["swVersion"] != null)
        {
            _livetv.SoftwareVersion = new VersionInfo(jobject["swVersion"].Value<string>());
            hasValidObject = true;
        }

        if (jobject["hwVersion"] != null)
        {
            _livetv.HardwareVersion = new VersionInfo(jobject["hwVersion"].Value<string>());
            hasValidObject = true;
        }

        if (jobject["ltvVersion"] != null)
        {
            _livetv.LTV2Version = new VersionInfo(jobject["ltvVersion"].Value<string>());
            hasValidObject = true;
        }

        if (jobject["ltv3Version"] != null)
        {
            _livetv.LTV3Version = new VersionInfo(jobject["ltv3Version"].Value<string>());
            hasValidObject = true;
        }

        if (jobject["cricVersion"] != null)
        {
            _livetv.KAVersion = new VersionInfo(jobject["cricVersion"].Value<string>());
            hasValidObject = true;
        }

        if (jobject["bbVersion"] != null)
        {
            _livetv.BasebandVersion = new VersionInfo(jobject["bbVersion"].Value<string>());
            hasValidObject = true;
        }

        if (hasValidObject)
        {
            return GenerateSuccessful();
        }

        return GenerateUnsuccessful(
            "Unable to parse version from request, try again.");
    };


texts: Number-guessing game with maximum and minimum values

texts:
This is a simple guessing game where you are prompted for a minimum and maximum value, then you must guess the number the computer chooses! This is the first program I have written so any and all suggestions are welcome.

def guessinggame():
    print "Welcome to the Guessing Game!."
    while True:
        try:
            numrange1 = int(raw_input("What is the minimum number you want?: "))
            break
        except ValueError:
            print "This must be an integer!"
    while True:
        try:
            numrange2 = int(raw_input("What is the maximum number you want?: "))
            break
        except ValueError:
            print "This must be an integer!"
    rnumber = random.randint(numrange1, numrange2)
    i = 0
    while True:
        x = int(raw_input("What is your guess?: "))
        if rnumber > x:
            print "Low!"
            i = i + 1
        elif rnumber < x:
            print "High!"
            i = i + 1
        elif rnumber == x:
            print "Correct!"
            i = i + 1
            print i
            break
    again = raw_input("Would you like to play again? (y/n): ")
    if again == 'y':
        guessinggame()
guessinggame()


texts:
This is my first experimentation with the producer-consumer problem (and thread manipulation in general), so any feedback on taboos and fixes is greatly appreciated!

#include <condition_variable>
std::condition_variable cv;

#include <iostream>
#include <random>

#include <mutex>
std::mutex mtx;

#include <thread>

// standard in all of my programs
void panic(const std::string &msg) {
    throw std::runtime_error("Error: " + msg + "\n");
}

int count = 0, buff_size = 0;
char* buff;

int random_int(int lower_bound) {
    std::random_device seed;
    std::mt19937 generator(seed());
    std::uniform_int_distribution<int> dist(lower_bound, std::nextafter(26, DBL_MAX));

    return dist(generator);
}

char random_char(int lower_bound) {
    return 'A' + (random_int(lower_bound) % 26);
}

/* Consumer

Reads characters from the buffer and prints them.

*/
void consume(int job) {
    std::unique_lock<std::mutex> lck(mtx);

    while (count == 0) {
        cv.wait(lck);
    }

    /*
    job + 1 = Running
    job = Ready
    */
    for (int i = 0; i < buff_size; i++) {
        std::cout << buff[i] << std::endl;
    }

    count--;
}

/* Producer

Randomly generates letters at (pos > buff_size & pos <= 26),
inserts them at the next available position in the buffer,
and then prints out the lowercase form of the inputted letter.

*/
void produce(int job) {
    std::unique_lock<std::mutex> lck(mtx);

    for (int i = 0; i < buff_size; i++) {
        buff[i] = random_char(buff_size);
        std::cout << static_cast<char>(tolower(buff[i])) << std::endl;
    }

    count++;
    cv.notify_one();
}

int main() {
    int buf_size = 0;

    std::cout << "The Producer-Consumer Problem (in C++11!)" << std::endl << "Enter the buffer size: ";
    std::cin >> buf_size;

    if (buf_size > 0 && buf_size <= 26) {
        // set the buffer size
        buff_size = buf_size;
        buff = new char[buff_size];
    }
    else {
        // rage quit
        panic("The range must be > 0 and <= 26.");
    }

    std::thread production[10], processed[10];

    /* Initialize the arrays */
    for (int order = 0; order < buff_size; order++) {
        production[order] = std::thread(produce, order);
        processed[order] = std::thread(consume, order);
    }

    /* Join the threads to the main threads */
    for (int order = 0; order < buff_size; order++) {
        processed[order].join();
        production[order].join();
    }
}


texts:
I am trying to build something that will allow us to configure "custom" validation for each customer.  So if a customer wants to see a value contain a specific char, be specific length, or equal something else they just add a pre-created option.  I wrote something that seems to be very primitive, but works.  I would like it to be more dynamic.  For instance, I can pass in actual C# code and it will perform that operation on the value input and being compared.

public class Operation
{
    public object value { get; set; }
    public OMagic perform { get; set; }
}

public class Magic
{

    public bool Validate(object val, Operation operation)
    {
        switch (operation.perform)
        {
            case OMagic.Equal:
                return (string)val == (string)operation.value;
            case OMagic.NotEqual:
                return (string)val != (string)operation.value;
            case OMagic.LengthGreaterThan:
                return (int)val < (int)operation.value;
            case OMagic.LengthEqual:
                return (int)val == (int)operation.value;
            case OMagic.LengthLessThan:
                return (int)val > (int)operation.value;
            default:
                return false;
        }
    }
}

public enum OMagic
{
    Equal,
    NotEqual,
    LengthGreaterThan,
    LengthEqual,
    LengthLessThan

}

That is the primitive code, and here are the tests I wrote (using nunit)

[TestFixtureSetUp]
    public void SetupTest()
    {
        //CurrentMessage = getMessage(WebIZ.Test.UnitTest.Properties.Resources.TestResponse1);
        Magic = new Magic();
    }

    private Magic Magic;

    [Test]
    public void Text_Compare_Works()
    {
        Assert.IsTrue(Magic.Validate("yes", new Operation() { value = "yes", perform = OMagic.Equal }));
        Assert.IsFalse(Magic.Validate("yes", new Operation() { value = "no", perform = OMagic.Equal }));
        Assert.IsTrue(Magic.Validate("yes", new Operation() { value = "no", perform = OMagic.NotEqual }));
        Assert.IsFalse(Magic.Validate("yes", new Operation() { value = "yes", perform = OMagic.NotEqual }));
    }

    [Test]
    public void Int_Compare_Works()
    {
        Assert.IsFalse(Magic.Validate(7, new Operation(){value = 7, perform=OMagic.LengthGreaterThan}));
        Assert.IsTrue(Magic.Validate(7, new Operation() { value = 8, perform = OMagic.LengthGreaterThan }));
        Assert.IsFalse(Magic.Validate(7, new Operation() { value = 7, perform = OMagic.LengthLessThan }));
        Assert.IsTrue(Magic.Validate(7, new Operation() { value = 6, perform = OMagic.LengthLessThan }));
        Assert.IsFalse(Magic.Validate(7, new Operation() { value = 8, perform = OMagic.LengthEqual }));
        Assert.IsTrue(Magic.Validate(7, new Operation() { value = 7, perform = OMagic.LengthEqual }));
    }


texts: Seconds -> Days, Hours, Minutes, and Seconds

texts:
This is just a simple function to convert seconds to days, hours, minutes and seconds for a larger app I'm going to be building. I'm just looking for thoughts on it.

import math

def convert_seconds(x):

    # Day's
    days = x / 86400
    fraction, whole = math.modf(days)
    days = int(whole)

    # Hours
    hours = fraction * 24
    fraction, whole = math.modf(hours)
    hours = int(whole)

    # Minutes
    minutes = fraction * 60
    fraction, whole = math.modf(minutes)
    minutes = int(whole)

    # Seconds
    seconds = fraction * 60
    fraction, whole = math.modf(seconds)
    seconds = int(whole)

    return days, hours, minutes, seconds

if True:
    print(convert_seconds(1043573894573948573))


texts: Could this template function be improved?

texts:
I'm writing wrapper functions for some of the functions in <algorithm>.
While the following works perfectly, I'm not sure if this is the best way to approach it:

template<class ContainerType, class Predicate>
ContainerType filter(
    const ContainerType& container,
    Predicate predicate
) {
    ContainerType filteredContainer;
    std::remove_copy_if(
        container.begin(),
        container.end(),
        std::back_inserter(filteredContainer),
        predicate
    );
    return filteredContainer;

Would you change something about the wrapper? I'm especially worried about the template parameters, e.g. you'll have to read the entire function in order to know what types are valid for predicate etc.


texts:
Requirements

Display movie datas inside all tags that have the class movie_list
Make an ajax call for fetching movie datas
Fill loading text before fetch data
If any error occurs during loading, the content should be empty

What I did

Cached all elements which have the class movie_list
Made functions which have only one responsibility
Functions take movieList elements for making easy to unit test

What I want to know

More readable/reusable code
Any performance improvement point
Any good design pattern on here

function loadMovies() {
   const url = 'http://moviedatas.com/movies';
   const movieList = $('.movie_list');

   setOnLoading(movieList);

   $.ajax({
       method: 'GET',
       url: url,
       data: {
           count: 10
       },
       success: function(response) {
           movieList.each(function() {
               const wrapper = $(this);

               render(wrapper, items);
           });
       },
       error: function(error) {
           onError(movieList);
       }
   })
}

function setOnLoading(movieList) {
   movieList.each(function() {
       $(this).html('Loading...');
   });
}

function render(wrapper, items) {
   const template = `

{title}

{description}

`;

   let movies = '';
   for (let i = 0; i < items.length; i++) {
       movies += template
           .replace('{title}', items[i].title)
           .replace('{description}', items[i].description);
   }

   wrapper.html(movies);
}

function onError(movieList) {
   movieList.each(function() {
       $(this).html('');
   });
}


texts:
I wrote this little class to wrap around a work-in-progress, poorly documented API and I'd like to know what else can be improved. I feel like there's a lot of repetition in the functions and I'd love to know if I could turn all those functions (which do the same thing, just setting a different command in the request object) into just one.

import json
import requests

BASE_URL = "https://chaos.aa.net.uk/"

class Chaos(object):
    """This class allows access to the Andrews & Arnold API.

    Note that it is based on trial and error, there is very little
    official documentation about this API yet, so use at your own risk.
    """

    def __init__(self, username, password):
        """Initialize the class.

        Use the same credentials as on control.aa.net.uk.

        Args:
            username: username like xx00@x
            password: self-explanatory
        """
        self.session = requests.session()
        self.session.headers["User-Agent"] = "Python Chaos Client"
        self.session.auth = (username, password)

    def _request(self, **kwargs):
        """Make an API request, lets Requests check the HTTP status code
        then checks if the "error" string is present in the response
        and raises an exception if that's the case.

        Args:
            **kwargs: will be passed as-is to python-requests
        Returns:
            a dict representation of the APi'S JSON reply
        Raises:
            Exception: the remote server returned an error
        """

        resp = self.session.post(BASE_URL, **kwargs)

        if resp.status_code != requests.codes.ok:
            resp.raise_for_status()

        resp = resp.json()

        if "error" in resp:
            raise APIError(resp["error"])

        return resp

    def info(self, **kwargs):
        return self._request(json={**kwargs, **{"command": "info"}})

    def change(self, **kwargs):
        required = ["broadband", "sim", "voip"]

        if not any(arg in required for arg in kwargs):
            raise InvalidParameters("Missing object of types: " + ", ".join(required))

        return self._request(json={**kwargs, **{"command": "change"}})

    def check(self, **kwargs):
        required = ["order"]

        if not any(arg in required for arg in kwargs):
            raise InvalidParameters("Missing object of types: " + ", ".join(required))

        return self._request(json={**kwargs, **{"command": "check"}})

    def preorder(self, **kwargs):
        required = ["order"]

        if not any(arg in required for arg in kwargs):
            raise InvalidParameters("Missing object of types: " + ", ".join(required))

        return self._request(json={**kwargs, **{"command": "preorder"}})

    def order(self, **kwargs):
        required = ["order"]

        if not any(arg in required for arg in kwargs):
            raise InvalidParameters("Missing object of types: " + ", ".join(required))

        return self._request(json={**kwargs, **{"command": "order"}})

    def usage(self, **kwargs):
        required =  ["broadband", "sim", "voip"]

        if not any(arg in required for arg in kwargs):
            raise InvalidParameters("Missing object of types: " + ", ".join(allowed))

        return self._request(json={**kwargs, **{"command": "usage"}})

    def availability(self, **kwargs):
        required = ["broadband"]

        if not any(arg in required for arg in kwargs):
            raise InvalidParameters("Missing object of types: " + ", ".join(required))

        return self._request(json={**kwargs, **{"command": "availability"}})

class ChaosException(Exception):
    """Base class for all our exceptions.
    """
    pass

class InvalidParameters(ChaosException):
    """Indicates a problem with the request's arguments.
    """
    pass

class APIError(ChaosException):
    """Indicates an error returned by the remote server.
    """
    pass


texts: Computing even huger Fibonacci numbers in Java - follow-up

texts:
See the previous and initial iteration.

I have incorporated almost all the suggestions by Peter Taylor:

The actual method returns a BigInteger instead of String.
The actual method can deal with Fibonacci numbers with negative indices, so there is no any need to throw IllegalArgumentException.
The only base case that is checked is \$n = 0\$.
fibonacciMatrix renamed to pow.
main is now more sensible.

(The matrix power method is still recursive.)

See what I have:

import java.math.BigInteger;

public class LargeFibonacciNumbers {

    public static BigInteger fibonacci(int n) {
        if (n == 0) {
            return BigInteger.ZERO;
        }

        BigInteger[][] matrix = new BigInteger[2][2];

        matrix[0][0] = BigInteger.ONE;
        matrix[0][1] = BigInteger.ONE;
        matrix[1][0] = BigInteger.ONE;
        matrix[1][1] = BigInteger.ZERO;

        BigInteger tmp = pow(matrix, Math.abs(n))[0][1];

        if (n > 0 || ((n & 1) == 1)) {
            return tmp;
        } else {
            return tmp.negate();
        }
    }

    private static BigInteger[][] multiply(BigInteger[][] matrix1,
                                           BigInteger[][] matrix2) {
        BigInteger[][] ret = new BigInteger[2][2];

        ret[0][0] = matrix1[0][0].multiply(matrix2[0][0])
               .add(matrix1[0][1].multiply(matrix2[1][0]));

        ret[0][1] = matrix1[0][0].multiply(matrix2[0][1])
               .add(matrix1[0][1].multiply(matrix2[1][1]));

        ret[1][0] = matrix1[1][0].multiply(matrix2[0][0])
               .add(matrix1[1][1].multiply(matrix2[1][0]));

        ret[1][1] = matrix1[1][0].multiply(matrix2[0][1])
               .add(matrix1[1][1].multiply(matrix2[1][1]));

        return ret;
    }

    private static BigInteger[][] pow(BigInteger[][] matrix, int n) {
        if (n == 1) {
            // End the recursion.
            return matrix;
        }

        BigInteger[][] tmp = pow(matrix, n >> 1);
        tmp = multiply(tmp, tmp);

        if ((n & 1) == 1) {
            tmp = multiply(matrix, tmp);
        }

        return tmp;
    }

    public static void main(String[] args) {
        if (args.length > 0) {
            int n;

            try {
                n = Integer.parseInt(args[0]);
            } catch (NumberFormatException ex) {
                System.err.println("Could not parse \"" + args[0] +
                                   "\" as an integer.");
                return;
            }

            System.out.println(fibonacci(n));
        } else {
            System.out.println("Usage: java -jar File.jar N");
            System.out.println("Where N is the index of the Fibonacci number " +
                               "to compute.");
        }
    }
}

So, what do you think?


texts: Vue.js: extracting data from a nested object using for...in

texts:
I have a getter in my vuex module which gets data from a nested object, then check if there is any key match to the string and push these matched objects into an array. ESLint says that for..in loops iterate over the entire prototype chain, which is virtually never what I want. Its suggests to use Object.{keys,values,entries}, and iterate over the resulting array.
How can I refactor this?

getUsersData({ users: { data: { users } } }) {
  if (users) {
    const arr = Object.keys(users.stats || {}).map(key => users.stats[key]);
    const str = 'active';
    const newArr = [];
    arr.forEach((el) => {
      const obj = {};
      for (const key in el) {
        if (!key.includes(str)) {
          obj[key] = el[key];
        }
      }
      newArr.push(obj);
    });
    return newArr;
  }
  return [];
}


texts: Transforming from spherical coordinates to Cartesian coordinates using Eigen

texts:
I need to transform the coordinates from spherical to Cartesian space using the Eigen C++ Library. The following code serves the purpose:

const int size = 1000;
    Eigen::Array<std::pair<float, float>, Eigen::Dynamic, 1> direction(size);
    for(int i=0; i<direction.size();i++)
    {
            direction(i).first = (i+10)%360; // some value for this example (denoting the azimuth angle)
            direction(i).second = (i+20)%360; // some value for this example (denoting the elevation angle)

     }

    Eigen::MatrixX<T1> transformedMatrix(3, direction.size());
    for(int i=0; i<transformedMatrix.cols(); i++)
    {
        const T1 azimuthAngle = direction(i).first*M_PI/180;    //converting to radians
        const T1 elevationAngle = direction(i).second*M_PI/180; //converting to radians

        transformedMatrix(0,i) = std::cos(azimuthAngle)*std::cos(elevationAngle);
        transformedMatrix(1,i) = std::sin(azimuthAngle)*std::cos(elevationAngle);
        transformedMatrix(2,i) = std::sin(elevationAngle);
    }

I would like to know a better implementation is possible to improve the speed. I know that Eigen has supporting functions for Geometrical transformations. But I am yet to see a clear example to implement the same. Is it also possible to vectorize the code to improve the performance?

Note: This is a duplicate posting. I think that the question will be more relevant on this site.