text:
Q: animating object with glfw I'm trying to animate a circle across the window which has the default coordinates -1.0 < x < 1.0 and -1.0 < y < 1.0.  I generate a random position for the circle and a random angle at which it moves across the window.
GLint modelLoc = glGetUniformLocation(program, "model");
GLfloat timer = glfwGetTime();
timer /= 10;

glm::mat4 model;
glm::vec3 position = circle.get_position();
GLfloat angle = glm::radians(circle.get_angle());

position.x += timer*cos(angle);
position.y += timer*sin(angle);

model = glm::translate(model, position);
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
glDrawArrays(GL_LINE_LOOP, 0, NUM_CIRCLE_VERTICES);

Now the object animates from its initial position to off the screen.  I would like it to appear on the other side of the window when it reaches the edge (i.e. turn x into -x).  I was thinking that the sine function would be useful here but I'm not quite sure how to implement it.

A: much simpler than using trig:
if(position.x < -1)
    position.x+=2;
if(position.y < -1)
    position.y+=2;
if(position.x > 1)
    position.x-=2;
if(position.y > 1)
    position.y-=2;

A: In order to get a smoother animation, you must not use an absolute value of timer, but a difference between the last value and the current, called delta.
So, I suggest you to change your code to accomplish this:
static GLfloast last = 0;
GLfloat delta;
GLfloat timer = glfwGetTime();
delta = timer - last;
last = timer;

...
position.x += delta*cos(angle);
position.y += delta*sin(angle);

// using ratchet freak's solution
if(position.x < -1)
    position.x+=2;
if(position.y < -1)
    position.y+=2;
if(position.x > 1)
    position.x-=2;
if(position.y > 1)
    position.y-=2;


text:
Q: Could you *PLEASE* ban this creep? This guy here keeps coming back every couple of days and keep SPAMMING Stackoverflow:
https://stackoverflow.com/questions/5056691/spam-removed
Please just BAN this guy to the moon and free us from having to deal with this creep over and over again - thanks!
I'm talking about this guy here:   https://stackoverflow.com/users/625176/amit-singh

A: What kind of spam?
If it is the same URL let us know and we can add that URL to our blacklist.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot view sauce labs test results I have two questions here. One, I am not able to run my appium tests against the sauce labs driver url specified in my account settings https://xxxxx:xxxxxxx@ondemand.eu-central-1.saucelabs.com:443/wd/hub. I do not get any error too..
But, i am able to run my tests against http://appium.testobject.com/wd/hub url. But i am not sure where to see my test results. If i try https://app.testobject.com, I am not able to login even though i give the correct credentials and am already logged in sauce labs. Please help.

A: I noticed a few things that could be doing wrong here. First, you are trying to run the tests on the European datacenter and port 443, which is an https connection. See which endpoint you should connect to. Some possible solutions:

*

*Make sure you are using the endpoint for US West (if you are in the US and that is the data center you signed up for)

*All your capabilities are up to date

*You used your sauce username and access key when connecting to the driver.

It's hard to know what is wrong without capabilities and knowing if you want to connect to a virtual device or a real device, testing an app or browser. Here is an example configuration for an app test on RDC:
@BeforeMethod
public void setup(Method method) throws MalformedURLException {

    System.out.println("Sauce iOS Native - BeforeMethod hook");
    String username = System.getenv("SAUCE_USERNAME");
    String accesskey = System.getenv("SAUCE_ACCESS_KEY");
    String sauceUrl;
    if (region.equalsIgnoreCase("eu")) {
        sauceUrl = "@ondemand.eu-central-1.saucelabs.com:443";
    } else {
        sauceUrl = "@ondemand.us-west-1.saucelabs.com:443";
    }

    String SAUCE_REMOTE_URL = "https://" + username + ":" + accesskey + sauceUrl +"/wd/hub";
    String appName = "iOS.RealDevice.SauceLabs.Mobile.Sample.app.2.7.1.ipa";
    String methodName = method.getName();
    URL url = new URL(SAUCE_REMOTE_URL);

    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability("deviceName", "iPhone 8.*");
    capabilities.setCapability("platformName", "iOS");
    capabilities.setCapability("automationName", "XCuiTest");
    capabilities.setCapability("app", "storage:filename="+appName);
    try {
        iosDriver.set(new IOSDriver(url, capabilities));
    } catch (Exception e) {
        System.out.println("*** Problem to create the iOS driver " + e.getMessage());
        throw new RuntimeException(e);
    }
}

A: I found out how to view my test results while using http://appium.testobject.com/wd/hub url. Navigate to saucelabs as usual. Then select "legacy rdc" under Sauce Apps in the displayed page. You can view the results in the displayed window.


text:
Q: I would like to borrow revtex's amazing footnote and bibtex macros Anybody know how revtex accomplishes its amazing citation handling.  For instance, if I have a list of references in natbib using any bibstyle it looks like this [1,2,3,4,5] or [2,4,5,3,1] depending on the order of the \cite{key2,key4,key5,key3,key1}.  However in revtex it takes that list, no matter the order and makes it [1-5] even for the \cite command I quote above (assuming they're already referenced).
I am trying to write a thesis which is not compatible with revtex, but I don't want to have to hunt down all my \cites and put them in order manually.  Additoinally there is no way to "shorten" the list on first citation by simply doing \cite{ref1}--\cite{ref5} as it would read [1]-[2] if 2,3,4 haven't already been cited.
There must be a way to get the actually superscript reference numbers in order by just "borrowing" one of the revtex packages?  Anyone know which one does it? An example from my thesis to illustrate:
Typically this material has been a high-κ dielectric [50,42,51,86,65,63,64].
which I would like to read:
Typically this material has been a high-κ dielectric [42,50,51,63-65,86].
Suggestions???

A: Revtex loads Patrick Daly's very versatile natbib package for this functionality. You can get the effect you are after with something like
\usepackage[numbers,sort&compress,mcite]{natbib}

A: The cite package provides this functionality - the ability to compress citation lists.

A: You could also look at the amsrefs package, which also allows to compress cites.  And the biblatex package is yet another (powerful) solution to many problems with bibliographies.


text:
Q: Mysql and a trigger updating a table in another database I have 4 databases in one server, and each one is for a different city, and the third one have all the data from the other databases (for control purposes). One database is called tijuana and the one wich have all the data is called sistemadeseguimiento. So, i made a trigger on when you insert a row in a table called amc and it works, it create the same row on the other database. The problem it's with the update, i want to update the same table in the other database and i created this trigger:
CREATE TRIGGER updateAMC AFTER UPDATE ON `tijuana`.amc
FOR EACH ROW
BEGIN
UPDATE `sistemadeseguimiento`.amc
SET  Matricula = new.Matricula, Nombre = new.Nombre, Paterno = new.Paterno, Materno =new.Materno,
Carrera = new.Carrera, Facultad = new.Facultad, Campus = new.Campus,Promedio = new.Promedio,
Destino = new.Destino,Email = new.Email,Area = new.Area,Anfitrion = new.Anfitrion,Cuenta = new.Cuenta
where id = new.id;
END

This trigger it's accepted by the database (MySql) and have no syntax errors, but it's not updating the other database. I tried changing
where Id = new.Id;

to
where Id = old.Id;

with no success. I'm thinking that i will have to do the change on the other database with php, but i think it's cleanner with triggers. Any help will be really apretiated. Thanks in advance.


text:
Q: What happens when an FPGA is powered on and left unconfigured? I am trying to get a general understanding on what happens if you leave an FPGA unprogrammed for a long duration of time.
Suppose you have an FPGA and you leave it unprogrammed for a long period of time (several minutes to hours after power-on), i.e. no bitstream on it, is this bad for the device? Is it recommended to have some bitstream on a powered-on FPGA at all times? What is the general opinion regarding this?
Are the results different on different devices or manufacturers (Xilinx vs. Altera vs. others)?

Additional Info:
I have a custom SoC board which uses a Xilinx Virtex-6 FPGA. I also have a Xilinx ML605 which I use for reference purposes.
Custom board: I power-on the board. I notice that I get a short duration of time to program it using XMD (Xilinx Microprocessor Debugger). If I lose the 20-30 sec window, I have to switch off and switch on the board before trying again. This does not happen with an ML605.
When I try to program the custom board over XMD, I get something like:
Error: Device Reset by JPROGRAM command, failed. INIT_COMPLETE did not go high.

Let me know what you think.

A: This is an interesting question. From personal experience, I have left FPGAs powered up for hours in an unprogrammed state while performing checks on the rest of the circuitry when a new board comes in from the assembly house. I have not noticed any detrimental effects from doing so. But I've honestly never thought about it.
I looked around to try and find a recommendation from an FPGA manufacturer but could not find one. The only statement I found regarding this state is from a Lattice whitepaper and regards the design of the FPGA itself and not how it should be used:

Pre-Programmed Static Quiescent Device Power Consumption is the amount of power
  consumed by the FPGA prior to the device being programmed.  For quiescent device
  power consumption the FPGA is in a non-programmed state, yet has been powered.  It
  is important that the device not consume significant power during this time, as
  conceptually the FPGA device could draw excessive power and potentially shut down
  power supplies, preventing the board from successfully initializing itself and the system.
  The FPGA supplier therefore has to carefully design transistors that have a low static 3  Designing for Low Power
  A Lattice Semiconductor White Paper
  power footprint, without compromising in areas where higher performance is required
  (e.g. I/O and SERDES)

Xilinx likewise mentions what the quiescent current is so that you can design your power supply accordingly. But does not mention what the effect on the device is of leaving it in such a state:

Static or
  quiescent power is mainly dominated by
  transistor leakage current. When this current
  is listed in data sheets, it is listed as ICCINTQ
  and is the current drawn through the
  VCCINT supply powering the FPGA core.

I would be very interested to hear if anyone has experienced damage to a device from leaving it in a quiescent state. But I think as long as the power supply is properly matched to the device, there should be no problem.

A: I am referencing the Spartan 3 datasheet, since that's the FPGA I'm most familiar with.
If you look at chapter 2 (Functional Description), the section "Configuration" has a couple flow diagrams.  Figure 27 (page 50) shows the flow diagram for loading from Flash.  Figure 28 shows the JTAG flow diagram.
Here's a brief summary.
1) Wait for Vccint, Vccaux, and Vcco to reach required levels.
2) Clear Configuration latches
3) Wait for INIT_B to go high.  INIT_B is an open-drain output that an external master can hold low in order to delay configuration.
4) Sample Mode pins.  This determines whether you're going to load via JTAG or Flash, and if Flash whether the FPGA or the Flash is the Master.
5) Load Configuration data frames.
6) Verify that the CRC for the data frames is correct.  If it is NOT correct, the FPGA will drive INIT_B low to indicate a CRC error and it will abort startup.
Step 5 is probably where your real question is - what happens if there is nothing to load from?  Well, you shouldn't get to Step 5 if you're doing things right.  The Flash chip will hold INIT_B low until it's ready to serve data to the FPGA.  If you're using JTAG, then I'm not sure whether your JTAG programmer would hold INIT_B low, but when it went to program the FPGA it would almost certainly assert PROG_B (by driving it low), which causes the FPGA to go back to step 2.
If I were you, I'd scope the INIT_B signal during power-on to see what's happening.  If it starts low, goes high, and then goes low again, the FPGA aborted the startup sequence and you will probably need to assert PROG_B in order to reset the FPGA.

A: The default configuration is designed to be as passive as possible in order to make the device universally usable.
For the Altera Cyclone series (which I have the most experience with) this means

*

*the I/O pins are weakly pulled up to VCCIO (to keep ICs with active-low chip enable lines off the bus),

*the CONF_DONE output is pulled low (you can connect this to the reset pin of other ICs to keep them in reset until a configuration has been loaded as well as restore them to known state when reconfiguring), and

*the clock inputs are not forwarded to the clock networks.

Other FPGA types should be similarly quiescent, and provide non-inverted and inverted outputs indicating configuration status to the rest of the board.
Leaving the device in that state is harmless, as the core is fairly isolated from the outside world, and only the pull-ups may have a small current across them.


text:
Q: ejabberd server broadcast message In short, I want ejabberd server to send some messages to a group of user clients.
the group of users may change. For example, the server send message to group 1, and then send different message to group 2.
In other words, how to make ejabberd server send messages to client?
I know how to send message from client to client.


text:
Q: Could not resolve placeholder 'login.serviceProviderKey' when deploying uaa to tomcat I have created a uaa war by following these steps:
$ git clone git://github.com/cloudfoundry/uaa.git
$ cd uaa
$ ./gradlew :cloudfoundry-identity-uaa:war

When i deploy the war to tomcat i am getting the following exception
[2017-04-19 15:24:20.797] cloudfoundry-identity-server/uaa - ???? [localhost-startStop-1] .... ERROR --- DispatcherServlet: Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'identityZoneConfigurationBootstrap' defined in ServletContext resource [/WEB-INF/spring-servlet.xml]: Could not resolve placeholder 'login.serviceProviderKey' in string value "${login.serviceProviderKey}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'login.serviceProviderKey' in string value "${login.serviceProviderKey}"

I am trying to deploy this on tomcat version 9 running locally and plan to get an AWS instance running with tomcat and deploy uaa on it.
Are there any steps i'm missing when deploying to tomcat? Can we deploy a uaa war to tomcat this way or do i have to deploy it to cloudfoundry?

A: A default configuration is embedded in the war file, you can ask to load it adding to the JVM options :
-DLOGIN_CONFIG_URL=classpath:required_configuration.yml


text:
Q: Where are math.py and sys.py? I found all the other modules in Python33/Lib, but I can't find these. I'm sure there are others "missing" too, but these are the only ones I've noticed. They work just fine when I import them, I just can't find them. I checked sys.path and they weren't anywhere in there. Are they built-in or something?

A: The math and sys modules are builtins -- for purposes of speed, they're written in C and are directly incorporated into the Python interpreter.
To get a full list of all builtins, you can run:
>>> import sys
>>> sys.builtin_module_names

On my machine, that results in the following list:
__builtin__
__main__
_ast
_bisect
_codecs
_codecs_cn
_codecs_hk
_codecs_iso2022
_codecs_jp
_codecs_kr
_codecs_tw
_collections
_csv
_functools
_heapq
_hotshot
_io
_json
_locale
_lsprof
_md5
_multibytecodec
_random
_sha
_sha256
_sha512
_sre
_struct
_subprocess
_symtable
_warnings
_weakref
_winreg
array
audioop
binascii
cPickle
cStringIO
cmath
datetime
errno
exceptions
future_builtins
gc
imageop
imp
itertools
marshal
math
mmap
msvcrt
nt
operator
parser
signal
strop
sys
thread
time
xxsubtype
zipimport
zlib

A: These modules are not written in Python but in C.
You can find them (at least on linux) in a subfolder of the lib-folder called lib-dynload.
The math module is then in a file math.cpython-33m.so (on windows probably with .dll instead of .so). The cpython-33m part is my python version (3.3).

A: I don't know about math, but sys is a runtime service for the interpretor, and hence always available. Check out this.
You'll also find the list of built-ins from this page.
Also check out this topic, and you could try following links.

A: The modules like math, time, gc are not written in python and as rightly said in above answers that they are somewhere (written or moduled) within python interpreter. If you import sys and then use sys.builtin_module_names (it gives tuple of module names built into this interpreter). math is one such module in this list. So, we can see that math comes from here and is not separately written in library or any other folder as a python code.


text: Q: Make macOS Mail.app to attach full certificate chain to mail When I'm sending S/MIME mails from Microsoft Outlook, it attaches the full certificate chain to the out-going mail so that recipients can verify the signing key (similar to how TLS works). However, when I'm sending S/MIME from Mail.app, no certificate is attached. The behavior is similar to this discussion thread, but the thread is about iOS, while I care more about macOS.


text:
Q: PHP: if condition then redirect1 else redirect2 I'm trying to make a really simple check here. I want to select from my db a record which represents a username and a password. Now the problem is where the if starts. Whether I'm putting in the form credentials that exist in the database or not I still don't get redirected. Besides using mysqli_num_fields($result), I also tried using mysqli_num_rows($result) and it still doesn't work. This is starting to drive me nuts.
Also I tried a var_dump of $result and I got this:
object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=> int(1) ["lengths"]=> NULL ["num_rows"]=> int(0) ["type"]=> int(0) }

Which I'm not sure how to interpret.
<?php
$con=mysqli_connect("localhost","root","XXXXX","test");
$pass = $_POST['pass'];
$uid = $_POST['uid'];
$result = mysqli_query($con, "SELECT uid FROM test.login WHERE uid = '$uid' AND pass = '$pass'");
if(mysqli_num_fields($result) == 0) { header('Location: index.html')} else { header('form.html')}

mysqli_close($con);
?>

Thanks in advance. This is probably a rather stupid question and I apologize for that, but understand I'm rather new in all LAMP.

A: You should send the right header. A bit of formatting reveals the difference between if- and else-branch:
if(mysqli_num_fields($result) == 0) {
    header('Location: index.html')
} else {
    header('form.html')
}

You should use
if(mysqli_num_fields($result) == 0) {
    header('Location: index.html');
} else {
    header('Location: form.html');
}

instead.
As @u_mulder remarked, PHP-Docu mentions no such function/method as mysqli_num_fields().
Your code is prone to SQL-Injection, you should properly escape the user input with mysqli_real_escape_string(). Even better: use prepared statements.
A successful login should depend of just one matching row in your result.
A sidenote: it's a very bad idea to store cleartext passwords.


text:
Q: Aptana "Building Workspace" extremely slow I'm running a pretty big web application (around 1.5gb) on my local server and I just added the project into Aptana. It automatically started building the work space after being added and started slowing down drastically whenever it encounters a Javascript file.
What exactly does building the workspace even do? Is there a way to shut it off if it's not much use? It's been stuck at 24% scanning different .js files for over 15 minutes now.

A: I have the same problem here. If I want to save my files and the 'Build Project' Operation is active, Aptana 3 stucks and I need to wait until the 'Build Project' Operation is done.
The 'Build Project' Operation means that the dependencies would be updated and the autocomplete function (over more then one file) can work with the newest changes.
For example: if u add a new html tag with a id="test", the autocomplete feature would show you this id in any corresponding css file if the wokspace was rebuild.
To turn of this function, visit the preferences (Aptana Studio 3, build: 3.3.1.201212171919): General -> Workspace -> 'Build Atomatically' Checkbox
Update:
To turn of this function, visit the preferences (Aptana Studio 3, build: 3.4.1.201306062137): Project > 'Build Automatically' Checkbox
I hope they will increase the performance for this feature!
Have fun :)


text:
Q: Передача php данных на JS Есть соц.сеть, в ней  надо будет отображать, через JS, свое имя, фамилию, аватар и т.п. Данные о себе получаю при открытии страницы. Вопрос: можно ли как-то передать эти данные взяты в PHP, в JS скрипт, без AJAX и DOM, как делают это другие соц.сети?

A: Как вариант, можно через cookie. Для удобства используйте плагин jquery.cookie. Простейший пример:
PHP
if(!isset($_COOKIE['name'])){
    setcookie('name', 'Zow');
}

JS
var cookieParams = $.cookie('name');
if(cookieParams){
    console.log(cookieParams); // Zow
}

A: PHP
$data = array('name' => 'Вася', 'secondname' => 'Пупкин');

JS
<script type="text/javascript">

var data = <?php json_encode($data) ?>;
for(key in data) {
    console.log(key, data[key]);
}

</script>


text:
Q: How do tell whether is a service/daemon is managed by System V Init scripts or upstart? I understand that Ubuntu derivatives support System V, which some consider the old method of starting services for a specifc runlevel and upstart however how do I tell whether a service or daemon is managed by scripts started by init or upstart. Do the commands service --status-all and initctl list convey these or is there a single command that would tell me so?

A: When you run ps, one of the fields is ppid.  You can use that to track it to its parent (the pid will match the process's ppid). Just track it back recursively. (You could probably script it with ps and awk)
or if you prefer a graphical way
ps -ely --forest

or just see if it is in /etc/init.d/* or /etc/rc.d/*
grep <something> /etc/*.d/*


text:
Q: Ionizing radiation in thermal radiation According to the black-body radiation equation, the spectrum extends to infinitely high frequency (although its intensity gets small quickly towards high frequency).
(1) How do you roughly estimate the ionizing radiation power in common high power thermal sources like a 2KW heater without fan, then make sure it is safe considering it is used for years instead of 0.1 second/year in the case of DR X-ray scan? (First the portion of power getting radiated instead of convected needs to be estimated, second this seems not to be black-body and will it have a similar radiation curve that extends to infinite frequency?)
(2) In the photoelectric effect, there are things like cut-off frequency; so, why doesn't thermal radiation - which is quantum mechanical in microscopic level - have a cut-off frequency, i.e. it doesn't radiate X-ray and gamma-ray at all?

A: (1) The element in most heaters appears to be a cooler color/temperature than the sun - and only similarly warm.  So, it is safer than the sun.
(2) The photo-electric effect reveals that below a cut-off frequency there is not enough energy to release an electron, so the energy eventually ends up as heat.  Above the cut-off an electron may be freed.  But all frequencies are involved and can do something.

A: If you plug in the values of $T=1000$K, $\nu=10^{15}$Hz into the spectral radiance formula of a blackbody (Plank's law):
$$B_{\nu}(\nu, T)
    =
    \cfrac{2h \nu^3}{c^2}
    \frac{1}{\exp\left(\frac{h \nu}{k_BT}\right) - 1}$$
where $B_{\nu}(\nu, T)$ is the power delivered per unit area per solid angle at a frequency range centred at $\nu$ by a blackbody at temperature $T$ and do the following integral
$$P\left(T,\nu_0\right)=\int_{\nu_0}^{\infty} \cfrac{2h \nu^3}{c^2}
    \frac{d\nu}{\exp\left(\frac{h \nu}{k_BT}\right) - 1}$$
Here since the argument of the exponential is $\sim 48$, we can approximate the integral to
$$P\left(T,\nu_0\right)=\int_{\nu_0}^{\infty} \cfrac{2h \nu^3}{c^2}\exp\left(-\frac{h \nu}{k_BT}\right)d\nu$$
This is a straightforward integral which can be done by parts to get the total ionising radiation power to be
$$P\left(1000\text K,10^{15}\text{Hz}\right)=1.69\times10^{-16}\frac{\text{W}}{\text{m}^2\cdot\text{st}}$$
This as you can see, is minuscule.

In photoelectric effect, we are knocking off an electron from the bulk using the energy of photons. The excess energy is converted into kinetic energy of the electron. Now consider the reverse. High energy electron is getting captured by the bulk. So now a photon is released depending on how much energy the electron lost. Since the electron before capture can have arbitrary energy, the emitted photon can have arbitrary energy. Thus there is no cutoff for radiation.
The cutoff comes in the case of photoelectric effect due to the restriction on allowed energies of the bound electron. However there is no such restriction on free electron.

A: Planck's law says:
$$B_\nu(\nu, T) = \frac{2h\nu^3}{c^2} \frac1{\exp\left(\frac{h\nu}{kT}\right) - 1}.$$
This is the power emitted by a black body of temperature $T$ at frequency $\nu$. If we consider a black object (thus highest possible purely thermal emission) of temperature $700°\mathrm C$ (an estimate of temperature of a heater), it'll emit total power of
$$P_\text{total}(700°\mathrm C)=\pi \int\limits_0^\infty \mathrm{d}\nu B_\nu(\nu,700°\mathrm C)=13.6\,\frac{\mathrm{kW}}{\mathrm{m}^2}.$$
(This can also be calculated via the Stefan-Boltzmann law.)
If we now want to find the power of only ionizing radiation, we should instead integrate in the range of $\nu\in[\nu_0,\infty)$, where $\nu_0$ could be taken somewhere in the UV range, e.g. lower border of UVB, i.e. $950\,\mathrm{THz}$. Then we have:
$$P_\text{hard}(700°\mathrm C)=\pi \int\limits_{950\,\mathrm{THz}}^\infty \mathrm{d}\nu B_\nu(\nu,700°\mathrm C)=3.1\times 10^{-20}\,\frac{\mathrm{W}}{\mathrm{m}^2}.$$
So a surface of $1\,\mathrm{m}^2$ will emit $~10^{-20}\,\mathrm{W}$. This is totally negligible, even in the course of a hundred years.

A: for 1) In this link there is the black body formula of Planck's law that gives the

the power per unit solid angle and per unit of area normal to the propagation

So for a given temperature of the body one can calculate the power, in your case for high enough frequencies, take a $Δ(ν)$  .
Once you have the power you will have the energy per second. Divide the power with  the average $hν$ of your  $Δ(ν)$ and you can estimate how many photons of that approximate frequency radiate per second.
You will find that one has to wait for a loooo..ng time for an X-ray photon to come our of your radiator. Better worry about the Xrays created by the muons passing your body at the rate of 1 every $cm^2$ every minute, much worse when you fly in an airplane.
for 2) Quantum mechanics gives probabilities for limits. When the probability gets very very small, that is a limit.To get enough energy for an x-ray the material would have to synchronize so that random vibrations would quantum mechanically allow for a quantum level to exist to have enough energy for an x-ray photon to come out.How improbable that is is reflected in the  Planck formula.
Also a limit is given by energy conservation laws , also included in the formula.
The basic line is that it is very improbable, as the other answers state.

A:
How to roughly estimate the ionizing radiation power in common high
  power thermal source like 2KW heater without fan then make sure it is
  safe considering it is used for years instead of 0.1 second/year in
  case of DR Xray scan?

A common 2 kW resistance heater does not emit ionizing radiation. It's radiant heat is primarily infra red. The range for infrared  radiation is about 430 x 10$^{12}$Hz to 300 x 10$^9$ Hz. It is considered non-ionizing radiation.
Ionizing radiation begins around 3 x 10$^{15}$ Hz. X-radiation is in the range of 3 x 10$^{16}$ to 2 x 10$^{19}$ Hz.
Bottom line: Infrared heaters do not pose the health risks associated with ionizing radiation like X-radiation.
Hope this helps.


text:
Q: Angular OAuthModule config factory I need to configure dynamic URLs for the OAuthModule to send the access token at each request.
The solution that I'm using (hint), providing an OAuthModuleConfig via a factory method, doesn't seem to work.
This is my AppModule where I configure everything:
import {BrowserModule} from '@angular/platform-browser';
import {APP_INITIALIZER, NgModule} from '@angular/core';
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {OAuthModule, OAuthModuleConfig} from 'angular-oauth2-oidc';
import {HttpClientModule} from '@angular/common/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MaterialModule} from './material/material.module';
import {DataSharingService} from './data-sharing/data-sharing.service';
import {EnvironmentService} from './environment/environment.service';
import {environment} from '../environments/environment';
import {ApiModule, BASE_PATH} from '@api/api-client';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    APIModule,
    HttpClientModule,
    OAuthModule.forRoot(),
    BrowserAnimationsModule,
    MaterialModule
  ],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: appInitializerFactory,
      deps: [EnvironmentService, DataSharingService],
      multi: true
    },
    {
      provide: OAuthModuleConfig,
      useFactory: oAuthModuleConfigFactory,
      deps: [DataSharingService]
    },
    {
      provide: BASE_PATH,
      useFactory: basePathFactory,
      deps: [DataSharingService]
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

function appInitializerFactory(environmentService: EnvironmentService, dataSharingService: DataSharingService): () => Promise<void> {
  return () => environmentService.getEnvironment(environment.production)
    .toPromise()
    .then(value => {
      dataSharingService.apiBasePath.next(value.API_BASE_PATH);
    });
}

function oAuthModuleConfigFactory(dataSharingService: DataSharingService): OAuthModuleConfig {
  return {
    resourceServer: {
      allowedUrls: [dataSharingService.apiBasePath.value],
      sendAccessToken: true
    }
  };
}

function basePathFactory(dataSharingService: DataSharingService): string {
  return dataSharingService.apiBasePath.value;
}

I think I should pass this configuration to the OAuthModule.forRoot() method in imports, but I don't know how.
How do I pass the provided OAuthModuleConfig to the OAuthModule.forRoot()?


text:
Q: wp get tags in custom query loop I'm stuck! I'm trying to render out the 'tags' for each post. The posts are split up into categories. I didn't build this site and I'm having trouble working with it.
I trying using the_tag() , but because its a custom query loop. I don't think that will work.
here is how the loop starts
<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$term = get_field('news_category');
$number = get_field('number_of_posts_per_page');

$the_query = new WP_Query(array(
'posts_per_page' => $number,
'paged' => $paged,

));
if ( $the_query->have_posts() ) : while ($the_query->have_posts()) : $the_query->the_post(); ?>

   <?php get_template_part( 'parts/loop', 'news' ); ?>

<?php endwhile; ?>

ANY help would be great, I'm so lost right now!
Thanks!

A: You said you used the_tag(), the function is called the_tags()?
Also, did you use the_tags() inside the loop?
<?php

    // Reformatted code

    $paged   =  ( get_query_var('paged') ) ? get_query_var('paged') : 1;

    // ACF Plugin related function
    $term    =  get_field('news_category');
    $number  =  get_field('number_of_posts_per_page');

    $the_query = new WP_Query(array(
        'post_type'      => 'post',
        'posts_per_page' => $number,
        'paged'          => $paged,
    ));

    if ( $the_query->have_posts() ) :

        while ($the_query->have_posts()) :

            $the_query->the_post();

        ?>

           <?php get_template_part( 'parts/loop', 'news' ); ?>

        <?php

            the_tags(); // Inside the loop

        endwhile;

    endif;

?>


text:
Q: Does making software open source make it vulnerable? This is more a philosophical question but its one I've been pondering for some time now.
I don't know anything about computer security or how computers are broken into. I thought hackers used disassembling software on executable software to create malware and other things.
My question is would making some software open source make it vulnerable to hackers or do I have reverse engineering confused with hacking?

A: Making something open source does not inherently make it more vulnerable. Trying to hide what you are doing is known as Security Through Obscurity, and it doesn't work very well.
Making something open source makes things easier for casual hackers, since they can see how your app works more easily. On the other hand, making it open source also lets anyone who is interested look through your code and report security vulnerabilities. They're two sides of the same coin.
For the most advanced threats, they'll get through regardless of whether your code is open source or not. On the other hand, honest volunteers are much less likely to bother trying to find and fix bugs in a closed source product.
So basically, it depends. In general, you're better off open sourcing things if you think people are actually going to be interested in the project.


text:
Q: The spectrum of a semiring One of the generalizations of algebraic geometry is provided by the theory of semiring schemes, viz. Lorscheid 2012. The theory follows the same set up of scheme theory, but we use semirings instead of rings, also known as rings without additive inverses; examples of which are the natural numbers $\mathbb{N}$ or the tropical semiring $\mathbb{T}$.
An ideal of a semiring $R$ is a set $I\subset R$ which 1) is closed under addition 2) contains $0$, and 3) is such that $IA=I$. Moreover, $I$ is prime if whenever $ab\in I$, then $a\in I$ or $b\in I$, and we write $\mathrm{Spec}(R)$ for the set of prime ideals of $R$.

What are $\mathrm{Spec}(\mathbb{N})$ and $\mathrm{Spec}(\mathbb{T})$? Do we have other nice examples of prime spectra of semirings?

A: First let's compute $\operatorname{Spec}\mathbb{N}$. Certainly $p\mathbb{N}$ is a prime ideal for every positive prime $p\in\mathbb{Z}$, and you can check that both $\{0\}$ and $\mathbb{N}\setminus\{1\}$ are prime ideals. As @Zhen Lin points out in the comments, these are in fact the only prime ideals of $\mathbb{N}$; to see why, suppose $P$ is a non-zero prime ideal of $\mathbb{N}$. Then there exists some non-zero natural number in $P$; if $P$ contains $1$, then $P=\mathbb{N}$, a contradiction. So $P$ contains a natural number greater than one, and hence must contain one of its prime factors $p$. If every element of $P$ is divisible by $p$, then $P=p\mathbb{N}$. Otherwise $P$ contains an element outside of $p\mathbb{N}$, and hence must contain one of its prime divisors $q$, which is necessarily distinct from $p$. By the "coin theorem", $P$ now contains every number greater than $pq-p-q$. In particular, for any $n>1$, there exists some $k$ such that $n^k>pq-p-q$, whence $n^k\in P$ and so $n\in P$. So $P=\mathbb{N}\setminus\{1\}$, as desired.
Now let's compute $\operatorname{Spec}\mathbb{T}$. By convention, I take $\mathbb{T}=\mathbb{R}\cup\{\infty\}$, with $\oplus$ as $\min$ and $\otimes$ as $+$. Note that $\{\infty\}$ is a prime ideal of $\mathbb{T}$; I claim it is the only one, and that it is in fact the only proper ideal of $\mathbb{T}$. To see this, suppose that $I$ is a proper ideal of $\mathbb{T}$ containing some $x\in\mathbb{R}$. Then $I\ni\lambda\otimes x$ for every $\lambda\in\mathbb{T}$. In particular, for any $y\in\mathbb{R}$, $I$ contains $(y-x)\otimes x=y$, and furthermore $I$ contains $\infty\otimes x=\infty$. So $I=\mathbb{T}$, a contradiction. Thus indeed $\{\infty\}$ is the only prime ideal of $\mathbb{T}$.


text:
Q: websocket unable to connect on ec2 with nginx I am running node.js and socket.io on EC2, using nginx v1.4.1
Here is my /etc/nginx/sites-available/default
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
        listen 80;

        server_name mysite.com;

        location / {
                proxy_pass http://localhost:4321;
                proxy_set_header Host $http_host;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection $connection_upgrade;
        }
}

However I get
WebSocket connection to 'ws://mysite.com/socket.io/1/websocket/nS7f2eI5jAZ-pIN_8fai' failed: Unexpected response code: 502
and from node:
debug - setting request GET /socket.io/1/websocket/nS7f2eI5jAZ-pIN_8fai
debug - set heartbeat interval for client nS7f2eI5jAZ-pIN_8fai
warn  - websocket connection invalid

Then it switches to xhr-polling.
I have followed exactly how so many online guides say about Nginx + websocket, but I don't know where I made a mistake.

A: As per the Nginx documentation, you can try the following in your nginx config file.
   location /wsapp/ {
        proxy_pass                           http://your-host:your-port/;
        proxy_http_version                   1.1;
        proxy_set_header                     Upgrade $http_upgrade;
        proxy_set_header                     Connection "Upgrade";
        proxy_set_header                     Host $host;
   }


text:
Q: Where should i write my javascript code in angular 4 for a component I am making an angular app and in that I have a component in which I have added a alert message using semantic-ui and to dismiss that message I have to write a specific provided by semantic itself.
I am not sure where should I write that code in order to make it work.
my html code:

        We're sorry we can't apply that discount

That offer has expired

script:
$('.message .close').on('click', function() {
    $(this).closest('.message').transition('fade');
});

A: I would suggest to use already adopted for Angular semantic-ui library: https://www.npmjs.com/package/ng2-semantic-ui. It's already wrapped in Angular so you don't need to worry about jQuery.
Angular doesn't recommend to manipulate DOM by jQuery or raw JavaScript. It has DOM abstraction services for it. You can read more here: https://blog.angularindepth.com/exploring-angular-dom-abstractions-80b3ebcfc02
So even if you wrap your jQuery code in Angular it will be bad from the point of best practices.I would really suggest to use ng2-semantic-ui. It will save your time.

A: Better create your own animation transition. Here is how
In your component.ts file do this:
import { trigger, style, animate, transition } from '@angular/animations';

@Component({
  selector: 'my-app',
  animations: [
    trigger(
      'enterAnimation', [
        transition(':enter', [
          style({transform: 'translateX(100%)', opacity: 0}),
          animate('500ms', style({transform: 'translateX(0)', opacity: 1}))
        ]),
        transition(':leave', [
          style({transform: 'translateX(0)', opacity: 1}),
          animate('500ms', style({transform: 'translateX(100%)', opacity: 0}))
        ])
      ]
    )
  ]
})
export class App {
  show:boolean = true; //The error message is displayed by default
}

So now you have the code to fade in and fade out. Now you need to change the value of your show boolean when the button is clicked. So you do this in your component.html

        We're sorry we can't apply that discount

That offer has expired

This way you do not have to use jquery in your angular app.


text:
Q: General form for $A^2=0$ where $A$ is a $2\times2$ matrix Find the general form for all the $2\times2$ matrices over $\mathbb{R}$ that $A^2=0$

A: Either $A=0$, or $A\neq 0$ and there exists $x\in\mathbb R^2$ such that $\{x,Ax\}$ is a basis of $\mathbb R^2$. We thus have the general form of $A$ up to a change of basis.

A: suppose $A=\begin{bmatrix}a&b\\c&d\end{bmatrix}$, then $A^2=0$ makes a four equation group of four unknown numbers($a,b,c,d$) like:
$$a^2+bc = 0\\ab+bd = 0\\ac+cd = 0\\bc+d^2 = 0$$
solve these equations, we have two possible solutions:
$$a=0, b=0,c\in R, d=0$$
or
$$a\in R,b\in R,c = -a^2/b,d=-a.$$
So the forms of matrix are:
$$\begin{bmatrix}a&b\\-a^2/b&-a\end{bmatrix}$$
or
$$\begin{bmatrix}0&0\\c&0\end{bmatrix}$$

A: Hint: First show that both eigenvalues of $A$ are $0$. Then, find the Jordan form of $A$. There are $2$ possibilities.

A: The characteristic polynomial of the given matrix is
X^2=0
So obviously, the eigenvalues can only be zeros. So it's Jordan canonical form J is either [0,0;0,0] or [0,1;0,0]. Further, the matrix M=P\J P , for any non singular 2by 2 matrix P.

A: The four condition that Martial found boil down to $\begin{pmatrix}\sqrt{-bc}& b\\ c & -\sqrt{-bc}\end{pmatrix}$ where $bc\le0$.


text:
Q: pointing to a memory address outside an array boundary I was wondering if accessing an array outside its boundary(line 2 in the following code sample) would ever produce an error?
int a[20];
int* ptr = &a[20]; // line 2
int count=20;
do
{
  ptr--;
  printf("%d",*ptr);
}while(--count!=0);

A: According to C Traps and Pitfalls:

But how can it make sense to refer to an element that doesn't exist?
  Fortunately we do not have to refer to this element, merely to its
  address, and that address does exist in every C implementation we have
  encountered. Moreover, ANSI C explicitly permits this usage: the address
  of the nonexistent element just past the end of an array may be taken and
  used for assignment and comparison purposes. Of course it is illegal
  actually to refer to that element!

A: Trying to access memory beyond the end of the array is undefined behavior. However, It is perfectly legal to have a pointer to point at one element beyond the end of the array.
The distinction between pointing to a certain address and accessing it is important.
For example, you can use the following to find the size of an array arr
int size = (&arr)[1] - arr;

A: Accessing memory address outside an array boundary may not crash the the process always. But certainly it will corrupt the address space if you modify the data. Also, sometime memory address outside an array boundary will really lie outside the process address space, that will result in seg-fault.
Anyway, this is a dangerous. It will introduce hard to narrow-down error. The memory corruption, or weird behavior of the program will manifest at some other place, and we will spend hours and hours finding the needle in the haystack.

A: Modifying the address past array boundary will never produce a compiler error, since C compiler doesn't treat it as error.
However on some machines if this address is not allowed to be accessed, you may get a Runtime Error (Seg Fault).
This is similar to writing to address 0 (NULL).
On a microprocessor/microcntroller/embedded devices on some architectures, you may be allowed to write at address 0, it is perfectly valid but on some other machines you may get SEGFAULT.
That is why this is also termed as undefined behavior.

A: Your code does not access memory beyond the end of the array.
so changes your code little. Count changed to 100 from 20
#include<stdio.h>

int main() {
int a[20];
int* ptr = &a[20]; // line 2
int count=100;
do
{
  ptr--;
  printf("%d",*ptr);
}while(--count!=0);
return 0;
}

see http://codepad.org/X8yqrnDC
NO at compilation it will not give any error.
But at run time it might get segmentation fault.
as per standard its undefined behavior


text:
Q: Cloud Functions Delete a Folder: TypeScript My storage bucket budget-32bfc contain the following folders;
--+ Folder1
--+ Folder2
--+ Folder3
I want to delete Folder1 from Cloud Functions.
ATTEMPT 1:

gcs.bucket("budget-32bfc").file('Folder1').delete().then(() => {
        console.log("Folder Deleted");
    }).catch(function (error) {
        console.log("Error listing users:", error);
    });

ATTEMPT 2:

admin.bucket("budget-32bfc").file('Folder1').delete().then(() => {
        console.log("Folder Deleted");
    }).catch(function (error) {
        console.log("Error listing users:", error);
    });

Both attempt gave me a 404 Error: 'No such object: budget-32bfc/Folder1'.
How do I delete a folder??

A: Version 1.7.x has the following method which returns a Promise:

deleteFiles(query, callback)

It will try to delete each file inside the specified folder (folders too). If the deletion of one file fails, the process is stopped. (use 'force: true' to override this behavior).
bucket.deleteFiles({
    prefix: `${userId}/images`
})
.catch( (err) => {
    console.log(`Failed to delete all images of user ${userId}`);
});

Official Documentation: Storage - deleteFiles
Another solution found here: click
(Note: I cannot mark this thread as duplicate as I only have 13 rep points, please stop deleting my comment because others might need to see this, thank you)

A: There is no concept of a "folder" in Cloud Storage, it is merely part of the name of each file. So you will have to delete all files that start with Folder1/. Once you do that, the folder is also gone.
Also see:

*

*How to get a list of files in a Google Cloud Storage folder using Node.js? (on how to get a list of files in a folder using the Node.js for Cloud Storage)

*How to get a list of all files in Cloud Storage in a Firebase app? (the Firebase SDKs do not have an API to list files)


text:
Q: How add an item template to Visual Studio 2010 Let me elaborate, since the title was a little rough. I have been looking for a way to make a WCF service work with Silverlight for days now. Eventually I come across a mention of something called a 'Silverlight-enabled WCF service'. The only problem is, this doesn't exist in my Visual Studio 2010 (and I have looked).
Someone then asked me whether it appears in Program Files(x86)\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Silverlight\1033. Well it looks to be - there is a file called SLWcfService.zip.
Assuming this is the template I'm looking for, how do I get Visual Studio to add this to the list of item templates that I get when I select a new project?
Thanks.

A: I don't about your specific case, but if you have an item up on VS and you want to save it as a template: Click on: File -> Export Template -> and then select Item Template.


text:
Q: Sum of product of products I was working on a proof, and found that, for my proof to hold, the following must be true:
Let $\Lambda_{i} > 0$ for $i \in \{0, 1, .. , k\}$, such that $\Lambda_{i} = \Lambda_{j} \iff i = j$. Then:
$$\sum_{m = 0}^{k-1} \prod_{i = 1, \neq m}^{k}\prod_{j = 0, \neq m}^{i-1}(\Lambda_j-\Lambda_i) = \prod_{i = 1}^{k-1}\prod_{j = 0}^{i-1}(\Lambda_j-\Lambda_i)$$.
I worked a couple of specific examples, where $k = 3$ and $k = 4$, enough to prove it in those cases. But in each case, I had to work through term by term. I tried induction, and ended up with a spaghetti mess of algebra. Does this expression hold for $k \in \mathbb{Z^+}$? If it doesn't, why doesn't it seem to hold for lower values?

A: Hint: Setting $k=3$, the left-hand side gives
\begin{align*}
\color{blue}{\sum_{m = 0}^{2}}
&\color{blue}{ \prod_{\substack{i = 1\\i\ne m}}^{3}\prod_{\substack{j = 0\\j \ne m}}^{i-1}(\Lambda_j-\Lambda_i)}\\
&=\prod_{\substack{i = 1\\i\ne 0}}^{3}\prod_{\substack{j = 0\\j \ne 0}}^{i-1}(\Lambda_j-\Lambda_i)
+\prod_{\substack{i = 1\\i\ne 1}}^{3}\prod_{\substack{j = 0\\j \ne 1}}^{i-1}(\Lambda_j-\Lambda_i)
\prod_{\substack{i = 1\\i\ne 2}}^{3}\prod_{\substack{j = 0\\j \ne 2}}^{i-1}(\Lambda_j-\Lambda_i)\\
&=\prod_{i=1}^{3}\prod_{j=1}^{i-1}(\Lambda_j-\Lambda_i)
+\prod_{\substack{i = 1\\i\ne 1}}^{3}\prod_{\substack{j = 0\\j \ne 1}}^{i-1}(\Lambda_j-\Lambda_i)
\prod_{\substack{i = 1\\i\ne 2}}^{3}\prod_{\substack{j = 0\\j \ne 2}}^{i-1}(\Lambda_j-\Lambda_i)\\
&=\left(\Lambda_1-\Lambda_2\right)\left(\Lambda_1-\Lambda_3\right)\left(\Lambda_2-\Lambda_3\right)\\
&\qquad+\left(\Lambda_0-\Lambda_2\right)\left(\Lambda_0-\Lambda_3\right)\left(\Lambda_2-\Lambda_3\right)\\
&\qquad+\left(\Lambda_0-\Lambda_1\right)\left(\Lambda_0-\Lambda_3\right)\left(\Lambda_1-\Lambda_3\right)\\
&=\Lambda_3^2\left[\left(\Lambda_1-\Lambda_2\right)
+\left(\Lambda_0-\Lambda_
2\right)+\left(\Lambda_0-\Lambda_1\right)\right]+\cdots\\
&\,\,\color{blue}{=2\Lambda_3^2\left[\Lambda_0-\Lambda_2\right]+\cdots}
\end{align*}
It seems, the LHS contains terms with $\Lambda_3$ contrary to the RHS.


text:
Q: Sabre Unable to use "Revalidate Itinerary" REST API I am trying to follow the developer guide for a air booking process found in the documentation. https://developer.sabre.com/guides/travel-agency/workflows/air-booking
Here, I have used token based authentication (v2) and I could successfully search and book using the rest api. However, Upon hitting the revalidate itinerary api with the example found in the documentation https://developer.sabre.com/docs/rest_apis/air/search/revalidate_itinerary/reference-documentation
Here, I am getting following error. (Note: I have changed the pcc code in here. The original request uses the correct pnr.)
Response:
{
    "groupedItineraryResponse": {
        "version": "6.3.0",
        "messages": [
            {
                "severity": "Info",
                "type": "WORKERTHREAD",
                "code": "TRANSACTIONID",
                "text": "3019835637227710880"
            },
            {
                "severity": "Info",
                "type": "SERVER",
                "code": "ASE032LPSCIL668.ATSE.CERT.ASCINT.SABRECIRRUS.COM",
                "text": "27038"
            },
            {
                "severity": "Info",
                "type": "DRE",
                "code": "RULEID",
                "text": "25961"
            },
            {
                "severity": "Info",
                "type": "DEFAULT",
                "code": "RULEID",
                "text": "25959"
            },
            {
                "severity": "Error",
                "type": "IF2",
                "code": "PROCESS",
                "text": "PCC EPCC: Revalidate Itinerary not requested."
            },
            {
                "severity": "Error",
                "type": "ERR",
                "code": "ERR",
                "text": "Error during Processing"
            }
        ],
        "statistics": {
            "itineraryCount": 0
        }
    }
}

API URL: https://api-crt.cert.havail.sabre.com/v3/shop/flights/revalidate
Request json:
{
    "OTA_AirLowFareSearchRQ": {
        "OriginDestinationInformation": [
            {
                "RPH": "0",
                "DepartureDateTime": "2021-08-14T00:00:00",
                "OriginLocation": {
                    "LocationCode": "KRK"
                },
                "DestinationLocation": {
                    "LocationCode": "WAW"
                }
            }
        ],
        "POS": {
            "Source": [
                {
                    "PseudoCityCode": "EPCC",
                    "RequestorID": {
                        "CompanyName": {
                            "Code": "TN"
                        },
                        "ID": "1",
                        "Type": "1"
                    }
                }
            ]
        },
        "TPA_Extensions": {
            "IntelliSellTransaction": {
                "RequestType": {
                    "Name": "200ITINS"
                }
            }
        },
        "TravelPreferences": {
            "TPA_Extensions": {
                "DataSources": {
                    "NDC": "Disable",
                    "ATPCO": "Enable",
                    "LCC": "Disable"
                },
                "NumTrips": {}
            }
        },
        "TravelerInfoSummary": {
            "AirTravelerAvail": [
                {
                    "PassengerTypeQuantity": [
                        {
                            "Code": "ADT",
                            "Quantity": 1
                        }
                    ]
                }
            ],
            "SeatsRequested": [
                1
            ]
        },
        "Version": "3"
    }
}

A: You need to list all the flights with booking classes in TPA_Extension under OriginDestinationInformation.
So, your OriginDestinationInformation should look something like this:
      "OriginDestinationInformation": [
            {
                "RPH": "0",
                "DepartureDateTime": "2021-10-11T14:50:00",
                "OriginLocation": {
                    "LocationCode": "BEG"
                },
                "DestinationLocation": {
                    "LocationCode": "ZRH"
                },
                "TPA_Extensions": {
                    "SegmentType": {
                        "Code": "O"
                    },
                    "Flight": [
                        {
                            "Number": 1417,
                            "DepartureDateTime": "2021-10-11T14:50:00",
                            "ArrivalDateTime": "2021-10-11T16:40:00",
                            "Type": "A",
                            "ClassOfService": "K",
                            "OriginLocation": {
                                "LocationCode": "BEG"
                            },
                            "DestinationLocation": {
                                "LocationCode": "ZRH"
                            },
                            "Airline": {
                                "Operating": "LX",
                                "Marketing": "LX"
                            }
                        }
                    ]
                }
            }
        ],


text:
Q: All possible combinations, choosing one item from multiple ArrayLists So I am trying to make a course scheduler. The program would contain all the courses offered in a particular semester. The user will input the courses he wants to take for a particular semester, and the program would generate all possible timetables based on the users input. (For example a particular course maybe taught my multiple instructors in multiple time slots, that is what I mean by ALL possible timetables)
The approach I am taking is the following
I have a Course class which stores all the information about a particular course
I have a CourseContainer which has an ArrayList of all the courses
I am having hard time in generating all possible timetables
So far I have a getAllCourse method
public ArrayList<Courses> getAllCourse(String name){
    ArrayList<Courses> all = new ArrayList<>();
    for (Courses  course : container) {
        if (course.getName().equals(name))
            all.add(course);
    }
    return all;
}

This way I have multiple arraylists of all the courses the user wants.
I can not figure out how to get the combinations out of this.
I would appreciate if any one can tip me on how to do this or a better way.
Thank you!

A: You want to use Map instead.
Create a Map which holds mapping of course name with list of courses, and then use it like this:
private final Map<String, List<Courses>> container = initializeIt();

public ArrayList<Courses> getAllCourse(String name){
    ArrayList<Courses> all = new ArrayList<>();
    List<Courses> courses = container.get(name);
    if(courses != null) all.addAll(courses);
    return all;
}

A: I don't fully understand your implementation, but it sounds like you have a list of courses for each time slot.
If you had 3 timeslots, you could use 3 nested loops to create all the possible combinations. I've simplified it slightly and used a String instead of a Course:
List<String> timeslot1 = new ArrayList<String>();
timeslot1.add("Maths");
timeslot1.add("English");

List<String> timeslot2 = new ArrayList<String>();
timeslot2.add("Science");
timeslot2.add("History");

List<String> timeslot3 = new ArrayList<String>();
timeslot3.add("Italian");
timeslot3.add("Geography");

// a list of all the possible course combinations
List<List<String>> timetables = new ArrayList<List<String>>();

// create the course combinations
for(String course1 : timeslot1) {
    for(String course2 : timeslot2) {
        for(String course3 : timeslot3) {
            List<String> timetable = new ArrayList<String>();
            timetable.add(course1);
            timetable.add(course2);
            timetable.add(course3);

            timetables.add(timetable);
        }
    }
}

// print them
for(List<String> timetable : timetables) {
    System.out.println(String.format("%s, %s, %s", timetable.get(0), timetable.get(1), timetable.get(2)));
}

With the following output:
Maths, Science, Italian
Maths, Science, Geography
Maths, History, Italian
Maths, History, Geography
English, Science, Italian
English, Science, Geography
English, History, Italian
English, History, Geography


text:
Q: Opening another window by a button and returning an empty window using Tkinter, Python The grid() can't draw the Button when other window is opening by clicking on another Button, returning just an empty window and an error:
_tkinter.TclError: image "pyimage1" doesn't exist

I read a similar problem in another topic (here), but it happened with a Label, which it was solved using .draw (). I wonder if there is a similar solution when the widget is a Button.
PS: I'm sure I placed the image path correctly from my project folder. The same image can be showed on the first button when running the program.
from tkinter import *
import pygame

root = Tk()
root.title('Test')

def open_window():
    other_window = Tk()

    def play_sound():
        pygame.init()
        pygame.mixer.music.load('path.mp3')
        pygame.mixer.music.play()
        pygame.event.wait()

    bt_play_sound = Button(other_window, text = 'Play', image=img_play, command = play_sound, compound="top")
    bt_play_sound.grid(row = 0, column = 0)

    other_window.mainloop()

#IMAGES
img_play = PhotoImage(file="path.png")

open_other_window = Button(root, text = "Open", image=img_play, command = open_window, compound="top")
open_other_window.grid(row = 0, column = 0)

root.mainloop()

A: To get the second image to work, you need to create a new PhotoImage and specify the master option set to the second Tk window.
def open_window():
    other_window = Tk()

    def play_sound():
        pygame.init()
        pygame.mixer.music.load('path.mp3')
        pygame.mixer.music.play()
        pygame.event.wait()

    img_play = PhotoImage(file="path.png", master=other_window)    # <<<< Add this line
    bt_play_sound = Button(other_window, text = 'Play', image=img_play, command = play_sound, compound="top")
    bt_play_sound.grid(row = 0, column = 0)

    other_window.mainloop()

As a side note, tkinter stores the images as strings (like keys in a dictionary). img_play = "pyimage1" (or whatever string tkinter assigns).


text:
Q: Valor padrão do Input no Laravel No Laravel, quero que, quando um determinado valor não exista no Input, eu possa definir um valor padrão.
Com PHP puro, é possível fazer assim:
$text = isset($_POST['text']) ? $_POST['text'] : 'padrão';

No Laravel sei que é possível fazer de uma forma parecida, algo assim:
 $text = Input::has('text') ? Input::get('text') : 'padrão';

Tendo em vista que o Laravel é um excelente frameworks com alguns recursos que diminuem a reescrita continua de códigos, existe um jeito mais fácil de se obter um valor parão para um valor do input? Ou esse é o único jeito que existe?
Pois as vezes fica cansativo ficar fazendo:
$a = Input::has('a') ? Input::get('a') : 'Valor padrão';
$b = Input::has('b') ? Input::get('b') : 'Valor padrão';
$c = Input::has('c') ? Input::get('c') : 'Valor padrão';

A: Você pode usar dessa forma Input::get('nome_campo','valor'); no caso o segundo parâmetro identifica o valor padrão caso o Input retorne null.

A: O Laravel inclui um helper que faz exatamente isso:
array_get($array, 'campo', 'valor padrão'); // null como default

A vantagem é que você pode fazer isso em qualquer lugar, não necessariamente somente no input.
Particularmente, não gosto do array_get, sou mais o operador Null coalescing do PHP 7.


text:
Q: How to enable audio of two ffplay windows simultaneously?(How can I hear audio of the video files at the same time?) When more than one ffplay-window is running only the audio of one of them is enable , But I need to hear all of them at the same time.
For example I run two command-lines separately like this:
//command line 1
ffplay -i video1.avi

//command line 2
ffplay -i video2.avi

How can I hear audio of the video files at the same time?
I did not find anything about that in the ffplay documents, So I want to change the ffplay source code.
this is event_loop function (in ffplay.c):
static void event_loop(VideoState *cur_stream)
{
SDL_Event event;
double incr, pos, frac;

for (;;) {
    double x;
    refresh_loop_wait_event(cur_stream, &event);
    switch (event.type) {
    case SDL_KEYDOWN:
        if (exit_on_keydown) {
            do_exit(cur_stream);
            break;
        }
        switch (event.key.keysym.sym) {
        case SDLK_ESCAPE:
        case SDLK_q:
            do_exit(cur_stream);
            break;
        case SDLK_f:
            toggle_full_screen(cur_stream);
            cur_stream->force_refresh = 1;
            break;
        case SDLK_p:
        case SDLK_SPACE:
            toggle_pause(cur_stream);
            break;
        case SDLK_m:
            toggle_mute(cur_stream);
            break;
        case SDLK_KP_MULTIPLY:
        case SDLK_0:
            update_volume(cur_stream, 1, SDL_VOLUME_STEP);
            break;
        case SDLK_KP_DIVIDE:
        case SDLK_9:
            update_volume(cur_stream, -1, SDL_VOLUME_STEP);
            break;
        case SDLK_s: // S: Step to next frame
            step_to_next_frame(cur_stream);
            break;
        case SDLK_a:
            stream_cycle_channel(cur_stream, AVMEDIA_TYPE_AUDIO);
            break;
        case SDLK_v:
            stream_cycle_channel(cur_stream, AVMEDIA_TYPE_VIDEO);
            break;
        case SDLK_c:
            stream_cycle_channel(cur_stream, AVMEDIA_TYPE_VIDEO);
            stream_cycle_channel(cur_stream, AVMEDIA_TYPE_AUDIO);
            stream_cycle_channel(cur_stream, AVMEDIA_TYPE_SUBTITLE);
            break;
        case SDLK_t:
            stream_cycle_channel(cur_stream, AVMEDIA_TYPE_SUBTITLE);
            break;
        case SDLK_w:
    #if CONFIG_AVFILTER
            if (cur_stream->show_mode == SHOW_MODE_VIDEO && cur_stream->vfilter_idx < nb_vfilters - 1) {
                if (++cur_stream->vfilter_idx >= nb_vfilters)
                    cur_stream->vfilter_idx = 0;
            } else {
                cur_stream->vfilter_idx = 0;
                toggle_audio_display(cur_stream);
            }
     #else
            toggle_audio_display(cur_stream);
     #endif
            break;
        case SDLK_PAGEUP:
            if (cur_stream->ic->nb_chapters <= 1) {
                incr = 600.0;
                goto do_seek;
            }
            seek_chapter(cur_stream, 1);
            break;
        case SDLK_PAGEDOWN:
            if (cur_stream->ic->nb_chapters <= 1) {
                incr = -600.0;
                goto do_seek;
            }
            seek_chapter(cur_stream, -1);
            break;
        case SDLK_LEFT:
            incr = -10.0;
            goto do_seek;
        case SDLK_RIGHT:
            incr = 10.0;
            goto do_seek;
        case SDLK_UP:
            incr = 60.0;
            goto do_seek;
        case SDLK_DOWN:
            incr = -60.0;
        do_seek:
                if (seek_by_bytes) {
                    pos = -1;
                    if (pos < 0 && cur_stream->video_stream >= 0)
                        pos = frame_queue_last_pos(&cur_stream->pictq);
                    if (pos < 0 && cur_stream->audio_stream >= 0)
                        pos = frame_queue_last_pos(&cur_stream->sampq);
                    if (pos < 0)
                        pos = avio_tell(cur_stream->ic->pb);
                    if (cur_stream->ic->bit_rate)
                        incr *= cur_stream->ic->bit_rate / 8.0;
                    else
                        incr *= 180000.0;
                    pos += incr;
                    stream_seek(cur_stream, pos, incr, 1);
                } else {
                    pos = get_master_clock(cur_stream);
                    if (isnan(pos))
                        pos = (double)cur_stream->seek_pos / AV_TIME_BASE;
                    pos += incr;
                    if (cur_stream->ic->start_time != AV_NOPTS_VALUE && pos < cur_stream->ic->start_time / (double)AV_TIME_BASE)
                        pos = cur_stream->ic->start_time / (double)AV_TIME_BASE;
                    stream_seek(cur_stream, (int64_t)(pos * AV_TIME_BASE), (int64_t)(incr * AV_TIME_BASE), 0);
                }
            break;
        default:
            break;
        }
        break;
    case SDL_VIDEOEXPOSE:
        cur_stream->force_refresh = 1;
        break;
    case SDL_MOUSEBUTTONDOWN:
        if (exit_on_mousedown) {
            do_exit(cur_stream);
            break;
        }
    case SDL_MOUSEMOTION:
        if (cursor_hidden) {
            SDL_ShowCursor(1);
            cursor_hidden = 0;
        }
        cursor_last_shown = av_gettime_relative();
        if (event.type == SDL_MOUSEBUTTONDOWN) {
            x = event.button.x;
        } else {
            if (event.motion.state != SDL_PRESSED)
                break;
            x = event.motion.x;
        }
            if (seek_by_bytes || cur_stream->ic->duration <= 0) {
                uint64_t size =  avio_size(cur_stream->ic->pb);
                stream_seek(cur_stream, size*x/cur_stream->width, 0, 1);
            } else {
                int64_t ts;
                int ns, hh, mm, ss;
                int tns, thh, tmm, tss;
                tns  = cur_stream->ic->duration / 1000000LL;
                thh  = tns / 3600;
                tmm  = (tns % 3600) / 60;
                tss  = (tns % 60);
                frac = x / cur_stream->width;
                ns   = frac * tns;
                hh   = ns / 3600;
                mm   = (ns % 3600) / 60;
                ss   = (ns % 60);
                av_log(NULL, AV_LOG_INFO,
                       "Seek to %2.0f%% (%2d:%02d:%02d) of total duration (%2d:%02d:%02d)       \n", frac*100,
                        hh, mm, ss, thh, tmm, tss);
                ts = frac * cur_stream->ic->duration;
                if (cur_stream->ic->start_time != AV_NOPTS_VALUE)
                    ts += cur_stream->ic->start_time;
                stream_seek(cur_stream, ts, 0, 0);
            }
        break;
    case SDL_VIDEORESIZE:
            screen = SDL_SetVideoMode(FFMIN(16383, event.resize.w), event.resize.h, 0,
                                      SDL_HWSURFACE|(is_full_screen?SDL_FULLSCREEN:SDL_RESIZABLE)|SDL_ASYNCBLIT|SDL_HWACCEL);
            if (!screen) {
                av_log(NULL, AV_LOG_FATAL, "Failed to set video mode\n");
                do_exit(cur_stream);
            }
            screen_width  = cur_stream->width  = screen->w;
            screen_height = cur_stream->height = screen->h;
            cur_stream->force_refresh = 1;
        break;
    case SDL_QUIT:
    case FF_QUIT_EVENT:
        do_exit(cur_stream);
        break;
    case FF_ALLOC_EVENT:
        alloc_picture(event.user.data1);
        break;
    default:
        break;
    }
}

}
But I can not find the command that cause disable audio when change active window or lost focus in event_loop function.

A: You can add multiple input files for ffplay and then "map" different streams together, but if you have alsa mixer as default audio device the system should mix the audio automatically for you. Modifying ffplay is not a trivial task
this is how you select output device
https://ffmpeg.org/ffmpeg-devices.html#Examples-7
this is how you "concatinate" mutiple inputs:
https://trac.ffmpeg.org/wiki/Concatenate


text:
Q: Java: Foreign Memory "VarHandleSegmentViewBase" error, Misaligned Access at Address I'm trying to understand how to read/write binary encoded versions of a simple struct, like below:
typedef struct Tuple {
    uint32_t length;
    uint8_t* data;
} Tuple;

I have the following code, which can correctly write a Tuple record in Java to binary data in a MemorySegment directly. But trying to read that data back fails -- whereas a simple C program can read it just fine.
Caused by: java.lang.IllegalArgumentException: Misaligned access at address: 16
    at java.base/java.lang.invoke.VarHandleSegmentViewBase.newIllegalArgumentExceptionForMisalignedAccess(VarHandleSegmentViewBase.java:57)
    at java.base/java.lang.invoke.VarHandleSegmentAsInts.offsetNoVMAlignCheck(VarHandleSegmentAsInts.java:100)
    at java.base/java.lang.invoke.VarHandleSegmentAsInts.get(VarHandleSegmentAsInts.java:111)
    at com.example.Tuple.deserialize(App.java:233)

What am I doing wrong in the below?
record Tuple(int size, byte[] data) {

    public static ValueLayout.OfInt SIZE_FIELD = ValueLayout.JAVA_INT.withName("size");
    public static ValueLayout.OfAddress DATA_FIELD = ValueLayout.ADDRESS.withName("data").withBitAlignment(32);

    public static GroupLayout LAYOUT = MemoryLayout.structLayout(SIZE_FIELD, DATA_FIELD).withName("Tuple");

    public static VarHandle VH_SIZE = LAYOUT.varHandle(MemoryLayout.PathElement.groupElement("size"));
    public static VarHandle VH_DATA = LAYOUT.varHandle(MemoryLayout.PathElement.groupElement("data"));

    Tuple(byte[] data) {
        this(data.length, data);
    }

    public static Tuple deserialize(MemorySegment segment) {
        int size = (int) VH_SIZE.get(segment);
        byte[] data = segment
                .asSlice(SIZE_FIELD.byteSize())
                .toArray(ValueLayout.JAVA_BYTE);
        return new Tuple(size, data);
    }

    public int byteSize() {
        return (int) (size + ValueLayout.JAVA_INT.byteSize());
    }

    public void serialize(MemorySegment segment) {
        VH_SIZE.set(segment, size);
        segment
                .asSlice(ValueLayout.JAVA_INT.byteSize())
                .copyFrom(MemorySegment.ofArray(data));
    }
}

public static void main(String[] args) throws Exception {
    Tuple tuple = new Tuple("Hello".getBytes());

    File file = new File("tuple.bin");
    file.createNewFile();

    try (MemorySession session = MemorySession.openConfined()) {
        MemorySegment segment = session.allocate(tuple.byteSize() * 2L);
        tuple.serialize(segment);
        byte[] bytes = segment.toArray(ValueLayout.JAVA_BYTE);
        Files.write(file.toPath(), bytes);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // Now read the file back in
    try (MemorySession session = MemorySession.openConfined()) {
        byte[] bytes = Files.readAllBytes(Paths.get("tuple.bin"));
        MemorySegment segment = MemorySegment.ofArray(bytes);
        Tuple tuple2 = Tuple.deserialize(segment);
        System.out.println(tuple2);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

I use the below C program to confirm it works there:
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct Tuple {
    uint32_t length;
    uint8_t* data;
} Tuple;

const char* EXAMPLE_FILE = "tuple.bin";

int main() {
    FILE* file = fopen(EXAMPLE_FILE, "rb");
    if (file == NULL) {
        printf("Could not open file %s\n", EXAMPLE_FILE);
        return 1;
    }

    Tuple tuple;
    fread(&tuple.length, sizeof(uint32_t), 1, file);
    tuple.data = malloc(tuple.length);
    fread(tuple.data, sizeof(uint8_t), tuple.length, file);
    fclose(file);

    // Convert tuple data to string
    char* string = malloc(tuple.length + 1);
    for (uint32_t i = 0; i < tuple.length; i++) {
        string[i] = tuple.data[i];
    }
    string[tuple.length] = '\0';

    printf("Tuple size: %u bytes\n", tuple.length);
    printf("Tuple data: %s\n", string);

    return 0;
}

EDIT: After using pahole to look at compiled struct layout, it seems there is 4 bytes padding inserted between the Tuple fields for alignment
Maybe the error is to do with this?
struct Tuple {
    uint32_t                   length;               /*     0     4 */

    /* XXX 4 bytes hole, try to pack */

    uint8_t *                  data;                 /*     8     8 */

    /* size: 16, cachelines: 1, members: 2 */
    /* sum members: 12, holes: 1, sum holes: 4 */
    /* last cacheline: 16 bytes */
};

A: You are reading values with aligned layouts from a byte[], but the elements of a byte[] are only assumed/guaranteed to be aligned to 1 byte (i.e. not aligned really). So, reading/writing a value with a layout that has a larger alignment constraint (such as the layouts you're using) will fail with an exception like that.
It likely works in the case where you are writing the data because in that case you're using a native segment. For native segments the 'real' memory address is used to do alignment checking, and the underlying allocator, which is malloc, typically return 16-byte aligned memory regions. (Though, the Java code only requests 1-byte alignment)
If you want to read from a byte[] directly like that, you can get around the exception by applying .withBitAlignment(8) to all the layouts you're using, which will effectively turn off the alignment checking.

A: I managed to fix it, there were two changes I made:

*

*I used the jextract tool to generate Java code similar to mine, to see where it might differ. It was mostly the same, but they defined C interop types like this:

class Constants {
    static final ValueLayout.OfBoolean C_BOOL_LAYOUT = ValueLayout.JAVA_BOOLEAN;
    static final ValueLayout.OfByte C_CHAR_LAYOUT = ValueLayout.JAVA_BYTE;
    static final ValueLayout.OfShort C_SHORT_LAYOUT = ValueLayout.JAVA_SHORT.withBitAlignment(16);
    static final ValueLayout.OfInt C_INT_LAYOUT = ValueLayout.JAVA_INT.withBitAlignment(32);
    static final ValueLayout.OfInt C_LONG_LAYOUT = ValueLayout.JAVA_INT.withBitAlignment(32);
    static final ValueLayout.OfLong C_LONG_LONG_LAYOUT = ValueLayout.JAVA_LONG.withBitAlignment(64);
    static final ValueLayout.OfFloat C_FLOAT_LAYOUT = ValueLayout.JAVA_FLOAT.withBitAlignment(32);
    static final ValueLayout.OfDouble C_DOUBLE_LAYOUT = ValueLayout.JAVA_DOUBLE.withBitAlignment(64);
    static final ValueLayout.OfAddress C_POINTER_LAYOUT = ValueLayout.ADDRESS.withBitAlignment(64);
}

And I noticed it had inserted 32 bytes of padding between the fields.
So I changed the definition of Tuple's layout to the below:
public static ValueLayout.OfInt SIZE_FIELD = Constants.C_LONG_LAYOUT.withName("size");
public static ValueLayout.OfAddress DATA_FIELD = Constants.C_POINTER_LAYOUT.withName("data");

public static GroupLayout LAYOUT = MemoryLayout.structLayout(
        SIZE_FIELD,
        MemoryLayout.paddingLayout(32),
        DATA_FIELD
).withName("Tuple");

*Instead of trying to pass in the memory segment from MemorySegment.ofArray(bytes) to .deserialize(), I allocated the memory first and then copied the bytes memory into it:

// Now read the file back in
try (MemorySession session = MemorySession.openConfined()) {
    byte[] bytes = Files.readAllBytes(Paths.get("tuple.bin"));

    MemorySegment segment = session.allocate(Tuple.LAYOUT);
    segment.copyFrom(MemorySegment.ofArray(bytes));

    Tuple tuple2 = Tuple.deserialize(segment);
    System.out.println(tuple2);
    System.out.println(new String(tuple2.data()));
} catch (Exception e) {
    throw new RuntimeException(e);
}


text:
Q: Entity Framework: Creating custom properties in Business Layer (object) Using Entity Framework the DataLayer is created (DataLayer.dll)
The DataLayer.dll contains the data-objects.
I need to add some business logic to the class 'person'.
Yes, i know, that I can use partial classes, to add business logic.
But in this case (using partial classes) we need to implement it in DataLayer.dll!
I need to uses the BusinessLayer.dll
So the business layer is created (BusinesLayer.dll)
in BusinesLayer.dll we have the file  myPerson.cs
using DataLayer;

namespace Businesslayer
{
public class myPerson : DataLayer.Person

public Property String FullName()
{
  get {return this.Firstname + " " + this.LastName}
}

}

Actually I need to show the data in the grid, like this
 var data=context.Person;
 dataGridView1.dataSource = data;

Yes, the context.Person returns a list of Person-Objects
 and so in the Grid the Column 'FullName' is not available
How to create the List on myPerson-Objects?

A: First of all, if you're only creating FullName in order to display it in a grid, then I'd say it belongs in the UI layer, not the business layer.
Second, you don't need inheritance for this. You can use delegation. Give your UIPerson class an instance of Person in the constructor. Then, for each property of Person that you want to expose to the grid, do something like this:
public DateTime BirthDate
{
   get {return _person.BirthDate;}
   set {_person.BirthDate = value;}
}

ReSharper can do this for you, or you can use some other tool or do it by hand. You then get to add your FullName property the same way.


text:
Q: Rails - Devise: Change Password and send mail notify I am new to Ruby on Rails. I want to send a mail notification that you changed your password in Devise, but I have no idea how to. I finish the Change Password job by adding <%= link_to "Change your password", edit_user_registration_path%> to application.html.erb.

A: Since Devise 3.5.3 notify after change pasword functionality has been built-in, but it is disabled by default. To enable it, open config/initializers/devise.rb and make this change and restart your app.
- # config.send_password_change_notification = false
+   config.send_password_change_notification = true

https://github.com/plataformatec/devise/wiki/Notify-users-via-email-when-their-passwords-change

A: You want to use ActionMailer.
See the one of these guides for details:

*

*Rails guide on ActionMailer

*This tutorial on sending email using rails, or

*"Sending Email from Your App" in Heroku help

A: I think there are many gems available to send mails.
Try this: https://github.com/benprew/pony


text:
Q: sigaction handler does not close the process I have the following sigaction handler code
void signal_term_handler(int sig)
{
    int rc = async_lockf(pid_file, F_UNLCK);
    if(rc) {
        char piderr[] = "PID file unlock failed!\n";
        write(STDOUT_FILENO, piderr, (sizeof(piderr))-1);
    }
    close(pid_file);
    char exitmsg[] = "EXIT Daemon:TERM signal Received!\n";
    write(STDOUT_FILENO, exitmsg, (sizeof(exitmsg))-1);
    _exit(EXIT_SUCCESS); //async-signal-save exit
}

All the function calls in the above function are an async-signal-save. Even the async_lockf() is an async-signal-save:
/*
 * The code of async_lockf is copied from eglibc-2.11.3/io/lockf.c
 * The lockf.c is under the terms of the GNU Lesser General Public
 * Copyright (C) 1994,1996,1997,1998,2000,2003 Free Software Foundation, Inc.
 * This file is part of the GNU C Library.
*/

int async_lockf(int fd, int cmd)
{
    struct flock fl = {0};

    /* async_lockf is always relative to the current file position.  */
    fl.l_whence = SEEK_CUR;
    fl.l_start = 0;
    fl.l_len = 0;

    switch (cmd)
    {
        case F_TEST:
            /* Test the async_lock: return 0 if FD is unlocked or locked by this process;
             return -1, set errno to EACCES, if another process holds the lock.  */
            fl.l_type = F_RDLCK;
            if (fcntl (fd, F_GETLK, &fl) < 0)
                return -1;
            if (fl.l_type == F_UNLCK || fl.l_pid == getpid ())
                return 0;
            errno = EACCES;
            return -1;

        case F_ULOCK:
            fl.l_type = F_UNLCK;
            cmd = F_SETLK;
            break;
        case F_LOCK:
            fl.l_type = F_WRLCK;
            cmd = F_SETLK;
            break;
        case F_TLOCK:
            fl.l_type = F_WRLCK;
            cmd = F_SETLK;
            break;

        default:
            errno = EINVAL;
            return -1;
    }

    /* async_lockf() is a cancellation point but so is fcntl() if F_SETLKW is
     used.  Therefore we don't have to care about cancellation here,
     the fcntl() function will take care of it.  */
    return fcntl (fd, cmd, &fl);
}

the sigaction handler should close the application if I execute kill -15 command but some times I get the processus running and does not exit. this happens rarely. For example If I launch the application and then I stopped with kill -15 1000 times, this behaviour will happens only ~5 times
Any explaination for this strange behaviour? Why my application does not exist? Especially that I m using async-signal-save function (_exit()) to close the processus

A: To see what's happening, try attaching strace or gdb to the process and to see where it's stuck. My best guess is that you have code that's masking signals (sigprocmask) while performing a blocking operation, thus preventing the signal handler from running.


text:
Q: AngularJS Error: [$injector:itkn] Incorrect injection token! Expected service name as string, got undefined Trying to run an Angular app containing this controller:
routerApp.controller('chartSettingsCtrl', ['$scope', '$timeout',
 , function($scope, $timeout) { /* body omitted */ }

gives me the error:
Error: [$injector:itkn] Incorrect injection token! Expected service name as string, got undefined

What am I doing wrong?

A: The actual problem is that I had an extra , in the controller. When I changed that, it worked.
From
routerApp.controller('chartSettingsCtrl', ['$scope', '$timeout',
 , function($scope, $timeout) {

To
routerApp.controller('chartSettingsCtrl', ['$scope', '$timeout',
 function($scope, $timeout) {


text:
Q: How to explain the result of this polynomial equation? Lets say that I predicted plant productivity (logy) by precipitation (logx1) and moisture content of soil (logx2). my original data gives me the best result only after taking logarithm on both side of variables.
mod <- lm(logy ~ poly(logx1*logx2, 2, raw=TRUE)

then I got following coefficients from the model:
intercept=6.773;
logx1*logx2 poly(1) = 2.511;
logx1*logx2 poly(2) = 0.458

With regard to equation, I have 2 questions:
1. How I can explain the result of this equation
2. How to find the value when precipitation is 0.
Thanks in advance!

A: As you can see from the 3D scatterplot, the posted data seems rather noisy with both a "vertical" section and a "flat" section. The best I could find from an equation search was "Y = a * pow(X1, b) + c * pow(X2, d) + Offset" with fitted parameters a = 2.6908392707633102E+03, b = 3.4211996168376331E+00, c = 2.8379254883958050E+05, d = 2.8577605809712245E-04, and Offset = -2.8395222685511003E+05 giving RMSE = 154.6 and R-squared = 0.38


text:
Q: Automatically logs out the user upon session expiry I am having a Spring roo project that user Spring security for login and logout.My application has got 15 mins timeout. But after 15 mins idle the application is not automatically logging me out and redirecting to login page.
I got the below code in  applicationContextSecurity.xml
<session-management invalid-session-url="/login"/>

My application uses Rest services integrated with angular js.
Can someone please help in this?


text:
Q: How to i can fix issue in magento 2.1.2 (There has been an error processing your request)? When i install magento 2.1.2, after complete installation when i open front view of website then i'm getting this error again and again... i install my magento again and again but same issue is occurred.

Error: There has been an error processing your request Exception
  printing is disabled by default for security reasons.
Error log record number: 238886554

Please help me how to i can fix this issue.
 (Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY', query was: INSERT INTO customer_visitor (customer_id, session_id, last_visit_at) VALUES (?, ?, ?)";i:1;s:13034:"#0

Solution: TRUNCATE customer_visitor table from database.


text:
Q: Vector Graphics in iOs? i have a vector logo that i want to include in my view. I created a png out of it and put it into an imageView. Unfortunately, the logo in the simulator then is of poor quality, even though it looks fine in Interface Builder.
Do you have a recommendation how to solve that problem? Can i embed the eps in my app?

A: You could probably convert the eps to SVG and load it in a UIWebView.


text:
Q: Java: Allocation of new objects and cache coherency In Java, suppose you have two threads T1 and T2 running simultaneously on two different processors P1 and P2.
At first, thread T2 works with some object obj that is allocated at (say) starting memory location 0x1000. This causes P2 to internally cache the value at that memory location. T2 then nulls out the (only) reference to the object and it is garbage collected.
Thread T1 then does
    Foo fooRef = new Foo();
    fooRef.x = 10;

and it just happens that fooRef.x's location is also at 0x1000, because this instance of Foo was allocated re-using memory that was freed by T2 above.
T1 then passes the fooRef reference to thread T2 (via a queue, or some other shared memory mechanism).
Will T2 see the old stale cached value from before, or will it see the new value of 10?
Let's say there is no hardware cache coherency mechanism. Does Java itself ensure the clearing of every processors' cache when it deallocates or allocates memory for an object? (Even with a hardware cache coherency mechanism in place, the coherency propagation is not instantaneous, and T2 might still happen to read the stale value, if no other coherency measures by Java itself are taken).

A: If you don't properly synchronise, then T2 could in principle see one of three things (not necessarily with equal probability):

*

*(a) an apparently correctly formed object, but containing incorrect data;

*(b) an object that isn't properly formed in the first place (i.e. never mind your data, the actual housekeeping metadata belonging to the object is not properly visible, potentially causing "bad things to happen");

*(c) accidentally, you "dodge the bullet" as it were and T2 sees the object as T1 left it.
If you properly synchronise (or put another way, properly publish the object) then T2 will see the object as T1 defined it. In this article on the final keyword and further articles linked to at the bottom, I discuss some of the issues and solutions. Some of this answers to this previous question on What is object publishing and why do we need it? may also help.
So, practically[*] all of the time, you need to properly synchronise. It is dangerous to try and guess which of the situations (a), (b) or (c) will occur if you don't properly synchronise.
[*] There are very occasional advanced techniques where synchronisation can be safely avoided if you can genuinely calculate all of the possible "paths" resulting from lack of synchronisation, such as a technique referred to as synchronisation piggybacking where you effectively know that synchronisation will be performed 'in time' somewhere else. I recommend you don't go down this route!

A: You will not see "junk" left over from the first object.
Each primitive in the object will contain either its initial value (0, false, etc) or some value that had been put there at some point -- though reordering may produce weird mixes of values. Additionally, if a primitive is a two-word value (long or double), you may see only one of those words updated: this could produce a value that no thread has ever put there, but it's consistent with the above in that you are seeing the effects of a write to this object -- you're just not seeing all of that write. But you're still not seeing the effects of a write on some totally other, random object.
For reference values, you'll either see the initial value (null) or a correct reference to a constructed object -- though that object's values are subject to the same vague rules as above (they can be either the initial value or any other value some other thread has put in, with reorderings etc allowed).
Now, I can't actually find the exact place in the JLS where this is written. But there are several parts that strongly imply it. For instance, JLS 17.4.5 states in an example:

Since there is no synchronization, each read can see either the write of the initial value or the write by the other thread.

Emphasis mine, but note that it lists the values that the read can see; it doesn't say "each read can see anything, including junk bytes left over from previous objects."
Also, in 17.4.8, another example states:

Since the reads come first in each thread, the very first action in the execution order must be a read. If that read cannot see a write that occurs later, then it cannot see any value other than the initial value for the variable it reads.

(Emphasis mine again). Note that this, though it's in an example and not in the "main" body, explicitly says that junk reads as you describe is not allowed.
And then, JLS 17.7 is all about the non-atomicity of 64 bit primitives (the long and double values I mentioned above). Again, if there were absolutely no guarantees about the bytes you see, then it wouldn't be meaningful to note that you can see one word from one write and another word from another write. In other words, the fact that the JLS says that you can see "broken" values that arise from only one word being updated, is a strong suggestion that you can't see "broken" values that arise from just complete left-over junk.

A: Java has no access to the underlying hardware cache, so it does not "ensure the clearing of every processsor's cache".
Most modern, real CPUs provide for cache coherency.  Some real CPUs require a memory barrier under some circumstances.  Your hypothetical CPU without a hardware mechanism will likely suffer from a stale cache under the conditions described.

A: As long as the accesses to fooRef and fooRef.x are properly synchronized, thread T2 will see the latest value of fooRef.x, i.e., 10.


text:
Q: What are the benefits of a "deep" over a "shallow" architectures? What are the benefits of a deep neural network architecture over a shallow architecture with many computational elements.
What are pros and cons of these two architectures and its limitations?


text:
Q: eclipse google cloud from appengine sdk migration problem Eclipse luna to Eclipse 2018 migration problem.
Switching to compiler to java jdk8. I get a lot of import problems such as javax. Also migrating from appengine sdk to google cloud the convertion to appengine project fails with the error: a problem occured
Bundle: org.eclipse.jface 3.14.0.v20180423-0714
Message: java.lang.RuntimeException: java.lang.NullPointerException
Exception:
java.lang.RuntimeException: java.lang.NullPointerException
    at org.eclipse.wst.common.project.facet.ui.internal.RuntimesPropertyPage.performOk(RuntimesPropertyPage.java:207)
    at org.eclipse.jface.preference.PreferenceDialog$7.run(PreferenceDialog.java:902)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.ui.internal.JFaceUtil.lambda$0(JFaceUtil.java:44)
    at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:173)
    at org.eclipse.jface.preference.PreferenceDialog.okPressed(PreferenceDialog.java:886)
    at org.eclipse.ui.internal.dialogs.FilteredPreferenceDialog.okPressed(FilteredPreferenceDialog.java:484)
    at org.eclipse.jface.preference.PreferenceDialog.buttonPressed(PreferenceDialog.java:230)
    at org.eclipse.jface.dialogs.Dialog.lambda$0(Dialog.java:619)
    at org.eclipse.swt.events.SelectionListener$1.widgetSelected(SelectionListener.java:81)
    at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:249)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:86)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4118)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1052)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3931)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3534)
    at org.eclipse.jface.window.Window.runEventLoop(Window.java:818)
    at org.eclipse.jface.window.Window.open(Window.java:794)
    at org.eclipse.ui.dialogs.PropertyDialogAction.run(PropertyDialogAction.java:157)
    at org.eclipse.jface.action.Action.runWithEvent(Action.java:473)
    at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:565)
    at org.eclipse.jface.action.ActionContributionItem.lambda$4(ActionContributionItem.java:397)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:86)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4118)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1052)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3931)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3534)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$5.run(PartRenderingEngine.java:1170)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1059)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:153)
    at org.eclipse.ui.internal.Workbench.lambda$3(Workbench.java:667)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:597)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:152)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(null:-2)
    at sun.reflect.NativeMethodAccessorImpl.invoke(null:-1)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(null:-1)
    at java.lang.reflect.Method.invoke(null:-1)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:656)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:592)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1498)

caused by java.lang.NullPointerException: null
    at org.eclipse.wst.common.project.facet.ui.internal.RuntimesPropertyPage$4.run(RuntimesPropertyPage.java:161)
    at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:2289)
    at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:2316)
    at org.eclipse.wst.common.project.facet.ui.internal.RuntimesPropertyPage$5.run(RuntimesPropertyPage.java:175)
    at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:119)


text:
Q: How to multi-match two tables efficiently? I'm relatively new to database-design and want to create a SQLite database for an application. The application needs to handle lots of objects and assign them to a smaller list of categories. Both tables have multiple columns. The problem is, that every object may belong to an indefinite amount of categories and I need to query both efficiently: All objects that belong to a specific category and for any object to which categories it belongs, which is why I can't just use joins.
My idea was to create a third table with just two columns, matching objects to categories. But it looks like an ugly solution to me and I also don't know what indices I should set upon it, if any at all. I might end up with the key column's data being saved four times: In the original table, in its PRIMARY KEY, in the matching table, and in the index on that table.
Is there a better approach or maybe even a standard method to handle such situations?

A: 3-table scheme is the most compatible. 3rd table will look like:
CREATE TABLE jointable
(
    obj_id,
    cat_id,

    PK (obj_id, cat_id),
    FK (obj_id) REF obj (id),
    FK (cat_id) REFcat (id)
);


text:
Q: Formation of commissions Of a group of seven women, Mary is one of them, and of four men, John is one of them. How many commissions can be formed with any number of people, provided there are the same number of men and women?
I did so:
4 men and 4 women:
$${7 \choose 4}  { {4} \choose {4} }  = 35 $$
3 men and 3 women:
$${7 \choose 3}  { {4} \choose {3} }  = 140 $$
2 men and 2 women:
$${7 \choose 2}  { {4} \choose {2} }  = 126 $$
1 man and 1 woman:
$${6 \choose 1}  { {4} \choose {1} }  = 24 $$
By the additive principle, it comes: $$35 + 140 + 126 + 24 = 325$$
The answer is 329. Have I forgotten a case or addressed the problem in the wrong way?