text:
Q: Specify alignment per column in align equation Using the following mwe i have not yet found a way to align the formulas correctly.
\documentclass{article}
\usepackage{mathtools}  % extends amsmath and fixes some of its quirks
\usepackage{amssymb}
\begin{document}

\begin{align}\label{eq:mergefunction_with_weighting}
\curlyvee(v, \omega) :=
l_1 \triangleright l_2 =
\left\{
 \begin{aligned}
       &l_1(v)               &                          &\text{wenn $v \in G_1 \setminus G_2$}\\
\omega(&l_1(v)) + (1-\omega)(&\hat{R}l_2(v) +\hat{t})   &\text{wenn $v \in G_1 \cap G_2$}\\
       &                     &\hat{R}l_2(v) +\hat{t}    &\text{wenn $v \in G_2 \setminus G_1$}.
 \end{aligned}
\right.
\end{align}

\end{document}

My output is currently like this:

Everything is fine except the vertical and horizontal alignment/spacing within the aligned environment. But in that you can notice the following:
 - First & works fine.
 - The second & should be aligned to
   \hat{R} and without spacing between the ( and the \hat{R} in
   the middle row
 - At the last &, the spacing in the middle row between
   \hat(t)) and wenn should be larger. (I think this one would disappear as soon as the second & is fixed.
So the requests i have sum up to the question: Whats the best and consistent way to approach placement issues like these?

A: Your output is what you'd expect from aligned: you have four columns, the 1st and 3rd right aligned, the 2nd and 4th left aligned, and some space between the first and the second "lr pair". What you actually want is best achieved with a cases environment; @{} is used where you don't want space between the columns.

Note that the vertical space between the lines is smaller than with your aligned code. If you want the same vertical spacing as with aligned, use \\[\jot] instead of \\ in the code below.
\documentclass{article}
\usepackage{mathtools}  % extends amsmath and fixes some of its quirks
\usepackage{amssymb}
\begin{document}
\begin{align}\label{eq:mergefunction_with_weighting}
  \curlyvee(v, \omega) := l_1 \triangleright l_2 =
  \left\{
    \begin{array}{@{}r@{}l@{}ll}
       &l_1(v)               &                          &\text{wenn $v \in G_1 \setminus G_2$}\\
\omega(&l_1(v)) + (1-\omega)(&\hat{R}l_2(v) +\hat{t})   &\text{wenn $v \in G_1 \cap G_2$}\\
       &                     &\hat{R}l_2(v) +\hat{t}    &\text{wenn $v \in G_2 \setminus G_1$}.
    \end{array}
  \right.
\end{align}
\end{document}

You can also use \begin{cases}...\end{cases} instead of \left\{...\right., but then in this particular example the equation number doesn't fit anymore. Moreover, note that there's no need to use align as the outer environment since that one has no tab stops; I'd use equation instead.

A: You can use the cases environment and \phantom to achieve the desired alignments
\[
\curlyvee(v, \omega) :=
l_1 \triangleright l_2 =
\begin{cases}
\phantom{\omega(}l_1(v) &   \text{wenn $v \in G_1 \setminus G_2$}\\
\omega(l_1(v)) + (1-\omega)(\hat{R}l_2(v) +\hat{t})   &\text{wenn $v \in G_1 \cap G_2$}\\
\phantom{\omega(l_1(v)) + (1-\omega)(}\hat{R}l_2(v) +\hat{t} &\text{wenn $v \in G_2 \setminus G_1$}.
\end{cases}
\]

A second option is to use a tabbing environment inside a minipage
\[
\curlyvee(v, \omega) :=  l_1 \triangleright l_2 =
\begin{cases}
  \begin{minipage}{0cm}
    \begin{tabbing}
      $\omega($\=$l_1(v)) + (1-\omega)($\=$\hat{R}l_2(v)+\hat{t})$ \quad\= \kill
      \> $l_1(v)$ \>\>   wenn $v \in G_1 \setminus G_2$\\
      $\omega(l_1(v)) + (1-\omega)(\hat{R}l_2(v) +\hat{t})$ \>\>\> wenn $v \in G_1 \cap G_2$\\
      \>\> $\hat{R}l_2(v) +\hat{t}$ \> wenn $v \in G_2 \setminus G_1$.
    \end{tabbing}
  \end{minipage}
\end{cases}
\]

A: I think you want to use the alignedat environment instead of aligned.  This is similar to the aligned environment in that it provides pairs of r/l equations, but without the inter equation space that the aligned environment adds. So the only changes required to your code as posted above are:

*

*Replace the \begin{aligned} with \begin{alignedat}{4}, and the corresponding end{}.

*Change the second and third alignment point from & to &&.  This doubling changes the alignment from right aligned to left aligned which is what you want.

*Change text{wenn...} to text{ wenn...}, or use \quad\text{wenn...} instead so that you have some space there.

Notes:

*

*But as the other solutions mention, the outed environment really is a cases (or dcases) environment and should not be an align as you do not have multiple equations that are aligned. You have one equation.

Code:
\documentclass{article}
\usepackage{mathtools}  % extends amsmath and fixes some of its quirks
\usepackage{amssymb}
\begin{document}

\begin{align}\label{eq:mergefunction_with_weighting}
\curlyvee(v, \omega) :=
l_1 \triangleright l_2 =
\left\{
 \begin{alignedat}{4}
       &l_1(v)               &&                          &&\quad\text{wenn $v \in G_1 \setminus G_2$}\\
\omega(&l_1(v)) + (1-\omega)(&&\hat{R}l_2(v) +\hat{t})   &&\quad\text{wenn $v \in G_1 \cap G_2$}\\
       &                     &&\hat{R}l_2(v) +\hat{t}    &&\quad\text{wenn $v \in G_2 \setminus G_1$}.
 \end{alignedat}
\right.
\end{align}

\end{document}


text:
Q: Fundamental issue with backbone collections Being trying to get my head around Backbone, and was working away fine until I hit the following snag which makes me think I'm going about this wrong.
In the following code, I have a model and a collection. The collection is called bb.model.Settings an a function called changetheme which gets a value. Now I have the value getting this far, but when I go to save this item, Do I need to pass it to the model. I'm trying to call the save function in the model but am wondering do I actually need to this, it keeps failing anyway. Should I just save the collection or what is best way to save this
bb.model.Setting = Backbone.Model.extend(_.extend({
    defaults: {
        theme: 'e'
    },

    initialize: function() {
        var self = this
        _.bindAll(self)
    },
    save: function() {
        var self = this
        _.bindAll(self)
    },
}))

bb.model.Settings = Backbone.Collection.extend(_.extend({
    model:  bb.model.Setting,
    localStorage: new Store("settingb"),

    initialize: function() {
        var self = this
        _.bindAll(self)
    },
    changetheme: function(value) {
        var self = this
        _.bindAll(self)
        this.remove
        this.model.save()
    },
}))

A: Try checking out this fiddle, you had a couple of errors in your code:
http://jsfiddle.net/8gDqb/1/
Here's the js portion, see the fiddle for full working example:
var bb = {};
bb.model={};

bb.model.Setting = Backbone.Model.extend({
    defaults: {
        theme: 'e'
    },

    initialize: function() {
        var self = this
        //_.bindAll(self) // no longer necessary with backbone.js
    },
    save: function() {
        var self = this
        //_.bindAll(self) // no longer necessary with backbone.js
    },
});

bb.model.Settings = Backbone.Collection.extend({
    model:  bb.model.Setting,
    //localStorage: new Store("settingb"),

    initialize: function() {
        var self = this
        //_.bindAll(self) // no longer necessary with backbone.js
    },
    changetheme: function(value) {
        var self = this
        _.bindAll(self)
        //this.remove
        //_.bindAll(self) // no longer necessary with backbone.js
    },
});

Also, just in case you're reading old howtos about backbone in the net, you don't need to bindAll anymore.  That hasn't been necessary for quite some time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Table of Contents in a Journal I have a problem with the numbering of items.
I own the items separately and do not know how to put it together, for the numbering, etc, etc.
I have several articles, and need to get an index should be done as follows
                               Contents

Name of the Article
Author of Article .......................................................Page Number
Name of the Article
Author of Article .......................................................Page Number
Name of the Article
Author of Article .......................................................Page Number
Etc, etc.
Thanks for your help

A: Use the combine class. The combine class can be used to turn a collection of independent *.tex files into a compilation. Here is an example:
main.tex
\documentclass[book]{combine}
\title{A Book Example Using the Combine Class}
\author{TeX.SX}

\begin{document}
\maketitle
\tableofcontents

\chapter{Introduction}
I'm adding an introduction to this collection

\begin{papers}
    \coltoctitle{Hello, World}
    \coltocauthor{Tom Thompson}
    \label{doc1}
    \import{doc1} % this is doc1.tex; notice the lack of *.tex in the file name

    \coltoctitle{Farewell, everyone}
    \coltocauthor{John Johnson}
    \label{doc2}
    \import{doc2}
\end{papers}

\chapter{Acknowledgements}
\emph{You}, for asking this question on TeX.SX!

\end{document}

doc1.tex
\documentclass{article}

\begin{document}
\chapter{Introduction}
Hello, world! How are you?

This is the end of the first part.
\end{document}

doc2.tex
\documentclass{article}

\begin{document}
\chapter{Farewell}
Goodbye, World. I'll miss you.

This is the end of the second part.

\end{document}

Note that the \import{} command takes the name of the LaTeX file without the *.tex extension. See the documentation for combine for more information on how to use it.


text:
Q: Create a label and it's associated element without using ID I'm gonna create a label element and it's associated input element together using JavaScript. This can be achieved if I use id and for attributes:

// Create input element:
let newInput = document.createElement('Input');
newInput.setAttribute('type', 'radio');
newInput.setAttribute('value', 'y');
newInput.setAttribute('id', 'myInput2');
newInput.setAttribute('name', 'opt');
document.body.appendChild(newInput);

// Create label for new Input:
let newlabel = document.createElement('Label');
newlabel.setAttribute('for', 'myInput2');
newlabel.textContent = 'Option 2:';
document.body.appendChild(newlabel);
<input type='radio' value='x' id='myInput1' name='opt'>
<label for='myInput1'>Option 1:</label>

The problem is: I have so many forms and so many inputs too, so this solution(which Chooses id for any input) looks like to be a nightmare rather than an option. In other hand, it seems ridiculous to create ID for an element just for binding it to a label (Of course it's my opinion)!
Fortunately there is an option in HTML to get rid of these kind of IDs:

// I couldn't find any way to create a new label and it's bounded element without using ID!
<label>
Option 1:
<input type='radio' value='x' name='opt'>
</label>

But I couldn't find it's JavaScript equivalent:(
So my question is: How can I create a label element in JavaScript and bind it to an input element without specifying ID?

A: you should append input to label, like this:

for (const i of [1, 2]) {

  // Create input element:
  let newInput = document.createElement('Input');
  newInput.setAttribute('type', 'radio');
  newInput.setAttribute('value', 'y');
  newInput.setAttribute('name', 'opt');

  // Create label for new Input:
  let newlabel = document.createElement('Label');
  newlabel.textContent = `Option ${i}:`;
  newlabel.appendChild(newInput);
  document.body.appendChild(newlabel);

}


text:
Q: Index Datetime freq stays NONE after asfreq I was going through a lot of questions here but nothing is working for me. I try to get an Datetime index for my Pandas Dataframe. tried resample, asfreq. The index is already a Datetime Object, but it keeps the NONE freq.
dfz = sale.loc[(sale.Open == 1) & (sale.Promo == 0) & (sale.Sales > 0), ["Sales", "Customers"]]
print(dfz.asfreq('M').index)
print(dfz.index)

Result is:
DatetimeIndex([], dtype='datetime64[ns]', name='Date', freq='M')
DatetimeIndex(['2015-07-20', '2015-07-20', '2015-07-20', '2015-07-20',
               '2015-07-20', '2015-07-20', '2015-07-20', '2015-07-20',
               '2015-07-20', '2015-07-20',
               ...
               '2013-01-06', '2013-01-06', '2013-01-06', '2013-01-06',
               '2013-01-06', '2013-01-06', '2013-01-06', '2013-01-06',
               '2013-01-06', '2013-01-06'],
              dtype='datetime64[ns]', name='Date', length=467463, freq=None)
            Sales  Customers

Why does it show me a freq in the result of the asfreq but when I call the index it is still NONE?


text:
Q: Hide/customize status 500 error message/status description inside response header (Glassfish) I'm developing jsf 2 web app which runs under GlassFish (v3.1.2.2). This app has custom error 500 page which is defined in web.xml. My question is whether there is a possibility to disable/hide/customize error message/status description inside response header for status 500 response? Currently I'm getting something like this:
HTTP/1.1 500 /view.xhtml @11,30 [error message same as in root exception] <- I want to hide this one (only message/status description)
X-Powered-By: JSF/2.0
Content-Type: text/html;charset=UTF-8
Transfer-Encoding: chunked
Date: Thu, 09 Jan 2014 15:33:44 GMT
Connection: close

Thank you!

A: Define a filter on web.xml to intercept the error and generate the response you like.
https://stackoverflow.com/tags/servlet-filters/info

A: I have found a solution. It is not nice but it works. See
JSF 2.0 web.xml error page status code.
Instead of changing status code I leave status code as it is and change only status message:
...
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
HttpServletResponse hp = (HttpServletResponse) ec.getResponse();
hp.setStatus(hp.getStatus(), "my new message");
...


text:
Q: Controlling unpredictable (to me) y-axis behavior using gap.barplot() I have a barplot with y-axis break for 10 pairs of data points (matrix A). I want the exact same barplot except a subset of just five of these pairs (matrix B). But when I plot B, the y-axis seems to begin not at 0, but at the minimum y value in the data.
I've tried specifying ylim=c(0,300), but it does not behave as expected with the axis break. Anyone have advice on having the same y-axis ranges for plots A and B?
A <- rbind( NA,
        c(7.31,8.13,0.44,60.50,8.51,19.25,10.50,25.86,296.64,44.86),
        c(6.65,6.08,0.34,58.88,8.08,24.83,9.05,47.89,240.31,36.31))
B <- A[,c(4,6,8,9,10)]

pA <- gap.barplot(A,
            gap=c(65,230),
            ytics=c(0,25,50,250,275,300),
            xaxt='n')

pB <- gap.barplot(B,
            gap=c(65,230),
            ytics=c(0,25,50,250,275,300),
            xaxt='n')

Graph of pA

Graph of pB

(The NA values are in there for spacing, by the way)

A: You were on the right track with specifying the y-limits.
#loading package
library(plotrix)

pB <- gap.barplot(B,
              gap=c(65,230),
              ytics=c(0,25,50,250,275,300),
              xaxt='n',
              ylim=c(0,135))

I can't embed pictures in my posts yet, so here's a link to the plot made by this code.
This reference page for the gap.barplot function says that

If the user does not ask for specific y limits, the function will calculate limits based on the range of the data values. If passing specific limits, remember to subtract the gap from the upper limit.

Since the barplot's gap is from 65 to 230, subtract 165 (that's 230 - 65) from the upper limit to get the real upper limit, 135. Another way to look at it is that the you want your plot to be 135 units tall (0 to 65, then 230 to 300), the y-limits will be ylim=c(0,135).
Just add ylim=c(0,135) to what you already have for plot B, and you're good.


text:
Q: Populating Jinja2 Template with Ansible Variables? In my Ansible playbook I am trying to set custom variables and then use those variables to populate a license file that I have in json. My idea is something like this.
   vars:
     customFields:
        unique_key: unique_value
        unique_key1: unique_value1

I would then populate the license.json using the template module and jinja2 in this way:
{
    "customer": "{{ customer_name }}",
    "validTil": "{{ lic_valid_till }}",
    {% for field in customFields %}
    "customFields": {
        "{{ field.key }}":"{{ field.value }}"
    }
    {% endfor %}
}

Am I doing this the right way and is something like this supported?

A: Yes. It's supported. Use items()
    {% for key, value in customFields.items() %}
    "customFields": {
        "{{ key }}":"{{ value }}"
    }
    {% endfor %}


text:
Q: Background-clip text from parent element I have a page with a full-screen background that has some blocks with a black background on it. I would like to achieve that the text in those black blocks looks like it's cut out from the black box so you can see the background image.
Below is a simplified version of the HTML and CSS set-up:

.background {
background-image: url(https://picsum.photos/200/300);
height: 100vh;
width: 100vw;
}

.blackbox {
background-color: black;
padding: 30px;
display: inline-block;
margin-top: 100px;
margin-left: 400px;
}

.text {
font-size: 40px;
font-weight: bold;
font-family: 'Helvetica', 'Arial', sans-serif;
background-clip: text;
-webkit-background-clip: text;
color: transparent;
background-image: url(https://picsum.photos/200/300);
}

TEXT

If I move the background image to the child text element, the clipping works but it doesn't match with the background-image on the parent element. I thought this question had my answer but the child element doesn't have a background.

A: This should be responsive. mix-blend-mode is what you're looking for:
Source (https://www.w3schools.com/howto/howto_css_cutout_text.asp)

.background {
background-image: url(https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/800px-Image_created_with_a_mobile_phone.png);
background-size: cover;
position: relative;
height: 200px;
}

.text {
  background-color: black;
  color: white;
  font-size: 5vw;
  font-weight: bold;
  margin: 0 auto;
  padding: 0 15px 0 15px;
  text-align: center;
  position: absolute;
  height: 200px;
  line-height: 200px;
  mix-blend-mode: multiply; /* This makes the cutout text possible */
}

TEXT


text:
Q: Keyboard not responding after resuming from suspend A fresh install of Lubuntu 16.04 (not dual, just Linux) on a HP EliteBook Folio G1 (with touchpad screen) seems to perform well, except for the fact that after resuming from the suspend state, the keyboard is unresponsive, and have to be restarted to continue operating.
Edit:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash atkbd.reset"

update-grub and reboot already tried, with no result. credit


text:
Q: Android: structuring of layout files (e.g. like in subfolders) Is there a way to structure layout files, e.g. like in subfolders (as subfolders of resources are not supported)?
I have many layout files which all lie in the layout folder.
This gets pretty
is it possible to somehow structure them, by tags, by subfolders or something else?
E.G.:

*

*layout

*

*screen A

*screen B

or

*

*layout

*

*fragments

*activities

or

*

*layout

*

*component A

*component B

A: Yes, you can have multiple resource folders in your project using Gradle.
It allows you to organize not only your layout files but any kind of resources.
This is how the configuration looks like:
sourceSets {
    main {
        res.srcDirs = ['src/main/res', 'src/main/res2']
    }
}

Documentation
Example Project


text:
Q: Remap UID in samba share Is it possible to remap the UID (and GID) that is being reported to a samba client? It looks like it may be possible with the various idmap options, but it looks overly complicated for the simple remap I want to accomplish and I'm confused as to whether this is even the right approach.
Consider two machines A and B.
Machine A has user smbuser with UID 701. Machine B only has a root user with UID 0.
smb.conf excerpt from machine A:
[share1]
  path = /tmp/share1
  valid users = smbuser

On machine B:
mount -t cifs -o username=smbuser,pass=**** //10.1.1.11/share1 /mnt
ls -l /mnt

I see:
drwx------  701  701       0 Jan  1 00:00  .
drwx------  root root      0 Jan  1 00:00  ..
-rw-------  701  701      42 Jan  1 00:00  testfile

I want:
drwx------  root root      0 Jan  1 00:00  .
drwx------  root root      0 Jan  1 00:00  ..
-rw-------  root root     42 Jan  1 00:00  testfile

TL;DR: I need samba to remap UID 701 -> 0 when feeding directory lists to clients.

A: You want the combination of the uid, forceuid, gid and forcegid mount options. That way, you can instruct a SMB client to always assign a certain UID and GID to own the files. As a plus, you don't need to change the SMB server config for this.
See the manpage for cifs.mount at https://linux.die.net/man/8/mount.cifs:

uid=arg sets the uid that will own all files or directories on the mounted filesystem when the server does not provide ownership information. It may be specified as either a username or a numeric uid. When not specified, the default is uid 0. The mount.cifs helper must be at version 1.10 or higher to support specifying the uid in non-numeric form. See the section on FILE AND DIRECTORY OWNERSHIP AND PERMISSIONS below for more information.
forceuid instructs the client to ignore any uid provided by the server for files and directories and to always assign the owner to be the value of the uid= option. See the section on FILE AND DIRECTORY OWNERSHIP AND PERMISSIONS below for more information.
gid=arg sets the gid that will own all files or directories on the mounted filesystem when the server does not provide ownership information. It may be specified as either a groupname or a numeric gid. When not specified, the default is gid 0. The mount.cifs helper must be at version 1.10 or higher to support specifying the gid in non-numeric form. See the section on FILE AND DIRECTORY OWNERSHIP AND PERMISSIONS below for more information.
forcegid instructs the client to ignore any gid provided by the server for files and directories and to always assign the owner to be the value of the gid= option. See the section on FILE AND DIRECTORY OWNERSHIP AND PERMISSIONS below for more information.

In your case, you can use (not specifying a UID/GID will use the default 0):
mount -t cifs -o username=smbuser,pass=****,uid,forceuid,gid,forcegid //10.1.1.11/share1 /mnt

Also take a look at the dynperm option which may be of use to you.
For reference, the "File And Directory Ownership And Permissions" sections learns:

File And Directory Ownership And Permissions
The core CIFS protocol does not provide unix ownership information or mode for files and directories. Because of this, files and directories will generally appear to be owned by whatever values the uid= or gid= options are set, and will have permissions set to the default file_mode and dir_mode for the mount. Attempting to change these values via chmod/chown will return success but have no effect.
When the client and server negotiate unix extensions, files and directories will be assigned the uid, gid, and mode provided by the server. Because CIFS mounts are generally single-user, and the same credentials are used no matter what user accesses the mount, newly created files and directories will generally be given ownership corresponding to whatever credentials were used to mount the share.
If the uid's and gid's being used do not match on the client and server, the forceuid and forcegid options may be helpful. Note however, that there is no corresponding option to override the mode. Permissions assigned to a file when forceuid or forcegid are in effect may not reflect the the real permissions.
When unix extensions are not negotiated, it's also possible to emulate them locally on the server using the "dynperm" mount option. When this mount option is in effect, newly created files and directories will receive what appear to be proper permissions. These permissions are not stored on the server however and can disappear at any time in the future (subject to the whims of the kernel flushing out the inode cache). In general, this mount option is discouraged.
It's also possible to override permission checking on the client altogether via the noperm option. Server-side permission checks cannot be overriden. The permission checks done by the server will always correspond to the credentials used to mount the share, and not necessarily to the user who is accessing the share.


text:
Q: Quiz from external text file Python I am trying to create a quiz where I have questions and answers from an external text file to import into Python so that the user can input a selection.
The problem is that my code only prints "Correct" at the end of the quiz once, and doesn't say after each question answered if the user got the question correct or incorrect.
The first column (detail[0]) is where the question is and the correct answer is in the fourth column (detail[4]))
Thanks
Here is what is in the text file:
What is 1+1,1,2,2
What is 2+2,4,2,4

Here is the source code below:
def quiz():
    file = open("quiz.txt","r")
    right = False

    for line in file:
        detail = line.split(",")
        print(detail[0])
        select = input("Select 1 or 2: ")
        if select == detail[3]:
            right = True
            break

    if right == True:
        print("Correct")
    else:
        print("Incorrect")

A: Just modify the main for-loop to print the result there and then:
for line in file:
    detail = line.split(",")
    print(detail[0])
    select = input("Select 1 or 2: ")
    if select == detail[3]:
        print("correct!")
    else:
        print("incorrect :(")


text:
Q: How to get proxy addresses using https://microsoft.graph.com and GraphServiceClient I am trying to obtain proxy addresses, but the proxy addresses property returns null even though proxy addresses exist.
    GraphClientHelper graphClientHelper = new GraphClientHelper(tenantId);
        GraphServiceClient graphServiceClient = graphClientHelper.GetGraphServiceClient();
        IGraphServiceUsersCollectionPage user = await graphServiceClient.Users.Request().GetAsync();

I get proxy addresses using https://windows.net and ActiveDirectoryCLient.

A: You need to request proxyAddresses specifically.
For example:
var users = await graphClient.Users.Request().Select("id, mail, proxyAddresses").GetAsync();


text:
Q: A interface IActionResult do asp.net.core.mvc serve pra exatamente o que? Estou aprendendo a fazer web api em C# e fiz um controller que tem um método POST que recebe um dado e faz uma regra de negócio na api, podendo retornar um BadRequest, um Ok ou um StatusCode dependendo do dado que vier do frontend.
        [HttpPost]
        public IActionResult EfetuarLogin([FromBody] LoginRequisicaoDto requisicao){
        ...

O LoginRequisicaoDto nada mais é que uma dto com login e senha, e 'requisicao' é onde foi guardado os dados recebidos pra ser usado, como se a requisicao fosse uma instância desse dto (por exemplo pra validar o login e a senha, ou certificar que não são nulos).
A pergunta é: não entendi o porque de ser um IActionResult como tipo de retorno, esse método EfetuarLogin() poderia ter outro tipo de retorno? Ou por ter várias possibilidades de retorno o IActionResult é o que precisa?
Obrigado e até mais!

A: Se a ideia é retornar os dados para o cliente sem considerar erros ou exceções e códigos HTTP (como 404, 200, 201, etc..) faria sentido, ainda que eu não entenda como uma boa prática.
Este endpoint que você demonstra (EfetuarLogin), recebe os dados do usuário, se os dados do usuário não estiverem corretos, ele terá que retornar um 404 - NotFound, por exemplo, já se estiverem corretos, terá que retornar um 200 - Ok.
Vale ressaltar que existe uma diferença entre utilizar IActionResult e ActionResult.
A interface IActionResult tem retornos mais amplos, que inclui qualquer código que implemente esta interface.
ActionRetult é limitada somente às classes que estendem a classe abstrata de ActionResult. (Você também pode customizar, a diferença é a herança múltipla que a interface permite e uma extensão de classe, não).

A: Todos os métodos públicos de uma classe MyClass : Controller são chamados de "Actions", e devolvem qualquer tipo de dado que seja definido no retorno do metódo à requisição, como por exemplo public List<MinhaLista>.
Porém .NET  inclui várias classes Result. O padrão do .NET framework é a classe abstrata "ActionResult", que representa diferentes tipos de retorno pré-definidos, como HTML, JSON, HttpUnauthorizedResult e etc.
.NET CORE adotou como retorno padrão a interface IActionResult, o que te habilita a, além de retornar implementações padrão, retornar sua própria classe customizada Result que herde de IActionResult.


text:
Q: I am trying to use join with update query but cant find the issue Please help me to correct the syntax
UPDATE
    user_shift_test
SET
    shifttime='01:00-21:00'
FROM
    user_shift_test
INNER JOIN swaps
ON
    user_shift_test.userid=swaps.csrid
WHERE
    user_shift_test.userid=5

This error am getting

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
  near 'FROM user_shift_test INNER JOIN swaps ON user_shift_test.useri'
  at line 5

A: UPDATE user_shift_test
SET shifttime='01:00-21:00'
WHERE userid IN
               (SELECT user_shift_test.userid
                FROM user_shift_test
                JOIN swaps ON swaps.csrid=user_shift_test.userid
                WHERE
                user_shift_test.userid=5
               );

A: Try this:
UPDATE user_shift_test
INNER JOIN swaps
ON user_shift_test.userid=swaps.csrid and user_shift_test.userid=5
SET shifttime='01:00-21:00'

(I am assuming that you are trying to do an update query using a JOIN)

A: this should do it
UPDATE user_shift_test
FROM user_shift_test
SET shifttime='01:00-21:00'
WHERE user_shift_test.userid=5
INNER JOIN swaps
ON user_shift_test.userid=swaps.csrid


text:
Q: Postgres column "value" does not exist I'm building a command that will execute a direct psql query on an operating system (Ubuntu) command line. Strangely enough the following error always occurs: ERROR: column "value" does not exist.
However, the query works if you are directly logged into the database.
Query:
psql -U testuser -x -c 'SELECT * FROM table where name = "value"'

I have already try different quotes , but it not works
Do you have any ideas?


text:
Q: How to sum the content of all the files in directory columnwise I want to add these files column wise i.e. column 1 of file 1 should be added to column 1 of file 2 and so on....,
similarly column 2 of file 1 should be added to column 2 of file 2 ......
Col1(File1) + Col1(File2) + Col1(File3) .............. + Col1(File'n') = Col1(output_file)

Col2(File1) + Col2(File2) + Col2(File3) .............. + Col2(File'n') = Col2(output_file)

or if the files are like this
File 1          File 2          File n                   Output File
a   d           b   e           c   f               a+b+...+c   d+e+....+f
c   d           c   d           a   b               c+c+...+a   d+d+....+b
e   f           e   f           a   b                   .       .
g   h      +    g   h           a   b               .       .
.   .           .   ......+......   .       =       .       .
.   .           .   .           .   .                   .       .
.   .           .   .           .   .                   .       .
.   .           .   .           .   .                   .       .
.   .           .   .           .   .                   .       .

A: Here's one way of doing it in perl:
#!/usr/bin/perl

use strict;

my @lines=();

# read and sum the columns of all input files.
foreach my $file (@ARGV) {
  my $lc=0;   # line counter

  open(FH,'<',$file) or die "couldn't open $_ for write: $!\n";

  while (<FH>) {
    # split columns by whitespace.  change to suit your input.
    my @fields=split;

    my $fc=0;   # field counter

    while ($fc < @fields) {
      $lines[$lc]->[$fc] += $fields[$fc++];
    };
    $lc++;
  };

  close(FH);
};

# now output the summed lines
foreach my $lc (0..@lines-1) {
  # output columns separated by a TAB (\t).  Change as required.
  print join("\t", @{ $lines[$lc] } ),"\n";
}

Sums columns for each line for all input files.
Non-numeric values in fields are treated as 0.
Works with files that have the same or different numbers of lines.
It even works if files have varying numbers of fields per line (although the output may not be what you expect or even usable - not recommended).


text:
Q: How can I decide which client can see a page and which not I have a multi step form and have validated it with java and php but yet I want that after submitting and redirected to my desired page my client to be the only one to see the redicted page , not like he can just copy the link and give it to somebody and than others could se that page to I don't want that .
So to be more specific I want it so that after my client submits his form to get a kind of an id or something that can see or checked from my redirect page and than the redicted page to oppened up to him and that only for a specific time.

A: Without any more information about frameworks used, etc., try using sessions
In the final form processing page, do something like:
$_SESSION['form_finished'] = true;

To "make a note" that this person has finished the form. In the final "submitted" page, ensure that the person has finished the form with something like:
if (!isset($_SESSION['form_finished'])) {
    // Redirect to error page, display error message, etc
}

A: There is several ways that you can do this, but it also depends on the environment. You can create a session on form submission with a parameter that will be checked when redirecting to the page, then checking if the parameter exists after redirection as @michaelb suggested.
form.php
session_start();
$_SESSION['form_finished'] = true;
header('location: /../mycode.php');

Then on destination.php...
session_start();
if(!$_SESSION['form_finished']) {
    header("HTTP/1.0 404 Not Found");
    exit;
}

EDIT:
To redirect once form is submitted you will need to do something like this.
if (isset($_POST['submit'])) {
//form processing code//
    if ($no_errors) {
        session_start();
        $_SESSION['form_finished'] = true;
        header('location: /../mycode.php');
    }
}

If your users are logged in, and you are looking for a more permanent and secure solution, you could add a field to the database which you check on destination.php instead of the $_SESSION() variable.


text:
Q: How to import a library from C to a Assembly code? I'm trying to convert a C code to Assembly but I have a problem in the Assembly code. In the C code i'm importing the 'conio.h' library to use the getch() function, but in the Assembly code when I have the call of this function the output says error because the getch() function is undefined. I've already tried use the extern command in the asm code but it didnt work. Any ideias how to solve this?
C code for reference:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

int main()
{
    int cont=0;
    char *string;
    string = (char*)malloc(sizeof(char)*20);
    do{
        string[cont] = getch();
        cont++;
    }while (string[cont] != '\0');
    printf("%s", string);
    return 0;
}

Assembly code for reference:
.intel_syntax
.global main
.text

main:
        push    %rbp
        mov     %rbp, %rsp
        push    %rbx
        sub     %rsp, 40
        mov     DWORD PTR [%rbp-28], 0
        mov     %edi, 20
        call    malloc
        mov     QWORD PTR [%rbp-24], %rax
.L2:
        mov     %eax, DWORD PTR [%rbp-28]
        cdqe
        mov     %rbx, %rax
        add     %rbx, QWORD PTR [%rbp-24]
        mov     %eax, 0
        call    getch   ; Call of the getch function
        mov     BYTE PTR [%rbx], %al
        inc     DWORD PTR [%rbp-28]
        mov     %eax, DWORD PTR [%rbp-28]
        cdqe
        add     %rax, QWORD PTR [%rbp-24]
        movzx   %eax, BYTE PTR [%rax]
        test    %al, %al
        jne     .L2
        mov     %rsi, QWORD PTR [%rbp-24]
        mov     %edi, OFFSET FLAT:.LC0
        mov     %eax, 0
        call    printf
        mov     %eax, 0
        add     %rsp, 40
        pop     %rbx
        leave
        ret

.LC0:
        .string "%s"


text:
Q: How does std::bind and std::thread copy the arguments that are perfectly forwarded? There is something I miss about std::bind and std::thread. Internally, they both forward the rvalue reference template argument (perfect forwarding). But it is known that it copies the object passed to it, instead we wrapp the lvalue references in std::ref(). If you pass a lvalue like the following:
template <typename T>
void fct(T&& x)
{
    f(std::forward(x));
}

...

int r{9};
fct(r);

In this case, r is perfectly forwarded as an lvalue.
So, where does the copy occurs, since in the source code, they always use std::forward?
I understand the reason behind the copying step, but how is it really implemented?
Also, this could help me to understand the use of std::ref in depth.
I thank you in advance for your help.


text:
Q: Shortest path to basic install of VS2015 DirectX app I have a C++ D3D11 project built in VS2015.  It would appear that vc-redistx86.exe does NOT contain everything I need for it to run.  To wit, all of the files such as api-ms-win-crt-runtime-l1-1-0.dll seem not to be installed by that redistributable.
My question then is twofold:

*

*What do I need to install in order to get all of the files such as api-ms-win-crt-runtime-l1-1-0.dll, whereas the redist package seems to install only 4 dlls.

*Is there an installer that can manage this without a week's learning curve?  I'd like to check a box for "VS2015 Prerequisites" and have it just happen.  It doesn't has to be free if it works well!  This is NOT a product recommendation question, it's a ease-of-use question; they can all do it at some level.

A: *

*Install all pending Windows Updates
Go to Start – Control Panel – Windows Update
Check for updates and install all pending updates, then restart the computer.
After the restart repeat the steps above again until no more updates are available.

*Download the Visual C++ Redistributable 2015
For Windows 64-bit
Visual C++ Redistributable for Visual Studio 2015 (64-bit)
For Windows 32-bit
Visual C++ Redistributable for Visual Studio 2015 (32-bit)
Run the vcredist_x64.exe (64-bit) or vcredist_x86.exe (32-bit) and select Uninstall if already installed

*Run the .exe again and select Install and restart the computer
See also here or here.


text:
Q: Rails render buttons by really complex condition My rails application members may have one of the two different roles: vip_lite and vip.
They can subscribe plan to renew their authorizing.
We also have four types plan: vip_lite/monthly, vip_lite/yearly, vip/monthly, vip/yearly.
A vip user might be subscribing one of the four plans, so does vip_lite.
Member with different roles and different plans can see different buttons in plan page(e.g. vip_lite and subscribing vip_lite/monthly member can see 'upgrade' button in vip plan page).
see the following sample code: (currently write in helper)
def plan_action_button(user)
  if user.vip? && user.subscribing_plan?(:vip_lite, :monthly)
    'button_a'
  elsif user.vip? && user.subscribing_plan?(:vip_lite, :yearly)
    'button_b'
  elsif user.vip? && user.subscribing_plan?(:vip, :monthly)
    'button_c'
  elsif user.vip? && user.subscribing_plan?(:vip, :monthly)
    'button_d'
  elsif user.vip_lite? && user.subscribing_plan?(:vip, :monthly)
    'button_e'
  elsif user.vip_lite? && user.subscribing_plan?(:vip, :yearly)
    'button_e'

    ... and so on...
  end
end

So I have to deal with 2 * 4 = 8 conditions for each button in these pages. Is there a good pattern in rails for dealing with such case? Thanks

A: There are some interesting patterns that you can use here. Let's see what's repeated the most: user.vip?
Let's start the method with a guard clause
def plan_action_button(user)
  return 'whatever you need to return' unless user.vip?

  if user.subscribing_plan?(:vip_lite, :monthly)
   'button_a'
[...]

Then because there's a lot of combinaisons, it's hard to tell what changes and what remains the same for those buttons. Is it a I18n key? Is is the button tag with different links? Do you have access to those parts separately like user.plan_name and user.plan_frequency?
Answering those questions would help you a lot in seeing emerge a pattern.


text:
Q: ReferenceError: serverTest is not defined I'm trying to pass a consol.log() output to a function, but i'm getting an error, i'm trying to fix this for hours but failed to do so. This is actually for travis ci but i'm having a hard time reading through all the documentation.
    $ npm test

    > rpoint-pos@0.0.1 test /home/ian/Projects/RPOINT-POS
    > mocha || true

    /home/ian/Projects/RPOINT-POS/app.js:62
    console.log(serverTest);
                ^

    ReferenceError: serverTest is not defined
    at Server.<anonymous> (/home/ian/Projects/RPOINT-POS/app.js:62:17)
    at Object.onceWrapper (events.js:416:28)
    at Server.emit (events.js:310:20)
    at emitListeningNT (net.js:1347:10)
    at processTicksAndRejections (internal/process/task_queues.js:83:21)

app.js file
    //connect to mongodb
    mongoose
      .connect(
        db,
       {   useNewUrlParser: true }
     )
    .then(() => console.log(dbTest))
    .catch(err => console.log(err));

     //routes
    app.use("/", require("./routes/web"));
    app.use("/api", require("./routes/api"));

   app.set("port",process.env.PORT || 3000);
    app.listen(app.get("port"),function(){
    console.log(serverTest);
    });

   module.exports = {
     serverTest: function() {
       return 'running';
     },
     dbTest: function() {
      return 'connected';
    }
    }

and trying to pass those function to test.js file
    const assert = require('chai').assert;
    const app = require('../app');

    //Results
    serverTestResult = app.serverTest();
    dbTestResult = app.dbTest();

    describe('App', function(){
      describe('serverTest()', function(done){
        it('sayHello should return server', function(){
         assert.equal(serverTestResult, 'running');
    });

    it('serverTest should return type string', function(){
      assert.typeOf(serverTestResult, 'string');
    });
  });

  describe('dbTest()', function(done){
    it('sayHello should return server', function(){
      assert.equal(dbTestResult, 'connected');
    });

    it('dbTest should return type string', function(){
      assert.typeOf(dbTestResult, 'string');
    });
  });

    });


text:
Q: Float right makes my columns a mess I created this html:
There are two input-fields in a col-sm-12:
And in the next column i have a submit button:

     <input id="bis" class="form-control input-sm a" type="text" value="18-12-2013" placeholder="Bis" name="bis">
     </input>

     <input id="von" class="form-control input-sm a" type="text" value="02-12-2013" placeholder="Von" name="von">
     </input>

     <input class="btn btn-info btn-sm" type="submit" value="Filtern" style="float:right" name="commit">
     </input>

And added this extra css to the text-fields:
.a {width:100px; float:right}

Because i tried to have the input fields next to each other and the submit button in the next colum right below it.
My problem now is that the submit button now is besides the two input fields! Although i wanted it below!Why? Thanks
Fiddle: http://jsfiddle.net/52VtD/807/

A: That's because you aren't clear after the floated elements.
You have two solutions :

*

*One add this to your CSS:
 .col-sm-12 {
    clear:both;
 }

Here in this article is all what you need to know about the use of float.

*

*Two use display:inline-block instead of float:
 .a {
   display:inline-block;
 }

The demo http://jsfiddle.net/52VtD/814/

A: Use CSS clear property for this. Refer CCS-CLEAR>> for more info.
Here you can try this:
.col-sm-12 {
    clear:both;
 }


text:
Q: AWS RDS SQL Server Migrate DB from Outside Today, I am using AWS EC2 DB Instance for my database (SQL Server).
I want to change the instance and instead to use RDS instance for my SQL Server.
In order to complete the migration from EC2 to RDS I need to pass the database with all its tables/stored procedures/types/views etc.
I tried to backup the database of the EC2 instance and then restore it in the RDS instance but I get the exception:

Moreover, I tried to generate a script of the EC2 instance DB and then run the script on RDS SQL Server connection but it failed to run many of the scripts because of permission exceptions.
I also found an article from the AWS documentation that shows that it is possible to upload a backup to S3 bucket. But I couldn't manage to understand how to restore the backup from the S3 bucket in the RDS instance.
Please, help me figure out how to do it? I belive it must be possible and easy somehow.
Thanks in advance.


text:
Q: Programmatically create and launch and RDP session (without gui) I'd like to know if there is a way to create and launch a Remote Desktop Session on a Windows Server programmatically.
I'm trying to make an automatic tool to create Local Users and then launch the associate RDP session. I've already made LocalUser creation and adding them to Remote Desktop Users (using net.exe).
But I'm struck with the next step : create and launch user's rdp-session.
I don't know how to handle this problem without having the Remote Desktop Client Gui.
I'm working on a Windows Server 2003 and I'm using VS2008 with .NET 3.5.
Regards.

A: You can use the Remote Desktop ActiveX control to connect, you would need to host it in a Form but the form wouldn't need to be visible. For an example see http://www.codeproject.com/KB/cs/RemoteDesktop_CSharpNET.aspx

A: You can call mstsc.exe and pass parameters on the command line to tell it what to connect to.
mstsc.exe documentation on MSDN

A: First, I've found that an option on the server is needed to enable Terminal Service autologin.

*

*On the Terminal Server, click Start, point to Programs, point to
  Administrative Tools, and then click
  Terminal Server Connection
  Configuration.

*Double-click the rdp-tcp connection, and then click Advanced.
  If you want to modify properties for
  ICA clients, double-click the ica-rdp
  connection instead, and then click
  Properties.

*In the AutoLogon section, click to clear the Prompt for Password check
  box.

*Click OK, click OK, and then click Exit on the Connection menu.

source : support.microsoft.com/kb/260711
After that, I've made something based on this project :
codeproject.com/KB/cs/RemoteDesktop_CSharpNET.aspx
For what I've tested, I think it's not possible to omit an RDP Client connection (MsTscLib or mstsc.exe)
I've got something working but it's certainly bad style. I'm using ActiveX Component Events to know the result of the connection. Ie : OnLogonError and OnLoginComplete.
here my source :
http://codepaste.net/uiuuxc
I'm awaiting your comments.


text:
Q: gzip compression showing off even though enabled I'm unsure as to why gzip it showing as failed on both webpagetest and gtmetrix when in my nginx config I have it enabled.
I'm currently running nginx version: nginx/1.10.1
Here is my current nginx config
# HTTPS
server {
    listen 443 ssl http2 default_server;
    root /home/www/youtstream;
    server_name dev.yout.com
    gzip_disable "msie6";
    access_log  off;
    error_log off;
    gzip_vary on;
    gzip on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_min_length 256;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon;

    ssl on;
    ssl_certificate      /srv/dehydrated/certs/dev.yout.com/fullchain.pem;
    ssl_certificate_key  /srv/dehydrated/certs/dev.yout.com/privkey.pem;
    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
    location /static {
        alias  /home/www/youtstream/static/;
    }
    location ~*  \.(jpg|jpeg|png|gif|ico|css|js|mp4|woff2)$ {
        expires           max;
    }

Here is the results of webpagetest and gtmetrix


text:
Q: How do I install debian linux to ssd from live system with uefi boot I have a usb drive with overclockix (debian-based) that I have booted my system from.  I am trying to figure out a way to install it to the attached SATA SSD drive.  I attempted the following:
I created the following partitions on the SSD with fdisk:
/dev/sda1 /boot ext2 (bootable)
/dev/sda2 / ext4
/dev/sda3 /var ext4
/dev/sda4 /home ext4
/dev/sda5 none swap
partprobe /dev/sda

I ran mkfs. on each partition and mkswap on sda5.
Then I mounted the partitions:
mount /dev/sda2 /mnt
mkdir /mnt/boot /mnt/var /mnt/home
mount /dev/sda1 /mnt/boot
mount /dev/sda3 /mnt/var
mount /dev/sda4 /mnt/home

Then I copied the files from the USB:
rsync -avp --exclude /proc --exclude /boot --exclude /home --exclude /var --exclude /sys --exclude /dev --exclude /run / /mnt
rsync -avp /var /mnt/var
rsync -avp /boot /mnt/boot
rsync -avp /home /mnt/home

Then I bind mounted proc, sys, run and dev:
mkdir /mnt/proc /mnt/run /mnt/sys /mnt/dev
mount --bind /proc /mnt/proc
mount --bind /sys /mnt/sys
mount --bind /dev /mnt/dev
mount --bind /run /mnt/run

Then I chrooted to /mnt:
chroot /mnt /bin/bash

I created a new fstab:
blkid >> /etc/fstab
vi /etc/fstab
UUID=<UUID> <mpoint> <type> defaults(or sw)  0 2

Then I ran grub-install /boot /dev/sda which returned no errors.
I exited the chroot, unmounted the partitions, removed the USB and rebooted.
I thought that this would create a nearly identical file system as what is on the USB device which would boot with grub. However, I wasn't able to boot from the drive. I am thinking it has something to do with UEFI, but I can't quite figure out what else needs to be done.
Any help is appreciated, thanks.

A: Format the  boot partition sda2 to Fat32 , it will be used as ESP partition
Mount partitions and replace mount /dev/sda1 /mnt/boot by:
mount /dev/sda1 /mnt/boot/efi

Run:
for i in /sys /proc /dev; do mount --bind $i /mnt$i; done

Get the internet working then change root:
cp /etc/resolv.conf /mnt/etc/
chroot /mnt /bin/bash

Install grub:
apt-get install --reinstall grub-efi
update-grub
exit
for i in /sys /proc /dev; do umount /mnt$i; done

Unmount partions and reboot

A:
with UEFI boot

Let me expand on this a bit so that the rest of the answer makes sense:
On old style IBM compatible PCs the firmware is loaded on start. This is usually BIOS firmware and looks for a MBR record on haarddisk, reads that, excutes bootsector, first stage bootloader etc etc. This is the same when booting windows or Linux. You just get different bootloaders. Or even multiple bootloaders, e.g. when you chain windows from grub.
BIOS is a basic system from about 1985 and is somewhat lacking on modern PCs. We just used it for backward compatability.
It since got replaced by EFI. EFI is well defined and much more capable. It does not use a bootsector. Instead it look at a GPT partitioned disk, locate the EFI system partition and reads files from that. Usually that includes something like boot.efi.*1
An EFI System partition must be present to boot from. It must be in a format which your EFI implementation understands. There is one filesystem which is required for EFI to understand, and that one just happens to be 100% compatible with FAT32.*2
Your setup shows you creating several partitions, none of which are the EFI system partition. I think you are following an old guide for BIOS, coreboot or CSM booting.
So much for background and why it did not work, that leaves the main question unanswered though.

How do I install debian linux to ssd from live system with UEFI boot

From wiki.debian.org/UEFI:
"Debian installs grub-efi for its EFI bootloader".
This is an .efi file and it should be installed on your EFI system partition. Which you do not have. Start again, partition the disk with an extra partition with the right type (identifier C12A7328-F81F-11D2-BA4B-00A0C93EC93B). format it FAT32. Read up on grub-efi and make sure that your kernal if UEFI enabled. Then at the right time issue an apt-get install --reinstall grub-efi-amd64 or play around with efibootmgr.

*1: Note: Grub2 is EFI compatible.
*2: One known exception: Apple EFI also groks HFS. As requires it also understands the normal format.


text:
Q: GWT .hgignore / .gitignore entries What are the typical entries in your source control ignore files for a GWT App (developed in eclipse)?

A: In addition to VonC's eclipse/ant/maven suggestions, I'd add the a few more gwt-specific entries:

*

*.gwt - compilation logs

*gwt-unitCache - caching for already compiled files

*www-test - gwt junit compilation files

Personally I'd stay away from trying to blacklist files/folders in any webapp dir, except either on a project-by-project basis, or by making sure that your compilation process builds gwt compiled files to another dir in a build/ or target/ dir - this might make things more annoying to start up, but you won't need to customize .gitignore with any new gwt module.

A: I would recommend:

*

*you leave the eclipse files (.project, .classpath, ...) in your VCS,

*you ignore what is generated by GWT compilation, like in this project
(.gitignore)

:
/build
/classes
*.jar
*.class
*~
*/web-app/gwt
*/web-app/WEB-INF/classes
target

The name of certain generated directories can vary slightly, so you should adapt them for your project.


text:
Q: Multiples instance of Producer/Consumer with Monitor in Java I'm building a webcrawler to download files from websites. I've a producer (the link fetcher) and a consumer (the downloader).
They both can be summarized as followed :
//Fetcher implements Runnable
public void run(){
  while(String link = getLinkFromDatabase != null){
     String htmlContent = HTTPrequest.getHTMLtoString(link);
     ArrayList<String> links = HTTPrequest.getUrlsFromString(htmlContent); //Custom Parser/Extractor
     ArrayList<String> files = HTTPrequest.getFilesFromString(htmlContent);//Custom Parser/Extractor
     String SqlQueryAddLinks = "INSERT IGNORE DUPLICATE INTO [...]"; //Insert query for Links with unique key : sha256 of the url.
     String SqlQUeryAddFiles = "INSERT IGNORE DUPLICATE INTO [...]"; //Insert query for Files with unique key : sha256 of the url.
     Queries.sqlExec(SqlQueryAddLinks);
     int RowAffected = Queries.sqlExec(SqlQueryAddFiles);
     Queries.archiveLink(link);
     Monitor.append(RowAffected);
  }
}

//Downloader implements Runnable
public void run(){
  while(String link = getFileFromeDatabase != null){
     //You don't care of steps here I just download the file
     if(fileDownloaded){
        Queries.archiveFile(link);
        Monitor.take();
     }
  }
}

Now i'm trying to synch both thread to assure that links cannot be too old. To do so I'm using Monitor (as described in Operating Systems : Internals and design principles wrote by William Stallings)
public class Monitor{
   int N = 10;
   int count;
   Condition notfull, notempty;

   public Monitor(){
      count = 0;
   }

   public void append(int nbr) throws InterruptedException{
      if(count >= N){
         notfull.wait();
      }
      count+=nbr;
      notempty.signal();
   }

   public void take() throws InterruptedException{
      if(count == 0){
         notempty.wait();
      }
      count--;
      notfull.signal();
   }

Now the thing is that I want to launch multiples couples of fetcher and downloader sync by a monitor. Do I need to create a new Monitors object and add a Monitor into the class of my Downloader and Fetcher or is there a better way ? The book isn't talking about multiples Producer/Consumer and is using the function parbegin(producer, consumer); in C++ (I presume it's C++).

A: Just by eyeballing, this code doesn't compile for many reasons and has guaranteed runtime failures.
a) you try to call a static method take/append but they are not static.
b) you try to have 2 Condition objects but you have no reentrant lock.
c) you don't even lock/unlock the reentrant lock behind the condition before waiting/notifying
d) you use Condition.wait() instead of the .await().
e) you are using Condition.signal() instead of the .signalAll()


text:
Q: C# - How to create stack Id for caller? I want to make Caller Id for method calling, what is that? CallerID is identify of calling a method like Task.CurrentId but in this case I don't want to create new thread to access ThreadId,
For Example:
    public class OperationMethodContext
{
    public static OperationMethodContext Current { get; set; }

    public int Id { get; set; }
    public string MethodName { get; set; }
    public Guid Guid { get; set; }
}

internal class Program
{
    private static void Main(string[] args)
    {
        OperationMethodContext.Current = new OperationMethodContext() {  Guid = Guid.NewGuid(), MethodName="call 1", Id = 1};
        MethodRun();
        OperationMethodContext.Current = new OperationMethodContext() {  Guid = Guid.NewGuid(), MethodName="call 2", Id = 2};
        MethodRun();
        OperationMethodContext.Current = new OperationMethodContext() {  Guid = Guid.NewGuid(), MethodName="call 3", Id = 3};
        MethodRun();
        OperationMethodContext.Current = new OperationMethodContext() {  Guid = Guid.NewGuid(), MethodName="call 4", Id = 4};
        MethodRun();
        Console.ReadKey();
    }

    private static async void MethodRun()
    {
        Console.WriteLine("call started: " + OperationMethodContext.Current.MethodName);
        await Task.Delay(2000);
        Console.WriteLine("call finished: " + OperationMethodContext.Current.MethodName);
    }
}

I want to get OperationMethodContext.Current per method calling without send OperationMethodContext as parameters or properties, if I had to more call stacks i want to access OperationMethodContext.Current per stack calling.


text:
Q: Transpose operation on pyspark data frame using python I am new to python and pyspark, I have done transpose operation using pandas df.T. I have found that there is no direct operation on the pyspark dataframe (pyspark version = 2.2.0 and python version = 3.6.2)
I am loading a CSV file for the above operation using the following code
from pyspark.sql import SQLContext
sql = SQLContext(spark_context)
path = 'sample.csv'
df = (sql.read.format("com.databricks.spark.csv").option("header","true").option("inferSchema", "true").load(path))

A: What is your data schema?
If it is some sort of sparse matrix, you can load with regular RDD and map + swap your coords.


text:
Q: What brand(s) of hard disk has the lowest failure rates? Wiki for information on which storage manufacturer(s)'s drives have the longest life / lowest failure rate?
Everyone has a favorite, but if you can refer to a (hopefully recent and somewhat impartial) study, that would help avoid subjectivity.
EDIT: Any information is useful, so rather than limit the question to server-grade drives, or a particular size etc I'd just ask that you mention any particulars in the answer.

A: The issue with this question is that there are good drive models for a manufacturer and bad drive models.
For example, there seems to be a high failure rate for the Seagate 1tb & 1.5tb drives, but their 250gb & 320gb drives are solid*.  Yet the Western Digital 1tb, 1.5tb, & 2tb drives seem more stable, but there have been issues with their 500gb drives*.
The answers to this question should address more of the good drive models, not the actual manufacturers themselves.
Thanks!
JFV
**Information for this data was obtained from ratings on websites like NewEgg.com, TigerDirect.com, etc*

A: StorageReview.com stores reliability rates for hundreds of drives.  You can view by manufacturer and see which drives have been reported to be reliable or failure-prone.  The data is mostly user submitted (perhaps even by SF peers) with 52900 entries to date.  At least you get numbers:
StorageReview's Survey
Registration is free, and you must enter at least one drive result but you get to view the entire database.
EDIT: Regarding Google, they used Hitachi Deskstars in one of their Data Centers at one point:
alt text http://www.hyperslug.com/image/photo/GoogleServerLarge.jpg
Courtesy of CNET

A: I hear them Winchester drives are pretty good.

A: Before you can understand the answer, you must first understand the question (ooohh, I durn sound smart!)
Seriously, you have to define a "failure" before you can really ask the question.
Is a failure:

*

*Failing to read the disk and returning bad data?

*Failing to read the disk and returning a read failure code once?

*Failing to read the disk and returning a read failure code X times?

*Total loss of access to your data? (i.e. head crashing, electronics failing, spinup fail)?

Of course, in addition to the Google report that username has linked, NetApp's whitepaper on data corruption is IMO a must read for any storage or systems administrators.

A: There aren't that many disk manufacturers these days, I'm sure we could all name 90% of them right away - I honestly don't think there is a true answer to this question - not across the board and not one that we can all agree on.
Ultimately this comes down to the fact that no one company is generally perceived as being of significantly lower quality than the others. I'm sure there have been single-model/batch issues with all of the main players but overall they're all pretty competitive with each other on speed, capacity, reliably etc.
So the bad news is that I'm not sure there's an answer to your question but the good news is it's this lack of quality tiers means that these days we can all get very fast and reliable disks for comparatively very little - which is nice :)

A: Interestingly, Google published a study that looked at a pretty large population of drives and their failure rates. One section says, and I quote:

"In contrast to age-related results,
  we note that all results shown in the
  rest of the paper are not affected
  significantly by the population mix."

The authors found that drives tended to fail (1) very soon after their first reported SMART scan error and (2) based more on the drive model number and vintage rather than manufacturer.

A: A more serious answer from me is, perhaps you're asking the wrong question :)
Google figured out a long time ago that you must design for failure. For the single user, I would recommend something like a Drobo combined with a good backup regimen. Server-side, it is not that much different, except that rather than a Drobo you probably want to look at RAID solutions. For applications, you can also consider something like cloud-storage, e.g., Amazon S3.

A: I have a nice graph (under NDA, sorry) that shows that Enterprise class SATA drives from Seagate and Hitachi are all slightly below the 1% annual return rate for the first 3 years, in case that helps.
You could also check the Storage Review reliability survey and see what they say of your favorite vendor or drive. However I don't know if this is of any statistical significance.

A: Since Google (in the study mentioned above) is the only one to have performed a field analysis with a sufficiently large population size, (more than one hundred thousand disk drives) it would be interesting to know which drives they now purchase.
Any IT flies on Google's walls out there have some comments?
Unfortunately for the rest of us, they were unable to name names of manufacturers (or specific models) with the results.  Instead (frustratingly) they confirm what we all already know, namely that "Failure rates are known to be highly correlated with drive models, manufacturers and vintages."
I tend to agree with JFV above - there are good drive models for manufacturers and bad drive models for the same manufacturer. Things change over the years too. It is therefore better to focus on models rather than manufacturers or brands.
Pay attention to warranty offered and anecdotal feedback on specific models from the likes of newegg, tigerdirect, amazon.
As the Google study seems to confirm, posted MTBF is often less informative than many people assume.

A: I have used thousands of drives over the years and about half tend to fail within the first year.  This is especially true for servers or desktops that have large amounts of disc activity.  Seagate, maxtor and western digital are the brands I use most of the time but I have learnt that buying large numbers of identical drives at the same time is suicide.
My solution is to spread the risk by purchasing between 2 and 5 at a time - constantly changing the manufacturer, the size and the supplier.  This spreads the failures out over time and it makes it easier to figure out which manufacturer has messed up.
Capacities increase as technologies change and although the manufacturers will do a lot of lab testing, this is not the same as regular drives in regular use.
The fastest way to kill a large hard drive for consumers is having a small amount of physical RAM in the PC.  When windows XP came out 256mb was generous but now 1gb is minimum and to prevent hard drives dying to quickly you need 2gb for heavy users.  When switching to 64 bit operating systems you need 2gb minimum and 4gb to be comfortable but heavy users will need 8gb of RAM.  Running a wordprocessor, an email client and a browser at the same time - and this is not an unusual - will be swapping memory like crazy on a machine with small amounts of ram and the sweet spot over the years keeps going up.  It it not unusual to require 1gb of RAM for the browser alone now.


text:
Q: Websphere MQ 7.1 on z/OS and big messages How to handle messages bigger than 4MB on z/OS? I can't use segmentation, because it is not supported on z/OS.
Some OS have even bigger limits measured even in kB.
What is the common approach in this case?

A: You are not hitting a z/OS limit but rather the default maximum message length on WebSphere MQ. Note that the Infocenter says "On z/OS, specify a value in the range zero through 100 MB (104 857 600 bytes)".
To fix this, change the MAXMSGL on any queues and channels through which the message might pass.  Don't forget to update the Dead Letter Queue's MAXMSGL as well as transmission queues.
Be aware that MAXMSGL is there to save you!  Many people set the value to its highest possible size and then run out of disk space.  If the application hits a soft limit such as MAXMSGL or MAXDEPTH the effect is limited and generally recoverable.  If the disk space is exhausted, the entire QMgr comes to a screeching halt and all connected apps are impacted.
For more on this, please see the Mice and Elephants article on developerWorks.
UDATE:
Update based on comments asking about specifics of HP NonStop and WMQ V5.3.
Please see the WMQ V5.3 manuals available in the WMQ Documentation library.  The second link is the System Administration Guide for WMQ V5.3 on HP NonStop.  Message lengths are discussed on P4:

The default maximum message length is 4 MB, although you can increase
  this to a maximum length of 100 MB (where 1 MB equals 1 048 576
  bytes). In practice, the message length might be limited by:

*

*The maximum message length defined for the receiving queue

*The maximum message length defined for the queue manager

*The maximum message length defined by the queue

*The maximum message length defined by either the sending or receiving application

*The amount of storage available for the message

So there's no arbitrarily small max message length on HP NonStop or associated with V5.3 of WMQ.

A: Maybe message grouping can help you there.
Of course the applications then have to be customized.


text:
Q: Is the Schwarzschild horizon lightlike? It is often said that the event horizon of a Schwarzschild black hole is lightlike. Is this correct and, if so, what exactly does this mean?
Intuitively, this may mean that any two points on the horizon surface are lightlike separated, but I am unable to see this from the metric. The temporal part of the Schwarzschild metric is zero at the horizon. The radial part approaches zero in the limit. However, the angular part remains well defined positive thus apparently making the interval spacelike.
What am I missing? I've searched the web, but couldn't find anything relevant. I would appreciate if someone points me in the right direction.

A:
It is often said that the event horizon of a Schwarzschild black hole is lightlike. Is this correct and, if so, what exactly does this mean?

It means that only lightlike geodesics can stay stationary at the horizon, all other geodesics must fall in (or escape, assuming there are space-like geodesics as well) and the proper time intervall they can spend at the horizon is infinitesimal. If an observer on a timelike path emitts a radially outwards directed photon when he crosses the horizon, it will stay there forever. So the only stationary probes you can have at the horizon are light-like (and inside space-like, which means that only Tachyons, if they existed, could remain stationary inside the horizon). Outside of the horizon the stationary (with respect to the black hole) probes (called Fidos for fiducional observers) are on time-like paths.

A: Lightlike simply means that your interval $ds^2=dx^2+dy^2+dz^2-c^2dt^2$ evaluates to zero.
It does not mean that real black hole would have light encircled forever in eternal loop over its event horizon. In fact, any non-zero energy object cannot do that. Real particles would lose energy because they would have accelerated orbit and gradually fall down. Even virtual particles are split and sucked under event horizon (BH is a heating engine).


text:
Q: Failed to initialise build environment I am trying to build "yocto" with "jethro" (https://wiki.yoctoproject.org/wiki/Releases) version but when I try initialise build environment it gives following error.
Error: 'meta-poky/conf' must be a directory containing local.conf &
bblayers.conf

I found out that meta-poky folder is not available in jethro version.
What am I doing wrong in initialisation?
I tried with later version krogoth and it is working fine with it.

A: meta-yocto was indeed renamed meta-poky in Krogoth. There is code to handle your configuration in the upgrade case (going from jethro to krogoth) but downgrade probably isn't tested: I'm guessing you did a build with a newer release and then jethro.
This could maybe be fixed by just modifying conf/templateconf.cfg & conf/bblayers.conf manually (to refer to "meta-yocto" instead of "meta-poky"). Alternatively you could move your whole conf/ out of the way, re-generate a template configuration with . oe-init-build-env and then redo any local configuration you had.


text:
Q: Using strategy or additional class? I have following code example (code below).
I have interfaces OnlyReverse and OnlySplit which define operations on class Data. I will sometimes have class available only for reversing and sometimes, I will be able to do reversing and splitting.
In the code I have 2 approaches.
1st approach is to use 2 separate classes for these 2 separate use-cases ReverseAndSplitImpl and OnlyReverseImpl. Here I do not like that I need additional class, and that I need to duplicate some of the code between those 2 classes.
2nd approach is to use 1 class for both use-cases SingleClassForReverseAndSplitImpl and then use strategy to inject either NormalSplit or NoSplit. Here I do not like this additional NoSplit class that is basically artificial one.
According to interface segregation principle - do I need to have ReverseAndSplit joining interface, or should I always use both interfaces separately (like SingleClassForReverseAndSplitImpl implements OnlyReverse, OnlySplit and not SingleClassForReverseAndSplitImpl implements ReverseAndSplit)?
Which approach of these is better in a long run (more flexible in the future)?
class Data{
  String a;
}

interface OnlyReverse{
  Data getData();
  OnlyReverse reverse();
}

interface OnlySplit{
  OnlySplit split();
}

interface ReverseAndSplit extends OnlyReverse, OnlySplit{
  @Override
  ReverseAndSplit reverse();
  @Override
  ReverseAndSplit split();
}

//------------------------- USE DISTINCT CLASSES; ONE HAS SPLIT OTHER NO

class ReverseAndSplitImpl implements ReverseAndSplit{
  Data data;

  public ReverseAndSplitImpl(Data data) {
    this.data = data;
  }

  @Override
  public Data getData() {
    return data;
  }

  @Override
  public ReverseAndSplit reverse() {
    //here reverse and return
    return new ReverseAndSplitImpl(data);
  }

  @Override
  public ReverseAndSplit split() {
    //here split and return
    return new ReverseAndSplitImpl(data);
  }
}

class OnlyReverseImpl implements OnlyReverse{
  Data data;

  public OnlyReverseImpl(Data data) {
    this.data = data;
  }

  @Override
  public Data getData() {
    return data;
  }

  @Override
  public OnlyReverse reverse() {
    return new OnlyReverseImpl(data);
  }
}

//------------------------- USE DISTINCT CLASSES; ONE HAS SPLIT OTHER NO

//------------------------- USE STRATEGY TO CHOOSE TO HAVE SPLITTING OR NO
interface SplitStrategy{
  Data split(Data data);
}
class NormalSplit implements SplitStrategy{
  @Override
  public Data split(Data data) {
    return new Data();
  }
}
//NullObject pattern
class NoSplit implements SplitStrategy{
  @Override
  public Data split(Data data) {
    return data;
  }
}

class SingleClassForReverseAndSplitImpl implements ReverseAndSplit{
  Data data;
  SplitStrategy splitStrategy;

  public SingleClassForReverseAndSplitImpl(Data data, SplitStrategy splitStrategy) {
    this.data = data;
    this.splitStrategy = splitStrategy;
  }

  @Override
  public Data getData() {
    return data;
  }

  @Override
  public ReverseAndSplit reverse() {
    //here reverse and return
    return new SingleClassForReverseAndSplitImpl(data, splitStrategy);
  }

  @Override
  public ReverseAndSplit split() {
    //here split and return
    SingleClassForReverseAndSplitImpl s = new SingleClassForReverseAndSplitImpl(data, splitStrategy);
    s.data = splitStrategy.split(data);
    return s;
  }
}
//------------------------- USE STRATEGY TO CHOOSE TO HAVE SPLITTING OR NO

public class Decorator {

  public static void main(String[] args) {

    ReverseAndSplit s11 = new SingleClassForReverseAndSplitImpl(new Data(), new NoSplit());
    s11 = s11.reverse();
    s11 = s11.split();  //has split operation, but NoSplit will do nothing

    OnlyReverse s12 = new OnlyReverseImpl(new Data());
    s12 = s12.reverse();
    //has no split operation present

    //Going from NoSplit to SplitAndReverse
    ReverseAndSplit s21 = new SingleClassForReverseAndSplitImpl(s11.getData(), new NormalSplit());
    s21 = s21.reverse();
    s21 = s21.split();  //has split and now it is using NormalSplit

    ReverseAndSplit s22 = new ReverseAndSplitImpl(s12.getData());
    s22 = s22.reverse();
    s22 = s22.split();

  }
}

A: I guess it's reasonable to use your first approach (two simpler interfaces) but to not call them OnlyReverse and OnlySplit but Reverse and Split. So it's reasonable to combine them and in future you can also just use one of them.
But it's also depending on your domain objects, so it's hard to make a choice for you. But I would not create an interface called NoSplit because you could still implement ReverseAndSplit and NoSplit which would make no sense for you.

A: According to the Interface Segregation Principle, if you have a client who never splits, then you should not present that client with an interface including a split method. The Strategy / Null Object approach is suitable for a single client who sometimes requires splitting and other times does not. The separate interfaces approach is suitable for two different clients who have different requirements.


text:
Q: Create Father Son Relationship table from 3 column data table? I'm trying to create a table like that in SQL (Oracle 19c):

ID
Name
FatherID

1
Category1
null

2
Category1.1
1

3
Category1.1.1
2

4
Category2
null

5
Category2.1
4

My data source actually a collection in Oracle Apex (loaded from a xlsx file) that is structured like that:

seq_id
C001
C002
C003

1
Category1
null
null

2
Category1
Category1.1
null

3
Category1
Category1.1
Category1.1.1

4
Category2
null
null

5
Category2
Category2.1
null

I've tried to make a WITH statement with 5 support tables and then unioning all at the last step but something is flapping at each query execution and i get an inconsistent result at each execution. I've tried to order every result of the temps tables to get the data to stay ordered but it isn't working.
I'm not a SQL master and so I'm here to ask for some help. How can i approach this problem?
This is my code:
EXECUTE IMMEDIATE 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT  = ''YYYY-MM-DD HH24:MI:SS'';

BEGIN
    insert /*+ append */ into conn_category

    WITH
        default_data as (
        SELECT c001, c002, c003
        FROM APEX_collections
        WHERE collection_name = 'DL_CATEGORIE_PORTALE_COLLECTION'

        ),
        cat1_lvl as (
        select ROW_NUMBER() OVER( ORDER BY c001 asc) as ID_PARENT, c001 as c001_new
        from default_data
        group by c001 ),

        cat2_lvl as (
            select distinct null as ID_PARENT,  a.c001 from
            default_data a
            , cat1_lvl b
            where
            a.c001 = b.c001_new
            UNION ALL
            select distinct  b.ID_PARENT,  a.c002 from
            default_data a
            , cat1_lvl b
            where
            a.c001 = b.c001_new),

        cat3_lvl as (
            select rownum as ID_PARENT, a.c001 from
            ( cat2_lvl ) a ),

        result as (
            select
            ID_PARENT as ID_CATEGORY_PARENT,
            c001 as NAME
            from cat2_lvl
            UNION ALL
            select
            b.ID_PARENT as ID_CATEGORY_PARENT,
            a.c003 as NAME
            from
            default_data a,
            cat3_lvl b
            where
            a.c002 = b.c001
            AND a.c003 is not null
        ),
        export as (
        select
        rownum as ID,
        name,
        id_category_parent,
        TO_CHAR(sysdate, 'YYYY-MM-DD HH24:MI:SS') as created_at,
        TO_CHAR(sysdate, 'YYYY-MM-DD HH24:MI:SS') as updated_at,
        NULL as processed_at
        from result )

        select * from export order by id;

END;

A: You can use a hierarchical query:
SELECT seq_id,
       COALESCE(C003, C002, C001) AS name,
       PRIOR seq_id AS father_id
FROM   table_name t
START WITH C002 IS NULL
AND        C003 IS NULL
CONNECT BY
   (LEVEL = 2 AND PRIOR C001 = C001 AND C002 IS NOT NULL AND C003 IS NULL)
OR (LEVEL = 3 AND PRIOR C001 = C001 AND PRIOR C002 = C002 AND C003 IS NOT NULL)

Which, for the sample data:
CREATE TABLE table_name (seq_id, C001, C002, C003) AS
SELECT 1, 'Category1', null,          null FROM DUAL UNION ALL
SELECT 2, 'Category1', 'Category1.1', null FROM DUAL UNION ALL
SELECT 3, 'Category1', 'Category1.1', 'Category1.1.1' FROM DUAL UNION ALL
SELECT 4, 'Category2', null,          null FROM DUAL UNION ALL
SELECT 5, 'Category2', 'Category2.1', null FROM DUAL;

Outputs:

SEQ_ID
NAME
FATHER_ID

1
Category1
null

2
Category1.1
1

3
Category1.1.1
2

4
Category2
null

5
Category2.1
4

fiddle


text:
Q: How to change the background color of a specific day in FullCalendar 5 with js? I'm trying to find the way to change the background color of a day (the full cell, not an event) in FullCalendar.
I'm using the current version, 5. I'm also using js, not jQuery. All of the examples I've found so far use dayRender, which doesn't seem to exist any longer in version 5, and jQuery.

A: The color of a day can be set by implementing the dayCellDidMount event like so:
dayCellDidMount: ({ date, el }) => {
      if (date.getDate() == new Date().getDate())
        el.style.backgroundColor = 'lime'
    }

In this example, current day background color is set to lime.
See a working example below:

document.addEventListener('DOMContentLoaded', function() {
  var calendarEl = document.getElementById('calendar');

  var calendar = new FullCalendar.Calendar(calendarEl, {
    timeZone: 'UTC',
    initialView: 'dayGridMonth',
    events: 'https://fullcalendar.io/api/demo-feeds/events.json',
    editable: true,
    selectable: true,
    dayCellDidMount: ({ date, el }) => {
      if (date.getDate() == new Date().getDate())
        el.style.backgroundColor = 'lime'
    }
  });

  calendar.render();
});
html, body {
  margin: 0;
  padding: 0;
  font-family: Arial, Helvetica Neue, Helvetica, sans-serif;
  font-size: 14px;
}

#calendar {
  max-width: 1100px;
  margin: 40px auto;
}

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar@5.11.0/main.min.css">


text:
Q: How to make an element appear on right or left depending of the position of the element clicked? I'm working on a project where i have a mosaic of images (4 images per row) and when user mouses over an image, it makes appear a sidebar with some content inside.
The thing is if the user hovers image 1 or 2, the side bar is on right, if he hovers image 3 or  4 the side bar is on left.
I'm trying with a click for now as i find it easiest to do.
But at a certain point, a bug appears and the side bar is not on right side.
Here is my code :
The html in the snippet is a copy of the source code but i use php and a foreach loop to build the sidebar and the mosaic of images.
Try the snippet below.
HTML & PHP

        <?php
        $i = 1;
        foreach ($allDatasEquipe AS $equipe):
            ?>
            <div id="membre_<?php echo $equipe['alias']; ?>" class="contenu_sidebar">

<?php echo nl2br(htmlspecialchars($equipe['nom'], ENT_QUOTES, 'UTF-8')) ?>

<?php echo nl2br(htmlspecialchars($equipe['fonction'], ENT_QUOTES, 'UTF-8')) ?>

<?php echo $equipe['texte']; ?>

            <?php
            $i ++;
        endforeach;
        reset($allDatasEquipe);
        ?>

        <?php
        $i = 1;
        foreach ($allDatasEquipe AS $equipe):
            if ($i == 1 || $i == 2) {
                $class = 'sidebar_left';
            } else {
                $class = 'sidebar_right';
            }
            ?>

                <div id="<?php echo $equipe['alias']; ?>" class="img_mosaique_equipe toggle-sidebar pointer <?php echo $class; ?>">
                    <img src="img/equipe/<?php echo nl2br(htmlspecialchars($equipe['image'], ENT_QUOTES, 'UTF-8')) ?>"  alt="<?php echo nl2br(htmlspecialchars($equipe['nom'], ENT_QUOTES, 'UTF-8')) ?>"/>

            <?php
            $i ++;
            if ($i > 4) {
                $i = 1;
            }
        endforeach;
        reset($allDatasEquipe);
        ?>

JS / jQuery

$sidebar_content = $('#sidebar_content');

$('.images').click(function() {

  var id = $(this).attr('id');
  console.log('id : ' + id);

  var position_sidebar = $('.contenu_sidebar').hasClass('sidebar_left');

  if ($sidebar_content.hasClass('visible')) {
    if ($(this).hasClass('sidebar_left')) {
      $('#sidebar_content').css({
        "text-align": "left",
        "right": "0"
      });
      $sidebar_content.animate({
        "right": "-1000px"
      }, "slow").removeClass('visible');
      console.log('sidebar_left closed');
      position_sidebar_content = 'right';
    } else if ($(this).hasClass('sidebar_right')) {
      $('#sidebar_content').css({
        "text-align": "right",
        "right": "0"
      });
      $('#sidebar_content').css({
        "left": "0"
      });
      $sidebar_content.animate({
        "left": "-1000px"
      }, "slow").removeClass('visible');
      position_sidebar_content = 'left';
      console.log('sidebar_right closed');
    }
  } else {
    if ($(this).hasClass('sidebar_left')) {
      $('#sidebar_content').css({
        "right": "-1000px"
      });
      position_sidebar_content = 'right';
      $sidebar_content.animate({
        "right": "0px"
      }, "slow").addClass('visible');
      console.log('sidebar_left open');
    } else if ($(this).hasClass('sidebar_right')) {
      $('#sidebar_content').css({
        "left": "-1000px"
      });
      position_sidebar_content = 'left';
      $sidebar_content.animate({
        "left": "0px"
      }, "slow").addClass('visible');
      console.log('sidebar_right open');
    }
  }
});
/* side bar content */

#sidebar_content {
  width: 50%;
  position: fixed;
  border-right: 1px solid #4c565c;
  /*    right: -50%;*/
  right: -1000px;
  top: 0;
  height: 100%;
  overflow: auto;
  background: black;
  z-index: 1000;
  background-color: #999;
  text-align: left;
}
.contenu_sidebar {
  display: none;
}
.sidebar_content_wrapper {
  position: relative;
  height: 100%;
  overflow: auto;
  padding: 115px 50px 50px 50px;
}
.images {
  width: 30px;
  height: 30px;
  background-color: red;
  margin-bottom: 5px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />

bt close

text

text

text

text

text

text

text

text

A: I didn't try your code but I think the example below shows a way of doing what you need.

Lorem ipsum ad his scripta blandit partiendo

Lorem ipsum ad his scripta blandit partiendo

Lorem ipsum ad his scripta blandit partiendo

Lorem ipsum ad his scripta blandit partiendo

The idea is to set the displaying element position to absolute and calculate the new coordinates on each hover event and set them using jquery.


text:
Q: SQL Query COUNT(Distinct I'm using SQL and am having trouble finding the correct syntax to run a specific query. I'm trying to look into a large amount of data which is why I need to make sure I get this right.
My table looks like the below.
Table1
Column 1 . Column 2
1234     . A
1245     . B
1234     . A
1256     . C
1234     . A

I want to be able to write a simple query that only gives me those in Column 1 that appear more than two times but still have their same values rather than replacing it with a different number (actual amounts will vary but this is the easiest).
I was thinking of using a Count(Distinct but I haven't been able to get it working. Any ideas?

A: I'm not sure what "still have their same values rather than replacing it with a different number" means, but perhaps this SQL is what you need:
select *
from Table1
where Column1 in (
  select Column1
  from Table1
  group by Column1
  having count(*) > 2
  );

Here it is working in a fiddle: http://sqlfiddle.com/#!6/4b443/1

A: this will work for sure
select column1, column2 from table where column1 in ( select column1
                    from table1
                    group by column1
                    having count(column1) >=2 )

A: If I understand correctly:
select column1
from table t
group by column 1
having count(*) > 2 and
       min(column2) = max(column2);

This gets values from column1 that appear more than two times, but where all the rows have the same value for column2.


text:
Q: Terraform split all object in a list while using count.index I have a terraform code like below.

locals {
 org_sub_accounts = [
   "111111111111",
   "222222222222,
   "333333333333",
 ]

 role_arns = [
   "arn:aws:iam::111111111111:role/DataConnector1",
   "arn:aws:iam::222222222222:role/DataConnector2",
   "arn:aws:iam::333333333333:role/DataConnector3",
 ]
}

resource "aws_cloudformation_stack_set_instance" "stack" {
  count               = length(local.org_sub_accounts)
  account_id          = local.org_sub_accounts[count.index]
  region              = "ap-east-1"
  parameter_overrides = {
RoleName = local.role_arns[count.index]
  }
  stack_set_name      = aws_cloudformation_stack_set.stackset.name
}

My problem is my RoleName should be DataConnector potion (after /) but not the entire ARN in the aws_cloudformation_stack_set_instance. How can I pass the RoleName DataConnector* within each index?
Note, here I defined the variables in the locals to show my use case. But actually those comes from other resource outputs.

A: This can be achieved by using the split built-in function:
locals {
  role_names = [for arn in local.role_arns : split("/", arn)[1]]
}

With this part split("/", arn)[1] you are splitting the IAM role ARN into two parts (before and after the /) and with the index [1] you are effectively getting the second part of that list. Then, you would have to change the code to reflect that with:
resource "aws_cloudformation_stack_set_instance" "stack" {
  count               = length(local.org_sub_accounts)
  account_id          = local.org_sub_accounts[count.index]
  region              = "ap-east-1"
  parameter_overrides = {
    RoleName  = local.role_names[count.index]
  }
  stack_set_name      = aws_cloudformation_stack_set.stackset.name
    }

[1] https://developer.hashicorp.com/terraform/language/functions/split


text:
Q: Running JUnit test multiple times gives different results I have a test case for my app which fills in the TextViews in an Activity and then simulates clicking the Save button which commits the data to a database. I repeat this several times with different data, call Instrumentation.waitForIdleSync(), and then check that the data inserted is in fact in the database. I recently ran this test three times in a row without changing or recompiling my code. The result each time was different: one test run passed and the other two test runs reported different data items missing from the database. What could cause this kind of behavior? Is it possibly due to some race condition between competing threads? How do I debug this when the outcome differs each time I run it?

A: Looks like a race condition.
remember in the world of threading there is no way to ensure runtime order.
I'm not an android dev so I'm only speculating but UI is only on one event thread generally so when you call the method from another thread (your test) you're probably breaking that as you're outside of the event thread.
You could try using a semaphore or more likely a lock on the resource.
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/Lock.html
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Semaphore.html

A: I (finally!) found a solution to this problem. I now call finish() on the tested Activity to make sure that all of its connections to the database are closed. This seems to ensure consistency in the data when I run the assertions.

A: I would suggest making a probe for the database data rather than a straight assert on it. By this I mean make a piece of code that will keep checking the database for up to a certain amount of time for a condition rather than waiting for x seconds (or idle time) then check, I am not on a proper computer so the following is only pseudo code
public static void assertDatabaseHasData(String message, String dataExpected, long maxTimeToWaitFor){
    long timeToWaitUntil = System.getCurrentTimeMillis() + maxTimeToWaitFor;
    boolean expectationMatched = false;
    do {
        if(databaseCheck() == dataExpected){
            expecttionMatched == true;
        }
    }while(!expectationMatched  && System.getCurrentTimeMillis() < timeToWaituntil);
    assertTrue(message, expectationMatched);
}

When i get to a computer i will try to relook into the above and make it better (I would actually of used hamcrest rather than asserts but that is personal preference)


text:
Q: Failed to use AudioContext to make sound in JavaScript I want to make four game buttons to make sound using AudioContext API in JavaScript. I set the onmouseclick listener to trigger startTone() method and onmouseup to trigger stopTone() method. However as I did like the tutorial, it doesn't make sound. Here's my code:
HTML button part:
<div id="gameButtonArea">
      <button id="button1" onclick="guess(1)" onmousedown="startTone(1)" onmouseup="stopTone()"></button>
      <button id="button2" onclick="guess(2)" onmousedown="startTone(2)" onmouseup="stopTone()"></button>
      <button id="button3" onclick="guess(3)" onmousedown="startTone(3)" onmouseup="stopTone()"></button>
      <button id="button4" onclick="guess(4)" onmousedown="startTone(4)" onmouseup="stopTone()"></button>
</div>

Javascript Initialization of Sound Synthesizer:
var context = new AudioContext()
var o = context.createOscillator()
var g = context.createGain()
g.connect(context.destination)
g.gain.setValueAtTime(0,context.currentTime)
o.connect(g)
o.start(0)

JavaScript Definition of Methods:
const freqMap = {
  1: 261.6,
  2: 329.6,
  3: 392,
  4: 466.2
}

function playTone(btn,len){
  o.frequency.value = freqMap[btn]
  g.gain.setTargetAtTime(volume,context.currentTime + 0.05,0.025)
  tonePlaying = true
  setTimeout(function(){
    stopTone()
  },len)
}

function startTone(btn){
  if(!tonePlaying){
    o.frequency.value = freqMap[btn]
    g.gain.setTargetAtTime(volume,context.currentTime + 0.05,0.025)
    tonePlaying = true
  }
}

function stopTone(){
    g.gain.setTargetAtTime(0,context.currentTime + 0.05,0.025)
    tonePlaying = false
}

A: I solved the problem by putting the initialization of Sound Synthesizer at the end of the script file. I found an error in console:

If initialized at the beginning like me before, it will go wrong.


text:
Q: when calculating optical flow, why frame has no value? so I'm trying to implement this code for optical flow
but when I try to call cv2.imshow('frame',img) I get an error because img, frame, and mask are all "None".
can anybody help me understand where the problem is?
here's my code:
import cv2
import numpy as np

feature_params = dict( maxCorners = 100,
                   qualityLevel = 0.3,
                   minDistance = 7,
                   blockSize = 7 )

lk_params = dict( winSize  = (15,15),
              maxLevel = 2,
              criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))

color = np.random.randint(0,255,(100,3))

cap = cv2.VideoCapture(0)
while( cap.isOpened() ) :
    ret,old_frame = cap.read()
    old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)
    p0 = cv2.goodFeaturesToTrack(old_gray, mask = None, **feature_params)

    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

    mask = np.zeros_like(old_frame)
    while (1):
        ret,frame = cap.read()
        frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params)

        good_new = p1[st==1]
        good_old = p0[st==1]

        for i,(new,old) in enumerate(zip(good_new,good_old)):
            a,b = new.ravel()
            c,d = old.ravel()
            mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)
            frame = cv2.circle(frame,(a,b),5,color[i].tolist(),-1)
        img = cv2.add(frame,mask)

        cv2.imshow('frame',img)

        k = cv2.waitKey(30) & 0xff

        old_gray = frame_gray.copy()
        p0 = good_new.reshape(-1,1,2)

    cv2.destroyAllWindows()
    cap.release()

A: You have
mask = cv2.line(...)
frame = cv2.circle(...)

But cv2.line and cv2.circle return None.


text:
Q: Getting "Target Repository Cannot be Empty" For Jenkins Artifactory Plugin on Slave We are currently utilizing the Jenkins Artifactory Plugin to push our artifacts to Artifactory, and everything is working well on the master Jenkins Node.
One thing we do in ALL of our builds is: we specify the target repository IN THE BUILD SCRIPT based on the version of the build (i.e. if the project version contains SNAPSHOT, put the builds somewhere else). This has worked without issues, even without explicitly setting the target repo as in the picture below:
On the master node, leaving "Target Repository" empty is no problem, and our artifacts go to the right places. But when running the exact same build on a JNLP slave node, we get the "Target Repository Cannot be Empty" exception. When we EXPLICITLY set the target repo, the job works fine on the slave node, but obviously, this defeats the purpose of dynamically setting the target repo in the build script.
Is there any reason that we'd be getting these errors when running jobs on our slave node, but not master? They're all running the same version of java, gradle, etc. So I'm not sure what the problem would be.


text:
Q: CSS element getting dimension of itself base on content I know that this is something we would use JavaScript for, but I was wondering if it's possible or planned in next releases of CSS maybe.
I'm working on a little platform and there's a lot of relative/absolute positions. Content is dynamic so it's not a best solution to specify the static width and elements must be centered somehow. I made it possible with almost no display-errors using CSS only, but it would be great if there is something like this in css.
Today's code (SASS):
element
    position: absolute
    top: 100px
    right: 50%
    margin-right: -50px (static width in %/px/em/rem/...)

Something I was thinking about:
element
    position: absolute
    top: 100px
    right: calc(50% - this.width / 2)

So, to not make this question too broad. Do you know some way to implement this kind of behavior in today's CSS? And if not, do you know if there are some plans to implement it in feature releases?

A: No, it is not possible today, to reference a property of it self.
Will it come? .. Hope so
In your particular sample, centering an absolute positioned div that has dynamic content, you can use transform: translate
Side note: CSS has a lot of properties, where, when combined, one can still achieve similar effect, as with below sample

div {
  position: absolute;
  top: 100px;
  border: 1px solid;
  right: 50%;
  transform: translateX(50%);
}

Centered with dynamic content