text:
Q: Map /phpmyadmin to a different folder in apache with Centos 7 I used the following instructions to install phpMyAdmin into Centos 7 webserver:
wget https://files.phpmyadmin.net/phpMyAdmin/4.6.5.2/phpMyAdmin-4.6.5.2-all-languages.tar.gz
tar xvzf phpMyAdmin-4.6.5.2-all-languages.tar.gz
mv phpMyAdmin-4.6.5.2-all-languages phpmyadmin
mv phpmyadmin /var/www/html/

Oddly (different from what I read in other questions), phpMyAdmin was installed here:
/var/www/html/phpmyadmin
And the phpmyadmin config file is here:
/var/www/html/phpmyadmin/config.inc.php
With the default apache configuration, the website is viewed from /var/www/html and phpMyAdmin is viewed from /var/www/html/phpmyadmin, and looks like this in the URL:
http://www.foo.com/phpmyadmin

So far so good, all working.
However, I added a virtual host and am now serving the website out of /var/www/foo.com/public_html
<VirtualHost *:80>
   ServerAdmin admin@example.com
   DocumentRoot /var/www/foo.com/public_html
   ServerName foo.com
   ServerAlias www.foo.com
   ErrorLog /var/www/foo.com/error.log
</VirtualHost>

It works if I mv  /var/www/html/phpmyadmin  /var/www/foo.com/public_html, but when logging in via FTP, I don't want the phpmyadmin folder to be visible under the /var/www/foo.com/public_html folder.
Is there a way to leave phpmyadmin in its original location at /var/www/html/phpmyadmin, but still be accessible via the url http://foo.com/phpmyadmin ?

A: You can actually put the folder anywhere as long as there is r-x permissions(not sure about write permissions).
For Apache v1:
Edit /etc/httpd/conf-available/phpmyadmin.conf or wherever the httpd folder is
Add the line Alias /phpmyadmin /location-of-folder if it is not already there
Run systemctl restart httpd
For Apache v2:
Edit /etc/apache2/conf-available/phpmyadmin.conf or wherever the apache2 folder is
Add the line Alias /phpmyadmin /location-of-folder if it is not already there
Run systemctl restart apache2

A: Just create symbolic link to your original phpmyadmin folder in
/var/www/html => ln -s {path of phpmyadmin} /var/www/html/phpmyadmin folder and configure httpd to Allow symbolic links with FollowSymLinks option


text:
Q: Is an explicit KEY redundant if it is covered by a UNIQUE KEY? I am auditing an application which I've been developing over the course of several weeks. I've noticed this in CREATE TABLE:
UNIQUE KEY `baz_3` (`baz`,`foo`,`bar`),
KEY `baz` (`baz`),

Is the explicit KEY redundant, as I think it is? I just want to make sure before I DROP it. From what I've read I do believe that the  UNIQUE KEY will act as an Index when the application performs WHERE baz='something' but MySQL seems so intricate that I find it prudent to ask here first.

A: Yes, you can drop it because baz and baz_3 have identical leading columns. This scenario is known as having redundant indexes.
However, be careful that the key baz is not being used to support a foreign key constraint if the table is InnoDB. See my post Do I have duplicate key indexes?
If the table is MyISAM, go ahead and drop it with confidence. The MySQL Query Optimizer will use the UNIQUE KEY baz_3 for query optimization in its execution plans.
If you want to locate all tables with redundant indexes, see this post : MySql - find redundant indexes

redpajama_set_name: RedPajamaStackExchange


text:
Q: Select2 multiselect duplicates values http://jsfiddle.net/tXFbk/2/
HTML:

    Some ID

        <input type="text" id="some_id" name="some_id" class="span4"/>

JS:
$(function() {
    $('#some_id').select2({
        allowClear: true,
        placeholder: 'Some ID',
        minimumInputLength: 2,
        multiple: true,
        data: [
            {id: 1, text: 'some text'},
            {id: 2, text: 'some other text'},
            {id: 3, text: 'some more text'}
        ]
    });
    $('#some_id').select2('data', [
        {'id':1,'text':'some text'}
    ]);

    console.log($('#some_id').select2('val'));
});

On first load it duplicates values and after clearing value it doesn't clear it from input. Also if you add an item (eg. "some more text") and then remove it, it doesn't clear it from input value. Is there any way to make it stop duplicating values?
One more thing - how to disable adding already added items?

A: Select2 4.0.0 support duplicate tags.
Jsfiddle Demo link
$eventSelect.on("select2:select", function (e) {
    log("select2:select", e);
  $eventSelect.append('<option value="'+e.params.data.text+'">' +e.params.data.text + '</option>');
});

$eventSelect.on("select2:unselect", function (e) {
    log("select2:unselect", e);
    e.params.data.element.remove();
});

function formatResultData (data) {
  if (!data.id) return data.text;
  if (data.element.selected) return
  return data.text;
};

Base on select2 event and github issues
Pic:

A: Check the following On Selecting event, and setting the isNew property in createSearchChoice
let me know if it resolved your issue
$('#some_id').select2({
            tags: true,
            tokenSeparators: [","],
            createSearchChoice: function (term, data) {
                if (term.trim().length > 0) {
                    if ($(data).filter(function () {
                      return this.text.toLowerCase().localeCompare(term.toLowerCase()) === 0;
                    }).length === 0) {
                        return {
                            id: term,
                            text: term,
                            isNew: true // this is necessary to check if the item is newly added or not
                        };
                    }
                }
            },
            multiple: true,
            minimumInputLength: 1,
            allowClear: true,
            data: [
        {id: 1, text: 'some text'},
        {id: 2, text: 'some other text'},
        {id: 3, text: 'some more text'}
    ],
        }).on("select2-selecting", function (e) {
            var tagId = '';
            if (e.choice.isNew) {
                self.AddTagToDatabase(e.choice.text);
            } else {
                var isValidTag = true;
                $(config.element[0] + ' ul li').find('div').each(function (index, item) {
                    if ($(item).html().toLowerCase().trim() == e.choice.text.toLowerCase().trim()) {
                        isValidTag = false;
                        e.choice.text = '';
                        return;
                    }
                });
            }
        })

A: You need to trigger the change event of select2 to reflect the changes.
$("#dropdownId").val("yourValues").trigger("change");

after setting the values, you need to fire trigger values manually, to reflect the latest changes done in your dropdownlist


text:
Q: Leaflet legend not working as intended The legend for one layer in a series is not showing all colors and I cant find out why.
I am confused. I have done a couple of legends by now working on an application and there is this one layer where the legend simply wont behave.
The legend is not picking up any other color but one so all squares are the same color. I have checked and recoded it many times. There has to be something else I'm missing. I have done a jsfiddle with a sample from my data to test and I was surprised to see it do the same thing there.
What could cause this?
JSFiddle
Sample of the code:
//Get color for Index
function getColorInd(d) {
    return d >= 0.51 ? '#7a0177' :
    d >= 0.44 && d <= 0.50 ? '#c51b8a' :
    d >= 0.33 && d <= 0.43 ? '#f768a1' :
    d >= 0.16 && d <= 0.32 ? '#fbb4b9' :
    '#feebe2';
}

[...]

var legend = L.control({position: 'bottomright'});
legend.onAdd = function (map) {

    var div = L.DomUtil.create('div', 'info legend'),
        labels = ['index'],
        lower = [0, 0.16, 0.33, 0.44, 0.51],
        upper = [0.15, 0.32, 0.43, 0.50, 0.68];

    for (var i = 0; i < lower.length; i++) {
        div.innerHTML += labels.push(
            ' '+
            lower[i] + '–' + upper[i]);
    }
    div.innerHTML = labels.join('
');
    return div;
};

legend.addTo(map);

var geojson = L.geoJson(Sample, {
    style: styleInd,
    onEachFeature: onEachFeature
}).addTo(map);

A: You're doing a logical mistake.
You're using getColorInd(lower[i] + 1)
replace this by getColorInd(lower[i])
means just remove the  +1 from the function and it'd work nicely.
here is the updated fiddle


text:
Q: QueryDSL: Query by composite primary key I have an entity Parte with a composite primary key. These are the columns:

*

*codabast

*codejerc

*codparte
I have annotated my entity with @IdClass(PartePK.class). Now, to perform a query by primary key, I do this:
JPAQuery query = new JPAQuery(entityManager);

query.from(qParte).where(qParte.codabast.eq(myCodAbast)
    .and(qParte.codejerc.eq(myCodEjerc)
    .and(qParte.codparte.eq(myCodParte))));

Parte p = query.singleResult(qParte);

Is it needed to do it field by field? Or does exist a way to query by primary key?
I would like something like this:
PartePK primaryKey = new PartePK(3, 4, 6);
query.from(qParte).byId(primaryKey);

Thanks in advance.


text:
Q: HP-UX - custom rsync path There are a range of HP-UX 11.11 hosts I'm unable to install rsync (I'm limited to a non-privileged user)
I've extracted both rsync binary and libpopt.sl, libiconv.sl, libintl.sl from the depots into one of that user's directories:
/home/zenith/rsync/
Problem is,
I can't get my RH Linux box communicating with it:
rsync -e --rsync-path=/home/zenith/rsync/rsync --compress=9 -pgtov --filter=+rs_/'*.log' --exclude='*' zenith@192.102.14.18:/home/zenith/service/logs/ /u01/rsync_depot/service/192.102.14.18/

/usr/lib/dld.sl: Can't find path for shared library: libintl.sl
/usr/lib/dld.sl: No such file or directory
sh: 1644 Abort(coredump)

I've added to the remote host .profile
export SHLIB_PATH=/usr/lib:/home/zenith/rsync
export PATH=$PATH:/home/zenith/rsync

but still, no libintl.sl is found.
How can I initialize the correct env variable/ get this to work?

A: How about adding LD_LIBRARY_PATH variable and adding the directory where the shared library is?


text:
Q: how do i display user input on the same page, with the option to delete Good day programmers. I am very new to jsp/javascript but this site has helped me a lot so far, but i can use some more help or guidance for a problem i am having.
I am making a web app for creating and saving recipes. For my "add recipe" process, i have the user enter a recipe name, they are then directed to another page where they can choose an ingredient from a dropdown (populated from a sql db), enter a quantity, and then click a button to ad another ingredient.
What i wish to do is have the ingredient selected and the amount displayed to the user on the same page where they are choosing the ingredients. I also want to add a button at the end of the "print out" that allows the user to remove that ingredient.
So far i am thinking that i should use a table and have a row created when the user adds an ingredient, then use the deleterow() method to remove that ingredient if desired.
Does anyone think this can work? or have a better solution.
PS: i am very new to jsp and javascript.
thanks in advance for any assistance rendered.

A: You can use ajax to achieve this. For that using jQuery will make you writing a lot less number of lines of code.
So it will work like this, they have entered the recipe name. Now using onblur on that field input, you load the dropdown of ingredients and give them option of entering quantity and selecting the ingredient with a button to save that data.
When they click on the button to save, after it getting saving into the database, you make an ajax call to load the recent added item with a button to delete it and when they click on delete, you make another ajax call to the database to delete it.
Here is a guide to ajax on javaScript
https://developer.mozilla.org/en-US/docs/AJAX


text:
Q: What is the difference between Bootstrap .container and .container-fluid classes? Just downloaded 3.1 and found in the docs...

Turn any fixed-width grid layout into a full-width layout by changing your outermost .container to .container-fluid.

Looking in bootstrap.css, it appears that .container-fluid is identical to .container.  Both have the same CSS, and every instance of .container-fluid is paired with .container, and all column classes are specified in percentages.
When twiddling with examples I could not see any difference, as everything seemed fluid.
What is the difference between Bootstrap .container and .container-fluid classes?

A: Quick version: .container has one fixed width for each screen size in bootstrap (xs,sm,md,lg); .container-fluid expands to fill the available width.

The difference between container and container-fluid comes from these lines of CSS:
@media (min-width: 568px) {
  .container {
    width: 550px;
  }
}
@media (min-width: 992px) {
  .container {
    width: 970px;
  }
}
@media (min-width: 1200px) {
  .container {
    width: 1170px;
  }
}

Depending on the width of the viewport that the webpage is being viewed on, the container class gives its div a specific fixed width. These lines don't exist in any form for container-fluid, so its width changes every time the viewport width changes.
So for example, say your browser window is 1000px wide. As it's greater than the min-width of 992px, your .container element will have a width of 970px. You then slowly widen your browser window. The width of your .container won't change until you get to 1200px, at which it will jump to 1170px wide and stay that way for any larger browser widths.
Your .container-fluid element, on the other hand, will constantly resize as you make even the smallest changes to your browser width.

A: .container has a max width pixel value, whereas .container-fluid is max-width 100%.
.container-fluid continuously resizes as you change the width of your window/browser by any amount.
.container resizes in chunks at several certain widths, controlled by media queries (technically we can say it's "fixed width"
because pixels values are specified, but if you stop there, people may get the
impression that it can't change size – i.e. not responsive.)

A: From a display perspective .container gives you more control over the what the users are seeing, and makes it easier to see what the users will see as you only have 4 variations of display (5 in the case of bootstrap 5) because the sizes relate to the same as the grid sizes. e.g. .col-xs, .col-sm, .col, and .col-lg.
What this means, is that when you are doing user testing if you test on a displays with the 4 different sizes you see all the veriations in display.
When using .container-fluid because the witdh is related to the viewport width the display is dynamic, so the varations are much greater and users with very large screens or uncommon screen widths may see results you weren't expecting.

A: Use .container-fluid when you want your page to shapeshift with every little difference in its viewport size.
Use .container when you want your page to shapeshift to only 4 kinds of sizes, which are also known as "breakpoints".
The breakpoints corresponding to their sizes are:

*

*Extra Small: (Only Mobile Resolution)

*Small: 768px (Tablets)

*Medium: 992px (Laptops)

*Large: 1200px (Laptops/Desktops)

A: I think you are saying that a container vs container-fluid is the difference between responsive and non-responsive to the grid. This is not true...what is saying is that the width is not fixed...its full width!
This is hard to explain so lets look at the examples

Example one
container-fluid:
http://www.bootply.com/119981
So you see how the container takes up the whole screen...that's a container-fluid.
Now lets look at the other just a normal container and watch the edges of the preview
Example two
container
http://www.bootply.com/119982
Now do you see the white space in the example? That's because its a fixed width container ! It might make more sense to open both examples up in two different tabs and switch back and forth.
EDIT
Better yet here is an example with both containers at once! Now you can really tell the difference!
http://www.bootply.com/119983
I hope this helped clarify a little bit!

A: Both .container and .container-fluid are responsive (i.e. they change the layout based on the screen width), but in different ways (I know, the naming doesn't make it sound that way).
Short Answer:
.container is jumpy / choppy resizing, and
.container-fluid is continuous / fine resizing at width: 100%.
From a functionality perspective:
.container-fluid continuously resizes as you change the width of your window/browser by any amount, leaving no extra empty space on the sides ever, unlike how .container does. (Hence the naming: "fluid" as opposed to "digital", "discrete", "chunked", or "quantized").
.container resizes in chunks at several certain widths. In other words, it will be different specific aka "fixed" widths different ranges of screen widths.
Semantics: "fixed width"
You can see how naming confusion can arise. Technically, we can say .container is "fixed width", but it is fixed only in the sense that it doesn't resize at every granular width. It's actually not "fixed" in the sense that it's always stays at a specific pixel width, since it actually can change size.
From a fundamental perspective:
.container-fluid has the CSS property width: 100%;, so it continually readjusts at every screen width granularity.
.container-fluid {
  width: 100%;
}

.container has something like "width = 800px" (or em, rem etc.), a specific pixel width value at different screen widths. This of course is what causes the element width to abruptly jump to a different width when the screen width crosses a screen width threshold. And that threshold is governed by CSS3 media queries, which allow you to apply different styles for different conditions, such as screen width ranges.
@media screen and (max-width: 400px){
  .container {
    width: 123px;
  }
}
@media screen and (min-width: 401px) and (max-width: 800px){

  .container {
    width: 456px;
  }
}
@media screen and (min-width: 801px){
  .container {
    width: 789px;
  }
}

Beyond
You can make any fixed widths element responsive via media queries, not just .container elements, since media queries is exactly how .container is implemented by bootstrap in the background (see JKillian's answer for the code).

A: Updated 2019
The basic difference is that container is scales responsively, while container-fluid is always width:100%. Therefore in the root CSS definitions, they appear the same, but if you look further you'll see that .container is bound to media queries.
Bootstrap 4
The container has 5 widths...
.container {
  width: 100%;
}

@media (min-width: 576px) {
  .container {
    max-width: 540px;
  }
}

@media (min-width: 768px) {
  .container {
    max-width: 720px;
  }
}

@media (min-width: 992px) {
  .container {
    max-width: 960px;
  }
}

@media (min-width: 1200px) {
  .container {
    max-width: 1140px;
  }
}

Bootstrap 3
The container has 4 sizes. Full width on xs screens, and then it's width varies based on the following media queries..
    @media (min-width: 1200px) {
        .container {
            width: 1170px;
        }
    }
    @media (min-width: 992px) {
        .container {
            width: 970px;
        }
    }
    @media (min-width: 768px) {
        .container {
            width: 750px;
        }
    }

container vs. container-fluid demo

A: You are right in 3.1 .container-fluid and .container are same and works like container but if you remove them it works like .container-fluid (full width). They had removed .container-fluid for "Mobile First Approach", but now it's back in 3.3.4 (and they will work differently)
To get latest bootstrap please read this post on stackoverflow it will help check it out.


text:
Q: LaTeX: Greek fonts available? I am using LaTeX and the default font that it is providing. I was wondering if there are any other fonts available I can have. My preamble is:
\documentclass[a4paper,12pt]{book}

%\usepackage{showframe}% just for the example
\usepackage{etoolbox}
\usepackage{changepage}% http://ctan.org/pkg/changepage
\usepackage{lipsum}% http://ctan.org/pkg/lipsum
\setcounter{secnumdepth}{-2} %For chapter/section not being visible in text
\let\cleardoublepage\clearpage
\usepackage[utf8x]{inputenc}

\usepackage[english, greek]{babel}
\usepackage{blindtext}
\usepackage[pdftex]{graphicx}

\newcommand{\gr}{\selectlanguage{greek}}
\newcommand{\en}{\selectlanguage{english}}

\usepackage[a4paper, inner=1.5cm, outer=3cm, top=2cm, bottom=3cm, bindingoffset=1cm]{geometry}
\usepackage[onehalfspacing]{setspace}
\pagestyle{fancy}
\fancyhf{}

What can I do to try other fonts too? The default one I'm getting is a little bit weird.

A: You have the GFS font collection (8 fonts), developped by the Greek Font Society (whence the name) that exist in opentype and type 1 formats and can be used by (pdf)LaTeX as well as XeLaTeX and LuaLaTeX. They also have latin letters, except 2 of them:  Porson and Baskerville, but there is LaTeX support for (latin) Baskerville.
At least for a part of them, there is some support for maths (I didn't check for all). For instance, GFS Artemisia relies on tx fonts, except of course for Greek letters. From this page of the LaTeX Catalogue, you will have access to all the details and font samples that you might want.
Using them is simple: if you're using (pdf)LaTeX, just  write \usepackage{artemisia} in your preamble. If you're  using Xe/LuaLaTeX, it's just
\usepackage{fontspec}
\setmainfont{GFS Artemisia}


text:
Q: PHP strange behaviour with line comment The last days I thought I was unable to write PHP code because sometimes my code didn't work. Even simple lines.
So now I found out that when I write a line comment that every new PHP code after that comment does not get executed.
For example:
$a = 2;
echo $a;
// let's add 2 to $a and echo it
$a = $a + 2;
echo $a;

Everything after that line comment won't work. But the next weird thing is that there is also no notice in the logs.
Does anyone know that behaviour or what to do to get PHP working normally again?
My PC has PHP 5.5.9-1ubuntu4.5 (cli) installed.

A: EDIT
I found my problem.
No restart helped me.
No new installation of PHP.
I use PHPStorm and for some unknown reasons the line separator in the Cody Styles had the option "System-Dependent".
And this options causes that all new created files were saved in a single line. I first recognized it when my partner open my files on the server.
Now I changed that line separator option to UNIX and everything is fine.
But I like to know where I can find this System-Dependent configuration on my Ubuntu that causes this behaviour.


text:
Q: Is $A_{S}$ a ring of fractions or a localized ring? Let $$A_{S}:=\Biggl\{\frac{a}{b}\in K\mid a\in A,b=1\vee b=st,\;\forall s,t\in S\Biggr\},$$
where $K=Frac(A)$, $A\subset K$, $A$-integral domain and $0\not\in S\subset A$.
Is $A_{S}$ a ring of fractions or is it a localized ring at $S$ or neither?
I think it is a ring of fractions but would like someone to check if I am correct.
I have learnt that a ring of fractions is a construction of this type
$$S^{-1}A:=\Biggl\{\frac{a}{s}\in K\mid a\in A,s\in S\Biggr\}$$ where we insist on $S$ to be a multiplicative set, i.e., $1\in S$ and $\forall s,t\in S\Rightarrow st\in S$.
Does it mean in the above notation that $b=1\in S$? Because then $S$ is a multiplicative set and $A_{S}=S^{-1}A$ right?
While a localized ring is a structure of a type
$$A_{P}:=\Biggl\{\frac{a}{b}\in K\mid a,b\in A \wedge b\not\in P\Biggr\}.$$
But here we localize a ring at a prime ideal $P$.
In my book I have found a statement that if $P$ is a prime ideal then $S=A\setminus P$ is a multiplicative set. This somehow indicates that localizing at $P$ is a way of creating a ring of fractions. Is it true?
Any ideas gratefully appreciated.

A: There is some confusion in notation. Some texts use $A_S$ where others use $S^{-1}A$ for the same thing, when $S$ is a multiplicative subset of $A$.
I too was a bit confused when my teacher said that when $P$ is a prime ideal, then we would write $A_P$ as an abbreviation of $A_{A\setminus P}$. Since then, I have always used the clearer notation $S^{-1}A$.
Localization at a prime ideal is a special case of making a ring of fractions. In the case $A$ is a domain, everything is simpler. If $S$ is a multiplicative subset of $A$ (that is, $st\in S$ whenever $s\in S$ and $t\in S$), one can define
$$
S^{-1}A=\left\{\frac{a}{b}:a\in A,\; b\in S\cup\{1\}\right\}
$$
and show that this is a subring of the quotient field of $A$, precisely the smallest subring where every element of $S$ is invertible. One has to assume $0\notin S$, of course, otherwise such a subring would not exist. Note also that it's always not restrictive to assume that $1\in S$, because
$$
S_1^{-1}A=S^{-1}A
$$
if $S_1=S\cup\{1\}$; $S_1$ is obviously a multiplicative subset if $S$ is.
When $P$ is a prime ideal, $S=A\setminus P$ is a multiplicative subset not containing $0$, so one defines
$$
A_P=(A\setminus P)^{-1}A
$$
because the emphasis is on $P$ rather than its complement. Just a question of notation.

Note that the operations can be carried over also when $A$ is not a domain. However, fraction must be defined more carefully. We consider the set $A\times S$ and the equivalence relation on it defined by $(a,s)\sim(b,t)$ if there exists $u\in S$ with $u(at-bs)=0$. We assume that $S$ is a multiplicative subset.
One can show that denoting by $\dfrac{a}{s}$ the equivalence class of $(a,s)$ and defining
$$
\frac{a}{s}+\frac{b}{t}=\frac{at+bs}{st},\qquad
\frac{a}{s}\frac{b}{t}=\frac{ab}{st}
$$
one obtains a ring structure on the quotient set, denoted by $S^{-1}A$.

A: That is sort of where the intuition comes from, it's more of a way of creating a field of fractions off of a certain prime ideal. However we can recover the concept of the "field of fractions" because $(0)$ is prime, and thus its compliment closed under multiplication. Thus when we localize at $(0)$ we get the set of all $p/q$, $p \in R$, $q \in R^*$ as desired. Hope this is enlightening! It's a good question to ask.
To answer your first question, I believe that what you're doing is essentially localizing at the compliment of the multiplicative closure of S.


text:
Q: Returning multiple HTML snippets per element of array Edited --
Let's say I have an array of JSON objects:
"social":[
      {
        "name":"facebook",
        "className":"fa fa-facebook"
      },
      {
        "name":"linkedin",
        "className":"fa fa-linkedin"
      },
      {
        "name":"instagram",
        "className":"fa fa-instagram"
      },
      {
        "name":"github",
        "className":"fa fa-github"
      }
]

How do I create an snippet for each of the objects such that they return

{social.name}

And I don't want to use map.
This is generalized for a more complicated example, but this seems to be the problem I am facing (i.e. I have the data in the format below and I need to get the property from each of the elements to display and I only have one function)

A: cleaner code :) , this might solve your issue
import React, { Component } from "react";

class Projects extends Component {
  constructor(props) {
    //initialize this component with props
    super(props);
  }

  render() {
    const { data } = this.props;
    if (data) {
      const projects = data.map(project => {
        return (

        );
      });

      const modals = data.map(project => {
        return (

            <button
              data-remodal-action="close"
              className="remodal-close"
            ></button>

Remodal

              Responsive, lightweight, fast, synchronized with CSS animations,
              fully customizable modal window plugin with declarative
              configuration and hash tracking.

            <button data-remodal-action="cancel" className="remodal-cancel">
              Cancel
            </button>
            <button data-remodal-action="confirm" className="remodal-confirm">
              OK
            </button>

        );
      });
    }

    return (

          {projects}
          {modals}

    );
  }
}

A: Assuming that social is a part of the state, you can implement a method that maps each item in the social array to a p tag:
renderSocialNames = () => {
  return this.state.social.map(
    socialItem =>
{socialItem.name}

  );
}

Here's a Working Sample StackBlitz for your ref.


text:
Q: How do I see response text in debugger? If this is my request, how do I see the response's text in the debugger window, in particular when there's an error?
let request = Alamofire.request(
                    webServiceUrl + url, method: method, parameters: parameters)
                    .validate(statusCode: 200..<300)
                    .validate(contentType: ["application/json"])

request.responseJSON { response in ... }

A: In my response handler, I added...
if let resp = response.data {

   NSLog("Server Response: \(NSString(data: resp, encoding: String.Encoding.utf8.rawValue))")
}


text:
Q: Jackson Deserialize an Object in different way depending of the context In my application, imagine I can create an Animal Object :
public class Animal {
    private int id;
    private String food;
    private String comment;

    // Getter and setters
}

From somwhere in the app we create lot of Animal object and they are stored into the database.
Animal can also be created from JSON, so if I receive
{
  "id":123456,
  "food":"biscuit",
  "comment":"black with white pows"
}

A new Animal will be created in database.
Now imagine we want to put that Animal into Zoo.
public class Zoo {
    List<Animal> animals = new Arraylist<>();

    // Getters and Setters
}

The Zoo can be constructed by Json. But here we don't want to receive the full Json for every Animal, but just their Id because they already exist into the database.
we will receive something like :
{
  "animals": [
    {
      "id":123456
    },
    {
      "id":987654
    }
  ]
}

So we have two case, in the first case Animal are the root element of the Json we receive all the fields and store it into the database.
In the second case Animal can be into a list or just a child of another object and we receive only is Id to load it from the database during the deserialization.
So my question is, how from a custom deserializer, I can verify if the json I try to deserialize is a root Animal or a child animal ?
I'd like to write something like that :
public class ReferenceDeserializer extends JsonDeserializer<Animal> {

    @Override
    public Animal deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        ObjectCodec oc = jp.getCodec();
        JsonNode node = oc.readTree(jp);

        if (I have a root Animal)
        {
            deserialize the full animal
        } else if (I have a List or a Animal which is not a root object)
        {
         load the Animal from database with the id received
       }
      return myAnimal:
    }
}

A: You can use @JsonIgnoreProperties(ignoreUnknown = true) annotation above the class definition. By this, only the id field of the Animal object will  be populated and you don't have to use Custom deserializer.


text:
Q: SAP UI5 [Panel]- How to create a new Panel on button click I have a requirement where I have add the panel on click on a button.
In the controller function I have written the code like below. I don't get the error in console neither do I get the panel when I click the button.
However when I console.log the panel object I can see the panel is created but not sure why not reflected in the view. suggestions please.
onAddObjectiveClick: function () {
        var panel = new Panel({
            headerText: "Description",
            visible: true,
            backgroundDesign: "Solid",
            content: new TextArea({
                value: "Lorem Ipsum is simply dummy text of the printing and typesetting industry",
                growing: true,
                width: "100%",
                height: "263px"
            })
        });

}
this.getView().addDependent(panel); // at this place I have tried setExapanded and setExpandible function too but none helped.

A: You are basically creating an object, assigning to a local variable and not adding it to your view.
You should have any kind of container element with an aggregation to add your Panel.
Depending on the container the aggregation name will be different and thus the method you need to call in order to add the Panel to it.
Example: If you need to add this Panel inside the aggregation content of the sap.m.Page class, you should
1) Have the Page
2) Capture it inside the controller
3) call the addContent()


text:
Q: How to parse XML with HTML tags in the elements using Jackson? I have a XML file and try to parse it using Jackson. My XML file looks similar to this:
<package>
  <name>Paul Muad'dib</name>
  <description>
    This is a description, and for some reason somebody decided to put html tags inside here
 </description>
</package>

My code for this looks something like this (I am using Kotlin, but the Java code would look basically the same):
class XmlThing {
  @JacksonXmlProperty(localName = "name")
  var name: String = ""

  @JacksonXmlProperty(localName = "description")
  var description: String = ""
}

...

val file: File = [my xml file]

val objectMapper = XmlMapper(JacksonXmlModule().apply {
        setDefaultUseWrapper(false)
    }).registerKotlinModule().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

val xmlThing = objectMapper.readValue(file, XmlThing::class.java)

This results in the following error message:
Resolving dependencies for 'some.xml' failed with: MismatchedInputException: Cannot deserialize value of type `java.lang.String` from Object value (token `JsonToken.FIELD_NAME`)

It looks like Jackson tries to interpret the HTML tag as another XML tag (I mean albalb is a valid XML tag) and then sees the content of <description> as another object.
I already tried the @JacksonXmlText annotation, but it just resulted in the content of <description> not being read at all (so it's just an empty String). I would really like to keep using Jackson for this, because the project already uses it and I don't want to add more dependencies.

A: Why not Jsoup..in my opinion it is much easier to extract attribute values in Jsoup.


text:
Q: PRISM + MEF -- Importing a Service I'm trying to figure out how to import a service into my ViewModel properly... here's my relevant code (I've omitted the unimportant stuff):
ClientBootstrapper.cs:
public sealed class ClientBootstrapper : MefBootstrapper
{
    protected override void ConfigureAggregateCatalog()
    {
        base.ConfigureAggregateCatalog();

        //Add the executing assembly to the catalog.
        AggregateCatalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
    }

    protected override DependencyObject CreateShell()
    {
        return Container.GetExportedValue<ClientShell>();
    }

    protected override void InitializeShell()
    {
        base.InitializeShell();

        Application.Current.MainWindow = (Window)Shell;
        Application.Current.MainWindow.Show();
    }
}

ClientShell.xaml.cs:
[Export()]
public partial class ClientShell : Window
{
    [Import()]
    public ClientViewModel ViewModel
    {
        get
        {
            return DataContext as ClientViewModel;
        }
        private set
        {
            DataContext = value;
        }
    }

    public ClientShell()
    {
        InitializeComponent();
    }
}

ClientViewModel.cs:
[Export()]
public class ClientViewModel : NotificationObject, IPartImportsSatisfiedNotification
{
    [Import()]
    private static RandomService Random { get; set; }

    public Int32 RandomNumber
    {
        get { return Random.Next(); } //(2) Then this throws a Null Exception!
    }

    public void OnImportsSatisfied()
    {
        Console.WriteLine("{0}: IMPORTS SATISFIED", this.ToString()); //(1)This shows up
    }
}

RandomService.cs:
[Export()]
public sealed class RandomService
{
    private static Random _random = new Random(DateTime.Now.Millisecond);

    public Int32 Next()
    {
        return _random.Next(0, 1000);
    }
}

I do get the notification that all the import parts have been satisfied (1), but then I get a NullReferenceException (2) on return Random.Next(); inside of the ClientViewModel. Not sure why I would get a NullReferenceException after I'm told that all Imports are satisfied...

A: MEF won't satisfy imports on a static property.  Make the random service an instance property.

A: You can use [ImportingConstructor] and set the static property in the constructor.
private static RandomService Random { get; set; }

[ImportingConstructor]
public ClientViewModel(RandomService random)
{
   Random = random;
}

Just don't set it to a static field.


text:
Q: Harmonize multiple choice number formatting I have a word document (word 2010) approx 1000 pages with 2000+ questions which are of the following format:
1. This is question text multiple lines
(a) Option 1
(b) Option 2
(c) Option 3
(d) Option 4

2. Next question text mutliple lines
A. Option 1
b) Option 2
c] Option 3
D) Option 4

and so on....
As Shown above, the word numbering in front of Options vary from question to question.
I need to all them in the following format:
A. Option 1
B. Option 2
C. Option 3
D. Option 4

These options need to have left indent at 1cm and hanging 1cm.
I googled around and it looks that I need to use
Selection.Range.ListFormat.ListValue
to get the bullet value
So far i have written (incomplete macro):
numOfLines = ActiveDocument.BuiltInDocumentProperties("NUMBER OF LINES")

Selection.HomeKey Unit:=wdStory

For x1 = 1 To numOfLines
        Selection.HomeKey Unit:=wdLine
        Selection.EndKey Unit:=wdLine, Extend:=wdExtend
        bulletValue = Selection.Range.ListFormat.ListValue
        If bulletValue = 0 OR bulletValue = 1 OR bulletValue = 2 OR bulletValue=3 Then
        'THis is where i have no clue what to do next

        EndIf
Next x1

This counter x1 is also a problem because i need to skip 4 lines containing 4 option and then move ahead. How?


text:
Q: scp to Local Machine After SSHing From my local machine I can copy files from a remote machine
scp remote:/some/file/path ~

But what if I'm already SSHed into the remote machine? Can I do something like this
ssh remote
cd /some/file
scp path local:~

where local somehow resolves to the machine I SSHed from. This would of course be possible if the local machine is running an SSH server and the remote is configured to connect to it, but that isn't always an option.
Is something like this possible?

A: As mentioned in the comments, I'd suggest using sftp:
$ sftp remote
user@remote's password:
Connected to remote.
sftp> pwd
Remote working directory: /home/user
sftp> cd /etc
sftp> get fstab
Fetching /etc/fstab to fstab
/etc/fstab                                 100%  435     0.4KB/s   00:00
sftp>

Another, rather… hacky approach would be abusing port-forwarding capabilities of SSH, combined with nc (a.k.a. netcat).  nc is the "swiss army knife of networking" (the smaller one… there's also socat, which is more the MultiTool® ;) — a kind of cat with networking capabilities.
The idea: tell ssh to forward a remote port of your remote machine to a local port on the client side and use this connection to pipe along your data using nc:

*

*Connect to $remote establishing remote port forwarding:
client:~> ssh -R 8888:localhost:8888 $remote

This establishes a normal connection to $remote, but additionally tells ssh to listen on port 8888 on the remote side.  If something connects to port 8888 on the remote side, ssh will open a connection to localhost, port 8888 on the client side (thus, the client) and forward anything sent to remote-side's port 8888 to this port.

*Listen on client side's port 8888 (so ssh has something to connect to), using nc.  We pipe the output (client-side) nc receives into tar, since we'll send a tar stream to it later:
client:~> nc --recv-only -l -p 8888 | tar xvf -

*On the remote side, change your current working directory anywhere you wanted.

*If you're on the right spot, use tar to gather the files you want to copy and pipe them into (remote-side) nc, connecting to the remote-side opened port:
server:~> cd /path/with/those/files
server:files> tar cvf - ./some/files | nc --send-only 127.0.0.1 8888

*Magic™ happens.
Note: There are at least three different implementations of nc out there, all with a slightly different syntax; --send-only and --recv-only are AFAIK only supported by netcat6.  If you've an implementation that does not support those (or similar) options, you'll have to look whether tar exited and hit Ctrl-C on the sender side.  nc usually waits forever and does not handle EOF (--send-only tells it to do and automatically close the connection).
Another note: You could also use nc directly, but by using ssh's port forwarding, your data goes through the SSH connection, avoiding two problems: first, your data is still sent encrypted, and second, this also works if your client is behind a NAT'ing firewall or otherwise not directly reachable from your $remote.


text:
Q: How to colour data points on a 3D scatterplot in matplotlib Edit: I managed to figure out what was going on. Scatter has a parameter 'line-width' (lw=n) that determines the thickness of the line surrounding the plot point for a scatter plot. Because my plot points were size 1 (s=1), the line width was so thick it was actually covering the colour of the plot point. Setting the line-width to a thickness of 0 (lw=0) should do the trick.
I want to generate a 3d scatterplot of data-points, colouring them based on the value of their y-coordinate, but I can't manage to get the points to actually colour.
If the value of the datapoint is low, the colour should be closer to the blue-end of the colour spectrum. If the value is higher the, the colour should be closer to the red-end of the spectrum.
I've managed to plot what I want in 2D, but am having trouble replicating the process in 3D. The current code only plots the points in black.
Here is my code for the 3D attempt, and a screenshot of the desired results in 2D. What exactly am I doing wrong here?
x_points, y_points, and z_points are lists of float values.
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D

def three_dimensional_scatterplot(
    self, x_points, y_points, z_points, data_file
):

    cm1 = cm.get_cmap('gist_rainbow')

    fig = plt1.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(
        x_points,
        y_points,
        z_points,
        s=1,
        c=y_points,
        cmap=cm1
    )

    ax.set_xlabel('X axis')
    plt1.show()

A: You have to plot  like here:
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

x = np.random.rand(25)
y = np.random.rand(25)
z = np.random.rand(25)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
p3d = ax.scatter(x, y, z, s=30, c=y, cmap = cm.coolwarm)
plt.show()


text:
Q: Face detector program in C via arrays So I need to make a "face detector" program in C. Basically I need to input the number of "face detections", resolution height and width (max 120), and the coordinates of the "face". Then the input is three h*w arrays which serve as RGB values.
The output of the program should be the same RGB values from the input, but with a green rectangle connecting the coordinates (thus highlighting the face on the picture), and the alpha values in the rectangle being 255 (the rest being alpha=127).
The issue I have is that the outputs are completely wrong. The first test case, which is a 5x5 black square with false coordinates, works fine. But the other test cases are actual pictures with 100x80 resolution. In those cases instead of a green rectangle, its random green lines and dots around the picture. The alpha value is simmilarly wrong, where its randomly 127 and randomly 255. I've tried rewriting my code several times, but the result is the same every time, just random values for alpha and G.
#include <stdio.h>
#define MAX 120

int main() {
FILE* fin = fopen("input.txt", "r");
FILE* fout = fopen("output.txt", "w");

int R[MAX][MAX], G[MAX][MAX], B[MAX][MAX], x1[MAX], y1[MAX], x2[MAX],
y2[MAX], A[MAX][MAX];
int h, w, n, i, j, k;

fscanf(fin, "%d %d %d", &n, &h, &w);

for (i = 0; i < n; i++) {
    fscanf(fin, "%d %d %d %d", &x1[i], &y1[i], &x2[i], &y2[i]);
}

for (i = 0; i < w; i++) {
    for (j = 0; j < h; j++) {
        fscanf(fin, "%d ", &R[i][j]);
    }
}
for (i = 0; i < w; i++) {
    for (j = 0; j < h; j++) {
        fscanf(fin, "%d ", &G[i][j]);
    }
}
for (i = 0; i < w; i++) {
    for (j = 0; j < h; j++) {
        fscanf(fin, "%d ", &B[i][j]);
    }
}
for (i = 0; i < w; i++) {
    for (j = 0; j < h; j++) {
        A[i][j] = 127;
    }
}
for (k = 0; k < n; k++) {
    for (i = x1[k]; i <= x2[k]; ++i) {
        G[i][y1[k]] = 255;
        G[i][y2[k]] = 255;
        A[i][y1[k]] = 255;
        A[i][y2[k]] = 255;
        R[i][y1[k]] = 0;
        R[i][y2[k]] = 0;
        B[i][y1[k]] = 0;
        B[i][y2[k]] = 0;
    }
    for (j = y1[k]; j <= y2[k]; ++j) {
        G[x1[k]][j] = 255;
        G[x2[k]][j] = 255;
        A[x1[k]][j] = 255;
        A[x2[k]][j] = 255;
        R[x1[k]][j] = 0;
        R[x2[k]][j] = 0;
        B[x1[k]][j] = 0;
        B[x2[k]][j] = 0;
    }
}
for (k = 0; k < n; k++) {
    for (i = x1[k] + 1; i <= x2[k] - 1; i++) {
        for (j = y1[k] + 1; j <= y2[k] - 1; j++) {
            A[i][j] = 255;
        }
    }
}
fprintf(fout, "/image %d %d RGBA\n", h, w);
for (i = 0; i < w; i++) {
    for (j = 0; j < h; j++) {
        fprintf(fout, "%d %d %d %d ", R[i][j], G[i][j], B[i][j], A[i][j]);
    }
}

return 0;
}

A: I don't see anything wrong with the logic you have so I would step through your solution with testcases like yano suggested to see if you are having issues reading things in.
You do make the mistake of not setting the R and B values to 0 when you set the G value to 255 for the rectangle.
Next I would do two things: sanitize your inputs and simplify your loops.
For sanitizing your inputs just make sure that your with, height, and number of faces are less than your max. The coordinates you receive for each face rectangle should all be less than w and h, but greater than 0. Also double check that your face rectangles are always in the format of: [bottom-left x val, bottom-left y val, top-right x val, top-right y val] like you assume when you do all of these calculations. If there were an input problem here, that would be my guess at the most likely to cause hidden issues.
You can simplify your loops to avoid touching anything outside of your rectangles when coloring the Alpha and Green.
For the Green values, just loop over the sides. Loop through all of the faces (n) like you are doing, but just do:
for (i = x1[n]; i <= x2[n]; ++i) { G[i][y1[n]] = 255; G[i][y2[n]] = 255; // Also set A to 255 as well as R and B to 0 here }
for (j = y1[n]; j <= y2[n]; ++j) { G[x1[n]][j] = 255; G[x2[n]][j] = 255; // Also set A to 255 as well as R and B to 0 here }

And then cover the Alpha values inside the rectangle by looping from x1[n] + 1 to x2[n] - 1 and y1[n] + 1 to y2[n] - 1. This will not only make your program quicker, but should stop any erroneous green or alpha values to show up anywhere outside of your given points.
After fixing those things it should be much easier to debug and see where errors are when you get unexpected behavior.
Edit: I missed a case for input sanitation.


text:
Q: JSON Parse iOS Array of Dictionaries parsed into array only displays last object in tableview I have a JSON array of dictionaries that I'm parsing. My problem is where I want to display all the records that fit my required key-value pair (key is name) within the array, I'm only displaying the very last one in my tableview. It's almost 4am and I've been going around in circle since 10pm so any help would be greatly appreciated as I'm overlooking something. Thanks!
NSArray *jsonDataArray = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
self.someArray = [[NSMutableArray alloc]init];

for (NSMutableDictionary *dictionary in jsonDataArray)
{
    NSMutableArray* Response_array = [dictionary objectForKey:@"loans"];
    NSLog(@"Array: %@", Response_array);

    NSDictionary *dict = [Response_array objectAtIndex:0];
    NSLog(@"dict is %@",dict);

    self.someMutableArray = [dict objectForKey:@"name"];

    NSLog(@"what is name %@",self.someMutableArray);
}

and I tried:
NSArray *jsonDataArray = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];

for ( int i = 0 ; i < jsonDataArray.count ; i++ )
{
    self.someDictionary = [[jsonDataArray objectAtIndex:i] objectForKey:@"loans"];
    self.someMutableArray = [self.someDictionary valueForKey:@"name"];
    NSLog(@"MutableArray inside is %@", self.someMutableArray);
}

NSLog(@"MutableArray outside is %@",self.someMutableArray);

On my last attempt I moved the location of valueForKey:@"name":
NSArray *jsonDataArray = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
self.someMutableArray = [NSMutableArray array];

for ( int i = 0 ; i < jsonDataArray.count ; i++ )
{
    self.someMutableArray = [[jsonDataArray objectAtIndex:i] objectForKey:@"loans"];
}

NSLog(@"someMutableArray outside is %@",self.someMutableArray);

Then in cellForRowAtIndexPath of my tableview, I have:
NSDictionary *dict2 = [self.someMutableArray objectAtIndex:indexPath.row];
NSLog(@"what is dict2 %@", dict2);
cell.textLabel.text = [dict2 valueForKey:@"name"];

Here's the setup of my JSON:
[
  -{
     id: 285,
     name: name 1,
    -loans: [
         -{
            id: 42,
            name: "Shark"
          }
     ]
   },
  -{
     id: 286,
     name: name 2,
     -loans: [
          -{
             id: 50,
             name: "Flipper"
           }
      ]
   }
]

A: Why are you going for a looping when already you have the Array? Just allocate your array with JSON response
NSArray *jsonDataArray = [[NSArray alloc] initWithArray:[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error]];

this array will be your datasource so return its count from delegate and in you rowAtIndexPath
NSDictionary *dictObject = [jsonDataArray objectAtIndex:indexPath.row];
cell.textLabel.text = [dictObject valueForKey:@"Shark"];

For custom cell do like
NSDictionary *dictObject = [jsonDataArray objectAtIndex:indexPath.row];
cell.textLabel1.text = [dictObject valueForKey:@"Shark"];
cell.textLabel2.text = [dictObject valueForKey:@"Flipper"];

A: From my example:
My JSON File:
{
status: "Success",
totalcount: "25",
currentcount: "25",
ticketreplies: [
  {
ticket_id: "5348CD97",
subject: "bA==",
posteduser: "10025",
postedby: "Admin (Paul)",
message: "PGRpdj4",
post_id: "75",
posted_on: "23 Apr 2014 12:58 IST",
photo: "10025.jpg"
},
{
ticket_id: "5348F754",
subject: "Y2FsbCBv",
posteduser: "10025",
postedby: "Admin (John)",
message: "PGRpdj4",
post_id: "74",
posted_on: "23 Apr 2014 11:46 IST",
photo: "10025.jpg"
}
    ]
}

My Implementation:
self.dic_response=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"Dictionary: %@",self.dic_response);
NSLog(@"Dictionary: %i",[self.dic_response count]);

NSString usrTicketId=[self.dic_response valueForKey:@"totalcount"];
NSLog(@"Ticket_Id: %@",usrTicketId);

NSArray arrTicketRplys=[self.dic_response valueForKey:@"ticketreplies"];
NSLog(@"Ticket_Id: %@",arrTicketRplys);

for(NSArray *tmpArr1 in arrTicketRplys){
    if([[tmpArr1 valueForKey:@"posteduser"] isEqualToString:@"10025"]){
        NSString *strPostUserName=[tmpArr1 valueForKey:@"postedby"];
        NSLog(@"Posted BY: %@", strPostUserName);
    }
}

// Sure, it'll logic work for read specific object keys and values.
// Mainly, these code avoid static values like objectAtIndex:4.

A: self.dic_response=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
if([self.dic_response valueForKey:@"success"]){
NSMutableArray *resultArray = [NSMutableArray alloc];
for(NSDictionary *tmpArr1 in self.dic_response){
{
    [resultArray addObject:tmpArr1];
    //this resultArray have whole array value.
}

}

Hope this is helps you

A: for ( int i = 0 ; i <jsonDataArray.count ; i++ )
{
    self.someDictionary = [[jsonDataArray objectAtIndex:i] objectForKey:@"loans"];
    [self.someMutableArray  addObject:[self.someDictionary valueForKey:@"name"]]
    NSLog(@"MutableArray inside is %@", self.someMutableArray);
}
NSLog(@"MutableArray outside is %@",self.someMutableArray);

----------


text:
Q: How can I pass large strings from one controller to another? I'm attempting to send an HTML table from one controller to another, but because of the size of the table I'm getting HTTP 400 errors. I think the errors are coming from a lower level than the framework, as it's just a raw HTTP 400 error instead of an error with a stack, query, etc. like a normal exception does when debugging.
If I limit the size of the DataTable to a single row, it works just fine. But once I get past two or three rows the length of the query string gets long enough it starts throwing errors.
I tried passing the DataTable itself to MailboxRulesResults and then doing the conversion from DataTable to HTML table there using a List<object>, but the DataTable never made it to the function.
Is there a better way to do this or do I need to tweak a config somewhere?
Thanks in advance
        [HttpPost, ValidateAntiForgeryToken]
        public IActionResult GetMailboxRules(MailboxRulesModel mailbox)
        {
            string currentuser = HttpContext.User.FindFirst("preferred_username")?.Value;
            string guid = Guid.NewGuid().ToString();
            using (DataTable results = Mail.GetMailboxRules(mailbox.EmailAddress, guid, currentuser))
            {
                List<string> return_list = new List<string>
                {
                    UtilityFunctions.ConvertDataTableToHTML(results, guid),
                    guid
                };
                return RedirectToAction("MailboxRulesResults", "Mail", new { data = return_list });
            }
        }
        [HttpPost, ValidateAntiForgeryToken]
        public IActionResult MailboxRulesResults(List<string> data)
        {
            ViewBag.TableHTML = data[0];
            ViewBag.Guid = data[1];
            return View();
        }

A: Ended up changing my original view from
<form asp-controller="Mail" asp-action="GetMailboxRules" method="post"

to
<form asp-controller="Mail" asp-action="MailboxRulesResults" method="post"

and then having the MailboxRulesResults action handle everything.
 [HttpPost, ValidateAntiForgeryToken]
        public IActionResult MailboxRulesResults(MailboxRulesModel mailbox)
        {
            string currentuser = HttpContext.User.FindFirst("preferred_username")?.Value;
            string guid = Guid.NewGuid().ToString();
            List<MailboxRulesModel> rules = Mail.GetMailboxRules(mailbox.EmailAddress, guid, currentuser);
            using (DataTable dt = UtilityFunctions.CreateDataTable(rules))
            {
                string html = UtilityFunctions.ConvertDataTableToHTML(dt, guid);
                ViewBag.TableHTML = html;
                ViewBag.Guid = guid;
                return View();
            }
        }

A: Just do the following and save table as text file on server than get it on next request.
   private IHostingEnvironment _env;
       var webRoot = _env.WebRootPath;
           var file = System.IO.Path.Combine(webRoot, "table.txt");
 [HttpPost, ValidateAntiForgeryToken]
    public IActionResult GetMailboxRules(MailboxRulesModel mailbox)
    {

        string currentuser = HttpContext.User.FindFirst("preferred_username")?.Value;
        string guid = Guid.NewGuid().ToString();
        using (DataTable results = Mail.GetMailboxRules(mailbox.EmailAddress, guid, currentuser))
        {
            List<string> return_list = new List<string>
            {
                UtilityFunctions.ConvertDataTableToHTML(results, guid),
                guid
            };

          using(TextWriter tw = new StreamWriter(file))
          {
          foreach (string s in return_list)
           tw.WriteLine(s);
          }
            return {Your action method without parameter}
        }
    }

Then retrieve:
[HttpPost, ValidateAntiForgeryToken]
    public IActionResult MailboxRulesResults(List<string> data)
    {

       using (StreamReader sr = new StreamReader(file))
        {

            String line;
            // Read line by line
            while ((line = sr.ReadLine()) != null)
            {
                Console.WriteLine(line);

            }
        }
        ViewBag.TableHTML = line;
        ViewBag.Guid = data[1];
        return View();
    }


text:
Q: Open a spreadsheet in the middle of macro Currently, I have a sub which downloads an Excel file from the Internet. I would like to open the spreadsheet and run more commands on it prior to the sub ending.
The issue is that the spreadsheet does not open until the macro has finished executing thus it cannot find the workbook.
With appIE
    .Navigate "https://www.alerian.com/wp-content/uploads/AMZmembers.xls"
    .Visible = False

   Application.Wait Now + TimeValue("00:00:03")
   SendKeys "{Enter}"
End With

Application.Workbooks("AMZmembers.xls").Close

SendKeys "{Enter}" opens the sheet but it will not open until the sub has finished; therefore, Workbooks.close cannot find the sheet because it isn't open yet.
Appreciate help!

A: Use Workbooks.Open "path_and_filename" instead of the SendKeys. There are a bunch of other parameters in the Open method such as whether you want it opened read-only, etc but the simplest way is as shown.


text:
Q: Folder rights doesn't work on group, but does on user I've got this share where I want to restrict access to two folders so that only members of a group can get access to them. I've done this countless of times, but this time there's something odd going on.
The root folder has these permissions set:
SYSTEM - Full access
Administrator - Full Access
Administrators (FILE01\Administrators) - Full Access
All in sales dpt (SALENET\All in sales dpt) - Full Access

This is so that everyone can get access to the root folder
Every subfolder has activated inheritable permissions from object's parent. But not the two folders I want to restrict permissions for!
So, these two folders have turned off inheritable permissions from object's parent. And also have these permissions set:
    SYSTEM - Full access
    Administrator - Full Access
    Administrators (FILE01\Administrators) - Full Access
    testgroup (SALENET\testgroup) - Full Access

Now, my test user is a member of the testgroup. But still, this folder doesn't show up. But if I manually add the test user directly to the permissions, it works right away. So why doesn't it work when adding the group? I tried to log off and on again, but that didn't do anything. Do I have to restart the file server in order to make this work?
Might be worth mentioning that these folders, test user and both groups are newly created. And no restart has been made on either domain controllers nor file servers. But I did restart my own client, as I mentioned. What's causing this? And why does it happen?

A: You need to wait a bit for all the domain controllers to see the new groups.
What's likely happening is that you create the group on DC 1, and your file server is authenticating users against DC 2.  If you turn on auditing login events on the file server you might be able to see why the login failed.
You can check in AD Sites and Services to see how often the domain controllers sync between each other.  The minimum is 15 minutes, but it can be set longer than that.


text:
Q: Creating pkg file with a option to user launch application after install I am using Packages application to create the .pkg file for my Mac Os x application.
My requirement is to have a UI where user can check or uncheck wether he wants to launch application after installation is completed.
Currently I am using postflight.sh to launch the application after install
Please help

A: I have found the solution for this ... we need to create installer plugin and add that to over pkg installer


text:
Q: Light control using android through wifi on Hardware Board I am building a simple android application which can control switching light on and off on a hardware with a wifi connectivity. The board can not create a access point it can only connect to a access point, so I have to use a wifi router to create a access point. Now i am stuck with the problem of how to connect my android device to that board through the access point (wifi router).

A: Can you give the board a fixed IP address? (192.168.110 for example. Remember that the Default gateway is the AP router's IP address). If yes; then you connect to that IP once the Android get connected to the AP Router. If the board has no way of configure a fixed IP address,  then, most of the routers have a Statistics page where you can see what is connected and what IP has been given.  Connect to the router admin page and go to Statistics page, look for the IP that the router gave to the board.  Use that IP to connect to the board. BTW: Do you know the port number to connect to?
EDIT: AN EXAMPLE
I send you a small method which you can use to connect to that board. Bear in mind that in Android all (most of them) networking stuff should be done in a separate Thread o AsyncTask otherwise you'll get an exception.
/**
 * Connect to the server_IP at the server_Port.
 *
 * @param server_IP
 *           host name or IP of the host to conenct to.
 * @param server_Port
 *           port number to connect to that host.
 * @return
 *  if connection succeded a connected socket; null otherwise.
 */
public static Socket doConnect(String server_IP, int server_Port)
{
    Socket retSocket;
    try
    {
        retSocket = new Socket();
        InetAddress addr = InetAddress.getByName(server_IP);
        SocketAddress sockaddr = new InetSocketAddress(addr, server_Port);
        // 10 seconds to connect or otherwise timeout.
        retSocket.connect(sockaddr, 10000);
        return retSocket;
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    return null;
}


text:
Q: Microservices - Spring AMQP/RabbitMQ, async calls between microservices best pattern I have three microservices - Service A, B and C.
Service A should call B and C asynchronously, A should build the response based B and C responses.
I am using Rabbit MQ for async ipc.
Tried RabbitTemplate's convertSendAndRecieve with direct-replyTo option to consume, which  makes the current processing thread wait/block on the  async call to complete which makes it synchronous.
I wouldn't like to use the convertAndSend and let Service A listen on the reply queue and process based on correlation id as there would be thousands of responses in the reply queue and mapping the messages based on correlation id results in poor performance.
Creating separate queues for each session is not an option either due to its own caveats (getting acknowledgement from all clusters on new queue creation impacts the performance too)
Sorry if this problem has been solved before, I couldnt get much help on this on internet. Any help would be appreciated.

A: There is AsyncRabbitTemplate for your purpose do not block the caller until the reply: https://docs.spring.io/spring-amqp/docs/2.0.0.RELEASE/reference/html/_reference.html#async-template:

Version 1.6 introduced the AsyncRabbitTemplate. This has similar sendAndReceive (and convertSendAndReceive) methods to those on the AmqpTemplate but instead of blocking, they return a ListenableFuture.

 RabbitConverterFuture<String> future = this.template.convertSendAndReceive("foo");
future.addCallback(new ListenableFutureCallback<String>() {

    @Override
    public void onSuccess(String result) {
        ...
    }

    @Override
    public void onFailure(Throwable ex) {
        ...
    }

});


text:
Q: Get method class inside decorator I have this code:
class Application(object):
    def cache(self, obj_to_cache):
        def decorator(f):
            print 'apply decorator'
            return f
        return decorator

app = Application()

class A(object):
    cache = []

    def add_cache(self, obj):
        self.cache.append(obj)

    def print_cache(self):
        print 'cache: ', self.cache

class B(A):
    @app.cache('Hello')
    def get(self):
        print 'get B'

    @app.cache('World')
    def another(self):
        print 'another B'

b = B()
b.print_cache()

Gets the result:
apply decorator
apply decorator
cache:  []

My question is: How could I access from Method def decorator(f): to object A and call add_cache?
The result I want is:
apply decorator
apply decorator
cache:  ['Hello', 'Word']


text:
Q: Rails 3: Measure database performance (MongoDB and MySQL) I set up my Rails application twice. One is working with MongoDB (Mongoid as mapper) and the other with MySQL and ActiveRecord. Then I wrote a rake task which inserts some test-data to both databases (100.000 entries).
I measured how long it takes for each database with the ruby Benchmark module. I did some testing with 100 and 10.000 entries where mongodb was always faster than mysql (about 1/3). The weird thing is that it takes about 3 times longer in mongodb to insert the 100.000 entries than with mysql. I have no idea why mongodb has this behaviour?! The only thing that I know is that the cpu time is much lower than the total time. Is it possible that mongodb starts some sort of garbage collection while it's inserting the data? At the beginning it's fast, but as more data mongodb is inserting, it gets slower and slower...any idea on this?
To get somehow a read performance of the two databases, I thought about measuring the time when the database gets an search query and respond the result. As I need some precise measurements, I don't want to include the time where Rails is processing my query from the controller to the database.
How do I do the measurement directly at the database and not in the Rails controller? Is there any gem / tool which would help me?
Thanks in advance!
EDIT: Updated my question according to my current situation

A: If your base goal is to measure database performance time at the DB level, I would recommend you get familiar with the benchRun method in MongoDB.
To do the type of thing you want to do, you can get started with the example on the linked page, here is a variant with explanations:
// skipped dropping the table and reinitializing as I'm assuming you have your test dataset
// your database is called test and collection is foo in this code
ops = [
// this sets up an array of operations benchRun will run
   {
      // possible operations include find (added in 2.1), findOne, update, insert, delete, etc.
      op : "find" ,
      // your db.collection
      ns : "test.foo" ,
      // different operations have different query options - this matches based on _id
      // using a random value between 0 and 100 each time
      query : { _id : { "#RAND_INT" : [ 0 , 100 ] } }
   }
]

for ( x = 1; x<=128; x*=2){
    // actual call to benchRun, each time using different number of threads
    res = benchRun( { parallel : x ,   // number of threads to run in parallel
                      seconds : 5 ,    // duration of run; can be fractional seconds
                      ops : ops        // array of operations to run (see above)
                    } )
    // res is a json object returned, easiest way to see everything in it:
    printjson( res )
    print( "threads: " + x + "\t queries/sec: " + res.query )
}

If you put this in a file called testing.js you can run it from mongo shell like this:
> load("testing.js")
{
    "note" : "values per second",
    "errCount" : NumberLong(0),
    "trapped" : "error: not implemented",
    "queryLatencyAverageMs" : 69.3567923734754,
    "insert" : 0,
    "query" : 12839.4,
    "update" : 0,
    "delete" : 0,
    "getmore" : 0,
    "command" : 128.4
}
threads: 1   queries/sec: 12839.4

and so on.

A: I found the reason why MongoDB is getting slower while inserting many documents.

Many to many relations are not recommended for over 10,000 documents when using MRI due to the garbage collector taking over 90% of the run time when calling #build or #create. This is due to the large array appending occuring in these operations.
  http://mongoid.org/performance.html

Now I would like to know how to measure the query performance of each database. My main concerns are the the measurement of the query time and the flow capacity / throughput. This measurement should be made directly at the database, so that nothing can adulterate the result.


text:
Q: WCF MetaData when to enable Hi I am currently trying to get my head around WCF services and have come to a bit of a roadblock in regards to metadata.
I have been doing some research and from what I am reading I have come to the understanding that metadata should only be enabled if necessary, as it increases the attack surface for the service. At the same time though it seems as if it is instrumental in their operation.
Now my question is what is metadata's role in WCF services, and how do I know when it is appropriate to enable metadata?
I have been on MSDNA but there explanation is a bit cryptic, can anyone explain it differently?
Thanks guys.

A: A rule of thumb, the only time you need meta data exposed is during development and testing stages.
The meta data as described on the MDSN page.

The Windows Communication Foundation (WCF) provides an infrastructure
  for exporting, publishing, retrieving, and importing service metadata.
  WCF services use metadata to describe how to interact with the
  service's endpoints so that tools, such as Svcutil.exe, can
  automatically generate client code for accessing the service.

This simply means, the metadata provides mechanisms for tools to auto-generate the classes and methods required to interact with the service.
In the case of Visual Studio the meta data is only used when you either Add the Service Reference or Update Service Reference. Visual Studio will request the meta data from the WCF service and build \ update the artifacts required to interact with the service.
During normal execution the Meta Data is not requested as the artifacts are already built and understand how to interact with the service.
However if you change the service schema at all the meta data must be turned back on so you can update the service reference.
There are other places that the Meta Data are requested. As stated in the description Svcutil.exe" and programs such as the WCF tester application.
Hope this helps.


text:
Q: capturing the text value of a textarea with jQuery I have a bunch of <textarea> elements on my page all with the same "name" attribute.  I'm trying to capture the text of the textarea that is currently in focus:
$('body').on('click', '[name=btnAddQuestion]', function () {

    questionText = $("[name=stem]").val();
    console.log('questionText: ' + questionText);

});

But I can only get it to capture the text of the first <textarea> in the list.  Is there a way of doing this without having to give each textbox a unique ID?
Thanks!
Here is a jsfiddle:
http://jsfiddle.net/9b2XA/2/

A: Try using the :focus selector.
$("[name=stem]:focus").val();

You can actually simply do the following:
$(document.activeElement).val();

EDIT: Actually that doesn't work since once you click the button, the textarea loses focus. I've written my answer too quickly.
However, what you could do is track which is the last textarea that had focus and use it in your click handler.
var lastFocusedTextArea = null;

$('textarea[name=stem]').focus(function (e) {
    lastFocusedTextArea = e.currentTarget;
});

A: Once you hit the button your textarea will lose focus, so the :focus selector will do you no good.
You can set the focus back to the last textarea once the button is clicked, and then use the :focus selector to pull the text.
http://jsfiddle.net/9b2XA/3/
In this fiddle I capture the last focused textarea and then focus it back when the button is clicked.
var lastFocus;
$("textarea").blur(function() {
    lastFocus = this;
});

$('body').on('click', '[name=btnAddQuestion]', function () {

    if(lastFocus) { lastFocus.focus(); }
    questionText = $("[name=stem]:focus").val();
        console.log('questionText: ' + questionText);

});

A: Use this code:
$('body').on('click', '[name=btnAddQuestion]', function () {
  questionText = $("[name=stem]:focus").val();
  console.log('questionText: ' + questionText);
});

UPDATE:
As others mentioned here, when clicking the button, your text-area is loses its focus because the button have it now and in that case you have to maintain the last focused element and use it in your click handler function:
var lastFocusedTextArea = null;

$('textarea[name=stem]').focus(function (e) {
    lastFocusedTextArea = e.currentTarget;
});

$('body').on('click', '[name=btnAddQuestion]', function () {
  if(lastFocusedTextArea.is('textarea')){
  questionText = lastFocusedTextArea.val();
  console.log('questionText: ' + questionText);
   }
});

A: If you want to get the text of each one of the text areas you will need to iterate over them:
$("[name=stem]").each(function() {
     questionText = $(this).val();
     console.log('questionText: ' + questionText);
});

If you wan to get a reference to the text are that had focus when the user clicks the button you will have to attach a blur event handler to all the text areas and record the text area that was "last in focus" (since the focus will change when the user clicks on the button)

A: You could store the last focused textareas text in a variable and then do what ever you need to do with it when you click the button:
$(document).ready(function () {
    var txt = '';
    $('textarea[name="stem"]').blur(function () {
        txt = $(this).text();
    });
    $('input[name="btnAddQuestion"]').click(function () {
        alert(txt);
    });
});


text:
Q: ConTeXt: Modify .sty LaTeX file for natural deduction Fitch diagrams I've written an introductory logic book in LaTeX and I want to have it in ConTeXt. I've made use of a .sty file (fitch.sty, authored by Peter Selinger, not distributed by TeXLive), downloadable here1. (I don't put the code here cause it has over 200 lines), and I'd like to make it work under ConTeXt, cause the use of graphic packages for making derivations is daunting. In a file called fitch.hacker.tex, Selinger says:

"The macros provided by this package mix TeX and LaTeX primitives.
  LaTeX is used for \rule, \settowidth, \addtolength, \hspace...  All
  macros are assumed to be called in math mode."

If you try to compile fitch.sty with mkiv, you have only two error messages:
1) At lines
\newenvironment{nd}{\begingroup\nd*init\nd*beginc}{\nd*endc\endgroup}
\newenvironment{ndresume}{\begingroup\nd*init\nd*resumec}{\nd*endc\endgroup}

near the end of the file, and
2) At line 85:
\newlength{\nd*dim}

I think error 1) is easily subsanable, I mean, to make it work under ConTexT is enough to define the pertinent commands. But I cannot figure out how to "translate" line 85 to ConTexT, cause \newlength is a macro that defines a length register. So:
¿Can anyone tell me if I'm right about error 1?
¿Can anyone tell me if exists a command or a script in ConTexT with the effect of \newlenght?

A: \newlength{\nd*dim}

is
\newskip\nd*dim

note that * is a letter here (as normally @ in latex is a letter in package code) due to the
\catcode`\*=11

near the top of the file
so this is just defining a single skip register token, with name nd*dim


text:
Q: Apollo Client - Possible to refetch only a fragment of a larger query when it's variables change? I wanted to explore the pattern of fetching all the needed data for a page in one request.  So let's say I have a user config page, which needs a list of teams to assign a user to, and a list of roles a user can have.  I'm using the following query to get the first page of users as well as all available roles and teams.
import { gql } from "@apollo/client";

const listUser = gql`
  fragment listUser on Query {
    users(page: $page, per: $per) {
      edges {
        node {
          id
          name
          title
          avatar
        }
      }
      pageInfo {
        count
      }
    }
  }
`;

const roleFragment = gql`
  fragment roleFragment on Query {
    roles {
      name
      id
    }
  }
`;

const teamsFragment = gql`
  fragment teamsFragment on Query {
    teams {
      nodes {
        id
        name
        manager {
          name
        }
      }
    }
  }
`;

export const getUserConfig = gql`
  query getUserConfig($page: Int, $per: Int) {
    ...listUser
    ...roleFragment
    ...teamsFragment
  }
  ${listUser}
  ${roleFragment}
  ${teamsFragment}
`;

And I'm using it like this (generated using graphql-codegen):
const { loading, error, data, refetch } = useGetUserConfigQuery({
 variables: {
   page: 1,
   per: 7,
  }
});

This works really well and allows me to grab the data I need for the page in one round trip.  However, whenever I change the page variable for users (to go to the next page obviously), it's going to refetch everything.  Is there a way of doing this so that it only refetches the fragment that's variables changed?  Or is there a better pattern for what I'm trying to accomplish? Thanks!

A: Instead of using the useQuery hook, you can query the initial data directly using ApolloClient.query method directly, and then in subcomponents of your page subscribe to updates on subsets of your data ApolloClient.watchQuery
You can view example code for a range of different ApolloClient methods here.


text:
Q: Draw CGGradient On Enclosed Path How does one draw a CGGradient on an enclosed path within a view? I have attempted to draw the gradient, however, it is drawn on the view itself, rather than only within a CGPath that I am filling inside the view. I would like to draw a gradient on the filled path only, and not on the view itself.

A: *

*Save the context's state.

*Set the path as a clip region in your context.

*Draw the gradient.

*Restore the context's state.

Example:
CGContextSaveGState(context);
CGContextAddPath(context, myPath);
CGContextClip(context);
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, kNilOptions);
CGContextRestoreGState(context);


text:
Q: iptables rules for "virtual wire" firewall My systems reside on a network with all public IP addresses. I need to firewall my particular subnet without the use of MASQUERADE. I have seen this configuration referred to as a "virtual wire" firewall.
My current configuration: internal subnet | router| rest of institution | internet
Configuration needed: internal subnet | firewall | router | rest of institution | internet
Firewall has two physical interfaces. I have not been able to construct a set of iptables rules that don't require MASQUERADING. Ip addresses I know and can use: xxx.123.68.0/24
router: xxx.123.68.1
firewall eth0 (outside): xxx.123.68.2
firewall eth1 (inside): xxx.123.68.3
rest of addresses are for internal systems
I have constructed INPUT and OUTPUT rules to allow connection to the firewall for management functions, but have not been successful with the FORWARDing chain rules.
Default policy on FORWARD is ACCEPT
Logging turned on to see if any traffic is flowing, but no entries in the log file. I thought that these rules should allow outbound traffic and return traffic
iptables -A FORWARD -p tcp -i eth1 -o eth0 -j ACCEPT
iptables -A FORWARD -p tcp -i eth0 -o eth1 -m state --state ESTABLISHED,RELATED -j ACCEPT
What am I missing?

A: A 'virtual wire' firewall as you are calling it usually acts as a ethernet bridge.  Under Linux, you nneed to use ebtables, at least at some level when filtering on a bridge.  There are rules you can add to your bridge filter so that your rules get evaluated by iptables.
Or if you want to use a newer kernel and nftables instead nftables combines all the filtering into a single command, though it may be a bit of a learning curve if you are already familiar with iptables.
Another option that doesn't require a bridge setup, is to instead configure the box for proxy-arp.  Using proxy-arp, you can make a box that is a router, act somewhat like a bridge from the perspective of the rest of the network.  With proxy-arp your iptables will work.


text:
Q: Duplicate edge type error in schema design I'm using NebulaGraph Explorer and encounter an issue as the screenshot shows below:
Explorer Screenshot
As shown in the figure, both table and column can be read_by by user, how to set schema in this case so that no duplicate edge type error is reported?

A: Looks like you are using the schema drafting feature of NebulaGraph Explorer. In the draft you uploaded, there are two types of edges with the same type name read_by, originating from two tags table and column, both targeting at the tag user. This is not allowed.
To avoid the duplicate edge type error, name the edges originating from the tag table tab_read_by or table_read_by, and the edges originating from the tag column col_read_by.


text:
Q: Array iteration I have a question regarding the iteration of a 2d array. Why does this work with System.out.println(n) and not System.out.println(row[n])? I am trying to print all the numbers.
public class test
{
    public static void main(String[] args){
        int numbers[][] = {{1,2,3}, {4,5,6}};
        for (int [] row : numbers){

            for (int n: row){

                System.out.println(n);

            }
        }
    }
}

A: because you are eventually accessing numbers outside of the array. In this example, the first iteration it is {1,2,3}, and the second iteration it is {4,5,6}. The first 2 iterations over the first iteration (let's call it x), will work, because x[1] and x[2] are still in the array. After that, you are trying to print x[3], which is not in the array.
Same thing for the iterations over the second iteration (let's call it y).
You are trying to print y[4], y[5], y[6], but y only has 3 values.

A: The first value of n is 1 and row[1] exists, it is the second item in rows (note that indexing starts from 0) but then n will be 2 and your array does not have a second element, just a 0th and a first, so you will get an ArrayIndexOutOfBoundsException.


text:
Q: Create history log per working directory in bash I was wondering if it is possible to keep a file containing history per current working directory. So for example if I was working in /user/temp/1/ and typed a few commands, these commands would be saved in /user/temp/1/.his or something.  I am using bash.

A: IMPORTANT: As pointed out by Gilles 'SO- stop being evil'. The approach below can expose your shell to attacks and leak information unintendedly. Proceed with care.

Building off the answer provided by Groggle, you can create an alternative cd (ch) in your ~/.bash_profile like.
function ch () {
    cd "$@"
    export HISTFILE="$(pwd)/.bash_history"
}

automatically exporting the new HISTFILE value each time ch is called.
The default behavior in bash only updates your history when you end a terminal session, so this alone will simply save the history to a .bash_history file in whichever folder you happen to end your session from.  A solution is mentioned in this post and detailed on this page, allowing you to update your HISTFILE in realtime.
A complete solution consists of adding two more lines to your ~/.bash_profile,
shopt -s histappend
PROMPT_COMMAND="history -a;$PROMPT_COMMAND"

changing the history mode to append with the first line and then configuring the history command to run at each prompt.

A: You can set up code to be executed when changing directories. In zsh, this is as simple as defining a function and adding it to the chpwd_functions array. In bash this takes a little more work but you can do it as well; see Execute bash scripts on entering a directory for how to define a chpwd function that is executed on each directory change.
For what you want to do, the chpwd function needs to write the current history to the old file. To save the history to the right place when exiting bash, set the HISTFILE variable to the history file for the new directory, and read the new history.
chpwd () {
  history -a
  mkdir -p "$HOME/.bash_history.d/${PWD%/*}"
  HISTFILE=~/.bash_history.d/$PWD
  history -r
}

Note that I write the history to a hierarchy under your home directory, not to the current directory. Writing shell history to the current directory would be extremely dangerous and disruptive: you'd end up with privacy leaks all over the place, you'd risk modifying unintended files (what if the history file name is an existing symlink to some other place?), etc.
It would probably be better to write out the history after each command. In bash, you can enable this with the histappend option. With this option, you don't need to run history -a explicitly.
shopt -s histappend
chpwd () {
  mkdir -p "$HOME/.bash_history.d/${PWD%/*}"
  HISTFILE=~/.bash_history.d/$PWD
  history -r
}

A: Depending on how frequently you change directories my solution might not work. You can export the HISTFILE which sets where bash history is stored, so the idea is that you can make separate profiles in the directories that you're working in and then automatically load them using something like direnv.
HISTFILE="$(pwd).bash_history"

Direnv
https://github.com/direnv/direnv


text:
Q: Setting provisioned concurrency for lambda conditionally using serverless The lambda function is created using serverless(2.22) and is deployed using codebuild (standard5.0). I want to conditionally set the provisioned concurrency only for UAT and Prod env and not for dev and test env.
These are the things I tried:
serverless.yml:
    ...
    alarms:
      - functionErrors
    Conditions:
      isProdOrUAT: {"Fn::Or": [{"${opt:stage}": "prod"}, {"${opt:stage}": "uat"}]}
functions:
  TestApi:
    handler: test.api.StreamLambdaHandler::handleRequest
    description: Lambda function for the Test API
    timeout: 20
    custom: !If [isProdOrUAT, "${file(./provisionedconcurrency.yml)}", !Ref "AWS::NoValue"]

provisionedconcurrency.yml
provisionedConcurrency: "${ssm:/${opt:stage}/TestsServiceProvisionedConcurrency}"

In this case what happens is, it imports the file successfully, build also passes. But there is no provisioned concurrency attached in the lambda configuration for UAT and Prod.
serverless.yml
 ...
    alarms:
      - functionErrors
    Conditions:
      isProdOrUAT: {"Fn::Or": [{"${opt:stage}": "prod"}, {"${opt:stage}": "uat"}]}
functions:
  TestApi:
    handler: test.api.StreamLambdaHandler::handleRequest
    description: Lambda function for the Test API
    timeout: 20
    provisionedConcurrency: !If [isProdOrUAT, "${ssm:/${opt:stage}/TestsServiceProvisionedConcurrency}", !Ref "AWS::NoValue"]

In this case getting the following error
Error --------------------------------------------------
  Error: The CloudFormation template is invalid: [/Resources/TestApiProvConcLambdaAlias/Type/ProvisionedConcurrencyConfig/ProvisionedConcurrentExecutions] 'null' values are not allowed in templates

Checked the serverless-state.json, found this to be there.
    "Name": "provisioned",
      "ProvisionedConcurrencyConfig": {
        "ProvisionedConcurrentExecutions": null
      }

A: Sls added support for stripping null properties about a year ago so now it's pretty strait-forward:
custom:
  stages:
    dev:
    # no need to set value for provisionedConcurrency
    uat:
      provisionedConcurrency: 5
    prod:
      provisionedConcurrency: 5

functions:
    TestApi:
        handler: test.api.StreamLambdaHandler::handleRequest
        description: Lambda function for the Test API
        timeout: 20
        provisionedConcurrency: ${self:custom.stages.${self:provider.stage}.provisionedConcurrency, null}

A: Just try to keep it simple, without additional yml configs and complicated if-statement and take benefit of Conditional variable:
custom:
    provisionedConcurrency:
        prod: 5
        uat: 5
        default: 0

functions:
    TestApi:
        handler: test.api.StreamLambdaHandler::handleRequest
        description: Lambda function for the Test API
        timeout: 20
        provisionedConcurrency: ${self:custom.provisionedConcurrency.${self:provider.stage}, self:custom.provisionedConcurrency.default}

A: I had the same question. Nowadays you can do this (YAML example)
Parameters:
 ProvisionedConcurrentExecutions:
    Description: The amount of provisioned concurrency to allocate for the function, use 0 to ignore setting
    Type: Number
    MinValue: 0
    MaxValue: 10
    Default: 0

Conditions:
  UseProvisionedConcurrentExecutions: !Not [!Equals [!Ref ProvisionedConcurrentExecutions, 0]]

Resources:
  LambdaFunction:
    Type: AWS::Serverless::Function
    Properties:
          ProvisionedConcurrencyConfig: !If
           - UseProvisionedConcurrentExecutions
           - ProvisionedConcurrentExecutions: !Ref ProvisionedConcurrentExecutions
           - !Ref 'AWS::NoValue'here


text:
Q: Question about Linear Transformation notation : L(U,W) vs. L(W,U) Hey Exchange community,
We have finite-dimensional vector spaces $V$ and $W$ with ordered bases $B$ and $A$ respectively.
Is it true/false that $L(V,W)=L(W,V)$?
Just wondering if someone could articulate what the difference is between the two notations. Having someone write it down as if they were verbally explaining it to someone would really help.
Thanks!

A: The symbols $\mathcal{L}(V,W)$ indicates the linear transformations from vector space $V$ into vector space $W$, and the analogous statement is made for $\mathcal{L}(W,V)$.  If $V$ and $W$ are not the same space (e.g. isomorphic) then you don't in general have the same maps going from $V$ to $W$ as you do from $W$ to $V$.  For instance, if $V$ were $2$-dimensional and $W$ were $3$-dimensional then the linear maps in $\mathcal{L}(V,W)$ could be represented by $3\times 2$ matrices, but the maps in $\mathcal{L}(W,V)$ would be $2\times 3$ matrices.

A: $\mathcal{L}(U,W)=\{T\colon U\to W/ T \mbox{ is a linear transformation }\}$
$\mathcal{L}(W,U)=\{T\colon W\to U/ T \mbox{ is a linear transformation }\}$
There are different because $Im(\mathcal{L}(U,V))\subset U$ and $Im((\mathcal{L}(V,U))\subset V$ and $ U, V$ nor always will be subsets of the same space.
For example $\mathcal{L}(U,\mathbb{K})$ obviusly not equal to $\mathcal{L}(\mathbb{K},U)$


text:
Q: How to place different sized widgets side by side? I have the following widgets which define to scrollbars with text:
from tkinter import ttk
from tkinter import *

# -------------
# set_up_output_scrollbar
def set_up_output_scrollbar():
    output_scrollbar = Scrollbar(root)
    output_scrollbar_text = Text(root, height=scrollbar_height, width=scrollbar_width)
    output_scrollbar.config(command=output_scrollbar_text.yview)
    return output_scrollbar, output_scrollbar_text

# -------------
# set_up_calculations_scrollbar
def set_up_calculation_scrollbar():
    calculation_scrollbar = Scrollbar(root)
    calculation_scrollbar_text = Text(root, height=calculation_scrollbar_height, width=calculation_scrollbar_width)
    calculation_scrollbar.config(command=calculation_scrollbar_text.yview)
    return calculation_scrollbar, calculation_scrollbar_text

Example on setup:
# -------------------------------------------
# PROGRAMM SET UP
if __name__ == '__main__':
    # ---------------------------
    # main definition of gui
    root = Tk()
    root.title('Wetterderivate und Klima v_a0.0.1')
    #icon_path = get_local_path()
    #root.iconbitmap(icon_path + 'icon.ico') # icon
    root.geometry("1920x1080")
    root.resizable(width=False, height=False)

    # ---------------------------
    # call initial functions and set inital values
    scrollbar_width = 75
    scrollbar_height = 15
    calculation_scrollbar_height = 25
    calculation_scrollbar_width = 100

    # -------------
    # output_scrollbar
    output_scrollbar, output_scrollbar_text = set_up_output_scrollbar()
    output_scrollbar_text.grid(row=6, column=0, sticky='NS')
    output_scrollbar.grid(row=6, column=1, sticky='NS')
    # -------------
    # calculation_scrollbar
    calculation_scrollbar, calculation_scrollbar_text = set_up_calculation_scrollbar()
    calculation_scrollbar_text.grid(row=1, column=4, sticky='NS')
    calculation_scrollbar.grid(row=1, column=5, sticky='NS')

    root.mainloop()

How I can place them independed of each other side by side? Above the output_scrollbar are a lot of buttons and menus so when I place the calculation_scrollbar it shows like that:

A: You can use the arguments columnspan and rowspan to have one of the widgets spanning over several rows and columns. In your case, the Text widget and the scrollbar on the right should span several rows:
calculation_scrollbar.grid(row=1, rowspan=6, column=5, sticky='NS')

At least I gather that 6 rows should suffice, given the other scrollbar resting at row 6. Just give the text-widget the same rowspan or it will look awkward.
EDIT: Sometimes it may also be a good idea to use Frame-widgets to organize your window. In your case, I would recommend three frames (top left, bottom left, right). Each of the frames then has its own grid.


text:
Q: How did 'even' semantically shift to emphasize something surprising or extreme? This post's title refers to ODO's definition 1. Used to emphasize something surprising or extreme.

[ OED : ]
   II. In weakened use as an intensive or emphatic particle. (In later use many uses of senses in this branch show some suggestion of sense A. 8.)
5. Exactly, precisely, just. In later use generally somewhat archaic.
8. a. Used to convey that what is being referred to is an extreme case in comparison with a weaker or more general one which is stated or implied in the adjacent context. Prefixed to the particular word, phrase, or clause in which the extremeness of the case is expressed.
 b. In uses parallel to those at A. 8a, but placed after the word, phrase, or clause to which it relates.
[ Etymonline : ]   The adverb is Old English efne "exactly, just, likewise." Modern adverbial sense (introducing an extreme case of something more generally implied) seems to have arisen 16c. from use of the word to emphasize identity ("Who, me?" "Even you").
Etymologists are uncertain whether the original sense was "level" or "alike."

Q1. What semantic notions underlie 'levelness' or 'alikeness', with 'something surprising or extreme'?
Q2. Don't the semantic notions of 'levelness' or 'alikeness'  contradict the notion of 'something surprising or extreme'? If X is more extreme than Y, then X and Y are neither level nor alike.

A: I will try to explain the underlying semantic notion that connects sense (6) to sense (9). It's speculative, but I think on the right track.
Consider:

*

*She's mean, evil even.

*She's mean. She's even evil.

I take it that these are the kinds of construction you're asking about. Here, even intimates a more extreme version of mean, licensing evil.
A rough paraphrase of these would be:

*She's mean, or, more exactly, evil.

or

*She's mean, or, more precisely, evil.

These paraphrases include the words exactly and precisely. This is essentially sense (6) of your definition. The idea is that the new, more extreme word (in this case evil), is more exact or precise than its antecedent (in this case mean).
This should help you see how to get from sense (6) to (9). That this is the correct link to be looking for is corroborated by your quote, which says that sense (6) "suggests some notion of sense (9)."

A: Even is a scalar focus particle: the exact meaning is not only one of "surprise," but there is also a comparative component. It almost always implies  that something is more unexpected than some understood reference point. So when you say:

Even Thomas came to the party.I even helped her find a new roommate.I didn't even put on a belt, I was in such a rush.

It implies that others, generally more inclined to attend the party, also came; or that you did other, less helpful things to assist with her living situation; or that there were other, less remarkable indicators of your haste.
Heine and Kuteva (World Lexicon of Grammaticalization) give examples of words meaning "resemble" in Chinese and Colloquial German grammaticalizing to a comparative marker. Could this be a similar phenomenon? Not sure. I think even is an interesting word because the precise meaning is often not well characterized.


text:
Q: UML new lifeline I am doing a UML sequence diagram and I've got like, say, a GUI Controller object who wants to create a new Circle object and then add it to an ActiveDrawables object. Would the diagram in the picture below be correct? Or should I've sent the add() from like the Circle's lifeline (thought this seems kind of weird)?

In code, for example, the Controller would have been the one calling add, like in the picture, but I was having doubts whether I should have sent the message from the Circle's lifeline (though, again, this seems weird).

A: Of course it depends on your design, but what you have drawn is the usual approach.
The other approach (with Circle contacting ActiveDrawables) is sometimes used as well, e.g.

*

*when all Circles has to be in the same ActiveDrawables,

*for efficiency reasons GUIController might pass ActiveDrawables identifier to Circle to create it immediately in ActiveDrawables

*if Circle needs to be always attached to ActiveDrawables you may also pass identifier like in previous point

Few things to consider about your diagram:

*

*You don't have to number your messages. It's a technology used in communication diagram rather than in sequence diagram.

*The last message seems to be a return (reply) from the previous one. You should use a different arrow for that.

*Instead of Circle name the lifeline c1: Circle. Then you'll have an object c1 of type Circle. Then in add operation you can use c1 showing precisely that your passing the newly created Circle object, not just some Circle.