Better Way of Storing Old Data for Faster Access

Question: The application we are developing is writing around 4-5 millions rows of data every day. And, we need to save these data for the past 90 days.
The table user_data has the following structure (simplified):
id INT PRIMARY AUTOINCREMENT
dt TIMESTAMP CURRENT_TIMESTAMP
user_id varchar(20)
data varchar(20)

About the application:

Data that is older than 7 days old will not be written / updated.
Data is mostly accessed based on user_id (i.e. all queries will have WHERE user_id = XXX)
There are around 13000 users at the moment.
User can still access older data. But, in accessing the older data, we can restrict that he/she can only get the whole day data only and not a time range. (e.g. If a user attempts to get the data for 2016-10-01, he/she will get the data for the whole day and will not be able to get the data for 2016-10-01 13:00 - 2016-10-01 14:00).

At the moment, we are using MySQL InnoDB to store the latest data (i.e. 7 days and newer) and it is working fine and fits in the innodb_buffer_pool.
As for the older data, we created smaller tables in the form of user_data_YYYYMMDD. After a while, we figured that these tables cannot fit into the innodb_buffer_pool and it started to slow down.
We think that separating / sharding based on dates, sharding based on user_ids would be better (i.e. using smaller data sets based on user and dates such as user_data_[YYYYMMDD]_[USER_ID]). This will keep the table in much smaller numbers (only around 10K rows at most).
After researching around, we have found that there are a few options out there:

Using mysql tables to store per user per date (i.e. user_data_[YYYYMMDD]_[USER_ID]).
Using mongodb collection for each user_data_[YYYYMMDD]_[USER_ID]
Write the old data (json encoded) into [USER_ID]/[YYYYMMDD].txt

The biggest con I see in this is that we will have huge number of tables/collections/files when we do this (i.e. 13000 x 90 = 1.170.000). I wonder if we are approaching this the right way in terms of future scalability. Or, if there are other standardized solutions for this.
Answer: Scaling a database is an unique problem to the application. Most of the times someone else's approach cannot be used as almost all applications writes its data in its own way. So you have to figure out how you are going to manage your data.
Having said that, if your data continue to grow, best solution is the shadring where you can distribute the data across different servers. As long as bound to a single server like creating different tables you are getting hit by resource limits like memory, storage and processing power. Those cannot be increased unlimited manner.
How to distribute the data, that you have to figure out based on your business use cases. As you mentioned, if you are not getting more request on old data, the best way to distribute the data base on date. Like DB for 2016 data, DB for 2015 and so on. Later you may purge or shutdown the servers which you have more old data.
Answer: 1 million+ tables sounds like a bad idea. Having sharding via dynamic table naming by the app code at runtime has also not been a favorable pattern for me.  My first go-to for this type of problem would be partitioning.  You probably don't want 400M+ rows in a single unpartitioned table. In MySQL 5.7 you can even subpartition (but that gets more complex). I would first range partition on your date field, with one partition per day. Index on the user_id. If you are on 5.7 and want to dabble with subpartitioning, I would suggest range partition by date, then hash subpartition by user_id.  As a starting point, try 16 to 32 hash buckets.  Still index the user_id field.
EDIT: Here's something to play with:
CREATE TABLE user_data (
    id INT AUTO_INCREMENT
  , dt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  , user_id VARCHAR(20)
  , data varchar(20)
  , PRIMARY KEY (id, user_id, dt)
  , KEY (user_id, dt)
) PARTITION BY RANGE (UNIX_TIMESTAMP(dt))
  SUBPARTITION BY KEY (user_id)
  SUBPARTITIONS 16 (
    PARTITION p1 VALUES LESS THAN (UNIX_TIMESTAMP('2016-10-25')),
    PARTITION p2 VALUES LESS THAN (UNIX_TIMESTAMP('2016-10-26')),
    PARTITION p3 VALUES LESS THAN (UNIX_TIMESTAMP('2016-10-27')),
    PARTITION p4 VALUES LESS THAN (UNIX_TIMESTAMP('2016-10-28')),
    PARTITION pMax VALUES LESS THAN MAXVALUE
);

-- View the metadata if you're interested
SELECT * FROM information_schema.partitions WHERE table_name='user_data';

Comment: Thank you, Joshua. Will definitely try to explore more on PARTITION.
Answer: This is a big table, but not unmanageable.
If user_id + dt is UNIQUE, make it the PRIMARY KEY, and get rid if id, thereby saving space.  (More in a minute...)
Normalize user_id to a SMALLINT UNSIGNED (2 bytes) or, to be safer MEDIUMINT UNSIGNED (3 bytes).  This will save a significant amount of space.
Saving space is important for speed (I/O) for big tables.
PARTITION BY RANGE(TO_DAYS(dt))

with 92 partitions -- the 90 you need, plus 1 waiting to be DROPped and one being filled.  See details here .
ENGINE=InnoDB

to get the PRIMARY KEY clustered.
PRIMARY KEY(user_id, dt)

If this is "unique", then it allows efficient access for any time range for a single user.  Note: you can remove the "just a day" restriction.  However, you must formulate the query without hiding dt in a function.  I recommend:
WHERE user_id = ?
  AND dt >= ?
  AND dt  < ? + INTERVAL 1 DAY

Furthermore,
PRIMARY KEY(user_id, dt, id),
INDEX(id)

Would also be efficient even if (user_id, dt) is not unique.  The addition of id to the PK is to make it unique; the addition of INDEX(id) is to keep AUTO_INCREMENT happy.  (No, UNIQUE(id) is not required.)
INT --> BIGINT UNSIGNED ??

INT (which is SIGNED) will top out at about 2 billion.  That will happen in a very few years.  Is that OK?  If not, you may need BIGINT (8 bytes vs 4).
This partitioning design does not care about your 7-day rule.  You may choose to keep the rule and enforce it in your app.
BY HASH

will not work as well.
SUBPARTITION

is generally useless.
Are there other queries?  If so they must be taken into consideration at the same time.
Sharding by user_id would be useful if the traffic were too much for a single server.  MySQL, itself, does not (yet) have a sharding solution.
Comment: Thank you for the detailed explanation. I will definitely look into PARTITION. I am curious if all the users are in one table (PARTITION) what kind of locking will it have when there are simultaneous reading say of different users with the same date range?
Comment: Locking is at the row level for InnoDB.  So, no interference between queries on separate users (other than overall system being busy).
Comment: In using InnoDB, I am looking on a possibility that the size of the table (around 2GB per day x 90 = 180GB) will not be able to fit into the `innodb_buffer_pool`. Will this impact the query speed with partition since I need to search based on the `user_id` as well on top of on `dt`?
Comment: In InnoDB, the PK is "clustered" with the data.  So, `PRIMARY KEY(user_id, dt)` puts all the rows for your `WHERE` in the same block(s), even without partitioning.  Can't get better than that, especially when the table won't fit in the buffer_pool.  Are there other queries that would compete for access to the table?  We need to consider all queries.
Answer: Try TokuDB engine at https://www.percona.com/software/mysql-database/percona-tokudb
Archive data are great for TokuDB. You will need about six times less disk space to store AND memory to PROCESS your dataset compared to InnoDB or about 2-3 times less than archived myisam.
Comment: Thank you. Will definitely look at TokuDB.


Unable to pass state value through react

Question: I am unable to pass the state of my functions through below, i have added {state.name.user} and also {onInputChange} but i am running into errors.
<Navigation isSignedIn={isSignedIn} onRouteChange={onRouteChange} />
            { route === 'home'
              ?

                  <Logo />
                  <Rank
                    name={state.user.name}
                    entries={state.user.entries}
                  />
                  <ImageLinkForm
                    onInputChange={onInputChange}
                    onButtonSubmit={onButtonSubmit}
                  />
                  <FaceRecognition box={box} imageUrl={imageUrl} />

              : (
                 route === 'signin'
                 ? <Signin loadUser={loadUser} onRouteChange={onRouteChange}/>
                 : <Register loadUser={loadUser} onRouteChange={onRouteChange}/>
                )
            }

        );
      }
    }

    export default App;

Comment: Can you show the errors and your state definitions?
Answer: This is a simple fix, for
<Navigation isSignedIn={isSignedIn} onRouteChange={this.onRouteChange} />
            { route === 'home'
              ?

                  <Logo />
                  <Rank
                    name={this.state.user.name}
                    entries={this.state.user.entries}
                  />
                  <ImageLinkForm
                    onInputChange={this.onInputChange}
                    onButtonSubmit={this.onButtonSubmit}
                  />
                  <FaceRecognition box={box} imageUrl={imageUrl} />

              : (
                 route === 'signin'
                 ? <Signin loadUser={this.loadUser} onRouteChange={onRouteChange}/>
                 : <Register loadUser={this.loadUser} onRouteChange={onRouteChange}/>
                )
            }

        );
      }
    }

    export default App;

Always make sure you pass through ".this" before.


Generate one dataframe per element in a column and merge into current dataframe

Question: Given the following (example) dataframe :
import pandas as pd
import pathlib
from pathlib import Path

cwd = Path('Path/to/somewhere')
df = pd.DataFrame(
    {
        'var1': [0, 5, 10, 15, 20, 25],
        'var2': ['A', 'B']*3,
        'var3': ['A', 'B']*3,
        'path_col': [cwd / 'a.dat', cwd / 'b.dat', cwd / 'c.dat', cwd / 'd.dat', cwd / 'e.dat', cwd / 'f.dat'],
    }
 )

Each path in path_col points to a datafile, which I have a function to convert into a dataframe, e.g. :
def open_and_convert_to_df(filepath: pathlib.Path):
    # do things
    return pd.Dataframe(...)

data_df = pd.DataFrame(
    {
        'var4': [10, 20, 30],
        'var5': [100, 200, 300],
        'obs': [1000, 2000, 3000],
    }
)

I'd like to generate a data_df from each path in path_col and merge into df such that the final df looks like :
    var1 var2 var3 var4 var5 obs
0   0    A    1    10   100  1000
1   0    A    1    10   100  2000
2   0    A    1    10   100  3000
3   0    A    1    10   200  1000
4   0    A    1    10   200  2000
5   0    A    1    10   200  3000
6   0    A    1    10   300  1000
...
n-3 25   B    2    30   200  3000
n-2 25   B    2    30   300  1000
n-1 25   B    2    30   300  2000
n   25   B    2    30   300  3000

In other words, variables 1 to 3 of the first df are indexes of the data contained in path_col.
Inside this data, var 4 and 5 are indexes of obs. I'm trying to index obs with all variables from 1 to 5.
The best I've come up with so far is using the .map() method like so :
df['path_col'] = df['path_col'].map(open_and_convert_to_df)

I end up with the right df's in each path_col element but I'm lacking the next steps in order to "un-nest" those and obtain the desired df.
Comment: the initial `df` is incorrect, it throws `ValueError: All arrays must be of the same length`
Comment: My bad, fixed it using mozway's answer
Comment: @MaximGi and did my approach work? Can you provide a dummy example of some of the files and the exact expected output for clarity?
Comment: Tested just now, it worked, see my comment to your answer.
Answer: Assuming you want some kind of join or each row with the output of the function, you could use concat:
out = df.join(pd.concat({k: open_and_convert_to_df(v)
                         for k,v in df['path_col'].items()}
                        ).droplevel(1))

Used input:
df = pd.DataFrame(
    {
        'var1': [0, 5, 10, 15, 20, 25],
        'var2': ['A', 'B']*3,
        'var3': [1, 2]*3,
        'path_col': [cwd / 'a.dat', cwd / 'b.dat', cwd / 'c.dat', cwd / 'd.dat', cwd / 'e.dat', cwd / 'f.dat'],
    }
 )

Comment: This solution worked for me. The resulting dataframe (out) index may be properly reset in the next step : `out.reset_index(drop=True)`. Thanks


ItemsSource binding and not working PropertyChanged

Question: I set DataContext:
this.DataContext = new MainWindowViewModel();

And I am binding the ItemsSource of a TabControl, when I add a new TabItem in the contructor of MainWindowViewModel it is working! But when I add a new TabItem in an event (Click) there is no effect.
I have this property:
List<Item> _listOfItem;
public List<Item> ListOfItem
{
    get
    {
        return _listOfItem;

    }
    set
    {
        _listOfItem = value;
        PropertyChanged(this, new PropertyChangedEventArgs("ListOfItem"));
    }
}

Please help.
Answer: You should use an ObservableCollection, rather than a List if you wish the UI to be notified of collection changes.
ObservableCollection<Item> _listOfItem;
public ObservableCollection<Item> ListOfItem
{
    get
    {
        return _listOfItem;
    }
    set
    {
        _listOfItem = value;
        PropertyChanged(this, new PropertyChangedEventArgs("ListOfItem"));
    }
}

Note that you only need to invoke the PropertyChanged event for your ListOfItem if the reference changes after construction of your view model type. If it doesn't change, then a simple auto property will suffice for ListOfItem.
Comment: No, you will need to invoke the PropertyChanged event if the reference to your observable collection changes in order to notify any UI elements. It's no different to any other property type in that regard.
Comment: It is to my understanding that you don't need to raise PropertyChanged on a ObservableCollection. So you can get rid of the property and only leave "Public ObservableCollection _listOfItem;". Mind you, this will only work for insert and delete (update = delete followed by insert).
Comment: I don't have a single view in all of my sourcecode where the reference of an observablecollection changes while the view is active. I only add INotifyPropertyChanged to the class stored in the OC to support updates. So I understand why you do this, but most of the times you wouldn't need the property.
Answer: For collection changes you need the source collection to implement INotifyCollectionChanged, you could use an ObservableCollection<T> (which implements it) instead of a List<T>.
Answer: You need to use and ObservableCollection for the UI to see additions and deletions to the collection.   It worked in the constructor as the List is was built for the the UI.
Answer: List will not work.
You should use ObservableCollection for the ListOfItem.


Duall Boot with two linux

Question: Please give me full instrunction for dual boot of two linux one is ubuntu and second is fedora.
i like ubuntu but, also fedora
Thank you
Comment: There are manuals on this site and elsewhere. One thing you need to decide on is whether you'll want to hibernate the system. If not, the two distros can share the swap partition.
Answer: It's a really straightforward process. First you install one of the distros, say Fedora. Then you install Ubuntu. Pay attention to the installation instructions, which will ask you if you want to wipe your hard drive or if you want to install the new operating system alongside the other one that's already installed (i.e., if you want to dual-boot).
In order to install Linux, make sure you have an installation media (CD, DVD or USB pendrive) and boot you system with this media inserted. You might have to configure your BIOS to boot from the disk or USB drive in order to trigger the installation procedure.

Duall Boot with two linux


How do I do a rectangular selection for the /tp command?

Question: I've been working on a project that requires the /tp command (teleportation command). I wondered if there was a way to only teleport every player (real player and NPC players, such as a villager or any mobs) in a precise rectangular selection instead of a block radius selection.
Thank you for reading my question.
Comment: What exactly do you mean by "rectangular selection"?
Comment: (@e means everything) /tp @e x y z
Comment: @Unionhawk, what I mean by "rectangular selection" is because when do the /tp command, we can do by the radius (for ex: r=5, it detect every entities in a radius of five blocks), but I didn't knew how to to detect entities that are, like for ex., in a rectangular area. For summary: _What I mean by here is "in a rectangular area"_ .
Answer: The delta parameters (dx, dy, dz) state the number of blocks away from the x, y, and z parameters to look for a target.
For example, the following teleports players starting from an origin of 10, up to 5 blocks in the X direction, 20 blocks in the Y, and 3 blocks in the Z.
The team parameter will throw out all non-living entities. Note that the selection will include armor stands, so that has been specifically excluded. If you're using teams, you may need to adjust usage (as the following only teleports those that aren't on a team):
/tp @e[x=10,y=10,z=10,dx=5,dy=20,dz=3,type=!ArmorStand,team=] 0 10 0

Comment: Thank you, but I only need it for making every players in my machine move each time it move of 1 block. It is because I don't want to make everyone in the server or world move of 1 block that I posted this question :)


AppImage application bundle

Question: I have a new pc with linux ubuntu 22.04.1 LTS installed. Linux is new to me so I am learning as I go. I am trying to install some accounting software via an appimage file, however i receive an error as follows:
Could Not Display "Manager-linux-x64.AppImage"
There is no application installed for "AppImage application bundle" files. Do you want to search for an application to open this file?
I have ticked the permissions to allow executing file as a program but it doesn't do anything when trying to open. Any recommendations on what I can do to install this file? The recommended software has negative reviews so I would prefer not to install that one. Thanks for your help.
Comment: Appimage files need to be set as executable.  `chmod +x Manager-linux-x64.AppImage` and they run in their own space.
Comment: yes i have set this to allow executing file as a program. However it still doesn't open. Anything else I need to do?
Comment: https://appimage.org/ is what they are.  Maybe you need to do the `chmod a+x filename.appimage` and it should work.  There should not be any associated files to open it, and if it is asking then it might be a bad download or just a bad file.
Comment: hmm, thanks for the info. Looks like my novice skills aren't going to get it working and I'll have to get outside help. Appreciate you taking to time to answer.
Answer: Appimages require the FUSE filesystem to run.  Ubuntu 22.04 LTS doesn't include FUSE by default.  But once you install it, the Appimage will work just fine.
Install instructions may be found here - be sure to pay attention to the fact that in 22.04 you use libfuse2 rather than fuse.
In future: this info (and the link) may be found by getting into a terminal and executing your Appimage from there: in that case you will see the log messages explaining that FUSE is not installed.  For example:
% ./sample-app
dlopen(): error loading libfuse.so.2

AppImages require FUSE to run.
You might still be able to extract the contents of this AppImage
if you run it with the --appimage-extract option.
See https://github.com/AppImage/AppImageKit/wiki/FUSE
for more information

Answer: For me, it was because the file manager was run as root.
Closing all file manager windows and then re-opening allowed me to double-click and run AppImage files.

AppImage application bundle


Formatting Date from arabic to english using momentjs

Question: I am trying to format a date which is in arabic to english using moment js
var mom = moment("٣٠/١١/٢٠٢٠","l", 'ar', true);
        if(mom.isValid()) {
        schedule.startTime.dateText= mom.locale('en').format('MM/DD/YYYY');
}

This does not seem to work I get mom value as "Invalid Date". "٣٠/١١/٢٠٢٠" is the value from backend how do I convert to english?
Answer: Just try specifying the format inside moment, and it should work fine.
Code sandbox link: https://codesandbox.io/s/compassionate-bas-fg1c2?file=/src/index.js:61-169

const arabicDate = "٣٠/١١/٢٠٢٠";
console.log(moment(arabicDate, "YYYY/MM/DD").locale("en").format("YYYY/MM/DD"));

Comment: doesn't work for me in node js 16.14.2, moment 2.29.1
Answer: pass in the local of the input string to the 3rd argument
moment(
  moment().locale('ar').format('YYYY/MM/DD'),
  'YYYY/MM/DD',
  'ar'
)

works for me in moment 2.29.1 and nodejs 16.14.2


Standard error for random effect (BLUP) of a mixed effect model in r

Question: Can we calculate standard errors (SE) for BLUPs from a mixed model in R? I am using a custom package called ASReml and it can calculate SE from the predicted value. However I am not sure where to find the SE for the BLUP values.
So far I have something like this...
df<-data.frame(inbred=c("x1","x2","x3","x4","x5","x1","x2","x3","x4","x5","x1","x2","x3","x4","x5","x1","x2","x3","x4","x5","x1","x2","x3","x4","x5","x1","x2","x3","x4","x5","x1","x2","x3","x4","x5","x1","x2","x3","x4","x5"),
                       trait1=rnorm(40,0,1),
                       block=c(1,1,1,1,1,2,2,2,2,2,1,1,1,1,1,2,2,2,2,2,1,1,1,1,1,2,2,2,2,2,1,1,1,1,1,2,2,2,2,2),
                       rep=c(rep(1,20),rep(2,20)))
df <- transform(df, inbred=factor(inbred), rep=factor(rep), block=factor(block))
head(df)

  inbred      trait1 block rep
1     x1 -1.15668530     1   1
2     x2  0.41492671     1   1
3     x3 -0.08740545     1   1
4     x4  0.37983415     1   1
5     x5  0.27180581     1   1
6     x1  1.22986338     2   1

Use asreml to fit the mixed model.
library(asreml)

df.reml < -asreml(trait1 ~  rep + block,
                  random = ~ inbred,
                  data=df)

Model fitted using the gamma parameterization.
ASReml 4.1.0 Fri Mar 12 13:56:29 2021
          LogLik        Sigma2     DF     wall    cpu
 1      -16.4111      0.669903     37 13:56:29    0.0 (1 restrained)
 2      -15.9428      0.692305     37 13:56:29    0.0 (1 restrained)
 3      -15.9183      0.694848     37 13:56:29    0.0 (1 restrained)
 4      -15.9168      0.695017     37 13:56:29    0.0 (1 restrained)
 5      -15.9167      0.695027     37 13:56:29    0.0 (1 restrained)
Warning message:
In asreml(trait1 ~ rep + block, random = ~inbred, data = df) :
  Some components changed by more than 1% on the last iteration.

And then we ask for the predicted values:
df.pred <- predict(df.reml,classify="inbred")
Model fitted using the gamma parameterization.
ASReml 4.1.0 Fri Mar 12 13:59:52 2021
          LogLik        Sigma2     DF     wall    cpu
 1      -15.9167      0.695028     37 13:59:53    0.0
 2      -15.9167      0.695028     37 13:59:53    0.0
 3      -15.9167      0.695028     37 13:59:53    0.0

df.pred$pvals

Notes:
- The predictions are obtained by averaging across the hypertable
  calculated from model terms constructed solely from factors in
  the averaging and classify sets.
- Use 'average' to move ignored factors into the averaging set.
- The simple averaging set: rep,block

  inbred predicted.value std.error    status
1     x1      -0.2584834 0.1318171 Estimable
2     x2      -0.2584834 0.1318171 Estimable
3     x3      -0.2584836 0.1318171 Estimable
4     x4      -0.2584839 0.1318171 Estimable
5     x5      -0.2584838 0.1318171 Estimable

These std.errors above are for the predicted.value column. Is there a way to get standard errors for the BLUP or random effects column?
The BLUPs for the random effects are:
 df.ran = df.reml$vcoeff$random
 df.ran
 [1] 1.599984e-06 1.599984e-06 1.599984e-06 1.599984e-06 1.599984e-06

Comment: Almost certainly, you want rep and block to be factors.  I've made that change and re-ran the code.
Answer: Good question. The answer is not obvious. You can get the standard errors for BLUPs using the summary function:
summary(df.reml, coef=TRUE)$coef.random
               solution   std.error       z.ratio
inbred_x1  3.231267e-06 0.001054529  3.064180e-03
inbred_x2  3.354557e-06 0.001054529  3.181093e-03
inbred_x3 -9.275731e-08 0.001054529 -8.796086e-05
inbred_x4 -3.410440e-06 0.001054529 -3.234087e-03
inbred_x5 -3.082627e-06 0.001054529 -2.923225e-03


spring boot with docker compose configured: services must be a mapping

Question: I created a sping-boot app with spring initializer, with Docker Compose Support added.
Generated project has an empty compose.yaml, as I havent added nothing to project yet.
When I try to run app in IDE(intellij) i get error:
Stderr:
validating ..../compose.yaml: services must be a mapping

    at org.springframework.boot.docker.compose.core.ProcessRunner.run(ProcessRunner.java:96) ~[spring-boot-docker-compose-3.3.0-20240301.111245-172.jar:3.3.0-SNAPSHOT]
    at org.springframework.boot.docker.compose.core.DockerCli.run(DockerCli.java:80) ~[spring-boot-docker-compose-3.3.0-20240301.111245-172.jar:3.3.0-SNAPSHOT]

Why is it so?
Answer: you can add following line in compose.yaml file.
version: '1.0'

it will solve your problem if you don't want to add any configuration.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: As there's no line reference in the error, but from what it says, it seems you are writing the services with a syntax error.
Often this error refers to adding a reference in the form of an array, in this way:
foo:
 - bar

when it should be a map, in this way:
foo:
  bar:

You can check the documentation to see what each area of the compose file expects.
As it refers to services, it is expected they are added in this way:
services:
  example:
    image: image-name:tag

with many variations in terms of each value.


Ubuntu Tweak natural scrolling not persistent

Question: I am using Ubuntu tweak on Ubuntu 12.04 and the natural scrolling setting does not persist after restart. So is there a way to permanently enable natural scrolling? If I have left any details out please tell me and I will add them as I am new to this.
System Details:

Ubuntu 12.04
processor ARMv7
memory 2.0 GiB
Unity 2D

My Ubuntu installation is on a Samsung Chromebook through crouton.
Answer: I have found out that the scrolling issue was caused by the crouton installer which is now updated with a fix for the bug thus anyone with this issue should update the crouton file with the Instructions located here.
If you can not get to those instructions here is a copy of them(All rights go to the crouton creators):

Check for updates, download the latest version, and see what's new by running croutonversion -u -d -c from the chroot (run croutonversion -h to see what those parameters actually do).
Exit the chroot and run sudo sh ~/Downloads/crouton -u -n chrootname. It will update all installed targets.
You can use this with -e to encrypt a non-encrypted chroot, but make sure you don't interrupt the operation.


How to execute perl script from a Windows Powershell script

Question: I have the below PowerShell code:
$HOME_DIR=[Environment]::GetEnvironmentVariable("HOME")
$WORKING_PATH="C:\tests\automation"
$TOOLS_PATH="$WORKING_PATH\Tools"

Start-Process -FilePath "$HOME_DIR\perl\perl.bat" "$TOOLS_PATH\my_perl_script.pl" -ArgumentList 'arg1' 'arg2' -NoNewWindow

I'm getting error:
Start-Process : A positional parameter cannot be found that accepts argument 'C:\tests\automation\Tools\my_perl_script.pl'.
At C:\RunUIAutomaionTests.ps1:46 char:14
+ Start-Process <<<<  -FilePath "$HOME_DIR\perl\perl.bat" "$TOOLS_PATH\my_perl_script.pl"
-ArgumentList 'arg1' 'arg2' -NoNewWindow
  + CategoryInfo          : InvalidArgument: (:) [Start-Process], ParameterBindingException
  + FullyQualifiedErrorId :
  PositionalParameterNotFound,Microsoft.PowerShell.Commands.StartProcessCommand

What I'm missing?How should I execute my_perl_script.pl using perl.bat with the arguments 'arg1' and 'arg2'?
Comment: File path can't consist of two paths :-) Move your pl path into arguments.
Answer: Why so complicated?
You can call perl doirectly like that:
...

$TOOLS_PATH="$WORKING_PATH\Tools"
  ...

perl $TOOLS_PATH\my_perl_script.pl arg1 arg2
Just make sure perl executable is in Windows path


Linq Expression tree compiling non-trivial object constants and somehow referring to them

Question: Usually, when compiling an expression tree, I would have thought constants which are not primitives types or strings would be impossible. However, this code:
   public class A
        { public int mint = -1; }

 public static void Main(String[] pArgs)
        {
            //Run(pArgs);

            Action pact = Thing();

            pact();
        }

        public static Action Thing()
        {
            var a = new A();
            a.mint = -1;

            LambdaExpression p =
                Expression.Lambda<Action>(Expression.Assign(Expression.Field(Expression.Constant(a, typeof(A)), Strong.Instance.Field<int>(b => b.mint)), Expression.Constant(3, typeof(int))));

            return ((Expression<Action>)p).Compile();

        }

not only compiles but it actually runs! If you run the compiled method in the Thing() method, then you can actually see the variable a change its field from -1 to 3
I don't see how this makes sense/is possible. How can a method refer to a local variable outside its scope (when inspecting the IL of Thing(), the variable a is just a standard local variable, not on the heap like with a closure). Is there some kind of hidden context past around? How can pact run in Main when the local variable a has presumably been removed from the stack!
Answer:
How can a method refer to a local variable outside its scope

It can't, and it doesn't.
It can sometimes refer to the object the local variable points to though.
Whether it can or not depends on which way the expression is compiled or otherwise used.
There are three ways that Expressions itself will compile an expression into a method:

Compilation with Compile() to IL in a DynamicMethod.
Compilation to IL in with CompileToMethod() (not available in all versions.
Compilation with Compile() into an interpreted set of instructions with a thunk delegate that runs the interpretation.

The first is used if IL compilation is available, unless true is passed to prefer interpretation (on those version with that overload) and interpretation is not also available. Here an array is used for the closure and it is much the same as closing over a local is, in a delegate.
The second is used to write to another assembly and cannot close in this way. Many constants that will work with Compile() will not work with CompileToMethod() for this reason.
The third is used if IL compilation is not available, or true was passed in those versions that have that overload to prefer interpretation. Here a reference to the object is put into an array of "constants" that the interpreter can then refer to.
The other possibility is that something else interprets the expression entirely, e.g. in producing SQL code. Generally this will fail with non-primitive constants other than string though, but if the query processor is aware of the type of the constant (e.g. if it is of a type of entity that it knows about) then code to produce the equivalent to that entity could be produced.
Answer: It is only a that is a local variable; the actual object (from new A()) was always on the heap. When you used Expression.Constant(a, typeof(A)), it wasn't a that you put in as a constant - it was the value of a, i.e. the object reference. So: the scope of a is irrelevant as far as the tree is concerned. This is actually exactly how captured variables (closures) are usually implemented by the compiler (although you don't see it usually, and the C#-based expression compiler doesn't allow assignment operators), so as far as the expression tree is concerned: this is business as usual.
As a comparable example using the C# expression compiler, see here, where
public void M() {
    int mint = -1;
    Expression<Func<int>> lambda = () => mint;
}

compiles to:
[CompilerGenerated]
private sealed class <>c__DisplayClass0_0
{
    public int mint;
}

public void M()
{
    <>c__DisplayClass0_0 <>c__DisplayClass0_ = new <>c__DisplayClass0_0();
    <>c__DisplayClass0_.mint = -1;
    Expression.Lambda<Func<int>>(Expression.Field(Expression.Constant(<>c__DisplayClass0_, typeof(<>c__DisplayClass0_0)), FieldInfo.GetFieldFromHandle((RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/)), Array.Empty<ParameterExpression>());
}

Comment: Yes for delegates you can see this happening, but the compiled IL for the delegate doesn't have a hidden context like the displayclass - there is no this object (I think) for the compiled delegate
Comment: all the IL can refer to is the arguments passed to it (which *I think* in my case is nothing) and constants such as ldstr, or ldc_i4. If an object was passed as the first argument containing the object constants, this would make sense, but the compiled delegate is an Action, not a Action
Comment: @Nick yes there is: look at `pact.Target` - it isn't `null` - it is a generated closure that contains this via two fields (constants and locals); although `Compile` could also have created it as a static method using static fields and no closure
Comment: @Nick don't forget that if the tooling generates a `some_funny_displayclass` internally, then `void some_method_on_that_class()` can be an `Action`
Comment: Yeah you're right - this is case one in Jon Hanna answer. Thanks!
Comment: There is a sublte difference in that your mint in M() actually gets put on the heap, whilst if you use Expression.Constant with a primtive/String you don't close over it or share the same reference.
Comment: @Nick some constants can be literalized, indeed; not all


How to pass data to pdf in just DOMPDF?

Question: I am stuck in a weird situation.
How can I send PHP data to dompdf's pdf ?
Here is my code
index.php
<?php

require_once 'dompdf/autoload.inc.php';
use Dompdf\Dompdf;
use Dompdf\Options;

function runPDF () {
    $options = new Options();
    $options->set('isPhpEnabled', true);
    $dompdf = new Dompdf($options);

    $data = array('name'=>'John Smith', 'date'=>'1/29/15');

    $html = file_get_contents("pdf.php");
    $dompdf->loadHTML($html);

    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();
    $dompdf->stream("niceshipest", array("Attachment" => 0));

}

if (isset($_GET['pdf'])) {
    runPDF();
  }
?>

print

pdf.php
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Value To PDF</title>

        Hello <?php echo $data['name']; ?>

So how can I access that $data value in generated pdf?
I have tried to change isPhpEnabled = false;  to isPhpEnabled = true;
But got no results.
Framworke version of dompdf like laravel-dompdf provides feature to pass data in HTML like loadView();  but there is only loadHTML();
Any help really appreciate?
Thanks
Comment: Check this out https://stackoverflow.com/questions/6905706/php-sending-variables-to-file-get-contents
Answer: The solution it's very simple, you should just add the with() like this :
$dompdf->loadHTML($html)->with('data', $data);

And you should delete this :
require_once 'dompdf/autoload.inc.php';

That's it.

How to pass data to pdf in just DOMPDF?


Redundant behaviors in context menu

Question: In the menu hierarchy tree of file managers such as Windows Explorer, why are redundant behaviors of "expand" "collapse" folders given in context menu when the user can anyways click the + or - icon beside the folder to expand or collapse it? See the icon and menu item outlined in yellow below:

What is the UX benefit of such redundancy?
Comment: Can you add a screenshot/mockup so that we understand the context?
Comment: I added a screenshot and some text. Was this what you were asking, Bhakti?
Comment: Yes Michael, this is what I was asking for.  Thank you :-)
Answer: According to Jef Raskin at his book The Humane Interface, designers use the following justifications, when they decide to use many ways to perform the same action :

One justification for having multiple methods to do a given task is
  that some users prefer one method and other users prefer a different
  method. For example, a novice user might find menus easier to learn,
  although an expert user might rather keep her hands on the keyboard
  and issue commands by typing them.

Another justification is that one method -- for example, selecting,
  cutting, and pasting -- is useful between distant portions of a
  document, and the other method -- selecting and dragging -- is
  effective only when the source and destination are both visible on the
  display.

Another reason for a plurality of methods is that each of them is
  sanctioned by custom, and the developers felt it wise to accommodate
  as many previously developed skills as possible.

backward compatibility

The author is against this strategy. He believes providing only one way to accomplish a task (monotony), makes the interface easier to learn and use.

When you have to choose among methods, your locus of attention is
  drawn from the task and temporarily becomes the decision itself. This
  is a primary reason for choosing to design a monotonous system. If the
  conditions for making the decision are sufficiently clear and
  distinct, the path you take in each case can become habitual, and you
  have monotonized the situation. It still behooves the designer to seek
  an efficient monotonous solution to gain benefits, including ease of
  learning, simplicity of implementation, minimization of documentation,
  and lowered maintenance costs. ... If I am correct, the use of a product based on modelessness and monotony would soon become so habitual as to be nearly addictive, leading to a user population devoted to and loyal to the product. Its users would find moving to a competitor's product psychologically difficult.

I tend to agree with the author, in most cases his approach is much better.
Comment: I fully agree with the four advantages listed in the first part of the answer, but I am somewhat surprised the fact that one of the two ways to expand/collapse the items is accessible very quickly (with one click), while the other one is self-explanatory (due to the clear text label), thereby adding the advantage of combining these two possible benefits, remains unmentioned.
Comment: Other than that, while in a strict marketing sense, "Its users would find moving to a competitor's product psychologically difficult." might somehow be seen as something good, I perceive it as a very negative trait to avoid at all cost and therefore as a strong reason not to design the so-called "monotonous systems" described in the quotation.
Comment: @O.R.Mapper the self-explanatory falls in to the novice/expert category (first bullet). The quote "it still behooves the designer to seek an efficient monotonous solution to gain benefits, including ease of learning, simplicity of implementation " answers your second comment, although I do agree that for some situations the monotonous approach, may not be appropriate.
Comment: Then why doesnt Visual studio follow its Microsoft guidelines? I am working on an application similar to an IDE. I kept Expand / Collapse and the product owner showed me the visual studio context menu which doesnt have it.
Answer: It's a Historical Leftover
Speaking specifically about the Windows File Manager, the answer is in the history of its UI. Look at screenshots of the older Windows file manager, and you'll see there are no +/- icons.

Instead, there was a pulldown menu command (in the Tree menu, I think) to expand/collapse. Double-clicking  and later the context menu were included as expert shortcuts ("expert," because they were easier to use than the pulldown menu, but harder to discover, at least in theory).
At some point (maybe Windows 95?), Microsoft decided that expand/collapse was too important and frequently used to be buried in menu or hidden in a secret gesture like double-clicking. Thus, it added the +/- icons. However it kept the double-clicking/context menu UI presumably for users that were used to it. So the two means to expand/collapse are to accommodate different user habits or skills (Raskin Bullet 3 in DesignerAnalyst's answer).
Other Factors?
Another possible factor is Microsoft wanted to keep the behavior of the folder icon in the tree consistent with the folder icons in the detail pane. There, double-clicking a folder shows the contents of the folder in the same pane. Since you don't want the user having to make fine distinctions on what folder icon where will respond how to double-click, you try to make them the same as possible. Sometimes you have two different ways to do the same command in order for one of the ways to be internally consistent, i.e., consistent with something else in the UI.
According to Microsoft's UX guidelines, if double-click does something, then the same command must be in the context menu (in bold, at the top), so, given there were a couple reasons to to keep double-clicking for expand/collapse, Microsoft was compelled to have the command in the context menu too to be externally consistent with other Windows UIs.
It's generally a good practice to have a text equivalent for any command executed with an icon because icons can be inscrutable labels. So, maybe Microsoft kept the context menu item to have a text equivalent. In other words, sometimes you have different ways to do the same command to accommodate different user expertise (Raskin Bullet 1 in DesignerAnalyst's answer). However, IMHO, I'd expect that users who understand an expert feature like context menus would also understand a standard and reasonably intuitive icon like +/- for expand/collapse.
Accessibility is another reason for redundant means of executing a command, but I don't think it played a role in this case.
Organic Development
Perhaps at the same time that Microsoft added the +/- icons, it dropped the expand/collapse command from the pulldown menu, and, eventually, hid the entire menu bar by default. Now the menu bar is the place of expert commands, accessible only with the secret Alt key. Not an entirely satisfactory solution, but that's how it evolved.
Complex UIs, especially over multiple versions, tend to drift from their original coherent vision due to lots of little easy decisions that seem reasonable in their own context but can morph the UI into something weird in aggregate.
Comment: Just a minor quibble in light of the entire answer, but Windows 3.x didn't have context menus. Those were a new innovation in WIndows 95, and a headlining one at that. So your only options for expanding a TreeView in File Manager were the menus or double-clicking (or most likely the same keyboard shortcuts as are available now, but I'm not certain of that).
Comment: @Cody: I believe you're correct. I've added "later" to my text to reduce confusion. Some Googling (e.g., http://getpcsoft.wikisend.com/windows-95-free-download.html) shows that the +/- icons _also_ came out in Windows 95. That implies Microsoft added the icons but kept the redundant double-click for users used to that, then simultaneously added the redundant context menu item to be consistent with the new UX guidelines for double-click. How byzantine.
Answer: Alan Cooper, in his classic interface design book, About Face, speaks directly to this question.
He points out, as you have, that there are multiple distinct techniques for issuing instructions to a program. He terms these, collectively, "command vectors." Menus are one type of command vector, as are toolbar "buttcons" (his term for toolbar buttons labeled with only an icon), drag-and-drop, and keyboard shortcuts (among others).

I call each distinct technique for issuing instructions to the program a command vector. Menus are a command vector, as are direct manipulation and toolbar buttcons. Good user interfaces will conscientiously provide what I call multiple command vectors, where each function in the program has menu commands, toolbar commands, keyboard commands, and direct-manipulation commands, each with the parallel ability to invoke a given command. This enables users of different skill sets and preferences to command the program according to their desires and abilities.

He argues that the primary purpose of menus is to serve as a pedagogic vector. In other words, they serve a teaching role because they are clearly labeled, explanatory, and present a catalog of all of the available options. Menus are also "safe," because users can easily browse all of the available options without actually invoking any of them. Finally, it is common for menus to display, in addition to a description of the command, the associated keyboard shortcut (if applicable). New users can easily ignore this information when learning the software for the first time, but as they begin to become more advanced, they will gradually discover it and begin to make use of it. Sure, this information could be buried in documentation somewhere, but that makes it harder to find and much less likely that anyone will ever read it. Taken together, all of these are compelling reasons why at least one of the command vectors must be a menu option.
But then, Cooper also points out that menus have a cost: they are slow and cumbersome to use for power users (or anyone who uses a particular piece of software frequently, becoming a sort of micro-expert with that software, even if they are not overall power-users when it comes to computers).
This is where the other types of command vector idioms come in, like toolbar buttons and direct-manipulation (like the +/– icons in a TreeView control). Keyboard shortcuts also fall into this category. They have the advantage of being quick and easy-to-use for power users, although they are not very clear or discoverable for novice users.
A well-designed UI should cater to all audiences. For anything but a throwaway, single-use application (for which speeding up experts is not an important goal), you need to provide both pedagogic and immediate vectors for the most commonly-used functions.

Both direct-manipulation and toolbar-buttcon command vectors have the property of being immediate vectors. There is no delay between pressing a buttcon and seeing the results of the function. Direct manipulation also has an immediate effect on the information without any intermediary. Neither menus nor dialog boxes have this immediate property. Each one requires an intermediate step, sometimes more than one.
In the same way that a stranger to town may take a roundabout route to her destination while a native will always proceed on the most economical path, experienced users of a program will commonly invoke a function with the most immediate command rather than the one that requires intermediate steps. Naturally, the most frequently used commands in a program are those that migrate onto buttcons in the toolbar. These functions are still supported by items on the menu—the menu command vector—where their use becomes increasingly the purview of beginners. Experienced users, however, gravitate toward the immediate vectors of buttcons and direct manipulation.
This bifurcation of usage along lines of experience is an important characteristic of software usage, and it affects how menus and dialog boxes are used. They are needed less and less for daily use, and have instead become a teaching tool for first-time and infrequent users.
The buttcons and other gizmos [controls] on the toolbar are usually redundant with respect to commands on the menu. Buttcons are immediate, while menu commands remain relatively slow and clunky. Menu commands have a great advantage, however, in their English description of the functions, and the detailed commands and data that appear on corresponding dialog boxes. This detailed data makes the menu/dialog command vector the most useful one for teaching purposes, which is why I call it the pedagogic vector.

This is all taken from Chapter 19 ("The Meaning of Menus"), p 278–80, in the book's first edition (© 1995). He goes on to say lots of other interesting and useful things in the chapter. I've tried to provide a concise summary of the observations most relevant to this question in my own words above. I'm not sure if he has changed his tune in the later editions of the book—I only have the first edition.
Even if he has, this still provides an illuminating historical perspective. Given Alan Cooper's influential role at Microsoft during this time (he is often credited as the "father" of Visual Basic), when the Windows GUI was evolving, it is reasonable to assume that many of the programmers and UI designers responsible for developing its characteristic idioms were strongly influenced by his opinions and perspectives.
Answer: It allows better accessibility, likewise those +/- buttons are highly inaccesible, except for users with high mouse dexterity (*). It serves also as notifier of what "default" action is when hitting enter (for directory, "expand" is default, for file "open"). Also power users are not likely to touch those +/- icons at all, but simply rely into TAB, ENTER, UP, DOWN, LEFT, RIGHT, SHIFT, CTRL, MENU keys for navigation and manipulation. In that era context menu serves also as intermediator between power and ordinary users, aka. group of people leveling up in experience.
(*) for someone without good mouse dexterity doing any operationa with mouse on tiny icons is challenge. Single clicks, double clicks, slow double clicks, all get mixed up and sometimes become even random drag'n'drops of files/dirs.

Redundant behaviors in context menu


How would I go about leveling a sagging floor?

Question: I had all my kitchen cabinets refaced last year.  I than decided to replace the counters with granite.  When the guy from the counter company came out he did some leveling test. I am putting counters on three sections of counters.  It seem that one side of my kitchen is higher than the rest.  He suspects the floor is unlevel and it is out of the 3/4 variance he can correct by shims. Two sides of the cabinets are on outside walls.
My basement is finished was remodeled a couple years back. I am really wanting to know what my options are how I would level the floor without tearing up what I already finished. What is the average and what type of skill set should I reaching out to get this solved?
Answer: There are two ways to fix this.

have the cabinets installed correctly.  They should have been shimmed to at least very close to level.  This is basically a one day job and isn't rocket science.  You unscrew cabinets and shim them.  Front bases have to be redone.  If someone installed these for you I would call that company to come back out.
install plywood over cabinets.  Have it planed/sanded to meet the needs (this will be difficult).
Comment: The cabinets **are** installed, aren't they?  But now so far out of level that you can't shim between the cabinet top and the new granite counter?
Comment: The cabinets are existing and have been refaced.  They are quite beautiful now.  And yes so far out of level that shim is not a option for the granite guy.
Comment: @User58220 - will edit my answer.


How to optimize three numbers such that their sum is always equal?

Question: I know the real numbers $a,b,c$ and $d$ and I am trying to find three more numbers - $x, y, z$ - such that their average is equal to $d$ and the sum $|a-x| + |b-y| + |c-z|$ is minimal.
How would I do that? I can use a computer to compute the numbers, but I have no idea how to approach the problem. Any help is appreaciated.
Answer: We'll do it by reducing to the case where $a=b=c=0$ by changing variables, where it's much easier to see what's going on.
Let $\delta_x = x-a$, $\delta_y = y-b$, and $\delta_z = z-c$. We must have $0=3d-(x+y+z) = 3d-(a+b+c)-(\delta_x+\delta_y+\delta_z)$. Let's write $\Delta = 3d-(a+b+c)$. So $\delta_x+\delta_y+\delta_z = \Delta$. And we want to minimize $|\delta_x|+|\delta_y|+|\delta_z|$. I claim the minimum is achieved with $\delta_x=\delta_y=\delta_z=\Delta/3$, so $|\delta_x|+|\delta_y|+|\delta_z| = |\Delta| = |3d-(a+b+c)|$. Here's why:
It's quite easy but there's some casework (as mjqxxxx states in their answer, we are proving the triangle inequality in one dimension). First suppose $\Delta \ge 0$. If $\delta_x<0$, then $\delta_y+\delta_z > \Delta$. If $\delta_y < 0$, then $\delta_z>\Delta$, so $|\delta_x|+|\delta_y|+|\delta_z|>\Delta = |\Delta|$. Similarly, if any two of the deltas are negative, we exceed $|\Delta|$. If $\delta_x<0$ and $\delta_y, \delta_z\ge 0$, then again $|\delta_y|+|\delta_z|=\delta_y+\delta_z > \Delta = |\Delta|$. Similarly, if any of the deltas is negative, we exceed $|\Delta|$. So all deltas are nonnegative, and so $|\delta_x|+|\delta_y|+|\delta_z| = \delta_x+\delta_y+\delta_z=\Delta=|\Delta|$.
If $\Delta<0$, then let $\Delta' = -\Delta$, $\delta_x'=-\delta_x$, $\delta_y'=-\delta_y$, and $\delta_z'=-\delta_z$. We have $|\delta_x'|+|\delta_y'|+|\delta_z'| = |\delta_x|+|\delta_y|+|\delta_z|$, and $\delta_x'+\delta_y'+\delta_z' = \Delta'$. The above paragraph shows that the minimum is again $|\Delta'|=|\Delta|$.
Answer: Let $x=a+d_a$, $y=b+d_b$, and $z=c+d_c$; then you want to minimize $|d_a|+|d_b|+|d_c|$ while satisfying $d_a+d_b+d_c=3d-a-b-c\equiv D$.  By the triangle inequality,
$$
|d_a|+|d_b|+|d_c|\ge|d_a+d_b+d_c|=|D|;
$$
so the minimized quantity can't possibly be smaller than $|D|$.  Clearly this optimal value can be achieved by setting $d_a=d_b=d_c=D/3$, and this is one pleasantly symmetric solution.  (For instance, it also minimizes $(x-a)^2+(y-b)^2+(z-c)^2$.)  In terms of the original variables, you would want $$
x=d+\frac{2}{3}a-\frac{1}{3}b-\frac{1}{3}c,  \\
y=d-\frac{1}{3}a+\frac{2}{3}b-\frac{1}{3}c, \\
z=d-\frac{1}{3}a-\frac{1}{3}b+\frac{2}{3}c.
$$
But in fact the optimal value is achieved whenever $d_a$, $d_b$, and $d_c$ have the same sign as $D$ and sum to $D$.  As OP describes, this solution space is geometrically an equilateral triangle, with vertices where $(d_a,d_b,d_c)$ is equal to $(D,0,0)$, $(0,D,0)$, and $(0,0,D)$.  In terms of the original values, those vertices are at $$(x,y,z)_1=(3d-b-c,b,c), \\(x,y,z)_2=(a,3d-a-c,c),\\(x,y,z)_3=(a,b,3d-a-b).$$
Comment: I accepted your answer as the "pleasantly symmetric" solution is good enough for what I need, but the three points of the triangle you have given are not the points that form the triangle with minimum values. Please fix that or remove it from your answer.
Comment: Can you give a specific example where it's not right, and say where you see the vertices?
Comment: I've plotted the function and your triangle in geogebra and they are completely off. If you need numbers I can find some tomorrow.
Comment: Sure, sounds good.  When I set $a=1$ and $b=2$ and $c=3$, for instance, and fix $z=3-x-y$ (that is, $d=1$), I expect the corners to be at $(x,y)_1=(-2,2)$ and $(x,y)_2=(1,-1)$ and $(x,y)_3=(1,2)$.  And in WolframAlpha, "minimize $|1-x|+|2-y|+|3-(3-x-y)|$" shows the corners exactly there.  So I'd be interested to see a counterexample.
Comment: Okay. So I checked your example and two of the points are correct, but (1,2) is not (and the two points being correct is a coincidence, they usually aren't) . Your formula gives the z-axis for that point 3d-a-b = 3-2-1 = 0, but the correct z-coordinate is of course the just the function output, so that would be |1-1| + |2-2|+ |3-(3-1-2)| = 3.

https://imgur.com/wtpUPLe That's the graph given some random values and it's completely off. Try setting d to something like 5, you'll see it just gets worse and worse.
Comment: I can't imagine what that picture represents.  Okay, take $z=15-x-y$ (that is, $d=5$).  Then the $(x,y)$ coordinates of the corners should be $(x,y)_1=(10,2)$ and $(x,y)_2=(1,11)$ and $(x,y)_3=(1,2)$.  "Minimize $|1-x|+|2-y|+|3-(15-x-y)|$."  And that's where the corners are... I feel like you may be misunderstanding something fundamental about your own question.  For instance, why would the correct $z$-coordinate be the function output?
Answer: Formulate
$\min \ |a-x| + |b-y | + |c-z|$
$s.t. \ x+y+z = 3d$
Replace $x = 3d - y - z$, you have $\min |a-3d + y+ z| + |b-y| + |c-z|$.
Linearize it by replacing:
$\min t_1 + t_2 + t_3 \\ s.t. \ -t_1 \leq a-3d+y+z \leq t_1 \\ \qquad -t_2 \leq b-y \leq t_2 \\ \qquad -t_3 \leq c-z \leq t_3 \\ \qquad \quad t_1,t_2,t_3 \geq 0$
You now have a linear problem. You can even solve this in Excel Solver.
I created an excel template for you available here. Just change the parameters in the orange part as you wish. Then, go to excel solver and just click the solve button. It will be updated after you do so.
If you can not find excel solver in your excel spreadsheet, just follow this: https://support.office.com/en-us/article/load-the-solver-add-in-in-excel-612926fc-d53b-46b4-872c-e24772f078ca
Comment: Could you please elaborate on how to solve the linear problem?
Comment: Check the updated answer
Answer: Considering the problem
$$
\min_{x_k}\sum_{k=1}^n |a_k-x_k|\ \ \mbox{s. t.}\ \ \sum_{k=1}^n x_k = n d
$$
This problem can be handled by the Dynamic Programming multi-stage process algorithm with $f_k(x_k) = |a_k-x_k|$
$$
M_1(x) = f_1(x)\\
M_k(x) = \min_{-nd \le x_k \le nd}\left[f_k(x_k)+M_{k-1}(x-x_k)\right]
$$
and finally $\min M_n(\cdot)$ is the sought value.
Answer: Let
$$s=3d-a-b-c.\tag1$$
If $\underline{s=0}$ then vector $\{x,y,z\}=\{a,b,c\}$ provides the global minimum
$|a-x|+|b-y|+|c-z| = 0.$
Otherwize, denote
\begin{cases}u=\min\left(\dfrac{x-a}s,\dfrac{y-b}s,\dfrac{z-c}s\right)\\
v=\mathrm{med}\left(\dfrac{x-a}s,\dfrac{y-b}s,\dfrac{z-c}s\right)\\
w=\max\left(\dfrac{x-a}s,\dfrac{y-b}s,\dfrac{z-c}s\right),\tag2
\end{cases}
then
$$u+v+w = 1,\quad u\le v\le w.\tag3$$
Let us minimize the function
$$f(u,v)=|u|+|v|+1-u-v\tag4$$
under the conditions $(3),$ using the intervals method.
$\underline{\text{Case }\mathrm{u \le v \le 0 \le 1-u-v}}.$
$$f(u,v) = 1-2u-2v,\quad u\le v\le 0\le 1-u-v,$$
$$\min f(u,v)= 1\quad\text{at}\quad \{u,v\}=\{0,0\}$$
$\underline{\text{Case }\mathrm{u \le 0\le v\le 1-u-v}}.$
$$f(u,v) = 1-2u,\quad u\le 0\le 2v\le 1-u,$$
$$\min f(u,v)= 1\quad\text{at}\quad u=0,\quad v\in\left[0,\frac12\right].$$
$\underline{\text{Case }\mathrm{0\le u \le v\le 1-u-v}}.$
$$\min f(u,v) = 1 \quad\text{at}\quad 0 \le u \le \dfrac13,\quad v \le \dfrac{1-u}2.\tag5$$
Formulas $(5)$ present the common solution. In the terms of $x,y,z,$ this gives
$$\color{brown}{\mathbf{\min|a-x|+|b-y|+|c-z| = |3d-a-b-c|\quad\text{at}\\
{\small \left[\begin{align}
&\left(\dfrac{x-a}s\in\left[0,\dfrac13\right]\right)\wedge\left(\dfrac{y-b}s\in\left[0,\dfrac12\left(1-\dfrac{x-a}s\right)\right]\right)\wedge\left(\dfrac{z-c}s\in\left[0,1-\dfrac{x-a}s-\dfrac{y-b}s\right]\right)\\
&\left(\dfrac{x-a}s\in\left[0,\dfrac13\right]\right)\wedge\left(\dfrac{z-c}s\in\left[0,\dfrac12\left(1-\dfrac{x-a}s\right)\right]\right)\wedge\left(\dfrac{y-b}s\in\left[0,1-\dfrac{x-a}s-\dfrac{z-c}s\right]\right)\\
&\left(\dfrac{y-b}s\in\left[0,\dfrac13\right]\right)\wedge\left(\dfrac{x-a}s\in\left[0,\dfrac12\left(1-\dfrac{y-b}s\right)\right]\right)\wedge\left(\dfrac{z-c}s\in\left[0,1-\dfrac{x-a}s-\dfrac{y-b}s\right]\right)\\
&\left(\dfrac{y-b}s\in\left[0,\dfrac13\right]\right)\wedge\left(\dfrac{z-c}s\in\left[0,\dfrac12\left(1-\dfrac{y-b}s\right)\right]\right)\wedge\left(\dfrac{x-a}s\in\left[0,1-\dfrac{z-c}s-\dfrac{y-b}s\right]\right)\\
&\left(\dfrac{z-c}s\in\left[0,\dfrac13\right]\right)\wedge\left(\dfrac{y-b}s\in\left[0,\dfrac12\left(1-\dfrac{z-c}s\right)\right]\right)\wedge\left(\dfrac{x-a}s\in\left[0,1-\dfrac{z-c}s-\dfrac{y-b}s\right]\right)\\
&\left(\dfrac{z-c}s\in\left[0,\dfrac13\right]\right)\wedge\left(\dfrac{x-a}s\in\left[0,\dfrac12\left(1-\dfrac{z-c}s\right)\right]\right)\wedge\left(\dfrac{y-b}s\in\left[0,1-\dfrac{z-c}s-\dfrac{x-a}s\right]\right)\\
\end{align}\right.}}}$$


How to get multiple value from different condition, Just like WP Meta Query works?

Question: META TABLE ==
meta_id | post_id | meta_key | meta_value
1       | 101     | quantity | 8
2       | 101     | price    | 100
3       | 102     | quantity | 7
4       | 102     | price    | 56
5       | 103     | quantity | 12
6       | 103     | price    | 256

POST TABLE ==
post_id | name      | about
101     | Pencil    | Luxurious pencil only for you
102     | Eraser    | All your mistakes, gone!
103     | Pen       | Unrivaled penmanship, stronger than sword.

How to do a query to post id and get post : name,about with meta: value, price and quantity in a single go?
so the results will be
 101   | Pencil   | Luxurious pencil only for you              | 8   | 100
 102   | Eraser   | All your mistakes, gone!                   | 7   | 56
 103   | Pen      | Unrivaled penmanship, stronger than sword. | 12  | 256

Thank you
Answer: You have to join meta_table twice. Use left join if either quantity or price will not have an entry in meta_table for a given post_id.
select p.post_id, p.name, p.about, m1.meta_value, m2.meta_value
from post_table p
join meta_table m1 on m1.post_id = p.post_id and m1.meta_key = 'quantity'
join meta_table m2 on m2.post_id = p.post_id and m2.meta_key = 'price'


How to connect C-Wire to Weil-McLain Boiler CGa Series 3

Question: I'm trying to install a Nest learning WIFI thermostat to my boiler. However, I'm not sure where to connect the common wire. I've went through multiple posts on this forum but unfortunately wasn't able to find a resolution.
Below is my boiler's schematic wiring diagram. Diagram Link

I'm assuming that TSTAT BK(C) is the common wire? However, my boiler is connected to low water cut off and high water limit. In attached picture, blue pen drawing shows existing wirings. The Low Water Cut Off has 4 wires, and one is already connected to the C Common terminal. Can I just connect my thermostat's C wire to the same terminal? (Green pen in drawing) Thanks!
Also, please let me know if the wiring is correct because the previous owner installed the boiler himself so the wiring might be off.
Comment: Is your boiler providing *hot water* to your heating system, or *steam*?
Comment: It's providing hot water to the heating system. Thanks for the question
Comment: Can you post photos of your boiler's nameplate please?
Comment: Just added a few more pictures to the thread. Let me know if you need additional information!
Comment: the manual for your boiler can be found [here](https://www.weil-mclain.com/sites/default/files/field-file/CGa%20Series%203%20Boiler%20Manual%20%20%200520.pdf) (it's a CGa Series 3, not the EG/PEG that other posters here had)
Answer: You'll need to work around what the installer did
Your boiler's installer put the safeties (high limit aquastat, LWCO) in line with the thermostat instead of wiring them in with the spill switch as the CGa manual calls for.  As a result of this, you'll need to tie the green wire into the R wire from the transformer and control connector, then connect it to Rc on your Nest, in addition to connecting the blue wire to C as you indicate in your diagram.  The red wire then lands on Rh, with the white on W, as you'd expect; this means that your boiler won't confuse your thermostat if it ever malfunctions and cuts out on low water, overtemperature, or such.
Comment: I've added a new digram with dash lines following what you recommended. Hopefully this is what you meant. where is R wire from the control board? Just curious, why do we need to connect green wire to red transformer and also connect it to Rc?
Comment: @Kevin2344 -- to make sure the thermostat doesn't get confused by a power cut if the low-water cutoff or high-limit aquastat kicks in to shut the boiler down
Comment: @Kevin2344 -- yeah, your diagram looks correct
Comment: I added a new diagram for my second boiler. However, I noticed the wiring is very different than the first one. Can I still use the suggestion above with the dash lines?
Comment: @Kevin2344 -- swap the wires going to RH and W on the thermostat, and you should be good for Boiler #2
Comment: Thanks for the response. Do you mind clarify why do we need to swap RH and W for the second boiler (the new flow will be Red wire going to W and White wire going to Rh)? Isn't red wire usually means Rh, and White wire is W? Did the previous installer mess it up?
Comment: @Kevin2344 -- it's not strictly necessary to swap them, no
Comment: I just connected thermostat c wire to black common wire from boiler, the smart thermostat is lighting up and showing the temperature. However, when I set the temperature, it's not heating up? Do you know why? I didn't swap Rh with W, do I need to swap these two wires?
Comment: @Kevin2344 -- make sure you have Rc provided as well as Rh
Comment: Just connected Rc to Red transformer. The boiler automatically starts heating, and I can't turn it off or set a temperature? hmmm
Comment: @Kevin2344 -- that's weird, you may have to go and reinit system setup on that Nest to make it "see" that it has separate power on Rc and Rh
Comment: do you think it's because my second boiler wiring is wrong? should I switch the wires to make them look like the first boiler? Thermostat Rh to LWCO white, Thermostat W to TSTAT black, LWCO yellow to Aquastat white, LWCO white to TSTAT common.
Comment: Also the thermostat already has a jumper wire between Rh and Rc, should I cut the jumper wire?
Comment: @Kevin2344 -- aah, I thought the second thermostat was a Nest as well -- since it's some other sort of thermostat with a physical Rh-Rc jumper, you'll have to remove the jumper wire
Comment: got it, I'll cut the jumper wire.. I also noticed that current w wire has voltage and r wire doesn't at thermostat. Shouldn't r be the wire with power and w without any voltage? should I swap them, maybe the previous installer didn't follow the color coding?
Comment: it worked!! thank you. After trying to install it for three months, my new home finally has a smart thermostat installed! Do you mind explain again why we need to connect Rc to Red transformer? Also why if not connected, I can't set the heat from the thermostat? Also if not cut the jumper wire from the thermostat, the heat will always be on and can't turn off?
Comment: @Kevin2344 -- the issue with the jumper was that it was shorting R to W effectively (and cutting out safeties in the process).  Connecting Rc to the transformer is needed so that a safety trip doesn't cut power to the thermostat entirely and confuse it


How to hide Unique Characters?

Question: I noticed that the generic Nine-tails have higher stats (equipment aptitude?) compared to Izuna. In fact, I checked that each Overlord have lower stats when compared to their generic counterpart (Geese - Chimera, Drumdawn - Zwei Head, etc.) Even with balanced distributions, I find the generic versions more appealing.
Is there some sort of room or lobby that I can use to hide them? Like the Detention Hall in Disgaea 3 or the Supporter Room in Disgaea 4?
Comment: I don't know if this would really classify as an answer but you could use your three character groups and only add in your generic characters and leave out the unique characters you don't want.
Comment: Yes. I think your explanation would count as an answer.
Answer: Unfortunately, there is no "Detention Hall"-like feature in Disgaea 5, as explained here. However, there are ways to make your unique characters disappear if you don't want to have to see them. From the above thread:

You can send them out to other netherworlds if you don't want to see them

A particularly interesting and useful way to use these characters is this one:

I recommend using dispatches, arranging your team so that the guys you don't care about will be the last ones down the list, and even having units for the sole purpose of delimiting your unit list (with names like "--USELESS--" or "--SUPPORT--").

Another suggestion with dispatches:

You can also set up a dispatch squad of the people you use by hitting the square button in the character list screen and then you won't see all the characters

How to hide Unique Characters?


CSS blur a portion of background image

Question: I have the following HTML/CSS code
<!DOCTYPE html>

I want the middle of the image to be blurred into a dot.  If I change the background color of #blur to blue, I can see that it exists.  But the circle blur isn't happening.
Any suggestions on how to get a blurred circle in the picture via CSS ?
Comment: Try `display:none` instead of block on #blur.
Comment: That removes the blur entirely
Answer: Workaround / solution:
You'll have to apply a blur to the initial image to blur it, since you can't apply it to a specified spot, we'll just have to use an overlay- blur this and resize it. We can use your dot pretty easily for this, just add the following CSS to your current file:
#blur {
    background-image: url(https://upload.wikimedia.org/wikipedia/commons/5/50/Montage_of_Toronto_7.jpg);
    background-position: center center;
}

And the outcome would look like this:

Comment: Oh i changed my question slightly.  In my `#image`, I made `background-size:cover;` and `width: 100%;` .  So now now the middle dot should blur different regions of the image as you re-size the window.  This will require a javascript solution then?
Comment: Let me juggle around with it tonight, pure CSS is probably cleaner
Comment: So that means if I make the `#blur` a draggable item, I'll have to re-calculate the background image position each time?
Comment: I'm afraid so John
Answer: you can use this code

body {
            background: url('https://images.unsplash.com/photo-1486723312829-f32b4a25211b?dpr=2&auto=format&fit=crop&w=1500&h=1000&q=80&cs=tinysrgb&crop=&bg=') no-repeat center center fixed;
            background-size: cover;
        }
        .blur {
            background: url(https://images.unsplash.com/photo-1486723312829-f32b4a25211b?dpr=2&auto=format&fit=crop&w=1500&h=1000&q=80&cs=tinysrgb&crop=&bg=) no-repeat center center fixed;
            background-size: cover;
            overflow: hidden;
            filter: blur(13px);
            position: absolute;
            height: 300px;
            top: -50px;
            left: -50px;
            right: -50px;
            bottom: -50px;
            width: 300px;
            margin: 0 auto;
            border-radius: 100px;
        }
        .widget {
            border: 5px solid rgba(255, 255, 255, .5);
            height: 300px;
            width: 300px;
            border-radius: 100%;
            overflow: hidden;
        }
        .center {
            position: absolute;
            margin: auto;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
        }
        .text {
            height: 300px;
            width: 300px;
        }
        .text h1 {
            text-align: center;
            text-shadow: 1px 1px rgba(0, 0, 0, .1);
            color: #ffffff;
            margin-top: 100px;
            font-family: 'Lora', serif;
            font-weight: 700;
            font-size: 38px;
        }
        .text p {
            text-align: center;
            color: #ffffff;
            text-shadow: 1px 1px rgba(0, 0, 0, .1);
            margin-top: 0px;
            font-family: 'Lato', serif;
            font-weight: 400;
            font-size: 22px;
        }

Lorem ipsum

sit amet ipsum dolor

CSS blur a portion of background image


Resizing Text by Theme in Flutter

Question: I'm trying to use a GestureDetector to allow the user to change the font size by pinching:
class _PinchToScaleFontState extends State<PinchToScaleFont> {
  double _baseFontScale = 1;
  double _fontScale = 1;
  ThemeData _themeData;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Theme(
        data: _themeData,
        child: widget.child       // The desired outcome is that all Text is resized
      ),
      onScaleStart: (ScaleStartDetails scaleStartDetails) {
        _baseFontScale = _fontScale;
      },
      onScaleUpdate: (ScaleUpdateDetails scaleUpdateDetails) {
        // don't update the UI if the scale didn't change
        if (scaleUpdateDetails.scale == 1.0) {
          return;
        }
        setState(() {
          double fontScale = (_baseFontScale * scaleUpdateDetails.scale).clamp(0.5, 5.0);
          _updateFontScale(fontScale);
          SharedPreferences.getInstance().then((prefs) => prefs.setDouble('fontScale', fontScale));
        });
      },
    );
  }

I can get the following code to adjust the scale of a TextField, but it won't resize any Text widgets.
  _updateFontScale(double fontScale) {
    setState(() {
      _fontScale = fontScale;
      ThemeData theme = Theme.of(context);

      /// This doesn't seem to work at all
      // _themeData = theme.copyWith(textTheme: theme.textTheme.merge(TextTheme(bodyText2: TextStyle(fontSize: 14 * fontScale))));

      /// This works for `TextField` but not `Text`
      _themeData = theme.copyWith(textTheme: theme.textTheme.apply(fontSizeFactor: fontScale)); // merge(TextTheme()));
    });
    // }
  }

It's strange. In the code below I can use the saved fontScale to initialise the font size for the whole app the next time it's loaded, but why won't the code above, which seems to be accessing the same theme property give the same results?
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  double savedFontScale = (await SharedPreferences.getInstance()).getDouble('fontScale') ?? 1.0;

  runApp(MyApp(savedFontScale));
}

class MyApp extends StatelessWidget {
  final double fontScale;

  MyApp(this.fontScale);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: APP_NAME,
      theme: ThemeData(
        textTheme: TextTheme(
          /// This works for all `Text` widgets - but you've got to restart the app
          bodyText2: TextStyle(fontSize: 14 * fontScale),
      ...
      home:
         ...
         PinchToScaleFont(
             ...
             TextField('This _will_ resize '),
             Text('This will not resize, but it should '),

Answer: You can copy paste run full code below
Because textScaleFactor of Text reference MediaQueryData.textScaleFactor
source code of Text.dart https://github.com/flutter/flutter/blob/97295dc9a885c995cda99ba9cee421d3ab1a8e2d/packages/flutter/lib/src/widgets/text.dart#L479
  /// The value given to the constructor as textScaleFactor. If null, will
  /// use the [MediaQueryData.textScaleFactor] obtained from the ambient
  /// [MediaQuery], or 1.0 if there is no [MediaQuery] in scope.
  final double? textScaleFactor;

You can wrap widget.child with MediaQuery
and set mediaQueryData.copyWith(textScaleFactor: fontScale)
code snippet
  MediaQueryData _mediaQueryData;

  _updateFontScale(double fontScale) {
    setState(() {
      _fontScale = fontScale;
      ThemeData theme = Theme.of(context);
      MediaQueryData mediaQueryData = MediaQuery.of(context);
      ...

      _mediaQueryData = mediaQueryData.copyWith(textScaleFactor: fontScale);
    });
  ...

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Theme(
          data: _themeData,
          child: MediaQuery(data: _mediaQueryData, child: widget.child)
          ),

working demo

full code
import 'package:flutter/material.dart';

class PinchToScaleFont extends StatefulWidget {
  final Widget child;

  const PinchToScaleFont({Key key, this.child}) : super(key: key);
  @override
  _PinchToScaleFontState createState() => _PinchToScaleFontState();
}

class _PinchToScaleFontState extends State<PinchToScaleFont> {
  double _baseFontScale = 1;
  double _fontScale = 1;
  ThemeData _themeData;
  MediaQueryData _mediaQueryData;

  _updateFontScale(double fontScale) {
    setState(() {
      _fontScale = fontScale;
      ThemeData theme = Theme.of(context);
      MediaQueryData mediaQueryData = MediaQuery.of(context);

      /// This doesn't seem to work at all
      // _themeData = theme.copyWith(textTheme: theme.textTheme.merge(TextTheme(bodyText2: TextStyle(fontSize: 14 * fontScale))));

      /// This works for `TextField` but not `Text`
      _themeData = theme.copyWith(
          textTheme: theme.textTheme
              .apply(fontSizeFactor: fontScale)); // merge(TextTheme()));

      _mediaQueryData = mediaQueryData.copyWith(textScaleFactor: fontScale);
    });
    // }
  }

  @override
  void didChangeDependencies() {
    _themeData = Theme.of(context);
    _mediaQueryData = MediaQuery.of(context);
    super.didChangeDependencies();
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Theme(
          data: _themeData,
          child: MediaQuery(data: _mediaQueryData, child: widget.child)
          // The desired outcome is that all Text is resized
          ),
      onScaleStart: (ScaleStartDetails scaleStartDetails) {
        _baseFontScale = _fontScale;
      },
      onScaleUpdate: (ScaleUpdateDetails scaleUpdateDetails) {
        // don't update the UI if the scale didn't change
        if (scaleUpdateDetails.scale == 1.0) {
          return;
        }
        setState(() {
          double fontScale =
              (_baseFontScale * scaleUpdateDetails.scale).clamp(0.5, 5.0);
          _updateFontScale(fontScale);
          //SharedPreferences.getInstance().then((prefs) => prefs.setDouble('fontScale', fontScale));
        });
      },
    );
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            PinchToScaleFont(
                child: Column(
              children: [
                TextField(),
                Text('This will not resize, but it should '),
              ],
            )),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

Comment: Awesome! Thanks for the work putting together the demo!
Comment: Glad to help. please mark this as answer if it helps you. thanks.

Resizing Text by Theme in Flutter


How to add a Firebase new doc with multiple keys and value through loop in JS

Question: I got this code in JS and I loop through all the elements with a specific class and then I want to take the id of each element and set that as a key with the value of each element to Firestore database.
Instead of doing something like this:
db.collection('fixprices').add({
    name: htmlname.value,
    stmp: gettime,
    fix1: value,
    fix2: value,
    fix3: value,
    fix4: value,
    fix5: value,
    fix6: value,
    fix7: value
});

Can I do it through the loop taking each element id and replace it with the fix1,fix2... and for the value also?
Is there a simple way to do so?
Comment: If you have multiple data stored in somewhere you can do it. But you have to keep on changing the values
Answer: Is this what you're trying to do?
const elements = [
    { id: 'id1', value: 'some value' },
    { id: 'id2', value: 'some other value' },
    { id: 'id3', value: 'another value' },
];
const objectToAdd = {
  name: htmlname.value,
  stmp: gettime
};
elements.forEach((element, index) => {
    objectToAdd['fix' + (index + 1)] = element.value;
});
db.collection('fixprices').add(objectToAdd);


Calling setState() with child functional component causes infinite loop

Question: I am using react-week-scheduler to display a week calendar view on my page. This component is a functional child component to a class-based parent component. I would like the parent component to manage the schedule state for the events that show up on the calendar and pass it down to the child component as props.
The issue I'm facing is that every time I make an adjustment on the TimeGrid (by clicking and dragging out a new event block) and trigger my handleGridChange function to save that adjustment to the schedule state field, it results in an endless loop of state updating as setState causes the child TimeGrid component to update, thus triggering the handleGridChange function again, putting me into an endless loop.
The TimeGrid component works fine if I handle the schedule state directly on the child component and update it with a useState hook, but then the rest of my application doesn't have access to the schedule state. I have tried converting the TimeGrid to a class-based component, but then I run into other issues with setState as I don't think the component was designed to be used that way.
I'm pretty new/unfamiliar with react hooks so I feel like that might contribute to some, or even all, of this issue. It may also have something to do with the way the TimeGrid component is designed with useEffect constantly changing things when I set state, but I'm not sure and can't figure it out. Any insight would be very helpful.
My parent component looks something like this:
import TimeGrid from './TimeGrid';

class ScheduleView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      schedule: [], // initially empty
    };
  )

  handleGridChange(newSchedule) {
    this.setState({
      schedule: newSchedule,
    });
  }

  render() {
    return (
      <TimeGrid
        schedule={this.state.schedule}
        handleGridChange={this.handleGridChange.bind(this)}
      />
    );
  }
}

And my TimeGrid component looks like this:
function TimeGrid(props) {
  // const [schedule, setSchedule] = useState([]); // <-- managing state with this works fine, but then I don't have access to it outside this component

  // oldHandleGridChange(newSchedule) {
  //   setSchedule(newSchedule);
  // }

  return (
    <TimeGridScheduler
      schedule={props.schedule}
      onChange={props.handleGridChange}
    />
  );
}

export default TimeGrid;

Comment: bind the function on the constructor and then pass the function to Child
Answer: Need to bind it on constructor, when ever function binding is passed as props a new function will be created by which the props will signify a change triggering the render again
import TimeGrid from './TimeGrid';

class ScheduleView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      schedule: [], // initially empty
    };
    this.handleGridChange = this.handleGridChange.bind(this);
  )

  handleGridChange(newSchedule) {
    this.setState({
      schedule: newSchedule,
    });
  }

  render() {
    return (
      <TimeGrid
        schedule={this.state.schedule}
        handleGridChange={this.handleGridChange}
      />
    );
  }
}

Comment: This worked! Why do I need to bind it on the constructor (why wasn't what I had working)? If you update your answer with an explanation, I'll accept it.
Comment: Updated with an explanation @McFizz
Answer: Just you need to trigger the onChange event once. Or in short, you can bind the function using the fat arrow function ( => ).
import TimeGrid from './TimeGrid';

class ScheduleView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      schedule: [], // initially empty
    };
  )

  handleGridChange = (newSchedule) => {
    this.setState({
      schedule: newSchedule,
    });
  }

  render() {
    return (
      <TimeGrid
        schedule={this.state.schedule}
        handleGridChange={(e) => this.handleGridChange(e)}
        /* or handleGridChange={ this.handleGridChange } */
      />
    );
  }
}

Comment: How is this different from my current implementation?
Comment: you are calling this.handleGridChange() on mounting of the component. Instead of you have to call the function on triggering some event i.e in this case this.handleGridChange()
Answer: It is mostly because onChange function is triggered infinite time and you will need to add arrow operator over there.
This link might help you
Prevent Infite loop
Answer: Use this instead of your handleGridChange function
<TimeGrid
        schedule={this.state.schedule}
        handleGridChange={(newSchedule) => this.setState({schedule: newSchedule})}
/>

it'll work for sure.


SQL Oracle - convert row to column

Question: My SQL output currently produces this:
DEPARTMENT | MM-YYYY | ROW_LABEL | SCORE
   A         05-2018    STAFF      79.0
   A         06-2018    STAFF      81.0
   A         05-2018    SCHED      72.3
   A         06-2018    SCHED      74.5
   B         05-2018    STAFF      77.4
   B         06-2018    STAFF      74.3
   B         05-2018    SCHED      81.3
   B         06-2018    SCHED      78.6

My goal is to automatically convert the date value from the row, to be it's own column. Something like this:
DEPARTMENT | ROW_LABEL | 05-2018 | 06-2018
   A           STAFF      79.0      81.0
   A           SCHED      72.3      74.5
   B           STAFF      77.4      74.3
   B           SCHED      81.3      78.6

This report would change monthly, so the goal is that the MM-YYYY + Score are auto populated. Next time I run this it would be 06-2018 and 07-2018, I don't want to hard code the date every time I want to produce this report.
Comment: Search "Oracle Pivot"
Comment: thanks for editing that. I was trying to figure out how to produce a table like output in SO. I will look into the Pivot. My earlier google searches gave me some options but were forcing me to specifically populate my MM-YYYY column instead of taking whatever MM-YYYY was already there.
Comment: This SQL code gets me what I want today...PIVOT (SUM(SCORE) AS S FOR (MM_YYYY) IN ('05-2018' AS A, '06-2018' AS B));

But, how do I automate that IN portion so it automatically picks the MM-YYYY instead of me having to populate it? @JuanCarlosOropeza
Answer: You can try like this:
SQL DEMO
SELECT
     "DEPARTMENT", "ROW_LABEL" ,
     MAX(CASE WHEN "MMYYYY" = (select TO_CHAR(ADD_MONTHS(sysdate,-1), 'MM-YYYY') from dual)
              THEN "SCORE"
         END) as previous_month,
     MAX(CASE WHEN "MMYYYY" = (select TO_CHAR(sysdate, 'MM-YYYY') from dual)
              THEN "SCORE"
         END) as current_month
FROM Table1
GROUP BY "DEPARTMENT", "ROW_LABEL"
ORDER BY "DEPARTMENT", "ROW_LABEL" DESC;

OUTPUT
| DEPARTMENT | ROW_LABEL | PREVIOUS_MONTH | CURRENT_MONTH |
|------------|-----------|----------------|---------------|
|          A |     STAFF |             79 |            81 |
|          A |     SCHED |           72.3 |          74.5 |
|          B |     STAFF |           77.4 |          74.3 |
|          B |     SCHED |           81.3 |          78.6 |

If you want the exact date on the header then you need DYNAMIC PIVOT

SQL Oracle - convert row to column


create a random integer unique in a given array

Question:
1572 4528 3564 8921 4521

I need to create a new random integer (4 digits), unique regarding the above content.
js
var content = $('#passarr').text();
var passarr = content.split(' ');
var pass = Math.floor(Math.random() * 9000) + 1000;
var i = 0;
while (i == 0) {
    if (jQuery.inArray(pass, passarr) > -1) {
        var pass = Math.floor(Math.random() * 9000) + 1000;
        i = 1;
    }
}

seems it works, but not sure this is the right and shortest way.
any suggestion?
Comment: It looks like the boolean expression in your `if` statement should actually be the boolean expression in the `while` statement. You don't need `i`.
Comment: I think what @4castle meant was `while (jQuery.inArray(pass, passarr) === -1)) { ... }`
Comment: This works by luck. In (5/9000)**2 cases, it wont work... ;0
Comment: Is `#passarr` the result?
Comment: @zer00ne, no, result is `pass`
Comment: Part of the issue is you have `var pass` twice I assume.  take the `var` off the inner pass.
Comment: @RobM. Yeah, I misread their code and thought they had written the opposite of what I thought, which means they need `> -1` in the `while` loop if they're trying to generate new numbers.
Answer: Your code is the way to go. However, you can eliminate a few smaller mistakes ( an unneccessary i and non working code in < 0.00001%) :
var content = $('#passarr').text();
var passarr = content.split(' ');
do {
  var pass = Math.floor(Math.random() * 9000) + 1000;
} while (jQuery.inArray(pass, passarr) > -1);

console.log(pass);

Comment: This is exactly the algorithm they need. My only suggestion is to move the declaration of `var pass` to be outside of the loop, so that someone who isn't aware of hoisting won't be confused by the scope of `pass`.
Comment: @4castle thats actually a point for not changing it. Theyll wonder that this works, and will be more clever afterwards ;)
Comment: excellent, later I saw that my code in fact doesn't work. This works. thanks a  lot.


How can I live in a large house and not have high utility bills?

Question: I would like to buy a five bedroom house in Illinois, mainly because I love the property. I wish the house was smaller, because I would be the only one living there. My plan would be to live in only a small portion of it, but how could the utility bills be low? It would need to be weatherized, but is there a way to heat just a small portion of the house without the pipes bursting in the winter?
Comment: How much work and capital do you want to invest in this house?
Comment: Also yes -- what do you have for a heating system in the house, and how well is it insulated and air sealed at present? (See if you can get a blower door test run as part of the inspection before you buy it)
Comment: @ThreePhaseEel It's forced air. I haven't decided how much work & capital I want to put into it, but don't want to be inundated with bills. The utility bills right now are through the roof, but there are a lot of cracks that can be sealed up. In the winter, you can feel cold air blowing from under the front door. Thanks for the advice. Property taxes are $27K/yr.
Answer: Good insulation, double glazing, air conditioning used with care (-8°C difference from outside is enough in summer, 20°C is ok in winter), class A++ electric appliance, gas tankless water heater, led lighting.
Comment: And don't forget the air sealing to go with that insulation!
Answer: It really depends on the existing insulation and heating system - depending on whether it's forced hot air, hot water radiators, steam radiators, or baseboard electric, it may be difficult to turn off the heat in unused rooms.
With baseboard electric, it's usually pretty easy - there's usually a thermostat in every room, essentially every room is it's own zone, you can turn it down or off as easily as turning a dial.  With steam and hot water, it really depends on how the zones are loops are laid out, but it's often doable with steam.
Protecting the pipes depends on the plumbing layout.  You have to be particularly careful where pipes are in outside walls, and how the outside walls are insulated.  It may be that you have to use heat tape and / or insulate those pipes to prevent freezing.
You probably don't want to let the temperature in the unused part of the house go too low for various reasons.  Properties that are used seasonally (vacation homes, etc.) have lots of issues that come from freezing and thawing etc. - condensation, cracks in the finishes, etc. etc.
No matter what you do, you can't change some factors - you still have more surface area, a larger system to maintain, etc., so costs are still going to be higher than a small house.
Comment: The Dept. of Energy puts out a "pie-chart" that shows where a typical family spends their energy costs. The chart shows about 60% - 65% goes towards heating/cooling. Another 20% - 25% goes towards hot water heating. The rest is lights, etc. So, if you're going to spend money to save energy, guess what you should attack first? Focus on quick paybacks like: 1) attic insulation, 2) wall insulation, 3) air filters, 4) full load washer/dishwasher
Comment: batsplatsterson Thanks a lot! It's forced hot air.


How to fix DateTimeNormalizer issue when using Symfony Serializer

Question: I am having trouble using the Symfony Serializer to normalize DateTime objects into strings.
I am using the following code:
<code>protected function createResponse($data, Int $statusCode){

    $serializedData = $this->serialize($data);

    return new Response($serializedData, $statusCode, array(
        'Content-Type' => 'application/json',
    ));

}

protected function serialize($data, string $format = 'json')
{
    $encoders = [new JsonEncoder()];
    $normalizers = [new ObjectNormalizer(), new DateTimeNormalizer()];

    $serializer = new Serializer($normalizers, $encoders);

    return $serializer->serialize($data, $format);
}
</code>
I am passing Entities which contain DateTimeInterface variables into the createResponse method defined above but the dates are not being normalised to the RFC3339 format. Am I missing an important step?
Example output I am getting:
<code>"reportDate":{"timezone":{"name":"UTC","transitions":[{"ts":-9223372036854775808,"time":"-292277022657-01-27T08:29:52+0000","offset":0,"isdst":false,"abbr":"UTC"}],"location":{"country_code":"??","latitude":0,"longitude":0,"comments":""}},"offset":0,"timestamp":1551398400}
</code>
Comment: Did you try moving the dateTimeNormalizer before the object normalizer?
Comment: I just tried emix and it works thank you so much!
Comment: Please mark my answer as the solution then. Glad I could help.
Answer: tl;dr order matters.
Try:
<code>$normalizers = [new DateTimeNormalizer(), new ObjectNormalizer()];
</code>
Instead of:
<code>$normalizers = [new ObjectNormalizer(), new DateTimeNormalizer()];
</code>
Comment: Could you explain on why this exactly solves the problem? Because it seems that the order of the normalizers is something that apparently matters but it does not seem to be documented.