text:
Q: Query all of a sudden stopped working - Simple left join but cannot see what is wrong I had a query that was a simple left join between two tables with IS NULL included in the where clause because I needed all of the rows of the left table shown, even if it gave null values in the right table.
This worked as I had it working within my php code and my site was displaying what it needed. I haven't looked at this in over a week and went back today to see that it is now all of a sudden not working even though I haven't touched it.
I have created a db fiddle here with my exact code and tables - https://dbfiddle.uk/?rdbms=mariadb_10.4&fiddle=2effc82390641ce513806252700fd25c
I want to show - all rows in the left table (level_quiz) and all rows in the right table (student_points) where student_no = 40204123 OR there are NULL rows
Could anyone please have a look at this to see why it is not showing the extra row of the left table? (where there would be NULL values for the right table)
This would be much appreciated.

A: You have to select the student before joining.
also use aliases so you have less to type in

SELECT
    *
FROM
    level_quiz
        LEFT JOIN
    (SELECT * FROM student_points WHERE student_no = 40204123) sp ON level_quiz.id = sp.level_id

id | level_title            | quiz_desc                                                                                | overall_quest                                                                                | student_no | level_id | points | timestamp
-: | :--------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------: | -------: | -----: | :------------------
 1 | Sets                   | The purpose of this challenge is to help you become completely familiar with how to write certain kinds of sets, and how to perform the standard operations on actual sets.  | Suppose we have three sets of numbers A, B and C, which are defined as follows: A = { 1, 10, 7, 3, 5, 2 };B = { 5, 8, 6, 7, 4 };C = { 7, 1, 8 } |   40204123 |        1 |     80 | 2021-01-12 15:37:11
 2 | sequences              | sequences desc                                                                                | overall question 2                                                                                |   40204123 |        2 |     75 | 2021-01-12 15:38:06
 3 | Propositional Logic    | logic desc                                                                                | overall quest logic                                                                                |   40204123 |        3 |     30 | 2021-01-13 22:13:13
 4 | Predicate Logic - Sets | predicate desc 1                                                                                | predicase quest 1                                                                                |       null |     null |   null | null

db<>fiddle here

A: Your code is doing exactly what you are telling it to do!
<TL;DR>
There are three possible solutions to the problem outlined here:

*

*add additional records with NULL entries to "force" the tables to JOIN,

*rewrite the SQL (making it less performant - see performance analysis section at the end),

*change the schema (normalisation) - this is optimal IMHO - better performance and a better respresentation of reality.
</TL;DR>
I adapted your schema to make it more legible for my tastes (the fiddle for the first part of this analysis is available here):
CREATE TABLE level_quiz
(
  id            INTEGER       NOT NULL,
  level_title   VARCHAR  (50) NOT NULL,
  quiz_desc     VARCHAR (200) NOT NULL,
  overall_quest VARCHAR (250) NOT NULL
);

CREATE TABLE student_points
(
  student_no INTEGER   NOT NULL,
  level_id   INTEGER   NOT NULL,
  points     INTEGER   NULL,  -- << have to make NULLable, see below
  ts         TIMESTAMP NULL  -- << renamed timestamp to ts!
);

Two points to note:

*

*declaring a field as INT(x) where x is a number is pointless unless you need ZEROFILL (or here & here) - plus LPAD will do the same thing - plus it makes your code non-portable (see below),

*you should never use an SQL keyword (TIMESTAMP in this case) as a table or column name - it's bad for debugging, produces confusing error messages and is generally bad practice.
To make the results simpler, I've truncated fields as follows:
INSERT INTO level_quiz (id, level_title, quiz_desc, overall_quest)
VALUES
(1, 'Sets',       'The purpose of...', 'Suppose we have... '),  -- << truncated strings
(2, 'Seqs',       'sequences desc...', 'overall question... '),
(3, 'Prop Logic', 'logic desc    ...', 'overall quest... '),
(4, 'Pred Logic', 'pred desc 1   ...', 'predicase quest...');

and there are two extra records which I'll INSERT later on in my analysis.
INSERT INTO student_points (student_no, level_id, points, ts)
VALUES
(12345678, 1, 80, '2021-01-15 16:07:43'),
(12345678, 2, 25, '2021-01-13 17:15:10'),
(12345678, 3, 90, '2021-01-17 22:41:55'),
(12345678, 4, 90, '2021-01-17 22:41:55'),

(40204123, 1, 80, '2021-01-12 15:37:11'),
(40204123, 2, 75, '2021-01-12 15:38:06'),
(40204123, 3, 30, '2021-01-13 22:13:13'),
-- (40204123, 4, NULL, NULL),           -- <<<  -- see below what happens when this
                                                -- record is inserted

(40213894, 1, 90, '2021-01-14 21:52:00'),
(40213894, 2, 95, '2021-01-17 22:42:50'),
(40213894, 4, 100, '2021-01-17 22:42:50');
-- (40213894, 4, NULL, NULL),            -- <<< see below also

Now, your code:
SELECT *
FROM level_quiz
LEFT JOIN student_points
  ON level_quiz.id = student_points.level_id
WHERE student_points.student_no = 40204123
OR student_points.student_no IS NULL  -- <<-- Makes NO difference

Result (see fiddle for better formatting):
id  level_title quiz_desc   overall_quest   student_no  level_id    points  ts
 1  Sets    The purpose of...   Suppose we have...  40204123    1   80  2021-01-12 15:37:11
 2  Seqs    sequences desc...   overall question...     40204123    2   75  2021-01-12 15:38:06
 3  Prop Logic  logic desc    ...   overall quest...    40204123    3   30  2021-01-13 22:13:13

But, you only have 3 records - no corresponding NULL for student_no 40204123 for quiz level 4!
Now, when I obtain a strange result, my "go-to" reflex is to check what PostgreSQL does in the same situation. I have always found PostgreSQL to be superior in virtually every respect to MySQL.
So rather than rushing to report bugs to MySQL (good luck with that... - they have so many!), you should try checking on other servers - it's unlikely that a fundamental bug in something so basic as a LEFT JOIN would have gone undetected for long! The result is here and it can be seen that the data returned by PostgreSQL for the same query is identical!
So, what's going on?
Well, we'll now take a look at @nbk's answer here.
--
-- Solution proposed by nbk - NULLs in the result as desired!
--

SELECT
  lq.id, lq.level_title, lq.quiz_desc, lq.overall_quest,
  sp.student_no, sp.level_id, sp.points, sp.ts
FROM
  level_quiz lq
LEFT JOIN
 (
   SELECT * FROM student_points
   WHERE student_no = 40204123
 ) sp
 ON lq.id = sp.level_id;

Result (better viewed on the fiddle):
id  level_title quiz_desc   overall_quest   student_no  level_id    points  ts
1   Sets    The purpose of...   Suppose we have...  40204123    1   80  2021-01-12 15:37:11
2   Seqs    sequences desc...   overall question...     40204123    2   75  2021-01-12 15:38:06
3   Prop Logic  logic desc    ...   overall quest...    40204123    3   30  2021-01-13 22:13:13
4   Pred Logic  pred desc 1   ...   predicase quest...  NULL    NULL   NULL  NULL

So now, we apparently have the correct result - with NULLs for quiz level 4! However, now let's look at what happens when we run the same query for **2** students!
--
-- bb25's original SQL - with 2 students - but no NULLs in the result!
--

SELECT *
FROM level_quiz
LEFT JOIN student_points
  ON level_quiz.id = student_points.level_id
WHERE student_points.student_no IN (40204123, 40213894)
OR student_points.student_no IS NULL  -- << Makes NO difference!

Result:
id  level_title quiz_desc   overall_quest   student_no  level_id    points  ts
1   Sets    The purpose of...   Suppose we have...  40204123    1   80  2021-01-12 15:37:11
2   Seqs    sequences desc...   overall question...     40204123    2   75  2021-01-12 15:38:06
3   Prop Logic  logic desc    ...   overall quest...    40204123    3   30  2021-01-13 22:13:13
1   Sets    The purpose of...   Suppose we have...  40213894    1   90  2021-01-14 21:52:00
2   Seqs    sequences desc...   overall question...     40213894    2   95  2021-01-17 22:42:50
4   Pred Logic  pred desc 1   ...   predicase quest...  40213894    4   100 2021-01-17 22:42:50

Unexpectedly there are no NULLs - we have quiz results for 1, 2 & 3 for student 40204123 and quizzes 1, 2 & 4 for student 40213894.
Next, we reexamine nbk's answer.
--
-- SQL proposed by nbk - with 2 students - but again no NULLs in the result!
--
SELECT
  lq.id, lq.level_title, lq.quiz_desc, lq.overall_quest,
  sp.student_no, sp.level_id, sp.points, sp.ts
FROM
  level_quiz lq
LEFT JOIN
 (
   SELECT * FROM student_points
   WHERE student_no IN (40204123, 40213894)
 ) sp
 ON lq.id = sp.level_id;

Result:
id  level_title quiz_desc   overall_quest   student_no  level_id    points  ts
1   Sets    The purpose of...   Suppose we have...  40204123    1   80  2021-01-12 15:37:11
2   Seqs    sequences desc...   overall question...     40204123    2   75  2021-01-12 15:38:06
3   Prop Logic  logic desc    ...   overall quest...    40204123    3   30  2021-01-13 22:13:13
1   Sets    The purpose of...   Suppose we have...  40213894    1   90  2021-01-14 21:52:00
2   Seqs    sequences desc...   overall question...     40213894    2   95  2021-01-17 22:42:50
4   Pred Logic  pred desc 1   ...   predicase quest...  40213894    4   100 2021-01-17 22:42:50

Again there are no NULLs anywhere to be seen! The result for @nbk's answer is identical to that of the OP's SQL
Solution 1: - Add some (2) records!
So, we do this:
INSERT INTO student_points VALUES
(40204123, 4, NULL, NULL),     -- <<<  NOW we INSERT these records!
(40213894, 3, NULL, NULL);

Now, we have records for all students for all quiz levels - but obviously there can't be points for levels the students haven't completed a level (points = NULL), nor can there be a TIMESTAMP for something that hasn't happened (ts = NULL)!
So, basically, bb25's (i.e. the OP's) SQL works for this scenario (as does nbk's) and both pieces of SQL work for two students as well as for one - so, adding these records can solve the issue!
I'm only showing the OP's original SQL here (for 2 students) - more is shown on the fiddle.
--
-- bb25 original SQL - 2 students - NULLs NOW in the result
--

SELECT *
FROM level_quiz
LEFT JOIN student_points
  ON level_quiz.id = student_points.level_id
WHERE student_points.student_no IN (40204123, 40213894)
ORDER BY student_points.student_no, level_quiz.id;

Result (better viewed on fiddle):
id  level_title quiz_desc   overall_quest   student_no  level_id    points  ts
1   Sets    The purpose of...   Suppose we have...  40204123    1   80  2021-01-12 15:37:11
2   Seqs    sequences desc...   overall question...     40204123    2   75  2021-01-12 15:38:06
3   Prop Logic  logic desc    ...   overall quest...    40204123    3   30  2021-01-13 22:13:13
4   Pred Logic  pred desc 1   ...   predicase quest...  40204123    4
1   Sets    The purpose of...   Suppose we have...  40213894    1   90  2021-01-14 21:52:00
2   Seqs    sequences desc...   overall question...     40213894    2   95  2021-01-17 22:42:50
3   Prop Logic  logic desc    ...   overall quest...    40213894    3
4   Pred Logic  pred desc 1   ...   predicase quest...  40213894    4   100 2021-01-17 22:42:50

and now we do have NULL in the appropriate places.
Solution 2 - change the SQL to work with the original dataset:
A better solution might be to actually get the SQL to produce the desired data without having to add supplementary records - esp. records with NULLs - which many find problematic.
So, here I just perform a CROSS JOIN on student_no in the student_points table with the ids of the level_quiz table to get all the possible combinations of students with quiz...
So, first we DELETE the records which we inserted in order for Solution 1 to work.
DELETE FROM student_points WHERE points IS NULL;

and then run this SQL:
SELECT distinct sp1.student_no, t1.id
FROM student_points sp1
CROSS JOIN
(
  SELECT distinct lq.id
  FROM level_quiz lq
) AS t1
ORDER BY sp1.student_no, t1.id;

Result:
student_no  id
12345678    1
12345678    2
12345678    3
12345678    4
40204123    1
40204123    2
40204123    3
40204123    4
40213894    1
40213894    2
40213894    3
40213894    4
12 rows

Then, we have to JOIN these records back to their original tables thus:
SELECT
  t2.id,
  SUBSTRING(lq2.level_title, 1, 6) AS "LT:", lq2.quiz_desc, lq2.overall_quest,
  t2.student_no, COALESCE(sp2.points, 0) AS "Points:", sp2.ts
FROM
(
  SELECT distinct sp1.student_no, t1.id
  FROM student_points sp1
  CROSS JOIN
  (
    SELECT distinct lq1.id
    FROM level_quiz lq1
  ) AS t1
) AS t2
LEFT JOIN student_points sp2
  ON t2.student_no = sp2.student_no
  AND t2.id = sp2.level_id
JOIN level_quiz lq2
  ON t2.id = lq2.id
WHERE t2.student_no IN (40204123, 40213894)
ORDER BY t2.student_no, t2.id;

Result:
id  LT: quiz_desc   overall_quest   student_no  Points: ts
1   Sets    The purpose of...   Suppose we have...  40204123    80  2021-01-12 15:37:11
2   Seqs    sequences desc...   overall question...     40204123    75  2021-01-12 15:38:06
3   Prop L  logic desc    ...   overall quest...    40204123    30  2021-01-13 22:13:13
4   Pred L  pred desc 1   ...   predicase quest...  40204123    0
1   Sets    The purpose of...   Suppose we have...  40213894    90  2021-01-14 21:52:00
2   Seqs    sequences desc...   overall question...     40213894    95  2021-01-17 22:42:50
3   Prop L  logic desc    ...   overall quest...    40213894    0
4   Pred L  pred desc 1   ...   predicase quest...  40213894    100 2021-01-17 22:42:50

We can see that we have 0 points for NULLs as a result of the COALESCE function, but that now our missing records have "reappeared".

Solution 3: Redesign the schema:

If, say, we had a student who hadn't take any quizzes (and recalling my student days, this is eminently possible!), how would we deal with this scenario?
We can improve the schema (fiddle here).
Relations (tables) are entities (things) - my (particularly brilliant) synopsis of relational theory! :-). Now, a quiz is a "thing" which implies that it must correspond to a relation (i.e. table) in our database of relations. A student is a "thing" also - so, a student table is required.
The "tricky" bit is this - the relationship between the student and the quiz is also a "thing" and hence, deserves to be a table! Entities such as these are called Associative Entities and their corresponding tables are called associative tables - but much more frequently joining or linking tables (in fact, there are 17 names for them on the link.
New Schema:
So, my own recommendation is that you do the following:
CREATE TABLE student
(
  s_id INTEGER NOT NULL,
  s_name VARCHAR (20) NOT NULL,
  CONSTRAINT student_pk PRIMARY KEY (s_id)
);

CREATE TABLE quiz
(
  q_id         INTEGER       NOT NULL,
  q_title   VARCHAR  (50) NOT NULL,
  CONSTRAINT ql_pk PRIMARY KEY (q_id)
);

CREATE TABLE student_score
(
  ss_s_id  INTEGER   NOT NULL,
  ss_q_id INTEGER   NOT NULL,
  score   INTEGER   NOT NULL,
  ts    TIMESTAMP NOT NULL,

  CONSTRAINT sp_pk PRIMARY KEY (ss_s_id, ss_q_id),
  CONSTRAINT sp_s_no_fk FOREIGN KEY (ss_s_id)  REFERENCES student (s_id),
  CONSTRAINT sp_ql_id   FOREIGN KEY (ss_q_id) REFERENCES quiz (q_id)
);

This answer is becoming rather long, so I'll just give the final SQL  here (some intermediate steps are shown in the fiddle) :
SELECT
  q.q_id, q.q_title,
  s.s_id, s.s_name, COALESCE(ss.score, 0) AS score
FROM quiz q
CROSS JOIN student s
LEFT JOIN student_score ss
  ON ss.ss_s_id = s.s_id
  AND ss.ss_q_id = q.q_id
ORDER BY s.s_id, q.q_id;

Result (note the 4 0s for student 4!):
q_id    q_title s_id    s_name  score
1   Quiz 1  12345678    Student1_name   80
2   Quiz 2  12345678    Student1_name   25
3   Quiz 3  12345678    Student1_name   90
4   Quiz 4  12345678    Student1_name   90
1   Quiz 1  40204123    Student2_name   80
2   Quiz 2  40204123    Student2_name   75
3   Quiz 3  40204123    Student2_name   30
4   Quiz 4  40204123    Student2_name   0
1   Quiz 1  40213894    Student3_name   90
2   Quiz 2  40213894    Student3_name   95
3   Quiz 3  40213894    Student3_name   0
4   Quiz 4  40213894    Student3_name   100
1   Quiz 1  98765432    Student4_name   0
2   Quiz 2  98765432    Student4_name   0
3   Quiz 3  98765432    Student4_name   0
4   Quiz 4  98765432    Student4_name   0

Performance analysis:
Using MySQL 8's EXPLAIN ANALYZE functionality, we see that the working SQL using the old schema produces the following plan (see fiddle here):
EXPLAIN
-> Sort: t2.student_no, t2.id  (actual time=0.184..0.185 rows=8 loops=1)
    -> Stream results  (cost=32.42 rows=320) (actual time=0.133..0.170 rows=8 loops=1)
        -> Left hash join (sp2.level_id = lq2.id), (sp2.student_no = t2.student_no)  (cost=32.42 rows=320) (actual time=0.125..0.148 rows=8 loops=1)
            -> Nested loop inner join  (cost=5.85 rows=32) (actual time=0.082..0.100 rows=8 loops=1)
                -> Table scan on lq2  (cost=0.65 rows=4) (actual time=0.005..0.015 rows=4 loops=1)
                -> Index lookup on t2 using <auto_key2> (id=lq2.id)  (actual time=0.001..0.002 rows=2 loops=4)
                    -> Materialize  (cost=4.60 rows=8) (actual time=0.020..0.021 rows=2 loops=4)
                        -> Table scan on <temporary>  (actual time=0.000..0.001 rows=8 loops=1)
                            -> Temporary table with deduplication  (cost=4.60 rows=8) (actual time=0.062..0.063 rows=8 loops=1)
                                -> Inner hash join (no condition)  (cost=4.60 rows=8) (actual time=0.046..0.049 rows=24 loops=1)
                                    -> Table scan on t1  (cost=1.48 rows=4) (actual time=0.000..0.001 rows=4 loops=1)
                                        -> Materialize  (cost=0.65 rows=4) (actual time=0.021..0.022 rows=4 loops=1)
                                            -> Table scan on <temporary>  (actual time=0.000..0.001 rows=4 loops=1)
                                                -> Temporary table with deduplication  (cost=0.65 rows=4) (actual time=0.016..0.017 rows=4 loops=1)
                                                    -> Table scan on lq1  (cost=0.65 rows=4) (actual time=0.004..0.008 rows=4 loops=1)
                                    -> Hash
                                        -> Filter: (sp1.student_no in (40204123,40213894))  (cost=1.25 rows=2) (actual time=0.010..0.016 rows=6 loops=1)
                                            -> Table scan on sp1  (cost=1.25 rows=10) (actual time=0.005..0.014 rows=10 loops=1)
            -> Hash
                -> Table scan on sp2  (cost=0.16 rows=10) (actual time=0.015..0.026 rows=10 loops=1)

The same SQL using PostgreSQL's EXPLAIN (ANALYZE, BUFFERS, COSTS, TIMING) functionality shows a very complex plan (see bottom of this fiddle).
The fiddle for the SQL with the revised schema is following (see bottom of this):
EXPLAIN
-> Nested loop left join  (cost=2.05 rows=4) (actual time=0.018..0.031 rows=4 loops=1)
    -> Table scan on q  (cost=0.65 rows=4) (actual time=0.011..0.015 rows=4 loops=1)
    -> Single-row index lookup on ss using PRIMARY (ss_s_id=40204123, ss_q_id=q.q_id)  (cost=0.28 rows=1) (actual time=0.003..0.003 rows=1 loops=4)

and just checking the PostgreSQL one here:
QUERY PLAN
Hash Left Join  (cost=14.64..46.31 rows=540 width=188) (actual time=0.077..0.083 rows=4 loops=1)
  Hash Cond: ((s.s_id = ss.ss_s_id) AND (q.q_id = ss.ss_q_id))
  Buffers: shared hit=5
  ->  Nested Loop  (cost=0.15..28.97 rows=540 width=184) (actual time=0.032..0.035 rows=4 loops=1)
        Buffers: shared hit=3
        ->  Index Scan using student_pk on student s  (cost=0.15..8.17 rows=1 width=62) (actual time=0.020..0.021 rows=1 loops=1)
              Index Cond: (s_id = 40204123)
              Buffers: shared hit=2
        ->  Seq Scan on quiz q  (cost=0.00..15.40 rows=540 width=122) (actual time=0.008..0.009 rows=4 loops=1)
              Buffers: shared hit=1
  ->  Hash  (cost=14.37..14.37 rows=8 width=12) (actual time=0.027..0.027 rows=3 loops=1)
        Buckets: 1024  Batches: 1  Memory Usage: 9kB
        Buffers: shared hit=2
        ->  Bitmap Heap Scan on student_score ss  (cost=4.21..14.37 rows=8 width=12) (actual time=0.017..0.019 rows=3 loops=1)
              Recheck Cond: (ss_s_id = 40204123)
              Heap Blocks: exact=1
              Buffers: shared hit=2
              ->  Bitmap Index Scan on sp_pk  (cost=0.00..4.21 rows=8 width=0) (actual time=0.006..0.007 rows=3 loops=1)
                    Index Cond: (ss_s_id = 40204123)
                    Buffers: shared hit=1
Planning Time: 0.254 ms
Execution Time: 0.188 ms
22 rows

So, the motto appears to be that a well-normalised schema produces a) - the correct results, or at least the correct results more easily and is more performant! Good to know!


text:
Q: Saving Core Data using AlertView and immediately in Cell When I push a cell, an AlertView with Prompt is popping up. My problem: I want to show the entered text from the prompt in to the selected cell. (and in the meantime save the text to Core Data). Can anyone push me in the right direction ?

A: You need to do the save in a background thread, if you want it to happen at the same time as the alert is showing.
The easiest approach is using nested contexts, and just saving from the main context.
Wherever you are creating your managed object context, replace the alloc/init part with...
NSManagedObjectContext *parentMoc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
parentMoc.persistentStoreCoordinator = persistentStoreCoordinator;
self.managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
self.managedObjectContext.parentContext = parenetMoc;

Now, you have the same MOC you were using before, except it is a main queue MOC, with a parent context running in a background queue.
You will have to use a method to save both contexts though.  The second save, on the parent, happens in a background thread, so you do not have to wait.
- (void)saveData {
    NSError *error = nil;
    NSManagedObjectContext *moc = self.managedObjectContext;
    if ([moc save:&error]) {
        moc = moc.parentContext;
        [moc performBlock:^{
            NSError *error = nil;
            if (![moc save:&error]) {
                // Handle the actual save error
            }
        }];
    } else {
        // Handle the error of saving up into the parent context...
    }
}

Now, instead of calling [managedObjectContext save:&error] directly, replace it with a message of saveData, and the method will return almost immediately, and the actual save will happen in a background thread.
None of your other code in your app (except for the save calls) should have to change at all.
In your case, right before you throw up the alert, call save, and the save will happen while the alert is being displayed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Redis as service fails with error code 87 I have installed Redis-64 using the chocolately package.  When I try and install redis as a service on windows with command:
 redis-server.exe --service-install

I get the following error:
# HandleServiceCommands: system error caught. error code=1073, message = CreateService failed: unknown error

I have also tried just executing the exe on its own, but get another different error:
# Creating Server TCP listening socket *:6379: bind: No such file or directory

Has anyone else got this error before?

A: Go to redis path and then
1) C:\Program Files\Redis>redis.windows.conf it will open file
2) Change port to 16379(higher) then run
3) C:\Program    Files\Redis>redis-server.exe redis.windows.conf

A: I had the same error when running the exe. (No such file or directory)
It worked when using a higher port in redis.windows.conf:
port 16379

and then run
c:\Program Files\Redis>redis-server.exe redis.windows.conf

A: What is meant by run
cd to c:\Program Files\Redis

then:
run redis-server.exe redis.windows.conf on command prompt

A: Changing the port to higher has solved the error for me.
Change the port in two files
redis.windows-service.conf and redis.windows.conf
And then run
c:\Program Files\Redis>redis-server.exe redis.windows.conf

c:\Program Files\Redis>redis-server.exe redis.windows-service.conf

After run you can see below description

A: For me the default port was already in use. I checked this by:

*

*Pressing Windows + R

*Typing resmon.exe

*Going to Network > Listening Ports

There I saw that I already had a redis process running on port 6379, so I:

*

*Opened Task Manager

*Found redis-server.exe

*Right click > End task

You can also end the process by running redis-server --service-stop.
Then redis-server --service-start worked as expected, no need to change config files.


text:
Q: PHP read console output Ok, so here's the thing. I need to read the output (the one that you usually see in a linux console). My biggest problem is that I don't need to read the output of a linear execution, but something rather like wget http://ubuntu.com/jaunty.iso and show its ETA.
Also, the work-flow is the following:
S - webserver
C1 - computer1 in S's intranet
C2 - computer 2 in S's intranet
and so on.
User connects to S which connects to Cx then starts a wget, top or other console logging command (at user's request). User can see the "console log" from Cx while wget downloads the specified target.
Is this plausible? Can it be done without using a server/client software?
Thanks!

A: You'll want to use the php function proc_open for this -- you can specify an array of pipes (stdin, which would normally be attached to the keyboard if you were on the console, std out, and stderr, both normally would be printed to the display). You can then control the input/output folw of the given program
So as an example:
$pipes = array();
$pipe_descriptions = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("file", "/tmp/error-output.txt", "a") // stderr is a file to write to
);

$cmd = "wget $url";

$proc_handle = proc_open($cmd, $pipe_descriptions, $pipes);

if(is_resource($proc_handle))
{
   // Your process is running. You may now read it's output with fread($pipes[1]) and fread($pipes[2])
   // Send input to your program with fwrite($pipes[0])
   // remember to fclose() all pipes and fclose() the process when you're done!

A: Do you have some existing PHP code you're working on?


text:
Q: Make scrollbar appear on vertical menu when page resized Having trouble with something that should be really simple. Basically, I have right-hand vertical menu wherein my client wants to have a scrollbar included on it when the page is resized to a certain point.

                 // User clicks this to open the hamburger menu

 // The "open" class is appended with
                                               // jQuery when menu is clicked.

List item

List item

List item

List item

List item

And the jQuery I have is this (hunted it down on another website and had to figure out from their code which parts were relevant):
function ScrollMenuMobile(){
$('.mobile-navigation.open').css('height', $(window.height() + 'px'));
}

$(document).ready(ScrollMenuMobile);
$(document).resize(ScrollMenuMobile);

Can't seem to get it to work. The css attribute is never entered within .mobile-navigation.open and I get the error in Firebug:
ReferenceError: $ is not defined
$(document).ready(ScrollMenuMobile);

You can click on the hamburger menu and check it out here:
www.prometrika.com/newPMK
Have searched for hours and tried everything. Jsfiddles are great to point out what I'm doing wrong.

A: $('.mobile-navigation.open') is undefined because your div has 2 separate classes: mobile-navigation, and open. They are not the same.
Try selecting it via $('.mobile-navigation').


text:
Q: SQLite Math Problems ROUND(SUM(price)-(SUM(price*TAX/100.0)+SUM(purchaseprice)),2) as profit = i get 227.8 as Profit

When i calculate them by my self i get 227.81 as Profit.
ROUND(SUM(price)-(SUM(price*TAX/100.0)+SUM(purchaseprice)),2)  as profit...GROUP BY productname (how i calculate it one by one i get the sum of 227.81)

Does SQLite have Problems calculating and Rounding floating points? I have already tried to change the type to numeric, real .... Maybe i can do the Math differently any ideas?


text:
Q: How do I call an auxiliary base-class constructor from a derived-class auxiliary constructor in Scala? You can call an auxiliary constructor in the base class via the derived class primary constructor:
class Base(n:Int) {
    def this(n:Int, i:Int) = {
        this(n)
        println(i)
    }
}

class Derived(n:Int, i:Int) extends Base(n, i)

Is there a syntax for calling an auxiliary base-class constructor from an auxiliary derived-class constructor? This doesn't work:
class Derived2(n:Int) extends Base(n) {
    def this(n:Int, i:Int) = {
        super.this(n, i) // Can't do this
        println(i)
    }
}

In other languages, you can do this, but you must call the base-class constructor first, which is why I tried to do it here.
Note that I am looking for the syntax for the call rather than alternative ways to achieve the same result.

A: In Scala you have to go through the default constructor no matter what, which forces you to choose one super construction in your class instantiation. This is basically what you're trying to do in terms of java:
public class Derived2 extends Base {
    public Derived2(int n, int i) {
        super(n, i);
    }
    public Derived2(int n) {
        super(n);
    }
}

Since in Scala you have to go through the default constructor this is what's happening:
public class Derived2 extends Base {
    public Derived2(int n, int i) {
        this(n);
        super(n, i); //does not compile
    }
    public Derived2(int n) {
        super(n);
    }
}

So, as is normal in Java, you can only call super or this as the first line of your constructor implementation. Since Scala forces the call to the default constructor, there's no way around only using one implementation of the Base constructor.
There is no work around, as this isn't really dogmatic Scala. I would suggest changing your design here. Inheritance in Scala is usually done through traits, not classes or abstract classes.
Here's what an alternative might look like using a trait:
  trait Base2 {
    val a:Int
  }

  class Derived3(n: Int) extends Base2 {

    val a = n

    def this(n: Int, i: Int) = {
      this(n)
    }
  }


text:
Q: How does PMF change given that you know p? For example this question:
A biased coin lands heads with probability $\frac{2}{3}$. The coin is tossed three times.
a) Given that there was at least one head in the three tosses, what is the probability that there were at least two heads?
Normally without the There was at least one head in the three tosses the PMF using binomial distribution would be:
$$
\begin{equation*}
p(0) = \binom{3}{0}*\left(\frac{2}{3}\right)^0*\left(\frac{1}{3}\right)^3\\
p(1) = \binom{3}{1}*\left(\frac{2}{3}\right)^1*\left(\frac{1}{3}\right)^2\\
p(2) = \binom{3}{2}*\left(\frac{2}{3}\right)^2*\left(\frac{1}{3}\right)^1\\
p(3) = \binom{3}{3}*\left(\frac{2}{3}\right)^3*\left(\frac{1}{3}\right)^0
\end{equation*}
$$
However since we know there is at least one head, the $p(0)$ shouldn't exist anymore, right?. But the PMF should add up to one. What happens to $p(0)$? Does it get distributed evenly along the rest of the $p(x)$?

A: We renormalize by taking the only possible outcomes. So the renormalization factor in your (good) notation is
$$\frac{1}{p(1) + p(2) + p(3)}$$
Hence the probability you want is
$$\frac{p(2) + p(3)}{p(1) + p(2) + p(3)}$$


text:
Q: Usage of buttons in Magento Hi Everyone I need to have see more button under my testimonial section so that on clicking it should redirect to the page where all the testimonials located.
Please see my images I want button in the place of see more.

A: Put this code after your testimonials content
  and in the setLocation give path of your required page.
 <button style="width: 98px; overflow: hidden;" type="button" title="SEE MORE" class="button btn-cart"
             onclick="setLocation('#')">SEE MORE</button>


text:
Q: Node crypto pbkdf2 yields different keys on 32bit and 64bit machines The following snippet seems to yield different answers on 32 bit and 64 bit machines.
var buf = new Buffer('ojHkXkabdV7X6xcDNKJgrg==', 'base64');
console.log(crypto.pbkdf2Sync('secret', buf.toString('binary'), 10000, 14, 'sha256').toString('base64'));

64bit machine is on Node v0.12.4.
32bit machine is on Node v0.10.12.
Is this even possible ?

A: I moved node from v0.12.4 to v0.10.12 on the 64 bIt machine and the keys match when the snippet is run on both machines.
I also found the implementation that I really needed resides in v0.12.4 therefore my solution to this issue is to upgrade the 32 bit machine to v0.12.4.
Sorry folks ! This is not an architecture problem.


text:
Q: Kotlin invoke constructor using reflection For a simple machine language reader, I have a number of classes AaaInstruction, BbbInstruction, CccInstruction, etc. which are invoked as aaaInstruction(v1, v2, v3).  The idea is that the input is given in the form:
aaa v1 v2 v3

bbb v1 v2 v3

ccc v1 v2 v3

In the main class I use the following code:
var input = Scanner(System.`in`)

val instcode = input.next()

val cname: String = instcode.capitalize()+"Instruction"

How can I then invoke cname(v1,v2,v3)?

A: There is no built-in way to enumerate types in Kotlin, there isn't a Kotlin analogue to Java's Class.forName() method, and I do not think anyone has made a Reflections-style library specifically for Kotlin yet, which means you would need to use Java reflection to get the Kotlin classes, and that's starting to sound pretty terrible. It's not great in the first place in my opinion - having an external input map to a class name sounds like a security nightmare.
Given your use case, there are a couple of approaches you could use.
First, you could implement a proper factory (a big switch statement would do, a map of constructors would be slightly more concise) instead of trying to build the name of the constructor you want from the opcode. I know that's probably what you're trying to avoid, but in my experience the problems you will run into avoiding it are bigger than the ones you are avoiding.
Second, if you are dead-set on using reflection somewhere, you can create all the opcode implementations as nested classes of a single meta-class, which you can then walk through using the nestedClasses property of KClass, and find the one whose simpleName property matches the opcode you're looking for. This is pretty ugly, though. You'll also need to include Kotlin's reflection runtime JAR, which is not included by default; see http://kotlinlang.org/docs/reference/reflection.html.


text:
Q: Empty values retrieved with values_list I have this list of countries retrieved from database based on one column (country_name) of the country table:
list_countries = Country.objects.values_list('country_name', flat=True).distinct()

result is like this:
[u'', u'China', u'France', u'Germany', ...]

Some of values in database are empty. How do I remove the empty retrieved so that I get the result retrieved just with country_name not null (cf country_name != '' ) ?

A: You can use Q object,
from django.db.models import Q
list_countries = Country.objects.filter(~Q(country_name='')).values_list('country_name', flat=True).distinct()

A: You could use a list comprehension to remove the zero length entries.
list_countries = [country for country in list_countries if len(country) > 0]

A: I have agree with Adem's answer except for one change.
from django.db.models import Q
list_countries = Country.objects.filter(~Q(country_name='')).distinct().values_list('country_name', flat=True)

This will be slightly better than Adem's answer.


text:
Q: How to do nothing in an SQL case statement? I need to update a column conditionally and in some cases not update it at all. this is the best way i can figure to do that but it seems like it may be inefficient in the ELSE as it's still updating the column with the current value of the column. Is there a better way in which the ELSE can just "do nothing" at all.
UPDATE mytable
SET col1 = CASE WHEN (col1 = 20) THEN 10 ELSE col1 END

A: Apply a WHERE:
UPDATE mytable
SET col1 = 10
WHERE col1 = 20

However, if your update is more complex and you actually need multiple CASE you either have to bite the bullet and omit the WHERE or you have to add all columns in the WHERE which you want to update:
UPDATE mytable
SET col1 = CASE WHEN (col1 = 20) THEN 10 ELSE col1 END,
SET col2 = CASE WHEN (col2 = 40) THEN 20 ELSE col2 END,
SET col3 = CASE WHEN (col3 = 80) THEN 30 ELSE col3 END
WHERE col1 = 20 OR col2 = 40 OR col3 = 80

This might still "update" columns unnecessarily(to their old values) but not complete rows.


text:
Q: How do I set the date format for a Label Widget? I don't understand how to put the pieces together.
The script:

*

*Gets a data range from a google spreadsheet.

*Filters the data into a new array

*Adds data to a widget label.

Dates are displayed as 'Tue Oct 06 1942 00:00:00 GMT-0400 (EDT)' and i want 'Oct 6, 1942.'
How do I use:
Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd'T'HH:mm:ss'Z'");

with
grid.setWidget(i +1, 2, ui.createLabel(mapData[i][3]));

A: Looks like you've answered your question yourself
Use
var dt = Utilities.formatDate(new Date(), "GMT", "MM dd, yyyy");
grid.setWidget(i+1, 2, ui.createLabel(dt));


text:
Q: Hierarchical POJOs not being properly serialized to JSON by RESTEasy/Jackson I have two POJOs defined as follows,
public class VertexDefinition {
    private final String name;
    private final Vertex vertex;

    public VertexDefinition(String name, Vertex vertex) {
        this.name = name;
        this.vertex = vertex;
    }

    @JsonProperty("name")
    public String getName() {
        return name;
    }

    @JsonProperty("properties")
    public Iterable<PropertyDefinition> getProperties() {
        if(vertex == null) {
            return Collections.emptySet();
        }
        return Iterables.transform(vertex.getPropertyKeys(), new Function<String, PropertyDefinition>() {
            @Nullable @Override public PropertyDefinition apply(@Nullable String s)  {
                return new PropertyDefinition(vertex, s);
            }
        });
    }

    @JsonProperty("propertyKeys")
    public Iterable<String> getPropertyKeys() {
        if (vertex == null) {
            return Collections.emptySet();
        }
        return vertex.getPropertyKeys();
    }

}

public class PropertyDefinition {

    private final Vertex vertex;
    private final String propertyName;

    public PropertyDefinition(Vertex vertex, String propertyName) {
        this.vertex = vertex;
        this.propertyName = propertyName;
    }

    @JsonProperty("name")
    public String getName() {
        return propertyName;
    }

    @JsonProperty("type")
    public String getType() {
        final Object property = vertex.getProperty(propertyName);

        if (property != null) {
            return property.getClass().getTypeName();
        }

        return "(unknown)";
    }
}

My Rest method looks as follows,
public Iterable<VertexDefinition> getSchema() {
    .....
}

When I make a request I get a json response as follows,
 [
   {
       "name" : "Foo",
       "properties" : [],
       "propertyKeys" : [
          "a",
          "b",
          "c"
       ]
   },
   {
       "name" : "Bar",
       "properties" : [],
       "propertyKeys" : [
          "a",
          "b",
          "c"
       ]
   }
]

In short I get an empty array returned for properties while the propertyKeys is filled in.
What am I doing wrong?

A: I don't think deserialization into an iterable works as you've tried. Could you try something like this instead in your getProperties method?
List<PropertyDefinition> propertyDefinitions = Arrays.asList(mapper.readValue(json, PropertyDefinition[].class))


text:
Q: PowerShell:Download a file from URL with 257 chars and 404 returned I tried to download a file from a url which has 257 characters,but the following error is returned:

Exception calling "DownloadFile" with "2" argument(s): "The remote server returned an error: (404) Not Found."

When I copy the URL to firefox or IE, I can download that file. then I tried to download a file from the same website but whose URL is short, I can download it successfully with Powershell.
Does anybody find the similar issue before? Could you pls share how to solve it?
Thanks a lot.

A: I recently faced the exact same issue and this is how I resolved it. Thought it would help someone who comes to this thread later.
In my case, the reason for the exception was incorrect URL due to a parameter I added to the URL. Something like this:
https://yourserverurl/archive-$OS.zip
I was using a parameter in the URL for the Operating System. And I was getting the $OS argument wrong.
Therefore, the two reasons I can think of when this error occurs:

*

*The file cannot be downloaded without authentication. But that would probably throw a 401.

*The URL is incorrect. Maybe due to some parametrization as in my case.

Hope this helps!


text:
Q: BeautifulSoup find_all give me the value of the last element only Hello hope you're all doing well I wrote the following program to extract the data from it's source but it gives me the last value and I don't know why
users_list = soup.find_all("li", class_= "ContentGrid-gridItem-2Ad e2e-ContentGriditem")
for user in users_list:

name = user.find("span", class_ = "e2e-UserSummary-displayName")
profile_link = user.find('a', class_='UserSummary-ownerLink-1cJ')

the variable profile_link gives me this output

i want to make it return only the link
another thing also I built other variables to return values but it keep returning the same values because it's having the same class and they all in h4 here's the code and it's returning the value of the first object which is appreciations 189.9k
appreciations = users.find("h4", class_= "UserSummaryStats-statAmount-13R").text
followers = users.find("h4", class_= "UserSummaryStats-statAmount-13R").text
project_views = users.find("h4", class_= "UserSummaryStats-statAmount-13R").text

A: To extract only href attribute of the tag you can use tag['<attr>']. For example:
profile_link = user.find('a', class_='UserSummary-ownerLink-1cJ')['href']

For the second case, just use .find_all(<tag_name>, <params>) method which returns all the tags with defined parameters as a list:
user_data = users.find_all("h4", class_= "UserSummaryStats-statAmount-13R")
for entry in user_data:
    # do something with each entry


text:
Q: How to obtain MANAGE_EXTERNAL_STORAGE permission I'm trying to get the MANAGE_EXTERNAL_STORAGE permission on my Android 10 (API 29) device.
https://developer.android.com/training/data-storage/manage-all-files
Manifest:
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

MainActivity:
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
startActivity(intent);

The result is:
No Activity found to handle Intent { act=android.settings.MANAGE_APP_ALL_FILES_ACCESS_PERMISSION }

Okay, this behaviour is possible. The doc says:
In some cases, a matching Activity may not exist, so ensure you safeguard against this.

But how can I obtain that permission?

A: Android 10 doesn't require "android.permission.MANAGE_EXTERNAL_STORAGE",   android:requestLegacyExternalStorage="true" under application tag in manifest will work.
For android 11, try this
if (Environment.isExternalStorageManager()) {
    //todo when permission is granted
} else {
    //request for the permission
    Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
    Uri uri = Uri.fromParts("package", getPackageName(), null);
    intent.setData(uri);
    startActivity(intent);
}


text:
Q: Using a ternary operator to set a variable I am trying to use a ternary operator to check if the value of an XML element is null. If it is then I want the variable to be one thing. If not then I would like it to return the value of element. This is what I have so far.
var rating = data.getElementsByTagName("overall_average")[0].childeNodes[0].length > 0 ? data.getElementsByTagName("overall_average")[0].childeNodes[0].nodeValue : "It is empty";

A: The shortest way:
var rating = (data.getElementsByTagName('overall_average')[0].childNodes[0] || {}).nodeValue || 'It is empty';

A: Your ternary operation look fine to me. One thing I would suggest (for readability and brevity) is to define your overall_average object as a variable and reference it after.
var overall_average = data.getElementsByTagName("overall_average")[0].childeNodes[0];
var rating = overall_average.length > 0 ? overall_average.nodeValue : "It is empty";

Good luck!

A: Here:
var node = data.getElementsByTagName( 'overall_average' )[0].childNodes[0];
var rating = node ? node.nodeValue : 'It is empty';

Note that this code throws (an error) in case there is not a single "overall_average" element in data, so you might want to guard against that case if necessary...


text:
Q: SoftKeyboard invalidateKey(Key key) not working as expected i am trying to change a single key label and its miniKeybord(popupKeyboard) resource id its changing label but when i longPress the key its not changing miniKeyboard resource id
i have toggle button in candidate view from which i want to change the "." to "-" key its changing label but not ResourceID for longPress
this is my toggle method for changing key label and ResourceID
 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    this.editor = this.mSharedPreferences.edit();
    switch (buttonView.getId()) {
        case R.id.easyUrduToggleBtn:
            if (isChecked) {
                this.editor.putBoolean("easy_urdu", true);
                this.mEasyUrdu = shouldChangePunctuationKey = true;
                SoftKeyboard keyboard = (SoftKeyboard) mKeyboardSwitcher.getInputView().getKeyboard();
                keyboard.mPunctuationKey.label = "۔";
                keyboard.mPunctuationKey.codes = new int[]{keyboard.mPunctuationKey.label.charAt(0)};
                keyboard.mPunctuationKey.popupResId = R.xml.popup_punctuation_ur;
                mKeyboardSwitcher.getInputView().invalidateKey(keyboard.mPunctuationKey);

            } else {
                this.editor.putBoolean("easy_urdu", false);
                this.mEasyUrdu = shouldChangePunctuationKey = false;
                SoftKeyboard keyboard = (SoftKeyboard) mKeyboardSwitcher.getInputView().getKeyboard();
                keyboard.mPunctuationKey.label = ".";
                keyboard.mPunctuationKey.codes = new int[]{keyboard.mPunctuationKey.label.charAt(0)};
                keyboard.mPunctuationKey.popupResId = R.xml.popup_punctuation;
                mKeyboardSwitcher.getInputView().invalidateKey(keyboard.mPunctuationKey);
            }
            this.editor.apply();
            return;
        default:
            return;
    }
}

and this is my invalidateKey method in KeyboardBaseView
 public void invalidateKey(Key key) {
    if (key == null)
        return;
    mInvalidatedKey = key;
    // TODO we should clean up this and record key's region to use in onBufferDraw.
    mDirtyRect.union(key.x + getPaddingLeft(), key.y + getPaddingTop(),
            key.x + key.width + getPaddingLeft(), key.y + key.height + getPaddingTop());
    onBufferDraw();
    invalidate(key.x + getPaddingLeft(), key.y + getPaddingTop(),
            key.x + key.width + getPaddingLeft(), key.y + key.height + getPaddingTop());
}

its only changing its label by redrawing it but not miniKeyboardResource id when i long press its showing old miniKeyboard but when i click on next EditText it changing the resource ID because i have check in class SoftKeyboard extends Keyboard in this method
 @Override
protected Key createKeyFromXml(Resources res, Row parent, int x, int y,
                               XmlResourceParser parser) {
    Key key = new LatinKey(res, parent, x, y, parser);
    switch (key.getCode()) {
        case 46:
            mPunctuationKey=key;
            if (LatinIME.shouldChangePunctuationKey) {
                key.label = "۔";
                key.codes = new int[]{key.label.charAt(0)};
                key.popupResId=R.xml.popup_punctuation_ur;
                mPunctuationKey=key;
                Log.e("akjskjas",1+"");

            } else {
                key.label = ".";
                key.codes = new int[]{key.label.charAt(0)};
                key.popupResId=R.xml.popup_punctuation;
                Log.e("akjskjas",2+"");

            }
            break;

but from toggle button its not working its only changes its label not miniKeyboard key.popupResId please help me what is the issue


text:
Q: External login using Google for PHPBB 3.1 I currently allow users to login into my website using their PHPBB credentials. I use the method described here:
https://wiki.phpbb.com/Practical.External_login
However, I would like to upgrade to PHPBB 3.1 and also allow logins by placing a "Login with Google", "Login with Facebook" buttons on the form as an alternative.
I have the "Login with Google" working on the forum itself using the new PHPBB 3.1 feature, but I have no idea how to implement that as an external login on my website.
The biggest issue I run into is that if the login is successful using "Google", my user is redirected to the forum. However, I would like the user to be redirected to a specific page on my website.

A: I figured out how to do this:
Create a "Login with Google" button for example and link it to:
http://www.example.com/forum/loginoauth.php?mode=login&login=external&oauth_service=google
Here is my loginoauth.php file:
<?php

// phpBB inclusion protection
define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
require($phpbb_root_path . 'common.' . $phpEx);

// Start session management
$user->session_begin();
$auth->acl($user->data);

if ($user->data['is_registered'])
{
    redirect('http://www.example.com/profile');
}
else
{
    //$autologin    = $request->is_set_post('autologin');
    $admin      = ($admin) ? 1 : 0;

    // Check if the supplied username is equal to the one stored within the database if re-authenticating
    if ($admin && utf8_clean_string($username) != utf8_clean_string($user->data['username']))
    {
        // We log the attempt to use a different username...
        add_log('admin', 'LOG_ADMIN_AUTH_FAIL');
        trigger_error('NO_AUTH_ADMIN_USER_DIFFER');
    }

    // If authentication is successful we redirect user to previous page
    // $result = $auth->login($username, $password, $autologin, $viewonline, $admin);
    $result = $auth->login('','');

    // The result parameter is always an array, holding the relevant information...
    if ($result['status'] == LOGIN_SUCCESS)
    {
        redirect('http://www.example.com/profile');
    }
}
?>


text:
Q: How does the internuclear repulsion vary in Hydrogenic atom collision? Hydrogen fusion requires two hydrogen nuclei to get close enough (typically a few fm) to fuse. Much of the problem of creating a fusion reactor is overcoming the Coulomb repulsion between a pair of nuclei - the millions of degrees for Maxwellian distributions, the Bremstrahlung losses for inertial confinement.
If we could align the paths of two neutral Hydrogen atoms (of whichever isotopes), what would the repulsion look like between them as they approach collision? Obviously at long range there is negligable force as both are neutral. But as they approach each other, what happens to the electron distribution?
Intuitively, I expect a bonding cloud to form between the nuclei, and antibonding clouds beyond them. This would presumably attract at first until reaching the usual Hydrogen covalent bond length, after which the internuclear repulsion would increasingly dominate.
But how does that compare to bare ionic collision? How much lower is the potential barrier?
Obviously if it was significantly lower and we could somehow engineer the collision to achieve fusion, the cross section would be larger than ionic fusion, but how much?
Or would the barrier be just as high over the final few femtometers?

A: Your last sentence is exactly right: the energy cost for fusion is almost all in those last few femtometers, at which electronic effects are negligible. Although there is in principle a difference between colliding neutral atoms and nuclei, at the energies required for fusion the effect is tiny.
The energy differences associated with the presence, absence, arrangement, etc., of electrons are of order a few to a few tens of electron volts. One way to see this is to note that the size scale of the electron's wavefunction is of order the Bohr radius $a_0$, so the energy levels are of order $e^2/(4\pi\epsilon_0 a_0)$. But to get fusion to happen, as you say, you have to get the two protons to get within a fermi or so of each other. This length scale is something like $10^4$ to $10^5$ times smaller, so it involves energies that are larger by about the same factor -- MeV rather than eV.


text:
Q: Does the AVD Ram effects the laptop ram? If I give the AVD emulator an amount of ram, does it affect my laptop?
because as default the AVD gets 2GB of ram and I would like to increase it for a better performance.
any advice about that?


text:
Q: cakephp 3.x datetime field comparison in query not returning correct result Trying to get all the records with which has been created 24 hr or prior. Here 'created' is a datatime field. I've three records in DB which must satisfy this condition, but returning 0 records.
$my_table_tbl = TableRegistry::get('my_table');
$records = $my_table_tbl
    ->find()
    ->where([
        'created <' => '(NOW() - INTERVAL 1 DAY)',
        'status' => 'pending'
    ])
    ->toArray();

A: CakePHP will always treat the right side of a clause as a variable binding. That means (NOW() - INTERVAL 1 DAY) is interpreted as a string value.
You can check what SQL is generated by converting the query to a string.
$query = $my_table_tbl->find()
              ->where([
                 'created <' => '(NOW() - INTERVAL 1 DAY)',
                 'status' => 'pending'
              ]);
dd((string)$query);

When you output the SQL above it will show created < :c0 instead of your expression.
Use a query object to create a custom expressions.
$q = $my_table_tbl->query();
$query = $my_table_tbl
    ->find()
    ->where([
        'created <' => $q->newExp('(NOW() - INTERVAL 1 DAY)'),
        'status' => 'pending'
    ]);
dd((string)$query);

When you output the SQL above it will show created < (NOW() - INTERVAL 1 DAY) as expected. This is because CakePHP checks if the values on the right hand are an expression object.


text:
Q: QT detect when a given date time is under day light saving or not We have an application that is failing because of DST, we use EST or New york time as our reference, I want to know whethere a given DateTime (QDateTime) is under DST or not, say if I pass Nov 2, 2021 i want to know if that date is under DST (Which it is) or not so we can perform our adjustment.
Is there a way programatically in QT to detect it? or maybe thru standard library time.h?


text:
Q: C++11 shared_ptr and pthread I have a library with APIs using std::shared_ptr as arguments.
I would like to use these APIs together with pthreads.
What I'm doing is: getting a raw pointer from the shared_ptr, in order to pass it to the pthread.
Create a new shared_ptr from the raw one and call my API from another thread.
However I get a double free or corruption error when converting the raw pointer back to a shared one.
This is my code
#include <memory>
#include <iostream>
#include <thread>
#include <pthread.h>

void* print_task(void* ptr)
{
    int* val_raw = static_cast<int*>(ptr);
    std::shared_ptr<int> val(val_raw);

    // CALL MY API WHICH TAKES A SHARED_PTR AS ARGUMENT
    std::cout<<"thread job done \n";
}

int main(int argc, char ** argv)
{

   pthread_t thread;

   std::shared_ptr<int> val = std::make_shared<int>(10);
   pthread_create(&thread, nullptr, &print_task, static_cast<void *>(val.get()));

   std::this_thread::sleep_for(std::chrono::seconds(5));

   return 0;
}

I guess that I'm doing something wrong with all the conversions from shared to raw pointer, because the same code using std::threads (where I can pass directly a shared_ptr) works.
However I need to set thread priorities, thus I'm trying to do this with pthreads.
Do you know how to change my code in order to be able to pass a shared pointer and use it inside a pthread?

A: As mentioned in the comments already, the problem is passing a shared pointer through a raw void pointer, so I'll ignore the threading part for now:
// this is what we have and what we want to pass to the given function
shared_ptr<some_type> sptr;

// function to somehow pass the shared pointer to
void function(void* ptr);

// As always, when passing anything that doesn't fit into
// the raw pointer, we need to do dynamic allocation:
void* arg = new shared_ptr<some_type>(sptr);

// we can now pass this to the function as intended:
function(arg);

// Note that we give up ownership of the dynamically allocated
// shared pointer instance. Hence, the called function must
// release that object again (it takes ownership). The function
// therefore starts like this:
void function(void* ptr)
{
    // convert the typeless pointer to a typed pointer again
    shared_ptr<some_type>* psptr = static_cast<shared_ptr<some_type>*>(ptr);
    // move the content to a new, local instance
    shared_ptr<some_type> sptr = *psptr;
    // release the dynamically allocated shared pointer again
    delete psptr;
    /// ... code using sptr here ...
}

Now, while this is guaranteed to work, under some circumstances this may not be an optimal solution:

*

*Firstly, the ups and downs of the reference counter don't come for free, especially since that is done in a thread-safe, atomic way. Copying the shared pointer inside the function just to then delete the copied pointer can be avoided. Just create as empty instance and swap() it with the pointer to copy. Assuming swap() is specialized, which is a safe bet because it's an obvious optimization, that then boils down to swapping two raw pointers. This swap doesn't have to be thread-safe and is therefore much faster.

*Secondly, dynamic allocations are expensive. You could avoid this and the manual release by passing the address of the original object to the function, but then you would have to guarantee that the object is not touched while the function is still executing. Especially with threads, that requires taking extra care.

A: I think this is a tricky little conundrum to be honest. The problem you are having is that by passing the raw pointer to your thread function you end up with two independant shared pointers managing the same object instead of two connected shared pointers sharing ownership.
Consequently both shared pointers try to delete it.
You also have a nasty lifetime problem to avoid if you pass a pointer to the shared pointer itself because you can not guarantee the shared pointer will not go out of scope before the new thread has copied it.
I get round that by passing a second dynamically allocated std::shared_ptr created from the original std::shared_ptr which guarantees the shared pointer's control block will live until the new thread tries to copy it.
#include <memory>
#include <iostream>
#include <thread>
#include <pthread.h>

void* print_task(void* ptr)
{
    // obtain the shared pointer from the dynamically created one guarantees
    // we will bee accessing a living control block preventing an
    // end-of-lifetime catastrophe
    std::shared_ptr<int> val = *static_cast<std::shared_ptr<int>*>(ptr);

    // DON'T FORGET TO DELETE THIS!!!
    // We had to allocate this dynamically to guarantee it lived until after
    // it was used.
    delete static_cast<std::shared_ptr<int>*>(ptr);

    // CALL MY API WHICH TAKES A SHARED_PTR AS ARGUMENT
    std::cout << "thread job done \n";

    return nullptr;
}

int main()
{
    pthread_t thread;

    // create the shared resource. This MAY go out of scope
    // before the new thread copies it (however unlikely you
    // think that is).
    std::shared_ptr<int> val = std::make_shared<int>(10);

    // So instead of sending the shared pointer we create a NEW std::shared_ptr
    // which will keep the shared pointer's control block alive even if the original
    // shared pointer goes out of scope.
    pthread_create(&thread, nullptr, &print_task,
        static_cast<void*>(new std::shared_ptr<int>(val)));

    // Do other time consuming thread stuff here.
    std::this_thread::sleep_for(std::chrono::seconds(2));

    // Tidy up.
    void* ret = nullptr;
    pthread_join(thread, &ret);

    return 0;
}

Of course you now have a new/delete pair here but you still gain in passing the shared ownership round between threads.
I suppose you can even get rid of that delete by adopting the passed in raw pointer by a temporary std::unique_ptr.
void* print_task(void* ptr)
{
    // obtain the shared pointer from the dynamically created one guarantees
    // we will bee accessing a living control block preventing an
    // end-of-lifetime catastrophe
    std::shared_ptr<int> val = *std::unique_ptr<std::shared_ptr<int>>(static_cast<std::shared_ptr<int>*>(ptr));

    // CALL MY API WHICH TAKES A SHARED_PTR AS ARGUMENT
    std::cout << "thread job done \n";

    return nullptr;
}


text:
Q: banner ads algorithm I am developing a banner ads system. Each banner will be stored in the db. Each banner will have a wight(int number). How can I transform that in percentage efficiently?
For ex:
banner_1 70
banner_2 90
banner_3 150
and I want to have banner 1 displayed 22%
second 29%
third 48%

A: If the weights are w[1], w[2], ..., w[n], then the percentage p[i] for the i'th banner ad be:
p[i] = w[i] / sum(w)

That is, the weight of the given ad, divided by the total sum of the weights. Your database system should be able to calculate that fairly easily.
If you have relatively few ads, and the ads get many more views than updates, it may be worth caching this p[i] for each ad, and then recalculating it whenever you add, remove or modify the weight of an ad.

A: This is called (surprise) "weighted random numbers". The top answer to this question should help you out.

A: Assuming your using a SQL database with the weights stored, you can return the total weight and use it for calcuations:
SELECT BannerId, BannerUrl, BannerWeight, SUM(BannerWeight) as TotalWeight FROM Banners;

Then use something like this to find a value:
public int GetRandomRow(Row[] rows)
{
    int TotalWeight = 3;
    int rnd = Random(rows[0].TotalWeight);
    for (int row=0; row < rows.Count; row++)
    {
        if (rnd < rows[row])
            return row;
    }
}

A: Banner1 = (70 / (70 + 90 + 150))  * 100 s
Banner2 = (90 / (70 + 90 + 150))  * 100 s
Banner3 = (150 / (70 + 90 + 150)) * 100 s

Yeah, it a simple weighted average logic.

A: If you just need weight to percentage conversion, that's really easy: you need to sum all the weights and then for each weight you divide it by sum and multiply by 100. It's O(n).

A: Fist off, your percentages add up to 99, so I'm going to guess that you rounded off some decimals.
To find the percentage of banner x you must sum up all the weights (to find 100 percent), the solve this equation: float percent = weight_x / sum of weights


text:
Q: Why can get_key() be used even if it is not called explicitly? I am coding a poker game along with a github file. This is the part of the code. As you can see, I have the get_key()function which I think is supposed to return the keys of the selected card. But in the second to last line of code "player.arrange(get_key)", it does not call the function. But the the code still works perfectly, so I wonder why is that? What is passed into the arrange method in class Player? Thank you.
class Player(object):

    def __init__(self, name):
        self._name = name
        self._cards_on_hands = []

    @property
    def name(self):
        return self._name
    @property
    def cards_on_hands(self):
        return self._cards_on_hands

    def get(self, card):
        self._cards_on_hands.append(card)

    def arrange(self, card_key):
        self._cards_on_hands.sort(key=card_key)

    def get_key(card):
        return (card.suite, card.face)
    def main():
    p = Poker()
    p.shuffle()
    players = [Player('Eva'), Player('Dude'), Player('Peta'), Player('Bruh')]
    for _ in range(13):
        for player in players:
            player.get(p.next)

    for player in players:
        print(player.name + ' : ', end=' ')
        player.arrange(get_key)
        print(player.cards_on_hands)

A: get_key is a function. Not the result of a function call but function. In your case this function is used to sort cards. key parameter of function sort accepts functions so that is why this code works fine.
https://docs.python.org/3/howto/sorting.html#key-functions

A: you are passing get_key instead of get_key():
player.arrange(get_key) instead of player.arrange(get_key(your_card_parameter))
This then gets passed to sort(key=card_key) which also accepts functions as keys. I wouldn't say it works. This is a bug waiting to happen.

The takeaway from this is you can pass functions as arguments!
You would be able to avoid this if you used type hints (if you are using Python >= 3.5 [no reason not to]).
For example:
from typing import Tuple
card_key_t: type = Tuple[int, int] # I don't know what it should really be as you did not show `card.suite` and `card.face`.

def get_key(card) -> card_key_t:
    return (card.suite, card.face)

def arrange(self, card_key: card_key_t):
    self._cards_on_hands.sort(key=card_key)

Pycharm would show a warning if you passed a Callable (a function) instead of an int.

Response to comment:

I am a bit confused because even in the arrange function I did not see
card_key() being explicitly called

@AD11011 player.arrange(get_key) passes the function itself to arrange. In arrange it is called card_key:  self._cards_on_hands.sort(key=card_key) which then gets passed to the built in list.sort: sort(key=card_key). So we see that list's sort gets called with key=get_key.
See list.sort documentation:

key specifies a function of one argument that is used to extract a
comparison key from each list element

It gets called inside sort.
It is hard to know what exactly happens there without knowing what is (card.suite, card.face)


text:
Q: Square bracket [] operator overloading c++ I have a project that wants me to make a BigNum class in c++ (university project)
and it said to overload operator bracket for get and set
but the problem is if the set was invalid we should throw an exception the invalid is like
BigNum a;
a[i]=11;//it is invalid because its >9

in searching I  found out how to make the set work
C++ : Overload bracket operators [] to get and set
but I didn't find out how to manage setting operation in c# you easily can manage the set value what is the equivalent of it in c++
to make it clear in C# we can say
public int this[int key]
{
    set
    {
        if(value<0||value>9)throw new Exception();
        SetValue(key,value);
    }
}

A: New Answer
I have to rewrite my answer, my old answer is a disaster.
The check should happen during the assignment, when the right hand side (11) is available. So the operator which you need to overload is operator=. For overloading operator=, at least one of its operands must be an user defined type. In this case, the only choice is the left hand side.
The left hand side we have here is the expression a[i]. The type of this expression, a.k.a the return type of operator[], must be an user defined type, say BigNumberElement. Then we can declare an operator= for BigNumberElement and do the range check inside the body of operator=.
class BigNum {
public:
  class BigNumberElement {
  public:
    BigNumberElement &operator=(int rhs) {
      // TODO : range check
      val_ = rhs;
      return *this;
    }

  private:
    int val_ = 0;
  };

  BigNumberElement &operator[](size_t index) {
    return element_[index];
  }

  BigNumberElement element_[10];
};

OLD answer
You can define a wapper, say NumWapper, which wraps a reference of BigNum's element. The operator= of BigNum returns the wrapper by value.
a[i]=11;

is then something like NumWrapper x(...); x = 11. Now you can do those checks in the operator= of NumWrapper.

class BigNum {
 public:
  NumWrapper operator[](size_t index) {
    return NumWrapper(array_[index]);
  }

  int operator[](size_t index) const {
    return array_[index];
  }
};

In the NumWrapper, overload some operators, such as:
class NumWrapper {
 public:
  NumWrapper(int &x) : ref_(x) {}
  NumWrapper(const NumWrapper &other) : ref_(other.ref_) {}

  NumWrapper &operator=(const NumWrapper &other);
  int operator=(int x);
  operator int();

 private:
  int &ref_;
};

You can also declare the NumWrapper's copy and move constructor as private, and make BigNum his friend, for preventing user code from copying your wrapper. Such code auto x = a[i] will not compile if you do so, while user code can still copy the wrapped value by auto x = static_cast<T>(a[i]) (kind of verbose though).
auto &x = a[i]; // not compiling
const auto &x = a[i]; // dangerous anyway, can't prevent.

Seems we are good.

These is also another approach: store the elements as a user defined class, say BigNumberElement. We now define the class BigNum as :
class BigNum {
 // some code
 private:
  BigNumberElement array_[10];
}

We need to declare a whole set operators for BigNumberElement, such as comparison(can also be done through conversion), assignment, constructor etc. for making it easy to use.
auto x = a[i] will now get a copy of BigNumberElement, which is fine for most cases. Only assigning to it will sometimes throw an exception and introduce some run-time overhead. But we can still write auto x = static_cast<T>(a[i]) (still verbose though...). And as far as I can see, unexpected compile-time error messages is better than unexpected run-time exceptions.
We can also make BigNumberElement non-copyable/moveable... but then it would be the same as the first approach. (If any member functions returns BigNumberElement &, the unexpected run-time exceptions comes back.)

A: the following defines a type foo::setter which is returned from operator[] and overloads its operator= to assign a value, but throws if the value is not in the allowed range.
class foo
{
  int data[10];
public:
  void set(int index, int value)
  {
    if(value<0 || value>9)
      throw std::runtime_error("foo::set(): value "+std::to_string(value)+" is not valid");
    if(index<0 || index>9)
      throw std::runtime_error("foo::set(): index "+std::to_string(index)+" is not valid");
    data[index] = value;
  }
  struct setter {
    foo &obj;
    size_t index;
    setter&operator=(int value)
    {
      obj.set(index,value);
      return*this;
    }
    setter(foo&o, int i)
    : obj(o), index(i) {}
  };
  int operator[](int index) const // getter
  { return data[index]; }
  setter operator[](int index) // setter
  { return {*this,index}; }
};

A: If what you are trying to do is overload [] where you can input info like a dict or map like dict[key] = val.  The answer is actually pretty simple:
lets say you want to load a std::string as the key, and std::vector as the value.
and lets say you have an unordered_map as your underlying structure that you're trying to pass info to
std::unordered_map<std::string, std::vector<double>> myMap;

Inside your own class, you have this definition:
class MyClass{
    private:
        std::unordered_map<std::string, std::vector<double>> myMap;
    public:
        std::vector<double>& operator [] (std::string key) {
        return myMap[key];
    }

}

Now, when you want to load your object, you can simply do this:
int main() {

    std::vector<double> x;
    x.push_back(10.0);
    x.push_back(20.0);
    x.push_back(30.0);
    x.push_back(40.0);

    MyClass myClass;
    myClass["hello world"] = x;

    double x = myClass["hello world"][0]; //returns 10.0
}

The overloaded [] returns a reference to where that vector is stored.  So, when you call it the first time, it returns the address of where your vector will be stored after assigning it with = x.  The second call returns the same address, now returning the vector you had input.


text:
Q: Cloned div is different from the original I'm creating a search feature for a smartphone app. It identifies the div containing the searched for term and appends it to an empty search results div. This is working fine. I'm trying to prevent multiple identical search results being displayed, this generally works but creates one duplicate search result.
It looks like the cloned and original text is different I've set up a jsfiddle here
    http://jsfiddle.net/tonybabb/2mwr3hp2/3/ illustrating the problem.
Html:

some text

Javascript:
var $originalText = $("#originalText").text();
$("#originalText").clone(true, true).appendTo("#copiedText");
if ("$originalText".match($("#copiedText").text())) {
    alert("Theyre the same");
} else {
    alert("Theyre different");
}

I have been working on this for several days now, I'd really appreciate some advice. Thanks.

A: You're not matching the text, you're checking if the literal string "$originalText" matches $('#copiedText').text()
Also, look at the rendered HTML, this is copying the whole div into the other div, not just the text.

A: Do the following,
1.remove quotes from "$originalText"
 2. You should use $("#copiedText").find("div").text(), since the cloned div is attached to $("#copiedText")
var $originalText = $("#originalText").text();
$("#originalText").clone(true, true).appendTo("#copiedText");
if ($originalText.match($("#copiedText").find("div").text())) {
        alert("Theyre the same");
}
else {
 alert("Theyre different");
}

Fiddle

A: I don't know if you need the clone, so that possibly event-handler are staying attached but here is another approach, which is working:
var $originalText = $("#originalText").text();
$("#copiedText").append($("#originalText").html());
if ($originalText.match($("#copiedText").text())) {
    alert("Theyre the same");
} else {
    alert("Theyre different");
}

In this solution, only the containing html is copied to the other div.
Furthermore: Your variable $originalText is containing a string already, so you don't have to put that in quotes to compare it via .match()
Demo

A: First, remove the quotes around "$originalText". Second, it doesn't work because of the line breaks in your html. The following works:

some text


text:
Q: Is there a PEFile for ELF I love using the PeFile library for Python to parse PE files.  Is there a similar library for parsing ELF?

A: You should take a look at pyelftools
It supports ELF and DWARF binary formats. It is a project which is in active development too.

A: This is pretty old, but it still came to the top of Google when I searched...
A good library is lief - https://lief.quarkslab.com
It has support for elf, pe and macho

A: There's also pylibelf: https://github.com/crackinglandia/pylibelf
It only supports the ELF format though, and it's read-only. But it's in active development, and the write part is expected soon at the time I write this.


text:
Q: Should accepting an answer on meta give a reputation bonus? Given that meta doesn't lend itself to every question having a single correct answer, it seems wrong that you can accept a particular answer.
I may be missing the mark, but you've got three classes of question here on meta:

*

*Tech support issues for SO/SF ("Where's my rep"/"How can I track my rep"/etc.)

*Feature/enhancement requests ("How about this new badge"/"Can we have comment notifications in the RSS feeds"/etc.)

*Opinion questions ("should easy questions be closed"/"How to deal with unwritten rules"/etc.)

Of those, I only see the tech support issues actually having an answer worth accepting, and seems that it could be exploitable if people started accepting answers, purely because they've of the same opinion for a feature request. Similarly, starting a bounty seems exploitable.

A: Since meta rep only applies to meta anyway, I don't think it's a big deal. It only means that people respect your opinion on meta-discussions, not necessarily your technical acumen.
Accepting answers may still be important on subjective questions as well, because it MAY signify that the issue has been closed. In which case it makes sense to allow the moderators (or super moderators) select the answers.

A: Though I initially suggested that the mechanism for accepting an answer be removed from Meta, as this site is intended to be more discussion-oriented, I have since changed my mind, and I do think that, when applicable the ability of the topic starter to select a reply that has resolved their issue is important, and I think that the rep bonus is part of that.

A: Here on MSO voting and accepting give reputation using the same rules as on the main site. This is because:

*

*MSO was the first meta site.

*It covers network issues as well as SO issues.

*It's special.

Other meta sites don't have separate reputation scores so while accepting an answer has the same meaning as on the main site it doesn't change your reputation.

A: I would say that if a question has an answer, then accepting an answer is appropriate and should result in some reputation gain, at least to the answerer.  Since we allow questions (topics?) on meta that may not have an answer, however, perhaps we need to distinguish between questions and non-questions (discussions).  Questions would follow the normal scoring rules, where topics would not allow the ability to accept an answer (since there really is none).  The user would get the option of classifying the question at the time it was submitted, though it could be reclassified by people with significant reputation using voting rules.  Reputation gains for accepted answers would be rolled back if the question is classified as a discusssion.

A: This has been brought up a bunch of times. Accepting an answer makes no sense on meta. We all get it already.


text:
Q: "value error: shape mismatch" but data same size same type I am trying to plot using scatter3D and receive the error above. When I query my x,y and z arguments they are each lists of floats and each have the same number of values? The code is:
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
xs = coords_x
ys = coords_y
zs = test
ax.scatter3D(xs,ys,zs, color = 'green')
plt.show()

and when I check len() and type() of each variable I get the same number and type. This is my first stackoverflow question...be nice


text:
Q: Embedding CefSharp in a plugin for Revit I'm having issues embedding CefSharp (WPF) in a addin for Revit:

*

*My addin cannot be loaded by Revit unless all files are in the Revit folder alongside with the main exe. This is not good because it messes with all Revit files. I've tried to set the PATH env variable to my private folder but it does not work. Any ideas how to make my libraries loadable? I'm not an expert of .NET assemblies etc...

*CEFSharp in the addin renders webpages but they occassionally flicker. Is there any flag to set?

*CEFSharp in the addin refuses to render WebGL. Any flag to set?

Note: outside of Revit, CEFSharp works fine (tried MinimalExample.WPF)

A: For the first part of your question, you'll need to subscribe to the AppDomain.AssemblyResolve event and point the program towards the location of your DLL files.
The alternative is to manually load the DLLs in the IExternalApplication.OnStartup method using the Assembly.Load command.
For more info on the AssemblyResolve event, see here: https://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve(v=vs.110).aspx

A: I just done exactly the same thing and it works pretty well
I've a dockable CEF windows (WPF) in Revit2018 by following DockableDialogs sample in Revit 2018.2
SDK found here: http://usa.autodesk.com/adsk/servlet/index?siteID=123112&id=2484975)
I'm currently using CEFSharp.Wpf version 57.0.0.0
And yes you should remap Cef third parties like this:
CefSettings settings = new CefSettings();
            settings.CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache");
            string rootPath = FileUtility.GetAssemblyPath();
            settings.BrowserSubprocessPath = Path.Combine(rootPath, "CefSharp.BrowserSubprocess.exe");
            settings.LocalesDirPath = Path.Combine(rootPath, "locales");
            settings.ResourcesDirPath = Path.Combine(rootPath);
            Cef.EnableHighDPISupport();
            //settings.CefCommandLineArgs.Add("disable-gpu", "1");
            Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);

Don't forget to call Cef.Shutdown(); at the end also


text:
Q: How to take average of two columns row by row in SQL? I have a table match which looks like this (please see attached image). I wanted to retrieve a dataset that had a column of average values for home_goal and away_goal using this code
SELECT
    m.country_id,
    m.season,
    m.home_goal,
    m.away_goal,
    AVG(m.home_goal + m.away_goal)  AS avg_goal
FROM match AS m;

However, I got this error
column "m.country_id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 3:  m.country_id,

My question is: why was GROUP BY clause required? Why couldn't SQL know how to take average of two columns row by row?
Thank you.

A: try this:
SELECT
    m.country_id,
    m.season,
    m.home_goal,
    m.away_goal,
    (m.home_goal + m.away_goal)/2  AS avg_goal
FROM match AS m;

You have been asked for the group_by as avg() much like sum() work on multiple values of one column where you classify all columns that are not a columns wise operation in the group by
You are looking to average two distinct columns - it is a row-wise operations instead of column-wise

A:
how to take average of two columns row by row?

You don't use AVG() for this; it is an aggregate function, that operates over a set of rows. Here, it seems like you just want a simple math computation:
SELECT
    m.country_id,
    m.season,
    m.home_goal,
    m.away_goal,
    (m.home_goal + m.away_goal) / 2.0 AS avg_goal
FROM match AS m;

Note the decimal denominator (2.0): this avoids integer division in databases that implement it.

A: Avg in the context of the function mentioned above is calculating the average of the values of the columns and not the average of the two values in the same row. It is an aggregate function and that's why the group by clause is required.
In order to take the average of two columns in the same row you need to divide by 2.

A: Let's consider the following table:
CREATE TABLE Numbers([x] int, [y] int, [category] nvarchar(10));

INSERT INTO Numbers ([x], [y], [category])
VALUES
    (1, 11, 'odd'),
    (2, 22, 'even'),
    (3, 33, 'odd'),
    (4, 44, 'even');

Here is an example of using two aggregate functions - AVG and SUM - with GROUP BY:
SELECT
  Category,
  AVG(x) as avg_x,
  AVG(x+y) as avg_xy,
  SUM(x) as sum_x,
  SUM(x+y) as sum_xy
FROM Numbers
GROUP BY Category

The result has two rows:
Category    avg_x   avg_xy  sum_x   sum_xy
even    3   36  6   72
odd     2   24  4   48

Please note that Category is available in the SELECT part because the results are GROUP BY'ed by it. If a GROUP BY is not specified then the result would be 1 row and Category is not available (which value should be displayed if we have sums and averages for multiple rows with different caetories?).
What you want is to compute a new column and for this you don't use aggregate functions:
SELECT
  (x+y)/2 as avg_xy,
  (x+y) as sum_xy
FROM Numbers

This returns all rows:
avg_xy  sum_xy
6   12
12  24
18  36
24  48

If your columns are integers don't forget to handle rounding, if needed. For example (CAST(x AS DECIMAL)+y)/2 as avg_xy,

A: The simple arithmetic calculation:
(m.home_goal + m.away_goal) / 2.0

is not exactly equivalent to AVG(), because NULL values mess it up.  Databases that support lateral joins provide a pretty easy (and efficient) way to actually use AVG() within a row.
The safe version looks like:
(coalesce(m.home_goal, 0) + coalesce(m.away_goal, 0)) /
nullif( (case when m.home_goal is not null then 1 else 0 end +
         case when m.away_goal is not null then 1 else 0 end
        ), 0
      )

Some databases have syntax extensions that allow the expression to be simplified.


text:
Q: How to render components in VueJs? I want to render component dependent on my variables
I use it :

{{ auth ? <AuthCorrect /> : <AuthIncorrect /> }}

but my app render like this :
{{ auth ?
auth correct
:
AuthIncorrect
}}
Someone know how to figure out this?

A: Conditional Rendering

Authentication Successful

Authentication Failed


text:
Q: c++ system() orphan & zombie processes I have a little application, let's call it "launch.exe".  It is a c++ appl.
What I do in it is I call system() 3 times to launch 3 other applications.  let's call these A, B, and C.
problem #1
A, B, and C are GUI apps and "launch.exe" is not able to progress until A exits.  Then it is stuck again until B exits.  Then stuck again until C exits.  I would like lauch.exe to be able to progress while the applications I have opened remain open.
Problem #2
Assuming that I am able to figure out a solution to problem #1, after A, B, and C are launched, I don't want "launch.exe" to stay open.  I want launch.exe to close and I want A, B, and C to remain running.
Here is a scenario for you.  Lets us say "launch.exe" only starts one application (let us call it A).  Then, after A is started, if i close "launch.exe", A remains open.
OK...this is what I want but what just happened?  Is A an orphan now? And if so, is this a problem?
And what if I closed A before I exited launch.exe?  On the surface it seems OK, but what does it return to?  If I launched an exe in cmd shell, it would return to that, but since I did it from a system() call in a c++ appl, does it return to my lauch.exe or does it become a zombie?
NOTES:
Why am I useing system()?
--Cause I need something that is Windows/Linux compatible.
--Cause I need to elevate privileges to admin level for some of the applications being launched.
--I should add that it is vital that A, B, and C be totally independent (for security reasons they should not share the same memory space or anything else).
--Last, some of the apps, B, and C are multi-threaded (I state this because I have read that some functions do not spawn multi-threaded applications properly.  I'm not clear on reasons why.).

A: Use spawn instead, this won't block the launcher until the child exits.
Or, since you're already using Qt, use QProcess.

There is no portable way to spawn a subprocess as a different user, but the Windows-specific way is CreateProcessWithLogonW.

A: Why don't you start your A B C processes with ampersand "&" appended to command parameters
std::system ("ProcessA&");
std::system ("ProcessB&");
std::system ("ProcessC&");

This way your launcher will not wait for these processes to exit.
Then exit your launcher with QApplication::exit or QApplication::quit
Read this SO question to see the difference between fork/execvp and system().


text:
Q: How to detach firebase Realtime listeners? I'm using the firebase real-time database version 9, and I use this method to retrieve back data:
const refList= ref(
  db,
  `users/${uid}`
);
onValue(refList, (snapshot) => {
  let allData = snapshot.val() === null ? [] : snapshot.val()
});

So this is real-time communication therefore this ref has to use a listener. I checked their documentation, they say to use the off() method onto the ref without any code examples.
refList.off()

Will this remove the listener?

A: The onValue call now returns a function that (when called) removes the listener. So:
const unsubscribe = onValue(refList, (snapshot) => {
  let allData = snapshot.val() === null ? [] : snapshot.val()
});

And then later:
unsubscribe();


text:
Q: How to find out a div's name attribute How do I read the name of a div with javascript or Jquery?
I have code that dynamically creates divs with the same name and appends an ascending number to make the div unique. ex:
How can I "read" the div Id?
$(this).divname()

or something....

A: If this refers to the div element then this.id will give the id value, $(this).attr('name') should give the name attribute value

*

*.attr()

A: For ID
$(this).attr('id');

For Name
$(this).attr('name');

A:
Get the id for that particular div. Use attr and prop in jquery.

 getId = $(this).attr('id');
 getName = $(this).attr('name');

Note : jQuery 1.6, the .attr() method sometimes took property values
  into account when retrieving some attributes, which could cause
  inconsistent behavior. As of jQuery 1.6, the .prop() method provides a
  way to explicitly retrieve property values, while .attr() retrieves
  attributes.

A: Use .attr() to get value of an attribute for the first element in the set of matched elements.
var id = $(this).attr('id');

A: there are different ways depend on the requirments
var variableName = $(this).attr('name');
var variableName = $(this).attr('id');
var variableName = $("#id").attr('find any attribute'); // name, id, class and so on
var variableName = $("div#id").attr('find any attribute'); // name, id, class and so on
var variableName = $(".class").attr('find any attribute'); // name, id, class and so on
var variableName = $("div.class").attr('find any attribute'); // name, id, class and so on
var variableName = $("div[id='test']").attr('find any attribute'); // name, id, class and so on
var variableName = $("div[class='testing']").attr('find any attribute'); // name, id, class and so on
var variableName = $("div[name='header']").attr('find any attribute'); // name, id, class and so on

use any of them which fit on your requirement... and this keyword refer to current object.
For example if I create a click function and directly I call div CLASS like
$(".test").click(function(){ this.id /*OR*/ (this).id /*OR*/ $(this).attr("name") });

OR indirectly call div CLASS like
$("div[class='test']").click(function(){ this.id /*OR*/ (this).id /*OR*/ $(this).attr("name") });

Now click function will give me the current object(s) ids BUT in selector if I use this keyword
$(this).click(function(){ this.id /*OR*/ (this).id /*OR*/ $(this).attr("any attribute name") });

now where ever I click at document any where it'll give me the ID and some where give me undefined OR also error so it depends on selector.
For example now you've multiple div, span OR any object with same class but different ids when you click at any div OR span it'll give current id because of this.id so this refer to current object.
So most of the time we use direct seletor to get any attribute like this
$("#test").attr("name");

A: If $(this) refers to the div you are talking about, then
$(this).attr('id')

returns either div id or undefined,
$(this).attr('name')

returns either div name or undefined.

A: Here is a generic function that will return the div name if you pass an id to it:
function returnName(id){
    var name = $('#'+id).attr('name');
    return name;
}

To use this function:
var currentDivId = $(this).attr('id');
var myDivName = returnName(currentDivId);


text:
Q: Python how to import urlib? mirko@mirko-imedia-S2870 ~ $ /usr/bin/python
Python 2.7.3 (default, Sep 26 2012, 21:51:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urlib
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named urlib

I'm using python from the command line, with a fresh installation of Mint Linux 14.
What must I do to make this work?

A: Perhaps adding an l could help:
import urllib

A: You are missing one l in urllib, but I would highly recommend that you use urllib2 if it is available on your installation.
Other good alternatives that requires you to install 3rd party packages are urllib3 or requests.


text:
Q: Sourcebranch value is $/ We are using the DevOps 2019 build server and some of the build definitions are returning a sourcebranch value like this $/ with the missing solution path.
Any idea what could be causing this?

A:
Sourcebranch value is $/

That because you are map two team projects in the Get Sources as in below image:

In this case, when you get the sourcebranch, Azure Devops could not find the their common parent folder, so it return the $/:

This issue has been reported to the MS team, but still no solution at this time:
Ticket: Build.SourceBranch/Build.SourceBranchName returns empty
Hope this helps.


text:
Q: Prove that if $|A|<|B|$ and both A and B are linearly indepdent, then not: $B\subseteq sp(A)$ I need to prove that if $|A|<|B|$ and both $A$ and $B$ are linearly indepdent, then it is not the case that: $B\subseteq A$ (ie. there is $a\in B$, such that $a\notin sp(A)$. No advanced theorems...
So $A$ and $B$ are both linearly independent that is
$\sum_{a\in A} \lambda_a a=0$
$\sum_{b\in B} \lambda_b b=0$
Only if all the lambdas are zero. Since $|A|<|B|$, there are more elements in $B$ than in $A$. What is the best way to continue the proof from here? Inductively it is straight forward to prove if for finite case:
Suppose $|B|=1$:
There is nothing in $sp(A)$ so the case follows trivially.
Now assume that the case holds for $|B|=n$.
Now add an element $b^*$ to  $B$, since it's linearly independent, this new element is
$\sum_{b\in B} \lambda_b b\neq b^*$
Also add an element $a^*$ to  $A$, so:
$\sum_{a\in A} \lambda_a a\neq a^*$
Now if $a^*=b^*$ there is an element in $B$ that is not in $A$. And if $a^*$ is that element, then $b^*$ is in $B$, but not in $A$.
Is this completely backwards? Would it be more appropriate to use induction on $|A\triangle B|$? What about the infinite case?


text:
Q: Changing the Layout Bounds of customViewGroup, doesnot affects the Nested child of the Layout I have CustomViewGroup, which Contains LinearLayout as direct child. Button is added as child of LinearLayout.. WhenEver I change the Layout of CustomViewGroup, LinearLayout Bounds Keeps changing, Button Bounds remains same as zero.
internal class CustomLayout : ViewGroup
{
LinearLayout Linear;
Button button;
internal CustomLayout(Context context):base(context)
{
linear=new LinearLayout(context);
button=new Button(context);
button.Text="ButtonView";
linear.AddView(button);
AddView(Linear);
}
 protected override void OnLayout(bool changed, int l, int t, int r, int b)
        {

        }
}

On changing the Layout Value to specified Value, Bounds of Button remains zero
CustomLayout m_custom=new CustomLayout(this);
m_custom.Layout(0,0,300,300);

A: I would suggest you give your button layout params something like this:
LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent,
    LinearLayout.LayoutParams.WrapContent);

linearLayoutParams.SetMargins(0, 0, 0, 0);

button.LayoutParameters = linearLayoutParams;
linear.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent,
    LinearLayout.LayoutParams.MatchParent);


text:
Q: Send email to user after password reset in django I am using the Django native password reset functionality to reset account passwords.
urls.py
path('reset/', auth_views.PasswordResetView.as_view(template_name='account/password_reset.html',
                                                        form_class=PasswordResetform), name='reset'),
    path('reset_done/', auth_views.PasswordResetDoneView.as_view(template_name='account/reset_done.html'),
         name='password_reset_done'),
    path("reset/<uidb64>/<token>/",
         auth_views.PasswordResetConfirmView.as_view(template_name='account/reset_confirm.html',
                                                     form_class=PasswordResetConfirm), name='password_reset_confirm'),
    path("reset/complete", auth_views.PasswordResetCompleteView.as_view(template_name='account/reset_complete.html'),
         name='password_reset_complete'),

now everything works fine, I get the password reset link in my email and when I open it I am able to reset my password, but after the user resets the password, I want to send them an email saying their password has been reset
I tried to write an ajax function that is triggered when it goes to the 'password_reset_complete' template, but there I am unable to access the user's email or username. how do i retrieve the user's email or username in the 3rd or the 4th template of the password reset steps?

A: I think the easiest way is to subclass the SetPasswordForm:
from django.contrib.auth.forms import SetPasswordForm
from django.core.mail import EmailMultiAlternatives
from django.contrib.auth import get_user_model

UserModel = get_user_model()

class MySetPasswordForm(SetPasswordForm):

    def send_email(self, to_mail):
        subject = 'Password changed successfully'
        body = 'Your password has been changed successfully'
        email = EmailMultiAlternatives(subject, body, None, [to_email])
        email.send()

    def save(self, commit=True):
        if commit:
            email = email_field_name = UserModel.get_email_field_name()
            user_email = getattr(self.user, email_field_name)
            self.send_email(user_email)
        super().save_(commit=commit)
and then use this form:
path(
    'reset/complete',
    auth_views.PasswordResetCompleteView.as_view(
        template_name='account/reset_complete.html',
        form_class=MySetPasswordForm
    ),
    name='password_reset_complete'
),