text:
Q: Is there a quick way in R to predict the class outcome of an observation from a nearest neighbours model from RANN? I am trying to identify the most probable group that an observation belongs to, for several thousand large datasets. It is possible that some of the data is incorrectly classified and I am trying to work out the most likely "true" value. I have tried to use knn3 from the caret package but the predictions take too long to compute. In researching alternatives I have came across the nn2 function from RANN package which performs a nearest neighbour search that is significantly faster than K-Nearest Neighbours.
library(RANN)
library(tidyverse)

iris.scaled <- iris %>%
    mutate_if(is.numeric, scale)

iris.nn2 <- nn2(iris.scaled[1:4])

The result on the nn2 function is two lists, one of indices and one of distances. I want to use the indices table to work out the most likely grouping of each observation, however it returns the row number of the observation and not it's group. I need to replace this with the group it belongs to (in this case, the species column).
distance.index <- iris.nn2$nn.idx[,-1]
target = iris.scaled$Species

I have removed the first column as the first nearest neighbour is always the observation itself.
matrix(target[distance.index[,]], nrow = nrow(distance.index), ncol = ncol(distance.index))

This code gives me the output I want, but is there a tidier way of creating this table and then calculating the most common response for each row, with the speed of calculation being the key.

A: Your scaling can be a real bottleneck when you have more columns (tested on 200 x 22216 gene expression matrix). My version might not seem that impressive with the iris dataset, but on the larger dataset I get 1.3 sec vs. 32.8 sec execution time.
Using tabulate instead of table gives an additional improvement, which is dwarfed, however, by the matrix scaling.
I used a custom scale function here, but using base::scale on a matrix would already be a major improvement.
I also addressed the issue raised by M. Papenberg of "self" not being considered the nearest neighbor by setting those to NA.
invisible(lapply(c("tidyverse", "matrixStats", "RANN", "microbenchmark", "compiler"),
    require, character.only=TRUE))

enableJIT(3)

# faster column scaling (modified from https://www.r-bloggers.com/author/strictlystat/)
colScale <- function(x, center = TRUE, scale = TRUE, rows = NULL, cols = NULL) {
    if (!is.null(rows) && !is.null(cols)) {x <- x[rows, cols, drop = FALSE]
    } else if (!is.null(rows)) {x <- x[rows, , drop = FALSE]
    } else if (!is.null(cols)) x <- x[, cols, drop = FALSE]
    cm <- colMeans(x, na.rm = TRUE)
    if (scale) csd <- matrixStats::colSds(x, center = cm, na.rm = TRUE) else
        csd <- rep(1, length = length(cm))
    if (!center) cm <- rep(0, length = length(cm))
    x <- t((t(x) - cm) / csd)
    return(x)
}

# your posted version (mostly):
oldv <- function(){
    iris.scaled <- iris %>%
        mutate_if(is.numeric, scale)
    iris.nn2 <- nn2(iris.scaled[1:4])
    distance.index <- iris.nn2$nn.idx[,-1]
    target = iris.scaled$Species
    category_neighbours <- matrix(target[distance.index[,]], nrow = nrow(distance.index), ncol = ncol(distance.index))
    class <- apply(category_neighbours, 1, function(x) {
        x1 <- table(x)
        names(x1)[which.max(x1)]})
    cbind(iris, class)
}

## my version:
myv <- function(){
    iris.scaled <- colScale(data.matrix(iris[, 1:(dim(iris)[2]-1)]))
    iris.nn2 <- nn2(iris.scaled)

    # set self neighbors to NA
    iris.nn2$nn.idx[iris.nn2$nn.idx - seq_len(dim(iris.nn2$nn.idx)[1]) == 0] <- NA

    # match up categories
    category_neighbours <- matrix(iris$Species[iris.nn2$nn.idx[,]],
        nrow = dim(iris.nn2$nn.idx)[1], ncol = dim(iris.nn2$nn.idx)[2])

    # turn category_neighbours into numeric for tabulate
    cn <- matrix(as.numeric(factor(category_neighbours, exclude=NULL)),
        nrow = dim(iris.nn2$nn.idx)[1], ncol = dim(iris.nn2$nn.idx)[2])
    cnl <- levels(factor(category_neighbours, exclude = NULL))

    # tabulate frequencies and match up with factor levels
    class <- apply(cn, 1, function(x) {
        cnl[which.max(tabulate(x, nbins=length(cnl))[!is.na(cnl)])]})
    cbind(iris, class)
}

microbenchmark(oldv(), myv(), times=100L)
#> Unit: milliseconds
#>    expr       min        lq      mean    median        uq      max neval cld
#>  oldv() 11.015986 11.679337 12.806252 12.064935 12.745082 33.89201   100   b
#>   myv()  2.430544  2.551342  3.020262  2.612714  2.691179 22.41435   100  a


text:
Q: How would I turn a array in to ol in laravel Right now I have a array that has a parent_id & I think I need to use recursion to accomplish what I would like to do
array
  0 =>
    object(Menu)[56]
      public 'attributes' =>
        array
          'id' => string '1' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'home' (length=4)
          'menu_url' => string 'test' (length=4)
          'parent_id' => string '0' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'original' =>
        array
          'id' => string '1' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'home' (length=4)
          'menu_url' => string 'test' (length=4)
          'parent_id' => string '0' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'relationships' =>
        array
          empty
      public 'exists' => boolean true
      public 'includes' =>
        array
          empty
  1 =>
    object(Menu)[60]
      public 'attributes' =>
        array
          'id' => string '2' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'Contact Us' (length=10)
          'menu_url' => string 'contact' (length=7)
          'parent_id' => string '1' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'original' =>
        array
          'id' => string '2' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'Contact Us' (length=10)
          'menu_url' => string 'contact' (length=7)
          'parent_id' => string '1' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'relationships' =>
        array
          empty
      public 'exists' => boolean true
      public 'includes' =>
        array
          empty
  2 =>
    object(Menu)[61]
      public 'attributes' =>
        array
          'id' => string '3' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'Privacy Docs' (length=12)
          'menu_url' => string 'privacy' (length=7)
          'parent_id' => string '1' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'original' =>
        array
          'id' => string '3' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'Privacy Docs' (length=12)
          'menu_url' => string 'privacy' (length=7)
          'parent_id' => string '1' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'relationships' =>
        array
          empty
      public 'exists' => boolean true
      public 'includes' =>
        array
          empty

array
  0 =>
    object(Menu)[56]
      public 'attributes' =>
        array
          'id' => string '1' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'home' (length=4)
          'menu_url' => string 'test' (length=4)
          'parent_id' => string '0' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'original' =>
        array
          'id' => string '1' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'home' (length=4)
          'menu_url' => string 'test' (length=4)
          'parent_id' => string '0' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'relationships' =>
        array
          empty
      public 'exists' => boolean true
      public 'includes' =>
        array
          empty
  1 =>
    object(Menu)[60]
      public 'attributes' =>
        array
          'id' => string '2' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'Contact Us' (length=10)
          'menu_url' => string 'contact' (length=7)
          'parent_id' => string '1' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'original' =>
        array
          'id' => string '2' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'Contact Us' (length=10)
          'menu_url' => string 'contact' (length=7)
          'parent_id' => string '1' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'relationships' =>
        array
          empty
      public 'exists' => boolean true
      public 'includes' =>
        array
          empty
  2 =>
    object(Menu)[61]
      public 'attributes' =>
        array
          'id' => string '3' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'Privacy Docs' (length=12)
          'menu_url' => string 'privacy' (length=7)
          'parent_id' => string '1' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'original' =>
        array
          'id' => string '3' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'Privacy Docs' (length=12)
          'menu_url' => string 'privacy' (length=7)
          'parent_id' => string '1' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'relationships' =>
        array
          empty
      public 'exists' => boolean true
      public 'includes' =>
        array
          empty

array
  0 =>
    object(Menu)[56]
      public 'attributes' =>
        array
          'id' => string '1' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'home' (length=4)
          'menu_url' => string 'test' (length=4)
          'parent_id' => string '0' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'original' =>
        array
          'id' => string '1' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'home' (length=4)
          'menu_url' => string 'test' (length=4)
          'parent_id' => string '0' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'relationships' =>
        array
          empty
      public 'exists' => boolean true
      public 'includes' =>
        array
          empty
  1 =>
    object(Menu)[60]
      public 'attributes' =>
        array
          'id' => string '2' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'Contact Us' (length=10)
          'menu_url' => string 'contact' (length=7)
          'parent_id' => string '1' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'original' =>
        array
          'id' => string '2' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'Contact Us' (length=10)
          'menu_url' => string 'contact' (length=7)
          'parent_id' => string '1' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'relationships' =>
        array
          empty
      public 'exists' => boolean true
      public 'includes' =>
        array
          empty
  2 =>
    object(Menu)[61]
      public 'attributes' =>
        array
          'id' => string '3' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'Privacy Docs' (length=12)
          'menu_url' => string 'privacy' (length=7)
          'parent_id' => string '1' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'original' =>
        array
          'id' => string '3' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'Privacy Docs' (length=12)
          'menu_url' => string 'privacy' (length=7)
          'parent_id' => string '1' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'relationships' =>
        array
          empty
      public 'exists' => boolean true
      public 'includes' =>
        array
          empty

array
  0 =>
    object(Menu)[56]
      public 'attributes' =>
        array
          'id' => string '1' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'home' (length=4)
          'menu_url' => string 'test' (length=4)
          'parent_id' => string '0' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'original' =>
        array
          'id' => string '1' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'home' (length=4)
          'menu_url' => string 'test' (length=4)
          'parent_id' => string '0' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'relationships' =>
        array
          empty
      public 'exists' => boolean true
      public 'includes' =>
        array
          empty
  1 =>
    object(Menu)[60]
      public 'attributes' =>
        array
          'id' => string '2' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'Contact Us' (length=10)
          'menu_url' => string 'contact' (length=7)
          'parent_id' => string '1' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'original' =>
        array
          'id' => string '2' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'Contact Us' (length=10)
          'menu_url' => string 'contact' (length=7)
          'parent_id' => string '1' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'relationships' =>
        array
          empty
      public 'exists' => boolean true
      public 'includes' =>
        array
          empty
  2 =>
    object(Menu)[61]
      public 'attributes' =>
        array
          'id' => string '3' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'Privacy Docs' (length=12)
          'menu_url' => string 'privacy' (length=7)
          'parent_id' => string '1' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'original' =>
        array
          'id' => string '3' (length=1)
          'menu_id' => string '1' (length=1)
          'menu_name' => string 'Privacy Docs' (length=12)
          'menu_url' => string 'privacy' (length=7)
          'parent_id' => string '1' (length=1)
          'position' => string '0' (length=1)
          'group_id' => string '1' (length=1)
          'menu_items' => null
      public 'relationships' =>
        array
          empty
      public 'exists' => boolean true
      public 'includes' =>
        array
          empty

Right now I have a function in a class called menuHelper
public static function make(array $array, $no = 0) {
        var_dump($array);
        $child = self::hasChildren($array, $no);
        if (empty($child))
            return "";
        $content = "
\n";
        foreach ($child as $value) {
            $content = sprintf("\t

%s
" . self::make($array, $value->id) . "
\n", $value->menu_name);
            //$content .= self::make($array, $value->id);
        }
        $content .= "
\n";
        //return $content;
        return($content == '' ? '' : "
" . $content . "
");
    }
public static function hasChildren($array, $id) {
        return array_filter($array, function ($var) use($id) {
                    return $var->parent_id == $id;
                });
    }

That I want this to output this

parent

Sub

Sub 2

parent 2

Sub

Sub 2

But that does not keep outputing parents it instead outputs 1 parent and then its children. Then it quits outputing even if theres another parent so I guess I have something wrong?

A: This is a really rough answer because your question is vague and missing details.
What you need is to store your main menu items in an array and then loop through them to draw the main menu. Then, as you loop through each main menu item, lookup/load any child menu items that parent might have. If there are child menu items - draw the child menu. easy peasy.

<?php
$main_menu_items = array( $first_menu_item, $second_menu_item );
foreach($main_menu_items as $menu_item)
{
    ?>

<?=$menu_item['menu_name']?>

    <?php
    $child_menu_items = get_child_menu_items($menu_item['menu_id']);
    if( count($child_menu_items) > 0 )
    {
        ?>

        <?php
        foreach($child_menu_items as $child_item)
        {
            ?>

<?=$menu_item['menu_name']?>

            <?php
        }
        ?>

        <?php
    }
    ?>

    <?php
}
?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: grails - validation of inherited domain class attributes I have a fairly straight-forward model of users with profiles and experts, who are special users:
class User { static hasOne = [profile: Profile] }

class Profile {
    String country
    static constraints = { country nullable: true, blank: true }
}

class Expert extends User {
    static constraints = {
        profile validator: { val, obj ->
            if (!val.country) {
                val.errors.rejectValue 'country', 'expert.profile.country.nullable'
            }
        }
    }
}

When I create an expert, set their profile properties and then save the expert, this works as it should. However, if a user wants to save their profile, I am stuck with how to properly validate the profile properties depending on whether they are an expert or not.
This is what I have so far:
    Expert expert = Expert.get(profile.user.id)
    if (expert) {
        expert.properties = params
        expert.save()
    } else {
        profile.user.properties = params
        profile.user.save()
    }

This code does the proper validation and sets the correct error message. However, there are (at least) three issues:

*

*The service doing the profile updating shouldn't really have to know anything about the different types of users.

*While the errors are set on the profile, the profile is still saved
to the DB.

*The error code is not turned into a message until a second attempt
is made to update the profile.

What is the proper way to validate an inherited domain class attribute? Alternatively, is there a better model that I could use to accomplish the goal of different types of users with role-specific validation requirements?
EDIT: It turned out that only the first of the three issues was real. The other two were caused by a tag lib saving the user object while trying to query the DB. The accepted solution (validation in Profile based on a user flag) addresses that.

A: I think you have to set that the profile belongs to an user, and could be nullable. After that you can create the validator inside the profile class. Maybe for you the expert type needs a new class, but i am not sure if that is compulsory.
Maybe I could implement a method inside the User class to know if an entity is an expert based on its properties, or a property itself
class User {
    static hasOne = [profile: Profile]
    boolean expert
}

class Profile {
    static belongsTo = [user: User]
    String country
    static constraints = {
        country validator: { val, obj ->
            if (obj.user?.expert && !val.country) {
                val.errors.rejectValue 'country', 'expert.profile.country.nullable'
            }
        }
        user nullable: true
    }
}


text:
Q: How can I improve my java code to make it dynamic? if message chunks are in double or triple digit for that matter
Given a char limit split message into meaningful chunks without splitting words.

import java.util.ArrayList;

public class splitMessage {

    static ArrayList<String> splitText(String message, int charLimit) {

        return splitTextAuxUsingSplit(message, charLimit);
    }

    static ArrayList<String> splitTextAuxUsingSplit(String message, int charLimitOriginal) {
        // Decrease the char limit to accomodate chunk number at the end i.e. (1/3). For
        // **now assuming, the message chunks won't be more than 9** //what if //message chunks are in double or triple digit? how do I improvise?
        int charLimit = charLimitOriginal - 7;
        // New arraylist to store message chunks
        ArrayList<String> result = new ArrayList<String>();
        String[] splitted = message.split(" ");
        String temp;

        for (int i = 0; i < splitted.length - 1; i++) {
            temp = splitted[i];
            // while length of temp and the next element combined is less than charLimit,
            // temp = temp + next element
            // Last element to be taken care of after this loop
            while ((temp + 1 + splitted[i + 1]).length() <= charLimit && i + 1 < splitted.length - 1) { // +1 for space
                temp = temp + " " + splitted[i + 1];
                i++;
            }
            result.add(temp);

        }
        // Take care of the last element
        // Add the last element from splitted to the last element of result if their
        // combined length is less than charLimit
        String lastElement = result.get(result.size() - 1);
        if (lastElement.length() + 1 + splitted[splitted.length - 1].length() < charLimit) { // +1 for space

            result.set(result.size() - 1, lastElement + " " + splitted[splitted.length - 1]);
        } else {
            result.add(splitted[splitted.length - 1]);
        }

        // append message chunk number for ex (1/3)
        int resultSize = result.size();
        for (int i = 0; i < resultSize; i++) {
            result.set(i, "[" + (i + 1) + "/" + resultSize + "]: " + result.get(i));
        }

        return result;
    }

    public static void main(String[] args) {
        String message;
        int charLmit;
        message = "Hi Sivasrinivas, your Uber is arriving now! And this is a bigger text. Hi Sivasrinivas, your Uber is arriving now! And this is a bigger text. Hi Sivasrinivas, your Uber is arriving now! And this is a bigger text Hi Sivasrinivas, your Uber is arriving now! And this is a bigger text ";
        charLmit = 25;
        ArrayList<String> result = splitText(message, charLmit);
        for (String item: result) {
            System.out.println(item);
        }

    }
}

How do I improvise this code so that it gives correct output even for 2,3 digit message chunks like [1/300] or [29/35]

A: This task does not have a very effective solution, you just need to try different chunk sizes in a loop. You initially assume that the text can be split in no more than 9 chunks, so the information text will be just 7 characters long, e.g. "[1/9]: ". You perform the actual split of the text into chunks of length charLimit - 7. If you get no more than 9 chunks after that - all good. If not, then you need to assume that the text can be split in no more than 99 chunks. The information text will be 9 characters long now, e.g. "[12/99]: ". So you try splitting the text into chunks of length charlimit - 9. If you get less than 100 chunks - all good. If not - you again increase the maximum to 1000 and information text size by 2 and repeat the process until you find the solution.
import java.util.ArrayList;
import java.util.List;

public class SplitMessage {

    static List<String> splitWordsToLimit(String[] words, int charLimit) {
        List<String> result = new ArrayList<>();
        StringBuilder line = new StringBuilder();
        int wordsOnThisLine = 0;
        for (String word : words) {
            if (wordsOnThisLine == 0 ||
               (line.length() + 1 + word.length() <= charLimit)) {
                    if (wordsOnThisLine != 0) {
                       line.append(" ");
                    }
                    line.append(word);
                    wordsOnThisLine++;
               } else {
                    result.add(line.toString());
                    wordsOnThisLine = 1;
                    line = new StringBuilder(word);
               }
        }
        if (wordsOnThisLine != 0) {
                result.add(line.toString());
        }
        return result;
    }

    static List<String> splitText(String message, int charLimit) {
        String[] words = message.split(" ");
        int maxChunks = 10;
        int infoSize = "[1/9]: ".length();
        List<String> chunks;
        while (true) {
            chunks = splitWordsToLimit(words, charLimit - infoSize);
            if (chunks.size() < maxChunks && charLimit > infoSize + 1) {
                break;
            }
            maxChunks *= 10;
            infoSize += 2;
        }
        int digits = String.valueOf(chunks.size()).length();
        String infoFormat = "[%" + String.valueOf(digits) + "d/" +
                             String.valueOf(chunks.size()) + "]: ";
        List<String> result = new ArrayList<>();
        for (int i = 0; i < chunks.size(); i++) {
            result.add(String.format(infoFormat, i + 1) + chunks.get(i));
        }
        return result;
    }

    public static void main(String[] args) {
        String message;
        int charLimit;
        message = "Hi Sivasrinivas, your Uber is arriving now! And this is a bigger text. Hi Sivasrinivas, your Uber is arriving now! And this is a bigger text. Hi Sivasrinivas, your Uber is arriving now! And this is a bigger text Hi Sivasrinivas, your Uber is arriving now! And this is a bigger text ";
        charLimit = 25;
        List<String> result = splitText(message, charLimit);
        for (String item: result) {
            System.out.println(item);
        }

    }
}

Output for charLimit = 50:
[1/7]: Hi Sivasrinivas, your Uber is arriving now!
[2/7]: And this is a bigger text. Hi Sivasrinivas,
[3/7]: your Uber is arriving now! And this is a
[4/7]: bigger text. Hi Sivasrinivas, your Uber is
[5/7]: arriving now! And this is a bigger text Hi
[6/7]: Sivasrinivas, your Uber is arriving now!
[7/7]: And this is a bigger text

Output for charLimit = 25:
[ 1/20]: Hi Sivasrinivas,
[ 2/20]: your Uber is
[ 3/20]: arriving now!
[ 4/20]: And this is a
[ 5/20]: bigger text. Hi
[ 6/20]: Sivasrinivas,
[ 7/20]: your Uber is
[ 8/20]: arriving now!
[ 9/20]: And this is a
[10/20]: bigger text. Hi
[11/20]: Sivasrinivas,
[12/20]: your Uber is
[13/20]: arriving now!
[14/20]: And this is a
[15/20]: bigger text Hi
[16/20]: Sivasrinivas,
[17/20]: your Uber is
[18/20]: arriving now!
[19/20]: And this is a
[20/20]: bigger text


text:
Q: Script error: "Unable to get value of the property 'split': Object is null or undefined I searched around, and couldn't find an answer to my question. I'm very new at coding, and at work, we have an application that current names that are logged in, and what they are doing.
Recently, they have changed from jquery 1.4.1 to jquery 1.8.3. Ever since then, I cannot get the results to process correctly, because of the following error;
"Unable to get value of the property 'split': Object is null or undefined"
I have the code setup to grab the results and split them;
function processAgents(xData, status) {
var avail    = xData.responseText.split("|")[0];
var acw      = xData.responseText.split("|")[1];
var total    = xData.responseText.split("|")[2];
var breaks    = xData.responseText.split("|")[3];
var pending  = xData.responseText.split("|")[4];

The application is setup to open as an HTA file which opens up the PHP script.
Any help would be appreciated, please let me know if I left anything out!
Thanks!
EDIT 1
I did some more investigating, and it looks like I'm not getting data from my process request. This is how it is currently setup
function updateAgents() {
var ts1 = new Date().getTime();
$.ajax({
      url: "http://SERVER/AgentSrc.php?x=" + ts1,
      complete: processAgents

I'm not sure if this is processing correctly since they went to jquery 1.8.3.
EDIT 2
So after looking into it more, it doesn't appear that the script is getting the data from the server, even though I have access. If I make a local file and put the information in it, it will pull the information and split it, but if I point to the path of the file on the server, it won't get the information. But the strange thing is, if I run it using jquery 1.4.1, it pulls the data fine, but can't display it. But with 1.8.3, it doesn't allow me to pull it from the server.
thanks again!

A: This will give some clarity
xData.responseText.toString().split("|")[0];

(split is part of string not jQuery)

A: Here is a possible explanation: in earlier versions of jQuery, ajax calls returned an xmlHttpRequest (XHR) object. Recent versions return a promise (jqXHR) instead.
See this page for more details.


text:
Q: Linkified textview invisible in RTL I'm facing some problems with RTL support on a linkified TextView. My code is as follows:
    final TextView textView = (TextView) findViewById(R.id.where);
        if (textView != null) {
            textView.setAutoLinkMask(0);
            textView.setText(location);
            if (!Linkify.addLinks(textView, Linkify.WEB_URLS |
                    Linkify.EMAIL_ADDRESSES | Linkify.MAP_ADDRESSES)) {
                Linkify.addLinks(textView, mWildcardPattern, "geo:0,0?q=");
            }
            textView.setOnTouchListener(new OnTouchListener() {
                public boolean onTouch(View v, MotionEvent event) {
                    try {
                        return v.onTouchEvent(event);
                    } catch (ActivityNotFoundException e) {
                        // ignore
                        return true;
                    }
                }
            });
        }

And for my TextView:
    <TextView
        android:id="@+id/where"
        style="@style/ViewEventStyle.FontSmall.Link"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:paddingBottom="8dp"
        android:layout_marginTop="@dimen/event_view_no_margin"
        android:textDirection="locale"
        android:singleLine="true"
        android:ellipsize="end"/>

The TextView is invisible when a RTL language is set, but visible as normal for any other language.
The strange this is also that if I touch the location of the TextView it becomes visible and starts the specified activity (from linkify) and when I go back the TextView is always visible. If I change the textDirection element to ltr it's visible as it should, but displayed from the wrong direction. I've tried invalidating, requestinglayout, changing textcolors, setting visibility, making sure it has enough space, getting the text and everything is as it should except that it's invisible. The style doesn't contain anything related to other than setting the size of the text
Anyone with any hints? This is on a phone running api 17

A: I solved the issue, the problem was that when single line was true the textview would be invisible, but if I changed it to maxLines=1 instead it worked as expected.

A: Dunno if it's still relevant nor if it's connected (i'd post it as a comment except i don't have enough reputation - yet :) but I had quite a lot of problems with RTL, some of them similar, when running on API 17. Buttons disappearing, etc. Try running it on 4.3 ?
I can't tell for sure that's the problem, because for me the issue was in the layouts: apparently,in 4.2.2=17, if there a Left and a Start element, they're both somehow taken into account, so you have to leave one out, but in your xml snippet there's none. Maybe in the rest of the file - in which case try this too (if you run only on >=17, use Start/End, otherwise you'll have to duplicate layouts)


text:
Q: Public Private Key Encryption Tutorials Do you know of a tutorial that demonstrates Public Private Key encryption(PPKE) in C++ or C?
I am trying to learn how it works and eventually use Crypto++ to create my own encryptions using public private keys. Maybe theres a Crypto++ PPKE tutorial?
Maybe someone can explain the relationship(if any) between the public and private keys? Could anyone suggest some very simple public and private key values I could use(like 'char*32','char/32') to create my simple PPKE program to understand the concept?

A: Here's a toy version of RSA I wrote some time back. The thing that makes it a toy is that it only uses 32-bit numbers. To provide any meaningful level of security, you need to support much larger numbers for the math (typical key ranges are something like 1024-4096 bits or so, though the latter probably doesn't accomplish much).
Nonetheless, this does implement the real RSA algorithm. It would take relatively little to plug in a bignum package so this code could work with RSA keys of practical size (though most other implementations are probably faster).
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <functional>

const int e_key = 47;
const int d_key = 15;
const int n = 391;

struct crypt : std::binary_function<int, int, int> {
    int operator()(int input, int key) const {
        int result = 1;
        for (int i=0; i<key; i++) {
            result *= input;
            result %= n;
        }
        return result;
    }
};

int main() {
    std::string msg = "Drink more Ovaltine.";
    std::vector<int> encrypted;

    std::transform(msg.begin(), msg.end(),
        std::back_inserter(encrypted),
        std::bind2nd(crypt(), e_key));

    std::transform(encrypted.begin(), encrypted.end(),
        std::ostream_iterator<char>(std::cout, ""),
        std::bind2nd(crypt(), d_key));
    std::cout << "\n";

    return 0;
}

Of course, this only covers the encryption and decryption itself -- that's a long ways short of being a complete security system.
Much like the comments have noted, this is intended purely to support understanding of the algorithm. I've never put it to serious use, and probably never will. Although supporting real key sizes would be fairly trivial, it's open to question whether I'll ever even do that -- if I did, somebody might mistake it for something that should be used on real data, which I don't really intend.

A: www.muppetlabs.com/~breadbox/txt/rsa.html
This article is very well written for programmers who want to understand RSA but do not have solid math background. It is the only article that actually makes me understand RSA. It doesn't contain C or C++ code but once you understand how it works, you should be able to write your own. (Even though I agree with others that it is not recommended, it should be still helpful to cleraly understand RSA) Hope it helps!


text:
Q: Why does a HTTP GET request with vanilla Rust get no answer? I have the following code but when I start the app it requests the page but gets no answer.
use std::io::Read;
use std::io::Result;
use std::io::Write;
use std::net::TcpStream;

fn main() {
    if let Err(err) = connect() {
        println!("err = {}", err);
    }
}

fn connect() -> Result<()> {
    let mut stream = TcpStream::connect("www.google.de:80")?;

    let mut request_data = String::new();
    request_data.push_str("GET / HTTP/1.1");
    request_data.push_str("\r\n");
    request_data.push_str("Host: www.google.de");
    request_data.push_str("\r\n");
    request_data.push_str("\r\n");
    println!("request_data = {:?}", request_data);

    let request = stream.write_all(request_data.as_bytes())?;
    println!("request = {:?}", request);

    let mut buf = String::new();
    let result = stream.read_to_string(&mut buf)?;
    println!("result = {}", result);
    println!("buf = {}", buf);

    Ok(())
}

A: You should pass the Connection: close HTTP header so the server can properly close the connection.
Note that Google will returns compressed content, so you'll get an error: err = stream did not contain valid UTF-8, even sending the header Accept-Encoding: identity.
Testing with the host changed to www.rust-lang.org:
use std::io::Read;
use std::io::Result;
use std::io::Write;
use std::net::TcpStream;

fn main() {
    if let Err(err) = connect() {
        println!("err = {}", err);
    }
}

fn connect() -> Result<()> {
    let mut stream = TcpStream::connect("www.rust-lang.org:80")?;

    let mut request_data = String::new();
    request_data.push_str("GET / HTTP/1.0");
    request_data.push_str("\r\n");
    request_data.push_str("Host: www.rust-lang.org");
    request_data.push_str("\r\n");
    request_data.push_str("Connection: close"); // <== Here!
    request_data.push_str("\r\n");
    request_data.push_str("\r\n");

    println!("request_data = {:?}", request_data);

    let request = stream.write_all(request_data.as_bytes())?;
    println!("request = {:?}", request);

    let mut buf = String::new();
    let result = stream.read_to_string(&mut buf)?;
    println!("result = {}", result);
    println!("buf = {}", buf);

    Ok(())
}

Will result in:
request_data = "GET / HTTP/1.0\r\nHost: www.rust-lang.org\r\nConnection: close\r\n\r\n"
request = ()
result = 554
buf = HTTP/1.1 301 Moved Permanently
Server: CloudFront
Date: Sun, 13 May 2018 04:46:00 GMT
Content-Type: text/html
Content-Length: 183
Connection: close
Location: https://www.rust-lang.org/
X-Cache: Redirect from cloudfront
Via: 1.1 17af5476e6187c3063f9ba7f797d342b.cloudfront.net (CloudFront)
X-Amz-Cf-Id: lzMymVQ6vTv27VxSU4J0MR6EmgPDCDqO8KFimo1kPvxmQxcKjT33jg==

<title>301 Moved Permanently</title>

301 Moved Permanently

CloudFront


text:
Q: jbox2d tutorial can you tell me:
where can I find tutorials "programming games in jbox2d"?

A: I have ported the Hello World sample from the C++ manual to jbox2d.  This is just a line by line port. Obviously you need to write a basic java program and call this code. You will also need to import a number of libraries, I had trouble with the formatting of my imports in StackOverflow so I am excluding them.  Hopefully your IDE will take care of the imports for you.
    // Static Body
    Vec2  gravity = new Vec2(0,-10);
    World world = new World(gravity);
    BodyDef groundBodyDef = new BodyDef();
    groundBodyDef.position.set(0, -10);
    Body groundBody = world.createBody(groundBodyDef);
    PolygonShape groundBox = new PolygonShape();
    groundBox.setAsBox(50, 10);
    groundBody.createFixture(groundBox, 0);

    // Dynamic Body
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyType.DYNAMIC;
    bodyDef.position.set(0, 4);
    Body body = world.createBody(bodyDef);
    PolygonShape dynamicBox = new PolygonShape();
    dynamicBox.setAsBox(1, 1);
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = dynamicBox;
    fixtureDef.density = 1;
    fixtureDef.friction = 0.3f;
    body.createFixture(fixtureDef);

    // Setup world
    float timeStep = 1.0f/60.0f;
    int velocityIterations = 6;
    int positionIterations = 2;

    // Run loop
    for (int i = 0; i < 60; ++i) {
        world.step(timeStep, velocityIterations, positionIterations);
        Vec2 position = body.getPosition();
        float angle = body.getAngle();
        System.out.printf("%4.2f %4.2f %4.2f\n", position.x, position.y, angle);
    }

A: I have developed one simple application using jBox2D and javaFX 2. You can find tutorial and source code for this application here.
Also you can watch application sample demo video here

A: This is not exactly a direct programming-related question, and thus will probably be closed soon.
Regardless, one does not program games in JBox2D, one programs games with JBox2D. If you're looking for help in using the jbox2d library, a quick Google search turned up one tutorial (for android, but I would expect the general use of the library to be quite general) that looks like it may be helpful - alternatively, try the JBox2D user manual.
On the other hand, if what you really want to know is how to program games in general... well, that's a far larger topic and one that is best solved with a Google search for game tutorials. Just remember that game-making is a general topic, not platform specific, so don't shy away from tutorials not written for Java - try and adapt their example code instead, and you may learn even more!


text:
Q: Android.mk rules to make a file.o from many files.txt then link it with other files.o produced from files.cpp I'm porting a modem connection manager written in C++ from linux to gingerbread. This does not end up being an "app" with a "gui" that I would use a java wrapper with the NDK but a service that is called at boot from "init.rc". I found some not up to date docs related to android build system under build/core/. There you find some html files explaining the basics of Android build system and several "file.mk" which are some templates for common situation like creating a c++ executable, static libraries, shared library etc.
I place my tree with all the sources under external/myservice and it's meant to be compiled at the same time as Android itself. (I've already ported the kernel to my platform and it works, just the modem left to go)
In a subfolder in an Android.mk file, I have a bunch of ".cpp" files listed with the variable LOCAL_SRC_FILES := cppfile1.cpp cppfile2.cpp ....  That will generate cppfile1.o cppfile2.o ...
I need to link those cppfile*.o with objfile.o to form a libfile.so. I found the rules on how to generate a libfile.so from a bunch of files.o.
Where things get complicated, is to port the "linux makefile" command to create objfile.o. Here is how it looks like

$(LD) $(LDFLAGS) -r -b binary -o QMIDB.o \
            QMI/Entity.txt \
            QMI/EnumEntry.txt \
            QMI/Enum.txt \
            QMI/Field.txt \
            QMI/Struct.txt

Which means it is a linker job to merge a bunch of text file to make that objfile.o. That file is just a bunch of initialized data structure, there is no code to execute in it but it's pretty ugly to look at all files.txt with a text editor.
I have no clue how to integrate that in the Android.mk file. How can it be done? I'd even appreciate just a hint on where I can find more information. It is easy to find information on building Android applications but it's another story to find anything closer to Android/Kernel itself.

A: From the mk. file file you can easily get so file....
You need to use android Ndk setup and cygwin setup if you are using windows platform to genreate so file from your native code.
Firstly install and place ndk to a location...
Then install cygwin setup not default one check all features in the installation process (it a sort of linux terminal) as ndk-build command is recognized from linux terminal.
Now from your cygwin terminal get access to your project folder jni file.. or where mk is placed...
http://developer.android.com/sdk/ndk/index.html

Use the following referal how to run ndk-build command from cygwin terminal..
Now providing complete path of ndk we use the ndk-build command...
After that the complied code generates the .so file for our project...
Now what we are using System.loadlibrary command to use the so file i.e our native code can now be used.
Note to get so file form mk we need to complie using ndk setup.We can't directly copy paste so file to make our native code run.Also we we are using windows platfrom we will need to use cygwin setup to do that


text:
Q: create dataframes using the loop parameter as part of the dataframe name I will loop through 12 months.
How do I write these two lines in such a way that the loop parameter takes the values from 1 to 12 when substituting the value of "1" in these lines:
df_month_1['a'] = df_month_1['Jan']
code_month[1] = len(df_month_1)

so the result is:
df_month_1['a'] = df_month_1['x']
code_month[1] = len(df_month_1)
…
df_month_12['a'] = df_month_12['x']
code_month[12] = len(df_month_12)

Thanks!

A: You can add all the df_month_i into a list then iterate over the list. Rather than adding them explicitly, you can use globals() function which returns a dictionary with all the defined variables to simplify this process.
for i in range(12):
    month = f'df_month_{i+1}'
    df_months.append(globals()[month])

for i, df_month in enumerate(df_months):
    df_month['a'] = df_month['x']
    code_month[i+1] = len(df_month)


text:
Q: How to run a python script which is on the host machine using docker file I have a python script in my local machine.The file is not in the docker file directory.Is it possible to reference the path of python script inside the docker file and we able to run the script while creating container

A: See docker build --help:

Usage:  docker build [OPTIONS] PATH | URL | -\
Options:
  -f, --file string             Name of the Dockerfile (Default is 'PATH/Dockerfile')

*

*The PATH here is build context which usually you will specify as ., means current dictory.

*Usually you won't specify -f, means it will use Dockerfile in $PATH(Usually . as current folder)

When docker build, docker will compress all items in build context, then pass it to build daemon, all files outside of build context can't be accessed by Dockerfile.
So, for your scenario, you have to change build context to the folder which has py script in it, or the parent folder. Then, specify Dockerfile explicitly.
A minimal example as next for your reference.
Folder structure:
cake@cake:~/20210904$ tree
.
├── docker
│   └── Dockerfile
└── run.py

1 directory, 2 files

run.py:
print("hello")

docker/Dockerfile:
FROM python:3
COPY run.py /
RUN python run.py

Execution:
cake@cake:~/20210904/docker$ docker build -t abc:1 -f Dockerfile ..
Sending build context to Docker daemon  3.584kB
Step 1/3 : FROM python:3
 ---> da24d18bf4bf
Step 2/3 : COPY run.py /
 ---> 6a4c4a76a7fb
Step 3/3 : RUN python run.py
 ---> Running in 4b736175e410
hello
Removing intermediate container 4b736175e410
 ---> 951dd3de7299
Successfully built 951dd3de7299
Successfully tagged abc:1

Expalination:

*

*Above change build context PATH to .. to have ability to access run.py

*Now, the Dockerfile no longer the default PATH/Dockerfile, so we should change it to Dockerfile which means it in current folder.

*COPY run.py / implict means copy the file from PATH/run.py.


text:
Q: Compiler error from type-checking a template parameter I'm trying to write a templated class that handles different template arguments differently.  I would like the class to support two data types: unsigned ints and std::strings and nothing else.  The class needs to behave a little differently depending on which type it gets, so I do some type-checking in the constructor.
Here's stripped-down code for what I'm doing.
#include <iostream>
#include <memory>
#include <utility>
#include <map>
typedef unsigned int uint;

template<typename input_id_t> class atom_t
{
    public:
        atom_t(input_id_t d) :
            data(d)
         { }

        const input_id_t data;
};

template<typename input_id_t> using atom_ptr = std::shared_ptr<atom_t<input_id_t>>;
template<typename input_id_t> using atom_map_t = std::map<input_id_t, atom_ptr<input_id_t>>;

template<typename input_id_t> class abstract_t
{
    public:

        abstract_t()
        {
            if (typeid(input_id_t).name() == typeid(uint).name())
            {
                this->base_entry = std::make_shared<atom_t<input_id_t>>(0);
                this->a_map->insert(std::pair<input_id_t, atom_ptr<input_id_t>>(0, this->base_entry));
            }
            else if (typeid(input_id_t).name() == typeid(std::string).name())
            {
                this->base_entry = std::make_shared<atom_t<input_id_t>>("");
                this->a_map->insert(std::pair<input_id_t, atom_ptr<input_id_t>>("", this->base_entry));
            }
            else { throw "abstract_t template argument invalid!\n"; }
        }

        atom_ptr<input_id_t> base_entry;

        atom_map_t<input_id_t> * a_map = new atom_map_t<input_id_t>;
};

int main()
{
    abstract_t<uint> A;
}

I have a few questions.

*

*The errors this code yields are below.  I think they're all related to the call to std::pair, but what's wrong?  I noticed that deleting the else if clause resolves them.
error: no matching constructor for initialization of 'std::pair<unsigned int, atom_ptr >' (aka 'pair<unsigned int, shared_ptr<atom_t > >')
this->a_map->insert(std::pair<input_id_t, atom_ptr<input_id_t>>("", this->base_entry));
error: static_assert failed due to requirement 'is_constructible<atom_t, char const (&)[1]>::value'
"Can't construct object in make_shared
error: no matching constructor for initialization of 'atom_t'

*I realize the typeid(input_id_t).name() == typeid(uint/std::string).name() approach is clunky.  Is there a better way to do this?

A: The problem is that the code for your std::string case is still compiled, even though it is not executed, and you cannot construct a pair<int, atom_ptr<int>> with "" as first argument. That is what the compiler tells you.
The better approach is to use template specializations:
template<typename input_id_t> class abstract_t {};

template<> class abstract_t<uint> {
public:
    typedef uint input_id_t;
    abstract_t()
    {
        this->base_entry = std::make_shared<atom_t<input_id_t>>(0);
        this->a_map->insert(std::pair<input_id_t, atom_ptr<input_id_t>>(0, this->base_entry));
    }

    atom_ptr<input_id_t> base_entry;
    atom_map_t<input_id_t> * a_map = new atom_map_t<input_id_t>;
}

template<> class abstract_t<std::string> {
public:
    typedef std::string input_id_t;
    abstract_t()
    {
        this->base_entry = std::make_shared<atom_t<input_id_t>>("");
        this->a_map->insert(std::pair<input_id_t, atom_ptr<input_id_t>>("", this->base_entry));
    }

    atom_ptr<input_id_t> base_entry;
    atom_map_t<input_id_t> * a_map = new atom_map_t<input_id_t>;
}

A: The problem is that the compiler tries to compile the else branch of your if statement, even if that branch is never taken.  With C++17 and later, this can be avoided by using a combination of std::is_same and if constexpr, like so:
    abstract_t()
    {
        if constexpr (std::is_same_v <input_id_t, uint>)
        {
            this->base_entry = std::make_shared<atom_t<input_id_t>>(0);
            this->a_map->insert(std::pair<input_id_t, atom_ptr<input_id_t>>(0, this->base_entry));
        }
        else if constexpr (std::is_same_v <input_id_t, std::string>)
        {
            this->base_entry = std::make_shared<atom_t<input_id_t>>("");
            this->a_map->insert(std::pair<input_id_t, atom_ptr<input_id_t>>("", this->base_entry));
        }
        else { throw "abstract_t template argument invalid!\n"; }
    }

And that also answers your second question.  But I prefer Roland's answer, it encapsulates the two constructors better.
Live demo


text:
Q: Yeoman - modifying default sub generators Using Yeoman to scaffold an AngularJS App. I want to change the default sub generator templates. I have found the template files and was wondering what is the right approach, overwriting the original files or creating my own templates, and if so, does it mean I should create a new generator?

A:
does it mean I should create a new generator?

Basically yes.
Yeoman don't allow you to switch templates from generator. This is not how it works.
But you could compose a new generator on top of generator-angular and just switch the parts you don't need.
See documentation here: http://yeoman.io/authoring/composability.html


text:
Q: setLocale method works on the translations in layout, but not for the ones insided yielded components I came across an issue while trying to implement a translation system in a Laravel project.
In the layout file, layout.php, I set the language before yielding the contents:
<?php
    \App::setLocale(session()->get('language'));
?>

And it seems to be working for the @lang instructions that follow (placed inside layout.php).
After those, I yield the content of the page like this:
@yield('content')

But the @lang instructions in the file that extends the layout (and has the 'content' section) do not work.
What might be the problem?

A: App::setLocale() is not persistent, locale will only work for current request at runtime. You can create a middleware and enforce locale on each request in the middleware's handle function
App::setLocale( session('app_locale', 'fallback_language') );

Then in In app\Http\Kernel.php under web group register Language middleware after the StartSession middleware as below.
protected $middleware = [
   ...
   \App\Http\Middleware\LanguageMiddleware::class,
   ...
];

Checkout this post, https://mydnic.be/post/laravel-5-and-his-fcking-non-persistent-app-setlocale its Laravel 5 but concept is the same.


text:
Q: What is the technical term for this type of export? I have seen some people using export in this fashion,
export { default as Something } from './Something';

Is there any technical term for it?

A: Re-exporting some module default's export aliasing it.
Or: re-exporting renaming default export.


text:
Q: manipulating textbox variables in calculations I have some code where I am trying to use variables in a tabpage. The first tabpage only has one text box for user entry (miles.text) and a button to do a calculation: traveltime = mileage/speed. The value from miles.text is stored into a variable called mileage while the speed used is stored in a variable called speed (me.speedtextbox.text).
Ordinarily, doing val(variable.text) works like a charm and it's not doing it in this case. When the user enters 100 for the mileage, it should be divided by 65 (the number in the database) and, therefore, the answer should be 1.53 hours. In my case, I'm getting "infinity" and whenever I do anything else with the variable, I get "when casting from a number, the value must be a number less than infinity." But it is! It's only 65 and I double-checked that the dataset said that too, which it does. Not sure why I am getting this error...thank you!
Public Class Form1

    Private Property Traveltime As Decimal

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 'fooDataSet.testdata' table. You can move, or remove it, as needed.
        Me.TestdataTableAdapter.Fill(Me.foouDataSet.testdata)

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim mileage As Integer
        Dim speed As Integer

        mileage = Val(miles.Text)
        speed = Val(Me.SpeedTextBox.Text)
        traveltime = mileage / speed

        txttraveltime.text = Traveltime.ToString

    End Sub

    Private Sub txtrate_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txttraveltime.TextChanged

    End Sub
End Class

So I did a test program where it did only one thing and that was to simply read one data column in a one row database and store it to a local variable and multiply it by 1.60  except now I am getting "reference to a non-shared member requires an object reference" and it doesn't seem to recognize Me.Speed when I declare it. What am I doing wrong?
Public Class Form1

    Dim Speed As Object
    Dim Me.Speed As New Speed

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Me.Speed = CDec(fooDataSet.testdataRow.Item("speed"))*1.60
        Speedtextbox.text = Me.Speed.tostring

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 'fooDataSet.testdata' table. You can move, or remove it, as needed.
        Me.TestdataTableAdapter.Fill(Me.fooDataSet.testdata)

    End Sub
End Class

A: Before you do anything else, you should do the following:

*

*Open the project's properties (right-click on the Project, then select Properties)

*Click on the Compile tab (left-hand side)

*Select All Configurations from the dropdown menu

*Select On from the Option Explicit menu.

*Select On from the Option Strict menu.

*Save the project
This will more than likely cause a lot of errors to be displayed, but fixing these errors will substantially improve your application's health.
Now, that that is done, the following code will fix the problems in the button click:
    Dim mileage As Integer
    Dim speed As Integer

    If IsNumeric(Me.Miles.Text) Then
        mileage = CInt(Me.Miles.Text)
    End If
    If IsNumeric(Me.SpeedTextBox.Text) Then
        speed = CInt(Me.SpeedTextBox.Text)
    End If

    If speed <> 0 Then
        Traveltime = CDec(mileage / speed)
    Else
        Traveltime = 0
    End If

    txtTravelTime.Text = Traveltime.ToString

However, the code as you have it will produce correct results, so there must be something else amiss. Try the above first and if there are still issues, you can update your question with the details.

A: I would implement the calculation in a separate class and then use object-binding. Here is how the travel time calculator would look like:
Imports System.ComponentModel

Public Class TraveltimeCalculator
    Implements INotifyPropertyChanged

    Private _miles As Double
    Public Property Miles() As Double
        Get
            Return _miles
        End Get
        Set(ByVal value As Double)
            If _miles <> value Then
                _miles = value
                OnPropertyChanged("Miles")
                OnPropertyChanged("Traveltime")
            End If
        End Set
    End Property

    Private _speed As Double
    Public Property Speed() As Double
        Get
            Return _speed
        End Get
        Set(ByVal value As Double)
            If _speed <> value Then
                _speed = value
                OnPropertyChanged("Speed")
                OnPropertyChanged("Traveltime")
            End If
        End Set
    End Property

    Public ReadOnly Property Traveltime() As Double
        Get
            Return If(_speed = 0.0, 0.0, _miles / _speed)
        End Get
    End Property

#Region "INotifyPropertyChanged Members"

    Public Event PropertyChanged As PropertyChangedEventHandler _
     Implements INotifyPropertyChanged.PropertyChanged

    Private Sub OnPropertyChanged(ByVal propertyName As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
    End Sub

#End Region

End Class

In Visual Studio, add a data source in the Data Sources panel. Choose "Object" and then select the TraveltimeCalculator (it has to be compiled, before you can do that). Now you can drag the speed, mileage and travel time fields from the data sources panel to your form. All the wire-up will happen automatically. VS automatically inserts a BindingSource and a navigator into your form. You will not need the navigator and can safely remove it. The only thing you still have to do is to add the following code in the form load event handler or in the form constructor:
Private Sub frmTravelTime_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    TraveltimeCalculatorBindingSource.DataSource = New TraveltimeCalculator()
End Sub

When you enter speeds and mileages, the travel time textbox will automatically be updated. Non-numeric entries will automatically be rejected and all the text-number conversions happen automatically.

A: I discovered what the problem was.
To store a field from a one-line database to a local variable for calculations, apparently it has to happen in the form1_load event, after the dataadapter fill statement, like so:
Me.TestdataTableAdapter.Fill(Me.foouDataSet.testdata)
  speed = Me.fooDataSet.testdata(0).speed

and just DIM speed as Decimal after the Public Class line. The same could be done for any other field you want to work with in a similar kind of single datarow:
yourvarname = Me.yourdatasetname.yourtablename(0).the_database_field_you_want_to_fetch

(Wow! Did I just write something textbooky? LOL)
Then, after the button click, to do a calculation, it is:
traveltime = CDec(miles.Text/ speed)
txttraveltime.Text = traveltime.ToString

making sure to DIM traveltime as Decimal.
Works! The problem was the (0) to indicate row 0 (because it's only one row.) Thank you everyone for your help, especially Competent_Tech. I learned something and I'm happy that I could get back to you guys and share.


text:
Q: max and min dates returning different than head, tail of sorted list I found some puzzling behavior. Given a list of 50 dates:
structure(c("15513", "12830", "16503", "-3628", "15833", "13553",
"473", "17126", "7916", "74", "4736", "7712", "12726", "8684",
"16217", "14725", "11836", "7061", "4687", "8733", "17176", "17175",
"16155", "14005", "14635", "-1793", "4296", "15316", "4746",
"6865", "14228", "5177", "4543", "1936", "10372", "-1393", "13648",
"17267", "9177", "10380", "9427", "9527", "-1375", "2133", "13966",
"336", "1925", "9611", "15601", "9218"), class = "Date")

I ran this:
head(sort(b), 1) ## prints "1960-01-26"
tail(sort(b), 1) ## prints "2017-04-11"

max(b)           ## prints "1996-04-25"
min(b)           ## prints "1966-03-28"

But what really confuses me is when all the printed values are in one list, max and min return the expected result.
dc = as.Date(c("1960-01-26", "2017-04-11", "1996-04-25", "1966-03-28"))
max(dc)    ## prints "2017-04-11"
min(dc)    ## prints "1960-01-26"

Why is this?

A: The min() and max() functions are only for input of class "numerical"
The vector in your example i class "Date".
For:
structure(min(as.numeric(example)), class ="Date")

where "example" is your vector you get the right solution...
Hope this makes it clear.
Cheers


text:
Q: LibreOffice Calc color-coding cells categorically I have a spreadsheet of text data; each column has a limited allowable set of string values. I have a second sheet in the file which, for each column in the first sheet, contains each allowed value exactly once. (There is currently no formula enforcing this; I am pretty sure that if I knew how to do that I wouldn't need to ask this question.)
What I want to do is make it so that each value in the main sheet is color-coded such that each allowed value for a given column has a different color. Manually assigning colors for each value is infeasible. I don't care about overlaps in color-range for separate columns.
I have seen this question, which is basically the same as my question but for Excel, and unclear in answer besides. Prompted by that, I've added additional columns such that to the left of each column in the domain sheet is a column mapping those values to consecutive integers. I don't know how to turn those into colors on the main sheet, though.
I did find instructions for color-scale formatting. This is about half of what I need; unfortunately, it seems that formulas can only be used there to define minimum, maximum, and midpoint values for the gradient, but not to process the cell value from a string to an integer to make it gradient-able.
Using that, I've gotten most of the way there: A third sheet reads the values from the first sheet, maps them to numbers using the second sheet, and applies a color scale to the result. This results in a sheet with the same data as the original, but represented in numbers and colors instead of strings. The remaining step (if this method goes anywhere) would be to either duplicate those colors onto the original sheet or have the new sheet display strings to the user while containing numbers for the formatter.

A: There is no way to dynamically create a set of new colors except with a macro.  It's possible to format using a color scale, as you stated.  It's also possible to create any number of new colors with styles (described here), but the question states that there are too many different colors.
So instead, highlight any duplicates and any values which are not in the list.

*

*Select the cells to check for one column on the main sheet.

*Format -> Conditional Formatting -> Manage.

*Add, Condition 1 Cell value is, duplicate, Apply Style Bad.  (This works in LO 5.4.3.2.  If your version is not new enough, then use COUNTIF as described here).

*Add, Condition 2 Formula is, ISNA(VLOOKUP(A1;Sheet2.$A$1:$A$100;1;)), Apply Style Error (based on here).

For example, if sheet 2 contains the following list:
apple
banana
carrot
date
eggplant
fig
grape

Then on the main sheet, problematic values are highlighted.

Note: You can enforce values to be in the list using Data -> Validity, Allow Cell range.


text:
Q: Remove duplicate lines from a file but leave 1 occurrence I'm looking to remove duplicate lines from a file but leave 1 occurrence in the file.
Example of the file:
this is a string
test line
test line 2
this is a string

From the above example, I would want to remove 1 occurrence of "this is a string".
Best way to do this?

A: As removing all but the last occurrence is the inverse of removing all but the first, there is also this solution:
tac file | awk '! seen[$0]++' | tac

tac reverses lines in the file, and awk will only output the first occurrence of a duplicate line.

A: Demo file stuff.txt contains:
one
two
three
one
two
four
five

Remove duplicate lines from a file assuming you don't mind that lines are sorted
$ sort -u stuff.txt
five
four
one
three
two

Explanation: the u flag sent to sort says sort the lines of the file and force unique.
Remove duplicate lines from a file, preserve original ordering, keep the first:
$ cat -n stuff.txt | sort -uk2 | sort -nk1 | cut -f2-
one
two
three
four
five

Explanation: The n flag passed to cat appends line numbers to left of every line, plus space, then the first sort says sort by unique and but only after the first word, the second sort command says use the line numbers we stored in step 1 to resort by the original ordering, finally cut off the first word.
Remove duplicate lines from a file, preserve order, keep last.
tac stuff.txt > stuff2.txt; cat -n stuff2.txt | sort -uk2 | sort -nk1 | cut -f2- > stuff3.txt; tac stuff3.txt > stuff4.txt; cat stuff4.txt
three
one
two
four
five

Explanation: Same as before, but tac reverse the file, achieving the desired result.

A: Based on your comments you want the result to be the same output file without having to create another output or append into the new file, you could use the following:
example:
gawk -i inplace '!a[$0]++' $file

A: This leaves the first occurrence:
awk '! a[$0]++' inputfile

start cmd:> echo 'this is a string
cont. cmd:> test line
cont. cmd:> test line 2
cont. cmd:> this is a string' | awk '! a[$0]++'
    this is a string
    test line
    test line 2

A: If you use vim, could try the following code:
g/./if(temp == getline('.')) | let temp = getline('.') | else | :norm dd | endif


text:
Q: Filter orders by product I am newbie in SQL development. I am not good in SQL join :( .
please help me to write a SQL query to extract the following fileds from the below tables for the product "A Home Portable Laser Hair Remover".
Fileds required:
orders.id, orders.order_price, orders.purchase_date, customers.email, product_orders.qty, products.name
Table 1: orders
id  customer_id order_price purchase_date
1   1                   0.20    12/6/2011
2   2                   0.20    12/6/2011
3   1                   0.20    12/6/2011
4   1                   0.20    12/6/2011
5   1                   0.20    12/7/2011
6   3                   199.00  12/7/2011
7   4                   199.00  12/7/2011
8   5                   199.00  12/7/2011
9   6                   199.00  12/7/2011
10  7                   199.00  12/7/2011

Table 2 : customers
id  email                   name
1   aa@dealboard.com.au aa
2   bb@dealboard.com.au bb
3   cc@live.com.au          cc
4   dd@acgglobal.com    dd
5   ee.heinrich@det.nsw.edu.au  ee
6   ff@optusnet.com.au  ff
7   ssy@hotmail.com         ss

table 3: products
id  name
1   A Home Portable Laser Hair Remover
2   Ipad
3   android
4   Asus
5   s
6   10 inch Android
7   A Fabric Steamer Cleaner
8   A Magnetic Fly Screen Door
9   pillopw
10  LCD

table 4: product_orders
       id orders_id product_id qty
        1   1      1         1
        2   2      1         1
        3   3      1         1
        4   4      1         1
        5   5      2         1
        6   6      1         1
        7   7      1         1
        8   8      1         1
        9   9      1         1
        10  10     1         1

i wanna extract the all the order for the product id 1 or filter orders by product
please help me

A: sounds like you want to join across all tables:
select orders.id, orders.order_price, orders.purchase_date, customers.email,
    product_orders.qty, products.name from orders, customers, product_orders,
    products where
    orders.customer_id = customers.id and
    product_orders.order_id = orders.id and
    products.id = product_orders.product_id and
    products.id = 1

A: Test this-
SELECT product_orders.id, OC.order_price, OC.purchase_date, OC.email, product_orders.qty, products.name
FROM product_orders
LEFT JOIN
(SELECT orders.id as oid,orders.order_price,orders.purchase_date,customers.id as cid ,customers.email,customers.name
FROM orders
LEFT JOIN customers
ON orders.customer_id=cutomers.id) as OC
ON
product_orders.orders_id=OC.oid AND
product_orders.product_id=1
LEFT JOIN
products
ON
product_orders.product_id=products.name


text: Q: Is PPO good for episodic delayed reward problems The problem I have is episodic (with early stopping when agent reaches goal state or avoid state) and with delayed rewards (agent is rewarded +1 when goal state is reached and penalized -1 when avoid state state is reached). State space is continuous while action space is discrete. I found that DQN/DDQN/averaged DQN learn well (after I shape rewards with potential based function agent reaches goal state the first time in 200 episodes). However, the PPO-clip performance as in https://github.com/ChintanTrivedi/rl-bot-football learning is very slow (agent reaches goal state first time in 3000 episodes). Is it possible somehow to tune PPO-clip for episodic with early stopping and delayed rewards problems?


text:
Q: Soldermask bridge gap too small - PCBWAY I've got a PCB design which contains a chip that uses the QFN (7x7) package.
Because of the package size the pins are very close together and the pads are 0.2mm apart, which is smaller than the minimum gap for soldermask colors other than green at PCBWAY and JLCPCB.
They mentioned they can still go ahead with the manufacture and assembly, but I'm wondering are there any risks that things will go bad during the assembly process especially for larger volumes?
Have anyone encountered similar situations with PCBWAY and JLCPCB before and can share their experiences?

A: It's quite certain that this will cause problems in the long run. I would recommend several steps:

*

*check your footprint, maybe you can adjust the footprint a little to increase the solder mask bridge thickness to make it manufacturable for your PCB supplier.

*switch to a higher PCB quality tier at your supplier (if applicable). You pay more, but the precision of the manufacturing is increased. Check their capabilities list.

*switch to another PCB supplier. There are a lot of them out there, and most will not have any problems with that pitch of pins.


text:
Q: CUDA: using structures and classes inside device kernel is there a way to use inside global kernel:
1) Simple structures like:
Structure Pixel{
    float p;
 }

2) Classes with functions and overloaded operators (C++)
3) std:: vector?
Thanks

A: *

*Yes

*Yes

*No

In general, C++ support is spelled out in the programming guide:

For the host code, nvcc supports whatever part of the C++ ISO/IEC 14882:2003 specification the host c++ compiler supports.
For the device code, nvcc supports the features illustrated in Code Samples with some restrictions described in Restrictions; it does not support run time type information (RTTI), exception handling, and the C++ Standard Library.

There are many CUDA sample codes that demonstrate various C++ support/features, including overloading.
Thrust is a template library that allows usage of (thrust) vector containers with various forms of parallelization (including GPU acceleration).  Users of STL vector containers and algorithms will find thrust constructs familiar.  The quick start guide may be of interest.


text:
Q: Getting " when trying to replace a character in string I want to replace " from a string with ^.
String str = "hello \"there";
System.out.println(str);
String str1 = str.replaceAll("\"", "^");
System.out.println(str1);
String str2= str1.replaceAll("^", "\"");
System.out.println(str2);

and the output is :
hello "there
hello ^there
"hello ^there

why I am getting extra " in start of string and ^ in between string
I am expecting:
hello "there

A: the replaceAll() method consume a regex for the 1st argument.
the ^ in String str2= str1.replaceAll("^", "\""); will match the starting position within the string.
So if you want the ^ char, write \^
Hope this code can help:
String str2= str1.replaceAll("\\^", "\"");

A: Try using replace which doesnt use regex
String str2 = str1.replace("^", "\"");

A: ^ means start of a line in regex, you can add two \ before it:
 String str2= str1.replaceAll("\\^", "\"");

The first is used to escape for compiling, the second is used to escape for regex.

A: Since String::replaceAll consumes regular expression you need to convert your search and replacement strings into regular expressions first:
str.replaceAll(Pattern.quote("\""), Matcher.quoteReplacement("^"));

A: Why do you want to use replaceAll. Is there any specific reason ?
If you can use replace function then try below
String str2= str1.replace("^", "\"");


text:
Q: Want to add padding if the item is shown - jquery So, I have this jQuery snippet:
$("#rectangle").hide();
$("#toggle-rec").click(function () {
      $("#rectangle").toggle(2000);
});

It means that I have a rectnagle div in my site, and firstly I hide him. When someone clicks on button that with id #toggle-rec, the rectangle is displayed. In the next click the rectangle will disappear and so on.
But, I want to do that if the rectangle is shown, padding-left the whole website (except from the rectangle) 200 px (as the rectangle's width), so:
padding-left:200px;

But I still don't know how to do it. Of course that if the rectangle disappear, we should cancel the padding-left or something. Any suggestions?
Please note that all site except the rectangle is under wrapper div.
My HTML:

Some text on the rectangle...

<button id="toggle-rec">Toggle rectangle</button>

A: This should work. Please check demo

$("#rectangle").hide();
$("#toggle-rec").click(function () {
   $("#rectangle").toggle(2000).promise().done(function() {
     if($("#rectangle").css('display') == 'none')
     {
       $('body').removeClass('leftMargin');
     }
     else {
       $('body').addClass('leftMargin');
     }
   });
});
.leftMargin
{
  padding-left:200px;

}

Some text on the rectangle...

<button id="toggle-rec">Toggle rectangle</button>

A: You can just to use .toggleClass.
$("#rectangle").hide();
$("#toggle-rec").click(function () {
  $("#rectangle").toggle(1000);
  $("#wrapper").toggleClass("leftpadwrapper")
});

here's a fiddle: https://jsfiddle.net/0kswh693/4/
and this animates it
#wrapper{
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}

A: I am guessing you want something like this. With the info provided above, I can provide this solution.
$("#toggle-rec").click(function () {
 $("#rectangle").toggle(function(){
   if($('#rectangle').is(':visible')){
    $('body').css({'padding-left':'200px'})
   }
   else{
    $('body').css({'padding-left':0})
   }
 });
});

A:

$("#rectangle").hide();
$("#toggle-rec").click(function () {
       $("#rectangle").toggle(2000);
       if($("#rectangle").is(":visible"))
       {
          $("#wrapper").removeClass("body-left-padding");
       }
       else
       {
          $("#wrapper").addClass("body-left-padding");
       }
});
#rectangle
{
  background: black;
  height: 100px;
  width: 200px;
  color: #fff;
}
.body-left-padding
{
  padding-left: 200px;
}

    Some text on the rectangle...

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas consequat est magna, vel vehicula augue efficitur ac. Vestibulum imperdiet eros dolor, ac vulputate felis tempor hendrerit. Ut eleifend diam ligula, ut ullamcorper est laoreet non. Mauris blandit risus in mi elementum, in feugiat ligula aliquet. Ut consequat at dolor nec scelerisque. Nullam condimentum fringilla dui non maximus. Ut sit amet erat ac eros viverra porttitor. Cras lobortis eleifend lacus eu egestas. Aenean pellentesque, erat eu dignissim congue, neque mi semper mauris, et eleifend leo dolor nec mi. Vivamus et vehicula magna. Aenean sit amet tincidunt quam, quis dapibus nisi. Aenean suscipit sem enim, sit amet rutrum urna tincidunt eu.

    <button id="toggle-rec">Toggle rectangle</button>

A: Try this :
<!DOCTYPE html>

Some text on the rectangle...

<button id="toggle-rec">Toggle rectangle</button>


text:
Q: Why Are There Heartless In Kingdom Hearts 2? In the first game, you seal all the keyholes, beat Ansem, the end, right? In KH2, you seal more keyholes and defeat more heartless, why? Weren't the keyholes sealed and the heartless beaten?

A: Heartless in Kingdom Hearts II are released by Organization XIII.

With Roxas and Xion gone and Sora awakened, Organization XIII begin manipulating Sora into collecting hearts for Kingdom Hearts. They release Heartless into many worlds, forcing Sora to fight and defeat them (source)

Additionally, the keyholes that are being sealed are not the way the Heartless get in.

The Heartless invade worlds and search for their Keyholes. Upon discovering the Keyhole, the Heartless will enter it and eventually devour the world's heart.

So basically, the keyholes that are being sealed are simply to stop the Heartless from attacking the heart of the world.  Once the keyblade locks it, it is assumed that it cannot be re-opened.
This would bring the question of why Organization XIII was invading worlds that were locked out.  As Nobodies, their ultimate goal was to become whole by reclaiming their hearts via Kingdom Hearts.  The way they could get to Kingdom Hearts is to get more Hearts by defeating the Heartless.

Emblem Heartless defeated by the Keyblade give up the stolen heart, which causes it to return to the owner's original body. Heartless slain by another weapon return to darkness and eventually reconstitute elsewhere. However, in Kingdom Hearts II, the hearts went to Organization XIII, who captured the hearts within usually unseen dark corridors in the sky. (source)

Also interesting to note, keyholes were not closed in Kingdom Hearts II.

Instead of sealing the Keyhole of a world, Sora opens the world's Gate, which reveals a new path to a different world. Curiously, though several never-before-seen worlds appeared in Kingdom Hearts II, not one of them had their Keyholes sealed, mainly because after End of the World was destroyed, all worlds went back to what they used to be, and the newer worlds therefore had no reason to be sealed by a Keyblade (source)

A: If you listened to Yen Sid's explanation after the prologue, Sora wasn't sealing the Keyholes to a world's heart in KH2. He was opening passageways to other worlds because it was no longer possible to travel in the space between different worlds; the walls were up again.

A: Yen Sid Answers this question, The Thing is Yes the Key holes were sealed no the heartless weren't beaten they did however Prevent a higher amount of heartless being around but heartless are going to be around as darkness still lurks in the hearts of many overall I highly doubt you can truly wipe out all heartless


text:
Q: Thread safety of using reference of forEach loop in thread Suppose I have these codes:
for(File file : fileList) {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            final File fileInThread = file;
            // doing some tasks which may take 5 sec to execute
        }
    });
    thread.start();
}

What I want to know, is it thread-safe? Is there any possibility that, in first iteration, I am expecting the file of the first iteration, but it is initialized by a file of any other iteration of the loop? In that case, what can I do to handle this situation?
I need to send each file to a different thread. For each file, one thread will be created. Thanks in advance.
EDIT: I have read this thread as well... Enhanced 'for' loop and lambda expressions This question is totally different from my one.

A: Here's what happens on each iteration of your for(...) loop:

*

*The local variable file is assigned to refer to the next item in the given fileList.

*The lambda expression creates a new instance of an anonymous, Runnable class, and the lambda captures the value of the file variable.

*A new Thread() is created and started, using the anonymous Runnable object as its delegate.

On each subsequent iteration of the loop, a different instance of the anonymous class is created and each of those instances captures a different value of file.
When those threads run, each anonymous Runnable object, will have its own, distinct captured value for file.

The declaration, final File fileInThread = file; is not necessary.  When the run() method gets called for each of the different anonymous objects, file will refer to the captured value, which will be a different member of the list in each thread.
The final fileInThread variable will simply be another name for the same File instance that file refers to.  Again, different in each of the threads.

D'Oh! I said "lambda" in my description above, but the actual argument of the Thread() constructor is not a lambda expression. It's an instantiation of an anonymous inner class. Similar idea, but it uses an older, more verbose syntax.


text:
Q: can we set tabindex for textbox and other controls in javascript can we set tabindex for input and other html controls using javascript. I've seen this in .net. can we do the same in javascript?
Thanks

A: You can set tabindex for input all html-elements, in javascript:
[someElement].tabIndex = [number]

A: document.getElementById("id").tabIndex=3  (any number I have used 3 for example and put the id of the element at the place of id)


text:
Q: Android Picking Sound File Path - Full Path Not Returned I am trying to get the full path of a sound file on the SD card.
This launches sound picker - I then use the Play Music app to select a file
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_PICK);
    intent.setData(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(intent, RESULT_SOUNDPICKER);

On activity result I am trying to get the full path
case RESULT_SOUNDPICKER: {
    Log.d("TAG", "onActivityResult "+requestCode+" "+resultCode);
        if (resultCode == RESULT_OK)
        {
            Uri uri = data.getData();
            String filePath = uri.getPath();
            Log.d("TAG", "FilePath: "+filePath);

            // A song was picked.
            Log.d("TAG", "PickSongActivity.onActivityResult: "+data.getDataString());
        }
}

But this returns a path like
//media/external/audio/media/13085

Rather than a proper path of where the file is held.
I need to get the full path back as I then want to use it to play the file.
Thank you.
Solution
This method can be used to get the full path.
private String getRealPathFromURI(Uri contentUri) {
    String[] proj = { MediaStore.Images.Media.DATA };
    CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null);
    Cursor cursor = loader.loadInBackground();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

A:
I need to get the full path back as I then want to use it to play the file.

There may not be a path (as it does not have to be a file), let alone a path that you can reach (as the file does not have to be on storage that is accessible to you).
MediaPlayer can use a Uri directly, so I suggest going that route.


text:
Q: Where this polarization vector is coming from? When dealing with vector fields in his QFT book, Schwartz writes the classical field in terms of a basis which I don't know how he is getting.
He first introduces the Proca Lagrangian
$$\mathcal{L}=-\dfrac{1}{4}F_{\mu\nu}F^{\mu\nu}+\dfrac{1}{2}m^2A_\mu A^\mu.$$
The equations of motion are then $(\Box + m^2)A_\mu = 0$ and $\partial^\mu A_\mu = 0$.
He then says:

Let us now find explicit solutions to the equations of motion. We start by Fourier transforming our classical fields. Since $(\Box+m^2)A_\mu=0$, we can write any solution as
$$A_\mu(x)=\sum_i \int \dfrac{d^3 p}{(2\pi)^3}\tilde{a}_i(p)\epsilon^i_\mu(p) e^{ipx}, \quad p_0=\omega_p=\sqrt{|\mathbf{p}|^2+m^2}$$
for some basis vectors $\epsilon^i_\mu(p)$. For example, we could trivially take $i=1,2,3,4$ and use four vectors $\epsilon^i_\mu(p)=\delta^i_\mu$ in this decomposition. Instead, we want a basis that forces $A_\mu$ to automatically satisfy also its equation of motion $\partial^\mu A_\mu=0$. This will happen if $p^\mu \epsilon_\mu^i(p) =0$. For any fixed $4$-momentum $p^\mu$ with $p^2=m^2$, there are three independent solutions to this equation given by three $4$-vectors $\epsilon_\mu^i(p)$, necessarily $p^\mu$ dependent, which we call polarization vectors. Thus we only have to sum over $i=1,2,3$. We conventionally normalize the polarizations by $\epsilon_\mu^\ast \epsilon^\mu =-1$.

I don't understand this at all. Taking the Fourier transform of $\Box A_\mu + m^2 A_\mu = 0$ and denoting $\hat{A}_\mu$ the Fourier transform we have
$$A_\mu(x)=\int \dfrac{d^3 p}{(2\pi)^3} (a_\mu(p) e^{-ipx}+a_\mu^\ast(p)e^{ipx}).$$
This is done by taking the three-dimensional Fourier transform, getting the equation $\partial_t^2\hat{A}+\omega_p^2 \hat{A}=0$, realizing that $\hat{A}_\mu= a_\mu(p) e^{-i\omega_p t}+b_\mu(p) e^{i\omega_p t}$ and finally using the condition that $A_\mu$ is real so that $b_\mu(p)=a_\mu^\ast(-p)$ which leads directly to the formula above.
There is no $\epsilon^i_\mu(p)$ anywhere. Nor can I see why there should be. The sum has only two terms anyway.
So I'm really missing something here. How is this result properly derived?

A: You're almost there. Given
$$
A_\mu(x)=\int \dfrac{d^3 p}{(2\pi)^3} (a_\mu(p) e^{-ipx}+a_\mu^\dagger(p)e^{ipx}).
$$
you may pick any set of four linearly independent vectors $\{\epsilon_\mu^1,\epsilon_\mu^2,\epsilon_\mu^3,\epsilon_\mu^4\}$ and expand the $a_\mu$ in terms of them:
$$
a_\mu=\sum_{i=1}^4a_i \epsilon_\mu^i
$$
for some coefficients $a_i$. The "trivial basis" mentioned by S. is $\epsilon^i_\mu\equiv\delta^i_\mu$, in which case this expression becomes
$$
a_\mu=\sum_{i=1}^4a_i \delta_\mu^i=a_\mu
$$
i.e. the coefficients $a_i$ are just the cartesian components of $a_\mu$. In principle, this is a valid basis, but we can do better. For one thing, in this basis the transversality condition $p\cdot a=0$ is not immediate to implement.
If we choose a basis that changes with $p$, such that
$$
p\cdot\epsilon^1=p\cdot\epsilon^2=p\cdot\epsilon^3=0,\qquad \epsilon^4=p/m
$$
then we may write, as before,
$$
a_\mu=\sum_{i=1}^4a_i \epsilon_\mu^i
$$
but now the condition $p\cdot a$ is equivalent to $a_4=0$, so that in effect
$$
a_\mu=\sum_{i=1}^3a_i \epsilon_\mu^i
$$
With this,
$$
A_\mu(x)=\sum_{i=1}^3\int \dfrac{d^3 p}{(2\pi)^3} (a_i \epsilon_\mu^i e^{-ipx}+a^\dagger_i \epsilon_\mu^{i*} e^{ipx}).
$$
which is the final expression for a free Proca field.


text:
Q: Check if 2 array elements are equal and print yes if so, and no if it isn't for each check I want to check if 2 string elements in array are equal and print Yes if so, and no if the new string isn't inserted to array before. The problem is that I want if I inserted 6 elements, I want to print 6 Yes or No, but the number of Yes and No is not equal to the number of elements inserted.
class Program
{
    static void Main(string[] args)
    {
        int num = Convert.ToInt32(Console.ReadLine());
        string[] names = new string[num];

        for (int i = 0; i < names.Length; i++)
        {
            names[i] = Console.ReadLine();
        }

        for (int i = 0; i < names.Length; i++)
        {
            for (int j = i + 1; j < names.Length; j++)
            {
                if (names[i] == names[j])
                {
                    Console.WriteLine("Yes");
                }
                else
                    Console.WriteLine("No");
            }
        }
    }
}

A: Assuming you want "for each item in the list print yes/no if the item shows up more than once in the list":
 Console.Write(String.Join(",",
        names.Select(n => names.Count(x => x == n) > 1 ? "yes" : "no")));

The core part is to .Count how many times given string happens in the array.


text:
Q: Replace a item in string array I have a string array and want to replace a value from that array.
Example:
string[] stud = new[] {"1","12","Mark","M"};
string[] otherStud = new [] {"2","16","MarkMark","F"};

I want to replace the Mark with Tom, then Result should be
Result:
string[] stud = new [] {"1","12","Tom","M"};
string[] otherStud = new [] {"2","16","TomTom","F"};

please suggest any solutions.
Thanks

A: stud = stud.Select( s => s.Replace("Mark","Tom") ).ToArray();

A: string[] stud = { "1", "12", "Mark", "M", "2", "16", "MarkMark", "F" };
for (int i = 0; i < stud.Length; ++i)
     stud[i] = stud[i].Replace("Mark", "Tom");

A: string[] stud = {"1", "12", "Mark", "M"};
        for (int i = 0; i < stud.Count(); i++)
        {
            stud[i] = stud[i].Replace("Mark", "Tom");
        }

A: Use for and in loop use String.Replace. You should be able to figure out how it should look exacly. :)

A: you can traverse the string array using foreach and can replace the required string

A: stud.Select(x => x != "Mark" ? x : "Tom");


text:
Q: html images appearing in wrong places I am designing a bigcartel website and am receiving a weird browser-specific problem, on chrome, mozilla and some other browsers when on the website images on the products and the home page do not load correctly and are either slightly above or below where they should be. It is resolved by reloading a couple of times but obviously that isn't good. Here is the link to the website, and the source html replaces bigcartel variables so here is a whole .zip containing all page html and theme css.
https://mega.co.nz/#!aMoTEAwJ!CM6ZLyTMiY8YGWg3StH0xFNVNb89M2WTLkJ0khR-np8


text:
Q: Albumentations in Pytorch: Inconsistent Augmentation for multi-target datasets I'm using Pytorch and want to perform the data augmentation of my images with Albumentations. My dataset object has two different targets: 'blurry' and 'sharp'. Each instance of both targets needs to have identical changes. When I try to perform the data augmentation with a Dataset object like this:
class ApplyTransform(Dataset):
def __init__(self, dataset, transformation):
    self.dataset = dataset
    self.aug = transformation

def __len__(self):
    return (len(self.dataset))

def __getitem__(self, idx):
    sample, target = self.dataset[idx]['blurry'], self.dataset[idx]['sharp']
    transformedImgs = self.aug(image=sample, target_image=target)
    sample_aug, target_aug = transformedImgs["image"], transformedImgs["target_image"]
    return {'blurry': sample_aug, 'sharp': target_aug}

Unfortunately, I receive two images with two different augmentations:

When I try the same without a Dataset object, I receive two images with the identical application of augmentations. Does anybody know how to make it work with a dataset object?
Here is my augmentation pipeline:
augmentation_transform = A.Compose(
        [
        A.Resize(1024,1024, p=1),
        A.HorizontalFlip(p=0.25),
        A.Rotate(limit=(-45, 65)),
        A.VerticalFlip(p=0.24),
        A.RandomContrast(limit=0.3, p=0.15),
        A.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
        A.pytorch.transforms.ToTensorV2(always_apply=True, p=1.0)
        ],
        additional_targets={"target_image": "image"}
        )

A: You can stack your blurry and sharp images, apply your augmentation then unstack them


text:
Q: 1990s movie. Aliens infiltrating earth. Protagonist tries to stop them Was reading a book which described aliens with knees that bent backwards (like an ostrich) and I remembered a scene from a movie and wanted to identify it.
Its probably from the 90s. I believe aliens are infiltrating Earth and either trying to set up terraforming stations to convert the earth to be more to their liking, or setting up a communication device. (Pretty sure it was terraforming)
I am NOT talking about either of "V" or "Them"
The Protagonist is more or less alone (no one believes him when he tells them what is going on) trying to sabotage their plans, while they are trying to kill him. [Using his intelligence to stop them as opposed to picking up guns ever 10 minutes and killing them all]
The scene I remember:
At the end of the movie, they are fighting in a radio telescope tower. Similar to this.

The some of the aliens chasing him deploy an implosion grenade in the control room under the tower that creates a mini black hole effect that over 30 seconds gradually sucks everything nearby into it, destroying the building and dropping the dish down on to it. (The aliens dying in the collapse)
The protagonist has survived, and a 15(?) year old African-American neighbor who had been doing minor errands for him/asking "whats he doing", and was with him at the radio tower, turns out to have been an alien who has been spying on him. He then twists his legs around so his knees are backwards and runs off at 40mph.
In an earlier scene I remember the aliens had deployed one of the implosion grenades in the protagonist's house to suck up all the info/maps/charts he had collected on their activities so he had no evidence. (pretty sure it stripped the house bare, furniture and all.)

A: The movie is The Arrival (1996) with Charlie Sheen.

After astronomer Zane Zaminski (Charlie Sheen) discovers a radio transmission that originated from space, he tells his boss, Phil (Ron Silver), who ignores him. Zane is promptly fired, and decides to investigate the signal himself. When he discovers a return radio transmission from Mexico, he goes to explore. There he meets climate scientist Ilana Green (Lindsay Crouse), who is studying anomalies in gases in the area. Zane soon makes a shocking finding that puts him in great danger.


text:
Q: UNIX List files of in domain of file sizes I am looking for a way to get all the files in a directory (which is a variable) and then check to see if those files are in between two values for file size.
I have three arguments. A directory to analyze, a minimum value of file size and max value of file size.
I have successfully done this in a directory using:
find "$directory" -maxdepth 1 -size +"$a"c -size -"$b"c -printf %P
Only this prints all results on the same line. I have tried adding a \n at the end with no luck.
a is min value
b is max value
I'm hoping for an output of just the filenames on one line each and with their size next to them.
(I had to change some of the backticking in order for the code to display properly)
How can I format this the way that I need?

A: You can do it with find:
find "$directory" -size +"$a" -a -size -"$a"

You shouldn't parse ls, its output is not meant to be parseable.