text:
Q: Program received signal sigsegv segmentation fault Fiz o código em C do enunciado:

Elabore um programa que simule um sistema de emissão de bilhetes de uma
  companhia aérea. A companhia possui n vôos, onde em cada um deles existem m
  lugares disponíveis. Os primeiros m/2 lugares de cada vôo estão reservados para não fumantes e o restante para fumantes.
Utilize uma matriz de n linhas por m colunas para representar os assentos dos vôos desta companhia. Inicialize os elementos da matriz com zero para indicar que todos os assentos de cada um dos n vôos estão disponíveis. À medida que os assentos forem sendo ocupados atribua 1 ao elemento correspondente da matriz.
Devem ser gerados aleatoriamente:

*

*O número de vôos.

*O número de passagens solicitadas por vôo.

*Se o passageiro é da área dos fumantes ou dos não fumantes.
  O programa devera imprimir no final da simulação:

*O número médio de passageiros por vôo.

*O número médio de passageiros por área em cada vôo

*O Número médio de passageiros não embarcados por falta de assento (observe
  que pode haver lugar no avião, mas não haver lugar na área solicitada)

Já usei o debug mas não consigo identificar o motivo do erro: Program received signal sigsegv segmentation fault Já mudei e coloquei de diversas formas o iniciar gerador de numeros aleatórios, usando NULL por exemplo, mas não adianta. srand(time(NULL)), abaixo o código:
main() {

  int n,m,p, i, j, matriz[n][m],f,assento_ocup,aux,fumantes,nao_fumantes;
  float media_passageiros_voo, media_passageiros_area,media_pas_falta_assento,
  media_passageiros_nao_fumantes_area, media_passageiros_fumantes_area;
  time_t t;

  // iniciar gerador de numeros aleatórios
  srand((unsigned)time(&t));

  //numero de voos-linhas
  n=rand()%1+500;

  //numero de lugares-colunas
  m= rand()%1+100;

  //numero de passagens solicitadas
  p= rand()%1+100;

  for(i=0; i<n; i++)  { //linha-voos
    for(j=0; j<m; j++){//coluna-passagens
        matriz[n][m]=0;//todos assentos disponiveis
    }
  }

  if(f%2==0){//se par nao e fumante
    for(i=0; i<n; i++)  {
        for(j=0; j<m/2; j++){
              matriz[i][j]=1;
              nao_fumantes++;
            }
    }
  }
  else{ //e fumante
    for(i=0; i<n; i++)  {
        aux=((m/2)+1);
        for(j=aux; j<m; j++){
            matriz[i][j]=1;
            fumantes++;
        }
    }
  }

  for(i=0; i<n; i++)  {
    for(j=0; j<m; j++){
        if(matriz[i][j]==1){
            assento_ocup++;
        }
    }
  }

  media_passageiros_voo=assento_ocup/n;

  media_pas_falta_assento= m-p;

  media_passageiros_fumantes_area= fumantes/(m/2);
  media_passageiros_nao_fumantes_area= nao_fumantes/(m/2);

  printf("\n MEDIA DE PASSAGEIROS POR VOO:%.2f ",media_passageiros_voo);
  printf("\n MEDIA DE PASSAGEIROS POR AREA EM CADA VOO: %.2f", media_passageiros_area);
  printf("\n PASSAGEIROS NAO EMBARCADOS POR FALTA DE ASSENTO",media_pas_falta_assento);

  getche();

}

A: Primeiramente, não se usa variáveis em declarações de tamanhos de arrays, ainda mais antes mesmo de defini-las, como você fez em matriz[n][m]. Coloque números inteiros como tamanhos ou defina suas próprias constantes com #define e faça algo do tipo
matriz[LINHAS_MAX][COLUNAS_MAX]

E, claramente, a seguinte linha está errada (provavelmente por erro de digitação):
matriz[n][m]=0;//todos assentos disponiveis

Deveria ser matriz[i][j] no lugar.


text:
Q: "Assembly will not load due to errors" Unity Делаю приложение на Unity, в котором нужно использовать базу данных, которая хранится на хостинге. При попытке добавить библиотеку MySql.Data в папку с проектом, чтобы использовать её в C#-скрипте, но после добавления .dll файла получаю ошибку:
Assembly 'Assets/Libraries/MySql.Data.dll' will not be loaded due to errors:
Unable to resolve reference 'Google.Protobuf'. Is the assembly missing or incompatible with the current platform? Reference validation can be disabled in the Plugin Inspector.
Unable to resolve reference 'Zstandard.Net'. Is the assembly missing or incompatible with the current platform? Reference validation can be disabled in the Plugin Inspector.
Unable to resolve reference 'K4os.Compression.LZ4.Streams'. Is the assembly missing or incompatible with the current platform? Reference validation can be disabled in the Plugin Inspector.
Unable to resolve reference 'BouncyCastle.Crypto'. Is the assembly missing or incompatible with the current platform? Reference validation can be disabled in the Plugin Inspector.
Unable to resolve reference 'Ubiety.Dns.Core'. Is the assembly missing or incompatible with the current platform? Reference validation can be disabled in the Plugin Inspector.
Unable to resolve reference 'Renci.SshNet'. Is the assembly missing or incompatible with the current platform? Reference validation can be disabled in the Plugin Inspector.

При это, если я добавлю using MySql; в любой C#-скрипт, то приложение просто не запускается.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Symmetrize a histogram plot or array? I have a histogram that runs from -5 to 5 that I can manipulate and plot as I please, and I use the following PDF's to run one-sample KS tests on it: norm, cauchy, students t, laplace.
However, I have to symmetrize the data (make it go from only 0 to 5) and run KS tests on that. Which is fine for norm and cauchy.. but I cannot find a "half students t" PDF in scipy.stats
So I would really appreciate your help either:
1) in how to plot a histogram going from 5, 4, 3, 2, 1, 0, 1, 2, ... back on up, where there are no negatives, that doesn't just show 0 to 5 and I can just set loc=0 as per usual for my KS test. (I wish I could just do a plt.MirroredAboutX() or something?) Or,
2) does anyone know if a half students t PDF is hiding somewhere I glossed over?
Thanks!
Edit: Giving clarification to #1 above, using this list
l = [-1.93067027 -1.00267766 -0.6349767  -0.82698775 -0.59277326 -0.67801007 -0.60888202 -0.27387228 -0.03645225 -0.02120668  0.02004329  0.40640109 0.661673 0.77414735  0.86466529  0.53162743  0.64943555  0.7827397 1.8450599   1.44000795]

plt.hist(l) shows me a histogram from -2 to 2,

and plt.hist(np.abs(l)) shows me a histogram from 0 to 2.

I want the histogram that goes from 0 to 2, to now be mirrored/flipped over the y-axis so that the range of the x-axis is from 2 to 2 (since it's centered at 0) and it is this nice symmetric, plotted histogram.

A: You may plot a bar chart of the results of a numpy histogramming. You can then invert the arrays to plot a mirrored version of them.
import matplotlib.pyplot as plt
import numpy as np

l = "-1.93067027 -1.00267766 -0.6349767 -0.82698775 -0.59277326 -0.67801007 -0.60888202 -0.27387228 -0.03645225 -0.02120668  0.02004329  0.40640109 0.661673 0.77414735  0.86466529  0.53162743  0.64943555  0.7827397 1.8450599   1.44000795"
l = np.array(list(map(lambda x: float(x),l.split() )))

step = 0.25
bins = np.arange(0,2.01, step)
hist, edges = np.histogram(np.abs(l),bins=bins)

plt.bar(bins[:-1], hist, width=step, align="edge", ec="k")

plt.bar(-bins[::-1][:-1], hist[::-1], width=step, align="edge", ec="k")

plt.show()

Note that doing this, the y axis has lost its quantitative meaning, as each values is accounted for twice in the mirrored plot.


text:
Q: Is this a correct implementation of Q-Learning for Checkers? I am trying to understand Q-Learning,

My current algorithm operates as follows:
1. A lookup table is maintained that maps a state to information about its immediate reward and utility for each action available.
2. At each state, check to see if it is contained in the lookup table and initialise it if not (With a default utility of 0).
3. Choose an action to take with a probability of:
    (*ϵ* = 0>ϵ>1 - probability of taking a random action)
    1-ϵ = Choosing the state-action pair with the highest utility.
    ϵ = Choosing a random move.
    ϵ decreases over time.

4. Update the current state's utility based on:
    Q(st, at) += a[rt+1, + d.max(Q(st+1, a)) - Q(st,at)]

I am currently playing my agent against a simple heuristic player, who always takes the move that will give it the best immediate reward.
The results - The results are very poor,  even after a couple hundred games, the Q-Learning agent is losing a lot more than it is winning. Furthermore, the change in win-rate is almost non-existent, especially after reaching a couple hundred games.
Am I missing something? I have implemented a couple agents:
(Rote-Learning, TD(0), TD(Lambda), Q-Learning)
But they all seem to be yielding similar, disappointing, results.

A: There are on the order of 10²⁰ different states in checkers, and you need to play a whole game for every update, so it will be a very, very long time until you get meaningful action values this way. Generally, you'd want a simplified state representation, like a neural network, to solve this kind of problem using reinforcement learning.
Also, a couple of caveats:

*

*Ideally, you should update 1 value per game, because the moves in a single game are highly correlated.

*You should initialize action values to small random values to avoid large policy changes from small Q updates.


text:
Q: Video is uploaded as an image from iOS device, how to upload properly I have an app that gets the images/videos from the mobile gallery, then uploads one of them to a server,
here are the steps i take, which works fine on Android:
1-get data from mobile storage:
MediaLibrary.getAssetsAsync({
  first: 20,
  mediaType: [MediaLibrary.MediaType.video, MediaLibrary.MediaType.photo]
})

2-upload to server:
formData.append('images[]', {
    uri: localUri,
    name: isVideo ? 'untitled.mp4'  : 'untitled',//for testing
    type: isVideo ? 'video/mp4' : 'image/jpeg'
})

axios.post(`url`, formData, {headers: headers,timeout:999999})

The problem is videos are uploaded as an image (only the first frame of the video), while it gets uploaded successfully on Android, the problem is only present on iOS.
The uri of the retrieved files is as follows:
assets-library://asset/asset.MP4?id=xxx&ext=MP4
Quick notes:
1 - the video is played fine locally using the <Video> component from Expo
2 - i tried using the CameraRoll API, but it gives the same results, and is a little buggy
any help would be appreciated

A: You can update to expo SDK 36 and you will be able to solve this problem by using localUri returned by MediaLibrary.getAssetInfoAsync
ex.
// get asset id like B84E8479-475C-4727-A4A4-B77AA9980897/L0/001
const info = await MediaLibrary.getAssetInfoAsync(asset.id)
const uri = info.localUri // use this for upload

Reffer this comment on github.
https://github.com/expo/expo/issues/3177#issuecomment-510096711


text:
Q: How can I increase OpenFabrics memory limit for Torque jobs? When I run MPI job over InfiniBand, I get the following worning. We use Torque Manager.
--------------------------------------------------------------------------
WARNING: It appears that your OpenFabrics subsystem is configured to only
allow registering part of your physical memory.  This can cause MPI jobs to
run with erratic performance, hang, and/or crash.

This may be caused by your OpenFabrics vendor limiting the amount of
physical memory that can be registered.  You should investigate the
relevant Linux kernel module parameters that control how much physical
memory can be registered, and increase them to allow registering all
physical memory on your machine.

See this Open MPI FAQ item for more information on these Linux kernel module
parameters:

http://www.open-mpi.org/faq/?category=openfabrics#ib-locked-pages

Local host:              host1

Registerable memory:     65536 MiB

Total memory:            196598 MiB

Your MPI job will continue, but may be behave poorly and/or hang.

--------------------------------------------------------------------------

I've read the link on the warning message, and I've done so far is;

*

*Append options mlx4_core log_num_mtt=20 log_mtts_per_seg=4 on /etc/modprobe.d/mlx4_en.conf.

*Make sure the following lines are written on /etc/security/limits.conf

*

** soft memlock unlimited

** hard memlock unlimited

*Append session    required     pam_limits.so on /etc/pam.d/sshd

*Make sure ulimit -c unlimited is uncommented on /etc/init.d/pbs_mom
Can anyone help me to find out what I'm missing?

A: Your mlx4_core parameters allow for the registration of 2^20 * 2^4 * 4 KiB = 64 GiB only. With 192 GiB of physical memory per node and given that it is recommended to have at least twice as much registerable memory, you should set log_num_mtt to 23, which would increase the limit to 512 GiB - the closest power of two greater or equal to twice the amount of RAM. Be sure to reboot the node(s) or unload and then reload the kernel module.
You should also submit a simple Torque job script that executes ulimit -l in order to verify the limits on locked memory and make sure there is no such limit. Note that ulimit -c unlimited does not remove the limit on the amount of locked memory but rather the limit on the size of core dump files.


text:
Q: How to Upgrade Memory From 2Gb To 8Gb?
Possible Duplicate:
How can I enable PAE on Windows 7 (32-bit) to support more than 3.5 GB of RAM?

I have a laptop which has 2GB DDR III RAM, 520MX 1GB Graphic, and Intel Core i3-2310M CPU @ 2.10GHz.
I use W7 32bit (I don't want to use 64bit W7), and I don't have enough RAM for some applications something like I am using Virtual Machines, MS Office 2010, PS5, CorelDraw X5, Nero 11, MS Visual Studio 2010, and many others. So I added two 4GB RAM for the machine. But I found that only 2.66GB usable instead of 8.00GB. Is there anything else I need to change in my system?

A: Your system has 1 GiB of graphics memory, and only 32 bits with which to address memory.
That means you have 232 - 230 = 3 GiB of address space left.
Subtracting away other device ranges and the amount of RAM that the OS needs, that leaves you with the ~2.6 GiB you mentioned.
Of course, applications probably won't be able to even use that much, because 1 GiB of address space is reserved for the kernel.


text:
Q: When inserting a result of a query, how do I insert random exact numbers? I can use IDENTITY to generate unique ID numbers, but is there a way to generate a completely random number when inserting data? Currently, all ID's start with "1000"
Here is my original table:
CREATE TABLE Badges
(ID INTEGER IDENTITY(1000000000,23),
EmpID INTEGER NOT NULL,
EmpName nvarchar(50) not null,
EmpLastName nvarchar(50) not null,
IssueDate date default getdate(),
Validity char(1) default 'Y',
CONSTRAINT STATUS_CHECK check (Validity in ('Y','N')))

Below is my attempt to set up random ID number generation. I also tried to nest RAND into IDENTITY, but it did not work. Probably incorrect syntax, not so sure.
CREATE TABLE Badges
(Badge_ID INTEGER DEFAULT ROUND(RAND()*100000000,0) UNIQUE,
EmpID INTEGER NOT NULL,
EmpName nvarchar(50) not null,
EmpLastName nvarchar(50) not null,
IssueDate date default getdate(),
Validity char(1) default 'Y',
CONSTRAINT ID_status CHECK(Validity in ('Y','N')));

For a test, I tried inserting all employees from department 8 but now it generates the same Badge_ID number for everybody, at least if I insert employees in bulk and not one by one.
INSERT INTO Badges (EmpID, EmpName, EmpLastName)
SELECT EmployeeID, FirstName, LastName FROM HR.Employee WHERE DepartmentID = 8


text:
Q: Problem while installing virtualenv on AWS Ubuntu 18.04 AMI How to install virtualenv properly on AWS Ubuntu 18.04 AMI. I have tried various ways such as through pip and through apt-get but I am not able to either properly install or configure it. Whenever I am running command virtualenv --python=python3.6 .venv or virtualenv --version it is giving me this error:
ERROR:root:failed to read config file /home/ubuntu/.config/virtualenv/virtualenv.ini because PermissionError(13, 'Permission denied')

How to properly install and configure virtualenv?

A: First check if Python3 is installed
apt list installed | grep -i python3

After that
python3 -m venv my_app/env


text:
Q: Losing Tracking data with reference content We've just recognized, that when using a reference content block within content builder, all tracking data i.E. link clicks will be lost in email send report. Is there an way to get the data?
I actually see the referenced content block in the tracking send but so link clicks behind it.

A: The links seem to be trackable. For the testing, I created a test content with one link embedded. Then I referenced the content in Email via

%%=ContentBlockbyID("26127")=%%

(this got autogenerated as soon as I referenced the content). When I did the send and clicked on the link, I can see one click count in tracking report.
Thanks
Chandan


text:
Q: insert or update(upsert) in loopback application I developed an API using Loopback framework, in that i have to insert or update to a table.
My table looks like below:
userid  bbid saved  id(PK)
  1      5    1000   1

So when next time if(bbid = 5) it should update the above row, if bbid =5 is not there it should insert into the above table.
I tried the following:
app.models.modelname.upsert({
  bbid: bb.id,
  saved: Saved,
  userid: 1
}, function(err, res) {});

EDIT for COMPOSITE ID:
app.models.modelname.upsert({
  bbid: vvvv.bbid,
  userid: 1,
  saved: amountSaved
}, function(err, res) {});

Also gone through Loopback doc it says
    upsert - checks if the instance (record) exists, based on the designated
ID property, which must have a unique value; if the instance already exists,
the method updates that instance.  Otherwise, it inserts a new instance.

But in my case it should check for bbid not id
But its inserting everytime. Please share your ideas. Thanks in advance
EDIT FOR UPSERT:
My process is as follows:
Fetch from table1 and loop that response and calculate the saved and upsert it into another table(table2 (this is where upsert should happen)). Also the fetching from table1 will happen frequently so suppose consider if is happens 2nd time it should update the already present bbid..

A: You can use the findOrCreate method as follows:
app.models.modelname({where: {bbid:bb.id} }, {bbid:bb.id, saved: Saved, userid:1}, function(err, instance) {
    if (err){
        cb(null, err);
    }
        cb(null, instance);
    });

A: There are two methods in loopback one is simple upsert and second is upsertWithWhere.To insert or update based on where condition you must use upsertWithWhere method upsert only inserts the data.
you are using
app.models.modelname.upsert({bbid:bb.id, saved: Saved, userid:1}
          ,function(err, res){});

instead use
app.models.modelname.upsertWithWhere({bbid:bb.id, saved: Saved, userid:1}
          ,function(err, res){});

this will solve your problem.
note: this only updates single instance.If multiple instances are returned in where condition result it will throw an error.


text:
Q: how to get first and last element from array guys i am storing dates like these 07/01/2016, 07/02/2016, 07/03/2016, 07/04/2016 in db
and when i fetch these dates from db using mysql_fetch_array()
the result is the whole array now i want to get only the starting and ending date i.e  07/01/2016 and
07/04/2016...i tried using explode function but explode function breaks a string into an array...and i am unable to find a String To Array function in php...Kindly help me and tell me what should i do...
   $leave_dates=$_POST['dates'];
   $check_dates=explode(',', $leave_dates);
    foreach ($check_dates as $date)
{
    # code...
    $count_dates=count($date);
    //THIS GIVES THE COUNT OF DATES E.G 4
    NOW I WANT TO ACCESS THE FIRST AND THE LAST ELEMENT

}

A: You could use reset and end
$firstDate = reset($check_dates);
$lastDate = end($check_dates);

A: here's the potential solution:
$leave_dates=$_POST['dates'];
$check_dates=explode(',', $leave_dates);
//To obtain the first element
$first_element=$check_dates[0];
//To obtain the last element
$last_element=$check_dates[count($check_dates)-1];

A: You can try this
<?php
$row = array('07/01/2016','07/02/2016','07/03/2016','07/04/2016');
$total = count($row);
echo $row[0];
echo "<br>";
echo $row[$total-1];

output
07/01/2016
07/04/2016

A: you can also use array_shift and array_pop
$first_element = array_shift($check_dates);
$last_element = array_pop($check_dates);

A: try this
$firstDate = current($count_dates);
$lastDate = end($count_dates);

A: Best way is to work out on Queries.
select * from table_name
where id = (select id from tab1 order by col1 asc limit 1) or
id = (select id from tab1 order by col1 desc  limit 1);

A: try this ,
<?php

    $check_dates=array('2016-5-11','2016-8-4','2016-4-9');
    $firstDate = current($check_dates);
    $lastDate = end($check_dates);

    print_r($firstDate);
    print_r($lastDate);

?>

Output will be :
 2016-5-11
 2016-4-9

A: Since you store all the value in an array named $check_dates. You can access the first element of an array with index 0
$firstlement=$check_dates['0'];

To access the last element of an array, you can use end function.
$lastement=end($check_dates);


text:
Q: Statistical Weighting Factor on thermal neutron importance The problem is concerning the use of a thermal fluxed squared weighting factor in a thermal reactor.
I have seen in sources the thermal flux in a reactor is squared as a statistical weighting factor, for example looking at temperature feedback. Say a number of thermocouples are measured in a reactor, the weighting of the importance of the thermocouples are to flux squared. Why is this when the reaction rate is equal to the flux? Is it simple statistics I'm not understanding.

A: $$
\Delta \rho \cong -\frac{\int_V \! \mathrm{d}^3r \phi(\mathbf{r}) \Sigma_a(\mathbf{r}) \phi(\mathbf{r})} {\int_V \! \mathrm{d}^3r \phi(\mathbf{r}) \Sigma_f(\mathbf{r}) \phi(\mathbf{r})}
$$
It seems like because of a result of one group perturbation theory. Page 223 of J. Duderstadt Nuclear Reactor Analysis. Since the temperature feedback is changing the thermal utilisation, which is the ratio between the absorbed and utilised thermal neutrons.

A: Well lets examine the situation that your are describing.  When talking about anything 'thermal', one is referring to 'heat'.  Heat can come in at least two forms that I am aware of.  Radiative and Kinetic.  Photons, of a thermal nature, come from the infrared spectrum of light.  While any photon can impart energy into a material, it has to be provided that the material absorbs the photon.  Temperature is a measure of a rate of Kinetic Energy transferred from a system high in KE to a system of lower KE. Matter vibrates, or rather the molecules in matter vibrate.  The level of this vibration can be measured as Black-body Radiation.  Objects in the same system, at equilibrium, if they are not active sources, will emit the same level of Black-body radiation.  If there is an active source of light, that is illuminating the non-active objects, they will emit differing levels of Black-body Radiation, due to any differentiating material qualities.
All objects, that have form, fit and function, have a surface.  The 'Flux' of anything is related as a function of surface, a 2D concept. As an example of this is the Magnetic Flux of the surface of a magnet.  The more lines of force per unit of surface area, the stronger the magnet.  The number of lines of force coming in and out of the surface of the magnet is the Magnetic Flux.  In the case of thermal photons, it would be the number of photons hitting the surface of a sensor, such as a thermocouple, per some unit of time, usually a second.  In the case of a thermometer, such as a Mercury thermometer, the Kinetic energy 'flux' of the material being measured, such as boiling water, in contact with the surface of glass that makes up the body of the thermometer, transmits that KE through the glass and into the mercury, which then expands, dependent upon the rate of transfer.  The transfer rate, equal to the flux, is dependent upon the rate of the generation of what makes-up the 'flux', be it boiling water, photon density, or thermal neutrons.
Often one has a volume of something to content with, and measurements are often taken on a cross-section of that volume, the cross-section is a 2D concept.  A single thermocouple, as a source of measurement, is considered a point concept.  If you have at least three of them in a volume, then you can define a triangle of surface within the volume, a cross-section if you will, thus a 2D concept.  Any distance squared will give you a function of area, a 2D concept, so the flux is squared as well.
Δρ≅−(∫ V d 3 rϕ(r)Σ a (r)ϕ(r)) / (∫ V d 3 rϕ(r)Σ f (r)ϕ(r))   is given as a function of volume, and is given as a unit-less ratio, but could be considered as a difference in 'degrees' just like the lines on the thermometer, indicate a change in volume of the mercury, thermocouples give a difference in electrical output in millivolts, which get translated into a temperature.  Typically here you have 2 cross-sections, each having a given flux, and there is a difference of flux between each cross-section, but still is referenced as an 2D concept, even though one is taking the temperature, say in degrees, a degree is not easily translated into actual units of distance, time, or mass.


text:
Q: How to give two indentical combo one on grid headr and one as grid column widget for store filter I have one widget column header by which I am selecting the value and filtering the grid store. I want exact the same on grid header as well. There for I am giving one combo with same values.
Here is my code for column header
header: {
    items: [{
            xtype: 'combo',
            displayField: "displayName",
            fieldLabel: 'Some Label',
            valueField: 'title',
            displayField: 'title',
            hidden : true,
            queryMode: 'local',
            value : 1,
            autoSelect : true,
            //dataindex:"MUTST",
            store: {
            fields: ["id", "displayName"],
            data: [
                    { "id": "1", "title": "Test1" },
                    { "id": "2", "title": "Test2" },
                    { "id": "3", "title": "Test3" }
                ]
            },
            listeners : {
                select : function(combo , record , eOpts){
                    debugger;
                    var sg = this.up("MyGrid");
                    var col = sg.getColumns()[0]; // Getting Header column
                    var flit =sg.getColumns()[0].filter // Here I am getting object instead of constructor
                    //this.focus = sg.onComboFilterFocus(combo);
                }
            },
        }]
},

I am creating widget type in column
MyColumn: function(headersXmlDoc) {
    var me = this,
        gridConfig = {};

    gridConfig.columns = [];
    Ext.each(headersXmlDoc.getElementsByTagName("HEADER"), function(header) {
        var column = {
            text: header.getAttribute("L"),
            dataIndex: header.getAttribute("DATAINDEX"),
            sortable: (header.getAttribute("ISSORTABLE").toLowerCase()=="true"),
            widgetType: header.getAttribute("WIDGET"),
            filterType: Ext.isEmpty(header.getAttribute("FILTER"))? undefined: header.getAttribute("FILTER"),
        };
        switch (header.getAttribute("WIDGET")) {
            case 'textbox':
                if(column.filterType){
                    if(column.filterType == 'TagData'){
                        column.filter = {
                            xtype: 'tagfield',
                            growMax  : 10,
                            valueField: 'title',
                            displayField: 'title',
                            parentGrid : me,
                            dataIndex:header.getAttribute("DATAINDEX"),
                            queryMode: 'local',
                            multiSelect: true,
                            isFilterDataLoaded: false,
                            disabled: true,
                            listeners:{
                                focus: me.SomeMethod, //
                            }
                        };
                    }
                }
                break;

        }
        this.columns.push(column);
    }, gridConfig);

    return gridConfig.columns;
},

I want if I select in header combo, it will directly select in widget combo as well. Can anyone explain how to get this. Thanks in advance

A: So you basically need a combo box in your header, that changes record values - the fact that you have a widget column displaying a combo within the grid cells doesn't really matter here.
I think you were fairly close - but you were trying to define a "header" config and add the combo to its items - instead you just define items directly on the column:
columns: [{
    text: 'Combo Test',
    dataIndex: 'title',
    items: [{
        xtype: 'combobox',
        width: '100%',
        editable: false,
        valueField: 'title',
        displayField: 'title',
        queryMode: 'local',
        autoSelect: true,
        store: {
            data: [{
                "id": "1",
                "title": "Test1"
            }, {
                "id": "2",
                "title": "Test2"
            }, {
                "id": "3",
                "title": "Test3"
            }]
        },
        listeners: {
            select: function (combo, selectedRecord) {
                //we could just get the value from the combo
                var value = combo.getValue();
                //or we could use the selectedRecord
                //var value = selectedRecord.get('id');

                //find the grid and get its store
                var store = combo.up('grid').getStore();

                //we are going to change many records, we dont want to fire off events for each one
                store.beginUpdate();
                store.each(function (rec) {
                    rec.set('title', value);
                });
                //finish "mass update" - this will now trigger any listeners for saving etc.
                store.endUpdate();

                //reset the combobox
                combo.setValue('');
            }

        }
    }],
},

The actual setting of values happens in the select listener as you were trying - the key is to loop through the records and call set on each one:
//find the grid and get its store
var store = combo.up('grid').getStore();

//we are going to change many records, we dont want to fire off events for each one
store.beginUpdate();
store.each(function (rec) {
    rec.set('title', value);
});
//finish "mass update" - this will now trigger any listeners for saving etc.
store.endUpdate();

I have created a fiddle to show this working:
https://fiddle.sencha.com/#view/editor&fiddle/1r01


text:
Q: Execute Django shell command as cron I'm try to Execute Django shell command as cron,
I have some queries and objects tasks to search and read and write using the models and queries of my django app.
How can I  execute this 1 or 2 times a day?
For example, how can I run these queries periodically:
from django.contrib.auth.models import User
from perfil.models import *

for user in usuarios:
        profiles = Perfil.objects.filter(user=user)
        create_task = Task.objects.create(user=user)

A: Take a look at Custom management commands for django.
As a basic example:
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from perfil.models import *

class Command(BaseCommand):

    help = 'What does this do? '

    def handle(self, *args, **options):
        for user in usuarios:
            profiles = Perfil.objects.filter(user=user)
            create_task = Task.objects.create(user=user)

On a side note, you should be more explicit about your import and not use from perfil.models import *.
From that, you can execute the command based on the file you saved it in.  If you saved the file in yourapp/management/commands/dofunstuff.py than you could execute it via python manage.py dofunstuff.


text: Q: Is precision in recommender system related to mean average error (MAE)? A recommender system is being evaluated while increasing the neighborhood size. The highest precision was achieved between 10-15 neighbors(users) while the lowest MAE was in the range from 30-40 users. Shouldn't the highest precision be achieved when the MAE is the lowest? If not, how the above results can be explained?


text:
Q: Old migration fails in Rails I have a Rails application which have a lot of migrations. Right now I want to redefine almost all the database structure, so most of those migrations will be useless.
What is the approach that I should take? Modify the existing tables with migrations that modify them, or remove those migrations and create new ones?
Thanks

A: In your database, if you want to modify your database migrations:
You can update migration file and can do updates on that migration by redoing it:
rake db:migrate:redo VERSION=001XXXXX

To down your existing migration:
rake db:migrate:down VERSION=001XXXXX

To up specific migration:
rake db:migrate:up VERSION=001XXXXX

A: If you check in your schema.rb to the VCS, and you are not seeding the database in your existing migrations, then it's probably ok to delete or archive the old migrations. It is nowhere recommended to create database from migrations anyways. For that you should use the schema.rb only.
Found a nice article on this.
http://adventuresincoding.com/2010/02/how-to-clean-up-your-activerecord-migrations


text:
Q: Adding macros in a CSV file I have a CSV file where I need to add a macro to insert the current date. I know you can't add a macro into a CSV so I stored it in a separate macro enabled .xlsm file. However when I try to run the macro I get a "Subscript out of range" error. How can I make this work?
Here is the code that is run:
Sub Insert_StartDate()
'
' Insert_StartDate Macro
' Inserts the current date into the StartDate fields
'
' Keyboard Shortcut: Ctrl+d
'
    Windows("Book1").Activate
    Range("J2").Select
    Windows("Activity File (White Collar 1).csv").Activate
    Range("J2").Select
    ActiveCell.FormulaR1C1 = "=TODAY()"
    Range("J2").Select
    Selection.Copy
    Range("J2:J13").Select
    ActiveSheet.Paste
End Sub

A: Sub Insert_StartDate()

    With Workbooks("Activity File (White Collar 1).csv").Sheets(1).Range("J2:J13")
        .Value = Date
    End With

End Sub


text:
Q: How to obey contract of equals() when deriving from abstract class In his book Effective Java, Joshua Bloch writes about the pitfalls that occur with the contract of equals() when derived classes add additional fields to the check. Normally, this would break the symmetry, but Bloch states that "you can add a value component to a subclass of an abstract class without violating the equals contract".
Obviously this is true because there can be no instances of the abstract class, so there is no symmetry to violate. But what about other subclasses? I wrote this example, intentionally omitting hashcode implementations and null-checks to keep the code short:
public abstract class Vehicle {

    private final String color;

    public Vehicle(String color) {
        this.color = color;
    }

    public String getColor() {
        return color;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;

        if (!(o instanceof Vehicle)) return false;

        Vehicle that = (Vehicle) o;

        return color.equals(that.color);
    }

}

public class Bicycle extends Vehicle {

    public Bicycle(String color) {
        super(color);
    }

}

public class Car extends Vehicle {

    private final String model;

    public Car(String color, String model) {
        super(color);
        this.model = model;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;

        if (!(o instanceof Car)) return false;

        Car that = (Car) o;

        return getColor().equals(that.getColor()) && model.equals(that.model);
    }

}

When I create one instance of each class with the same color string, the symmetry of equals() is broken:
Bicycle bicycle = new Bicycle("blue");
Car car = new Car("blue", "Mercedes");

bicycle.equals(car) <- true
car.equals(bicycle) <- false

I am unsure on how to handle this the best way. Declare equals() as abstract in the abstract class to enforce an implementation in the subclasses? But the same effect could be achieved by not declaring equals () at all in the abstract class.

A: Java's equals contract gets especially spotty in situations like this, and in the end it all becomes a matter of the programmer's preferences and needs. I remember reaching this very same issue and I came across this article, which goes over several possibilities and issues when considering the equals contract with Java. It basically ends up saying there's no way to properly do it without breaking the Java equals contract.
When dealing with abstract classes, my personal preference is to not give the abstract class an equals method at all. It doesn't make sense. You can't have two objects of an abstract type; how should you compare them? Instead, I give each subclass its own equals, and the runtime handles the rest whenever equals() is called. And overall, the solution presented in the article that I most often follow is the "only objects of the exact same class may be compared", which seems the most sensible to me.

A: Comparing the class object instead of doing an instanceof check solves the problem.
        if (getClass() != obj.getClass()) {
            return false;
        }

Here is the full implementation (generated by Eclipse):
public class Vehicle {

    // ...

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        Vehicle other = (Vehicle) obj;
        if (color == null) {
            if (other.color != null) {
                return false;
            }
        } else if (!color.equals(other.color)) {
            return false;
        }
        return true;
    }

}

public class Car extends Vehicle {

    // ...

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!super.equals(obj)) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        Car other = (Car) obj;
        if (model == null) {
            if (other.model != null) {
                return false;
            }
        } else if (!model.equals(other.model)) {
            return false;
        }
        return true;
    }

}

Both checks in your example will then yield false.

A: The symmetry of the equals() got broken mainly, because Bicycle class is a subclass and it is dependent on the super class (Vehicle) for it's own equality. If you define the equals() method for each sub class then you will not encounter this issue.
Here is the equals() implementation for each of the class. (Only Bicycle equals() is added, other implementations are same but simplified.)
public abstract class Vehicle {
....
      @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Vehicle)) return false;
    Vehicle that = (Vehicle) o;
    return color.equals(that.color);
  }
}

public class Bicycle extends Vehicle {
...
  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Bicycle)) return false;
    Bicycle that = (Bicycle) o;
    return super.getColor().equals(that.getColor());
  }
}

public class Car extends Vehicle {
...
  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Car)) return false;
    if (!super.equals(o)) return false;
    Car car = (Car) o;
    return model.equals(car.model);
  }
}

// This is main class for testing the above functionality.

class MainClass {
  public static void main(String[] args) {
    Bicycle bicycle = new Bicycle("blue");
    Car car = new Car("blue", "Mercedes");

    System.out.println(bicycle.equals(car));   -> false
    System.out.println(car.equals(bicycle));   -> false
  }
}

OR you should use the object.getClass() instead of instanceof operator in your super class implementation as suggested by @FranzBecker. The sub classes can still use the instanceOf operator without any issue.
public abstract class Vehicle {
...
  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if ((this.getClass() !=  o.getClass())) return false;
    Vehicle that = (Vehicle) o;
    return color.equals(that.color);
  }
}

A: equals() essentially compares the state of the object. When creating your abstract class, you should think about how you want to treat the state of the object.
In your case, your Vehicle has a state of having certain color. Question is: Do you want all vehicles with the same color treated as equal? Then make the answer to this question part of the contract of your abstract class.
If you answer YES:
Simple enough, just make the equals final.
If you answer NO:
You (quite understandably) want your equals to be symmetric. Let's look at the following code:
Bicycle bike = new Bicycle("blue");
Car car = new Car("blue", "gtr");
assert car.equals(bike) == bike.equals(car);

This will fail with AssertionError, because when calling bike.equals(car), you are comparing by bike's standards. To resolve this, you could implement equals for Bicycle. However, you do not want to be looking at all the classes to make sure someone did not forget to implement equals somewhere.
In this case it is enough to make sure in your abstract parent, that different subclasses return false. This can be done simply by replacing your if (! (o instanceof P)) return false; with if (!getClass().equals(o.getClass())) return false;. Your symmetry will be preserved.


text:
Q: Winedt 7, Doesn't show greek correctly I have this problem. I use WinEdt 6 to write latex documents and the main language is greek. Up to now i had no problem and i could, when fisrt installing a new version of WinEdt, find a way of having it "read" greek characters properly. Now i'm trying WinEdt 7 and all greek  part of the text shows wrong. I tried looking at the relative options but nothing seems to work.
I believe the problem is related to the fact that WinEdt 7 has changed the way it supports unicode from version 6. Any tips?
Thank you in advance

A: Problem solved and this because of the suggestion to click on tex in the status line. Even though I use WinEdt for a long time i was not aware of this option, so thanks once more!! By clicking on tex in the  status line of WinEdt 7 Document Settings window pops-up.  In WinEdt 7 there is a new tab that appears called CP Converter. There I had Document Format: ANSI and the new thing was that i played with: Custom ANSI Code Page, which i set to: 1253 Windows 3.1 Greek. Then i pressed apply and then reload and it worked and greek showed properly!!
Thank you all!!


text:
Q: In Seaborn's FacetGrid how to adjust the scale of the x axes to the range of available data I have the following Seaborn FaceGrid output:

generated with a snippet like this:
imax = 3

df = pd.DataFrame(columns = ['x','y','i'])
for i in range(imax):
    # Creating vectors X and Y
    x = np.linspace(0, 1/(2 ** i),101)
    y = x ** x
    df = df.append(pd.DataFrame({'x': x, 'y': y, 'i':i}), ignore_index = True)

g = sns.FacetGrid(df, col='i')
g = g.map(sns.lineplot, 'x', 'y')

import matplotlib.pyplot as plt
plt.show()

(See this gist for the full source.)
In the grid I would like the x axes always be adjusted to the available x values for the respective "i". How can I do this?
What I have tried
I called set_xbound on the axes objects:
for i,b in enumerate(g.axes[0]):
    b.set_xbound(0, 1/(2 ** i))

but this sets the x-scale to [0,0.25] for all subplots, while I obviously want for the first subplot [0,1], then [0.5]  and only for the last subplot [0,0.25].


text:
Q: The result of subtracting the integer part of $x$ from $x$ I want to know what does this formula do with the integer $x$
$$\text{frac}(x) = x - \lfloor {x}\rfloor ,\  x >= 0$$
I've searched and found that this is called finding the fraction part of $x$
Can anyone explain it for me?

A: First, look at
$$\lfloor {x}\rfloor $$
which finds the largest integer less than or equal to $x$. Some examples:
\begin{align}
x && \lfloor {x}\rfloor\\
3.2 && 3.0\\
1.999 && 1\\
0.5 && 0.0 \\
4.0 && 4.0
\end{align}
Now let's subtract  $\lfloor {x}\rfloor$ from $x$:
\begin{align}
x && \lfloor {x}\rfloor && x - \lfloor {x}\rfloor\\
3.2 && 3.0 && 0.2\\
1.999 && 1 && 0.999\\
0.5 && 0.0 && 0.5\\
4.0 && 4.0 && 0.0
\end{align}
In short: for positive numbers, this expression is "the stuff to the right of the decimal point."
Extra credit: You might ask yourself why this doesn't work for negative numbers.

A: If I understand correctly then you mean:
f(x)=abs(x - [x]), when [x] is the floor function of x.
floor function of x:
max{n, n is integer and n<=x}
for example f(-5.372)= -5.372-floor(-5.372)=abs(-5.372-(-5))=0.372
it could be without abs.
The function f(x) returns the part after the decimal point for the decimal representation of x.

A: The 'floor' function $(\lfloor \cdot \rfloor)$, returns the largest integer value which is less than (or equal to) the argument which was provided.
For example:
$$\lfloor 4 \rfloor = \lfloor 4.5 \rfloor = 4$$
The function you created 'frac' is the difference of the argument, and it's integer part, so that you are basically returning the fractional remainder


text:
Q: IE 9 has trouble loading HTML5 audio from Tomcat My HTML5 audio player, when running inside of IE9, has trouble playing audio files located on a server running Apache Tomcat. For example, it'll never load the file at this path:
http://www.siascend.com/repository/audios/1017_Q1.mp3
but happily plays the same file located @:
http://hirebrodie.com/demo/audio/1017_Q1.mp3
Either path works fine when the player runs in Chrome or Safari. Why wouldn't it work in Internet Explorer? Is this a known issue with the IE implementation of HTML5 audio?

A: Tomcat by default specifies for a .mp3 extension the MIME type audio/x-mpeg.Changing this default to audio/mpeg solves the issue.In other words IE9 is NOT comfortable with audio/x-mpeg but accepts audio/mpeg as MIME type of a resource for an  tag.
Source: http://social.msdn.microsoft.com/Forums/pl-PL/iewebdevelopment/thread/b4f58d95-ac27-4a28-a4ae-86477ddfc74f


text:
Q: Adding an image in Android Studio? How can I add an image to be permanently there? For example in the photo below, the Tinder logo is always at the top, and it has navigational buttons on it.

A: This is known as the Action Bar, but if you didn't know that I suggest you study how Android Layout works first, otherwise you will just have a bunch of more doubts of how layouts works, it won't take long and will be very clarifying.


text:
Q: How to transpile JavaScript Using Babel? I know that setting up inline javascript transpile using babel
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script type="text/babel">
     // your es6 code
</script>

but is it possible to give string version of the es6 code into babel and get the transpiled version as a string?
var normal_jacascript = babel.convert(es6_code);

A: Yeah, sure.
Here is a really simple example, if you notice the code is using const and some React JSX, and then I compile to es2015/React, it changes to a var, and React.createElement for the JSX.
You can of course decide what presets to use too.

var ret = Babel.transform("const x = 2; const b = <b/>;", {
  "presets": ["es2015", "react"]
});

console.log(ret.code);
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>


text:
Q: How to convert NumberDecimal to Double in MongoDB shell? I have a document with "test" filed as NumberDecimal type
{ "_id" : ObjectId("5d1a202e476381c30cd995a4"),  "test" : NumberDecimal("0.1") }

How to convert "test" field from NumberDecimal to Double in mongodb shell?
I tried execute
db.collection.find({"test": {$exists: true}}).forEach(function (x) {   x.test = parseFloat(x.test);   db.collection.save(x); });

but don't solve this problem because it return NaN

A: The decimal type is not native to JavaScript, so NumberDecimal values in the shell are special wrappers representing the BSON value stored in MongoDB. If you want to use parseFloat() you can convert a NumberDecimal to JSON in order to access the string value. For example, in your original code this would be: parseFloat(x.test.toJSON()["$numberDecimal"]) .
However, a better approach would be to use the aggregation framework to manipulate decimal values including arithmetic operations (MongoDB 3.4+) and type conversion (MongoDB 4.0+).
MongoDB 4.0+ includes a $toDouble() expression that will convert numeric values (decimal, int, long, boolean, date, string) to a double. The aggregation framework in MongoDB 4.0 cannot be used to update documents (unless you want to create a new collection or replace the existing collection using $out), so you would have to run an aggregation query to convert the values and then separately apply document updates:
// Find matching documents
var docs = db.collection.aggregate([
    { $match: {
        test: { $exists: true }
    }},

    // Add a new field converting the decimal to a double
    // (alternatively, the original "test" value could also be replaced)
    { $addFields: {
        testDouble: { $toDouble: "$test" }
    }}
])

// Update with the changes (Note: this could be a bulk update for efficiency)
docs.forEach(function (doc) {
     db.collection.update({ _id: doc._id}, {$set: { testDouble: doc.testDouble }});
});

// Check the results
> db.collection.find().limit(1)
{
    "_id" : ObjectId("5d1a202e476381c30cd995a4"),
    "test" : NumberDecimal("0.1"),
    "testDouble" : 0.1
}

MongoDB 4.2 (currently in RC) adds support for using some aggregation stages for updates, so in 4.2 the above update can be more concisely expressed as:
db.collection.updateMany(
    { test: { $exists: true }},
    [ { $addFields: { testDouble: { $toDouble: "$test" }}}]
)


text:
Q: Python Dataframe: Create function that makes all values in one column uppercase I have two python data frames.  I want to make all the values in one column of both data frames uppercase.
The following code works:
df_ERA4['reqmnt'] = df_ERA4['reqmnt'].str.upper()
df_ERA5['reqmnt'] = df_ERA5['reqmnt'].str.upper()

But when I want to do the same thing in a function it doesn't work:
def uppercase(df):
    df['reqmnt'] = df['reqmnt'].str.upper()

df_ERA4 = uppercase(df_ERA4)
df_ERA5 = uppercase(df_ERA5)

df_ERA4.head()

Specifically, when I run the above code it gives me the following error: AttributeError: 'NoneType' object has no attribute 'head'

A: Your function, by default does not return anything. So, by default, it returns None. When calling your function, the correct thing to do would be to not assign the return value to anything, since changes are being made in-place.
There are a couple of options now. The first one being: don't return anything, and don't assign anything.
def upper(df, col):
    df[col] = df[col].str.upper()

upper(df, 'reqmnt')

However, this may not be the best approach (personally, I don't much fancy functions that perform in-place operations). You could, alternatively, have a copy returned via an assign call.
def upper(df, col):
    return df.assign(**{col : df[col].str.upper()})

df = upper(df, 'reqmnt')

Note that there's a caveat on this side to - assign returns a copy, and sometimes, where efficiency/performance are paramount, you don't want to be needlessly making copies of GBs of data. What to use should be decided by a combination of style and need.


text:
Q: Вызов subscribe из сервиса в Angular2 Я в сервисе делаю общую функцию (для всех компонентов) для запроса к серверу. Для обработки ошибок на сервере и в самом ответе сразу вызываю subscribe. Как можно дальше в компоненте получить response? Повторно вызывать subscribe (getData().subscribe..) не получается. Сохранять response в локальные переменные и отдельно вызывать?
  getData(){
   return this.http.get(url)
      .subscribe(response => {
        return response;
      }, error => {
        return error;
      });

A: Можно использовать сколько хотите map, filter - они будут вызваны до subscribe. Они будут вызываны, если сервер вернул статус 200-OK. В них вы можете сделать проверку на валидность JSON, проверить ответ еще как-то согласно вашей логике.
В catch попадут ошибки, связанные с недоступностью ресурса (404, 500, 503) или если было какое-то исключение в map.
getData(){
   return this.http.get(url)
      .map(response => { // Здесь делаете преобразования
        return response;
      })
      .map(response => { // Здесь делаете проверки
        if(response==null)
           throw new Error("response is null");
        return response;
      })
      .catch(error=> {
        return response;
      });

Потом где-то в компонентах.
getData().subscribe(resp=>{});

A: Вот пример запроса в сервисе:
getUsersList() {
    const url = 'http://test.ru/api/users/'; // url запроса
    return this.http.get(url)
    .map(
      ( res ) => {
        return res; // можно что то сделать с ответом перед подпиской из компонента
    });
  }

Делаем переменную dataResponse в сервисе:
 import { Subject } from 'rxjs/Subject';
 ... // переходим в класс
 public dataResponse = new Subject<any>();

Затем вызов из того же сервиса:
getResult() {
 this.getUsersList().subscribe(
    (data) => {
        console.log(data); // список пользователей
        this.dataResponse.next(data);
    }, (error) => {
        console.log(error); // сервер вернул ошибку
        // сделать что угодно.
       }
 );
}

Что бы избежать двойного получения данных из сервиса и компонента просто нужно в компоненте подписаться на dataResponse нашего сервиса.
this.ourService.dataResponse.subscribe(
  (data) => {
      // data -  Полученные данные.
  }
)


text:
Q: Solving $n^a = x(n^x)$ for $x$ Okay. Let me just get straight to the point. I have a formula, $n^a = x(n^x)$. What I'm trying to do is make $x$ the subject of the formula. In other words, I want $x$ to express in terms of $a$ and $n$ only. It occured to me that this problem seemed rather impossible, but I'm no expert, you all are. So, here's my question. Is it possible, using any current mathematical hocus pocus, to express $x$ in terms of $a$ and $n$ only? If so, which area of maths do we have to get ourselves into? Can calculus help?
Here are some facts and informations that I've gathered from this formula and feel free to correct me if I'm wrong:
1) $a \geq x$ (obviously)
2) $a = x = 1$ (even more obvious)
3) $n$ is a constant, $a$ is the independent variable and $x$ is the dependent variable.
4) All value of $x$ are real numbers
5) When $a = 0$, $n$th root of $n = 1/x$
That's all the info I currently have. I really wish my question receives some decent answers. Thank you all for helping a poor little boy. I'm 15 in case you're wondering. I just realized I couldn't attach a picture because I don't have enough reputation :(

A: One requires the use of the Lambert W function, which is required in step 3.  The solution is given as follows,
$$n^a=xn^x=xe^{x\ln(n)}\tag1$$
$$n^a\ln(n)=x\ln(n)e^{x\ln(n)}\tag2$$
$$W\left(n^a\ln(n)\right)=x\ln(n)\tag3$$

$$x=\frac{W\left(n^a\ln(n)\right)}{\ln(n)}\tag4$$


text:
Q: Will Unity fix the plugin issues with Chrome? As you may be aware, Chrome dropped support for NPAPI-based plugins, giving at least a year for affected software, like Unity, to switch away. Unity unfortunately didn't do so, and so recently the support on Chrome is dropped and we end users have to find our own workarounds. I heard that Mozilla is going in that direction too. Does anyone know if the folks at Unity are working towards a long-term solution, or is Unity effectively killed? I haven't been able to find anything official from the Unity team yet.

A: The Unity Web Browser plugin is dead and will be buried when Firefox removes support of NPAPI, which will happen soon. The funeral of Unity Browser plugin will be held when Firefox removes support of NPAPI.
The solution to your problem is to download Unity 5 and compile your Game using WebGL from the Build Settings. The WebGL is the replacement of NPAPI and is also compatible with most web browsers. NPAPI will be considered a legacy technology very soon.


text:
Q: Does every model of ZF-foundation have an extension, with no new well-founded sets, where every set is bijective with a well-founded set? This question follows up on an issue arising in Peter LeFanu
Lumsdaine's nice question: Does foundation/regularity have any
categorical/structural consequences, in
ZF?
Let me mention first that my view of the role of the axiom of
foundation in the foundation of set theory differs from Peter's. (But see Peter's remarks about this in the comments below; our views may not actually be so different.)
Specifically, Peter explains how to view the axiom of foundation in
ZFC as an axiom of convenience (see his answer
here). Namely, since every
set is well-orderable, all the non-well-founded sets are bijective
with an ordinal and therefore with a set in the well-founded part
of the universe $\bigcup_\alpha V_\alpha$. In particular, any
mathematical structure to be found at all can be found up to
isomorphism in the well-founded realm, where the axiom of
foundation is true.
Peter's follow-up question arose essentially from his observation that this
argument uses the axiom of choice, and my
answer shows that indeed
this is the case, for there are models of ZF-foundation where some
sets are not bijective with any well-founded set.
My view of the axiom of foundation, in contrast, is that it is not
merely an axiom of convenience, but rather expresses a fundamental
truth of the intended realm of sets the theory is trying to
describe. Specifically, the cumulative universe of all sets arises
from the urelements in a well-ordered series of set-building
stages; every set comes into existence at the first stage after all
of its elements exist. This cumulative universe picture leads
immediately to the axiom of foundation. Andreas Blass expresses a
similar view in answer to an earlier
question. (To my way of
thinking, the real step of convenience in ZFC consists instead of
the insight that we don't actually need urelements for any purpose;
and the resulting ZFC theory without urelements is more uniform and
elegant.)
My question here is whether one can resurrect the idea of the
harmlessness of foundation by showing that every model of
ZF-foundation can be extended, without changing the well-founded
part, to one where every set is bijective with a well-founded set.
Question 1. Does every model of ZF-foundation have an
extension, with the same well-founded sets, in which every set is
bijective with a well-founded set?
A weaker version of the question asks about doing this for just one
set at a time:
Question 2. In any model of ZF-foundation, if $A$ is any set,
then is there an extension of the model, without changing the
well-founded part, in which $A$ becomes bijective with a
well-founded set?
For example, perhaps we might hope to make $A$ well-orderable or
even countable. The trouble would be to do so without adding any
well-founded sets. Definitely we cannot hope to always make a set
$A$ well-orderable, if there are non-well-orderable well-founded
sets.
If you can answer the question for countable models, or by making
further assumptions on the models, I would be interested.

A: Well. The question is what do you mean by an extension exactly.
There's a theorem of Paul Larson and Shelah (originally the work started with Eric Hall, then continued with Paul Larson a few years later) that you can construct a permutation model that has no extension to models of choice with the same pure sets. And of course moving from atoms to Quine atoms, pure sets become well-founded sets.
The idea is roughly to sort of code into the structure of the model a collapse of some cardinals, with the pure sets satisfying $V=L$. Then if you well-order the atoms, then you necessarily had to collapse cardinals and thus add new pure sets.
So from a Platonistic point of view, the answer is negative. If your universe has only those pure sets, then there is no possible way to extend this model further. But if you want to allow forcing extensions, then the answer is yes, you can just add the necessary sets and collapse these cardinals.
In general, if you are willing to add new well-founded sets, then simply collapsing more and more cardinals should in principle work. But I suspect that one can modify Larson and Shelah's work to a class setting such that for every $\alpha$, there is a set of atoms with structure that codes collapsing $\omega_\alpha$ to $\omega$. And then the answer is negative. But this would require a model where the atoms form a proper class.


text:
Q: T-SQL - In Single Stored procedure want to pass value(result) of one query to another query as input
I have a Stored procedure, in which I have to insert 3 strings into 3 different Tables at a time, each string into each of the 3 tables.
In each table, a unique primary key (rowid) would be generated on insertion of the value.
Now, the Primary Key of first two tables is the Foreign key of the Third Table which as you all know, should not be null.
Here in my SP, insertion of value and generation of RowID (PrimaryKey) is done successfully.
Now I have to pass the two primary keys(Rowids) as values/Parameters(foreignkeys) into the third table, which is returning null.
Here is my SP:-
    (1st Table)
   INSERT INTO [kk_admin].[FA_Master](FA_Name,FA_CSession,FA_MSession) Values
             (@FA_Name,@Session_Id,@Session_Id)

   SELECT @**FA_ID=FA_ID** FROM [kk_admin].[FA_Master] where FA_Name=@FA_Name

    (2nd Table)
   INSERT INTO [kk_admin].[Dept_Master](Dept_Name,Dept_CSession,Dept_MSession) Values
   (@Dept_Name,@Session_Id,@Session_Id)

   SELECT @**Dept_id=Dept_id** from [kk_admin].[Dept_Master] where Dept_Name=@Dept_Name

   (3rd Table)
   INSERT INTO [kk_admin].[Category_Master] (**FA_Id**,**Dept_Id**,Category_Name,Category_CSession,Category_MSession) Values    (@**FA_ID**,@**Dept_Id**,@Category_Name,@Session_Id,@Session_Id)

Hope everyone understood what I have explained.
Plz  Help me,
Iam running out of time.
  Plz help me.
  Thank You in Advance,
Brightsy

A: You can use an OUTPUT clause (assuming you're using SQL Server 2005) to capture the primary key for the two rows you're inserting with the first two queries. You can capture the values into a temporary table. [I previously wrote that you could use a regular variable, but that's not supported.] Example code:
CREATE TABLE #FA_Master_ID ( ID int );
CREATE TABLE #Dept_Master_ID ( ID int );

INSERT kk_admin.FA_Master ( FA_Name, FA_CSession, FA_MSession )
OUTPUT INSERTED.ID INTO #FA_Master_ID
VALUES ( @FA_Name, @Session_Id, @Session_Id );

INSERT kk_admin.Dept_Master ( Dept_Name, Dept_CSession, Dept_MSession )
OUTPUT INSERTED.ID INTO #Dept_Master_ID
VALUES ( @Dept_Name, @Session_Id, @Session_Id );

INSERT kk_admin.Category_Master ( **FA_Id**, **Dept_Id**, Category_Name, Category_CSession, Category_MSession )
SELECT  **FA_Id** = ( SELECT TOP 1 ID FROM #FA_Master_ID ),
        **Dept_Id** = ( SELECT TOP 1 ID FROM #Dept_Master_ID ),
        Category_Name = @Category_Name,
        Category_CSession = @Session_Id,
        Category_MSession = @Session_Id;


text:
Q: Find Type Of Exception I have made a class (derived from Exception):
class InvalidFilterException(Exception):
      #some code here
      super().__init__(message)

Now, when I run tests on this module, using unittest.Testcase , running
assertRaises(Exception, InvalidFilterException, arg1, arg2)
Gives an Error:
AssertionError: Exception not raised by InvalidFilterException
Can someone tell me what should I put in place of Exception as the first argument in assertRaisesso that this test passes?
I also tried using InvalidFilterException, as the argument, but that failed too, with the same output.

A: In your case you are trying to InvalidFilterException because the second argument to assertRaises is callable that you want to test.
You need to use your exception like...
assertRaises(InvalidFilterException, do_something, arg1, arg2)

or
with assertRaises(InvalidFilterException):
    do_something(arg1, arg2)

do_something is your function or callable that needs to be tested.


text:
Q: React - Activate sound on render I manage to activate sound library like
import useSound from

'use-sound';

import boopSfx from '../../sounds/boop.mp3';

const BoopButton = () => {

const [play] = useSound(boopSfx);

return <button onClick={play}>Boop!</button>;

};

but I would like to make it go off on render part, like to have some if statement and if its satisfied to play it. Any way to do it?

A: Playing sound on render of button can be achieved using useEffect hook in react. You can see the code here.
const BoopButton = () => {
  const url = "https://www.soundjay.com/button/sounds/beep-01a.mp3";

  const [play] = useSound(url);
  React.useEffect(() => {
    setTimeout(() => {
      play();
    }, 5);
  }, [play]);

  return <button onClick={play}>Boop!</button>;
};

The reason I have added the setTimeOut is to let the URL load so that sound would play, in your case with link to file, it is not needed.

A: You can use 'useEffect' hook to play the sound just before the component is rendered.
import useSound from

'use-sound';

import {useEffect} from 'react'

import boopSfx from '../../sounds/boop.mp3';

const BoopButton = () => {

const [play] = useSound(boopSfx);

//keep an empty array to make sure it only executes once
useEffect(()=>play(),[])

return <button onClick={play}>Boop!</button>;

};

A: It works this way

const [play] = useSound(yourSFX);

useEffect(() => play(), [play])

But make sure that your window is in focus. If it's not, click somewhere inside the window and it will start with the play


text:
Q: Getting all unique values stored in a many-to-many field I have a many-to-many field called categories and I would like to get distinct values stored in that field.
The following is my model:
class Book (models.Model):
    categories=models.ManyToManyField(Category, related_name = 'categories', blank = True, null=True)

Here is my Category model:
class Category (MPTTModel):
    category = models.CharField(max_length=250)
    parent = TreeForeignKey('self', blank=True, null=True, related_name='children')

I'd like to get every single one of the categories related to a book. How would I do this?

A: If you want to get categories related to one instance of book, do book_inst.category_set.all(). There will not be duplicates.
But I think, you want to get all Categories which are related to any Book, you can do:
Category.objects.filter(categories__in=[Book.objects.all()]).distinct()

A: Basically, you need a reverse lookup from the category side to check if there is book for that category if yes, add to the resultant query set. Since, the related_name argument in the Book is 'categories', your reverse lookup would look something like this.
  Category.objects.filter(categories__in = Book.objects.all())


text:
Q: Problem with class instances, Android I am trying to make a game for android
I have a bitmap and canvas instance in my main class.
I have another instance of, lets say, renderer class.
That renderer class is in the same package, but not the subclass of my main class.
If i pass the bitmap and canvas instance to a method of that renderer class and that method will draw that passed bitmap to the passed canvas, are the actual instances passed or new instance copies created and then passed ? Well, i have tried and saw that actual instances were being passed. Because i was seeing the bitmap being drawn to the canvas.
Here is my question, why are the actual instances are passed ?
if it was something like this ->

public class instanceTest
{
    static int num;

    static void numIncrementor(int number)
    {
        number++;
    }

    public static void main(String[] args)
    {
        num = 0;
        numIncrementor(num);
        System.out.println(num);
    }
}

Here, when i print the num, i will still get 0, but with other bitmap and canvas thing, i do send the actual instances. This got me really confused. Can someone explain it ?
Or is it always the case with class objects unlike primitive types ? Does it make garbage collector go crazy ?
Thanks in advance, if you did not understand my engrish, tell and i will put pseudo codes here for clarification;

A: You should really read the Java tutorial before starting to write Java code.
In your example above you passed a primitive - so it's value is simply passed to the method, placed on the stack and that value is altered. That is how primitives work in Java. This means that your number variable only exists within the scope of the numIncrementor method - and does not effect what is outside.
Your actual code works with objects. When you pass an object you actually pass the reference to it on the heap. So every change you do to it will be done on the actual object. The only exception is that you cannot "re-assign" the object to something else since you only hold a reference to the heap - you can "re-assign" your reference to another location on the heap, but the original reference will continue to point to the original object.
As for your question on the garbage collector - no, it will not go crazy. It actually works pretty good. (There is more than one type of GC, but that is a whole different discussion).
Java does not use Copy Constructors - if you want to pass a copy of an object to a method, you should make it cloneable and pass a clone of it.  But this is probably not what you need - note that Copy Constructors consume more resources than just passing the reference to the object.