text:
Q: Space text in row but only based on one child widget So I want to create this:
|     12          5          300     |
|   monkeys    baboons   chimpanzees |

Basically, put the widgets in a Row and use mainAxisAlignment: MainAxisAlignment.spaceAround on the numbers. The problem is, the text is disrupting the spacing, and since 'chimpanzees' is longer, it causes the 5 baboons to be off center. What is the best way to have the spaceAround only align the numbers, then center the text underneath the numbers?
Row(
    mainAxisAlignment: MainAxisAlignment.spaceAround,
    children: <Widget>[
        Column(
            children: <Widget>[
                Text('12'),
                Text('monkeys'),
            ],
        ),
        Column(
            children: <Widget>[
                Text('5'),
                Text('baboons'),
            ],
        ),
        Column(
            children: <Widget>[
                Text('300'),
                Text('chimpanzees'),
            ],
        ),
    ],
),

A: You can try to use Expanded() to have same width for the Row() children. No need to use spaceAround.
Row(
    children: <Widget>[
        Expanded(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                    Text('12'),
                    Text('monkeys'),
                ],
            ),
        ),
        Expanded(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                    Text('5'),
                    Text('baboons'),
                ],
            ),
        ),
        Expanded(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                    Text('300'),
                    Text('chimpanzees'),
                ],
            ),
        ),
    ],
),

A: Try this
mainAxisAlignment: MainAxisAlignment.spaceEvenly,


text:
Q: Perlbrew | установка cpanm для произвольной версии perl В системе кроме стандартного perl5.8.8 стоит, установленный с помощью perlbrew, perl5.10.1
При попытке установить локальный cpanm для него, ругается..
[shev_ay@pandora 20120203]$ perl -v
This is perl, v5.10.1 (*) built for i686-linux

[shev_ay@pandora 20120203]$ curl -L http://cpanmin.us | perl - App::cpanminus
 % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  319k  100  319k    0     0  97867      0  0:00:03  0:00:03 --:--:--  276k
perl: symbol lookup error: /usr/lib/perl5/site_perl/5.8.8/i386-linux-thread-    multi/auto/Compress/Raw/Zlib/Zlib.so: undefined symbol: Perl_Gthr_key_ptr

И что мне делать? )))
p.s. How-to взято отсюда http://blog.fox.geek.nz/2010/09/installing-multiple-perls-with.html
A: perlbrew install-cpanm ?

redpajama_set_name: RedPajamaStackExchange


text: Q: How to make Visual C# Form Applications resize all control automatically with form resize in Visual Studio 2017? I have been developing windows form apps for school for a while but I couldn't find how to make all controls resize with the form like normal native windows apps. I am using C# in this case. I hope this was a good enough question to ask, please comment for question pointers, I have gotten a few worse reviews some deserved and some I don't know exactly why. I'm a student programmer as well so most help would be appreciated!


text:
Q: Is it possible to transfer a sitecore site to umbraco I have clients who are using sitecore for their site. Its over bloated and much more than they need. I am redesigning their site in wordpress, no problem. However they have certain 'tools' setup that they want to keep, so Im wondering if I can transfer them to Umbraco or any CMS that doesn't have a hefty license fee!
The sitecore license is due to be renewed for another year, and Im trying to find a stop gap so we dont have to pay... can you transfer the whole site easily to umbraco?

A: The best you are likely to be able to get is the raw content of the site as XML. You can then run that through some XSLT to generate an input XML format for Umbraco.
Alternatively, use wget to spider the website and generate a whole load of HTML, and then copy/paste that back into the new CMS. Sounds painful, but it's often what's needed in these migrations (I have resorted to that for several clients).

A: I did that once. Implementation partner converted all the templates and gave me an xml output. Then I used CMSImport (Disclaimer: I'm the author of that package don't need to use it but it's quite handy) for Umbraco to import the data.


text:
Q: Style for exercises with vertical and top bar Please, I'd like to define an exercise environment in the preamble with mdframed or tabularx, like in the image below.

I think this environment theorem may solve the problem, just i have to fill in white the right and bottom sides.
 \documentclass{article}
 \usepackage{amssymb}
\usepackage[framemethod=TikZ]{mdframed}

\newcounter{ex}%[section] \setcounter{theo}{0}
\newenvironment{ex}[2][]{%
\refstepcounter{ex}%
\ifstrempty{#1}%
{\mdfsetup{%
frametitle={%
\tikz[baseline=(current bounding box.east),outer sep=0pt]
\node[anchor=east,rectangle,fill=white]
{\strut \textcolor{red}{Exercice~\theex}};}}
}%
{\mdfsetup{%
frametitle={
\tikz[baseline=(current bounding box.east),outer sep=0pt]
\node[anchor=east,rectangle,fill=white]
{\strut \textcolor{red}{Exercice~#1}};}}%
}%
\mdfsetup{innertopmargin=5pt, innerbottommargin=10pt, linecolor=yellow!60!brown!60!,%
linewidth=2.3pt,topline=true,%
frametitleaboveskip=\dimexpr-\ht\strutbox\relax, roundcorner=5pt
}
\begin{mdframed}[]\relax%
\label{#2}}{\end{mdframed}}

\begin{document}
\begin{ex}{application}
ljlklkj
\end{ex}

\end{document}

A: This is just to-start-with.  It was taken from one of the replies on this forum, I donot remember from where.  Thanks
\documentclass{article}
%\usepackage{fontspec}
\usepackage{mdframed} % Add easy frames to paragraphs
\usepackage{lipsum} % For dummy text
\usepackage{xcolor}
\usepackage{xparse} % Add support for \NewDocumentEnvironment
\definecolor{graylight}{cmyk}{.30,0,0,.67} % define color using xcolor syntax

\newmdenv[ % Define mdframe settings and store as leftrule
  linecolor=graylight,
  linewidth=4pt,
  topline=true,
  bottomline=false,
  rightline=false,
  skipabove=\topsep,
  skipbelow=\topsep
]{leftrule}

\NewDocumentEnvironment{example}{O{\textbf{Example:}}} % Define example environment
{\begin{leftrule}\noindent\textcolor{graylight}{#1}\par}
{\end{leftrule}}

\begin{document}
\begin{example}
\lipsum[1]
\end{example}

\begin{example}[Example]
\lipsum[1]
\end{example}
\end{document}[![enter image description here][1]][1]

A: Try this
\documentclass{article}
 \usepackage{amssymb}
\usepackage[framemethod=TikZ]{mdframed}

\newcounter{ex}%[section] \setcounter{theo}{0}
\newenvironment{ex}[2][]{%
\refstepcounter{ex}%
\ifstrempty{#1}%
{\mdfsetup{%
frametitle={%
\tikz[baseline=(current bounding box.east),outer sep=0pt]
\node[anchor=east,rectangle,fill=white]
{\strut \textcolor{red}{Exercice~\theex}};}}
}%
{\mdfsetup{%
frametitle={
\tikz[baseline=(current bounding box.east),outer sep=5pt]
\node[anchor=east,rectangle,fill=white]
{\strut \textcolor{red}{Exercice~#1}};}}%
}%
\mdfsetup{innertopmargin=5pt, innerbottommargin=10pt, linecolor=yellow!60!brown!60!,%
linewidth=2.3pt,topline=true,%
rightline=false,%
bottomline=false,%
frametitleaboveskip=\dimexpr-\ht\strutbox\relax, roundcorner=0pt
}
\begin{mdframed}[]\relax%
\label{#2}}{\end{mdframed}}

\begin{document}
\begin{ex}{application}
ljlklkj
\end{ex}

\end{document}


text:
Q: Filter records from MySQL by year
*

*If I have column type date and it shows date like this 2013-06-25. How to filter records just by year, e.g. 2011 or 2013?

*How to filter records that are between dates for example: 2013-06-25 and 2013-07-20

A: All dates between 2013-06-25 and 2013-07-20:
SELECT * FROM myTable
WHERE myDateColumn BETWEEN '2013-06-25' AND '2013-07-20'

All dates in 2011 or 2013:
SELECT * FROM myTable
WHERE YEAR(myDateColumn) IN (2011, 2013)

All dates between 2011 and 2013:
SELECT * FROM myTable
WHERE YEAR(myDateColumn) BETWEEN 2011 AND 2013

Or if you have an index on the date and want an optimizable query you should drop the YEAR function call:
SELECT * FROM myTable
WHERE myDateColumn BETWEEN '2011-01-01' AND '2013-12-31'

And have a look at the date functions as suggested. Good luck!

A: Use something like this:
SELECT * FROM table
WHERE date LIKE '%2013%'

to get the data that contains the year 2013.
Apply this to your own table structure, and it should give you the desired result.

A: You should probably look at MySql's date and time functions which shows you a great deal of information about the different functions available for date and time.  To answer your question, however, I hope that these quick queries will help.
SELECT
    *
FROM MyTable
WHERE datecolumn > '2011-01-01'
    AND datecolumn < '2012-01-01'

Alternatively, you can write this as
SELECT
    *
FROM MyTable
WHERE datecolumn BETWEEN '2011-01-01' AND '2012-01-01'

Writing the queries this way rather than using the YEAR function will help take advantage of indexes (if there are any).


text:
Q: How can I specify a subset of a numpy matrix for placement of smaller matrix? I have an image pyramid with a down sample rate of 2. That is, the bottom of my pyramid is a an image of shape (256, 256), where the next level is (128, 128), etc.
My goal is to display this pyramid into a single image. The first image is placed on the left. The second is placed in the top right corner. Each subsequent image must be placed beneath the previous and wedged into the corner.
Here is my current function:
def pyramid2img(pmd):
    '''
    Given a pre-constructed pyramid, this is a helper
    function to display the pyramid in a single image.
    '''

    # orignal shape (pyramid goes from biggest to smallest)
    org_img_shp = pmd[0].shape

    # the output will have to have 1.5 times the width
    out_shp = tuple(int(x*y) \
        for (x,y) in zip(org_img_shp, (1, 1.5)))
    new_img = np.zeros(out_shp, dtype=np.int8)

    # i keep track of the top left corner of where I want to
    # place the current image matrix
    origin = [0, 0]
    for lvl, img_mtx in enumerate(pmd):

        # trying to specify the subset to place the next img_mtx in
        sub = new_img[origin[0]:origin[0]+pmd[lvl].shape[0],
            origin[1]:origin[1]+pmd[lvl].shape[1]]# = img_mtx

        # some prints to see exactly whats being called above ^
        print 'level {}, sub {}, mtx {}'.format(
            lvl, sub.shape, img_mtx.shape)
        print 'sub = new_img[{}:{}, {}:{}]'.format(
            origin[0], origin[0]+pmd[lvl].shape[0],
            origin[1], origin[1]+pmd[lvl].shape[1])

        # first shift moves the origin to the right
        if lvl == 0:
            origin[0] += pmd[lvl].shape[0]
        # the rest move the origin downward
        else:
            origin[1] += pmd[lvl].shape[1]

    return new_img

OUTPUT FROM THE PRINT STATEMENTS:
level 0, sub (256, 256), mtx (256, 256)
sub = new_img[0:256, 0:256]

level 1, sub (0, 128), mtx (128, 128)
sub = new_img[256:384, 0:128]

level 2, sub (0, 64), mtx (64, 64)
sub = new_img[256:320, 128:192]

level 3, sub (0, 32), mtx (32, 32)
sub = new_img[256:288, 192:224]

level 4, sub (0, 16), mtx (16, 16)
sub = new_img[256:272, 224:240]

level 5, sub (0, 8), mtx (8, 8)
sub = new_img[256:264, 240:248]

level 6, sub (0, 4), mtx (4, 4)
sub = new_img[256:260, 248:252]

If you look at the output, you can see that I am trying to reference a 2d-slice of the output image so that I can place the next level of the pyramid inside it.
The problem is that the slicing I am performing is not giving a 2d-array with the shape I expect it too. It thinks I am trying to put a (n,n) matrix into a (0, n) matrix.
How come when I specify a slice like new_img[256:320, 128:192], it returns an object with shape (0, 64), NOT (64, 64)?
Is there an easier way to do what I am trying to do?

A: Here is an example.
Create a pyramid first:
import numpy as np
import pylab as pl
import cv2

img = cv2.imread("earth.jpg")[:, :, ::-1]

size = 512
imgs = []
while size >= 2:
    imgs.append(cv2.resize(img, (size, size)))
    size //= 2

And here is the code to merge the images:
def align(size, width, loc):
    if loc in ("left", "top"):
        return 0
    elif loc in ("right", "bottom"):
        return size - width
    elif loc == "center":
        return (size - width) // 2

def resize_canvas(img, shape, loc, fill=255):
    new_img = np.full(shape + img.shape[2:], fill, dtype=img.dtype)
    y = align(shape[0], img.shape[0], loc[0])
    x = align(shape[1], img.shape[1], loc[1])
    new_img[y:y+img.shape[0], x:x+img.shape[1], ...] = img
    return new_img

def vbox(imgs, align="right", fill=255):
    width = max(img.shape[1] for img in imgs)
    return np.concatenate([
            resize_canvas(img, (img.shape[0], width), ("top", align), fill=fill)
            for img in imgs
        ])

def hbox(imgs, align="top", fill=255):
    height = max(img.shape[0] for img in imgs)
    return np.concatenate([
            resize_canvas(img, (height, img.shape[1]), (align, "left"), fill=fill)
            for img in imgs
        ], axis=1)

the output of:
pl.imshow(hbox([imgs[0], vbox(imgs[1:])]))


text:
Q: Registering a protocol handler in Windows 8 I'm trying to register my application that will handle opening of links, e,g, http://stackoverflow.com.  I need to do this explicitly for Windows 8, I have itworking in earlier versions of Windows.  According to MSDN this has changed in Win8.
I've been through the Default Programs page on MSDN (msdn.microsoft.com/en-us/library/cc144154.aspx) page on MSDN.  It provides a great walkthrough on handling file types but is light on details for protocols.  Registering an Application to a URL Protocol only goes over the steps involved in setting up a new protocol, but not how to correctly add a new handler to an existing protocol.
I've also tried the registry settings outlined in other SO posts.
One more thing, the application is not a Metro/Windows Store App, so adding an entry in the manifest won't work for me.

A: Side note since this is a top answer found when googling this kind of an issue:
Make sure the path in the shell command open is a proper path to your application.
I spent an entire day debugging issue that seemed only to affect Chrome and Edge on Windows 10. They never triggered the protocol handler while Firefox did.
What was the issue? The path to the .bat file used mixed
 \ and / slashes.
Using only proper \ slashes in the path made Edge & Chrome suddenly able to pick up the request.

A: You were on the right track with the Default Programs web page - in fact, it's my reference for this post.
The following adapts their example:
First, you need a ProgID in HKLM\SOFTWARE\Classes that dictates how to handle any input given to it (yours may already exist):
HKLM\SOFTWARE\Classes
     MyApp.ProtocolHandler //this is the ProgID, subkeys are its properties
        (Default) = My Protocol //name of any type passed to this
        DefaultIcon
           (Default) = %ProgramFiles%\MyApp\MyApp.exe, 0 //for example
        shell
           open
              command
                 (Default) = %ProgramFiles%\MyApp\MyApp.exe %1 //for example

Then fill the registry with DefaultProgram info inside a Capabilities key:
HKLM\SOFTWARE\MyApp
    Capabilities
       ApplicationDescription
           URLAssociations
              myprotocol = MyApp.ProtocolHandler //Associated with your ProgID

Finally, register your application's capabilities with DefaultPrograms:
HKLM\SOFTWARE
      RegisteredApplications
         MyApplication = HKLM\SOFTWARE\MyApp\Capabilities

Now all "myprotocol:" links should trigger %ProgramFiles%\MyApp\MyApp.exe %1.

A: LaunchUriAsync(Uri)
Starts the default app associated with the URI scheme name for the specified URI.
You can allow the user to specify, in this case.
http://msdn.microsoft.com/library/windows/apps/Hh701476
        // Create the URI to launch from a string.
        var uri = new Uri(uriToLaunch);

        // Calulcate the position for the Open With dialog.
        // An alternative to using the point is to set the rect of the UI element that triggered the launch.
        Point openWithPosition = GetOpenWithPosition(LaunchUriOpenWithButton);

        // Next, configure the Open With dialog.
        // Here is where you choose the program.
        var options = new Windows.System.LauncherOptions();
        options.DisplayApplicationPicker = true;
        options.UI.InvocationPoint = openWithPosition;
        options.UI.PreferredPlacement = Windows.UI.Popups.Placement.Below;

        // Launch the URI.
        bool success = await Windows.System.Launcher.LaunchUriAsync(uri, options);
        if (success)
        {
           // URI launched: uri.AbsoluteUri
        }
        else
        {
            // URI launch failed.  uri.AbsoluteUri

        }


text:
Q: Custom excel sort/order? So I've gone through a whole lot of sorting which isn't relevant to the question,
but for elaboration I'm getting 10 results out of 14. These results will be in order from 1-14 as I get them through my sort.
I'll get back a column of 10, of all the active numbers in this case
[2, 4, 5, 6, 7, 8, 9, 10, 12, 14]
And essentially I need this to be sorted in a way that it prioritizes 1-10 and fills out the ones missing with 11-14 like so:
[12, 2, 14, 4, 5, 6, 7, 8, 9, 10]
|What I get|What I want|
|----------|-----------|
|2         |12         |
|4         |2          |
|5         |14         |
|6         |4          |
|7         |5          |
|8         |6          |
|9         |7          |
|10        |8          |
|12        |9          |
|14        |10         |

All the sorting happens dynamically and the solution needs to be able to handle that as well. The range can be anything from 1-14. I get 20 columns that all need to dynamically sort with this logic.
I'm hoping my question and what I'm trying to do makes sense. It's my first time posting so I hope I structured it correctly. [EDIT] It doesn't seem like the table formatting is going through? Changed it.


text:
Q: If $f(x) = g(x)|h(x)|$ and $h(x_0)=0$, then what is the condition for $f$ to be differentiable in $x_0$? The functions $g$ and $h$ are differentiable on $\mathbb{R}$. The function $f$ is:
$$f : \mathbb{R} \rightarrow \mathbb{R} \hspace{2cm} f(x)=g(x)|h(x)|$$
If we know that $h(x_0) = 0$, then what is the condition for the function $f$ to be differentiable at the point $x_0$? I have to choose between $5$ possible answers:
A. $h'(x_0)=0$
B. $g(x_0) > 0$
C. $g(x_0)=0$
D. $g(x_0)h'(x_0)=0$
E. Other answer
How should I approach this?


text:
Q: I want to porting zsh's function as fishshell I have a question related to fishshell.
I wrote zsh's function as this:
function agvim() {
  vim $(ag "$@" | peco --query "$LBUFFER" | awk -F : '{print "-c " $2 " " $1}')
}

it works.
But I just ported this function doesn't work properly, this function is ported from zsh to fishshell.
function agvim
  ag $argv | peco --query "$LBUFFER" | awk -F : '{print "-c " $2 " " $1}' >> $HOME/.agvim_history
  vim (tail -n 1 $HOME/.agvim_history)
end

However it doesn't work properly. vim command will be opening with tail's output as filename.
because I think expand-command-substitution is a little different from the zsh.
This is tail's output example -c 3 bin/ec and I want to use this output as options.
Please tell me better solution.

A:
This is tail's output example -c 3 bin/ec and I want to use this output as options.

The issue you are running into here is that zsh, like bash, will split command substitutions on spaces, while fish only splits on newlines.
That means zsh will send "-c", "3" and "bin/ec" to vim, while fish will send "-c 3 bin/ec" as one argument.
There's a few ways to get around this - one, if you are running fish from git, is to use tail | string split " ". Another which should work with pretty much any fish version is to use sed (tail | sed "s/ /\n/g").

A: If you trust the input, this is a place to use eval
function agvim
  eval vim (ag $argv | peco --query "$LBUFFER" | awk -F: '{print "-c",$2,$1}')
end


text:
Q: Working out my code in java I'm trying to make a program that allows the user to input his first name, middle name and family name but the catch is that he can choose not to input his middle name and the program will work out that it should display only the first and last name in that case.
The problem is I want to get the length of my "middle_name" Scanner and put that into a variable that would allow me to sort out two "if" statements
Here is the code in question:
import java.util.Scanner;

public class Names {

        public static void main(String[] args){
            System.out.print("Enter your name : ");
            Scanner first_name = new Scanner(System.in);
            System.out.print("Enter your middle name : ");
            Scanner middle_name = new Scanner(System.in);
            System.out.print("Enter your last name : ");
            Scanner last_name = new Scanner(System.in);
            int x = Integer.parseInt(middle_name);
            if(x == 0) {
                System.out.println("First name : " + first_name);
                System.out.println("Last name : " + last_name);
            }
            if(x > 0) {
                System.out.println("First name : " + first_name);
                System.out.println("Middle name : " + middle_name);
                System.out.println("Last name : " + last_name);
            }
       }
}

A: I guess what you want to do is this:

*

*have one Scanner that reads different lines

*check middle_name for isEmpty() and only have three System.out statements
public static void main(String[] args){
    Scanner in = new Scanner(System.in);

    System.out.print("Enter your name : ");
    String first_name = in.nextLine();
    System.out.print("Enter your middle name : ");
    String middle_name = in.nextLine();
    System.out.print("Enter your last name : ");
    String last_name = in.nextLine();

    System.out.println("First name : " + first_name);
    if(!middle_name.isEmpty()) {
        System.out.println("Middle name : " + middle_name);
    }
    System.out.println("Last name : " + last_name);

    in.close();
}


text:
Q: Is there a way to have a "default color" with a canvas in Tkinter? Is there a way I can set the default color of canvas objects (lines, rectangles, etc.) without setting each one individually? I know the default color is black, and I basically just want to change that so that everything I subsequently create is, say, green. Is there a way to do this with Tkinter in Python?

A: No, there is no way to set the default color. However, if you store the color in a variable, you can use that whenever you create new items.
self.my_color = "red"
...
self.canvas.create_rectangle(..., fill=my_color)

You can also change all objects at once by giving the id "all" to the itemconfigure method. For example:
self.my_color = "green"
self.canvas.itemconfigure("all", fill=self.my_color)

For more on item identifiers (including the special "all" identifier) see Item Specifiers: Handles and Tags on effbot.org as well as the Tags section in the canvas tutorial on tkdocs.com


text:
Q: Redux how to update nested state object immutably without useless shallow copies? Im using NGRX store on angular project.
This is the state type:
export interface TagsMap {
    [key:number]: { // lets call this key - user id.
        [key: number]: number // and this key - tag id.
    }
}

So for example:
{5: {1: 1, 2: 2}, 6: {3: 3}}

User 5 has tags: 1,2, and user 6 has tag 3.
I have above 200k keys in this state, and would like to make the updates as efficient as possible.
The operation is to add a tag to all the users in the state.
I tried the best practice approach like so :
const addTagToAllUsers = (state, tagIdToAdd) => {
  const userIds = Object.keys(state.userTags);
  return userIds.reduce((acc, contactId, index) => {
    return {
      ...acc,
      [contactId]: {
        ...acc[contactId],
        [tagIdToAdd]: tagIdToAdd
      }
    };
  }, state.userTags);
};

But unfortunately this makes the browser crush when there are over 200k users and around 5 tags each.
I managed to make it work with this:
const addTagToAllUsers = (state, tagIdToAdd) => {
  const stateUserTagsShallowCopy = {...state.userTags};
  const userIds = Object.keys(stateUserTags);
  for (let i = 0; i <= userIds.length - 1; i++) {
    const currUserId = userIds[i];
    stateUserTagsShallowCopy[currUserId] = {
      ...stateUserTagsShallowCopy[currUserId],
      [tagIdToAdd]: tagIdToAdd
    };
  }
  return stateUserTagsShallowCopy;
};

And the components are updated from the store nicely without any bugs as far as I checked.
But as written here: Redux website mentions :

The key to updating nested data is that every level of nesting must be copied and updated appropriately

Therefore I wonder if my solution is bad.
Questions:

*

*I Believe I'm still shallow coping all levels in state, am i wrong ?

*Is it a bad solution? if so what bugs may it produce that I might be missing ?

*Why is it required to update sub nested level state in an immutable manner, if the store selector will still fire because the parent reference indeed changed. (Since it works with shallow checks on the top level.)

*What is the best efficient solution ?
Regarding question 3, here is an example of the selector code :
import {createFeatureSelector, createSelector, select} from '@ngrx/store';//ngrx version 10.0.0

//The reducer
const reducers = {
  userTags: (state, action) => {
    //the reducer function..
  }
}

//then on app module:
StoreModule.forRoot(reducers)

//The selector :
const stateToUserTags = createSelector(
  createFeatureSelector('userTags'),
  (userTags) => {
    //this will execute whenever userTags state is updated, as long as it passes the shallow check comparison.
    //hence the question why is it required to return a new reference to every nested level object of the state...
    return userTags;
  }
)

//this.store is NGRX: Store<State>
const tags$: Observable<any> = this.store.pipe(select(stateToUser))

//then in component I use it something like this:
<tagsList tags=[tags$ | async]>
</tagsList>

A: Your solution is perfectly fine.
The rule of thumb is that you cannot mutate an object/array stored in state.
In Your example, the only thing that You are mutating is the stateUserTagsShallowCopy object (it is not stored inside state since it is a shallow copy of state.userTags).
Sidenote: It is better to use for of here since you don't need to access the index
const addTagToAllUsers = (state, tagIdToAdd) => {
  const stateUserTagsShallowCopy = {...state.userTags};
  const userIds = Object.keys(stateUserTags);
  for (let currUserId of userIds) {
    stateUserTagsShallowCopy[currUserId] = {
      ...stateUserTagsShallowCopy[currUserId],
      [tagIdToAdd]: tagIdToAdd
    };
  }
  return stateUserTagsShallowCopy;
};

If you decide to use immer this will look like this
import produce from "immer";

const addTagToAllUsers = (state, tagIdToAdd) => {
  const updatedStateUserTags = produce(state.userTags, draft => {
    for (let draftTags of Object.values(draft)) {
       tags[tagIdToAdd] = tagIdToAdd
    }
  })
  return updatedStateUserTags
});

(this comes usually with performance cost). With immer you can sacrifice performance to gain readability
ad 3.

Why is it required to update sub nested level state in an immutable manner, if the store selector will still fire because the parent reference indeed changed. (Since it works with shallow checks on the top level.)

Every store change selectors recompute to see if the dependent component should re-render.
imagine that instead of immutable update of the user tags we decided to mutate tags inside user (state.userTags is a new object reference but we mutate (reuse) old entries objects state.userTags[userId])
const addTagToAllUsers = (state, tagIdToAdd) => {
  const stateUserTagsShallowCopy = {...state.userTags};
  const userIds = Object.keys(stateUserTags);
  for (let currUserId of userIds) {
    stateUserTagsShallowCopy[currUserId][tagIdToAdd] = tagIdToAdd;
  }
  return stateUserTagsShallowCopy;
};

In your case, you have a selector that takes out state.userTags.
It means that every time a state update happens nrgx will compare the previous result of the selector and the current one (prevUserTags === currUserTags by reference). In our case, we change state.userTags so the component that uses this selector will be refreshed with new userTags.
But imagine other selectors that instead of all userTags will select only one user tags. In our imaginary situation, we mutate directly userTags[someUserId] so the reference remains the same each time. The negative effect here is that subscribing component will be not refreshed (will not see an update after a tag is added).


text:
Q: cant see the html page when navigating to /home or new. Only index is showing In this project I am trying to learn Angular and nesting components. For some reason I can't navigate to /home page. The page is not showing. Any help please. Thank you.
app-routing.module.ts
const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: '/home' },
  { path: 'home', component: IndexComponent },
  { path: 'view/:id', component: ShowComponent },
  { path: 'new', component: NewComponent },
  { path: 'edit/:id', component: EditComponent },
  { path: '**', component: IndexComponent }
];

A: Just update your code to
[{
    path: '',
    pathMatch: 'full',
    redirectTo: 'home' // you dont need /home
  },
  {
    path: 'home',
    component: IndexComponent
  }
]


text:
Q: Proving supermartingale (sequence of uniformly distributed random variables) Let's take $X_1 \sim U[0,1]$ and if $X_{n-1}=a$ then $X_n \sim U[0,a]$. I want t prove that $X_n$ is supermartingale.
So what I want to do prove is :
$$E[X_{n+1}\mid \mathbb{F}_n]\le X_n$$
And I have several problems with it. Let's just think a little about next expectations  :
$E[X_1]=\frac12$
$E[X_2]=\frac{a_1}{2}$
$E[X_3]=\frac{a_2}{2}$
and so on. So how can I translate it now to language of conditional expectation with filtration ? Is it really submartingale ? I found it very unintuitive.


text:
Q: JavascriptExecutor cannot be resolved to a type I am getting following error
JavascriptExecutor cannot be resolved to a type

while i am using the following
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView()", webelement);

A: Add the below import
import org.openqa.selenium.JavascriptExecutor;

and it'll fix the issue.

A: Try below :-
JavascriptExecutor js=(JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView()", webelement));

Hope it will help you :)

A: I believe you are missing a boolean statement in your js-snippet. Try
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true)", webelement);

A: you have to import JavascriptExecuter class from java API. then your error will be rectified.
hope it helps


text: Q: Google App Engine: Query.GeoRegion.Rectangle Intersection Can anybody suggest an elegant, robust method for finding the intersection of two com.google.appengine.api.datastore.Query.GeoRegion.Rectangle objects? Current thinking is to re-implement java.awt.geom.Rectangle2D.intersect().


text:
Q: Selecting from Multiple tables in same Query using PHP MySQL Kindly pardon me if i looks silly , I am newbie in PhP MySQL
Totally there are three tables

Student,Class,Parent

I am working on parent user now . As a parent i want to view some things as below

*

*My Students studying

*Their class

Student Table :
s_id   s_name    parent_id   s_class_id

1       name1     40           20

Class Table :
c_id   c_name

20      Ten

Parent Table :
p_id    p_name

40      Parent1

My 1st task as mentioned above "1. My Students studying " i done successfully with the following query
"SELECT * FROM student where parent_id='$update_id' "

then by displaying
$row['s_name']

For all who thinks where the $update id comes from , I already done it few codes above as follows
$update_id = $login_type['p_id'];

Where $login_type i am taking from session
Now i want to do my second task which is "2. Their class"
I don't want it to do as separate select query which i can do now, i want it to be in the same select above done . as i am just learning from scratch i am stuck over here . Kindly help me please mates.
I tried to explain the max as i can , if you still has any clarifications , kindly ask me .

A: You should use join to get results from multiple tables.
Your query should look similar to this:
SELECT * FROM student
    JOIN class
    ON class.c_id = student.s_class_id
    WHERE parent_id='$update_id'

You can read more about mysql join here: http://dev.mysql.com/doc/refman/5.7/en/join.html

A: SELECT * FROM student
INNER JOIN class ON class.c_id = student.s_class_id
WHERE parent_id = '$update_id'

You can use mysql join query like this and can get the student's class name in
$row['c_name']

A: In this single SELECT you can obtain all data from tables 'student' and 'class' related to the students with parent_id='$update_id' using JOIN.
SELECT * FROM student
LEFT JOIN class ON s_class_id=c_id
WHERE parent_id='$update_id'

To access the data from, use same method you already use:
echo $row['s_name'];
echo $row['c_name'];
// ..and so on for other fields.

[Edited: added LEFT to join, so that you will get data from ALL students, including those not having any class assigned. With INNER JOIN (or JOIN 'only') you will miss rows from students with no class]


text:
Q: How to clear facebook share image cache for entire site I have cleared facebook cache to change "share image" by using
https://developers.facebook.com/tools/debug for specific URL.
I want to clear cache and change "share image" for entire site. There are hundreds of URL, so it is tough to clear cache for each url by entering here
 https://developers.facebook.com/tools/debug
Also I use http://www.webcoachbd.com?fbrefresh=5465468464 this in above debugger. Yet not appearing correct image when share in facebook for many URL in this site (webcoachbd.com).
somebody help plz.


text:
Q: Using WPF Infragistics Excel export functionality with MVVM I'm using the Infragistics WPF datagrid and I want to make use of the Excel export functionality that Infragistics provides. The API for the Excel export requires an instance of the grid as a parameter. This isn't very MVVM friendly since I'd prefer to handle the command to export the data in my viewModel which wouldn't know about the instance of the datagrid control in my view.
Does anyone know of a more MVVM friendly mechanism to do excel exports (preferable based on the collection the grid is bound to) using the Infragistics libraries?

A: Due to the required reference to the grid, as you know, you should not put the logic into the View Model.  You just need to handle the Export command in your code-behind.  There is nothing conceptually wrong, or anti-MVVM, about doing this: this particular logic just happens to be View-specific.

A: The datagrid is part of view and export to excel is a feature of this grid. There is no involvement of ViewModel at all. Its a pure case of View activity. Considering this as apure view feature, you cannot / need not handle the Export Command in ViewModel but in the View (code-behind) itself.
Tomorrow if you replace this datagrid with another datagrid, the export to excel feature will also go, since its provided by infragistics. Hence your view model is not supposed to do anything. However if you want to implement a generic and independent functionality which is not specific to infragistics, you may do it in the ViewModel (Because its generic and not dependent of infragistics).

A: simply ,
you can add button in ur xaml like this and use command parmeter to pass grid.
<Button Content="Print" HorizontalAlignment="Left" Margin="201,35,0,0" Grid.Row="2"    VerticalAlignment="Top" Width="75" Height="29"
            Command="{Binding PrintCommand, Mode=OneWay}" CommandParameter="{Binding ElementName=ParentC1DataGrid,Mode=OneWay}"
            />

and in ur view model add this command:
private ICommand m_PrintCommand;
    public ICommand PrintCommand
    {

        get {

            if (this.m_PrintCommand == null)
            {
                this.m_PrintCommand = new DelegateCommand<C1.WPF.DataGrid.C1DataGrid>(PrintData);
            }
            return m_PrintCommand;
        }
    }

    private void PrintData(C1.WPF.DataGrid.C1DataGrid v)
    {
////put exporting code here
        PrintDialog printDlg = new PrintDialog();
        printDlg.PrintVisual(v, "Grid Printing.");

    }


text:
Q: Using forms authentication, is it possible to switch the logged in user in code, just for the current request? In a certain situation, I want a request to execute as a user different than the one actually logged in.  So, when User A requests a particular page, from code I want to switch it execute under the user account of User B -- only for this single request (or even for a single block of code...)
I've used this:
FormsAuthentication.SetAuthCookie("UserB")

This works, but it's persistent.  When I request a new page, I'm now logged in as User B, which is not what I want.
Is this possible?  I've RTFM'd up and down for this.
Edit: I may have found an answer, which I posted below.  Looking for confirmation or refutation of this solution.

A: I think I might have found it.  I'm not 100% sure, but this works.  I just don't know if it's completely correct or if there's something I'm not considering.
HttpContext.Current.User = PrincipalInfo.CreatePrincipal("UserB");

Again, this seems to do what I originally wanted.  If you have experience that would prove me right or wrong, please comment.


text:
Q: statistically comparing linear regressions (in R) I would like to compare regression models collected in three locations to see whether location makes a difference.
Consider some toy data:
mydata <- read.table(header=TRUE, text="
location    height  weight
    spain   178 90
    spain   187 80
    spain   155 70
    spain   187 85
    spain   150 60
    spain   155 73
    spain   168 80
    spain   160 75
    spain   177 77
    spain   178 83
    russia  165 60
    russia  161 55
    russia  187 94
    russia  175 77
    russia  170 70
    russia  181 90
    russia  173 72
    russia  163 58
    russia  177 80
    russia  167 67
    peru    177 75
    peru    182 65
    peru    145 55
    peru    176 70
    peru    150 45
    peru    155 58
    peru    168 65
    peru    160 60
    peru    177 62
    peru    178 68
        ")

I know I can use ANOVAs etc to see if there is a treatment (i.e. country) difference in height or weight but I am not sure if I can do this explicitly for the REGRESSIONS (i.e. is there a difference in the relationship between height and weight in different countries). For this example, I would like to assume that weight is a function of height.
If you produce a regression for each country, you'll see that spain and peru have a similar slope but a different intercept, while russia has a much steeper slope and intercept. How can I formally test this (ideally with significance values etc)?

A: What you are describing is a difference in slopes for each country. You can assess this by including an interaction term in your model, such that each country gets its own addition to the slope:
$\text{weight}_{ijk} = \beta_0 + \beta_1 \cdot \text{height}_j + \beta_2 \cdot \text{location}_k + \beta_3 (\text{height}\cdot\text{location})_{jk} + \epsilon_{ijk}$
In $\textsf{R}$, you can do this as follows:
LM <- lm(weight ~ height * location, mydata)
summary(LM)

If you look at the coefficients tab for example, you will see which slopes are different by looking at the interaction term:
Coefficients:
                       Estimate Std. Error t value Pr(>|t|)
(Intercept)            -23.6958    18.3472  -1.292    0.209
height                   0.5156     0.1097   4.701 8.89e-05 ***
locationrussia        -173.4683    35.3684  -4.905 5.29e-05 ***
locationspain           15.6250    25.7157   0.608    0.549
height:locationrussia    1.0520     0.2071   5.079 3.41e-05 ***
height:locationspain    -0.0119     0.1525  -0.078    0.938

In this case Russia's slope differs significantly from Peru (Intercept) by about 1. You can change which country is in the intercept with the function relevel() to make other comparisons than just Peru.
If your interest lies not in these countries specifically, but more generally "do countries differ", you could also consider location to be a random effect in the context of a mixed model. In this case, you would want to estimate a random slope for height, e.g.:
LMM <- lmer(weight ~ height + (0 + height|location), mydata)

You could then bootstrap confidence intervals to see if the random effect for location is indeed significant (i.e. countries differ significantly):
confint(LMM, method = "boot")


text:
Q: Oozie: Does oozie generate output-events? In oozie, input-events are pretty straightforward, if the specifies file/folder is not present, the coordinator job is kept in WAITING state. But I could not understand what output-events does.
As per my understanding, the files/folders specified in output-events tag should be created by oozie in case all specified actions are successful. But that does not happen. I cannot find any relevant logs either. Nor are the documentations clear about this.
So, the question is, does Oozie really create files/folders specified in output-events? Or does it just mention that these particular files/folders are created during the workflow and the responsibility of creation is on jobs, not on Oozie?
Relevant piece of code can be found at https://gist.github.com/venkateshshukla/de0dc395797a7ffba153

A: The official Oozie documentation for Oozie Coordinator is not very clear on the exact purpose of the output-events element. However, the book "Apache Oozie: The Workflow Scheduler for Hadoop" mentions the following:

During reprocessing of a coordinator, Oozie tries to help the retry attempt by cleaning up the output directories by default. For this, it uses the <output-events> specification in the coordinator XML to remove the old output before running the new attempt. Users can override this default behavior using the –noCleanup option.

So, in summary:

*

*No, files specified in output-events are not automatically created by Oozie, you need to create those files in your Oozie workflow actions.

*The output-events configuration is for giving Oozie information on what files will be created by your Oozie workflow actions, which Oozie would use to cleanup files when rerunning/reprocessing a coordinator.

A: Always the actions generate the data, these settings are just for control.
You'll find some examples here


text:
Q: What is an alternative to the broken WoW API call GetCurrentRegion()? I'm trying to fix a problem in the "Ask Mr. Robot" add-on for World of Warcraft.
The buggy code goes something like this:
function AskMrRobot.ScanCharacter()
    AmrDb.Region = AskMrRobot.regionNames[GetCurrentRegion()]

    -- other stuff here
end

The problem is that GetCurrentRegion() returns the client region and not the logged in region: I have a EU client logged in on a US realm which has a EU counterpart with the same name (Area52). The net effect is that the plugin returns an existing, but incorrect realm ("EU-Area52"), instead of the existing and correct one ("US-Area52").
This problem is also documented on gamepedia

This function is unreliable for players who switch between regions. For example, if a player installs the US client and then logs into EU servers, this function will incorrectly report that they are still in the US region.

So, I'd like to replace the GetCurrentRegion() with an alternative call or function which returns reliable data.
How can I do this?

A: There is the library LibRealmInfo (WoWI/Curse) that provides lookups of hardcoded, hand-collected data to determine the current region in a reliable way (may fail for new realms added at a later point, so check for updates)
Other methods that are unreliable:

*

*The CVar "portal" is in fact the value that GetCurrentRegion() returns, so it's the same, possibly incorrect value

*As a reply in the thread linked by Hotted24 by the infamous Simca states, the CVar "realmList" no longer works in WoD. (may still 'work' - as in not throwing an error when given to GetCVar - if it's in Config.wtf, but will most likely not be changed anymore by the Launcher)
edit: sanitized post

A: local realmlist = GetCVar("realmList")
local region = string.match(realmlist,"(%a+)%..+")
if region then
  -- use region
end

Saw it on wowinterface, been using it, working last time I checked =)
Reference
EDIT :
Not tested, but fairly sure it'll work :
local guid = UnitGUID("player")
local currentRegion
if guid then
    local server = tonumber(strmatch(guid, "^Player%-(%d+)"))
    local realm = realmData[server]
    if realm then
        currentRegion = realm.region
    end
end

Reference


text:
Q: How can I do bulk search and replace with Perl? I have the following script that takes in an input file, output file and
replaces the string in the input file with some other string and writes out
the output file.
I want to change the script to traverse through a directory of files
i.e. instead of prompting for input and output files, the script should take
as argument a directory path such as C:\temp\allFilesTobeReplaced\ and
search for a string x and replace it with y for all files under that
directory path and write out the same files.
How do I do this?
Thanks.
$file=$ARGV[0];

open(INFO,$file);
@lines=<INFO>;
print @lines;

open(INFO,">c:/filelist.txt");

foreach $file (@lines){
   #print "$file\n";
   print INFO "$file";
}

#print "Input file name: ";
#chomp($infilename = <STDIN>);

if ($ARGV[0]){
   $file= $ARGV[0]
}

print "Output file name: ";
chomp($outfilename = <STDIN>);
print "Search string: ";
chomp($search = <STDIN>);
print "Replacement string: ";
chomp($replace = <STDIN>);

open(INFO,$file);
@lines=<INFO>;
open(OUT,">$outfilename") || die "cannot create $outfilename: $!";

foreach $file (@lines){
    # read a line from file IN into $_
    s/$search/$replace/g; # change the lines
    print OUT $_; # print that line to file OUT
}
close(IN);
close(OUT);

A: You can do this with the -i param:
Just process all the files as normal, but include -i.bak:
#!/usr/bin/perl -i.bak

while ( <> ) {
   s/before/after/;
   print;
}

This should process each file, and rename the original to original.bak  And of course you can do it as a one-liner as mentioned by @Jamie Cook

A: The use of the perl single liner
perl -pi -e 's/original string/new string/' filename

can be combined with File::Find, to give the following single script (this is a template I use for many such operations).
use File::Find;

# search for files down a directory hierarchy ('.' taken for this example)
find(\&wanted, ".");

sub wanted
{
    if (-f $_)
    {
        # for the files we are interested in call edit_file().
        edit_file($_);
    }
}

sub edit_file
{
    my ($filename) = @_;

    # you can re-create the one-liner above by localizing @ARGV as the list of
    # files the <> will process, and localizing $^I as the name of the backup file.
    local (@ARGV) = ($filename);
    local($^I) = '.bak';

    while (<>)
    {
        s/original string/new string/g;
    }
    continue
    {
        print;
    }
}

A: Try this
#!/usr/bin/perl -w

@files = <*>;
foreach $file (@files) {
  print $file . '\n';
}

Take also a look to glob in Perl:

*

*http://perldoc.perl.org/File/Glob.html

*http://www.lyingonthecovers.net/?p=312

A: I know you can use a simple Perl one-liner from the command line, where filename can be a single filename or a list of filenames. You could probably combine this with bgy's answer to get the desired effect:
perl -pi -e 's/original string/new string/' filename

And I know it's trite but this sounds a lot like sed, if you can use gnu tools:
for i in `find ./allFilesTobeReplaced`; do sed -i s/original string/new string/g $i; done

A: perl -pi -e 's#OLD#NEW#g' filename.
You can replace filename with the pattern that suits your file list.


text:
Q: How to make regular expression for this? I want to make a regular expression to match a string like :
Function_Name ( 'parameters' ) Function Description

so I get the name, parameters and description.

A: Assuming parameters are seperated by , Following PCRE regular expression should work for you.
(\w+)\s+\(([^\)]+)\s+(.+)

Subgroup 1 > function name
Subgroup 2 > parameters
Subgroup 3 > function description

A: If you are using AutoIt, as the tags suggest, the pattern should be a PCRE.
(\w+)\s*\(\s*([^)]+)\s*\)\s*(.+)

This is a slightly modified version of the pattern Shiplu suggested.
It has optional spaces so they don't end up in the match and the same goes for the closing parentheses. There is also no need to escape the parentheses inside a character set.

*

*( start capturing group 1

*\w+ match one or more word characters (alphanumeric and underscore)

*) close capturing group 1

*\s* match zero or more whitespace characters

*\( match an opening parantheses

*\s* match zero or more whitespace characters

*( start capturing group 2

*[^)]+ match one or more characters that are not a closing parentheses

*) close capturing group 2

*\s* match zero or more whitespace characters

*\) match a closing parentheses

*\s* match zero or more whitespace characters

*( start capturing group 3

*.+ match one or more characters that are not a whitespace

*) end capturing group 3

A: I am writing Python Regex, but I don't think it would be hard at all to pass it to PHP or Perl.
My guess would be something like this, but I am uncertain on the second .*, if it will capture correctly the EOL or not.
(\w+)\s\(\s'\s(.+)\s'\s\)\s(.*)


text:
Q: how to commit changes to a drupal project i've issue understanding the module releasing system in drupal, it's really confusing me.
i have a project published on drupal.org, whenever i make change i had to commit and add a new tag, because git won't allow me to push on a detached head.
i need i way to commit changes to '7.x-1.0' which is a tag, now i read that a tag is just a reference to a specific commit, how i can commit a change to specific tag without creating a new tag for it? and why drupal uses the tagging system instead of branching ?

A: git push origin <commit-ish>:refs/heads/foo

Here "commit-ish" is a valid git revision that points to a commit object. It can be HEAD, a tag, a specific commit, a branch and etc.
For example, if you'd like to push the detached HEAD to create or update foo:
git push origin HEAD:refs/heads/foo

or
git push origin HEAD:foo

The detached HEAD should come from a branch. If it comes from a tag, the tag should come from a branch. You could check what branches the remote repository has via git ls-remote -h. Find out the branch that you can work with.


text:
Q: Unescape the chinese characters in url? Sometimes, Chinese characters are escaped into forms like:
%B9%F3%D6%DD%C3%A9%CC%A8
How do I convert these back to readable chinese characters in Python?

A: You can use urllib2.unquote like this:
>>> import urllib2
>>> print urllib2.unquote('%B9%F3%D6%DD%C3%A9%CC%A8').decode('gbk')
贵州茅台

A: Try this,
urllib.unquote(your_string).decode(your_encoding)


text:
Q: What graph is best suited for this data? (and how can I produce it in R) I have this df object (9x19),
clusters pearson..s pearson..c pearson..a spearman..s spearman..c spearman..a cosine..s cosine..c cosine..a    Z0e..s    Z0e..c    Z0e..a    Z1e..s    Z1e..c    Z1e..a    Z2e..s    Z2e..c    Z2e..a
       2  0.5220314  0.9619119  0.8902166   0.9619119   0.8566094   0.8566094 0.9619119 0.9253174 0.9619119 0.5177371 0.5177371 0.5177371 0.5177371 0.5177371 0.5177371 0.5177371 0.5371546 0.5177371
       3  0.9477222  0.9058999  0.8902166   0.9477222   0.9238237   0.9238237 0.9477222 0.9118745 0.8416729 0.5218447 0.5218447 0.5218447 0.5218447 0.5218447 0.5218447 0.5263256 0.5420090 0.5311800
       4  0.9342793  0.9029126  0.8909634   0.9223301   0.8035848   0.9118745 0.9058999 0.7735250 0.8274832 0.5261389 0.5412621 0.5412621 0.5308066 0.5308066 0.5308066 0.5308066 0.5412621 0.5308066
       5  0.8409261  0.7768857  0.8050784   0.9217700   0.7615758   0.7916355 0.8200149 0.7399178 0.8140403 0.5354742 0.5405153 0.5405153 0.5354742 0.5405153 0.5405153 0.5354742 0.5405153 0.5405153
       6  0.8065721  0.7462659  0.7923824   0.9001120   0.6719567   0.7901419 0.8065721 0.7261016 0.7826736 0.5403286 0.5403286 0.5403286 0.5352875 0.5403286 0.5403286 0.5403286 0.5403286 0.5403286
       7  0.7938760  0.6700896  0.7804332   0.8792009   0.6506721   0.7610157 0.8020911 0.7092980 0.7481329 0.5401419 0.5401419 0.5401419 0.5401419 0.5401419 0.5401419 0.5401419 0.5401419 0.5401419
       8  0.7854742  0.6671023  0.7182599   0.8590366   0.6491785   0.7520538 0.7936893 0.7078043 0.7406647 0.5311800 0.6161314 0.5311800 0.5311800 0.5085885 0.5237117 0.5311800 0.5115758 0.5237117
       9  0.7809933  0.6577670  0.7197535   0.8491412   0.6071695   0.7356236 0.7949963 0.6779313 0.7279686 0.5229649 0.6030620 0.5408887 0.5229649 0.5029873 0.5130695 0.5229649 0.5037341 0.5162435
      10  0.7823002  0.6338686  0.6898805   0.8267364   0.6023152   0.7057506 0.7823002 0.6301344 0.7160194 0.5154966 0.5537715 0.5319268 0.5154966 0.4985063 0.5067214 0.5123226 0.4992532 0.5067214

which shows the adjusted Rand index between a hierarchical clustering for a given number of clusters and the true groups in the original data. For example, df[1, 1]=0.5220314, is the adjusted Rand index for "Pearson's correlation" proximity measure along with "s" which is the "single" linkage method. Similarly, c is complete and a is average. "Spearman" is "Spearman's correlation", "Cosine" is cosine, "Z0e" is "Euclidean" for original data, whereas "Z1" and "Z2" are standardized versions of the original data.
Any recommendations for graphing are welcomed. I wish to compare firstly, the different proximity measures, and secondly, for each proximity measure, to compare the linkage method for each, for the different cluster values.

A: My first try would be this:
R
library(data.table)
library(ggplot2)

dat <- fread('data.tsv')
dat <- melt(data=dat, id.var='clusters', value.name='corr')
dat[, clusters := as.character(clusters)]
dat[, method := sub('\\.\\..*', '', variable)]
dat[, linkage := sub('.*\\.\\.', '', variable)]
dat[, variable := NULL]
dat
     clusters      corr  method linkage
  1:        2 0.5220314 pearson       s
  2:        3 0.9477222 pearson       s
  3:        4 0.9342793 pearson       s
  4:        5 0.8409261 pearson       s
  5:        6 0.8065721 pearson       s
 ---
158:        6 0.5403286     Z2e       a
159:        7 0.5401419     Z2e       a
160:        8 0.5237117     Z2e       a
161:        9 0.5162435     Z2e       a
162:       10 0.5067214     Z2e       a

gg <- ggplot(dat=dat, aes(x=clusters, y=corr, colour=linkage, group=linkage)) +
    geom_point() +
    geom_line() +
    facet_wrap(~method)

In the ggplot call, you could try swapping clusters with method or linkage to see if it suits your needs better.
Also, it is rarely a good idea to have factors arranged in alphabetical order so I would re-order them in a more meaningful way.


text:
Q: XSLT-Last node of child to be removed or inserted based on the condtions-How it can be achieved Given Input
<Parent status="success">
  <Child id="1" name="chi">
    <grandchild id="316" selected="0" />
    <grandchild id="317" selected="2" />
    <grandchild id="318" selected="0" />
    <grandchild id="319" selected="0" />
    <grandchild id="320" selected="2" />
  </Child>

required output for scenario one
if anyone of node(except last node,always selected would be 2) has attribute selected = '2'
we should have as same as input
expected output
<Parent status="success">
  <Child id="1" name="chi">
    <grandchild id="316" selected="0" />
    <grandchild id="317" selected="2" />
    <grandchild id="318" selected="0" />
    <grandchild id="319" selected="0" />
    <grandchild id="320" selected="2" />
  </Child>
 </Parent>

required output for scenario two
if the input is as below
<Parent status="success">
    <Child id="1" name="chi">
        <grandchild id="316" selected="0" />
        <grandchild id="317" selected="0" />
        <grandchild id="318" selected="0" />
        <grandchild id="319" selected="0" />
        <grandchild id="320" selected="2" />
    </Child>
</Parent>

required output should be
<Parent status="success">
  <Child id="1" name="chi">
    <grandchild id="316" selected="0" />
    <grandchild id="317" selected="0" />
    <grandchild id="318" selected="0" />
    <grandchild id="319" selected="0" />
  </Child>
</Parent>

how we can achieve this XSL

A: It seems you could restate your requirements as:

remove the last grandchild if any other grandchild has a selected
  attribute with the value of 2

which is easily achieved by:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="grandchild[last()][not(preceding-sibling::grandchild/@selected=2)]"/>

</xsl:stylesheet>


text:
Q: How can i write HQL statements inside criteria I have a case where i need to use a sub-select join inside my criteria. Normal FetchMode.JOIN (as given below) doesn't work, as the database is old and mappings are messed up. Is there way to use SQL inside my criteria to join the tables.
def criteria = User.createCriteria()
List users = criteria.list() {
    fetchMode "comments", FetchMode.JOIN
    fetchMode "comments.property", FetchMode.JOIN
}

A: def criteria = User.createCriteria()
List users = criteria.list() { //or User.withCriteria
    comments {
        property {
            ....
        }
    }
}

should do with what you are trying to. Skeptical about the usage as property for the association, otherwise I would try for "property" { }.


text:
Q: Unable to set cookie on Safari (Works on Chrome) Hi I have been creating my first MERN stack web application and deployed frontend and backend on separate domains.

Frontend (netlify) : example.netlify.app
Backend (heroku) : example.herokuapp.com
Github (this is my repository, just in case) : https://github.com/dbwjd5864/YumPlan

So getting cookies from Backend and storing in order to request another api calls with cookies worked fine with Chrome (I haven't tried yet with Firefox but I believe it works as well)

However, when I tested it with Safari, I can see cookies on response but it was not stored for later request, so I couldn't get authorized. However, when I uncheck Prevent cross-site tracking under Safari preferences, I could get cookies for the later API calls.
I guess this is a cors issue which came from Safari property. I spent so much time to find a way to solve it but I couldn't. Is there any way to make it possible for Safari users to get login and set token on different domains?
Or Should I just use the same domain, for example, I deploy the frontend and backend on Heroku together to use the same domain?
I really appreciate any help you can provide.


text:
Q: Math typestting improper after copy and paste. Can I get Mathematica to "refresh" the entire expression? I copied the content shown in the square brackets from that shown selected in the rounded brackets.  When I pasted the content, the "hats" were misplaced, as shown in all but the first two terms of the pasted text.
The first two terms were fixed by simply copying the '^' and pasting it over itself.  That causes the character to move back to its proper location.
Is there a way to get that to happen without touching each misplaced character?
This is the content being copied:

This is the content after pasting:

Here is an example from a smaller expression with the same problem:

And the cell expression:

Cell[TextData[Cell[BoxData[
 FormBox[
  RowBox[{
   RowBox[{
    SubscriptBox["a",
     RowBox[{"1", "\[InvisibleComma]", "1"}]],
    OverscriptBox["\[GothicI]", "^"],
    OverscriptBox["\[GothicI]", "^"]}], "+",
   RowBox[{
    SubscriptBox["a",
     RowBox[{"1", "\[InvisibleComma]", "2"}]],
    OverscriptBox["\[GothicI]", "^"],
    OverscriptBox["\[GothicJ]", "^"]}], "+",
   RowBox[{
    SubscriptBox["a",
     RowBox[{"1", "\[InvisibleComma]", "3"}]],
    OverscriptBox["\[GothicI]", "^"],
    OverscriptBox["\[GothicK]", "^"]}]}], TraditionalForm]],
 FormatType->"TraditionalForm"]], "Text",
 CellChangeTimes->{{3.72528311041591*^9, 3.725283111409934*^9}}]

The same cell with some of the hats fixed:

And the corresponding cell expression:

 Cell[TextData[Cell[BoxData[
  FormBox[
   RowBox[{
    RowBox[{
     SubscriptBox["a",
      RowBox[{"1", "\[InvisibleComma]", "1"}]],
     OverscriptBox["\[GothicI]", "^"],
     OverscriptBox["\[GothicI]", "^"]}], "+",
    RowBox[{
     SubscriptBox["a",
      RowBox[{"1", "\[InvisibleComma]", "2"}]],
     OverscriptBox["\[GothicI]", "^"],
     OverscriptBox["\[GothicJ]", "^"]}], "+",
    RowBox[{
     SubscriptBox["a",
      RowBox[{"1", "\[InvisibleComma]", "3"}]],
     OverscriptBox["\[GothicI]", "^"],
     OverscriptBox["\[GothicK]", "^"]}]}], TraditionalForm]],
  FormatType->"TraditionalForm"]], "Text",
 CellChangeTimes->{{3.72528311041591*^9, 3.725283111409934*^9}, {3.725292068048725*^9, 3.725292090693556*^9}}]

A: This looks like an issue worth reporting to support. Here are a few workarounds:

*

*Evaluate the following expression after the problematic cell:

NotebookWrite[PreviousCell[], NotebookRead@PreviousCell[]]

Animation:

*Use the following button to fix a cell containing the insertion point:

Button[
    "Reset formatting",
    With[{p=ParentCell @@ SelectedCells[EvaluationNotebook[]]},
        NotebookWrite[p, NotebookRead[p]]
    ]
]
Animation:

*Use Cell | Show Expression and edit the contents by deleting and restoring a character.

Animation:


text:
Q: How to set the directory where the script is in in to working directory? I want to import multiple files which will always be in the same directory as the script itself. But the script might be copied and pasted to somewhere else. I know how to set and change the working directory but I don't know how to set the working directory dynamically/automatically to where the .py file is located and run from.
The path must not be hard-coded.
I've seen Changing current working directory to the directory from where script is running (Python) but there is not really an answer.


text:
Q: java.sql.SQLException: ORA-01036: illegal variable name/number I've got a weird problem in Oracle query running from Java with Oracle 11g. The same query worked good with Oracle 10g. tool_availability is a view.
final String SELECT_SQL = "select * " +
            "from tool_availability " +
            "where tool_code = ? " +
            "and tool_number = ? " +
            "and unit = ? " +
            "and part_id = ? ";

ps = con.prepareStatement(SELECT_SQL);
ps.setFetchDirection(ResultSet.FETCH_FORWARD);
ps.setFetchSize(1);
ps.setString(1, tool_code);
ps.setString(2, tool_number);
ps.setString(3, unit);
ps.setString(4, part_id);
rs = ps.executeQuery();

The query has space before and after '?' mark. The same query is not working with 11g and I'm getting below error:
java.sql.SQLException: ORA-01036: illegal variable name/number

If I remove the space before and after '?' mark. The same query is working with 11g.
Could anybody give some insight what could be the problem?

A: You have to avoid to set String in preparedstatement.
In preparedStatement , you need to set actual type.
ps.setString(1, tool_code);
ps.setInt(2, tool_number);
ps.setInt(3, unit);
ps.setString(4, part_id);

like that you have to do


text:
Q: Click event during scrolling of LazyRow not registered I have 2 LazyRows and a button. During scrolling of LazyRow A, I can click on the button without a problem, but when I click on a LazyRow A item during scrolling of LazyRow B, no click event is registered.
 Button(modifier = Modifier.size(50.dp), onClick = {
            // reached during scrolling of Lazy Row B
        }) {}
        // Lazy Row A
        LazyRow {
            items(10) {
                Box(modifier = Modifier.size(50.dp).clickable {
                    // not reached during scrolling of Lazy Row B
                })
            }
        }
        // Lazy Row B
        LazyRow {
            items(10) {
                Box(modifier = Modifier.size(50.dp))
            }
        }

Any idea why this happens and how one can override this behaviour?

A: The following code seems to work fine for me when pasted into a new "Empty Compose" project. The button and both of the LazyRow item sets are clickable and update the message.
@Composable
fun Greeting() {
    Column(modifier = Modifier.fillMaxSize()) {
        var message by remember { mutableStateOf("") }
        Text("message: $message")
        Button(
            modifier = Modifier.size(50.dp),
            onClick = {
                // reached during scrolling of Lazy Row B
                message = "Button clicked"
            }
        ) {}

        // Lazy Row A
        LazyRow {
            items(10) { i ->
                Text(
                    text = i.toString(),
                    modifier = Modifier.size(50.dp).background(Color.Gray)
                        .clickable {
                            // not reached during scrolling of Lazy Row B
                            message = "Row A clicked $i"
                        },
                )
                Spacer(modifier = Modifier.width(2.dp))
            }
        }
        // Lazy Row B
        LazyRow {
            items(10) { i ->
                Text(
                    text = i.toString(),
                    modifier = Modifier.size(50.dp).background(Color.Cyan)
                        .clickable {
                            message = "Row B clicked $i"
                        },
                )
                Spacer(modifier = Modifier.width(2.dp))
            }
        }
    }
}


text:
Q: Increase thickness of vistime y axis How to increase the Y-axis and thickness of the bar. I want to make it look big. Rather than being narrow
data <- read.csv(text="event,group,start,end,color
                            Phase 1,Project,2016-12-22,2016-12-23,#c8e6c9
                            Phase 2,Project,2016-12-23,2016-12-29,#a5d6a7
                            Phase 3,Project,2016-12-29,2017-01-06,#fb8c00
                            Phase 4,Project,2017-02-06,2017-03-02,#DD4B39
                            Room 334,Team 1,2016-12-22,2016-12-28,#DEEBF7
                            Room 335,Team 1,2016-12-28,2017-01-05,#C6DBEF
                            Room 335,Team 1,2017-01-05,2017-01-23,#9ECAE1
                            Group 1,Team 2,2016-12-22,2016-12-28,#E5F5E0
                            Group 2,Team 2,2016-12-28,2017-01-23,#C7E9C0
                            3-200,category 1,2016-12-25,2016-12-25,#1565c0
                            3-330,category 1,2016-12-25,2016-12-25,#1565c0
                            3-223,category 1,2016-12-28,2016-12-28,#1565c0
                            3-225,category 1,2016-12-28,2016-12-28,#1565c0
                            3-226,category 1,2016-12-28,2016-12-28,#1565c0
                            3-226,category 1,2017-01-19,2017-01-19,#1565c0
                            3-330,category 1,2017-01-19,2017-01-19,#1565c0
                            1-217.0,category 2,2016-12-27,2016-12-27,#90caf9
                            4-399.7,moon rising,2017-01-13,2017-01-13,#f44336
                            8-831.0,sundowner drink,2017-01-17,2017-01-17,#8d6e63
                            9-984.1,birthday party,2016-12-22,2016-12-22,#90a4ae
                            F01.9,Meetings,2016-12-26,2016-12-26,#e8a735
                            Z71,Meetings,2017-01-12,2017-01-12,#e8a735
                            B95.7,Meetings,2017-01-15,2017-01-15,#e8a735
                        T82.7,Meetings,2017-01-15,2017-01-15,#e8a735")
    gg_vistime(data)

A: gg_vistime can be used as a ggplot object. This means you can change the theme like this:
library(vistime)
gg_vistime(data) +
  theme(axis.ticks.y = element_line(colour = "black", size = 2))

Output:

Check this link for more information about creating custom themes in ggplot.

A: Trying using the linewidth argument to set your bar widths. Note that the value you set depends on the final size of your plot so you may need to play around to get an optimal value.
gg_vistime(data, linewidth=20)

Update:

You say you "don't want the data to overlap". I assume you mean the geom_points used for events that have the same start and end time (as these are the only elements I can see that overlap). Looking at the underlying code for the gg_vistime function, it appears that the point size is set to be the linewidth * 0.7.
If you want to set the point size independent of the bar linewidths, you can override the aesthetic parameters for geom_point in the returned ggplot object. For example...
gg <- gg_vistime(data, linewidth=20)
gg$layers[[3]]$aes_params$size = 10


text:
Q: template event class take any arg I have a simple event class, everything works fine with it.
Im trying to add a template class that i can pass arguments to and then read it when wait finishes.
At the moment i have it working with struct only as i need to set the arg to 0 if im not using it.
Is there a better/easier way to do this so i can pass any type of argument to it?
class Event
{
public:

    Event() : _signalled(false) {}

    virtual void notify()
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _signalled = true;
        _condvar.notify_one();
    }

    virtual void wait()
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _condvar.wait(lock, [&] { return _signalled; });
        _signalled = false;
    }

    void stop()
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _signalled = false;
    }

private:

    std::mutex _mutex;
    std::condition_variable _condvar;
    bool _signalled;
};

template <class T>
class ArgEvent : public Event
{
public:

    void notify()
    {
        Event::notify();
        this->arg = { 0 };
    }

    void notify(T arg)
    {
        Event::notify();
        this->arg = arg;
    }

    T getArg()
    {
        return this->arg;
    }

    void wait()
    {
        Event::wait();
    }

    void wait(T& arg)
    {
        Event::wait();
        arg = this->arg;
    }

private:
    T arg;
};

A: Boost.Optional allows the implementation to work without c++17.
https://www.boost.org/doc/libs/1_67_0/libs/optional/doc/html/index.html


text:
Q: Can you convert Visual Studio 7.10 project to Visual Studios 2012? I haven't programmed in a while and was interested in getting back into c++. my internet is very slow so I'm still in the process of downloading it.
I have a project that some one else wrote and I'm trying to understand the algorithms and rewrite it to suit my needs but it is vs 7.10 project

A: Converting from an older version may cause problems, here and here
you can find more about converting from an older version. You can also try to make rebuild the code manually, you can rewrite the project in a newer version by yourself and this will also help you understand the code.


text:
Q: Triggering widget animation from outside widget I have a custom widget that has normal / animated state. Sometimes I want to be it animated, and sometimes static.
I have made a simple test project to demonstrate my problem: test page contains my custom widget (ScoreBoard) and 2 buttons to start / stop animating scoreboard. My problem, that ScoreBoard is not animated, even if I start animation.
Here is my code:
TestPage:
class TestPage extends StatefulWidget {
  @override
  _TestPageState createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> {
  bool _animate;

  @override
  void initState() {
    _animate = false;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          ScoreBoard(
            text: "Hello, world!",
            animate: _animate,
          ),
          FlatButton(
            child: Text("START animation"),
            onPressed: () {
              setState(() {
                _animate = true;
              });
            },
          ),
          FlatButton(
            child: Text("STOP animation"),
            onPressed: () {
              setState(() {
                _animate = false;
              });
            },
          ),
        ],
      ),
    );
  }
}

ScoreBoard widget:
class ScoreBoard extends StatefulWidget {
  final String text;
  final bool animate;

  const ScoreBoard({Key key, this.text, this.animate}) : super(key: key);

  @override
  _ScoreBoardState createState() => _ScoreBoardState();
}

class _ScoreBoardState extends State<ScoreBoard>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = new AnimationController(
      duration: const Duration(seconds: 1),
      vsync: this,
    )..forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return widget.animate
        ? ScaleTransition(
            child:
                Text(widget.text, style: Theme.of(context).textTheme.display1),
            scale: new CurvedAnimation(
              parent: _controller,
              curve: Curves.easeIn,
            ),
          )
        : Container(
            child:
                Text(widget.text, style: Theme.of(context).textTheme.display1),
          );
  }
}

Would you be so kind to help me? Thanks in advance!

A: Answer
If you initialize an AnimationController widget and do not specify arguments for lowerBound and upperBound (which is the case here), your animation is going to start by default with lowerBound 0.0.

AnimationController({double value, Duration duration, String debugLabel, double lowerBound: 0.0, double upperBound: 1.0, AnimationBehavior animationBehavior: AnimationBehavior.normal, @required TickerProvider vsync })
  Creates an animation controller. [...]

https://docs.flutter.io/flutter/animation/AnimationController-class.html
If you initialize the state of your widget ScoreBoard, the method forward gets called only once during the whole lifetime of your app. The method forward makes that your animation increases from the lowerBound (0.0) to the upperBound (1.0) within 1 second.

Starts running this animation forwards (towards the end).

https://docs.flutter.io/flutter/animation/AnimationController/forward.html
In our case, there is no way back once the method forward got called. We are only able to stop the animation.
Press Ctrl + F5 for a full restart of the app to see the animation.
To make it even clearer, change the duration of your animation to 10 seconds.
Btw. since Dart 2 you do not need to use the new keyword.
  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 10),
      vsync: this,
    )..forward();
  }

Example
To see what happens you could add this to your build method:
  @override
  Widget build(BuildContext context) {
    // Execute 'reverse' if the animation is completed
    if (_controller.isCompleted)
      _controller.reverse();
    else if (_controller.isDismissed)
      _controller.forward();
    // ...

... and do not call the method forward in the initState method:
  @override
  void initState() {
    super.initState();
    _controller = new AnimationController(
      duration: const Duration(seconds: 10),
      vsync: this,
    );
  }


text:
Q: Ошибка в phpsrorm. No data sources are configured to run this SQL and provide advanced code assistance Warning: mysql_query() expects parameter 1 to be string, object given in ..\account.php on line 13
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null ..\account.php on line 13
Warning: mysql_query() expects parameter 1 to be string, object given in ..\account.php on line 15
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given in ..\account.php on line 15
Warning: mysql_query() expects parameter 1 to be string, object given in ..\account.php on line 17
Ошибка: No data sources are configured to run this SQL and provide advanced code assistance. Disable this inspection via problem menu (Alt+Enter). Please configure SQL dialect for this file. Advanced features such as code completion, navigation and inspection will be activated.

A: Включаем закладку "Базы данных" View -> Tool windows -> Database
На ней подключаем ту же базу данных к которой обращаемся в коде PHP
Также желательно указать диалект SQL (PL SQL, T-SQL, mySQL), т.к. у них немного разный синтаксис, и поэтому PHPStorm тоже ругается. Вот инструкция где указывать: https://www.jetbrains.com/help/phpstorm/2016.2/sql-dialects.html


text:
Q: Is there a bash command to do this? I want to know if new files/directories have been created in a specific directory A since a fixed date time.
Is there a bash command to do this?

A: No, since creation dates aren't stored on most *nix filesystems. Try find with the -amin, -atime, -mmin, or -mtime predicates.

A: $ man find

http://unixhelp.ed.ac.uk/CGI/man-cgi?find

A: use the touch command to create a dummy file. eg touch .dummy. then use the find command with -newer option to check for new files. eg
find /path -newer .dummy


text:
Q: Remove a key from INI file during installation I know how to insert a key to INI file during installation - this is the way I use it:
[INI]
Filename: mydefine.ini; Section: "General"; Key: "Lic"; String: "9O/2Xv"

My question is about removing a key during installation (yes - I'm not talking about uninstall).
Is that possible to remove a key during installation? How to?
I'd prefer to remove the key (rather than leaving it as an empty text).
The context:
We use some internal unit-testing during development and I turn them on if a key does exist on the INI file. I want to make sure that the key will never be released to users, so I want to explicitly remove it during installation.
THANK YOU

A: The only way, at this time, is using scripting code. To be more specific, the DeleteIniEntry function. For example, if you'd like to remove the Key key from the Section section of a certain INI file before the installation starts, you might write:
[Code]
function PrepareToInstall(var NeedsRestart: Boolean): string;
begin
  DeleteIniEntry('Section', 'Key', 'C:\File.ini');
end;


text:
Q: Conditionally enabling an external system integration in Spring Boot I'm trying to implement support for several alternative integrations to external systems in a Spring Boot app. The idea is that a specific environment variable defines which integration is in use (there can only be one enabled at a time), and Spring Boot only initializes the components (@Configuration, @Service, @RestController etc.) specific to that integration. Is there a best practice approach for doing this?
Currently I'm thinking of something like this:

*

*Create one @Configuration class per integration, annotate it with @ConditionalOnProperty. Read all relevant environment variables during app initialization, validate them, and prevent the app from starting if the configurations are invalid.

*Annotate all other components related to that particular integration with @ConditionalOnBean, and make them dependent on the configuration bean being initialized.

Simplified example:
@Configuration
@ConditionalOnProperty(prefix = "integration", name = "name", havingValue = "FOO")
class FooConfig {
    // Read environment variables etc.
}

@Service
@ConditionalOnBean(FooConfig.class)
class FooService implements ExternalSystemIntegration {

    @Inject
    // Inject the configuration to get access to the relevant environment variables
    public FooService(FooConfig config, ...) { ... }

    @Override
    public void doIt() { ... }
}

Does this approach seem reasonable, or can you see some problems with it? One (small) downside is that it's not immediately clear which components are related to a specific integration (you need to find out which components depend on the configuration bean).
One alternative solution would be to create only one configuration class with a bunch of @Bean methods that would use the various @Conditional* annotations to control which components should be initialized. However, this would require manually feeding the dependencies to the created beans (as we use constructor injection), which I'd very much like to avoid. And I'm not sure if there's a good way to control which environment variables to read and validate during app bootstrapping with this solution.

A: @Conditional... bean definitions are indeed the typical approach for this, and your approach sounds reasonable. If you're concerned that it might be hard to find which components depend on the configuration bean, you could:

*

*declare your own @Conditional annotation, allowing you to find all matching components by scanning for the uses of that annotation, or

*move all bean definitions sharing a condition into a configuration class with that condition, declaring the services using java based configuration. The disadvantage is that java based configuration makes constructor injection a bit verbose.

*or you could move these into separate packages, and use conditional component scanning to only pick up the beans you want. However, that is only easy if the conditional packages are outside your normal package root, which is overkill in most cases.


text:
Q: Editing cloud formation templates terminates existing instances and creates new instances We are using a cloud formation template for a set of VMs and each time after the code deployment , we need to edit the package version on the template parameters for auto scaling to take the latest package from the s3 bucket.
The issue is, editing cloud formation template triggers a cloudformation-based upgrade of the instances(which involves destroying the existing machines and creating new ones from scratch, which is time consuming).
Is there anyway we can prevent this.
Basically, we dont need the cloud formation template to destroy and recreate the instances whenever we edit it.?
EDIT : This my autoscaling group setting
    "*********":{
        "Type":"AWS::AutoScaling::AutoScalingGroup",
        "Properties":{
            "AvailabilityZones":[
                {
                    "Ref":"PrimaryAvailabilityZone"
                }
            ],
            "Cooldown":"300",
            "DesiredCapacity":"2",
            "HealthCheckGracePeriod":"300",
            "HealthCheckType":"EC2",
            "LoadBalancerNames":[
                {
                    "Ref":"elbxxbalancer"
                }
            ],
            "MaxSize":"8",
            "MinSize":"1",
            "VPCZoneIdentifier":[
                {
                    "Ref":"PrivateSubnetId"
                }
            ],
            "Tags":[
                {
                    "Key":"Name",
                    "Value":"my-Server",
                    "PropagateAtLaunch":"true"
                },
                {
                    "Key":"VPCRole",
                    "Value":{
                        "Ref":"VpcRole"
                    },
                    "PropagateAtLaunch":"true"
                }
            ],
            "TerminationPolicies":[
                "Default"
            ],
            "LaunchConfigurationName":{
                "Ref":"xxlaunch"
            }
        },
        "CreationPolicy":{
            "ResourceSignal":{
                "Timeout":"PT10M",
                "Count":"1"
            }
        },
        "UpdatePolicy":{
            "AutoScalingRollingUpdate":{
                "MinInstancesInService":"1",
                "MaxBatchSize":"1",
                "PauseTime":"PT10M",
                "WaitOnResourceSignals":"true"
            }
        }
    },

A: You can look at the documentation and view the Update requires: field on the property you modifying on your CF template.
If it says Replacement it will recreate the instance, with a new logical id
If it says Some Interruption it will make the instance unavailable, in the ec2 case, restarting it, but will not recreate the instance, keeping the same logical id
If it says No interruption it will not impact the instance at all
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html


text:
Q: Action from page not handled in controller in ASP.NET CORE I created controller and views with default utility in VS that generate code.
When I click on create button on Create page I always have exception and breakpoints in Create method not working. I try change some handlers, change arguments or change asp-action for form but I couldn't enter to Create handler.
How I can fix it?
Create page
@model BulkyBook.Models.Category

@{
    ViewData["Title"] = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Create

Category

        <form asp-action="Create">

                <input asp-for="Name" class="form-control" />

                <input type="submit" value="Create" class="btn btn-primary" />

        </form>

    Back to List

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Part of controller core that not working
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using BulkyBook.DataAccess.Data;
using BulkyBook.Models;

namespace BulkyBook.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class CategoriesController : Controller
    {
        private readonly ApplicationDbContext _context;

        public CategoriesController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: Admin/Categories
        public async Task<IActionResult> Index()
        {
            return View(await _context.Categories.ToListAsync());
        }

        // GET: Admin/Categories/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Admin/Categories/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,Name")] Category category)
        {
            if (ModelState.IsValid)
            {
                _context.Add(category);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(category);
        }
    }
}

Exception

A: Can you describe what kind of exception that you are getting when you clicking the Create Button

A:
When I click on create button on Create page I always have exception and breakpoints in Create method not working. I try change some handlers, change arguments or change asp-action for form but I couldn't enter to Create handler.

It seems that you create and use Areas feature in your project, please check if you create/copy _ViewImports.cshtml file with following code snippet to the appropriate view folder under areas, which could help make Tag Helpers available for your areas view(s).
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

For more information, please check this doc:
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/areas?view=aspnetcore-5.0#_viewimportscshtml
Besides, if your view page Create is not in the same area, please explicitly asp-area="admin" for your form tag helper.

A: <form asp-action="Create" asp-area="Admin" method="post">

Please try above bold area.
And let me know if it's not work.


text:
Q: How can I install Ubuntu in a computer without an OS? I got a computer from my office and ordered IT to wipe it all from Windows OS. Now how can I get Ubuntu OS on this computer?

A: It's so simple. Just download Ubuntu from this official website.
http://www.ubuntu.com/download/desktop
Burn it to a DVD.
Insert it and change the boot device order in BIOS to DVD drive.
Now boot from the DVD and follow this link to install Ubuntu from DVD.
https://help.ubuntu.com/community/Installation


text:
Q: Do custom wrapper classes take more/less space than Java wrapper classes? Public class A
{
    int a;

}

vs.
java.lang.Integer
Or Longs, Doubles, etc.
Do they take the same amount of memory? Or more/less? If I'm not missing anything the answer should be same...

A: The purpose of the wrapper classes are to be able to treat a primitive as an object by wrapping it in an Integer object, allowing you to call methods from it, or pass it as a parameter value for parameters that require an Object rather than a primitive.
Creating your own wrapper for a primitive, such as you are doing now, is not advised, as it will not allow for auto-boxing and unboxing of primitives. There's more functionality you are losing, but if we're talking memory, you'll save more memory over-time using Integer rather than your personal wrapper, since there is a constant pool for integer objects, allowing you to re-use a pre-existing value from the pool if one exists, instead of creating a new object every time. You'd need to implement the flyweight pattern to achieve the same kind of memory-saving system.


text:
Q: Angular2 + PrimeNG - Dropdown selected value not working properly if Editable is set I have an Angular2 application with PrimeNG suite installed.
I'm trying to implement a form with a primeNG dropdown component.
The problem happens when I run the application and I select an element from the listbox.
Instead of shows the value, it shows [object Object]
the problem

html component
 <p-dropdown [options]="listCustomers_itm" placeholder="Selezionare" formControlName="Customer_itm" [(ngModel)]="Customer_itm" filter="filter" editable="editable"> </p-dropdown>

declarations
 /*primeng listBox */
  Customer_itm: SelectItem;
  listCustomers_itm: SelectItem[];

ts code to fill the options:
this.mdService.Get_Customer(false).subscribe(
      data => {
        this.listCustomers = data;

        this.listCustomers_itm = [];
        for (let c of this.listCustomers) {
          this.listCustomers_itm.push({ label: (c.code + ' - ' + c.businessName), value: { id: c.idCustomer, name: c.businessName, code: c.code } });
        }

      }
    );

If instad of use custom label and value, is use flat values like:
this.listCustomers_itm.push({ label: c.code, value:c.businessName });

All works properly...
I tried also to implement onChange function:
  onCustomerSelect(e)
  {
    console.log(e);
  }

The ouput in the console when I select an item is:
Object { id: 5, name: "Luigino Gatto", code: "5" }

I finally discovered that the code works properly if I remove editable="editable" attribute, but I need to set it editable...
Thanks to support

A: Instead of pushing individual values in the value you can put the entire object in it.
this.mdService.Get_Customer(false).subscribe(
  data => {
    this.listCustomers = data;

    this.listCustomers_itm = [];
    for (let c of this.listCustomers) {
      this.listCustomers_itm.push({ label: (c.code + ' - ' + c.businessName), value: c });
    }

  }
);

A: from your template it looks like to trying to work with model driven (formcontrolName)
and template driven (ngModel) approach.
which does not make sense.
<p-dropdown [options]="listCustomers_itm" placeholder="Selezionare" **formControlName**="Customer_itm" **[(ngModel)]**="Customer_itm" filter="filter" editable="editable"> </p-dropdown>

Please select the appropriate why and use it correctly.

A: I was having the same issue. From what I can tell, when provided with an object as a value, the p-dropdown component will call value.toString().
In order to fix this, I added the following method to the object I wanted in the value field.
toString() : string{
  return this.name.toString();
}

Just to clarify as to why I'm using name.toString() - Prime likes to work with Typescripts primitive string rather than the wrapper object String.


text:
Q: Angular Material component not working: 'mat-option' is not a known element I am trying to add angular material component. but the component did not work properly. that error said
Uncaught Error: Template parse errors: 'mat-option' is not a known element:
// ...

I think the error comes from app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { SidebarComponent } from './sidebar/sidebar.component';
import { PostsComponent } from './posts/posts.component';
import { UsersComponent } from './users/users.component';
import { DetailsComponent } from './details/details.component';
import { HttpClientModule } from '@angular/common/http';
import { FooterComponent } from './footer/footer.component';
import {MatButtonModule, MatCheckboxModule} from '@angular/material';
import {MatFormFieldModule} from '@angular/material/form-field';
import { MyFormComponent } from './my-form/my-form.component';
@NgModule({
  declarations: [
    AppComponent,
    SidebarComponent,
    PostsComponent,
    UsersComponent,
    DetailsComponent,
    FooterComponent, MyFormComponent
  ],
  imports: [
    BrowserModule, AppRoutingModule,HttpClientModule,MatButtonModule, MatCheckboxModule,MatFormFieldModule
  ]
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

A: You need to import MatSelectModule cause mat-option are declared inside this module and add this into the AppModule imports
import { ..., MatSelectModule, ... } from '@angular/material';

@NgModule({
   imports: [ ..., MatSelectModule, ...]
})
export class AppModule { }

A: You need to import MatSelectModule,
imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    MaterialModule,
    MatSelectModule,
    //..Other modules here
],

A: Actually you also need to add MatOptionModule not just MatSelectModule.
imports: [
  ...
  MatSelectModule,
  MatOptionModule,
  ...
],

Otherwise you may encounter problems when setting the value of your mat-option.

A: I amazed that none of the answers given by the user is correct, how I knew that?
is because i faced the same problem by myself.
the solution is to import
import {MatSelectModule} from '@angular/material/select';
and write in import
MatSelectModule

A: You need to import MatSelectModule in AppModule.ts
import {MatButtonModule, MatCheckboxModule, MatSelectModule} from '@angular/material';

imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    MatButtonModule,
    MatCheckboxModule,
    MatFormFieldModule,
    MatSelectModule
  ]

A: It is likely that most people make a custom component which they then add to "shared.module.ts"
In this case, you should pay attention to what you need to import into the custom component itself
custom-select.module.ts
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { MatInputModule } from '@angular/material/input';
import { CustomSelectComponent } from './custom-select.component';
import { MatSelectModule } from '@angular/material/select';

@NgModule({
  declarations: [CustomSelectComponent],
  imports: [CommonModule, MatSelectModule, FormsModule],
  exports: [CustomSelectComponent, MatInputModule],
})
export class CustomSelectModule {}

shared.module.ts
import { NgModule } from '@angular/core';
import { CustomSelectModule } from './components/customSelect/custom-select.module';
import { DatePipe } from './pipes/date.pipe';

@NgModule({
  declarations: [
    ...
  ]
  imports: [
    ...

    M̶a̶t̶S̶e̶l̶e̶c̶t̶M̶o̶d̶u̶l̶e̶,̶,
    CustomSelectModule,
    ...
  ],
  exports: [
    ...
    M̶a̶t̶S̶e̶l̶e̶c̶t̶M̶o̶d̶u̶l̶e̶,
    CustomSelectModule,
    ...
  ],
})
export class SharedModule {}


text:
Q: i want to have a vertical scrollbar in my bootstrap table by giving the height How to have a vertical scrollbar in the bootstrap table?
I have given a height of 100px but the table is taking more than 100 px and scroll is not coming for the table

A: Firstly you need to apply the scroll;
    overflow-x: auto;

or
    overflow-y: auto;

Then finally to prevent movement in the opposite axis you should disregard whitespace.
    white-space: nowrap;


text:
Q: How to add image to an HTML page after creating/drawing the image in the browser? I am using https://github.com/szimek/signature_pad to create an HTML page which allows for someone to sign a form. On my web page I have some text and then at the bottom I have the signature pad canvas which allows someone to draw/sign. What I want to do is have someone write on the canvas, and then click a button which then adds the exact image they just wrote/drew to the bottom of the page. I am using javascript to handle the addition of signature pad, so far my method looks like this (when they click the button this code runs):
var data = signaturePad.toDataURL('image/png');
  //window.open(data);
I don't want to open a new window and have the image show there. I want to have the canvas be placed at the bottom of the page, which I will then convert the whole page to PDF.

A: Here is an example in which you need to tweak the coordinates and some parameters to serve your purpose:

        <canvas id="can" width="400" height="400" style="position:absolute;top:10%;left:10%;border:2px solid;"></canvas>

Choose Color

Eraser

        <input type="button" value="save" id="btn" size="30" onclick="save()" style="position:absolute;top:55%;left:10%;">
        <input type="button" value="clear" id="clr" size="23" onclick="erase()" style="position:absolute;top:55%;left:15%;">