text:
Q: Interpolating data points in Excel I'm sure this is the kind of problem other have solved many times before.
A group of people are going to do measurements (Home energy usage to be exact).
All of them will do that at different times and in different intervals.
So what I'll get from each person is a set of {date, value} pairs where there are dates missing in the set.
What I need is a complete set of {date, value} pairs where for each date withing the range a value is known (either measured or calculated).
I expect that a simple linear interpolation would suffice for this project.
If I assume that it must be done in Excel.
What is the best way to interpolate in such a dataset (so I have a value for every day) ?
Thanks.
NOTE: When these datasets are complete I'll determine the slope (i.e. usage per day) and from that we can start doing home-to-home comparisons.
ADDITIONAL INFO After first few suggestions:
I do not want to manually figure out where the holes are in my measurement set (too many incomplete measurement sets!!).
I'm looking for something (existing) automatic to do that for me.
So if my input is
{2009-06-01,  10}
{2009-06-03,  20}
{2009-06-06, 110}

Then I expect to automatically get
{2009-06-01,  10}
{2009-06-02,  15}
{2009-06-03,  20}
{2009-06-04,  50}
{2009-06-05,  80}
{2009-06-06, 110}

Yes, I can write software that does this. I am just hoping that someone already has a "ready to run" software (Excel) feature for this (rather generic) problem.

A: There are two functions, LINEST and TREND, that you can try to see which gives you the better results.  They both take sets of known Xs and Ys along with a new X value, and calculate a new Y value.  The difference is that LINEST does a simple linear regression, while TREND will first try to find a curve that fits your data before doing the regression.

A: The easiest way to do it probably is as follows:

*

*Download Excel add-on here: XlXtrFun™ Extra Functions for Microsoft Excel

*Use function intepolate().
=Interpolate($A$1:$A$3,$B$1:$B$3,D1,FALSE,FALSE)
Columns A and B should contain your input, and column G should contain all your date values. Formula goes into the column E.

A: I came across this and was reluctant to use an add-in because it makes it tough to share the sheet with people who don't have the add-in installed.
My officemate designed a clean formula that is relatively compact (at the expensive of using a bit of magic).
Things to note:

*

*The formula works by:

*

*using the MATCH function to find the row in the inputs range just before the value being searched for (e.g. 3 is the value just before 3.5)

*using OFFSETs to select the square of that line and the next (in light purple)

*using FORECAST to build a linear interpolation using just those two points, and getting the result

*This formula cannot do extrapolations; make sure that your search value is between the endpoints (I do this in the example below by having extreme values).
Not sure if this is too complicated for folks; but it had the benefit of being very portable (and simpler than many alternate solutions).
If you want to copy-paste the formula, it is:
=FORECAST(F3,OFFSET(inputs,MATCH(F3,inputs)-1,1,2,1),OFFSET(inputs,MATCH(F3,inputs)-1,0,2,1
(inputs being a named range)

A: A nice graphical way to see how well your interpolated results fit:
Take your date,value pairs and graph them using the XY chart in Excel (not the Line chart).  Right-click on the resulting line on the graph and click 'Add trendline'.  There are lots of different options to choose which type of curve fitting is used.  Then you can go to the properties of the newly created trendline and display the equation and the R-squared value.
Make sure that when you format the trendline Equation label, you set the numerical format to have a high degree of precision, so that all of the significant digits of the equation constants are displayed.

A: The answer above by YGA doesn't handle end of range cases where the desired X value is the same as the reference range's X value.  Using the example given by YGA, the excel formula would return #DIV/0! error if an interpolated value at 9999 was asked for. This is obviously part of the reason why YGA added the extreme endpoints of 9999 and -9999 to the input data range, and then assumes that all forecasted values are between these two numbers.  If such padding is undesired or not possible, another way to avoid a #DIV/0! error is to check for an exact input value match using the following formula:
=IF(ISNA(MATCH(F3,inputs,0)),FORECAST(F3,OFFSET(inputs,MATCH(F3,inputs)-1,1,2,1),OFFSET(inputs,MATCH(F3,inputs)-1,0,2,1)),OFFSET(inputs,MATCH(F3,inputs)-1,1,1,1))

where F3 is the value where interpolated results are wanted.
Note: I would have just added this as a comment to the original YGA post, but I don't have enough reputation points yet.

A: alternatively.
=INDEX(yVals,MATCH(J7,xVals,1))+(J7-MATCH(J7,xVals,1))*(INDEX(yVals,MATCH(J7,xVals,1)+1)-INDEX(yVals,MATCH(J7,xVals,1)))/(INDEX(xVals,MATCH(J7,xVals,1)+1)-MATCH(J7,xVals,1))

where j7 is the x value.
xvals is range of x values
yvals is range of y values
easier to put this into code.

A: You can find out which formula fits best your data, using Excel's "trend line" feature. Using that formula, you can calculate y for any x

*

*Create linear scatter (XY) for it (Insert => Scatter);

*Create Polynominal or Moving Average trend line, check "Display Equation on
chart" (right-click on series => Add Trend Line);

*Copy the equation into cell and replace x's with your desired x value

On screenshot below A12:A16 holds x's, B12:B16 holds y's, and C12 contains formula that calculates y for any x.

I first posted an answer here, but later found this question


text:
Q: Equivalent of PHP gmdate I'm trying to sign an Amazon request and I need the following timestamp format:
gmdate('Y-m-d\TH:i:s\Z');

How can I obtain that in a nodejs environment? Many thanks in advance.

A: For anyone who will need this:
new Date().toISOString()

That's it. Merry Xmas to the downvoters!

redpajama_set_name: RedPajamaStackExchange


text:
Q: RTL8821CE driver malfunctioning I just bought a Lenovo ideapad S130 141GM and installed Ubuntu Budgie 19.04.
The wifi chip is a rtl8821ce so i had to install a driver with the commands :
sudo apt-get install --reinstall git dkms build-essential linux-headers-$(uname -r)
    git clone https://github.com/tomaspinho/rtl8821ce
    cd rtl8821ce
    chmod +x dkms-install.sh
    chmod +x dkms-remove.sh
    sudo ./dkms-install.sh
After rebooting, it worked, i could see many networks, but not my box. After that i used a wifi dongle with a RTL8188EUS which worked directly out of the box and saw the same networks and my box.
My box is working on channel 6, so it is not a problem of country channel allocation. The signal level o my box is of course much higher than the signal of all others networks and there is no other network on channel 6 (I tried on other channel without success too). My provider is "Free".
Does somebody have the same problem solved and could give me a hint of where to look (I would be happy to be able to use again the usb connector occupied by the wifi dongle) ?
Thanks in advance.

A: From the comments...
Uninstall your current dkms driver (https://github.com/tomaspinho/rtl8821ce)...
cd rtl8821ce          # old source folder
sudo ./dkms-remove.sh # uninstall old dkms driver

And try this one... https://github.com/shubham151/rtl8821ce. (git clone https://github.com/shubham151/rtl8821ce.git). Don't follow the ReadMe there for how to install it, rather, follow the same procedure that you did before, so that you get the dkms install.
git clone https://github.com/shubham151/rtl8821ce.git # git clone new driver
cd rtl8821ce             # new source folder
chmod +x dkms-install.sh # make executable
chmod +x dkms-remove.sh  # make executable
sudo ./dkms-install.sh   # install new dkms driver

A: For ubuntu 20.04 this should do the trick:
apt install rtl8821ce-dkms


text:
Q: mongoDB sort on two fields I have a mongodb document something like below :
 {

        "match_key" : 44801,
        "total_points" : 10.00,

    },
    {
        "match_key" : 44901,
        "total_points" : 8.00,
    },
   {
        "match_key" : 44901,
        "total_points" : 7.00,
    },

   {
        "match_key" : 44901,
        "total_points" : 11.00,
    },
    {

    "match_key" : 44801,
    "total_points" : 7.00,

}

I want to sort the above docs ,but want to keep the documents with same match_key together.
Actual result :
 {
        "match_key" : 44901,
        "total_points" : 11.00,
    }
,
 {

        "match_key" : 44801,
        "total_points" : 10.00,

    },
{
        "match_key" : 44901,
        "total_points" : 8.00,
    },

{

    "match_key" : 44801,
    "total_points" : 7.00,

}

 {
        "match_key" : 44901,
        "total_points" : 6.00,
    },

But you see that same match keys are not together.
Expected result :
{
        "match_key" : 44901,
        "total_points" : 11.00,
    },
{
        "match_key" : 44901,
        "total_points" : 8.00,
    },
{
        "match_key" : 44901,
        "total_points" : 7.00,
    },
{

        "match_key" : 44801,
        "total_points" : 10.00,

    },
{

        "match_key" : 44801,
        "total_points" : 6.00,

    },

Such that docs with same_match key are in descending  order.
This is what I tried doing :
 db.collection.aggregate(
    [
      { $match: { match_key:{$in:[44801,45910]}}},
      { $sort: {total_points:1,match_key:1} }
    ]
 )

This is some sql equivalent of the question ,I am trying to ask -Sort by most recent but keep together by another ID column
My main motive here is to  sort the docs and keep the docs with same match_key together but in order
/**

A: You need to split this $sort into two stages like below :
db.collection.aggregate([
  {
    $match: {
      match_key: {
        $in: [
          44801,
          45910
        ]
      }
    }
  },
  {
    $sort: {
      total_points: -1
    }
  },
  {
    $sort: {
      match_key: -1
    }
  }
])

Test : MongoDB-Playground
Note : As we've $match as first stage, we should be good to do sorting, but even though as we need to do sort twice, try to keep your dataset as low as possible, You need to have two Single-field-index on two of your fields total_points & match_key.
Issue :
 So when you do this : { $sort: {total_points:-1,match_key:1} } your query is sorting on total_points :1 field first & if it finds two docs with same total_points value then it would go to match_key:1 will sort those two docs to keep them in order.
Example of issue : Using compound sorting like above you would get below result
  {
    "_id": ObjectId("5a934e000102030405000002"),
    "match_key": 44801,
    "total_points": 10
  },
  {
    "_id": ObjectId("5a934e000102030405000003"),
    "match_key": 45910,
    "total_points": 10
  },
  {
    "_id": ObjectId("5a934e000102030405000005"),
    "match_key": 44801,
    "total_points": 7
  }

If you see total_points are sorted in order, with first priority is on total_points & since there are two docs with "total_points": 10 it kicks in second priority of match_key. Anyway if you want to sort like 11->10->7 you need to use descending mechanism with -1 but not 1 (which is ascending).


text:
Q: Mapbox - Get an accurate road route to display on the map When we use the directions api over long distances we noticed the lines aren't exactly on the roads, like in this image:

it's from:
https://docs.mapbox.com/playground/directions/
coordinates: -86.945145,40.090054;-88.26635,40.136585
I didn't find any way to make the directions API return a more precise path but I saw the matching API so I thought I could use the route I got from the directions API and match it to the roads.
The problem is when I use it I encounter the error:

"All coordinates are too far away from each other"

Even when I try to split the route to pairs of two coordinates it still says that. There's no mention of such a limit in https://docs.mapbox.com/api/navigation/#map-matching. The coordinates above return that error.
That's the coordinates I got from directions API so I have no choice but to use them but they're incompatible with matching API, so what can I do to get an accurate directions path that sits exactly on the roads?
I thought about adding midpoints between every pair of coordinates but that won't work in cases where those midpoints would be far off any road.

A: There are two ways to get more precise geometries from the Directions API:

*

*geometries: "polyline6" (get geometries with 6 decimal places of precision)

*overview: "full" (include full geometry in the overview, not just in the route legs)

I think using those will solve your problem.


text:
Q: Getting estimated means after multiple imputation using the mitml, nlme & geepack R packages I'm running multilevel multiple imputation through the package mitml (using the panimpute() function) and am fitting linear mixed models and marginal models through the packages nlme and geepack and the mitml:with() function.
I can get the estimates, p-values etc for those through the testEstimates() function but I'm also looking to get estimated means across my model predictors. I've tried the emmeans package, which I normally use for getting estimated means when running nlme & geepack without multiple imputation but doing so emmeans tell me "Can't handle an object of class "mitml.result"".
I'm wondering is there a way to get pooled estimated means from the multiple imputation analyses I've run?
The data frames I'm analyzing are longitudinal/repeated measures and in long format. In the linear mixed model I want to get the estimated means for a 2x2 interaction effect and in the marginal model I'm trying to get estimated means for the 6 levels of 'time' variable. The outcome in all models is continuous.
Here's my code
# mixed model
fml <- Dep + time ~ 1 + (1|id)
imp <- panImpute(data=Data, formula=fml, n.burn=50000, n.iter=5000, m=100, group = "treatment")
summary(imp)
plot(imp, trace="all")
implist <- mitmlComplete(imp, "all", force.list = TRUE)

fit <- with(implist, lme(Dep ~ time*treatment, random = ~ 1|id, method = "ML", na.action = na.exclude, control = list(opt = "optim")))
testEstimates(fit, var.comp = TRUE)
confint.mitml.testEstimates(testEstimates(fit, var.comp = TRUE))

# marginal model
fml <- Dep + time ~ 1 + (1|id)
imp <- panImpute(data=Data, formula=fml, n.burn=50000, n.iter=5000, m=100)
summary(imp)
plot(imp, trace="all")
implist <- mitmlComplete(imp, "all", force.list = TRUE)

fit <- with(implist, geeglm(Dep ~ time, id = id, corstr ="unstructured"))
testEstimates(fit, var.comp = TRUE)
confint.mitml.testEstimates(testEstimates(fit, var.comp = TRUE))

A:
is there a way to get pooled estimated means from the multiple imputation analyses I've run?

This is not a reprex without Data, so I can't verify this works for you.  But emmeans provides support for mira-class (lists of) models in the mice package.  So if you fit your model in with() using the mids rather than mitml.list class object, then you can use that to obtain marginal means of your outcome (and any contrasts or pairwise comparisons afterward).
Using example data found here, which uncomfortably loads an external workspace:
con <- url("https://www.gerkovink.com/mimp/popular.RData")
load(con)

## imputation

library(mice)

ini <- mice(popNCR, maxit = 0)
meth <- ini$meth
meth[c(3, 5, 6, 7)] <- "norm"

pred <- ini$pred
pred[, "pupil"] <- 0

imp <- mice(popNCR, meth = meth, pred = pred, print = FALSE)

## analysis

library(lme4) # fit multilevel model
mod <- with(imp, lmer(popular ~ sex + (1|class)))

library(emmeans) # obtain pooled estimates of means
(em <- emmeans(mod, specs = ~ sex) )
pairs(em) # test comparison


text:
Q: Animate the outer stroke of a view (button) I'd like to flash/blink the stroke of a button a few times based on a timer.  For example, every 30 seconds flash the stroke 3 times from white to black or some such thing.  Can this be done?  Thanks

A: you can create custom button layouts like such and put them in the drawable folder
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item>
    <shape>
        <gradient
            android:endColor="@color/white"
            android:startColor="@color/whitesmoke"
            android:angle="270" />
        <stroke
            android:width="2dp"
            android:color="@color/grey3" />
        <corners
            android:radius="10dp" />
    </shape>
</item>

where the color grey3 is the border and you can start a timer and add a TimerTask class to your class and then make it run the task every 30 seconds and just change the buttons background from one .xml to another with a different border color.


text:
Q: How can I change the Multimedia Backend in Qt 5.7? Hello I developed an application on linux that is a music player with an spectrum analyzer.
Now I want to compile it for windows.
However, it turns out that DirectShow does not support audio probe as stated here:
https://wiki.qt.io/Qt_5.7_Multimedia_Backends
But apparently Media Foundation does. How can I use this backend instead of DirectShow?


text:
Q: Matrices over a ring: does $PAQ=A'$ imply $\mathrm{Coker}A\cong\mathrm{Coker}A'$? In A Singular Introduction to Commutative Algebra by Greuel & Pfister, there is written on p. 127:

Let $R$ be a commutative unital ring and $A\in R^{n\times k}$, $P\in R^{n\times n}$, $Q\in R^{k\times k}$, with $P$ and $Q$ invertible. Why do we have $\mathrm{Coker}\,A \cong \mathrm{Coker}\,PAQ$?

I understand that $R^n/\mathrm{Im}(A)\cong R^n/\mathrm{Im}(PA)$ via $P$.

A: You want to prove that $R^n/\mathrm{Im}(A)\cong R^n/\mathrm{Im}(AQ)$ with $Q$ invertible. Well, I don't think this is necessarily true, but for the special case when $Q$ is an elementary transformation this is easily seen. The image of $A$ is the submodule generated by the columns of $A$ and the image of $AT$ is the same since the elementary transforms on columns of $A$ don't affect the image: they simply interchange two columns, multiply a column by an invertible element, or add a multiple of a column to another column and obviously these operations don't change the submodule generated by the columns of $A$.


text:
Q: Is it possible to define a code style in checkstyle based on a code style from IntelliJ idea? I have a project which I'm developing in IntelliJ Idea and I have formatting rules like where curly braces are to be located and so on. Is it possible to convert an IntelliJ code style into a checkstyle one so that when I run reports through Maven, I don't see warnings like "Right curly brace and next "else", "catch" and "finally" keywords should be located on the same line"...?
Thanks in advance!

A: Answer for your question is a maven-checkstyle-plugin.
http://maven.apache.org/plugins/maven-checkstyle-plugin/
But before using, you need to understand that maven is a separate application is not fully integrated with the idea. ie this plugin will not use the idea of setting, but it will have to use a separate files configuration.


text:
Q: Force GMail to check mails from other accounts I am using GMail to collect mails from other non-Google email accounts. It turned out that GMail uses its own rules to check new mails in these external accounts. This does not happen in real time or at least periodically with the required frequency (say, every 1 or 2 minutes). Even the Refresh button above the mail list does not help if I want to check mails manually. To nudge GMail to check emails in external accounts, I open its Settings (first Quick Settings, then All settings, then open the Accounts and Import tab, and finally click the Check mail now link in the Check mail from other accounts: section.
My questions:

*

*Is there any setting that makes the Refresh button work for external accounts?

*How to set the desired frequency of checking mails in external accounts from GMail?

A: I recommend you to use the following simple & effective tool:
https://www.danielslaughter.com/project/gmailpop3/


text:
Q: How to deploy a react app on cPanel? I've created a react app with the following folder structure
-public
 --dist
  ---bundle.js
  ---styles.css
 --index.html
 --images
-server
 --server.js
-src
 --components
 --app.js
-.babelrc
-package.json
-webpack.config.js
I want to upload it to cPanel. Is that possible? Would I also need to upload the node_modules/ folder?
here is a link to my repo: https://github.com/theoiorga/react-expensify-app

A: Follow the steps to  deploy your React website on CPanel
Step(1) : Under your local project directory run this command "npm
           run build" or "yarn build" then "build" directory will be created. This directory contains the bundle of all static files with dependencies which you can directly copy onto your production server.

Step (2) : Go to inside the "build" folder and select all files and compress or make a Zip then upload in cpanel it will work.

Note: for react app no need to upload whole projects we need to deploy only "build" directory.

A: To Deploy React App on Cpanel/Server. Please follow the Steps
Step 1) Go to Package.json file and add this Property "homepage":"http://yourdomain.com" and paste your domain within it. Like

Step 2)  Now build the App using npm run build
In your project directory it will create a build folder and it will contain all your static files for project. Zip all files and upload on your cpanel directory where your website run.
Step 3) Create an .htaccess file and Place it on root directory. And paste the below code in .htaccess file.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]
</IfModule>

Now Run your Project. It will Work.
Thanks

A: I had the same issue recently. As a newbie to React, I have deployed my app to Heroku many times, as part of the React course. However, I wanted to deploy to my own shared server (CPanel), to learn how it is done. But also to use my hosting to host other apps I code.
Anyway, What Kallayya and Sumit mentioned above both needs to be done. There is also a great step by step information here.
NB. If you did not use something like 'npx create-react-app' to create the app (boilerplate) then, you will not get a 'Build' folder.
My initial boilerplate was created from scratch as part of the course. So I was initially confused about why I was not getting a Build folder. Then I realised that 'Build' folder is created if the app was created with e.g. 'npx create-react-app' or 'yarn create react-app'. I had used 'npx create-react-app' to start another project. In the new project, I was able to get a Build folder. Hence, my realisation.
So if you run a build and you don't get a Build folder (as mentioned above). Then the files to deploy to live will be the content in the 'public' directory on your local site. (If you have env setup for production and development, then you may need to build for production e.g. yarn build:prod).
Now follow the same process in the step by step link, above. However, upload the content from your 'public' directory in your local site, to the public_html folder on your remote hosting server. Create and upload your .htaccess file as shown on the page of the above link. Now view your site at your relevant domain.
Following the steps in the above link, I was able to deploy to my Shared hosting and view my app at my domain. It works perfectly fine. Haven't seen any issues yet.
I hope this will be helpful to others.

A: step 1:"homepage": ".", -->add this on package.json file
step 2 : npm run build  --> this will create a build folder.
step 3 : make a .htaccess it will look like this
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]
</IfModule>

step 4 : now take all the files in build folder plus your htaccess  and drop them in the desired domain or subdomain

A: I resolved it by implementing the following steps
Step 1
Add the following in package.json
"homepage": "."

Step 2
Add the following in the public/index.html above meta: description
<script type="text/javascript"> document.write("<base href='//" + document.location.host + "' />"); </script>

Step 3
Build your App using npm run build
Step 4
Upload files inside /build folder to the server using any file transfer tool
Step 5
Create and add the following in .htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]
</IfModule>

A: Just upload your local public folder to your hosting public_html folder

A: Make sure your hosting provider supports Node.js that you will see on CPanel.
The company I use is Namecheap and they just added Node.js runtime environment to CPanel.
Contact your hosting company and ask them if they support Node.js

A: I'm agree with the fact that you should have a dedicated or VPS hosting, because you will need to have control to the command line.
What I would suggest you to do, apart of what has been mentioned in other comments (accessing the cPanel via SSH and install node and npm, etc), you should upload the files using GitHub or BitBucket.
When you do it this way it will be even easier to keep updating your web app every time you need.

A: I imagine you have ssh access. If you do install NodeJS via SSH and then upload your files, it will be better if you do it on your public_html. Not only the build but the whole project. I would do it using git.
When you have you files up you will have to install npm and in your client folder you have to install your client, because just uploading the node_modules folders won't work.
You should install forever and run forever node server.js, that will make the server run even when you close the terminal
I hope I explained myself.

A: I have a hosting plan with siteground and I can host as many websites as I want with that plan.
Hosting a react app with siteground was super easy once I figured it out.
I got a good chunk of what I know by reading this thread, so if you want visuals you can look to the top answer.
Step 1) Add "homepage":".", to the object in your package.json file.
Step 2) In your terminal run npm run build
Step 3) Add a .htaccess file to your build folder with the following code:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]
</IfModule>

Step 4) Use a file manager to upload all of the files from your build folder including your .htaccess file to the public folder on the server. I used FileZilla, but you can use the built in file manager or SSH keys. If you don't know how to make an FTP user, go here.
Siteground specific instructions:
Step 5) Navigate to the site tools for the desired website. (You can even use a temporary domain for this).
Step 6) Install an SSL certificate in Security > SSL Manager. (You can use the free one. Take note of the expiration date.)
Step 7) Enforce HTTPS by going to Security > HTTPS Enforce and turn it on.
That should work! Send questions if you have any.
I have no affiliation with siteground or any company. I am a freelance web developer that is developing my react skills

A: React applications are built on Node.js and do not work out of the box on Cpanel.
I am assuming you are working with a Linux server. To deploy your react app, you need to do the following.

*

*Make sure you have root assess to the server. That is only possible if you are working with a VPS or dedicated hosting and not shared hosting.

*Log into your account using SSH

*Install node.js and npm on the server

*Upload your build files to the server

*Run the command to start your app in production.
These steps look easy but are a bit complicated. If you are a newbie who just started working on react, I will advise you not to bother yourself with these steps. You can easily get your react app working in less than 10 mins with a cloud service like Heroku for free too.


text:
Q: WinApi - Byte Array to Gray 8-bit Bitmap (+Performance) I have a byte array that needs to be displayed on the desktop (or Form). I'm using WinApi for that and not sure how to set all pixels at once. The byte array is in my memory and needs to be displayed as quickly as possible (with just WinApi).
I'm using C# but simple pseudo-code would be ok for me:
// create bitmap
byte[] bytes = ...;// contains pixel data, 1 byte per pixel
HDC desktopDC = GetWindowDC(GetDesktopWindow());
HDC bitmapDC = CreateCompatibleDC(desktopDC);
HBITMAP bitmap = CreateCompatibleBitmap(bitmapDC, 320, 240);
DeleteObject(SelectObject(bitmapDC, bitmap));

BITMAPINFO info = new BITMAPINFO();
info.bmiColors = new tagRGBQUAD[256];
for (int i = 0; i < info.bmiColors.Length; i++)
{
    info.bmiColors[i].rgbRed = (byte)i;
    info.bmiColors[i].rgbGreen = (byte)i;
    info.bmiColors[i].rgbBlue = (byte)i;
    info.bmiColors[i].rgbReserved = 0;
}
info.bmiHeader = new BITMAPINFOHEADER();
info.bmiHeader.biSize = (uint) Marshal.SizeOf(info.bmiHeader);
info.bmiHeader.biWidth = 320;
info.bmiHeader.biHeight = 240;
info.bmiHeader.biPlanes = 1;
info.bmiHeader.biBitCount = 8;
info.bmiHeader.biCompression = BI_RGB;
info.bmiHeader.biSizeImage = 0;
info.bmiHeader.biClrUsed = 256;
info.bmiHeader.biClrImportant = 0;
// next line throws wrong parameter exception all the time
// SetDIBits(bitmapDC, bh, 0, 240, Marshal.UnsafeAddrOfPinnedArrayElement(info.bmiColors, 0), ref info, DIB_PAL_COLORS);

// how do i store all pixels into the bitmap at once ?
for (int i = 0; i < bytes.Length;i++)
    SetPixel(bitmapDC, i % 320, i / 320, random(0x1000000));

// draw the bitmap
BitBlt(desktopDC, 0, 0, 320, 240, bitmapDC, 0, 0, SRCCOPY);

When I just try to set each pixel by itself with SetPixel() I see a monochrome image without gray colors only black and white. How can I correctly create a gray scale bitmap for displaying ? And how do I do that quick ?

Update:
The call ends up in an error outside of my program in WinApi. Can't catch exception:

public const int DIB_RGB_COLORS = 0;
public const int DIB_PAL_COLORS = 1;

[DllImport("gdi32.dll")]
public static extern int SetDIBits(IntPtr hdc, IntPtr hbmp, uint uStartScan, uint cScanLines, byte[] lpvBits, [In] ref BITMAPINFO lpbmi, uint fuColorUse);

// parameters as above
SetDIBits(bitmapDC, bitmap, 0, 240, bytes, ref info, DIB_RGB_COLORS);

A: Two of the SetDIBits parameters are wrong:

*

*lpvBits - this is the image data but you're passing the palette data.  You should be passing your bytes array.

*lpBmi - this is OK - the BITMAPINFO structure contains both the BITMAPINFOHEADER and the palette so you don't need to pass the palette separately.  My answer to your other question describes how to declare the structure.

*fuColorUse - this describes the format of the palette.  You are using an RGB palette so you should pass DIB_RGB_COLORS.


text:
Q: How to get the doc.length of today record in flutter firebase I'm new in flutter firebase, how can i display the length of my Total sales sales record. I have the collection of SalesRecord and and a field name Created and i want to know how many sales i made during this Day.
My Code:
var todaySales = 0;
FutureBuilder(
    future: FirebaseFirestore.instance
        .collection('SalesRecord')
        // .orderBy('Created', descending: true | false)
        .where("Created", isGreaterThan: DateTime.now())
        .get()
        .then((myDocuments) {
      setState(() {
        todaySales = myDocuments.docs.length;
      });
      //print("${myDocuments.docs.length}");
    }),
    builder: (context, snapshot) {
      if (snapshot.hasData) {
        return const Center(
            child: CircularProgressIndicator());
      } else if (snapshot.hasError) {
        return const Center(
            child: CircularProgressIndicator());
      }
      return Text(
        todaySales.toString(),
        style: const TextStyle(
          fontSize: 50.0,
          fontWeight: FontWeight.bold,
        ),
      );
    }),

Code Update :-
FutureBuilder<QuerySnapshot<Map<String, dynamic>>>(
                        future: FirebaseFirestore.instance
                            .collection('SalesRecord')
                            .where("Created",
                                isGreaterThan: DateTime.now())
                            .get(),
                        builder: (context, snapshot) {
                          if (snapshot.hasData) {
                            return Text(
                              snapshot.data!.docs.length.toString(),
                              style: const TextStyle(
                                fontSize: 50.0,
                                fontWeight: FontWeight.bold,
                              ),
                            );
                          } else if (snapshot.hasError) {
                            return const Center(
                                child: CircularProgressIndicator());
                          } else {
                            return CircularProgressIndicator();
                          }
                        }),

When i update the SalesRecord it change the value for a while but the record count back to 0 again by itself after 20sec

A: The reason for count getting back to 0 is that DateTime.now() gets the current date time i.e. if you made a sale 30 seconds ago it won't be shown as the current time is 30 seconds greater than previous one.
So declare a variable as shown below which will get us the today's date (2022-01-31 00:00:00.000) and zero time values to mark the beginning of the day.
DateTime dateToday = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day);

And now use this in your code as:-
FutureBuilder<QuerySnapshot<Map<String, dynamic>>>(
      future: FirebaseFirestore.instance
          .collection('SalesRecord')
          .where("Created",
          isGreaterThan: dateToday)
          .get(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Text(
            snapshot.data!.docs.length.toString(),
            style: const TextStyle(
              fontSize: 50.0,
              fontWeight: FontWeight.bold,
            ),
          );
        } else if (snapshot.hasError) {
          return const Center(
              child: CircularProgressIndicator());
        } else {
          return CircularProgressIndicator();
        }
      })

A: You can do the following:
          FutureBuilder<QuerySnapshot<Map<String, dynamic>>>(
              future: FirebaseFirestore.instance
                  .collection('SalesRecord')
                  .where("Created", isGreaterThan: DateTime.now())
                  .get(),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return Text(
                    snapshot.data!.docs.length.toString(),
                    style: const TextStyle(
                      fontSize: 50.0,
                      fontWeight: FontWeight.bold,
                    ),
                  );
                } else if (snapshot.hasError) {
                  return const Center(child: CircularProgressIndicator());
                } else {
                  return CircularProgressIndicator();
                }
              }),

get() returns a Future<QuerySnapshot<Map<String, dynamic>>> so assign that to the future property. Then the snapshot of type AsyncSnapshot will contain the data of this future and you can access it inside if(snapshot.hasData) using the data property.


text:
Q: What is non-inheritance hierarchy? Exercise from T.Budd book:
"In an object-oriented inheritance hierarchy each level is a more specialized form of the
preceding level. Given one more example of a hierarchy found in everyday life that
has this property. There are other types of hierarchy found in everyday life that are
not inheritance hierarchies. Give an example of a non-inheritance hierarchy."
What is an example of "non-inheritance hierarchy"???
Composition/aggregation are suitable?
Thanks

A: I understood you are to give a real life example. There are a lot of things you can think of.
Eg. the hierarchy in a company.
CEO - Technical Team Leader - Developer
                            - Architect
    - CFO - acountant
    - secretary of the CEO

As far as skills go, the secretary of the CEO is not a more specialized CEO and neither is the developer.


text:
Q: how to manipulate angular-ui-date with bower This is my console error:

Error: [$injector:nomod] Module 'ui.date' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.


text:
Q: How to avoid the "divide by zero" error in SQL? I have this error message:

Msg 8134, Level 16, State 1, Line 1 Divide by zero error encountered.

What is the best way to write SQL code so that I will never see this error message again?
I could do either of the following:

*

*Add a where clause so that my divisor is never zero

Or

*

*I could add a case statement, so that there is a special treatment for zero.

Is the best way to use a NULLIF clause?
Is there better way, or how can this be enforced?

A: In order to avoid a "Division by zero" error we have programmed it like this:
Select Case when divisor=0 then null
Else dividend / divisor
End ,,,

But here is a much nicer way of doing it:
Select dividend / NULLIF(divisor, 0) ...

Now the only problem is to remember the NullIf bit, if I use the "/" key.

A: This seemed to be the best fix for my situation when trying to address dividing by zero, which does happen in my data.
Suppose you want to calculate the male–female ratios for various school clubs, but you discover that the following query fails and issues a divide-by-zero error when it tries to calculate ratio for the Lord of the Rings Club, which has no women:
SELECT club_id, males, females, males/females AS ratio
  FROM school_clubs;

You can use the function NULLIF to avoid division by zero. NULLIF compares two expressions and returns null if they are equal or the first expression otherwise.
Rewrite the query as:
SELECT club_id, males, females, males/NULLIF(females, 0) AS ratio
  FROM school_clubs;

Any number divided by NULL gives NULL, and no error is generated.

A: You can also do this at the beginning of the query:
SET ARITHABORT OFF
SET ANSI_WARNINGS OFF

So if you have something like 100/0 it will return NULL. I've only done this for simple queries, so I don't know how it will affect longer/complex ones.

A: I wrote a function a while back to handle it for my stored procedures:
print 'Creating safeDivide Stored Proc ...'
go

if exists (select * from dbo.sysobjects where  name = 'safeDivide') drop function safeDivide;
go

create function dbo.safeDivide( @Numerator decimal(38,19), @divisor decimal(39,19))
   returns decimal(38,19)
begin
 -- **************************************************************************
 --  Procedure: safeDivide()
 --     Author: Ron Savage, Central, ex: 1282
 --       Date: 06/22/2004
 --
 --  Description:
 --  This function divides the first argument by the second argument after
 --  checking for NULL or 0 divisors to avoid "divide by zero" errors.
 -- Change History:
 --
 -- Date        Init. Description
 -- 05/14/2009  RS    Updated to handle really freaking big numbers, just in
 --                   case. :-)
 -- 05/14/2009  RS    Updated to handle negative divisors.
 -- **************************************************************************
   declare @p_product    decimal(38,19);

   select @p_product = null;

   if ( @divisor is not null and @divisor <> 0 and @Numerator is not null )
      select @p_product = @Numerator / @divisor;

   return(@p_product)
end
go

A: You can at least stop the query from breaking with an error and return NULL if there is a division by zero:
SELECT a / NULLIF(b, 0) FROM t

However, I would NEVER convert this to Zero with coalesce like it is shown in that other answer which got many upvotes. This is completely wrong in a mathematical sense, and it is even dangerous as your application will likely return wrong and misleading results.

A: *

*Add a CHECK constraint that forces Divisor to be non-zero

*Add a validator to the form so that the user cannot enter zero values into this field.

A: For update SQLs:
update Table1 set Col1 = Col2 / ISNULL(NULLIF(Col3,0),1)

A: SELECT Dividend / ISNULL(NULLIF(Divisor,0), 1) AS Result from table

By catching the zero with a nullif(), then the resulting null with an isnull() you can circumvent your divide by zero error.

A: EDIT:
I'm getting a lot of downvotes on this recently...so I thought I'd just add a note that this answer was written before the question underwent it's most recent edit, where returning null was highlighted as an option...which seems very acceptable.  Some of my answer was addressed to concerns like that of Edwardo, in the comments, who seemed to be advocating returning a 0.  This is the case I was railing against.
ANSWER:
I think there's an underlying issue here, which is that division by 0 is not legal.  It's an indication that something is fundementally wrong.  If you're dividing by zero, you're trying to do something that doesn't make sense mathematically, so no numeric answer you can get will be valid.  (Use of null in this case is reasonable, as it is not a value that will be used in later mathematical calculations).
So Edwardo asks in the comments "what if the user puts in a 0?", and he advocates that it should be okay to get a 0 in return.  If the user puts zero in the amount, and you want 0 returned when they do that, then you should put in code at the business rules level to catch that value and return 0...not have some special case where division by 0 = 0.
That's a subtle difference, but it's important...because the next time someone calls your function and expects it to do the right thing, and it does something funky that isn't mathematically correct, but just handles the particular edge case it's got a good chance of biting someone later.  You're not really dividing by 0...you're just returning an bad answer to a bad question.
Imagine I'm coding something, and I screw it up.  I should be reading in a radiation measurement scaling value, but in a strange edge case I didn't anticipate, I read in 0.  I then drop my value into your function...you return me a 0!  Hurray, no radiation!  Except it's really there and it's just that I was passing in a bad value...but I have no idea.  I want division to throw the error because it's the flag that something is wrong.

A: There is no magic global setting 'turn division by 0 exceptions off'. The operation has to to throw, since the mathematical meaning of x/0 is different from the NULL meaning, so it cannot return NULL.
I assume you are taking care of the obvious and your queries have conditions that should eliminate the records with the 0 divisor and never evaluate the division. The usual 'gotcha' is than most developers expect SQL to behave like procedural languages and offer logical operator short-circuit, but it does NOT. I recommend you read this article: http://www.sqlmag.com/Articles/ArticleID/9148/pg/2/2.html

A: Here is a situation where you can divide by zero.  The business rule is that to calculate inventory turns, you take cost of goods sold for a period, annualize it.  After you have the annualized number, you divide by the average inventory for the period.
I'm looking at calculating the number of inventory turns that occur in a three month period.  I have calculated that I have Cost of Goods sold during the three month period of $1,000.  The annual rate of sales is $4,000  ($1,000/3)*12.  The beginning inventory is 0.  The ending inventory is 0.  My average inventory is now 0.  I have sales of $4000 per year, and no inventory.  This yields an infinite number of turns.  This means that all my inventory is being converted and purchased by customers.
This is a business rule of how to calculate inventory turns.

A: In case you want to return zero, in case a zero devision would happen, you can use:
SELECT COALESCE(dividend / NULLIF(divisor,0), 0) FROM sometable

For every divisor that is zero, you will get a zero in the result set.

A: CREATE FUNCTION dbo.Divide(@Numerator Real, @Denominator Real)
RETURNS Real AS
/*
Purpose:      Handle Division by Zero errors
Description:  User Defined Scalar Function
Parameter(s): @Numerator and @Denominator

Test it:

SELECT 'Numerator = 0' Division, dbo.fn_CORP_Divide(0,16) Results
UNION ALL
SELECT 'Denominator = 0', dbo.fn_CORP_Divide(16,0)
UNION ALL
SELECT 'Numerator is NULL', dbo.fn_CORP_Divide(NULL,16)
UNION ALL
SELECT 'Denominator is NULL', dbo.fn_CORP_Divide(16,NULL)
UNION ALL
SELECT 'Numerator & Denominator is NULL', dbo.fn_CORP_Divide(NULL,NULL)
UNION ALL
SELECT 'Numerator & Denominator = 0', dbo.fn_CORP_Divide(0,0)
UNION ALL
SELECT '16 / 4', dbo.fn_CORP_Divide(16,4)
UNION ALL
SELECT '16 / 3', dbo.fn_CORP_Divide(16,3)

*/
BEGIN
    RETURN
        CASE WHEN @Denominator = 0 THEN
            NULL
        ELSE
            @Numerator / @Denominator
        END
END
GO

A: Replacing "divide by zero" with zero is controversial - but it's also not the only option. In some cases replacing with 1 is (reasonably) appropriate. I often find myself using
 ISNULL(Numerator/NULLIF(Divisor,0),1)

when I'm looking at shifts in scores/counts, and want to default to 1 if I don't have data. For example
NewScore = OldScore *  ISNULL(NewSampleScore/NULLIF(OldSampleScore,0),1)

More often than not, I've actually calculated this ratio somewhere else (not least because it can throw some very large adjustment factors for low denominators. In this case I'd normally control for OldSampleScore is greater than a threshold; which then precludes zero. But sometimes the 'hack' is appropriate.

A: Filter out data in using a where clause so that you don't get 0 values.

A: Sometimes, 0 might not be appropriate, but sometimes 1 is also not appropriate.  Sometimes a jump from 0 to 100,000,000 described as 1 or 100-percent change might also be misleading.  100,000,000 percent might be appropriate in that scenario.  It depends on what kind of conclusions you intend to draw based on the percentages or ratios.
For example, a very small-selling item moving from 2-4 sold and a very large-selling item changing from 1,000,000 to 2,000,000 sold might mean very different things to an analyst or to management, but would both come through as 100% or 1 change.
It might be easier to isolate NULL values than to scour over a bunch of 0% or 100% rows mixed with legitimate data.  Often, a 0 in the denominator can indicate an error or missing value, and you might not want to just fill in an arbitrary value just to make your dataset look tidy.
CASE
     WHEN [Denominator] = 0
     THEN NULL --or any value or sub case
     ELSE [Numerator]/[Denominator]
END as DivisionProblem

A: This is how I fixed it:
IIF(ValueA != 0, Total / ValueA, 0)

It can be wrapped in an update:
SET Pct = IIF(ValueA != 0, Total / ValueA, 0)

Or in a select:
SELECT IIF(ValueA != 0, Total / ValueA, 0) AS Pct FROM Tablename;

Thoughts?

A: You can handle the error appropriately when it propagates back to the calling program (or ignore it if that's what you want). In C# any errors that occur in SQL will throw an exception that I can catch and then handle in my code, just like any other error.
I agree with Beska in that you do not want to hide the error. You may not be dealing with a nuclear reactor but hiding errors in general is bad programming practice. This is one of the reasons most modern programming languages implement structured exception handling to decouple the actual return value with an error / status code. This is especially true when you are doing math. The biggest problem is that you cannot distinguish between a correctly computed 0 being returned or a 0 as the result of an error. Instead any value returned is the computed value and if anything goes wrong an exception is thrown. This will of course differ depending on how you are accessing the database and what language you are using but you should always be able to get an error message that you can deal with.
try
{
    Database.ComputePercentage();
}
catch (SqlException e)
{
    // now you can handle the exception or at least log that the exception was thrown if you choose not to handle it
    // Exception Details: System.Data.SqlClient.SqlException: Divide by zero error encountered.
}

A: Use NULLIF(exp,0) but in this way - NULLIF(ISNULL(exp,0),0)
NULLIF(exp,0) breaks if exp is null but NULLIF(ISNULL(exp,0),0) will not break


text:
Q: Unable replace \x.. sequence from a twitter feed in R I've been grappling with regex in following string:
"Just beautiful, let's see how the next few days go. \n\nLong term buying opportunities could be around the corner \xed\xa0\xbd\xed\xb2\xb0\xed\xa0\xbd\xed\xb3\x89\xed\xa0\xbd\xed\xb2\xb8... https://t dot co/hUradDaNVX"

*

*I am unable to remove the entire \x...\x pattern from the above string.

*I'm unable to remove https URL from above string.

My regex expression are:
gsub('http.* *', '', twts_array)
gsub("\\x.*\\x..","",twts_array)

My output is:
"Just beautiful let's see how the next few days go \n\nLong term buying opportunities could be around the corner \xed\xa0\xbd\xed\xb2\xb0\xed\xa0\xbd\xed\xb3\x89\xed\xa0\xbd\xed\xb2\xb8... httpstcohUradDaNVX"

My expected output is:
Just beautiful, let's see how the next few days go. Long term buying opportunities could be around the corner

P.S: As you can see neither of problems got solved. I also added dot for . in https://t dot co/hUradDaNVX as StackOverflow does not allow me to post shortened urls. Can some one help me in tackling this problem.

A: On Linux you can do the following:
twts_array <- "Just beautiful, let's see how the next few days go. \n\nLong term buying opportunities could be around the corner \xed\xa0\xbd\xed\xb2\xb0\xed\xa0\xbd\xed\xb3\x89\xed\xa0\xbd\xed\xb2\xb8... https://t dot co/hUradDaNVX"

twts_array_str <- enc2utf8(twts_array)
twts_array_str <- gsub('<..>', '', twts_array_str)
twts_array_str <- gsub('http.*', '', twts_array_str)

twts_array_str
# "Just beautiful, let's see how the next few days go. \n\nLong term buying opportunities could be around the corner ... "

enc2utf8 will convert any unknown Unicode sequences to <..> format. Then it will be replaced by gsub with URL as well.


text:
Q: PHP $_Server Not Working Properly I have the following line:

http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]

It's all great and it displays the current link, let's say: http://www.example.com/mypage.php
Now I want to associate this with a variable as such
$myURL = 'http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]'

When I echo this out I get "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" - in other words the code itself. What am I doing wrong?
I've also tried:
$myURL = '{http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]}'
I've also tried echoing it out directly:
echo 'http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]';

What am I overlooking? Thank you!

A: Variables are not interpolated when in single quotes. Use double quotes:
$myURL = "http://$_SERVER['HTTP_HOST']$_SERVER['REQUEST_URI']";

Or, for clarity:
$myURL = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$myURL = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$myURL = sprintf("http://%%",$_SERVER['HTTP_HOST],$_SERVER['REQUEST_URI']);


text:
Q: Maximal entropy of joint distribution of 2 independent random variables given probability of equality Consider 2 INDEPENDENT random variables $X$ and $Y$ with values in $A=\{0, 1, \ldots, q-1\}$. Suppose that $P(X=Y)$ is equal to some constant $\varepsilon$.

*

*What is the maximal entropy $H(X, Y)$?

*At which distribution this maximum is attained?
My hypothesis is that the distribution $P(X=0)=P(Y=0)=\alpha$, $P(X=k)=P(Y=k)=(1-\alpha) / (q - 1)$, $k=1,\ldots,q-1$ gives the optimal answer, where $\alpha$ is calculated from equation $\alpha^2+(1-\alpha)^2/(q-1)=\varepsilon$. Using the standard method of Lagrange multipliers and some hacks I've managed to prove that for $\varepsilon>1/q$ the optimal distribution have the following form
$P(X=i)=P(Y=i)=p_1$ for $i=0, \ldots, l-1$ and $P(X=i)=P(Y=i)=p_2$ for $k=l,\ldots,q-1$. Computer simulations show that you can always pick $l=1$.


text:
Q: Unable to use QFileSystemModel along custom QSortFilterProxy I'm new to qt and trying to hide some directories in a QTreeView. I'm trying to hide some folders based on their names using a custom QSortFilterProxy named CacheFilterProxy.
I setup the tree view this way:
fileModel = QtGui.QFileSystemModel()
rootIndex = fileModel.setRootPath(rootDir)
fileModel.setFilter(QtCore.QDir.Dirs | QtCore.QDir.NoDotAndDotDot)
fileModel.setNameFilters([patternString])
model = CacheFilterProxy()
model.setSourceModel(fileModel)
self.fileTreeView.setModel(model)
self.fileTreeView.setRootIndex(model.mapFromSource(rootIndex))
self.fileTreeView.clicked.connect(self.selectedFileChanged)

and then, in self.selectedFileChanged I try to extract fileName and filePath of currently selected item in tree view. Name of the file will be easily retrieved, but retrieving file path causes the whole program to stop working and then quit.
def selectedFileChanged(self, index):
    fileModel = self.fileTreeView.model().sourceModel()
    indexItem = self.fileTreeView.model().index(index.row(), 0, index.parent())
    # this works normal
    fileName = fileModel.fileName(indexItem)
    # this breaks the entire program
    filePath = fileModel.filePath(indexItem)

A: This seems wrong. Your fileModelis the source but I think index is a proxy index. I think you must map it to the source model before using it in the fileModel.
def selectedFileChanged(self, proxyIndex):
    sourceModel = self.fileTreeView.model().sourceModel()
    sourceIndex = self.fileTreeView.model().mapToSource(proxyIndex)
    sourceIndexCol0 = sourceModel.index(sourceIndex.row(), 0, sourceIndex.parent())

    # this works normal
    fileName = sourceModel.fileName(sourceIndexCol0)
    # this breaks the entire program
    filePath = sourceModel.filePath(sourceIndexCol0)

Note that I renamed indexItem to sourceIndexCol0 as it is an index and not an item. It was a bit confusing at first glance.
I could not test the code above. If it doesn't work, verify that the indexes are valid before using them and check their model class.


text:
Q: a very simple case does not write pdf file by using itext in IBM i i'm trying to use itext (5.5.13) in IBM i (AKA iseries, Power, long ago AS/400). It could be done embedding java code into RPG ILE procedures, or executing plain java. We use Apache POI for Excel for a while, and it works well. We are testing itext now, but some issue persist yet.
Given that, I'm trying to test itext in plain java into IBM i. I prepared a very simple example, taken from listing 1.1 of "Itext in action", and run it. It seems to work well, but nothing is generated. No pdf file results. And no error appears while running.
am i forgetting something? are there some other aspects to take in account?
here is the code:
package QOpenSys.CONSUM.Testjeu;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class test1{
    public static final String filePdf = "/QOpenSys/MyFolder/Testjeu/PdfRead1.pdf";

    public static void main(String[] args)
    throws DocumentException, IOException
     {
        ///QOpenSys/MyFolder/Test/WrkBookRead1.pdf

        //pdfDocument = new_DocumentVoid()
        Document pdfDocument = new Document();

        //pdfWriter = get_PdfWriter( pdfDocument: pdfFilePath);
        PdfWriter.getInstance(pdfDocument, new FileOutputStream( filePdf ));

        // jItxDocumentOpen( pdfDocument );
        pdfDocument.open();

        //pdfParagraph = new_PdfParagraphStr( PhraseString );
        Paragraph jItxParagraph = new Paragraph("Hola, pdf");

        //addToDocPg = jItxDocumentAddParagraph( pdfDocument: pdfParagraph );
        pdfDocument.add(jItxParagraph);

        //jItxDocumentClose( pdfDocument );
        pdfDocument.close();
    }
}

A: Solved. As said before, there was a first issue: it seems java function ran well because not errors/warnings were visible at qshell. It was false: errors were sent to outq, and were available at spool file. Being reviewed, it was a simple classpath issue. It required a full day to figure out what failed locating classpath.
Now it works, and pdf is created. I ran it on qshell, declaring environment variables for java_home (three jvm are executed concurrently by several applications), for classpath, and a couple required for tracing. Classpath declares first my class and secondly itext classes. Remaining classes comes from JRE. I have a full list of classes loaded by class loader. I hope it will help to find what fails in our embedded RPG ILE call to itext.


text:
Q: Can not get Shopify online access token I am using @shopify/koa-shopify-auth and need to implement online access mode authorization flow, I set accessMode to online but still get offline access token which does not contain associated_user data described in Shopify docs

Please, correct me If I am doing something wrong.

A: After some debugging I found out that the problem was in @shopify/koa-shopify-auth. it just did not put the data to session. This is the pull request for the fix.


text:
Q: Reading a power transformer ratings table I'm  trying to read a rating table of a power transformer that is available for sale on Alibaba (link: https://www.alibaba.com/product-detail/Three-Phase-Step-Down-Distribution-Transformer_1600350385746.html?spm=a2700.7724857.normal_offer.d_title.4d2a5f484VjJCX). I just want to know that there are multiple voltage ratings on it i.e. 110v/220v/400v/3kv. There are four voltages mentioned in this ratio. All I want to know is what this represents and how it gives the information about the voltage ratio of transformer.
Thank you.

A: Down the page of the linked information, a table shows: 10kva; 110v/220v/400v/3kv; Dyn11/Yd11/Yyno. That seems to be a 10kva transformer that has 3 low voltage options for 3kv high voltage with three vector group connections. However, the overview indicates this is an autotransformer. It seems to me that there is not a way to achieve that with an autotransformer.


text:
Q: getting a win percentage from one-hot encoded dataframe i have this one-hot encoded dataframe
the win column is one if the observations won and 0 otherwise.
how do i get the win percentage for each one of the categories (food,fitness,retail,grocery)?
each observation can be in multiple categories and some ids are duplicated because each id is an experiment where multiple things can be tested.
id food    fitness   retail    grocery win
1  1       0         1         1       1
2  1       0         0         0       0
3  0       1         0         0       1
4  1       0         0         1       1
4  1       0         0         1       0
5  1       0         1         0       1
6  0       1         1         0       1
6  0       1         1         0       0

expected output
category win_percentage
food     .6
fitness  .66
retail   .75
grocery  .66

A: You can do this:
df1 = df.drop(['id','win'], 1)
win_percent = df1[df1 == 1].mul(df.win, 0).mean()

Output
win_percent

food       0.600000
fitness    0.666667
retail     0.750000
grocery    0.666667
dtype: float64

To get exactly your expected output:
win_percent.to_frame('win_percent').rename_axis('category').reset_index()

  category  win_percent
0     food     0.600000
1  fitness     0.666667
2   retail     0.750000
3  grocery     0.666667

A: category, win_perecentage = [], []
for c in df.loc[:, "food":"grocery"]:
    category.append(c)
    win_perecentage.append(df.loc[df[c] == 1, "win"].sum() / df[c].sum())

df_out = pd.DataFrame(
    {"category": category, "win_perecentage": win_perecentage}
)
print(df_out)

Prints:
  category  win_perecentage
0     food         0.600000
1  fitness         0.666667
2   retail         0.750000
3  grocery         0.666667


text:
Q: In Java, how would I round a number to an arbitrary level of precision? For example suppose I have a method
double roundDown(double unrounded, double precision) {
}

roundDown(137.42973, 0.01) would return 137.42
roundDown(137.42973, 0.05) would return 137.4
roundDown(137.42973, 0.25) would return 137.25

Are there libraries to do something like this otherwise is the algorithm reasonably simple?

A: Divide the original number by the precision, round down to the nearest integer, and then multiply by the precision again:
double roundDown(double unrounded, double precision) {
    return precision * Math.floor(unrounded / precision);
}

Note that inherent floating point inaccuracies mean that your number may not be exactly the answer you're looking for - e.g. you might get 137.399999 instead of 137.4

A: If you want truly arbitrary precision in decimal, look into this library: http://download.oracle.com/javase/1.4.2/docs/api/java/math/BigDecimal.html


text:
Q: migrating/replacing Magento 1.3 data to maganeto 1.6 We have a Magento 1.3 project and we want it to upgrade it into magento 1.6.
so We Install a new magento 1.6, Now we want to put all the products and customers data from maganeto 1.3 to magento 1.6. We back up all the products and customers data in its database tables from the magento 1.3.
these are the tables that We backed up the datas:
-------------------------------------
Product Tables:
-------------------------------------
catalogrule /
catalogrule_product /
catalogrule_product_price /
catalogrule_affected_product /

catalogindex_price /
catalogindex_eav /
catalogindex_minimal_price /
catalogindex_aggregation_tag /
catalogindex_aggregation /
catalogindex_aggregation_to_tag /

catalogsearch_query /
catalogsearch_fulltext /
catalogsearch_result /
catalog_compare_item /

catalog_category_product /
catalog_category_product_index /
catalog_category_flat_1 /

catalog_product_entity_tier_price /
catalog_product_enabled_index /
catalog_product_website /

catalog_category_entity /
catalog_category_entity_datetime /
catalog_category_entity_decimal /
catalog_category_entity_int /
catalog_category_entity_text /
catalog_category_entity_varchar /

catalog_product_entity /
catalog_product_entity_datetime /
catalog_product_entity_decimal /
catalog_product_entity_gallery /
catalog_product_entity_int /
catalog_product_entity_media_gallery /
catalog_product_entity_media_gallery_value /
catalog_product_entity_text /
catalog_product_entity_varchar /

catalog_product_super_link /
catalog_product_link_type /
catalog_product_link /
catalog_product_link_attribute /
catalog_product_link_attribute_decimal /
catalog_product_link_attribute_int /
catalog_product_link_attribute_varchar /

catalog_product_option/
catalog_product_option_title /
catalog_product_option_price /
catalog_product_option_type_value /
catalog_product_option_type_title /
catalog_product_option_type_price /

cataloginventory_stock /
cataloginventory_stock_status /
cataloginventory_stock_item /

catalog_product_bundle_option /
catalog_product_bundle_option_value /
catalog_product_bundle_selection /
catalog_product_bundle_price_index /

catalog_product_super_attribute //
catalog_product_super_attribute_label/
catalog_product_super_attribute_pricing /

product_alert_price /
product_alert_stock /

downloadable_link_price /
downloadable_link_title /
downloadable_link  /
downloadable_sample_title /
downloadable_sample /

----------------------------------------------
Customers Tables :
----------------------------------------------
customer_group/

newsletter_template /
newsletter_queue/
newsletter_queue_store_link/
newsletter_problem/
newsletter_queue_link/
newsletter_subscriber/

customer_entity/
customer_entity_datetime/
customer_entity_decimal/
customer_entity_int/
customer_entity_text/
customer_entity_varchar/

customer_address_entity/
customer_address_entity_datetime/
customer_address_entity_decimal/
customer_address_entity_int/
customer_address_entity_text/
customer_address_entity_varchar/

review_entity/
review_status/
review/
review_store/
review_entity_summary/
review_detail/

rating_entity/
rating/
rating_store/
rating_option
rating_option_vote/
rating_title/
rating_option_vote_aggregated/

poll/
poll_store/
poll_answer/
poll_vote/

wishlist/
wishlist_item/

then We delete all products and customers data in its database tables in the magento 1.6. Now, when we restore the backed up data from magento 1.3 to 1.6, We got this error...
Query:
/*Data for the table `catalog_category_entity` */
insert  into `catalog_category_entity`(...)

Error occured at:2012-09-12 14:05:06
Line no.:20
Error Code: 1062 - Duplicate entry '1' for key 'PRIMARY'

I was just wondering that, why it became "Duplicate entry for primary key" when I deleted all the old data in the magento 1.6?
Does anyone have an idea about my case? Can you give me another Idea about on how can I transfer all products and customers data from magento 1.3 to 1.6?
any help will be appreciated. Thanks in advance...

A: better way:

*

*turn of caching

*turn off all custom local and community extensions

*turn off all local core overwrites

*turn off all custom themes and theme customisations

*regenerate indexes

*copy in 1.6 or latest Magento code

*fire the upgrade and be done with it


text:
Q: Unit testing my wcf services I am hoping there is a better way to do this.  Do I really have to wrap each method of my wcf service into an interface in order to use it?
I don't think my fellow developers are going to buy into this because of the amount of time it takes... there must be a better way!

A: Wrapping each method of a service into an interface isn't only testable design, but in general a good design. If you want to replace your wcf services with say rest service, consumers of the service don't have to do anything as they are using the interface. Using, an interface will allow you to do mocking and all that, which is good. But, here the most important thing is correct design.


text:
Q: How to display the name with the smallest length inside the Array - JavaScript let friends = ['Alfonso Waters', 'Mona', 'Mania','Mona Dunn', 'Mae','Mae Lane']

A: Hope it's not too confusing :)
friends = ['Alfonso Waters', 'Mona', 'Mania','Mona Dunn', 'Mae','Mae Lane']
friends_lenght = friends.map(word => word.length)
friends_lenght_min_index = Math.min(...friends_lenght)
friend_index = friends_lenght.indexOf(friends_lenght_min_index)
friend = friends[friend_index]

// Output
// 'Mae'

p.s. You can make a function out of this code.


text:
Q: Modify value in iterator of a for-each loop I currently started with learning Swift 3 (I already have experience with other programming languages) and asked me the question if I can modify a value inside of an iterator of a for-each loop (not for-in!). Let's take a look at the following example:
var numbers = [45000.0, 50000.0, 60000.0]

for i in 0..<numbers.count {
    numbers[i] = numbers[i] + (numbers[i] * 0.1)
}

In this example, I could modify the value inside of the array. But if I want to use the for-each loop:
for number in numbers {
    number = number + (number * 0.1)
}

it will not compile. Is it possible in any other way to modify the value of number (which seems to me like an iterator in C++)?
Thanks for all answers!

A: You are still thinking in terms of old programming languages. The modern approach is to do everything in one step using a helper function, without using manual iteration:
let numbers = [45000.0, 50000.0, 60000.0]
let newNumbers = numbers.map { $0 + $0 * 0.1 }

Note we have generated a new array instead of changing the existing one. The use of constants (immutables) helps us to avoid many common programming mistakes.

A: It is not possible using your example because Array<Double> is value type and the index variable number is a constant. To make number mutable you have to copy it which leaves the original item in the array unchanged.
A compromise is the enumerated() function.
var numbers = [45000.0, 50000.0, 60000.0]

for (i, number) in numbers.enumerated() {
    numbers[i] = number + (number * 0.1)
}

However the solution suggested by Sulthan is preferable.


text:
Q: Is there any way to run an onClick event before a formik onSubmit? I am trying to create a login page with the following submit button
<Button
  color="primary"
  disabled={isSubmitting}
  fullWidth
  size="large"
  type="submit"
  variant="contained"
  onClick={() => { login(values.email, values.password); }}>
  Sign in
</Button>

The login logic looks like this
const login = async (email, password) => {
  try {
    const user = await signInWithEmailAndPassword(
      auth,
      email,
      password
    );
    console.log('User: ', user);
    authenticated = true;
    console.log('Authenticated: ', authenticated);
  } catch (error) {
    console.log('Error: ', error);
    authenticated = false;
  }
};

My formik component looks like this
<Formik
  initialValues={{
    email: '',
    password: ''
  }}
  validationSchema={Yup.object().shape({
    email: Yup.string().email('Must be a valid email').max(255).required('Email is required'),
    password: Yup.string().max(255).required('Password is required')
  })}
  onSubmit={() => {
    console.log('Authenticated: ', authenticated);
    if (authenticated === true) {
      navigate('/app/dashboard', { replace: true });
    }
  }}
>

My idea is to get the onClick of the submit button, to run the login logic before the onSubmit runs, this would set authenticated to true and allow the user to be redirected to Dashboard.js. Currently, it seems like the onSubmit runs before the onClick, causing authenticated to have it's default value of false and thus not redirecting the user to the Dashboard.

A: Since your login function is an async function, it returns a promise and hence the login inside onSubmit runs asynchronously.
You can call the login function inside onSubmit but have to wait for the promsie to fulfill
for example:
<Formik
  initialValues={{
    email: '',
    password: ''
  }}
  validationSchema={Yup.object().shape({
    email: Yup.string().email('Must be a valid email').max(255).required('Email is required'),
    password: Yup.string().max(255).required('Password is required')
  })}
  onSubmit={() => {
    login(email, password)
    .then(() => {
      console.log('Authenticated: ', authenticated);
      if (authenticated === true) {
        navigate('/app/dashboard', { replace: true });
      }
    })
    .catch((error) => {
       // handle error
    })
  }}
>

Also rather than setting a variable authenticated outside a scope you can simply return from the login function and use it in the promise success handler.
const login = async (email, password) => {
  try {
    const user = await signInWithEmailAndPassword(
      auth,
      email,
      password
    );
    console.log('User: ', user);
    return true
  } catch (error) {
    console.log('Error: ', error);
    throw error
  }
};

  onSubmit={() => {
    login(email, password)
    .then((isAuthenticated) => {
      console.log('Authenticated: ', isAuthenticated);
      if (isAuthenticated === true) {
        navigate('/app/dashboard', { replace: true });
      }
    })
    .catch((error) => {
       // handle error
    })
  }}

Please read and understand more about javascript promises, asynchronous javascript and how they work.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise


text:
Q: What is the "bounty size" sort actually sorting by in new nav? When visiting the bounty list with the new navigation, I attempted to sort by the "bounty size". My sort selection looks like this:

The expectation is that this will return a list of bounties sorted either highest to lowest or lowest to highest (I'm not picky) across all available bounties.
The actual returned list is a sorted list of bounties sorted by size from highest to lowest PER RESULT PAGE.
For example, page one (50 questions per page) of the bounties returns this:

Page 8, returns this:

I would expect everything on page 8 that had a bounty of 150 or higher to have appeared in my page one results.
Update after new-new nav release:
The bug is still present.
Page 1: http://i.imgur.com/cHzYFWg.png,
Page 2: http://i.imgur.com/VbH4N6D.png
Page 3: http://i.imgur.com/HH0S4QN.png


text:
Q: Why is a binary search over a sorted vector is slower than std::set find? Here you can see the code, run it and see the times.
http://rextester.com/MNQZS47293
I get similar results on my machine (using the same version of MSVC), the lookup in the vector is slower than in the std::set.
I would expect the sorted vector version to be faster, due to better locality of the data (more cache friendly).
In the worse case, I would expect them to be similar, because they both perform a binary search, but I cannot understand why the std::set is much faster than the sorted vector version.
Thank you very much
Edit: Sorry, I pasted the wrong link (I modified the code but forgot to copy the link) the old code was using an unordered_set, this code is using a set, and the question remains the same: Why is the binary search over a sorted vector slower than over a set? I've noticed that if the number of elements is large enough, then the sorted vector is faster, but I still cannot understand why the set can outperform the sorted vector for any number of elements.

A: The linked code seem to use unordered_set, not set.
unordered_set is a hash table. There the search is not binary search. There, search performance depends on the hash function and the load factor.

A: For the updated question:
-O1 and -O2 gives the same performance for the two methods.
-Ox slows down the vector version.
Why this is, you need to look at the disassembly or at the details of the -Ox level. It has nothing to do with the algorithmic properties of set.find and lower_bound/binary_search.
Regarding the locality of data. A binary_search and a set::find has for reasonable implementations exactly the same locality of data. The set might even win with the data being read in a left-to-right fashion.


text:
Q: Sine of the signal in Xilinx Simulink I am implementing a DQPSK modulator and Demodulator. I would like to calculate the exp(1j*Phase) in Simulink.
How can I realize such a model ?
Here is the part of the model to calculate the Phase:

Incidentally, ROM3 block in the model stores the values: 0, pi/2, pi, 3*pi/2 ( Constellation points)

A: Two options for implementing sin(x) in an FPGA:

*

*lookup table

*CORDIC
I have no idea how you would link these with your Simulink model.


text:
Q: Why does my programme not react to "Alt" + "F4"? I am working on a GUI for a little java game. I have a class Window that extends a JFrame and contains an object of MainMenuPanel, a class that extends a JPanel and contains some JButtons.
I want that the MainMenuPanel is replaced with an object of OptionsPanel, a class that also extends a JPanel, after clicking the optionsButton.
I realized this using the following code:
public class MainMenuPanel extends JPanel implements ActionListener
{
    private Window window;
    private JButton playButton;
    private JButton optionsButton;
    private ImageIcon buttonIcon;
    private SavegamesPanel savegamesPanel;
    private OptionsPanel optionsPanel;

    public MainMenuPanel(Window w)
    {
        window = w;

        setSize(window.getContentPane().getSize());
        setLocation(0, 0);
        setLayout(null);

        playButton = new JButton();
        optionsButton = new JButton();

        buttonIcon = new ImageIcon("res/buttonIcon.png");

        playButton.setIcon(buttonIcon);
        playButton.setSize(200, 50);
        playButton.setLocation(((window.getContentPane().getWidth() - 200) / 2), ((window.getContentPane().getHeight() - 200) / 2));
        playButton.addActionListener(this);

        optionsButton.setIcon(buttonIcon);
        optionsButton.setSize(200, 50);
        optionsButton.setLocation(((window.getContentPane().getWidth() - 200) / 2), (((window.getContentPane().getHeight() - 200) / 2) + 50));
        optionsButton.addActionListener(this);

        add(playButton);
        add(optionsButton);
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource().equals(playButton))
        {
            //do things
        }
        else if(e.getSource().equals(optionsButton))
        {
            window.remove(this);

            optionsPanel = new OptionsPanel(window, null, 0);

            window.add(optionsPanel);
            window.repaint();
        }
    }
}

The problem is that after the panels have changed the key combination Alt + F4 does not work anymore and I do not understand why.
You might say that this is not very important but it will cause other problems for me later.
So I would be very happy if you could help me!

A: As already mentioned in the comments, Alt+F4 simply tells the active window to close. The window needs to actually respond to this event for anything to actually happen.
You can either make use of setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) (e.g. somewhere in your JFrame construction chain), or you can explicitly listen for window events using a java.awt.event.WindowListener yourself. The WindowListener is called when the window is closed (either by the button or Alt-F4), and you will need to actively close the window (e.g. using setVisible(false)).
Unless you do something (very) weird, your panels inside the window should have no effect at all on the behaviour of the window with respect to closing.


text:
Q: Getting ajax loaded elements in chrome extension I am trying to create a chrome extension that accesses a web site in the background, gets an element from the loaded page and then changes the badge text according to that element.
So far I have this in background.js:
function updateIcon(text) {
    chrome.browserAction.setBadgeText({"text": text});
}

chrome.browserAction.onClicked.addListener(function() {
    $.get(link, function(data) {
        myText = $(data).filter("#myElement").html()
        updateIcon(myText);
    });
});

And this works perfect on my test.html page:
<html>
  <button id="myElement">Test</button>
</html>

But as I have recently found out, the reason it doesn't work on the page I intend to use it is because "myElement" is loaded via ajax and is not in the dom on pageload. Would there be any methods of getting that element even if it loads through ajax? Right now my code returns an "undefined" value.

A: In the end I followed wOxxOm's advice and reproduced the site's AJAX requets and it worked. Thank you.


text:
Q: Confidence interval - No sample "According to thorough measurements, the average waiting time at a restaurant is normally distributed with an average of $28$ minutes and a standard deviation of $5$ minutes.
Calculate a $95\%$ confidence interval for the waiting time."
So what I do first is that I calculate the z for the confidence interval $95\%$. Which is $z = 1.96$. And I'm aware of the following formula:
$$\bar{X} - z_{a/2}\cdot \left(\frac{\sigma}{\sqrt{n}}\right) < \mu < \bar{X} + z_{a/2}\cdot\left(\frac{\sigma}{\sqrt{n}}\right)$$
However, since I wasn't given a sample, I'm not sure how to compute $\sqrt{n}$, what would I do next?

A: Since the waiting time $X$ at a restaurant is normally distributed with an average of $28$ minutes and a standard deviation of $5$ minutes, in symbols $$X \sim N(\mu=28,\sigma=5)$$ the $95\%$ confidence interval with the least width is given by $$P(x_{0.025}\le X\le x_{0.975})$$ But since generally $$x_p=μ+σ\cdot z_p$$ you can use the standard normal distribution table to conclude that $$x_{0.025}=28+5\cdot(-1.96)=18.2 \\ x_{0.975}=28+5\cdot (+1.96) = 37.8\phantom{}$$ Thus, the $95\%$ confidence interval for the waiting time is $$(l,u)=(18.2, 37.8)$$

Thorough examination means a very big sample (actually the whole population). That is why you do not have to consider any sample and you can take $X$ that refers directly to the population.


text:
Q: Certain Range of Date in each Month I'd like to have a range of day 20th - 25th in each month in BigQuery but i dont know what syntax should i use. For ex:
Jan 20 - 25
Feb 20 - 25
and so on
I only can think of creating a CTE for every month then union all those.

A: Consider below query.
SELECT DATE_ADD(month, INTERVAL day - 1 DAY) date_range,
  FROM UNNEST(GENERATE_DATE_ARRAY('2022-01-01', '2022-03-01', INTERVAL 1 MONTH)) month,
       UNNEST(GENERATE_ARRAY(20, 25)) day;

Query results

Below seem to be more simple than my original answer and you could adjust date range by specifying condition on WHERE clause.
SELECT *
  FROM UNNEST(GENERATE_DATE_ARRAY('2022-01-01', '2022-12-31', INTERVAL 1 DAY)) date_range
 WHERE EXTRACT(DAY FROM date_range) BETWEEN 21 AND 25

For the usecase that you commented,

WHERE EXTRACT(DAY FROM date_range) >= 21 OR EXTRACT(DAY FROM date_range) = 1


text:
Q: Odoo - Hide button for specific user I am using odoo 10 enterpeise . I want to show buttons to specific users not to groups because there would be many users in a group and i want to only show below button who have the previlige to reject/approve a object.
Here is button
<xpath expr="//sheet" position="before">
          <header>
            <button name="update_approve" attrs="{'invisible':[('first_approve', '=', uid)]}" string="Approve" type="object" class="oe_highlight"/>
              <button name="update_reject" attrs="{'invisible':[('second_approve', '=', uid)]}" string="Reject" type="object" class="btn-danger"/>
          </header>
      </xpath>

I tried to do this using uid but uid is not available in xml
first_approve and second_approve are the fields in my model based on which i want to show button only to users which are assigned in first_approve/second_approve

A: One of the thing i know to use a field in attrs the field must be Mentionsed in the form.
 i don't know how to get the value of the user id in the form. but if there is not a short
 way like uid or user you can work arround this, just create a m2o field to res.users
 make this field compute field with store = False.
    # by default store = False this means the value of this field
    # is always computed.
    current_user = fields.Many2one('res.users', compute='_get_current_user')

    @api.depends()
    def _get_current_user(self):
        for rec in self:
            rec.current_user = self.env.user

and you can use this field in your form.
    <xpath expr="//sheet" position="before">
              <header>
                 <!-- fin a good place for the field if i make the header look ugly -->
                <!-- make invisible -->
                 <field name="current_user" invisible="1"/>
                                                                                <!-- hope it work like this -->
                <button name="update_approve" attrs="{'invisible':[('first_approve', '=', current_user)]}" string="Approve" type="object" class="oe_highlight"/>
                <button name="update_reject" attrs="{'invisible':[('second_approve', '=', current_user)]}" string="Reject" type="object" class="btn-danger"/>
              </header>
     </xpath>

sorry for my english.

A: I have understood that you have a fixed list of users who will be able to approve and other fixed list of users who will be able to reject. In spite of being a few users, I would create two groups and use groups attribute on your buttons, but if even so you do not want to create a couple of groups for them, you can do this:
from openerp import models, api
import json
from lxml import etree

FIRST_APPROVE = []  # Fill this list with the IDs of the users who can update approve
SECOND_APPROVE = []  # Fill this list with the IDs of the users who can update reject

class YourClass(models.Model):
    _inherit = 'your.class'

    def update_json_data(self, json_data=False, update_data={}):
        ''' It updates JSON data. It gets JSON data, converts it to a Python
        dictionary, updates this, and converts the dictionary to JSON data
        again. '''
        dict_data = json.loads(json_data) if json_data else {}
        dict_data.update(update_data)
        return json.dumps(dict_data, ensure_ascii=False)

    def set_modifiers(self, element=False, modifiers_upd={}):
        ''' It updates the JSON modifiers with the specified data to indicate
        if a XML tag is readonly or invisible or not. '''
        if element is not False:  # Do not write only if element:
            modifiers = element.get('modifiers') or {}
            modifiers_json = self.update_json_data(
                modifiers, modifiers_upd)
            element.set('modifiers', modifiers_json)

    @api.model
    def fields_view_get(self, view_id=None, view_type='form', toolbar=False,
                        submenu=False):
        res = super(YourClass, self).fields_view_get(
            view_id=view_id, view_type=view_type, toolbar=toolbar,
            submenu=submenu)

        doc = etree.XML(res['arch'])

        if view_type == 'form':
            if self.env.uid in FIRST_APPROVE:
                upd_approve_btn_search = doc.xpath("//button[@name='update_approve']")
                upd_approve_btn = upd_approve_btn_search[0] \
                    if upd_approve_btn_search else False
                if upd_approve_btn:
                    self.set_modifiers(upd_approve_btn, {'invisible': False, })

            if self.env.uid in SECOND_APPROVE:
                upd_reject_btn_search = doc.xpath("//button[@name='update_reject']")
                upd_reject_btn = upd_reject_btn_search[0] \
                    if upd_reject_btn_search else False
                if upd_reject_btn:
                    self.set_modifiers(upd_reject_btn, {'invisible': False, })

        res['arch'] = etree.tostring(doc)
        return res

FIRST APPROVE and SECOND_APPROVE will be const in which you must introduce the fixed IDS of the users who can perform the respective action (for example: FIRST APPROVE = [2, 7, 9]).
YourClass must be the class in which you have declared the methods of your buttons (the one in which you have declared update_approve and update_reject).
IMPORTANT: with this code, your buttons must be always invisible (write invisible="1" at your XML view), because after loading the XML code, the fields_view_get will overwrite the invisible value to set 0.
This is an uncommon way to manage your purpose, but unfortunately I think it is the simplest one if you do not want to create groups. I hope it helps you and other users!


text:
Q: C++ Infinity Sign Hello I was just wondering how I can display the infinity (∞) in C++? I am using CodeBlocks. I read couple of Q&A's on this topic but I'm a newbie at this stuff, especially with Hex coding and stuff. What do I have to include and what do I type out exactly. If someone can write the code and explain it, that'd be great! Thanks!

A: The symbol is not part of the ASCII code. However, in the code page 437 (most of the time the default in Windows Command Prompt with English locales/US regional settings) it is represented as the character #236. So in principle
std::cout << static_cast<unsigned char>(236);

should display it, but the result depends on the current locale/encoding. On my Mac (OS X) it is not displayed properly.
The best way to go about it is to use the UNICODE set of characters (which standardized a large amount of characters/symbols). In this case,
std::cout << "\u221E";

should do the job, as the UNICODE character #221 represents inf.
However, to be able to display UNICODE, your output device should support UTF encoding. On my Mac, the Terminal uses UTF, however Windows Command Prompt still uses the old ASCII encoding CodePage 437 (thanks to @chris for pointing this out). According to this answer, you can change to UNICODE by typing
chcp 65001

in a Command Prompt.

A: You can show it through its UNICODE
∞ has the value: \u221E
You can show any character from the Character Map by its unicode.


text:
Q: Python requests post reponse 400 I have no idea where is error. My response is 400 cuz of it:
"errors":{"data":["The data field is required."
but i am sending 'data':
data = "{'example': 'example'}"
url = f'http://localhost:5219/myApi'
payload = {'data': str(data).encode('utf-8')}
req = requests.post(url, data=payload)
print(req.content)

response
b'{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-355ed090aff5fa10460587fe222edbbe-3b3927cf18b26b78-00","errors":{"data":["The data field is required."]}}'

how can i repair that?
i tried changing formats and other things but it didn't work pls help me
this is c# code from api:
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using System.Text.Json.Nodes;

namespace spyware.Api.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class api : ControllerBase
    {
        [HttpPost]
        public void GetResponse(string data)
        {
            Console.WriteLine(JsonConvert.DeserializeObject(data.ToString()));
        }

    }
}


text:
Q: Как передать значение input type="file" по localStorage Подскажите как сделать? Смысл - на одной странице index.html к которой прикреплен app.js пользователь выбирает аудиофайл, а на другой result.html и result.js - он запускается в плеере. При использовании localStorage значение File передается, но в переменной path которая берет значение из localStorage лежит уже не File  а [object File] . В результате - появляется вот такая ошибка GET file:///D:/education/DREAM_STARTING/2020/trainer/result/[object%20File] net::ERR_FILE_NOT_FOUND
Я передаю также имя файла по localStorage nameaudio - тут все нормально.
Как сделать, чтобы проигрыватель запускался? Вот код
index.html:

Выберите аудиофайл на своем устройстве:
                <input id="input1" type="file">

Go

app.js:

$(document).ready(function () {
  $('#but_go').on('click', function () {
    var nameaudioinindexhtml = document.getElementById('input1').files[0].name;
    var arrinindexhtml =input1.files[0];
    localStorage.setItem('audioname_ls', nameaudioinindexhtml);
    localStorage.setItem('arr_ls', arrinindexhtml);

result.js:

            let path = localStorage.getItem('arr_ls'),
            nameaudio = localStorage.getItem('audioname_ls');
$(document).ready(function(){
    let Song,  songs = [0,'Песня_1'];
   function playNewSong(id) {
            let duration;
            Song = new Audio();
            Song.src = path;
            Song.onloadeddata = function(){
                duration = Song.duration;
                songs.push(duration);
                songs.push(nameaudio);
                Song.play(); ... вот с этого места появляется ошибка
               .....код

A: Нужно преобразовать файл в Blob-ссылку и ставить в localStorage уже её
$(document).ready(function () {
  $('#but_go').on('click', function () {
    let audioName = $('#input1').files[0].name,
        audioURL = URL.createObjectURL($('#input1').files[0]);

    localStorage.setItem('audioname_ls', audioName);
    localStorage.setItem('arr_ls', audioURL);
  });
});


text:
Q: Silverstripe 3 - GridFieldExtensions MultiClass Adding I'm trying to use https://github.com/silverstripe-australia/silverstripe-gridfieldextensions/ to create a gridfield where I can add different types of dataobjects.
Sadly I can't figure out how to write the correct code for that on my class where I want the gridfield.
Could someone please point me in the right direction?
UPDATE:
Based on your answers, I now have the following structure
class ModularPage extends Page {

   private static $has_many = array(
    'Sections' => 'MP_Section',
    'Galleries' => 'MP_Gallery',
    'Paragraphs' => 'MP_Paragraph'
    );

    public function getCMSFields() {
        ...

        $fields->addFieldToTab('Root.Main', $mutli_grid = GridField::create('Sections', 'Sektionen', $this->Sections(), MultiClassGrid::create(15)));

        ...
    }

}

class MP_Section extends DataObject {

    private static $has_one = array(
        'Section' => 'MP_Section',
        'ModularPage' => 'ModularPage'
    );

}

class MP_Gallery extends MP_Section {

    private static $has_one = array(
        'Section' => 'MP_Section',
        'ModularPage' => 'ModularPage'
    );

}

So far, so good? Is this right until now?
Cause If I want to add for example a gallery, I receive the following error

[User Error] Couldn't run query: SELECT DISTINCT "MP_Section"."ID", "MP_Section"."SortID" FROM "MP_Section" LEFT JOIN "MP_Gallery" ON "MP_Gallery"."ID" = "MP_Section"."ID" LEFT JOIN "MP_Paragraph" ON "MP_Paragraph"."ID" = "MP_Section"."ID" WHERE ("ModularPageID" = '13') ORDER BY "MP_Section"."SortID" ASC LIMIT 9223372036854775807 Column 'ModularPageID' in where clause is ambiguous

A: Here is how I usually setup my GridField:
$c = GridFieldConfig_RelationEditor::create();
$c->removeComponentsByType('GridFieldAddNewButton')
  ->addComponent(new GridFieldAddNewMultiClass())
  ;

$c->getComponentByType('GridFieldAddNewMultiClass')
  ->setClasses(array(
    'SectionThemesBlock'    => SectionThemesBlock::get_section_type(),
    'SectionFeaturedCourse' => SectionFeaturedCourse::get_section_type(),
    'SectionCallForAction'  => SectionCallForAction::get_section_type(),
    'SectionContactSheet'   => SectionContactSheet::get_section_type()
    //....
  ));

$f = GridField::create('Sections', "Sections", $this->Sections(), $c);
$fields->addFieldToTab("Root.Sections", $f);

Based on the GridFieldConfig_RelationEditor, just remove GridFieldAddNewButton then add GridFieldAddNewMultiClass. Then configure the component to know which classes to have available in the dropdown to create. All those SectionThemesBlock, SectionFeaturedCourse etc extend a common Section dataObject as base. The get_section_type() function is a custom static function on the Section dataobject to get a nice looking name in the dropdown and not have to type it manually all the time....
The basics of the Section dataobject looks like so:
class Section extends DataObject {

  public static function get_section_type()
  {
    return trim(preg_replace('/([A-Z])/', ' $1', str_ireplace('Section', '', get_called_class())));
  }

  //...
}

And the page where that gridField goes and that has the relation defined on:
class Page extends SiteTree {
  //...
  private static $has_many = array(
    'Slides' => 'Slide'
  );
  //...
}

A: Something like this should work
        $config = new GridFieldConfig_RecordEditor();
        $config->addComponent(new GridFieldAddNewMultiClass());
         ...
        $grid = GridField::create('Grid', 'Grid', $this->GalleryItems(), $config);

You need three DataObjects:

*

*GalleryItem extends DataObject{}

*FooGalleryItem extends GalleryItem{}

*BarGalleryItem extends GalleryItem{}


text:
Q: Type of reference to boost::filtered_range value I want to add an operator[] to boost::filtered_range class.
There is my code:
template <typename TPredicate, typename TRange>
class my_filtered_range : public boost::filtered_range<TPredicate, TRange>
{
public:
    my_filtered_range(TPredicate Predicate, TRange &Range) : boost::filtered_range<TPredicate, TRange>(Predicate, Range)
    {
    }

    size_t size() const
    {
        return std::distance(begin(), end());
    }

    ???? &operator[](size_t Index) const
    {
        assert(Index < size());
        auto It = begin();
        std::advance(It, Index);
        return *It;
    }
};

The question is what type to use as return type for operator[]?
Specifiyng 'value_type' doesn't allow to use class with 'const' containers, "decltype(*begin())" doesn't compile with my VC++2013.

A: You should be able to use the boost::range_reference<> trait on the base class.
Live On  Coliru
#include <boost/range/adaptors.hpp>

template <typename TPredicate, typename TRange>
class my_filtered_range : public boost::filtered_range<TPredicate, TRange>
{
public:
    typedef boost::filtered_range<TPredicate, TRange> base_type;

    my_filtered_range(TPredicate Predicate, TRange &Range) : boost::filtered_range<TPredicate, TRange>(Predicate, Range)
    {
    }

    size_t size() const
    {
        return std::distance(this->begin(), this->end());
    }

    typename boost::range_reference<const base_type>::type operator[](size_t Index) const
    {
        assert(Index < this->size());
        auto It = this->begin();
        std::advance(It, Index);
        return *It;
    }
};

Note how I detected you are using a broken compiler (MSVC) so I added the necessary qualifications to dependent base members and types.