text:
Q: How to convert these objects to array in typescript How can I convert a string to a Typescript array?. Please help me.
Look at the code:
private validateEmptyOption(): any {
    console.log("CHECKED")
    let isValid = true;
    this.currentForm.sections.forEach((section: Section) => {
        section.fields.forEach((field: Field) => {
            debugger
            if (field.type === 'select') {
                console.log(field)

                const emptyOptionSections = JSON.parse(field.property).emptyOptionSections;

                if ((emptyOptionSections !== undefined) && (emptyOptionSections == null)) {
                    alert('QAZWSX');
                    isValid = false;
                }
             }
        return isValid;
        });
    });
}

This is my Result in console. I want do this convert to array and looping it.

Expected Result : There should be a validation message to inform that select controller cannot be empty
Actual Result : Form can save without any validation

A: If you would use validateEmptyOption(): boolean you would get the hint, that your function does not return any value. The problem is your return statement if inside other functions thus not beeing return by the main one.
There is almost never a need to use any as a type with typescript. (Until you do very complicated things...)
function validateEmptyOption(): boolean {
    console.log("CHECKED")

    return this.currentForm.sections.every((section: Section) => {
        return section.fields.every((field: Field) => {
            debugger
            if (field.type !== 'select') {
                return false;
            }

            console.log(field)

            try {
                const emptyOptionSections = JSON.parse(field.property).emptyOptionSections;
                if ((emptyOptionSections !== undefined) && (emptyOptionSections == null)) {
                    alert('QAZWSX');
                    return false;
                }
            } catch (e) {
                return false;
            }

            return true
        });
    });
}

The every method is used to check if for every value inner function returns true.

A: Because your return statement was written in the wrong place.
Check your { } ( )


text:
Q: Image rotation relative to wrong (top right) point I am trying to place a rotated image onto a blank canvas.
This is the command i am using:
convert "(" -size 1000x1000 xc:transparent ")" "(" "img.jpg" -virtual-pixel white -rotate -10.75 ")" -geometry +136+148 -composite "overlay.png" -geometry +0+0 -composite out.png

I would expect the image to appear at +136+148 rotated around its center. However, it appears to be rotated around its upper right corner instead.
I confirmed this in Photoshop:
This is the resulting image (using slightly different size but same parameters as my example command given here):

The 4 lines are the guides that mark the coordinates that define where the image sits. As you can see, the image is rotated -10.75 degrees. And the rotation center is the upper right corner.
Here i select the box at the correct coordinates in Photoshop:

And here i rotate it after setting the rotation point to the top right:

As you can see, the selection now matches the image as it was calculated by my convert command.
I have tried dealing with this for many hours. I tried switching to +distort and -distort and what not, but there i simply get either a cropped image or another wrongly positioned bounding box.
I don't know how to address this problem. What am i doing wrong? How can i tell -rotate to rotate my image around its center, not around the top right corner (why top right anyway?).
Thank you for your help!

A:
Try using the offset geometry that aligns with the outer edges of your target area. That would be more along the red lines I've added here, not along the cyan lines in your example image.
Edited to add: For a method of finding the proper offset information to fill the hole and placing the image under the hole, see my other answer in this thread.

A: The default gravity for offsetting is the northwest corner or top-left corner. The geometry offset you are using moves the top left corner of the padded rotated image after its background has been added and not the top left corner of the where the Input gets rotated. So I think that may be why you are not getting the expected result. ImageMagick -rotate does rotate about its center, but it fills the background out to make a complete rectangular image that is the bounding rectangle about the rotated image.
In ImageMagick, a better approach to what you did would be to use -gravity center and align the center of the rotated input image with the center of the transparent region in the overlay image.
Alternately, measure the 4 corners of your transparent region in the overlay and 4 corners of the input image and do a perspective or affine distortion to align the two.
Here is how to do it in bash unix syntax.
over1="122,186"
over2="466,118"
over3="510,345"
over4="166,411"
WxH=`convert -ping "Image.jpg" -format "%wx%h" info:`
ww=`echo "$WxH" | cut -dx -f1`
hh=`echo "$WxH" | cut -dx -f2`
ww=$((ww-1))
hh=$((hh-1))
in1="0,0"
in2="$ww,0"
in3="$ww,$hh"
in4="0,$hh"
convert overlay.png \
\( Image.jpg -virtual-pixel none +distort Perspective \
"$in1 $over1  $in2 $over2  $in3 $over3  $in4 $over4" \) \
-layers merge +repage \
out.png

See https://imagemagick.org/Usage/distorts/#perspective

A: You can find the location of the cutout in your overlay image, then use that information to properly place your under image with a command like this...
convert overlay.png -background none \
   \( +clone -alpha extract -trim \
      -set option:offset +%[fx:page.x]+%[fx:page.y] +delete \) \
   \( image.jpg -rotate -10.7 -set page %[offset] \) \
   -set page %[fx:u.w]x%[fx:u.h] +swap -layers merge result.png

This makes use of the fact that the bounding box dimensions of the rotated input image are the same as the bounding box dimensions of the cutout of the transparent region in the overlay image.
That reads in the overlay, and inside parentheses it makes a clone of it, extracts the alpha channel, and trims the result to find the offset of the cutout. It saves the offset to a variable named "offset".
Then inside another set of parentheses it reads in the under image, rotates it the known -10.7 degrees, and uses that variable "offset" to set the paging offset on the rotated "image.jpg".
Then outside the parentheses it uses the width and height of the overlay to set the paging dimensions for the under image.
It finishes by swapping the order of the images to put the overlay on top, then merging the two layers to create the output.

A: Here is an alternate to GeeMack's excellent ImageMagick solution. This computes the center of the original input.jpg, and the center of the transparent region in the Overlay.png. Then it uses +distort SRT to translate and rotate the image before finally compositing with -layers merge.
convert Overlay.png \
\( +clone -alpha extract -trim -set option:center "%[fx:page.x+w/2],%[fx:page.y+h/2]" +delete \) \
\( Image.jpg -virtual-pixel none +distort SRT "%[fx:w/2],%[fx:h/2] 1 -10.7 %[center]" \) \
+swap -layers merge +repage result2.png

The second line is much line GeeMack's, but it computes the center of the transparent region's bounding box and saves that in the "center" argument and then deletes the trimmed image.
The third line computes the center of the Input.jpg image (before rotation). It then uses +distort SRT to translate from the input center, (scale=1) and rotate -10.7 and translate to the center of the transparent region's bounding box.
See https://imagemagick.org/Usage/distorts/#srt

redpajama_set_name: RedPajamaStackExchange


text:
Q: c++ how to read a cfg file more complex? I recently changed from c# to c++.
Ive been watching some tutorials on how to read a config file. I am probably asking it wrong, what I mean is:
I am making a program, but it's for multiple users. Every user will have his prefence on what will be in a textfile.
Example:
In my textfile ("items.txt"), i have default "ints" and configurable "ints".
10=5
90=2
50=9

In c#, if i remember correctly, i read all lines and if the line started with for example "10=", i splitted the text so my line would only be the configurable  int left and i can use that easly in my program, it was something like:
string[] lines = File.ReadAllLines(path);
string str;
foreach (string line in lines)
{
if (line.StartsWith("10"))
{
str = line.Split('=')[1];
//I have what i need (str);
}
}

I did that for everything that i needed. So, what's the best way to do this in c++?
ALSO: I need to get a specific line for them, so i can use them all later on in my program.
Thanks a lot in advance!

A: This code is a C++ equivalent of the C# code you posted. This code by itself will compile, of course you have to fill something in for path instead of an empty string. If you need this somewhere in a method instead of as a program on itself, abandon the int main() and return 0 of course. Reply to this if something is unclear. I tried to set it up the same way your C# code is structured, so you would understand everything.
#include <fstream>
#include <vector>
#include <string>

int main()
{
    std::string path = "";
    std::ifstream file(path); //open the file from path, might want to check file.fail()
    std::vector<std::string> lines;
    std::string line;
    while (file >> line)
        lines.push_back(line);

    std::string str;
    for (const std::string& line : lines)
    {
        if (line.substr(0, 2).compare("10") == 0)
        {
            size_t foundIdx = line.find('=');
            str = line.substr(foundIdx + 1);
        }
    }
    file.close();
    return 0;
}

A: Well in C++ we now use std::regex
For your case - I'd use the following:
#include <iostream>
#include <string>
#include <regex>
#include <iterator>

int main()
{
    // Simple config file
    std::string rules = "10=5\n  90=2\n50=9";

    std::regex single_rule_regex("[0-9]+\\=[0-9]+");
    std::regex single_rule_part_regex("[0-9]+");

    auto rules_begin = std::sregex_iterator(rules.begin(),
                                            rules.end(),
                                            single_rule_regex);
    auto rules_end = std::sregex_iterator();

    for (auto it = rules_begin; it != rules_end; ++it)
    {
        std::smatch rule_match = *it;
        std::string rule_str = rule_match.str();

        std::cout << rule_str << std::endl;

        // key=value
        auto parts = std::sregex_iterator(rule_str.begin(),
                                          rule_str.end(),
                                          single_rule_part_regex);
        std::string key = parts->str();
        std::string value = (++parts)->str();

        std::cout << key << " has " << value << std::endl;
    }
}

Output for the gives rules is:

10=5
  10 has 5
  90=2
  90 has 2
  50=9
  50 has 9

A: You have 3 things in your files:

*

*lines, which we can read with getline

*keys (the part of the line before =)

*values (the part after the =).
We can split the key and value by finding the = character.
So, you get something like:
std::ifstream file(path);
if (!file) {
    std::cerr << "unable to open " << path << std::endl;
    return false;
}

for (std::string line; getline(file, line); ) {
    auto pos = line.find('=');
    if (pos == line.end()) {
        std::cerr << "skipping invalid line '" << line << "'\n";
        continue;
    }
    auto key = line.substr(0, pos);
    auto val = line.substr(pos);
    // do something with key,val
}

If you want to convert the key and value strings above into int, you can use a std::stringstream to do the conversion, or use std::strtol.


text:
Q: how to pragmatically add a folder to an already present storage directory in laravel I have a controller that generates a folder for any user that registers with a laravel app. However, I'm also trying to add folders to their user directories in storage. For instance, if a user registers, they have in their directory folders for images, files, contacts, etc. How would I do this in Laravel 5.4?

A: The best way would be calling a function after creating the newly registered user (mostly after the User::create([..]); line). In the function you can call
Storage::makeDirectory("path/to/your/dir/".$user->name);

to create the wanted directory. If you want to add an image directory in the newly created folder, just use the same method again.
Storage::makeDirectory("path/to/your/dir/".$user->name."/img");

When you want to add a lot of subfolders, go for an array with the folder strings and a foreach loop.
$folders = ["/img","/files","/somethingElse"];
foreach($folders as $folder){
    Storage::makeDirectory("path/to/your/dir/" . $user->name . $folder);
}

A: Using a foreach loop with an array map did the trick. I now have all current folders inside the user directory in storage. Here is a sample of the code:
$folders = ['images', 'files', 'contacts'];

    foreach ($folders as $folder)
    {
        Storage::disk('public')->makeDirectory($data['name'] . '/' . $folder);
    }


text:
Q: Extract an elelment's property without repetitions from an array of objects, obtained from an API, in Vue 2 I have this array of objects working fine obtained from an API in mounted in Vue.
0:
author: (...)
genre: ("Rock")
poster: (...)
title: (...)
year: (...)

1:
author: (...)
genre: ("Pop")
poster: (...)
title: (...)
year: (...)

2:
author: (...)
genre: ("Jazz")
poster: (...)
title: (...)
year: (...)

3:
author: (...)
genre: ("Rock")
poster: (...)
title: (...)
year: (...)

4:
author: (...)
genre: ("Pop")
poster: (...)
title: (...)
year: (...)

5:
author: (...)
genre: ("Jazz")
poster: (...)
title: (...)
year: (...)

6:
author: (...)
genre: ("Rock")
poster: (...)
title: (...)
year: (...)

7:
author: (...)
genre: ("Pop")
poster: (...)
title: (...)
year: (...)

8:
author: (...)
genre: ("Jazz")
poster: (...)
title: (...)
year: (...)

9:
author: (...)
genre: ("Jazz")
poster: (...)
title: (...)
year: (...)

I have this <select> that I want to fill with the genre seen in the previous array, but without repetitions.

                Genre
                <select id="genre" name="genre">
                    <option value="">Seleziona</option>
                    <option v-for="(element, index) in cds" :value="cds.genre">{{ element.genre }}</option>
                </select>

The way I did in HTML prints every genre with repetitions, so my idea was to filter the original array to obtain a new one with only the three genres present once.
The problem is the original array populates itself after the filter, I've seen its console.log after the filter one, so I did this way to prevent this thing.
if (this.cds.length == 10) {
    const genres = this.cds.filter((element) => {
    return element.genre != element.genre;
}

So it starts to filter only when the original array contains 10 elements.
Outside of my if statement I've written:
this.genreArray = [...genres];
console.log('Genere', this.genreArray);

To obtain the genre of the element only when it's different and then I would have saved const genres inside an empty array in data, that is genreArray, to obtain the new array with the genres repeated once.
Where have I been wrong?

A: Your filter function is not correct. the element.genre != element.genre condition is always false because it is comparing the same element to itself each time.
you can do something like this:
if (this.cds.length == 10) {
    const genres = {};
    this.cds.forEach((element) => {
       if(!genres[element.genre]) {
          genres[element.genre] = element;
       }
    });
}
this.genreArray = Object.values(genres);


text:
Q: Registry management in C# I would like to delete the following node from the registry. How can I do it?
HKEY_CLASSES_ROOT\Wow6432Node\CLSID\{D9AC2148-5E15-48AD-A693-E48714592381}

I have this much:
string key = "D9AC2148-5E15-48AD-A693-E48714592381";
StringBuilder sb = new StringBuilder(key);
RegistryKey k = Registry.ClassesRoot.OpenSubKey("Wow6432Node\\CLSID", true);

How do I proceed?

A: You need to take into account registry redirection; that's the real issue here. On a 32-bit machine, the key you need doesn't have WoW6432Node in the path.
You are trying to delete
HKEY_CLASSES_ROOT\CLSID\{D9AC2148-5E15-48AD-A693-E48714592381}

from the 32-bit view of the registry. Microsoft is very clear that you should not hard code WoW6432Node in your applications:

Redirected keys are mapped to physical locations under Wow6432Node. For example, HKEY_LOCAL_MACHINE\Software is redirected to HKEY_LOCAL_MACHINE\Software\Wow6432Node. However, the physical location of redirected keys should be considered reserved by the system. Applications should not access a key's physical location directly, because this location may change.

So delete that key by calling
DeleteSubKey(@"HKEY_CLASSES_ROOT\CLSID\{D9AC2148-5E15-48AD-A693-E48714592381}")

But use the redirector to ensure that you operate on the 32-bit view of the registry.
In .NET you can achieve what you need in two ways.

*

*Target x86 and let redirection do the work for you.

*If you target x64 or AnyCPU, you need to use RegistryView.Registry32 (new in .NET 4) to open a 32-bit view of the registry. If you don't have .NET 4 then you have to P/Invoke.

A: You could use the DeleteSubKey method:
string key = "{D9AC2148-5E15-48AD-A693-E48714592381}";
Registry.ClassesRoot.DeleteSubKey(@"Wow6432Node\CLSID\" + key);


text:
Q: open the Treeview by clicking a button on grid Devextreme How can I get the data of the row where I click the button? I added a picture to make it more clear what I ve meant.
this is the code for adding datafields to gridtable
   @(Html.DevExtreme().DataGrid()
    .ID("RoleGroupTable")
    .DataSource(d => d.WebApi().Controller("UserRoleManagementApi").Key("RoleGroupId")
    .LoadAction("Get")
    .InsertAction("Post")
    .UpdateAction("Put")
    .DeleteAction("Delete"))

.Columns(c =>
{
          c.Add().DataField("TreeView").CellTemplate(@<text>
  @(Html.DevExtreme().Button().Text("Clickme").Icon("airplane").OnClick("btnclick").ID("expandtreeview")) </text>);

     c.Add().DataField("RoleGroupId");  /* CellTemplate("<input class=button1 type=button value=click me ng-click=test()>");*/
    c.Add().DataField("Name");
    c.Add().DataField("Description");
    c.Add().DataField("InsertionDate").DataType(GridColumnDataType.Date);
    c.Add().DataField("InsertedUserId");
    c.Add().DataField("UpdatedDate").DataType(GridColumnDataType.Date);
    c.Add().DataField("UpdatedUserId");
})

also some script to retrieve the data..
function btnclick(data) {
    console.log('btnclick(data)');
    console.log(data);

    var treeViewInstance = $('#RolesTreeView').dxTreeView('instance');
    //var itemElement = treeViewInstance.element().find("[data-item-id='" + args.itemData.RoleId + "'] > .dx-treeview-item").get(0);
    var itemElement = treeViewInstance.element().find("[data-item-id='10']  > .dx-treeview-item").get(0);
    treeViewInstance.expandItem(itemElement);
    treeViewInstance.selectItem(itemElement);
}

A: There are two possible ways to pass row data to a button click handler.
1. Implement a cell template as js function:
@(Html.DevExtreme().DataGrid()
     //...
     .Columns(c => {
        c.Add().DataField("CompanyName").CellTemplate(new JS("cellTemplate"));
        //...
     }
)

<script>
    function onButtonClick(cellInfo, evt) {
        //use the cellInfo argument here
    }

    function cellTemplate(cellElement, cellInfo) {
        cellElement.append(
            $("<div>").dxButton({
                text: "click me",
                onClick: onButtonClick.bind(this, cellInfo)
            })
        );
    }
</script>

2. Change context of button click handler:
@(Html.DevExtreme().DataGrid()
    //...
    .Columns(c => {
        c.Add().DataField("CompanyName").CellTemplate(@<text>
            @(Html.DevExtreme()
                .Button()
                .Text("Click me")
                .OnClick("onButtonClick.bind(this, arguments[0])"))
        </text>);
        //...
    })
)

<script>
    function onButtonClick(cellInfo, evt) {
        //use the cellInfo argument here
    }
</script>

Read more information about implementing templates in this article.


text:
Q: Java GUI JButtons don't work to add or clear isbn and author and window doesn't exit Sorry for such a generic question, but I can't figure out where I went wrong. The jbuttons: submit, clear and exit are not working. Do I need to place the actionListeners somewhere else?
Also, can someone check my code for submitAction() used with my submit button? It is almost the last method at the bottom. It should take the book info (isbn & author) submitted from user and save it to book object. I want to be able to search by isbn or author LATER so I need to make sure that the program will identify them separately within book. Thanks for your help in advance!
package library.presentation;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import library.domain.Book;

public class AddBooks extends JFrame {

    public static void main(String args[])
    {
        java.awt.EventQueue.invokeLater(() -> {
            new AddBooks().setVisible(true);
        });
    }

    private static final long serialVersionUID = 1L;

    private JPanel northPanel = new JPanel();           //north panel
    private JLabel northLabel = new JLabel("");            //north label

    private JPanel centerPanel = new JPanel();          //center panel
    private JPanel bookLabelPanel = new JPanel();           //internal in center panel
    private JLabel[] bookLabel = new JLabel[2];         //create array JLabel
    private String[] bookString = { //create String array
        " ISBN: ", " Author(s): "
    };

    private JPanel bookTextFieldPanel = new JPanel();           //create internal center panel
    private JTextField[] bookTextField = new JTextField[2];         //create array JTextField

    private JPanel submitButtonPanel = new JPanel();            //create internal center panel
    private JButton submitButton = new JButton("Submit");           //create submit button

    private JPanel southPanel = new JPanel();           //create south panel
    private JButton clearButton = new JButton("Clear");
    private JButton exitButton = new JButton("Exit");           //create exit button

    private Book book;          //create object from other class in actionlistener
    private String[] data;          //create string array to store data

    public boolean isCorrect()          //to check book information in text field
    {
        data = new String[2];
        for (int i = 0; i < bookLabel.length; i++) {
            if (!bookTextField[i].getText().equals("")) {
                data[i] = bookTextField[i].getText();
            }
            else {
                return false;
            }
        }
        return true;
    }

    public void setText()
    {
        int i = 0;
        bookTextField[i].setText(null);
    }

//constructor of addBooks
    public AddBooks()
    {
        super("Add Books");         //title - internal frame
        Container container = getContentPane();             //GUI components display area
        northPanel.setLayout(new FlowLayout(FlowLayout.CENTER));            //set layout
        northLabel.setFont(new Font("Book Antigua", Font.BOLD, 16));            //set font - north panel
        northPanel.add(northLabel);             //add label - north panel
        container.add("North", northPanel);             //add north panel to container

        centerPanel.setLayout(new BorderLayout());          //set layout
        centerPanel.setBorder(BorderFactory.createTitledBorder("Add a new book:"));         //set border panel
        bookLabelPanel.setLayout(new GridLayout(11, 1, 1, 1));          //set layout

        for (int i = 0; i < bookLabel.length; i++) {        // oop to add strings to labels, set font, add labels to panel
            bookLabelPanel.add(bookLabel[i] = new JLabel(bookString[i]));
            bookLabel[i].setFont(new Font("Book Antigua", Font.BOLD, 12));
        }

        centerPanel.add("West", bookLabelPanel);            //set layout
        bookTextFieldPanel.setLayout(new GridLayout(11, 1, 1, 1));          //set layout

        for (int i = 0; i < bookTextField.length; i++) {       //loop to add string to labels, set font, add labels to panel
            bookTextFieldPanel.add(bookTextField[i] = new JTextField(25));
            bookTextField[i].setFont(new Font("Book Antigua", Font.PLAIN, 12));
        }

        centerPanel.add("East", bookTextFieldPanel);            //set layout

        submitButtonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));          //set layout
        submitButton.setFont(new Font("Book Antigua", Font.BOLD, 12));          //set font
        submitButtonPanel.add(submitButton);            //add submit button
        centerPanel.add("South", submitButtonPanel);            //add submit button panel
        container.add("Center", centerPanel);       //add to container

        southPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));         //set layout
        exitButton.setFont(new Font("Book Antigua", Font.BOLD, 12));            //set font
        clearButton.setFont(new Font("Book Antigua", Font.BOLD, 12));            //set font
        southPanel.add(clearButton);         //add clear button
        southPanel.add(exitButton);         //add exit button
        southPanel.setBorder(BorderFactory.createEtchedBorder());       //set border
        container.add("South", southPanel);         //add to container

        setVisible(true);
        pack();

        submitButton.addActionListener(new ActionListener() {
            public void submitAction(java.awt.event.ActionEvent evt)
            {
                try {
                    String isbn = null;
                    String author = null;
                    int i = 0;
                    Book book = new Book(isbn, author);
                    book.setIsbn(bookTextField[i].getText());
                    book.setAuthor(bookTextField[i].getText());
                    book.setText(isbn + "" + author);
                    System.out.println("You have submitted a book! " + book.toString());
                    // Book -> BookMgr.storeBook;           //code to pass to BookMgr

                } catch (Exception e) {
                    System.out.println("Exception:" + e);
                }
            }

            @Override
            public void actionPerformed(ActionEvent e)
            {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        });

        clearButton.addActionListener(new ActionListener() {
            public void clearAction(java.awt.event.ActionEvent evt)
            {
                try {
                    setText();
                } catch (Exception e) {
                    System.out.println("Exception:" + e);
                }
            }

            @Override
            public void actionPerformed(ActionEvent e)
            {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        });

        exitButton.addActionListener(new ActionListener() {
            public void exitAction(java.awt.event.ActionEvent evt)
            {
                System.exit(0);
            }

            @Override
            public void actionPerformed(ActionEvent e)
            {
                throw new UnsupportedOperationException("Not supported yet.");
            }

        });

    }       //end of constructor
}       //end of class AddBooks

A: The methods exitAction, clearAction, or submitAction are never called. On a click, only a JButton's ActionListener's actionPerformed method will be called, as it serves as the callback function/observer function for the click event.
The solution here is easy though, have the corresponding actionPerformed method simply call one of the three methods you created. In addition, it would probably would be best to move the three methods outside the ActionListeners and into AddBooks as they operate on AddBooks data.
@Override
public void actionPerformed(ActionEvent e)
{
    submitAction(); // doesn't look like ActionEvent needs to be a parameter.
}


text:
Q: Same hashing algorithm in Java and Swift gives different result I am new to iOS and Swift and I am using HMACSHA256 algorithm in Java as well as Swift. However, for same input values I am getting different result. I am not sure why.
This is my Java Code
 byte[] secret = new byte[] {0, 0, 0, 0, 38, 8, 117, -119};
 byte[] message = new byte[] {5, 96, 98, 37, 5, -110, 99, 2, -125,
 88, 55};

 Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
 SecretKeySpec secret_key = new SecretKeySpec(secret,
"HmacSHA256");
 sha256_HMAC.init(secret_key);

 String hash =
Base64.encodeBase64String(sha256_HMAC.doFinal(message));
 System.out.println(hash);

This is my Swift Code
func hmac(algorithm: CryptoAlgorithm, key: String) -> String {

        let str = self.cString(using: String.Encoding.utf8)
        let strLen = Int(self.lengthOfBytes(using:
String.Encoding.utf8))
        let digestLen = algorithm.digestLength
        let result =
UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        let keyStr = key.cString(using: String.Encoding.utf8)
        let keyLen = Int(key.lengthOfBytes(using:
String.Encoding.utf8))

        CCHmac(algorithm.HMACAlgorithm, keyStr, keyLen, str,
strLen, result)

        let digest = stringFromResult(result: result, length:
digestLen)

        //result.deallocate(capacity: digestLen)
        result.deallocate()
        return digest

    }

     private func stringFromResult(result:
UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {

        let hash = NSMutableString()

        for i in 0..<length {

            hash.appendFormat("%02x", result[i])

        }

    return String(hash).lowercased()

}

The input to both functions are same
byte[] secret = new byte[] {0, 0, 0, 0, 38, 8, 117, -119};
byte[] message = new byte[] {5, 96, 98, 37, 5, -110, 99, 2, -125, 88, 55};

Below is the result I am expecting
Exact result in byte array [-18, -12, 79, 109, 84, 107, 37, 114, 80, 22, 83, 18, 126, -123, -73, -38, 120, -79, 49, 87, -109, -30, -103, -17, -87, 69, 117, 3, -89, 36, -46, 108]

Result in String - 7vRPbVRrJXJQFlMSfoW32nixMVeT4pnvqUV1A6ck0mw=


text:
Q: Connect IBM Conversation to Watson Workspace? Using Watson Workspace, I would like to talk to the bot I've built using IBM Conversation.
To do so, I tried to adapt the code from a watsonwork demo: https://github.com/watsonwork/watsonwork-echo (This demo shows how to connect an app to the Watson Workspace and echoes every 'Hello' that is written there.)
Now, instead of echoing a message, I would like to feed the message into Conversation and write back that answer into the Watson Workspace.
I assume this should be quite easy by changing the app.js at lines 32-44 to something like
var context = {};
conversation.message({
  workspace_id: 'workspace-id',
  input: {'text': 'Turn on the lights'},
  context: context
  },  function(err, response) {
    if (err)
      console.log('error:', err);
   else
      console.log(JSON.stringify(response, null, 2));
});

API Reference: https://www.ibm.com/watson/developercloud/conversation/api/v1/#send_message
(And of course the authentication at the top of the file).
But this doesn't seem to work; I was not able to connect to the Conversation bot. Has anyone been doing something similar or might know what I'm doing wrong?
Thanks!!

A: I'm not sure, but, for some explanation I need the error when you try use your workspace with this repository. But, In this case you need to set your Service Credentials inside username and password variables, and not only the Workspace_id, because every Watson service created inside your IBM Bluemix have Services Credentials, but you can also see if you click inside the service this option.
But, I really recommend the official example from IBM developers: conversation-simple
In this example you can easy set your credentials and use the project to test your conversation created (with the workspace_id), is a complete project.
And you can follow the same steps to built your app. I did.


text:
Q: Problems Linking boost log 1_60 with MinGw on Windows 7 On upgrading to boost 1.60.0 some applications are failing to link with boost log when built with MinGw 4.9.2 on Windows 7.
I get the following linker errors:
undefined reference to `_imp___ZN5boost3log9v2_mt_nt67trivial6logger3getEv'
undefined reference to `_imp___ZN5boost3log9v2_mt_nt63aux15stream_providerIcE17allocate_compoundERNS1_6recordE'
undefined reference to `_imp___ZN5boost3log9v2_mt_nt63aux25unhandled_exception_countEv'
undefined reference to `_imp___ZN5boost3log9v2_mt_nt611record_view11public_data7destroyEPKS3_'
bad reloc address 0x1 in section `.text$_ZNK5boost4asio5error6detail13misc_category4nameEv[__ZNK5boost4asio5error6detail13misc_category4nameEv]'

Note: BOOST_LOG_DYN_LINK is defined:
g++ -c -pipe -fno-keep-inline-dllexport -Wall -Wextra -Wpedantic -Ofast -std=c++1y -frtti -fexceptions -mthreads -DUNICODE -DLOGGING_ENABLED -DNTDDI_VERSION=NTDDI_WIN7 -D_WIN32_WINNT=_WIN32_WINNT_WIN7 -DBOOST_THREAD_USE_LIB=1 -DBOOST_LOG_DYN_LINK=1

The boost 1.60.0 build log file shows that both boost log and boost log_setup built without any errors or warnings, including some of the files that it's failing to link with e.g.:
gcc.compile.c++ bin.v2\libs\log\build\gcc-mingw-4.9.2\release\threading-multi\trivial.o
gcc.compile.c++ bin.v2\libs\log\build\gcc-mingw-4.9.2\release\threading-multi\unhandled_exception_count.o

The applications link OK using boost 1.59.0 with MinGw 4.9.2 on Windows 7 and also link OK using boost 1.60.0 with gcc 5.1.1 on Fedora 23.
boost asio hasn't changed since boost 1.58.0. So what's changed in boost log between boost 1.59.0 and boost 1.60.0 to cause MinGw linking to fail on Windows?

A: Boost.Log was probably built with different options than your application, so it has a differently named version namespace. Have a look at the exported symbols with Dependency Walker and see the description. I suspect, the difference will be in the OS API component of the namespace, as the setup of the target Windows version has changed in 1.60. You're building your application for Windows 7 while Boost.Log is most likely built for Windows XP.
When you identify the difference, you have to correct Boost building options and rebuild Boost. E.g. to set target Windows version to 7 define BOOST_USE_WINAPI_VERSION to 0x0601. If you don't want to change Windows version Boost is targeted for, you can define BOOST_USE_WINAPI_VERSION to 0x0501 while building your application, indicating that you want Boost to keep targeting XP even though your application is targeting 7.


text:
Q: How create directory with permissions for temporary file downloads on IIS that survives visual studio publish This is probably a fairly trivial question
Is there a way to make a temporary directory (with appropriate permissions) so my MVC applications can generate/create temporary files for the user to download
var tempfolder = Server.MapPath(@"~/Temp");
var tempName = String.Format("{0}-{1}.xlsx", client.Name, DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss"));
Directory.CreateDirectory(tempfolder);

I get an access denied error from the proceeding code (probably for good reason)
I can of course create that directory manually under IIS and give the appropriate permissions to the appPool. However the directory doesn't survive a publish from visual studio
Whats the common (best practice) approach to solve this problem
Thanks

A: It seems the easiest way to achieve this is by creating a directory in the solution and adding a dummy file, publish, then change the permissions on the directory in question
This should all survive a republish


text:
Q: chrome extension content script removeEventListener not working I am new to programming and chrome extensions. I am not able to remove event listener from content script in my google extension.
AddeventListener is working and myFunc is called. myFunc is also getting called on removeEventListener.
It may be a trivial issue but I am not able to figure out. Thank you in advance for your help.
testScript.js:
chrome.storage.sync.get('isOn',function(data) {
    var isOn =data.isOn;

    console.log('TESTSCRIPT:ACTIVATED, isOn: ' +isOn);
    if(isOn){
        console.log('add Event Listener');
        document.addEventListener('mouseup',myFunc);
    }
    else{
        console.log('remove Event Listener');
        document.removeEventListener('mouseup',myFunc);
    }
});

function myFunc(){
    console.log('my func activated');
}

Background.js:
chrome.browserAction.onClicked.addListener(function (tab) {
    chrome.storage.sync.get('isOn',function(data){
        var isOn =data.isOn;
        console.log('value of isOn' ,isOn);

        if (isOn){
            chrome.storage.sync.set({'isOn' : false},function() {
                    console.log('The isOn is set to false.');
                chrome.browserAction.setIcon({path: 'boy_off.png'});
            });

        }
        else{
            chrome.storage.sync.set({'isOn' : true},function() {
                chrome.browserAction.setIcon({path: 'boy.png'});

            });
        }
        chrome.tabs.executeScript(null,{
                    file:'testScript.js'
                });
    });

});

manifest.json
{
  "manifest_version":1,

  "name":"MyGC",
  "description":"This is chrome Extension",
  "version":"1.0",

  "browser_action":{
    "default_icon":"boy_off.png"
  },
  "background":{
    "scripts":["background.js"]

  },
  "permissions":[

    "activeTab",
    "tabs",
    "http://*/*",
    "https://*/*",

   ],

}

A: A function is an object.  Each time you execute the script on document, it redefines myFunc as a new function.  This new function is not the same as the old one, in the previous execution.  So, removeEventListener(... myFunc) won't work.
One way to make it work is executing the content script once, and sending messages to it from background.js so the content script still has myFunc value.
Another way I didn't try: define myFunc only once in a content script.  Then run as many times as you wish another content script that invokes it, but don't define it again.


text:
Q: Regular Expression to find entire link in string I have a regular expression in apex that is only grabbing part of the link I need in a string. I need it to grab the entire link.
Here is what im working with:
String myvar = 'this is an example http://test.com/testing/123654123%0A%0A%0A%';

String myvar1 = '(?:(?:(?:[a-z0-9]{3,9}:(?://)?)(?:[-;:&=+$,w]+@)?[a-z0-9.-]+|(?:www.|[-;:&=+$??,w]+@)[a-z0-9.-]+)((?:/[+~%/.w-]*)?\\??(?:[-+=&;%@.w]*)#?w*)?)';

            Pattern MyPattern = Pattern.compile(myvar1);

            Matcher MyMatcher = MyPattern.matcher(myvar);

            while (MyMatcher.find()) {
                System.debug(MyMatcher.group());
                Location = MyMatcher.group();
        }

This is only returning http://test.com/
I need http://test.com/testing/123654123
How can I modify the regular expression to provide the complete link?
I just need to modify my existing regex to accomplish this. How can keep as much of the regular expression im using as possible?
(?:(?:(?:[a-z0-9]{3,9}:(?://)?)(?:[-;:&=+$,w]+@)?[a-z0-9.-]+|(?:www.|[-;:&=+$??,w]+@)[a-z0-9.-]+)((?:/[+~%/.w-]*)?\\??(?:[-+=&;%@.w]*)#?w*)?)

A: Use this regex :
https?:\/\/[a-zA-Z0-9.\/-]*

Online demo http://regexr.com/3d7j7


text:
Q: MAC: Make a Hard drive mount on request only I am replacing my internal HDD with an SSD. I am going to mount the older 1TB HDD on a HDD Caddy in my laptop. However that will only be used for time machine backups and long term storage of files. Is there a way to mount the drive only on request. I think that would save energy as well as prolong the drive's life.

A: On my old Mac Pro I having 4 HDD inside and I having a loginhook script at launch to unmount somes drives (for the noise).
On my MacBook Pro I have a HDD on a caddy, I just let it sleeping.
Create a Shell script like
#!/bin/bash
diskutil umountDisk /Volumes/YourDriveName &

Test it
chmod +x yourloginhookscript.sh
./yourloginhookscript.sh

And install it as a LoginHook
sudo defaults write com.apple.loginwindow LoginHook "/Users/dragon/the/path/to/your/shell/script"

And next to remount your drive, on a terminal
diskutil list
diskutil mountDisk /dev/disk1

If you want to mount a network drive, I know that is not your question:
osascript -e 'mount volume \"afp://192.168.0.100/backup/\"' &>/dev/null &

You can also create a file in LaunchAgents to start your script.

A: This is the method I use.
Create a file /etc/fstab with the following contents.
# fstab
#
# Identifier  mount point  fs type  options1
#
UUID=3CA41C88-3E86-3A39-88CE-9379FF44B6A5 none hfs rw,noauto

The alphabet soup after the = sign can be found with diskutility.
Launch DiskUtility, select the volume, right click, More Information Universal ID
or on El Capitan, select the volume, then the Info button, top right, File System UUID.
FS tab needs the following ownership and permissions:
bash-3.2# ls -l /etc/fstab
-rw-r--r--  1 root  wheel  71 29 Aug  2011 /etc/fstab

To create the file try this:
sudo nano /etc/fstab

The noauto option causes it to not mount at boot.
In a terminal window type man fstab for other options
Source: Ask Different - How can I tell OSX NOT to mount some of the drives in my computer?
If you only need to mount the drive occasionally, you can mount from Disk Utility. It will not re-mount at next boot, or you can unmount manually the same way.


text:
Q: A bounded non Riemann integrable real function with set of discontinuity of empty interior Is possible to construct a bounded non Riemann integrable real function such that the set of discontinuity points has empty interior?
I know that if the set of discontinuity points is a null set then the answer is no. Every null set has empty interior but the converse is not true.

A: Certainly. Say $K$ is a "fat Cantor set". So in particular $K$ is compact, has empty interior and positive Lebesgue measure.
Now define, for example, $$ f(x) = \begin{cases}
0,&(x \in K),
\\\sin(1 / (1+d(x,K))),&(x\notin K).
\end{cases}$$Then $f$ is discontinuous precisely on $K$ (and hence $f$ is not Riemann integrable, since $K$ is not a null set).

Note This is fairly stupid; as zhw points out we could simply let $f=\chi_K$ (that is, $f(t)=1$ for $t\in K$, $0$ for $t\notin K$). Replacing my stupidity with his non-stupidity seems like cheating, so I'll leave the above as it is.


text:
Q: How can I DRY up code in my MVC Editor Templates? Over time I have created a bunch of handy custom attributes for my editor templates.
But accessing their values in each template has started to clog them with a load of repeated code.
I am considering creating a Model for the required properties. Then instantiating it in the template, like this:
var editorTemplatePropertySet = new EditorTemplatePropertySet(ViewData, ModelMetadata)

My questions:

*

*What are common approaches to managing code in Editor Templates?

*Are there any existing resources covering this issue? I haven't been able to find any

*Is it bad smell to have so much code in there?

Example Editor Template:
It's the code at the top that is repeated in most templates.
@model decimal?

@{
    var displayName = ModelMetadata.FromLambdaExpression(x => x, ViewData).DisplayName;
    var displayDescription = ModelMetadata.FromLambdaExpression(x => x, ViewData).Description;

    var placeholderAttribute = ModelMetadata.FromLambdaExpression(x => x, ViewData).GetPropertyAttribute<PlaceholderTextAttribute>();
    string placeholderText = (placeholderAttribute == null ? "" : placeholderAttribute.Text);

    var importantInformationAttribute = ModelMetadata.FromLambdaExpression(x => x, ViewData).GetPropertyAttribute<ImportantInformationAttribute>();
    string importantInformationText = (importantInformationAttribute == null ? "" : importantInformationAttribute.Information);

    var inputGroupAddonAttribute = ModelMetadata.FromLambdaExpression(x => x, ViewData).GetPropertyAttribute<InputGroupAddonAttribute>();
    string inputGroupIconClasses = (inputGroupAddonAttribute == null ? "" : inputGroupAddonAttribute.IconClasses);
    string inputGroupText = (inputGroupAddonAttribute == null ? "" : inputGroupAddonAttribute.Text);
    bool isInputGroup = !(string.IsNullOrWhiteSpace(inputGroupIconClasses) && string.IsNullOrWhiteSpace(inputGroupText));

    var htmlAttributesFromView = ViewData["htmlAttributes"] ?? new { };
    var defaultAttributesForEditorType = ViewBag.ClearTextField == true ? new { @class = "form-control FormEditor__input clear-text-field input-block-level" } : new { @class = "form-control input-block-level" };
    var htmlAttributes = Html.MergeHtmlAttributes(htmlAttributesFromView, defaultAttributesForEditorType);
}

    @Html.LabelFor(x => x, new { @class = "control-label FormEditor__label" })

    @if (!String.IsNullOrEmpty(importantInformationText))
    {

@Html.Raw(importantInformationText)

    }

        @if (!string.IsNullOrEmpty(inputGroupIconClasses))
        {

        }
        else if (!string.IsNullOrEmpty(inputGroupText))
        {
            @inputGroupText
        }

        @Html.TextBox(
            "",
            Model == null ? "" : String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:F2}", ViewData.ModelMetadata.Model),
            htmlAttributes)

    @if (!String.IsNullOrEmpty(displayDescription))
    {

@Html.Raw(displayDescription)

    }
    @Html.ValidationMessageFor(x => x, null, new { @class = "FormEditor__validation-message" })

Update - Final Code
This is the code I ended up using - the dataset class:
public class EditorTemplateDataset
{
    public string DisplayName { get; set; }
    public string DisplayDecription { get; set; }
    public string Placeholder { get; set; }
    public string ImportantInformation { get; set; }
    public InputGroupAddonType InputGroupAddonType { get; set; }
    public string InputGroupAddonValue { get; set; }
}

public enum InputGroupAddonType
{
    None,
    Icon,
    Text
}

With an extension method:
public static class ModelMetadataExtensionMethods
{
    public static EditorTemplateDataset ToEditorTemplateDataset(this ModelMetadata source)
    {
        var dataset = new EditorTemplateDataset();

        dataset.DisplayName = source.DisplayName;
        dataset.DisplayDecription = source.Description;

        var placeholderAttribute = source.GetPropertyAttribute<PlaceholderTextAttribute>();
        dataset.Placeholder = (placeholderAttribute == null ? string.Empty : placeholderAttribute.Text);

        var importantInformationAttribute = source.GetPropertyAttribute<ImportantInformationAttribute>();
        dataset.ImportantInformation = (importantInformationAttribute == null ? string.Empty : importantInformationAttribute.Information);

        var inputGroupAddonAttribute = source.GetPropertyAttribute<InputGroupAddonAttribute>();
        if (inputGroupAddonAttribute == null)
        {
            dataset.InputGroupAddonType = InputGroupAddonType.None;
            dataset.InputGroupAddonValue = string.Empty;
        }
        else
        {
            dataset.InputGroupAddonType = inputGroupAddonAttribute.Type;
            dataset.InputGroupAddonValue = inputGroupAddonAttribute.Value;
        }

        return dataset;
    }

    public static T GetPropertyAttribute<T>(this ModelMetadata source)
        where T : Attribute
    {
        var result = source.ContainerType
          .GetProperty(source.PropertyName)
          .GetCustomAttributes(typeof(T), false)
          .Select(a => a as T)
          .FirstOrDefault(a => a != null);

        return result;
    }
}

Letting me use it like this in the editor templates:
@model decimal?

@{
    var modelMetadata = ModelMetadata.FromLambdaExpression(x => x, ViewData);
    var etDataset = modelMetadata.ToEditorTemplateDataset();

    var htmlAttributesFromView = ViewData["htmlAttributes"] ?? new { };
    var defaultAttributesForEditorType = ViewBag.ClearTextField == true ? new { @class = "form-control FormEditor__input clear-text-field input-block-level" } : new { @class = "form-control input-block-level" };
    var htmlAttributes = FP.WpBasic.Core.StaticHelpers.HtmlAttributeHelper.MergeHtmlAttributes(htmlAttributesFromView, defaultAttributesForEditorType);
}

    @Html.LabelFor(x => x, new { @class = "control-label FormEditor__label" })

    @if (!String.IsNullOrEmpty(etDataset.ImportantInformation))
    {

@Html.Raw(etDataset.ImportantInformation)

    }

        @if (etDataset.InputGroupAddonType == InputGroupAddonType.Icon)
        {

        }
        else if (etDataset.InputGroupAddonType == InputGroupAddonType.Text)
        {
            @etDataset.InputGroupAddonValue
        }

        @Html.TextBox(
            "",
            Model == null ? "" : String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:F2}", ViewData.ModelMetadata.Model),
            htmlAttributes)

    @if (!String.IsNullOrEmpty(etDataset.DisplayDecription))
    {

@Html.Raw(etDataset.DisplayDecription)

    }
    @Html.ValidationMessageFor(x => x, null, new { @class = "FormEditor__validation-message" })


text:
Q: Kernel and Jupyter errors after updating Spyder I am a newbie to Spyder/python and feel I have committed one of the most basic of errors. I updated Spyder in dev environment, and now have a whole host of errors in starting the kernel. Moreover, Jupyter does not work as the kernel is unable to start.
I am not sure whether I should have created a virtual environment before starting (duh im sure) but now am not able to get a kernel working in either Spyder or Jupyter.  Not sure if there is a way to reset or backtrack.
The command I ran in the Spyder ide was:
pip install --upgrade spyder
And the kernel error is:
        from pandas.core.computation.check import NUMEXPR_INSTALLED
        Traceback (most recent call last):
        File "C:\Users\farha\AppData\Roaming\Python\Python38\site‑packages\spyder_kernels\console\__main__.py", line 24, in
        start.main()
        File "C:\Users\farha\AppData\Roaming\Python\Python38\site‑packages\spyder_kernels\console\start.py", line 303, in main
        from ipykernel.kernelapp import IPKernelApp
        File "C:\Users\farha\AppData\Roaming\Python\Python38\site‑packages\ipykernel\kernelapp.py", line 42, in
        from traitlets.utils import filefind
        ImportError: cannot import name 'filefind' from 'traitlets.utils' (C:\Users\farha\anaconda3\lib\site‑packages\traitlets\utils\__init__.py)
        Traceback (most recent call last):
        File "C:\Users\farha\anaconda3\lib\runpy.py", line 194, in _run_module_as_main
        return _run_code(code, main_globals, None,
        File "C:\Users\farha\anaconda3\lib\runpy.py", line 87, in _run_code
        exec(code, run_globals)
        File "C:\Users\farha\AppData\Roaming\Python\Python38\site‑packages\spyder_kernels\console\__main__.py", line 24, in
        start.main()
        File "C:\Users\farha\AppData\Roaming\Python\Python38\site‑packages\spyder_kernels\console\start.py", line 303, in main
        from ipykernel.kernelapp import IPKernelApp
        File "C:\Users\farha\AppData\Roaming\Python\Python38\site‑packages\ipykernel\kernelapp.py", line 42, in
        from traitlets.utils import filefind
        ImportError: cannot import name 'filefind' from 'traitlets.utils' (C:\Users\farha\anaconda3\lib\site‑packages\traitlets\utils\__init__.py)


text:
Q: How to use build-helper-maven-plugin to create extra directory? I have a Java Maven project with the following structure. (This is a logical structure, not necessarily the exact directory structure.)
Project
|-Submodule
| |-src/main/java
| |-src/main/resources
| |-src/test/java
| |-src/test/resources
| `-pom.xml
`-pom.xml

In accordance with (my understanding of) Maven standards, the parent pom references the submodule in it's <modules> tag, and the submodule pom references the parent pom as it's <parent>.
Now, my goal is to use Maven to add two new source folders to the submodule, namely src/integrationTest/java and src/integrationTest/resources. I want Maven to "know about" these two folders so that I can execute the tests therein using my Maven testing plugin, maven-pmd-plugin. And I want Eclipse to "know about" these two folders so that they display correctly in Eclipse's graphical Project Explorer.
I was told that the build-helper-maven-plugin plugin could be used to create these additional directories that I needed. So I added the following configuration to my submodule pom:
<plugins>
    <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <executions>
            <execution>
                <id>add-integration-test-sources</id>
                <phase>generate-test-sources</phase>
                <goals>
                    <goal>add-test-source</goal>
                </goals>
                <configuration>
                    <sources>
                        <source>src/integration-test/java</source>
                    </sources>
                </configuration>
            </execution>
            <execution>
                <id>add-integration-test-resources</id>
                <phase>generate-test-resources</phase>
                <goals>
                    <goal>add-test-resource</goal>
                </goals>
                <configuration>
                    <resources>
                        <resource>
                            <directory>src/integration-test/resources</directory>
                        </resource>
                    </resources>
                </configuration>
            </execution>
        </executions>
    </plugin>
</plugins>

When I rebuilt the project, Maven didn't generate the directories I wanted. So I took the plugin configuration out of my submodule pom and put it in my parent pom instead. Maven still didn't generate my directories.
At this point, I don't know how to get this plugin working. I'm trying to follow other online tutorials, but I must be doing something wrong. Could anyone explain which pom file is intended to configure build-helper-maven-plugin? And how do I configure Eclipse to display the new Maven project structure correctly?
Thanks for the help!

A: khmarbaise's comment made me realize my mistake, although I didn't take his advice.
The build-helper-maven-plugin configuration should go in the submodule pom (not the parent pom) where I originally had it. But Maven will not create these directories for you, you create the directories and then Maven uses them.
Once Maven is using your new directories, Eclipse displays them just fine.


text:
Q: mysql - execute SELECT query only when TABLE EXIST I am working on a Joomla Module where images can be shown and be linked to a Joomla Article, Virtuemart product or an external link.
To have to option to select a Virtuemart Product, I added the following parameter to the module manifest xml:
<field
                    name="image_1_product"
                    type="sql"
                    default="10"
                    query="SELECT #__virtuemart_products.virtuemart_product_id, #__virtuemart_products_en_gb.product_name
                        FROM #__virtuemart_products, #__virtuemart_products_en_gb
                        WHERE #__virtuemart_products.virtuemart_product_id = #__virtuemart_products_en_gb.virtuemart_product_id
                        AND #__virtuemart_products.published = 1"
                    key_field="virtuemart_product_id"
                    value_field="product_name"
                    label="LABEL_PRODUCT"
                    description="DESC_PRODUCT">
                </field>

This works just fine, when Virtuemart is installed. When Virtuemart is not installed, you get an error 'Unknown column' - which makes sense.
Because this is a Module Manifest Option, I can use only 1 query. Is there a way to run a query that checks if a table exists before it executes the select? Like:
IF EXISTS TABLE `table_a` (SELECT * FROM table_a)

If so, can it return a row like:
| id | value                |
| 0  | Virtuemart not found |
Thank you!

A: I'm afraid its not possible with just single database query.
The only workaround that I can think of is to create a parameter helper for your module and use an addfieldpath to your module fieldset tag. With this solution you can write an method to do the query and create the output, then you can check if the table exists or not before creating your parameter.
for example:
<config>
    <fields name="params">
        <fieldset name="basic" addfieldpath="/modules/mod_mymodule/elements/">
            <field name="image_1_product" type="product" default="10" label="LABEL_PRODUCT" description="DESC_PRODUCT"/>
        </fieldset>
    </fields>
</config>

now in /modules/mod_mymodule/elements/ create a PHP file named product.php and write your custom query and field descriptions as described in Joomla's documentation.
Joomla documentation is available for Custom parameter types and Creating custom template parameter types


text:
Q: Formview Mode Change - Scroll to the top of page So once I submit a asp.net formview in insert mode, I am changing it back to 'Read Onlymode, to display user entered information. The issue I am facing is the page does not scroll to the top. I am using this javacript code, in theOnPreRender` function for the page, but nothing is happening.
Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
    'To check, if form is in ReadOnly After Recent Save Event
    If fmvExerciseRequestForm.CurrentMode = FormViewMode.ReadOnly AndAlso CurrentFormID > 0 Then
        InsertForm.Visible = False
        EditForm.Visible = True
        UserInfo.Visible = False
        ItemInfo.Visible = True
        LoadEditPage()
        Dim script As String = String.Empty
        script = "<script type=""text/javascript"" id=""ScrollScript"">window.scrollTo(0, 0);</script>"
        If (Not Page.ClientScript.IsStartupScriptRegistered("ScrollScript")) Then
            ScriptManager.RegisterStartupScript(Me, Me.GetType(), "ScrollScript", script, False)
        End If
    End If
End Sub

Please let me know, how can I scroll the page to top?
Why my script is not working?


text:
Q: Windows 10 scaling keeps changing During a typical day I move from my desk to meeting rooms and back several times a day. Every time I dock or un-dock the scaling of apps will change and the fonts and windows will become large. If I go into display settings the scaling will show as 100% although everything looks like it is set to 125%. I can resolve it by setting it to 125% and then back to 100%. This is annoying and sometimes causes long delays and apps to crash. It is also odd because all of my displays are Full HD 1920x1080 and I have always go them set at 100% scaling. I suspect the reason it does this is because the default scaling of the laptop monitor is 125% for a new windows install. I have set the scaling of all monitors to 100% more times than I can remember. When I do the change from 100 to 125 to 100 this mostly resolves the issue but some apps don't respond and keep the large settings making it difficult to work. Anyone have this issue?
Specs are:
Laptop screen: 15" 1920x1080
External screens: 2 x 24" 1920x1080

A: I have something similar to you; 3x 1920x1080 with 2x 24" and 1x 14" and I had the same symptoms.
The only way I managed to sort it was to use a custom font scaling size, instructions below:

*

*Open Control Panel > Display

*Under 'Change size of items' there is a paragraph of text with 'set a custom scaling level' as a hyperlink; click through to that

*I manually set a value of 120%, and the issue went away for me


text:
Q: PL/MySQL does it exist? In Oracle there is PL/SQL, a powerful imperative language. Is there anything similar for MySQL?

A: Terminology Problem
Some relational database vendors follow the traditional definition of SQL, which defines it as a declarative language. Examples of these vendors include PostgreSQL, IBM, Oracle. For these databases vendors you write procedural code in their own procedural languages they provide which may or may not make available SQL.
Some vendors though see their procedural language as an extension to SQL. These vendors don't have any such differentiation. For example, in MySQL a "Stored Program" is declared with LANGUAGE SQL even though it provides different language-features (like LEAVE, REPEAT and UNTIL that are not provided elsewhere). So you have essentially a different "SQL Language" in a "SQL Routine" then you have in a query expression. Other vendors like Microsoft call everything they do with just one term -- "T-SQL". This dropping of a term makes it hard to find equivalent features in other databases, or to know what features are likely to be different.
The procedural features being entirely standardized are likely to be different. While the declarative query syntax is likely to be similar because there is a spec on it.

A: I don't know how powerful they are, but this site gives information on writing MySQL stored procedures with SQL;
http://www.mysqltutorial.org/mysql-stored-procedure-tutorial.aspx
E.g.
http://www.mysqltutorial.org/sql-cursor-in-stored-procedures.aspx

A: No. pl/sql is a stored procedure language specific to Oracle. Different databases use different languages for stored procedures. See this page of the mySql documentation for their information on stored procedures.

A: While MySQL does have similar components, no, you cannot use PL\SQL in MySQL. The same goes for T-SQL used by MS SQL Server.
MySQL has plenty of documentation on it at their website.
You'll see that both PL\SQL and T-SQL are Turing-complete, and probably provide slightly more functionality. But MySQL has plenty of ways to perform similar tasks.
Here is the content from the Yahoo Answers post:

MySQL is a multithreaded, multi-user SQL database management system
(DBMS)1 which has, according to MySQL AB, more than 10 million
installations.
Libraries for accessing MySQL databases are available in all major
programming languages with language-specific APIs. In addition, an
ODBC interface called MyODBC allows additional programming languages
that support the ODBC interface to communicate with a MySQL database,
such as ASP or Coldfusion. The MySQL server and official libraries are
mostly implemented in ANSI C.
MySQL is popular for web applications and acts as the database
component of the LAMP, MAMP, and WAMP platforms
(Linux/Mac/Windows-Apache-MySQL-PHP/Perl... and for open-source bug
tracking tools like Bugzilla. Its popularity as a web application is
closely tied to the popularity of PHP, which is often combined with
MySQL. PHP and MySQL are essential components for running the popular
WordPress blogging platform.
The following features are implemented by MySQL but not by some other
RDBMSes:

*

*Multiple storage engines, allowing you to choose the one which is most effective for each table in the application (in MySQL 5.0,
storage engines must be compiled in; in MySQL 5.1, storage engines can
be dynamically loaded at run time):  o Native storage engines (MyISAM,
Falcon, Merge, Memory (heap), Federated, Archive, CSV, Blackhole,
Cluster)
-Partner-developed storage engines (InnoDB, solidDB, NitroEDB, BrightHouse)
-Community-developed storage engines

*

*Custom storage engines

*

*Commit grouping, gathering multiple transactions from multiple connections together to increase the number of commits per second.

Note:: MySQL is written in C and C++. The SQL parser uses yacc and
home-brewed lexer. A document describing some of the internal
structures of the code and the coding guidelines is available from the
MySQL web site.
SQL

SQL commonly expanded as Structured Query Language, is a computer
language designed for the retrieval and management of data in
relational database management systems, database schema creation and
modification, and database object access control management.
The SQL language is sub-divided into several language elements,
including:

*

*Statements which may have a persistent effect on schemas and data, or which may control transactions, program flow, connections,
sessions, or diagnostics.

*Queries which retrieve data based on specific criteria.

*Expressions which can produce either scalar values or tables consisting of columns and rows of data.

*Predicates which specify conditions that can be evaluated to SQL three-valued logic (3VL) Boolean truth values and are commonly used to
limit the effects of statements and queries, or to change program
flow.

*Clauses which are (in some cases optional) constituent components of statements and queries

it works under..concept of  query  data manipulation  data defination
transaction control
The SQL:2003 standard makes minor modifications to all parts of
SQL:1999, and officially introduces a few new features such as:1

*

*XML-related features

*window functions

*the sequence generator, which allows standardized sequences

*two new column types: auto-generated values and identity-columns

*the new MERGE statement

*extensions to the CREATE TABLE statement, to allow "CREATE TABLE AS" and "CREATE TABLE LIKE"

*removal of the poorly-implemented "BIT" and "BIT VARYING" data types

PL/SQL

PL/SQL is Oracle Corporation's proprietary server-based procedural extension to
the SQL database language. (Some other SQL database management systems
offer languages similar to PL/SQL.) Its syntax strongly resembles that
of Ada.
PL/SQL supports variables, conditions, arrays, and exceptions.
Implementations from version 8 of the Oracle RDBMS onwards have
included features associated with object-orientation.
The underlying SQL functions as a declarative language. Standard
SQL—unlike some functional programming languages—does not require
implementations to convert tail calls to jumps. SQL does not readily
provide "first row" and "rest of table" accessors, and it cannot
easily perform some constructs such as loops. PL/SQL, however, as a
Turing-complete procedural language which fills in these gaps, allows
Oracle database developers to interface with the underlying relational
database in an imperative manner. SQL statements can make explicit
in-line calls to PL/SQL functions, or can cause PL/SQL triggers to
fire upon pre-defined Data Manipulation Language (DML) events.
PL/SQL stored procedures (functions, procedures, packages, and
triggers) which perform DML get compiled into an Oracle database: to
this extent their SQL code can undergo syntax-checking. Programmers
working in an Oracle database environment can construct PL/SQL blocks
of such functionality to serve as procedures, functions; or they can
write in-line segments of PL/SQL within SQL*Plus scripts.
While programmers can readily incorporate SQL DML statements into
PL/SQL (as cursor definitions, for example, or using the SELECT ...
INTO syntax), Data Definition Language (DDL) statements such as CREATE
TABLE/DROP INDEX etc require the use of "Dynamic SQL". Earlier
versions of Oracle required the use of a complex built-in DBMS_SQL
package for Dynamic SQL where the system needed to explicitly parse
and execute an SQL statement. Later versions have included an EXECUTE
IMMEDIATE syntax called "Native Dynamic SQL" which considerably
simplifies matters. Any use of DDL in Oracle will result in an
implicit commit. Programmers can also use Dynamic SQL to execute DML
where they do not know the exact content of the statement in advance.
PL/SQL offers several pre-defined packages for specific purposes. Such
PL/SQL packages include:

*

*DBMS_OUTPUT - for output operations to non-database destinations

*DBMS_JOB - for running specific procedures/functions at a particular time (i.e. scheduling)

*DBMS_XPLAN - for formatting "Explain Plan" output

*DBMS_SESSION - provides access to SQL ALTER SESSION and SET ROLE statements, and other session information.

*DBMS_METADATA - for extracting meta data from the data dictionary (such as DDL statements)

*UTL_FILE - for reading and writing files on disk

*UTL_HTTP - for making requests to web servers from the database

*UTL_SMTP - for sending mail from the database (via an SMTP server)

Oracle Corporation customarily adds more packages and/or extends
package functionality with each successive release of the Oracle DBMS.

A: Google for "Getting started with mysql stored procedures", the syntax is not that far from PLSQL.
    DELIMITER //
    CREATE PROCEDURE GetAllProducts()
       BEGIN
       SELECT *  FROM products;
    END //
    DELIMITER ;


text:
Q: How can I set the 'markerStyle' to 'selected' in jVectorMap when the page opens? This is an example fiddle.
I am trying to have a marker already selected on the map as soon as the page loads.
is there a way to add the selected state defined in markerStyle to the markers:
var markerArray = [
    {name:'Houston', latLng:[29.761993,-95.369568]},
    {name:'New York', latLng:[40.710833,-74.002533]},
    {name:'Kansas City', latLng:[39.115145,-94.633484]}
];

A: You can use selectedMarkers options for that. For example the following snippet will make the first and the second markers to be selected on load:
selectedMarkers: [0,1]


text:
Q: Design pattern for graphical application using JFrame I've always coded my graphical applications in Java by extending the JFrame class like so:
public class CalculatorApp extends JFrame {
    // GUI components are declared as member variables of JFrame
    private final JLabel answerLabel;
    private final JButton sumButton;
    private final JButton divideButton;
    ...

    // Create and display the GUI
    public CalculatorApp() {
        setTitle("A Calculator");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ...

        // Initialize components
        answerLabel = new JLabel("Your answer will appear here");
        sumButton = new JButton("Sum");
        sumButton.addActionListener((ActionEvent e) -> {
            sum();
        });
        ...

        // Make visible
        pack();
        setVisible(true);
    }

    // Actions performed by the user; these methods have access to
    // the GUI components to grab the user input (eg. TextField.getText())
    // and then update the GUI with the result (eg. answerLabel.setText()).
    public void sum() {
        ...
    }
    public void divide() {
        ...
    }
    ...

    public static void main(String[] args) {
        new CalculatorApp();
    }
}

Although recently I've learned that this is not very good practice since you're putting your specific application's function into a JFrame - something that really shouldn't have the function of a calculator, for example. I've found that trying to create applications with more and more features with this approach leads to really horribly organized code because there's no line between GUI & input verification code, and the actual application's features.
So what's the best way to structure a program like this?
I've outlined the only sensible alternative I could think of below.
Handlers
This structure separates the function of the application from the GUI by putting the GUI nicely into its own little class that can be created and shown, but has the drawback of having to manage a lot of annoying handlers. The handlers are a way to give the application function to the GUI. This structure is also easier to convert to other JWindows like JDialog because the entire class hierarchy doesn't have to be changed.
public class CalculatorApp {
    // Create the GUI and pass it the handlers
    public CalculatorApp() {
        new CalculatorAppGUI(
            new SumHandlerImpl(),
            new DivideHandlerImpl(),
            ...
        ).show();
    }

    // All of the application function is in the handlers
    private class SumHandlerImpl() implements SumHandler {
        public double sum(double a, double b) {
            return a + b;
        }
    }
    private class DivideHandlerImpl() implements DivideHandler {
        public double divide(double a, double b) {
            return a / b;
        }
    }
    ...

    public static void main(String[] args) {
        new CalculatorApp();
    }
}

public class CalculatorAppGUI {
    // Handlers that perform application function are stored as member variables
    private final SumHandler sumHandler;
    private final DivideHandler divideHandler;

    // GUI components are declared as member variables
    private final JPanel mainPanel;
    private final JLabel answerLabel;
    private final JButton sumButton;
    private final JButton divideButton;
    ...

    public CalculatorAppGUI(SumHandler sumHandler, DivideHandler divideHandler) {
        // Store handlers
        this.sumHandler = sumHandler;
        this.divideHandler = divideHandler;

        // Initialize components
        mainPanel = new JPanel(new SomeLayoutManager());

        answerLabel = new JLabel("Your answer will appear here");
        sumButton = new JButton("Sum");
        sumButton.addActionListener((ActionEvent e) -> {
            double answer = sumHandler.sum(/* Values from GUI */);
            answerLabel.setText(String.valueOf(answer));
        });
        ...

        mainPanel.add(answerLabel);
    }

    // Create a frame for the GUI and display it
    public void show() {
        JFrame frame = new JFrame();
        frame.setTitle("A Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ...
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setVisible(true);
    }

    // Nested static handler interfaces
    @FunctionalInterface
    public static interface SumHandler {
        public double sum(double a, double b);
    }
    ...
}

The handlers in this case are very simple, but in a larger application they would be much more complicated operations like JoinGameHandler or whatnot. Here the application function and things like application state (connected to a game or not?) would be stored in the CalculatorApp class and all the GUI code would be in the CalculatorAppGUI class. The issue here is that a GUI with a lot of buttons and a lot of features leads to a lot of handlers which doesn't organize very well either (you could end up with a hundred handlers to store for a sufficiently complex application, which is just impractical).
In case it isn't already apparent, I'm 100% self-taught in the area of Java Swing and haven't really been exposed to the standards for this sort of stuff. All help appreciated.

A:
I am asking about program structure, not GUI design.

No single design pattern will solve all GUI design problems, but many well-known patterns recur in GUI design. Some common heuristics may be helpful:

*

*Use the model-view-controler and observer patterns as an aid to loose coupling; both patterns are examined here.

*Use Action to encapsulate functionality; among the several examples cited here, KeyPadPanel may be the most relevant.

*To manage copmplexity, use nested classes for ease in prototyping; as the need arises, inner classes can be promoted to separate classes having package-private access.


text:
Q: How to start dhclient at boot? Here's the problem:
root@home:~# ping 8.8.8.8
connect: Network is unreachable

root@home:~# dhclient eth0
RTNETLINK answers: File exists

root@home:~# ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_req=1 ttl=51 time=16.8 ms
64 bytes from 8.8.8.8: icmp_req=2 ttl=51 time=16.6 ms
^C
--- 8.8.8.8 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1002ms
rtt min/avg/max/mdev = 16.654/16.737/16.820/0.083 ms
root@home:~#

Network is working only after I manually invoke dhclient. I don't have NetworkManager (removed it). Here are relevant lines from /etc/network/interfaces:
auto eth0
iface eth0 inet dhcp

And here is startup log:
root@home:~# cat /var/log/syslog | grep dhclient
May 28 21:39:44 home kernel: [    7.237076] type=1400 audit(1369762781.497:2): apparmor="STATUS" operation="profile_load" name="/sbin/dhclient" pid=405 comm="apparmor_parser"
May 28 21:39:44 home kernel: [    7.238298] type=1400 audit(1369762781.497:4): apparmor="STATUS" operation="profile_load" name="/usr/lib/connman/scripts/dhclient-script" pid=405 comm="apparmor_parser"
May 28 21:39:45 home dhclient: DHCPDISCOVER on eth0 to 255.255.255.255 port 67 interval 8 (xid=0x79607e29)
May 28 21:39:45 home dhclient: DHCPREQUEST of 192.168.0.103 on eth0 to 255.255.255.255 port 67 (xid=0x79607e29)
May 28 21:39:45 home dhclient: DHCPOFFER of 192.168.0.103 from 192.168.0.1
May 28 21:39:45 home dhclient: DHCPACK of 192.168.0.103 from 192.168.0.1
May 28 21:39:45 home dhclient: bound to 192.168.0.103 -- renewal in 234779 seconds.
May 28 21:39:45 home kernel: [   11.695666] type=1400 audit(1369762785.953:10): apparmor="STATUS" operation="profile_replace" name="/sbin/dhclient" pid=1154 comm="apparmor_parser"
May 28 21:40:11 home dhclient: DHCPREQUEST of 192.168.0.103 on eth0 to 255.255.255.255 port 67 (xid=0x2aa61c47)
May 28 21:40:11 home dhclient: DHCPACK of 192.168.0.103 from 192.168.0.1
May 28 21:40:11 home dhclient: bound to 192.168.0.103 -- renewal in 243414 seconds.

Any ideas what may cause such problem?

A: As it seems its because the  /var/lib/dhcp3 or /var/run has not yet been mounted when
the DHCP client is started.
According to the ManPage of dhclient, try to specify the names and/or  locations  for these  files,  use  the  -cf,  -lf,  -pf  and  -sf flags, respectively,followed by the name of the file. (The DHCP  client  normally  gets  its  configuration  information  from
  /etc/dhcp3/dhclient.conf

,its       lease      database      from
  /var/lib/dhcp3/dhclient.leases

, stores its process ID in a file  called
   /var/run/dhclient.pid

and  configures  the  network  interface  using
   /sbin/dhclient-script


text:
Q: Best way to handle arg validation Is there any downside to validating args this way:
if x in [1,2,3]:
    ...

Or is it better to do the more traditional way:
if x == 1 or x == 2 or x == 3:
    ...

A: The only downside I could see is performance.
On my machine, windows 8.1, python 3.7.3, via ipython, I get:
x = 4

%timeit x in [1,2,3]
183 ns ± 19 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

%timeit x == 1 or x == 2 or x == 3
295 ns ± 19.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

So it seems both cleaner and faster.
FYI, using a set, I get:
%timeit x in {1,2,3}
116 ns ± 7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)


text:
Q: Trouble parsing array of objects returned from UrlFetchApp.fetch in Google App Script UrlFetchApp.fetch returns this arrav of objects I'm assigning to the variable results:
var results = [{"Category 1": "Benefits/Compensatio", "Category 2": "Compensation", "Category 3": "Recognizing You", "Processing Team": "myHR Tier 2 US CA"}];

To access the value of "Category 1" I'm using results[0]["Category 1"] which returns null. What am I missing? I can't figure out the right notation to access the key:value pairs in the zeroth object in the array.
Hopefully a simple answer and a dumb question.

A: I ran into the same issue and found a solution!
Add a line like var jsonObject = JSON.parse(response);
or this var jsonObject = JSON.parse(response.getContentText());
after your var results = ... line
Sources:

*

*https://learn.microsoft.com/en-us/advertising/scripts/examples/fetch-resources

*https://developers.google.com/apps-script/reference/url-fetch/http-response


text:
Q: MongoDB the difference between db.getCollection.find and db.tablename.find? What is the difference between:
db.getCollection('booking').find()

and
db.booking.find()

Are they exactly the same, or when should I use which one?
db.getCollection('booking').find({_id:"0J0DR"})

db.booking.find({_id:"0J0DR"})

A: Yes, they are exactly the same and you can use either.
The first form db.getCollection(collectionName).find() becomes handy when your collection name contains special characters that will otherwise render the other syntax redundant.
Example:
Suppose your collection has a name that begin with _ or matches a database shell method or has a space, then you can use db.getCollection("booking trips").find() or db["booking trips"].find() where doing db.booking trips.find() is impossible.

A: I prefer using db.collection() to either as it will work on nonexistent collections, which is particularly useful when for example creating the first user in a users collection that doesn't yet exist.
db.collection('users').findOneAndUpdate(...) // Won't throw even if the collection doesn't exist yet

A: In addition to the previous answers, on the shell, they might be exactly the same but in real IDE (like PyCharm), db.getCollection(collectionName) gives you back the whole doculment even with out the find() method.


text:
Q: Extending a closed DLL - by merging? I am currently faced with a problem of extending a library (dll) which is which is closed to the eventual user.
The library has a class:
 public partial Extender
 {
     ...
 }

which is nominally where the extension is intended to happen, but of course the eventual user cannot directly
replace this class with their own.
To test out an approach I have built a solution with 3 projects:
MainLibrary - a class library project, containing the code that is nominally closed to the eventual user. Contains:
    public partial Extender
    {
        ...
    }

code in this library instantiates and uses the Extender class which is to all intents and purposes empty.
ExtenderLibrary - a class library project, referencing MainLibrary, and containing:
    public partial Extender
    {
        ...
        //  contains methods that the eventual user wants to invoke
        ...
    }

I want this class to become the 'concrete implementation' of MainLibrary:Extender and operate just as if it was the 'original' class.
ConsoleApp - a console app which references MainLibrary and is intended to be the driver to
                 validate that I can call the methods in Extender
My current approach is based on the blog of Scott Hanselmann
, although in my case I dont have a mixed language scenario, basically trying to merge MainLibrary and ExtenderLibrary so
that the single merged form (of Extender via its partial kwd)
can be then addressed by the ConsolApp.
I have had no success in getting this merging approach to work.
Does anyone have some insights as to how I can achieve what I want here?


text:
Q: How to get keys from the following json
I am working with handsontable with a php backend. i am tring to dynamically create table column headers so I can create an array of column names which I can feed into handsontable using:
colHeaders: ['ID', 'First', 'Last Name', 'Address'],

I've included a sample of JSON produced at backend in the screenshot. How do I create get the keys so I can create the colHeaders array? i've tried:
 var keys = res.keys();

My load function is:
            $parent.find('button[name=load]').click(function () {
              $.ajax({
                url: "AjaxController/tableLoad/"+tablename,
                dataType: 'json',
                type: 'GET',
                success: function (res) {

                    var keys = res.keys();
                    console.log(keys);

                    // create js title array from 1st row data
//                      colHeaders: ['ID', 'First', 'Last Name', 'Address'],
//                      handsontable.colHeaders: keys;
                  handsontable.loadData(res);
                  $console.text('Data loaded');
                  console.log(res)
                },

A: For a valid JSON use Object.keys(object), to get its keys which returns an iterable object.
var keys = Object.keys(res);

A: You can use .map() to get the keys of an object as follows:
var keys = $.map(res, function(element,key) { return key; });

However for the sample you've provided, an array of objects, you would use the following:
var keys = $.map(res[0], function(element,key) { return key; });
//RESULT: ["id", "name", "description"]


text:
Q: How to change the message of an alert dialog when one of its button clicked? I have an AlertDialog with "Tell me more" and "OK" buttons, I want to change its message when user clicks on 'Tell me more' button and hide this button. How can I do this?
I have this code currently:
new AlertDialog
    .Builder(this)
    .setMessage("Initial message")
    .setNeutralButton("Tell me more", (dialog, which) -> {
        // change dialog's message to "Detailed message".
        // hide this "Tell me more" button
    })
    .setNegativeButton(android.R.string.ok, (dialog, which) -> dialog.dismiss())
    .show();

A: Instead of using the setMessage method you would have to create a custom layout for your dialog, with the buttons in the layout.
You would then set the click listeners to the buttons in your layout and update the text and the button visibility in the layout.
val binding = MyDialogBinding.inflate(/* todo */)
binding.button.setOnClickListener {
    binding.button.isVisible = false
    binding.textView.text = /* new text here */
}
new AlertDialog.Builder(this).setView(binding.root).show()

A: dont use AlertDialog, use Dialog.
or in your case, you can show other or new AlertDialog on button cliked
example in kotlin
fun showDialogWithButton() {
val dialog = Dialog(this)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setContentView(R.layout.dialog_layout)
dialog.setCanceledOnTouchOutside(true)
dialog.setCancelable(true)

val tvMess = dialog.findViewById(R.id.tv_body_dialog) as TextView
val btnOk = dialog.findViewById(R.id.btn_ok) as Button
var more = false
tvMess.text = "Initial message"
btnTell.text = "Tell me more"
btnOk.setOnClickListener {
if(!more)
{
        tvMess.text = "some thing more"
        btnOk.text = "OK"}
more = true
}else{
dialog.dismiss()
}

}
dialog.show()

}


text:
Q: Add AAAA record in Google Cloud DNS Hei guys so I got an issue on my website, it can't be accessed because the SSL certificate can't be renew and then when I do script for renew it give some error because the AAAA record. So I need to add AAAA record on my google cloud dns

To fix these errors, please make sure that your domain name was
     entered correctly and the DNS A/AAAA record(s) for that domain
     contain(s) the right IP address. Additionally, please check that
     your computer has a publicly routable IP address and that no
     firewalls are preventing the server from communicating with the
     client. If you're using the webroot plugin, you should also verify
     that you are serving files from the webroot path you provided.

My question is how to know ipv6 in my compute engine ? because I only knew my ipv4, please help me guys. thank you

A: Go to App Engine and Settings and you will see something like attached. This is where you find the AAAA records. You can use app engine or computer engine or kubernetes engine but custom domain settings remain in App Engine settings.As attached


text:
Q: numba: sorting an array in place Numba has the amazing ability to speed up loops with JIT compilation. The key twist, however, is that when using numpy, one isn't allowed to create any new arrays. Fortunately, most numpy functions include an optional out parameter for writing output to -- except numpy.sort. The most obvious alternative is numpy.ndarray.sort, which IS in place,
@njit("void(f8[:])")
def sort_inplace(arr):
  arr.sort()

but this fails to compile,
...
...
...
/Users/duckworthd/anaconda/lib/python2.7/site-packages/numba/typeinfer.pyc in propagate(self)
    293                 print("propagate".center(80, '-'))
    294             oldtoken = newtoken
--> 295             self.constrains.propagate(self.context, self.typevars)
    296             newtoken = self.get_state_token()
    297             if config.DEBUG:

/Users/duckworthd/anaconda/lib/python2.7/site-packages/numba/typeinfer.pyc in propagate(self, context, typevars)
    112                 raise
    113             except Exception as e:
--> 114                 raise TypingError("Internal error:\n%s" % e, constrain.loc)
    115
    116

TypingError: Internal error:
Attribute 'sort' of array(float64, 1d, A) is not typed

Short of re-implementing a sorting algorithm, is there a way to sort a numpy array in a JIT-compiled numba loop?

A: Numba should be able to compile this in "nopython" mode, but unfortunately we haven't added support for ndarray.sort() yet. It compiles in "python" mode though which is slower since it has to go through the python object layer, but since it looks like ndarray.sort() is implemented in C it may not make much of a difference. I went ahead and added a bug report in numba's github issue tracker.
Another thing to note is that numba will compile loops in nopython mode if possible while the rest of the function is compiled in python mode. This allows you to use unsupported functions like ndarray.sort(), and functions like numpy.arange() that create and return a new array, while still having fast compiled loops (as long as you're not calling ndarray.sort() or numpy.arange() inside your loops, but you probably don't want to do that anyway if performance is a big concern).
So to sum up: you may be able to get away with using the jit decorator instead of the njit decorator until numba properly supports calling ndarray.sort() in nopython mode, as long as you're not sorting arrays inside a loop.


text:
Q: Best way to escape javascript string? (json?) Using C# .net I am parsing some data with some partial html/javascript inside it (i dont know who made that decision) and i need to pull a link. The link looks like this
http:\/\/fc0.site.net\/fs50\/i\/2009\/name.jpg

It came from this which i assume is javascript and looks like json
"name":{"id":"589","src":"http:\/\/fc0.site.net\/fs50\/i\/2009\/name.jpg"}

But anyways how should i escape the first link so i get
    http://fc0.site.net/fs50/i/2009/name.jpg
In this case i could just replace '\' with '' since links dont contain \ nor " so i could do that but i am a fan of knowing the right solution and doing things properly. So how might i escape this. After looking at that link for a minute i thought is that valid? does java script or json escape / with \? It doesnt seem like it should?

A: In your case:
"name":{"id":"589","src":"http://fc0.site.net/fs50/i/2009/name.jpg"}

"/" is a valid escape sequence. However, it is not required that / be escaped. You may escape it if you need to. The reason JSON explicitly allows escaping of slash is because HTML does not allow a string in a  to contain "...

Update:

*

*Check out this post

A: Odd, it doesn't look like any JavaScript/JSON escaping you'd expect. You can have forward slashes in JavaScript strings just fine.

A: Why dont you try a regex on the escaped slashes to replace them in the C# code...
String url = @"http:\/\/fc0.site.net\/fs50\/i\/2009\/name.jpg";

String pattern = @"\\/";

String cleanUrl = Regex.Replace(url, pattern, "/");

Hope it helps!

A: Actually you want to unescape the string. Answered in this question.


text:
Q: Regex Equivalent for +apple +banana +"baby cart" –blog I have made application where i run  to get html of a page,when i get it i have to mark the url as useable or not useable depending on different patterns. The patterns are provided in txt file :
Example:
+apple+banana+"baby cart" –blog
+"apple skin" +banana +"baby cart" –blog
+"apple skin" +"buy now" +jpg

The " is to tell for phrases than words.

*

*html must contain apple AND banana AND baby cart AND CANNOT contain blog

*html must contain apple skin AND banana AND baby cart AND CANNOT contain blog

*html must contain apple skin AND buy now AND jpg

Problem
Can i uses regex in this case? If yes what would be the regex equivalent for the above patterns, so we can use them in the txt file except these and just use it as a pattern to match in HTML....
(The patterns are not Case sensitive).

A: A sample regex to at least dissect your search strings (although assuming - and " instead of – and "):
(?<operator>[+-])?(?<word>["][^"]+["]|[^\s+-]+)

This matches a either a + or a - and the word or phrase that comes after it.
Quick PowerShell test:
PS> [regex]::matches($s, '(?<operator>[+-])?(?<word>["][^"]+["]|[^\s+-]+)')|ft -auto

Groups                         Success Captures       Index Length Value
------                         ------- --------       ----- ------ -----
{+apple, +, apple}                True {+apple}           0      6 +apple
{+banana, +, banana}              True {+banana}          6      7 +banana
{+"baby cart", +, "baby cart"}    True {+"baby cart"}    13     12 +"baby cart"
{-blog, -, blog}                  True {-blog}           26      5 -blog

You can then process that to build a regex for your content, e.g.:
var re = @"(?<operator>[+-])?(?<word>[""][^""]+[""]|[^\s+-]+)";
var matches = Regex.Matches(s, re);

StringBuilder sb = new StringBuilder();
sb.Append("(?i)");
foreach (Match m in matches) {
  sb.Append(string.Format("(?{1}.*{0})",
      Regex.Escape(m.Groups["word"]).Trim('"'),
      m.Groups["operator"] == "+" ? "=" : "!"));
}

var finalRe = sb.ToString();

But bear in mind that the resulting regex is very slow, especially for longer lists of words.


text:
Q: How do I force Portainer to recreate container? I have one docker-compose.yml file that runs the Portainer service.
However I have just installed Loki, Promtail and Grafana to do log monitoring. For that to work I have to force recreate the containers in Portainer (15+ containers).
However, those containers in Portainer has to be force recreated and that is no option through Portainer. How would I do this?


text:
Q: Search, find, copy and paste macro debug VBA I am pretty new to VBA and I am having a bit of trouble writing a macro.
I want to search a value in a cell, on a column, that is on another worksheet and if it finds it, copy and paste the whole row where it is to another worksheet.
I pretty much have that one sorted but only doing 1 row. What I can't get to work is that after the first value has been read in "sheetTarget" say in cell T4, found in "sheetToSearch" say in A230 and pasted in row 1 in "sheetPaste" move and read the next cell T5 in "sheetTarget" and then keep repeating the process eg. find value of T5 on A350 and paste in row 2, T6 in A20 and paste on row 3, etc..
Sub copyE()

Dim LCopyToRow As Integer

    On Error GoTo Err_Execute

    LCopyToRow = 1

    Dim sheetPaste As String: sheetPaste = "Sheet11"
    Dim sheetTarget As String: sheetTarget = "Sheet8"
    Dim sheetToSearch As String: sheetToSearch = "Sheet1"
    Dim x As String

    Dim columnValue As String: columnValue = "T"
    Dim rowValue As Integer: rowValue = 4
    Dim LTargetRow As Long
    Dim maxRowToTarget As Long: maxRowToTarget = 1000

    Dim columnToSearch As String: columnToSearch = "A"
    Dim iniRowToSearch As Integer: iniRowToSearch = 5
    Dim LSearchRow As Long
    Dim maxRowToSearch As Long: maxRowToSearch = 1000

    For LTargetRow = rowValue To Sheets(sheetTarget).Rows.Count

    Sheets(sheetTarget).Range(columValue & CStr(LTargetRow)).Value = x

        For LSearchRow = iniRowToSearch To Sheets(sheetToSearch).Rows.Count
            If Sheets(sheetToSearch).Range(columnToSearch & CStr(LSearchRow)).Value = x Then

                Sheets(sheetToSearch).Rows(LSearchRow).copy

                Sheets(sheetPaste).Rows(LCopyToRow).PasteSpecial Paste:=xlPasteValues

                LCopyToRow = LCopyToRow + 1

            End If

            If (LSearchRow >= maxRowToSearch) Then
                Exit For
            End If

        Next LSearchRow

    If (LTargetRow >= maxRowToTarget) Then
         Exit For
    End If
    Next LTargetRow

       Application.CutCopyMode = False
            Range("A3").Select

    Exit Sub

Err_Execute:
    MsgBox "An error occurred."
End Sub

I will greatly appreciate any help.

A: This works for me and I believe it is what you are asking for.
Sub test()

Dim sheetPaste As Worksheet
Dim sheetTarget As Worksheet
Dim sheetToSearch As Worksheet
Dim x As String

Dim columnValue As String: columnValue = "T"
Dim rowValue As Integer: rowValue = 4
Dim LTargetRow As Long
Dim maxRowToTarget As Long: maxRowToTarget = 1000

Dim columnToSearch As String: columnToSearch = "A"
Dim iniRowToSearch As Integer: iniRowToSearch = 5
Dim LSearchRow As Long
Dim maxRowToSearch As Long: maxRowToSearch = 1000

LCopyToRow = 1

Set sheetPaste = ThisWorkbook.Worksheets("Sheet11")
Set sheetTarget = ThisWorkbook.Worksheets("Sheet8")
Set sheetToSearch = ThisWorkbook.Worksheets("Sheet1")

'MsgBox sheetTarget.Cells(Rows.Count, 20).End(xlUp).Row
'finds the last row with a value in it in column T of sheetTarget
For LTargetRow = rowValue To sheetTarget.Cells(Rows.Count, 20).End(xlUp).Row

    'targetCell = columValue & CStr(LTargetRow)
    'must set x = , not the value in the column = to x (which is not initialize to it is "")
    If sheetTarget.Range(columnValue & CStr(LTargetRow)).Text <> "" Then
        x = sheetTarget.Range(columnValue & CStr(LTargetRow)).Text

        'finds the last row with a value in it in column A of sheetToSearch
        For LSearchRow = iniRowToSearch To sheetToSearch.Cells(Rows.Count, 1).End(xlUp).Row
            If sheetToSearch.Range(columnToSearch & CStr(LSearchRow)).Value = x Then

                sheetToSearch.Rows(LSearchRow).Copy

                sheetPaste.Rows(LCopyToRow).PasteSpecial Paste:=xlPasteValues

                LCopyToRow = LCopyToRow + 1

                Exit For

            End If

            'dont need this anymore now that we know that last row with data in it.
    '        If (LSearchRow >= maxRowToSearch) Then
    '            Exit For
    '        End If

        Next LSearchRow
    End If

'If (LTargetRow >= maxRowToTarget) Then
'     Exit For
'End If
Next LTargetRow

'Sheets("data").Cells(Rows.Count, 1).End(xlUp).Row

End Sub

Some of the variables are not used anymore and if you have any questions feel free to ask.