text:
Q: how did the kernel find the right process to send hardware interrupt At first, this two things might exist:

*

*A system has a table to response hardware interrupt

*A process has a table to response interrupt send/set by the kernel

If I hit a key on the keyboard, the keyboard will send a interrupt to the CPU/kernel, and the kernel will process this interrupt. But, maybe the current running process is not the foreground one in front of our eyes, it could be a daemon process or something else. So, how the kernel knows which process should read/response our key stroke?
Thanks!

A: Hardware interrupts are only handled by the kernel.  The device-specific event is processed and if there is event/data to share with user space then the driver makes that available.  In your example of a keyboard, the device driver services the interrupt, extracting any data and clearing the condition.  The input event representing the data which is pulled from the hardware is then sent to the input subsystem.  A user space process must have the exposed input device handle open and blocked on a read.  The input subsystem within the kernel is managing this.  It's very common to see the same in other drivers: expose a device handle (e.g. /dev/misc/mydevice) which responds to open/close/read/write/ioctl.  When a process performs a "read" and there is no data, the kernel code blocks the calling process causing it to wait until there is data to satisfy the read condition.  I recommend reading up on kernel device drivers.  "Linux Device Drivers" is a great start.


text:
Q: Specifying min eigen value in factor analysis call in R This is a statistics question--
In STATA, you can specify the minimum eigen value so that the optimal number of factors are chosen.
. forvalues i=1/11{
  2.         unab vars: `vv`i''
  3.         di _n(3)"################## vars: `vars' ##################"
  4.         factor `vv`i'',pcf mineigen(1)
  5.         rotate
  6.         alpha `vv`i''
  7.   }

Both factanal() and psych::principal() require the programmer to specify the exact number of factors in the initial call.
for example:
 fit <- factanal(mydata, 3, rotation="varimax")

I know that I can run some further exploration to find the ideal number:
https://www.statmethods.net/advstats/factor.html
    # Determine Number of Factors to Extract
    library(nFactors)
    ev <- eigen(cor(mydata)) # get eigenvalues
    ap <- parallel(subject=nrow(mydata),var=ncol(mydata),
      rep=100,cent=.05)
    nS <- nScree(x=ev$values, aparallel=ap$eigen$qevpea)
    plotnScree(nS)

I would like R to decide on the factors to extract, without having to do any exploratory work. Is this possible in R?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does progressDeadlineSeconds mention the complete time of rollout deployment or will it reset for each pod during deployment? As per official documentation, kubectl rollout status returns a non-zero exit code if the Deployment has exceeded the progression deadline.
Progress Deadline Seconds
Now let's say I would like to create 2 pods as a part of my deployment.
Once the first pod is successfully up, will the progressDeadlineSeconds reset to 0 again and check for second pod to come up until progressDeadlineSeconds or is it the waiting time for complete deployment?
example:
progressDeadlineSeconds is 120, deployment needs to create 2 pods.
pod1 gets takes 80 seconds to come up.
for pod2, will it wait for 40 seconds or will it reset to 120 seconds before reporting success/failure ?


text:
Q: Remove Values from PHP Array if Present I have the following PHP array:
Array
(
    [0] => 750
    [1] => 563
    [2] => 605
    [3] => 598
    [4] => 593
)

I need to perform the following action on the array using PHP:

*

*Search the array for a value (the value will be in a
variable; let's call it $number). If the value
is present in the array, remove it.

If someone could walk me through how to do that, it would be much appreciated.
Note: If it makes it any easier, I can form the array so the keys are the same as the values.

A: $array = array_unique($array) // removes dupicate values

while(false !== ($num = array_search($num, $array))){
    unset($array[$num]);
}
$max = max($array);

will search for all keys with value $num and unset them

A: lets say your $array
$array = array_unique($array) // removes dupicate values

$array = arsort($array)

$variable = $array[0]  //  the maximum value in the array, and place it in a variable.

$key = array_search($array, $number);

if($key){

    unset($array[$key])  // Search array for a value, value is present in array, remove it.

}

A: array_search() and unset() seems a good method for your sample data in your question.  I'll just show a different way for comparison's sake (or in case your use case is slightly different from what you have posted here).
Methods: (Demo)
$array=[750,563,605,598,593];

// if removing just one number apply the number as an array element
$number=605;
var_export(array_diff($array,[$number]));

// if you are performing this task with more than one $number, make $numbers=array() and do the same...
$numbers=[605,563];  // order doesn't matter
var_export(array_diff($array,$numbers));

// if you need to re-index the output array, use array_values()...
$numbers=[605,563];  // order doesn't matter
var_export(array_values(array_diff($array,$numbers)));

Output:
array (
  0 => 750,
  1 => 563,
  3 => 598,
  4 => 593,
)

array (
  0 => 750,
  3 => 598,
  4 => 593,
)

array (
  0 => 750,
  1 => 598,
  2 => 593,
)


text:
Q: Is there a bug in sklearn's stratified sampling module? I am following a book on basic machine learning and I come across the following example:
# testing the model will be done on the remaining 10000 images
X_train, X_test, y_train, y_test = X[:60000], X[60000:],y[:60000], y[60000:]

import numpy as np
shuffle_index = np.random.permutation(60000)
X_train,y_train = X_train[shuffle_index], y_train[shuffle_index]

y_train_5 = (y_train == 5) # returns numpy array of bools
y_test_5  = (y_test == 5)

from sklearn.linear_model import SGDClassifier
sgd_clf = SGDClassifier(random_state=42)
sgd_clf.fit(X_train,y_train_5)

from sklearn.model_selection import StratifiedKFold
from sklearn.base import clone

skfolds = StratifiedKFold(n_splits=3, random_state=42)

'''
The following code splits the training set into n_splits sets
and trains the model (each iteration) on the union of n_splits -1
of the sets and tests in on the remaining set. This is carried out
n_splits times.
'''

for train_index, test_index in skfolds.split(X_train,y_train_5):
    clone_clf = clone(sgd_clf)
    X_train_folds = X_train[train_index]
    y_train_folds = y_train_5[train_index]
    print '\n'
    print "train_index "
    print train_index
    print "test_index "
    print test_index
    X_test_fold   = X_train[test_index]
    y_test_fold   = y_train_5[test_index]

    clone_clf.fit(X_train_folds,y_train_folds)
    y_pred = clone_clf.predict(X_test_fold)

    n_correct = sum(y_pred == y_test_fold)
    print(n_correct/(1.0*len(y_pred)))

This outputs
train_index
[19703 19718 19737 ... 59997 59998 59999]
test_index
[    0     1     2 ... 20026 20027 20028]
0.96895

train_index
[    0     1     2 ... 59997 59998 59999]
test_index
[19703 19718 19737 ... 40040 40041 40042]
0.96385

train_index
[    0     1     2 ... 40040 40041 40042]
test_index
[39682 39692 39695 ... 59997 59998 59999]
0.89245

The second output is using the entire training set for training and then testing the hypothesis on a portion of the training set. Is this correct?

If so, is this normal/fair/legitimate?

I understand that the sets don't have size exactly 20000 because the method is stratified ( the data is heavily skewed ).

No there is not a bug. If I actually calculate the lengths of these lists (although I think they are generators). The length returned as 40000 for all sub-training sets. So the second training set in the out put is
[0,1,......,~20000,~40000,....,59999]


text:
Q: show and hide div click on radio button using Alloy ui Hi I want to show and hide div using alloy ui onclick function of radio button.I mentioned my code as below.please help me to solve this problem.when i clicked on married i want to open one div it has anniversary date and when I click on single it will hide that div.
 <aui:field-wrapper name="maritial_status">
        <aui:input checked="<%= true %>" inlineLabel="right" name="maritial_status" type="radio"         value="single" label="single" onClick="javascript:unMarriedStatus();" />
        <aui:input  inlineLabel="right" name="maritial_status" type="radio" value="married" label="married"  onClick="javascript:marriedStatus();" />
    </aui:field-wrapper>

A: You can solve this issue by having the function and the div class
so based on the selection call the function which will implicitly create the structure form in div method
function design:
function temp()
{
var chasisno = "";
        $('#dyanamicDivElement').append(chasisno);
}
div structure:
Explanation:
so as per here the function will keep appending the value to the div
hope this solved the issue

A: You could try this way:
<aui:field-wrapper name="maritial_status">
    <aui:input checked="<%= true %>" inlineLabel="right" name="maritial_status" type="radio" value="single" label="single" onClick="document.getElementById('DIV-ID').style.display = this.checked ? 'none' : 'block';" />
    <aui:input  inlineLabel="right" name="maritial_status" type="radio" value="married" label="married"  onClick="document.getElementById('DIV-ID').style.display = this.checked ? 'block' : 'none';" />
</aui:field-wrapper>


text:
Q: Using Physical EFI Disk Image as a Virtual Hard Drive I imaged an HP Envy laptop that has an M.2 Solid State drive. When I view the image file in FTK I can see 5 partitions including the Windows partition.
I would like a virtual instance of this physical machine and have tried two different ways, one with VMWare and the other with Virtual Box.
For VMWare, I mounted the image file as a physical drive, then created a Virtual Machine and selected to use the physical drive as the VMs hard drive. When it booted it said no operating system detected.
I then took the raw image and used VBoxManager convertfromraw command to turn it into a .vmdk file. Again when I boot it up in VirtualBox no operating system can be found again.
I believe it has to do with EFI, but I am not sure.

A: The solution for VirtualBox was to Enable UEFI boot on the mother board.
https://www.serverwatch.com/server-tutorials/enabling-uefi-on-virtual-machines.html


text:
Q: Proving Equivalence with Logical Laws I'm having a bit of trouble proving that:
$\neg p \rightarrow (q \rightarrow r)$ is equivalent to $q \rightarrow (p \vee r)$.
I tried using the implication law twice to get to this:
$$p \vee (\neg q \vee r).$$
This is where I get stuck.  Can anyone help out with this?

A: We can swap things around to get $$\neg q \vee (p \vee r)$$ due to commutativity and associativity. By using the implication law once again (in reverse direction), we arrive at the required expression.


text:
Q: Kids/YA chapter book with invisible spaceship and force field, 1988 or earlier I read a kid's chapter book from my school library in 1988. I remember it was 1988 because that was the year George H. W. Bush was inaugurated and the whole school watched it on TV, and that's the only year I was at that school.
The book was a science fiction chapter book, almost certainly paperback. I was in second grade and was a good reader, but this was a stretch even for me.
I only recall a little bit, because I didn't finish the book. There was an invisible alien spaceship parked in a field, and the main character somehow got on board. He tried to escape by jumping off the spaceship, but a force field bounced him back. There was possibly a second character, possibly a girl, but I could be imagining that bit. I don't recall any alien characters, but again, I didn't finish the book.
My recollection is that this book was set in the regular world. I.e., not in a future world where aliens and spaceships are commonplace. So the invisible spaceship and force field were a big deal.
So really, all I have to go on is:

*

*Kids or Young Adult chapter book

*English

*Published 1988 or prior

*Invisible spaceship

*Force field

*Jumping into the force field and being bounced back

I'm afraid I don't recall the cover art. I do have a mental image of a towering spaceship that looks more like a building with a balcony than a stereotypical rocketship or UFO, but I suspect that's my mental image of the scene where the kid jumps off the spaceship and gets bounced back by the force field. So, not actually the cover art.

A: Long shot:
"The Sometimes Invisible Spaceship" by Charles Bowles (1988)
Solely on title and date
A review and details about the book can be found here: The Sometimes Invisible Spaceship by Charles Bowles
From the back cover:

During summer vacation from school, a brother and sister (Jeef and S.L. Strewbury) must work to help their widowed mother (Maria) make a living.
S.L. (Sabedora Louise) is younger than her brother; but, always
speaking with clarity and volume, she is equally blunt, daring, and
self-assertive. She is able, for instance, to drive a farm tractor
though her legs are too short for her feet to touch the floor pedals.
Jeef (Jefferson Francisco) would rather fish or wander the woods with
his dog Sam, but he recognizes the need to earn money. He has a
stronger urge toward adventure than he will readily admit.
The youngsters become involved with a brilliant, conceited, and
bumbling scientist (Professor Szrplqx) when they accidentally discover
his secret base of operations. The professor has developed an unusual
spacecraft, which he is testing before beginning an exploration of
outer space. Among his other achievements is a device (amatrivance) he
invented "on a whim," which can force any person or animal to like and
obey its operator. When the professor's former assistant (Zarch) gains
control of the amatrivance, the professor fears the entire universe
will come under the rule of an evil dictator.
A mixed crew, made up of the Strewbury youngsters, Sam, the professor,
and a greeble named Doctor Harkel, sets out to save the universe.

Vanity publisher
This book was published in 1987 by Aegina Press, a vanity publisher. It's well done. That is, it's been proofread for typos and such, and the paper and binding are fine. But the typesetting has very small margins for a children's book, and the cover is pretty spare. Still, not a bad effort.
Capital letters
The absent-minded Professor Szrplqx (pronounced Zerplix) is annoying, but not half so irritating as S.L., who always talks in ALL CAPITAL LETTERS, and is continually announces that SHE"S HONGRY. Not hungry, HONGRY.
Plot
Professor Szrplqx has built a spaceship named GLOMBUS, and he takes Jeef and S.L. out to explore the galaxy. They rescue a pink alien named Doctor Harkel. Szrplqx has also invented a device called an amatrivance, which compells love and obedience. Of course the professor's nemesis, Zama Z. Zarch, steals the device and escapes in his own spaceship.
Szrplqx and the crew chase Zarch to the planet Kimera. They meet Sir Gruel, a medieval knight on horseback. It's like a whole renaissance fair planet. Kimera is ruled by Queen Whoomit I, and she sends one of her knights--Sir Quembly, because why not add more characters?--to help Szrplqx. The Professor and the children and the knight eventually catch Zarch, who turns out a be a woman. Yes, Zarch was a woman all along. She used to be Szrplqx's assistant, and she only stole the amatrivance to teach him a lesson about being responsible. She has no desire for conquest. Um. OK.
Of course Zarch and Szrplqx get married.


text:
Q: SQL select statement confusion
Possible Duplicate:
What is the dual table in Oracle?

I have always wondered how does the query like:
select sysdate
from dual;

or
select 8
from dual;

do work.
As I'm used to select statement selects column/s value from a given table. But in the examples
mentioned above table dual DOESN'T have sysdate or just '8' columns....
Could someone explain me how it works?

A: You don't have to select columns. You can select expressions, which can by columns, constant values, function calls, calculations.... So you could select this from an employee table
select
  e.nr,  -- column
  upper(e.name) as name, -- Function call to change the name to uppercase.
  e.age + 5 as age, -- expression with calculation with column value.
  1  -- Just a value. Contains 1  for each row that the query returns.
from
  employees e;

Note as name and as age. This is because the column name is lost once an expression contains more that just a column name. In that case, you can specify the name that you want the column to have in the query results. A similar trick is done for the table name itself. The alias e is just a shorthand. This is especially useful when using multiple tables (in a join). In this simple query, the table alias can be omitted altogether.
dual is just a special table that has 1 row exactly, and one column named dummy. It has many different uses which have been discussed before. From Oracle 23c onwards, from dual is optional, as it has been in MySQL for a while longer. You can simply write:
select
  1;

A: It's just a table with one row.  It was created by Charles Weiss of Oracle to provide a table for joining in internal views of the Oracle Data Dictionary.

I created the DUAL table as an underlying object in the Oracle Data
  Dictionary. It was never meant to be seen itself, but instead used
  inside a view that was expected to be queried. The idea was that you
  could do a JOIN to the DUAL table and create two rows in the result
  for every one row in your table. Then, by using GROUP BY, the
  resulting join could be summarized to show the amount of storage for
  the DATA extent and for the INDEX extent(s). The name, DUAL, seemed
  apt for the process of creating a pair of rows from just one.

There are lot of neat things you can leverage dual for.  I use it to generate a list of numbers.  For example
SELECT LEVEL just_a_column
FROM dual
CONNECT BY LEVEL <= 365

Also note that as of 10g Oracle recognizes dual for its unique usages and that the logical reads / full table scans in 9i and earlier have been eliminated for applications.  Upgrading to 10g had signficant performance benefits for applications that used dual. (e.g. Select sysdate from dual).
Explain Plan example:
In 10g and above, dual is a magic table - if you select sysdate from dual, the plan would be:
sql> select sysdate from dual;

SYSDATE
---------
12-DEC-02

Execution Plan
-----------------------------------------------------------------
| Id  | Operation        | Name | Rows  | Cost (%CPU)| Time     |
-----------------------------------------------------------------
|   0 | SELECT STATEMENT |      |     1 |     2   (0)| 00:00:01 |
|   1 |  FAST DUAL       |      |     1 |     2   (0)| 00:00:01 |
-----------------------------------------------------------------


text:
Q: Sticky nav assistance I've been trying to make a sticky nav with the source code down bellow, but just simply cant find anything or make anything work.
The code has the two nav bars TOP & MID that i'd hope someone could help me create the TOPnav go behind the MIDnav at a certain point to create that sticky like effect.
I have no JS linked cause i hope someone could give me a rough idea of what to do.
thank you :).
PS: if anything in my code seem  odd/weird or perhaps not needed feel free to point it out as i hope to improve it.

html{

overflow-x: hidden;
height: 2000px;

background: white;
}

.TOPNAV {
  position: fixed;
  width: 80vw;
  height: 20px;
  margin-top: -720px;
  margin-left: -10px;
  border-top: 70px solid #AC3838;
  border-left: 60px solid transparent;
  border-right: 60px solid transparent;
  z-index: 10;
}
.TOPNAV a {
  position: fixed;
  font-family: 'Bungee', cursive;
  text-decoration: none;
  font-size: 20px;
  margin-top: -60px;
  margin-left: 4vw;
  color: white;
  text-shadow: 1px 1px 1px black, 0 0 0 #000, 2px 4px 10px black;
}
.TOPNAV li {
  float: left;
  width: 15vw;
  padding: 0px 0px 10px 0px;
  display: block;
  list-style-type: none;
}
.MIDNAV {
  position: relative;
  width: 100vw;
  height: 20px;
  margin-top: 730px;
  margin-left: -10px;
  border-bottom: 70px solid #575194;
  z-index: 10;
}
.MIDNAV a {
  position: absolute;
  font-family: 'Bungee', cursive;
  text-decoration: none;
  font-size: 20px;
  margin-top: 30px;
  margin-left: 10vw;
  color: white;
  text-shadow: 1px 1px 1px black, 0 0 0 #000, 2px 4px 10px black;
}
.MIDNAV li {
  float: left;
  width: 15vw;
  padding: 0px 0px 20px 0px;
  display: block;
  list-style-type: none;
}

  <title></title>

  <link rel="stylesheet" type="text/css" href=".//CSS\SCRAP_CSS.css">

  <link href="https://fonts.googleapis.com/css?family=Bungee" rel="stylesheet">

Home

Index

About

List

Login

Home

Index

About

List

Login

A: If you are looking for a simple sticky nav with pure Javascript, html and css then you can use this snippet. I got it from the 30day Javascript tutorial which I highly recommend and I added some comments.
Credits to Wes Bos.

   // grab the element that contains the navigation we want to create a sticky effect for
const nav = document.querySelector("#main");

// create a variable that stores the height of the space between the top of the parent node (in this case our body element) of our nav and the top of our nav
let topOfNav = nav.offsetTop;

// create our function that should run everytime the user scrolls
function fixNav() {
  // if the user scrolls further down than the height of our variable add the class fixed-nav and add a padding
  if( window.scrollY >= topOfNav ) {
    // the padding is added because the element is removed from the document flow due to position: fixed
    document.body.style.paddingTop = nav.offsetHeight + 'px';
    // position: add css class fixed-nav
    document.body.classList.add('fixed-nav');
    } else {
    // remove the class and padding when the user scrolls above our nav again
    document.body.style.paddingTop = 0;
    document.body.classList.remove('fixed-nav');
    }
}

window.addEventListener('scroll', fixNav);
* {
  margin: 0;
  padding: 0;
  }

body {
  height: 800px;
  background: grey;
  }

.upper-space {
  display: block;
  background: red;
  height:200px
  }

nav {
  display: block;
  width: 100%;
  top: 0;
  color: white;
  background: #333;
  height: 100px;
  }

ul.navigation {
  list-style-type: none;
  }

.navigation li {
  float: left;
  width: 100px;
  }

.fixed-nav #main {
  position: fixed;
  }

menu item 1

menu item 2

menu item 3

  Suscipit, libero, aperiam est sequi aspernatur malesuada ratione, quaerat ipsa posuere nisl perferendis laboris facilisis voluptas conubia sodales, dolorem? Malesuada purus, dolorem torquent distinctio, animi qui rerum, culpa. Mattis accumsan doloribus pellentesque eveniet. Porro sequi omnis soluta inceptos, dicta curae hac adipiscing anim adipiscing ante. Luctus hymenaeos pharetra, facilisi explicabo.

Laboris justo tincidunt illo incididunt erat netus quisquam doloremque eos habitasse sequi! Rerum primis, sodales! Totam, feugiat mattis est atque! Eiusmod curabitur deserunt earum quis, libero euismod reiciendis quae et, perspiciatis donec voluptates, consequuntur, vel purus! Voluptate platea doloribus? Blanditiis aptent litora excepteur vulputate! Cursus. Felis nostrum mattis, nisi, adipiscing.


text:
Q: Switch case of strings in objective c I would like to ask you which is the most efficient way to do something like a switch (…) statement of NSStrings in Objective-C.
What I want to do is a function that I send a File Extension (doc, txt, ...) and I get its MIME Type.
I was thinking in some array of key->value but I am not sure if would be the best way to do this.
What do you suggest me?

A: Declare a static dictionary mapping from file extensions to mime types and simply query it:
NSDictionary *mimeTypes = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    mimeType = @{
        @"txt" : @"text/plain",
        @"doc" : @"application/msword",
        ....
    };
});
NSString *mimeType = mimeTypes[@"txt"]; // result: @"text/plain"


text:
Q: Skip first line within a "for line" loop I have an efficient way of combining large CSV files (without reading into memory) that I want to modify so that it skips header rows. Is there a way to skip the header row, something like for line in infile if not the first line but without reading into memory?
filenames = os.listdir(localdir)
print("concatenating files %s"%(sorted((filenames))))
with open(localdir+outfile+'.csv', 'w') as outfile:
    for fname in filenames:
        with open(localdir+fname) as infile:
            for line in infile:
                outfile.write(line)


text:
Q: Db2 nested JSON I am trying to use Db2 JSON capabilities and in particular nested tables.
CREATE TABLE JSON.TEST1 (COL1 VARBINARY(2000));
INSERT INTO JSON.TEST1 (COL1) VALUES (JSON_TO_BSON(
'{"id"       : 103,
  "orderDate": "2014-06-20",
  "items": {
             "item": [ { "partNum": "872-AA",
                         "productName": "Lawnmower",
                         "quantity": 1,
                         "USPrice": 749.99
                       },
                       { "partNum": "837-CM",
                         "productName": "Digital Camera",
                         "quantity": 2,
                         "USPrice": 199.99
                       }
                     ]
            }
    }'
));

This works fine, however obviously items in the array are hardcoded references.
SELECT  id
       ,orderDate
       ,product1
       ,product2

FROM json.TEST1 AS js,
    JSON_TABLE
      (js.COL1, 'strict $'
       COLUMNS( id                  INTEGER        PATH '$.id'
               ,orderDate           DATE           PATH '$.orderDate'
               ,product1            VARCHAR(32)    PATH '$.items.item[0].productName'
               ,product2            VARCHAR(32)    PATH '$.items.item[1].productName'
       )
ERROR ON ERROR) AS t
;

The following is what I am trying to get working:
SELECT  id
       ,orderDate
       ,productName
FROM json.TEST1 AS js,
    JSON_TABLE
      (js.COL1, '$'
       COLUMNS( id                  INTEGER        PATH '$.id'
               ,orderDate           DATE           PATH '$.orderDate'
               ,NESTED 'lax $.items.item[]'
               COLUMNS (
                         "productName" VARCHAR(32)
                       )
               )
       ) as t;

For reference the error I am receiving
1) [Code: -104, SQL State: 42601]  An unexpected token "'lax $.items.item[]'
               COLUMNS (
    " was found following ",NESTED".  Expected tokens may include:  "<space>".. SQLCODE=-104, SQLSTATE=42601, DRIVER=4.26.14
2) [Code: -727, SQL State: 56098]  An error occurred during implicit system action type "2". Information returned for the error includes SQLCODE "-104", SQLSTATE "42601" and message tokens "'lax $.items.item[]'
               COLUMNS (
    |,N".. SQLCODE=-727, SQLSTATE=56098, DRIVER=4.26.14

A: Unfortunately, you must unnest JSON arrays on your own, for example, with Recursive Common Table Expression (RCTE):
-- A table with JSON documents
WITH TAB (DOC_ID, DOC) AS
(
VALUES
(
1,
'{"id"       : 103,
  "orderDate": "2014-06-20",
  "items": {
             "item": [ { "partNum": "872-AA",
                         "productName": "Lawnmower",
                         "quantity": 1,
                         "USPrice": 749.99
                       },
                       { "partNum": "837-CM",
                         "productName": "Digital Camera",
                         "quantity": 2,
                         "USPrice": 199.99
                       }
                     ]
            }
 }'
)
)
-- get a JSON array only for each record
, ITEMS_ARRAY (DOC_ID, ITEMS) AS
(
  SELECT DOC_ID, JSON_OBJECT(KEY 'items' VALUE JSON_QUERY(DOC, '$.items.item') FORMAT JSON)
  FROM TAB
)
-- Use RCTE to unnest it
, ITEMS (DOC_ID, INDEX, ITEM) AS
(
  SELECT DOC_ID, 0, JSON_QUERY(ITEMS, '$.items[0]')
  FROM ITEMS_ARRAY
  WHERE JSON_EXISTS(ITEMS, '$.items[0]')
    UNION ALL
  SELECT I.DOC_ID, I.INDEX+1, JSON_QUERY(A.ITEMS, '$.items['|| TRIM(I.INDEX+1) ||']')
  FROM ITEMS I, ITEMS_ARRAY A
  WHERE I.DOC_ID = A.DOC_ID AND JSON_EXISTS(A.ITEMS, '$.items['|| TRIM(I.INDEX+1) ||']')
)
SELECT D.*, IT.*
--, I.*
FROM TAB T
JOIN ITEMS I ON I.DOC_ID = T.DOC_ID
-- array element to row
CROSS JOIN JSON_TABLE
  (
    I.ITEM, 'strict $' COLUMNS
    (
        PARTNUM      VARCHAR(20) PATH '$.partNum'
      , PRODCUCTNAME VARCHAR(20) PATH '$.productName'
      , QUANTITY     INT         PATH '$.quantity'
      , USPRICE      DECFLOAT    PATH '$.USPrice'
    ) ERROR ON ERROR
  ) IT
-- other elements of original JSON to row
CROSS JOIN JSON_TABLE
  (
    T.DOC, 'strict $' COLUMNS
    (
        ID        INT  PATH '$.id'
      , ORDERDATE DATE PATH '$.orderDate'
    ) ERROR ON ERROR
  ) D
;

There result is:
|ID |ORDERDATE |PARTNUM|PRODCUCTNAME  |QUANTITY|USPRICE|
|---|----------|-------|--------------|--------|-------|
|103|2014-06-20|872-AA |Lawnmower     |1       |749.99 |
|103|2014-06-20|837-CM |Digital Camera|2       |199.99 |

db<>fiddle example.
Update
It's convenient to create a generic function suitable for any JSON array:
-- WITH A GENERIC TABLE FUNCTION

CREATE OR REPLACE FUNCTION UNNEST_JSON (P_DOC CLOB(1M), P_PATH VARCHAR(128))
RETURNS TABLE
(
  INDEX INT
, ITEM  CLOB(1M)
)
RETURN
  WITH ITEMS_ARRAY (ITEMS) AS
(
  VALUES JSON_OBJECT(KEY 'items' VALUE JSON_QUERY(P_DOC, P_PATH) FORMAT JSON)
)
, ITEMS (INDEX, ITEM) AS
(
  SELECT 0, JSON_QUERY(ITEMS, '$.items[0]')
  FROM ITEMS_ARRAY
  WHERE JSON_EXISTS(ITEMS, '$.items[0]')
    UNION ALL
  SELECT I.INDEX+1, JSON_QUERY(A.ITEMS, '$.items['|| TRIM(I.INDEX+1) ||']')
  FROM ITEMS I, ITEMS_ARRAY A
  WHERE JSON_EXISTS(A.ITEMS, '$.items['|| TRIM(I.INDEX+1) ||']')
)
SELECT INDEX, ITEM
FROM ITEMS
@

Such a generic function simplifies the solution:
WITH TAB (DOC_ID, DOC) AS
(
VALUES
(
1,
'{"id"       : 103,
  "orderDate": "2014-06-20",
  "items": {
             "item": [ { "partNum": "872-AA",
                         "productName": "Lawnmower",
                         "quantity": 1,
                         "USPrice": 749.99
                       },
                       { "partNum": "837-CM",
                         "productName": "Digital Camera",
                         "quantity": 2,
                         "USPrice": 199.99
                       }
                     ]
            }
 }'
)
,
(
2,
'{"id"       : 203,
  "orderDate": "2014-06-20",
  "items": {
             "item": [ { "partNum": "002-AA",
                         "productName": "Lawnmower",
                         "quantity": 10,
                         "USPrice": 749.99
                       },
                       { "partNum": "002-BB",
                         "productName": "Digital Camera",
                         "quantity": 20,
                         "USPrice": 199.99
                       }
                     ]
            }
 }'
)
)
SELECT T.DOC_ID, A.INDEX, D.*, IT.*
FROM
  TAB T
-- unnesting
, TABLE(UNNEST_JSON(T.DOC, '$.items.item')) A
-- array element to row
, JSON_TABLE
  (
    A.ITEM, 'strict $' COLUMNS
    (
        PARTNUM      VARCHAR(20) PATH '$.partNum'
      , PRODCUCTNAME VARCHAR(20) PATH '$.productName'
      , QUANTITY     INT         PATH '$.quantity'
      , USPRICE      DECFLOAT    PATH '$.USPrice'
    ) ERROR ON ERROR
  ) IT
-- other elements of original JSON to row
, JSON_TABLE
  (
    T.DOC, 'strict $' COLUMNS
    (
        ID        INT  PATH '$.id'
      , ORDERDATE DATE PATH '$.orderDate'
    ) ERROR ON ERROR
  ) D;

The result is:
|DOC_ID|INDEX|ID |ORDERDATE |PARTNUM|PRODCUCTNAME  |QUANTITY|USPRICE|
|------|-----|---|----------|-------|--------------|--------|-------|
|1     |0    |103|2014-06-20|872-AA |Lawnmower     |1       |749.990|
|1     |1    |103|2014-06-20|837-CM |Digital Camera|2       |199.990|
|2     |0    |203|2014-06-20|002-AA |Lawnmower     |10      |749.990|
|2     |1    |203|2014-06-20|002-BB |Digital Camera|20      |199.990|

A: A couple of UDFs with the same functionality which should work faster, since they don't use RCTE.
The example of use is in my another older answer here.
-- Uses XML, should work in all environments
CREATE OR REPLACE FUNCTION UNNEST_JSON2 (P_DOC CLOB(1M), P_PATH VARCHAR(128))
RETURNS TABLE
(
  INDEX INT
, ITEM  CLOB (1M)
)
DETERMINISTIC
NO EXTERNAL ACTION
BEGIN ATOMIC
  DECLARE L_IDX INT DEFAULT 0;
  DECLARE L_XML XML;

  L1:
  WHILE TRUE DO
    IF NOT JSON_EXISTS (P_DOC, P_PATH || '[' || L_IDX || ']') THEN LEAVE L1; END IF;
    SET (L_XML, L_IDX) =
    (
      XMLCONCAT (L_XML, XMLELEMENT (NAME "A", JSON_QUERY (P_DOC, P_PATH || '[' || L_IDX || ']')))
    , L_IDX + 1
    );
  END WHILE L1;

  RETURN
  SELECT SEQ - 1, T.ITEM
  FROM XMLTABLE
  (
    '$D' PASSING L_XML AS "D"
    COLUMNS
      SEQ  FOR ORDINALITY
    , ITEM CLOB (1M) PATH '.'
  ) T
  WHERE L_XML IS NOT NULL;

END
@

-- Doesn't work in DPF environment, but should be the fastest one
CREATE OR REPLACE FUNCTION UNNEST_JSON3 (P_DOC CLOB(1M), P_PATH VARCHAR(128))
RETURNS TABLE
(
  INDEX INT
, ITEM  CLOB (1M)
)
DETERMINISTIC
NO EXTERNAL ACTION
BEGIN
  DECLARE L_IDX INT DEFAULT 0;

  L1:
  WHILE TRUE DO
    IF NOT JSON_EXISTS (P_DOC, P_PATH || '[' || L_IDX || ']') THEN LEAVE L1; END IF;
    PIPE (L_IDX, JSON_QUERY (P_DOC, P_PATH || '[' || L_IDX || ']'));
    SET L_IDX = L_IDX + 1;
  END WHILE L1;

  RETURN;
END
@


text:
Q: How to get and process json data given by ajax request in prototype? This is my first attempt to prototype. I want to initiate an AJAX request that should get a JSON response and alert that. I have done following so far.
JS:

HTML:
Testing AJAX

JSON source:
function ajaxresponse() {

    // Data
    $data = array("New York", "New Yorkshire", "New Jersey");
    // encode and return json data
    echo json_encode( $data );
}

On clicking "Testing AJAX" link I am getting following result in alert box:
no JSON object

Any idea ?
Thanks

A: I dont see any second variable passed to onSuccess handler in prototype. Look here. There is only transport object. So this should help:
...
onSuccess: function(transport) {
      var json = transport.responseText;
      alert(json ? Object.inspect(json) : "no JSON object");
 },
...


text:
Q: WITH clause in MySQL? Does MySQL support common table expressions?  For example in Oracle there's the WITH clause? :
WITH aliasname
AS
  ( SELECT COUNT(*) FROM table_name )
SELECT COUNT(*) FROM dept,aliasname

A: SELECT t.name,
       t.num
  FROM TABLE t
  JOIN (SELECT c.id,COUNT(*) 'num1'
          FROM TABLE1 c
         WHERE c.column = 'a'
      GROUP BY c.id) ta1 ON ta1.id = t.id
 JOIN (SELECT d.id,COUNT(*) 'num2'
          FROM TABLE2 d
         WHERE d.column = 'a'
      GROUP BY d.id) ta2 ON ta2.id = t.id

A: One way is to use a subquery:
  SELECT COUNT(*)
  FROM dept,
  (
      SELECT COUNT(*)
      FROM table_name
  ) AS aliasname

Note that the , between the two tables will cross join the two tables the same as in your query you posted. IF there is any relation between them you can JOIN them instead.

A: No, MySQL does not support Common Table Expressions (CTE). So instead of using WITH tablealias as (....), you will have to do a subquery.
For example,
WITH totalcount AS
(select userid, count(*) as tot from logins group by userid)
SELECT a.firstname, a.lastname, b.tot
FROM users a
INNER JOIN
totalcount b
    on a.userid = b.userid

can be re-written in MySQL as
SELECT a.firstname, a.lastname, b.totalcount
FROM users a
INNER JOIN
(select userid, count(*) as tot from logins group by userid) b
    on a.userid = b.userid

A: So let's talk about WITH clause .
WITH clause and INNER JOIN otherwise JOIN are a kind of same , but WITH clause gives you much more latitude especially in WHERE clause ;
I am going to make a view that'll get values like count of users , user name and etc.
First (Creating our tables users and inserted_users) :
inserted_users table :
 CREATE TABLE users (id BIGINT(10) AUTO INCEREMENT PRIMARY KEY , name VARCHAR(50))

users table :
CREATE TABLE users (id BIGINT(10) AUTO INCEREMENT PRIMARY KEY , name VARCHAR(50) , gender TINYINT(1))

Second (Inserting some values to work with) :
users table :
INSERT INTO users (name,gender) VALUES ('Abolfazl M' , 1)

I don't want to insert into inserted_users by query , but I want to add a TRUGGER which will insert data automatically to users_inserted table before data be inserted into users table.
Third (Creating trigger add_uinserted) :
DELIMITER $$

CREATE TRIGGER IF NOT EXISTS add_uinserted BEFORE INSERT ON users FOR EACH ROW
BEGIN

IF NEW.name <> '' THEN

     INSERT INTO users_inserted (name) VALUES (NEW.name);

ELSE

INSERT INTO users (name,gender) VALUES ('Unknown',NEW.gender);
INSERT INTO users_inserted (name) VALUES ('Unknown');

END IF;

END$$

DELIMITER ;

Run the query and the trigger will be created and at last let's create a view to give us result from a query having WITH clause .
CREATE VIEW select_users AS

WITH GetCAll AS (
SELECT u1.id As Uid ,COUNT(u1.name) AS CnAll FROM users u1
)

SELECT u1.name AS NAME,CASE
WHEN s1.gender = 1 THEN "MALE"
WHEN s1.gender = 0 THEN "FEMALE"
ELSE "UNKNOWN"
END AS GENDER,CASE
WHEN u1.id = gca.Uid THEN "INSERTED TO users_inserted"
ELSE "NOT INSERTED TO users_inserted"
END AS INSERTED,gca.CnAll FROM GetCAll AS gca INNER JOIN users u1;

After you query got ran the view will be created and by calling the view select_users the data will be shown
Last step (calling the select_users view) :
SELECT * FROM select_users

Thanks for taking a look at my answer , and that's it !!


text:
Q: What does "string!" mean? I am trying to modify the popular Energy-skate-park
simulation so that it launches with the grids visible. While looking at the code I came across declarations like the following:
var energyEnergyString = require( 'string!ENERGY_SKATE_PARK_BASICS/energy.energy' );

var energyKineticString = require(
'string!ENERGY_SKATE_PARK_BASICS/energy.kinetic' );

I have no idea what this "string!" followed by some file path means. Is it angular? Is it vanilla JS feature?
Can anyone please guide me to the right direction/documentation to understand these declarations better?

A: This is probably a webpack-loader, in your case, string-loader that transforms the required file to a string.


text:
Q: Smart extended test fails on same LBA every time. Is my drive really dying? I ran a smart extended test on my old laptop's hard disk, and got a read error. I ran it again, and it got the same LBA of the error. Does this mean the disk is really dying, or just that there is a bad block or two? Additionally, when I look at the individual smart attributes, they are well over the threshold, even though the drive is pretty old.
Based on this, is the hard drive actually going bad? Or is smart just acting weird?

A: The LBA is just another name for sector.  Based solely on the information we know you have 1 bad sector.  You need to find the total number of bad sectors in order to know what condition the hard drive is in.
1 bad sector is hardly the end of the world, but more will following over the coming years.  The total number and rate at which the occur tells you more about the drives overall health.
You should

*

*Make sure your backup is in good working order

*Start putting money away so in 6 months, a year, or whenever it fails you can replace it.


text:
Q: Date comparison in Oracle database I have two variable TO_DATE and FROM_DATE. My table has two fields DOJ and DOL. I want to select all the records where DOJ < TO_DATE and DOL > FROM_DATE.
How can I write an SQL query in for this?

A: You might run into troubles with the variable named to_date, since that is a built-in Oracle command. You can work around that using double quotes wherever the variable is used, like this:
SELECT * FROM my_table WHERE doj < "to_date" AND dol > from_date;

A: It is not clear what you would like to do.
FIRST INTERPRETATION
I want to select all the records whose DOJ < TO_DATE and, IN THE MEANTIME, DOL > FROM_DATE.
SELECT *
  FROM MY_TABLE
 WHERE DOJ < "TO_DATE" AND DOL > "FROM_DATE"; -- using double quotes in order to
                                              -- avoid confusion with TO_DATE
                                              -- built-in function with the same name.
                                              -- Thanks to kicsit ;-)

SECOND INTERPRETATION
I want to select all the records whose DOJ < TO_DATE and, SEPARATELY, DOL > FROM_DATE.
SELECT *
  FROM MY_TABLE
 WHERE DOJ < "TO_DATE"
UNION -- UNION ALL substituted with UNION, thanks to kicsit user ;-)
SELECT *
  FROM MY_TABLE
 WHERE DOL > "FROM_DATE";

... or - that is the same:
SELECT *
  FROM MY_TABLE
 WHERE DOJ < "TO_DATE" OR DOL > "FROM_DATE";


text:
Q: Alternatives to snapshot functionality, SQL Server Standard For testing purposes I would like to reset a complete database to a certain state (data and structure). I would like to do this automated. Preferably a command line instruction before I start my tests.
After some searching I discovered that SQL Server offers an great solution for this. Snapshots. After writing a test query I discovered that the standard edition of SQL Server does NOT support this. :-(
Given the fact that I want this to be automated: what are my options? Overwriting the data files immediately doesn't sound like a good option to me...
Some other information:

*

*Windows 7

*Microsoft SQL Server Standard Edition (64-bit), 10.50.1600.1

*Database size is app. 1 gigabyte

*This is only meant for testing. So the database is NOT used by other users when I'm returning to my 'snapshot'.

*More information about snapshots:

*

*http://msdn.microsoft.com/en-us/library/ms190677.aspx

*This page also states that the standard edition does not support this. :-(

Thank you in advance!

A: Detach the MDF file, copy it somewhere, re-attach it.
When you want to reset the database, detatch the MDF, copy the old one over the top, and re-attach it.
Alternatively backup and restore.

A: If you're doing this for testing purposes, you can use Developer Edition:

SQL Server 2008 Developer includes all of the functionality of Enterprise Edition, but is licensed only for development, test, and demo use.

A: I homebrewed a solution like this because I wasn't happy with the way replication was running (and I was also using standard edition) - maybe my solution will lead you in the right direction:
http://trycatchfinally.net/2009/09/moving-a-sql-server-database-to-another-server-on-a-schedule-without-using-replication/
Basically, it takes a periodic backup, zips it, FTPs it somewhere, and the remote server checks for new files, extracts them, restores them, and then emails you to let you know a new replica has been restored.

A: For testing, you can use Developers Edition, which has snapshots and is quite cheap. However, we prefer to build a new test database from scripts in source control - that allows us to easily determine the changes, quickly roll out a testing system on any box, and saves us a lot of time.


text:
Q: Web-run bug in visual studio2015 I opened Web  a project in visual studio -my code is based on angular,html and css.
sometimes when I run the code on my Chrome  browser I cant see my recent changes of my code,and I see only the old code.
I think the problem is   the caching on my browser,but I don't sure about that.
Hope that someone has a answer to my problem...
Thanks.

A: A few ideas:

*

*When you refresh your page in Chrome, do a CTRL+F5 to do a full refresh.

*Even if you set the expires to 0, it will still cache during the session. You'll have to close and re-open your browser again.

*Make sure when you save the files on the server, the timestamps are getting updated. Chrome will first issue a HEAD command instead of a full GET to see if it needs to download the full file again, and the server uses the timestamp to see.

If you want to disable caching on your server, you can do something like:
Header set Expires "Thu, 19 Nov 1981 08:52:00 GM"
Header set Cache-Control "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"
Header set Pragma "no-cache"

In .htaccess

*OR disable Chrome cache:

When you reload the page, the JS, CSS should now get refreshed.


text:
Q: How to setup meteor project in subdirectory at host? trying to deploy a meteor application to centos 6 google cloud server, I followed this post after two days of setting up this server and compiling the project I stocked with the last step where I need to configure the app URL so what I did for now
1) create a sub directory at "/var/www/html/myproject" in centos 6 google cloud server
2) install nodejs v8.12.0 throw nvm
3) install mongodb 4.0.4
4) installing meteor 1.7.0.5 because my project is version 1.7.0.5
5) bundling my meteor project using "meteor build myproject"
6) uploading the genrated myproject.tar.gz to the server using FTP client to "/var/www/html/myproject"
7) unzip the myproject.tar.gz cd to /var/www/html/myproject/bundle/programs/server exucut npm installeverything is installed and ok
8) setting the PORT export PORT=3084
9) setting the MONGO_URL export
MONGO_URL=mongodb://127.0.0.1:27017/myprojectdb
10) setting the ROOT_URL export ROOT_URL=http://domain/myproject/ is that right to do so like http://domain/myproject/ or http://domain/is that correct thing to do?
11) i installed forever npm -g install forever
12) forever start /var/www/html/myproject/bundle/main.js and it's run without errors
and here where I got stocked how can I access my project how can I configure the app url to access it like http://mydomin/myproject I tried like the psot says in step 7 "Step 7: configure a reverse proxy in your apache configuration"
vi /etc/httpd/conf.d/yourapp_domain.conf

then
 <VirtualHost *:80>
  ServerName myproject
  ProxyRequests off
  <Proxy *>
    Order deny,allow
    Allow from all
  </Proxy>
  <Location />
    ProxyPass http://serverip:3084/myproject
    ProxyPassReverse http://serverip:3084/myproject
  </Location>
</VirtualHost>

but I couldn't access the website throw http://serverip:3084/myproject I'm new with server configurations, and I couldn't find any good resources online doing what I'm trying to do please any help.


text:
Q: Development machine IIS version vs deployment IIS version My development machine is running Windows XP SP2 (and IIS 5.1 by implication).
Until recently our deployment environment was based around Windows Server 2003 (and therefore IIS 6.0).
We are about to move to Windows Server 2008 (and therefore IIS 7.0) for a new project.
Our projects use ASP.NET MVC and WCF Services.
Are there any key reasons for us to upgrade our development machines to run Windows Server 2008 (or possibly Vista, since this also comes with IIS 7.0)?

A: I  would say it's in your best interest to upgrade your development machines to emulate as much of the production environment as possible within your means and resources. Otherwise you may fall into traps you're completely unaware of just by deploying an application from your development machine to the server's environment, which may pertain to differing versions of IIS, the version of .NET framework each machine is running, or just the way the code is compiled or executed at runtime.
Especially since IIS 7 has been vastly upgraded since IIS 5.1, why shouldn't you work closer with it's current functionality while developing before you missing out on some great opportunities? To really know what to expect from an application in production, develop it under the same circumstances.
Edit/Added: This link may help you see at least one significant example of how differing versions can affect your project.

A: I would recommend that you develop against the same major build as you intend to deploy on. That said, this leaves you with a few options. First, you could build against your local IIS installation (as it appears you currently do). That means that all of your boxes should likely be upgraded to Windows Vista or Windows 2008 Server (or Windows 7 as it is running IIS 7.5). Your second option is to deploy to a remote machine. It is entirely possible to deploy your application to a remote test machine running IIS 7 and remotely debug as well. The problem is that if you have more than one developer working on the remote site, it becomes problematic. IIS can handle the remote debugging on different webs for different developers, but depending on your architecture and configuration, you may still be sharing resources between instances of test web applications.You could occasionally deadlock each other. The only benefit is that you don't have to buy licenses for all of your machines (and potentially upgrade hardware to support the OS upgrade). However, I think that would be short-sighted. The loss of developer productivity wouldn't be worth it, IMHO.
There are major changes between IIS 5.1 and IIS 7.x. The changes to the architecture, such as the integrated pipeline, can result in drastically different behavior and compatibility issues.  I think you will find that IIS 7 far more developer-friendly. The introduction of things such as failed request tracing, extended logging, and enhanced error pages alone make it much easier to track down errors in your application. In that regard, the upgrade is well worth it.


text:
Q: Convert private variables into public variables I'm trying to discover how to send some private variables to the global scope. I've created a brief demo:
function test() {
    let private1 = 1, private2 = 2;

    return private1;
}

test(); // returns the first variable value, but not if I have multiple variables
console.log(private1); // returns obvious error - how to make private variable global?

Obviously logging any variables will return an error as they only exist in the local scope relative to the test function. So my question is, how can these variables be made public?
I've never had to use variables this way, nor could I find any other posts that explains this, so is this generally bad practice? I'm curious to know. Any explanation or guidance of how best to treat variables would be very helpful, thank you.

A: A variable declared inside a function is only available inside that said function, unless you declare it outside the function.
In this example, you can't use private1 outside the function.

function test() {
  let private1 = 1;
  return private1;
}
test();
console.log(private1);

You can't make it global otherwise from outside the scope of the said function.
In this example, you can use private1 outside the function.

let private1;

function test() {
  private1 = 1;
  return private1;
}
test();
console.log(private1);

A: The are 2 ways to add a variable to the global (and only the global scope) from inside a function (without returning the variables in an object or array). Though, by adding a variable to the global scope, you make it available to every script running on that page.
1. Make sure that strict mode is not activated and "forget" to declare the variables
// Dont do "use strict";
function test() {
    private1 = 1;
    private2 = 2;
    return private1;
}

When strict mode is not used, then whenever JavaScript sees a variable that has not been declared then it automatically declares it on the global scope. Though, this is very bad practice and should be avoided.
2. Add the variables directly to the global object
function test() {
    window.private1 = 1;
    this.private2 = 2;
    return private1;
}

The window object can be obtained using window or this. But this will only return the window if it is not called from inside an object or a binded/applied function.
Return and Destructuring (ES6)
A nice feature of ES6 (meaning this cant be used on older browsers like IE) is destructuring which allows you to do this:
function test() {
    return { private1: 1, private2: 2 };
}
var { private1: private1, private2: private2 } = test();

Or
function test() {
    return [1, 2];
}
var { 0: private1, 1: private2 } = test();

A: You can either create global variables and assign value to them
let global1,global2;
function test() {
    let private1 = 1, private2 = 2;
    global1 = private1;
    global2 = private2;

    return private1;
}

test();
console.log(global1);

or you can use returned value
function test() {
    let private1 = 1, private2 = 2;

    return private1;
}

var result = test();
console.log(result);

A: The simplest way to make private1 global would be to do something like this
let global1

function test() {
    let private1 = 1, private2 = 2;

    return private1;
}

global1 = test()

But, as the other answer says, if you wanted this, it would be better to declare the variable outside the function scope.

A: If you're on a browser, you can assign them to window.

function test() {
  window.private1 = 1, window.private2 = 2;
}

test()

console.log(private1, private2)

Or you can export them by returning them:

function test() {
    let private1 = 1, private2 = 2;

    return {
      private1,
      private2
    };
}

console.log(test())

So is this generally bad practice?

Yes, making them global is bad practice. Exporting them if they are really needed outside the function itself is ok though.

A: scope of let is fixed, you cant access it outside the function. On solution to your problem is binding variable to window.

function test() {
    private1 = 1; // or you can use window.private1 = 1
    private2 = 2;
    return private1;
}

test();
console.log(private1);

If you dont declare your variable with var let or const it automatically gets binded to window scope, But this not considered as a good practice. You can also use window.variableName for this purpose.

A: Why first private and then public? If you need some private space, you could take an IIFE and a destructuring assignment of the result object to global variables.

var { private1: global1, private2: global2 } = function () {
        let private1 = 'foo',
            private2 = 'bar';

        return { private1, private2 };
    }();

console.log(global1, global2);

A: Just don't add any declaration at the Begining.Javascript treat this as a global variable.
function test(){
   private1 = 1;
   private2 = 2
}

test();

After the call of the function test the private1 and private2 set as a global variable.
If you put a console below test like this
console.log(private1,private2);
//1 2 is the answer.

It will printed in the console and you can able to call it like this too.
window.private1;
window.private2;

That's it.


text:
Q: How to make input and select to be same width in css In my page, there are several input and select tags.
I use width:100%; to define their width, but the width in the browser is not 100%.
I used the debug tool in chrome, and found there is also useragent stylesheet styles applied.
How can I make the width 100%?

A: Demo Fiddle
You should ideally separate style from content, so in your CSS include:
input, select{
  width:100%;
  box-sizing:border-box;
}

nb. demo fiddle without box-sizing set
And you need to use box-sizing:border-box in order for sizing to take into account any browser specific or set margin/padding/borders. Here's a handy read on the subject.
Box-Sizing on MDN:

The box-sizing CSS property is used to alter the default CSS box model
  used to calculate widths and heights of elements. It is possible to
  use this property to emulate the behavior of browsers that do not
  correctly support the CSS box model specification.
border-box
The width and height properties include the padding and border, but
  not the margin. This is the box model used by Internet Explorer when
  the document is in Quirks mode.

A: To override the user agent stylesheet use reset.css in your code at the start.
   /*
      Reset .css
   */

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

If you do not want to override the useragent then you can go for width value in 'px'

A: Try to use the width CSS property of select tag as follows:
<Select name="foo" width="100" style="width: 100px">
 <option>One</option>
 <option>Two</option>
 <option>Three</option>
 <option>Four</option>
</select>

So the same for the input tag
<input type="text" name="faa" value="test" style="width: 100px;" />

You can use the style in css as well for input tag.

A: or use the following css:
input[type=text], select {
    width: 100% //or whatever you want)
}


text:
Q: How to set up a zip-download via button click? (header) I've got a site with a table and want to add a button in front of each tr. Clicking on the button should pop up the download dialog (save file) and after pushing "save", download the file.
I see this so often, and still don't know how to do that. I have set up the button via a form:
<form method="get">
<input type="submit" value="<?php echo $paket; ?>" name="download" />
</form>

where $paketcontains the filename without the .zip ending.
In the same php file, just under two require_once statements, I did this:
if ( isset( $_GET['download'] ) ) {
$name = $_GET['download'];
header( 'Content-Disposition: attachment; filename = '.$name.'.zip' );
header( 'Content-type: application/zip' );
}

If I push the button, I get these errors:
Warning: Cannot modify header information - headers already sent by (output started at /is/lib/require.req:154)

I do know that the header information needs to sit on the very top, but how am I supposed to use functions I include with require_once, if the require_once comes a few lines after?
Is there a nice (and foolproof) tutorial that I just can't find?

A: Use an output buffer if you need to send content before the headers http://php.net/manual/pt_BR/function.ob-start.php .
Anyway your donwload file should be on  a different location or put the download handling part at the very top off the file and exit after it

A: Do not use echo, print() or something similar before header() or start_session(). HTTP-sepcific information has to be before common-output.
Just look at the php-documentation
"Remember that header() must be called before any actual output is sent [...]"

A: The header must always been send before any other output took place. That means it must be the first thing send in the current file (which contains the header information) but it also has to be the first thing send for all other files, that include this file.
Won't work
<?php
    // application logic here
    print "X";
    require 'header.php';
    // application logic here

Will ork
<?php
    // application logic here
    require 'header.php';
    // application logic here

header.php
<?php
    // application logic here
    header( 'Content-type: application/zip' );
    // application logic here

A: It turned out there was a whitespace before the first <?php tag, that caused the error.


text:
Q: Hello i need to get the fastest response, all successful (which means ignore the rejected) and three first responded I've already tried to get the fastest response but in chrome toolbar network i see all the responses but not the fastest. Also as i mentioned above I want to get all the successful responses and ignore rejected
const url = 'https://mate-academy.github.io/phone-catalogue-static/api/phones.json';
const detailsUrl = 'https://mate-academy.github.io/phone-catalogue-static/api/phones/';

const getPhones = () => {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        setTimeout(() => {
          return Promise.reject(new Error('It was an accident'));
        }, 5000);
      }

      return response.json();
    });
};

const getFirstPhoneDetails = (arrId) => {
  return Promise.race(arrId.map(id =>
    fetch(`${detailsUrl}${id}.json`)));
};

getPhones()
  .then(phones => {
    const ids = phones.map(p => p.id);

    return getFirstPhoneDetails(ids);
  })
  .catch(error => {
    console.warn(error);
  });


text:
Q: How to get width and height of ContentChild TemplateRef in Angular 11 I'm doing a web application with Angular 11. I need to show a list of cards, where each card has its own design.
I have created a component that receives a list of items and a child component to be projected, this child is another component that has the style (UI) I want to show.
Component:
@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss']
})
export class ListComponent {

  @Input() items: any[];
  @ContentChild(TemplateRef) template: TemplateRef<any>;

  constructor() {
  }

}

Template:

    <ng-container *ngTemplateOutlet="template; context: {$implicit: i}"></ng-container>

How do I use this component? Here is an example.
<app-list [items]="myArray">
  <ng-template let-item>

    <app-card-style-one [item]="item"></app-card-style-one>
  </ng-template>
</app-list>

All good so far. Now, I need to get the child's width and height.
I have tried this on my ListComponent:
  @Input() items: any[];
  @ContentChild(TemplateRef, {read: ElementRef}) template: TemplateRef<any>;

  constructor(
    private element: ElementRef
  ) {
  }

  ngAfterViewInit() {
    console.log(this.element.nativeElement);
    console.log(this.template.elementRef.nativeElement);
    console.log(this.template.elementRef.nativeElement.nextSibling);
  }

No luck, I receives undefined or templateRef.createEmbeddedView is not a function.
My goal is to get the width and height of the child that is being projected. I will use those two variables to adjust other UI components that I have in my ListComponent.


text:
Q: Odoo8 Qweb generated pdf document. The tablerows on the 2nd page are jammed On the 2nd 3rd etc. page the tableheader and tablerows of quotation or invoice are jammed, when I print the document in pdf format.
This works the same (wrong) way in my own written templates too.
Brand new installed LinuxMint17 (Ubuntu clone), latest odoo8 (2015-01-29), wkhtmltox0.12.2.1

Is this a bug or a feature?
Any help would be appreciated!
Cheers! Janos

A: Hear it means that the current Report not using the compatible version of
Wkhtmltopdf python  library
you need to check from version of current Wkhtmltopdf python library  and
if it 0.12 to lower remove and reinstall then install the latest Wkhtmltopdf 0.12.X version or later and print your report again.
I hope this should help you.

A: There was a bug with wkhtmltox. I've downgraded to wkhtmltox-0.12.1 and everything works fine.


text:
Q: How to change the order in dimensions xarray.Dataset? I am creating a xarray dataset as below:
import numpy as np
import xarray as xr

x_example = np.random.rand(1488,)
y_example = np.random.rand(1331,)
time_example = np.random.rand(120,)
rainfall_example = np.random.rand(120, 1331, 1488)

rainfall_dataset = xr.Dataset(
    data_vars=dict(
        rainfall_depth=(['time', 'y', 'x'], rainfall_example),
    ),
    coords=dict(
        time=(['time'], time_example),
        x=(['x'], x_example),
        y=(['y'], y_example)
    )
)

The results are like this

And the dimensions when I run rainfall_example.dims are like this Frozen({'time': 120, 'y': 1331, 'x': 1488}) (this can also be seen in the above results). I know the xarray.Dataset.dims cannot be modified according to here
My question is: How can we change the order of those dimensions into the dimensions like this Frozen({'time': 120, 'x': 1488, 'y': 1331}) without changing anything else (everything will be the same only the order in dimensions is changed)?

A: You can reorder your coordinates and variables by selecting them both in order using a list:
In [3]: rainfall_dataset[["time", "y", "x", "rainfall_depth"]]
Out[3]:
<xarray.Dataset>
Dimensions:         (time: 120, y: 1331, x: 1488)
Coordinates:
  * time            (time) float64 0.2848 0.7556 0.9501 ... 0.694 0.734 0.198
  * y               (y) float64 0.1941 0.1132 0.2504 ... 0.1501 0.5085 0.006135
  * x               (x) float64 0.2776 0.4504 0.1886 ... 0.4071 0.3327 0.5555
Data variables:
    rainfall_depth  (time, y, x) float64 ...


text:
Q: Zend Framework: Getting request object in bootstrap How do I get the request object from inside the bootstrap file?
I can try this methods but not work.
$request= new Zend_Controller_Request_Http();
$request = Zend_Controller_FrontController::getInstance()->getRequest();

A: If you really want to, you may achieve this calling:
public function _initRequest()
{
    $this->bootstrap('frontController');
    $front = $this->getResource('frontController');
    $front->setRequest(new Zend_Controller_Request_Http());

    $request = $front->getRequest();
}

However, this should be avoided, because the most data you need from the Response object will be available after the front controller is dispatched (eg. module, controller or action name).
The other variables stored in the Response object are extracted from global arrays such as $_SERVER, $_POST or $_GET which you may exceptionally read directly in bootstrap.
But most likely, you want to use Response object in front controller plugin:
class Your_Controller_Plugin_PluginName extends Zend_Controller_Plugin_Abstract
{
     public function preDispatch(Zend_Controller_Request_Abstract $request)
     {
         // do anything with the $request here
     }
}

A: You shouldn't get the request objet, since if you see the dispatch loop, the idea is that the bootstrap are actions prior to execute in a request.
If you need to alter someway of the application use a Controller Plugin to do that.

A: You need to bootstrap the frontController first, try something like:
function initFoo()
{
    $this->bootstrap('frontController');
    $req = $this->frontController->getRequest();
}


text:
Q: How to plot chart from external JSON and format X-AXIS to show time using Chart.JS? I am using Chart.JS to plot some data from external JSON. But I am unable to format the X-AXIS in a proper way.
My html & javascripts codes are here:

$(document).ready(function(){
  $.ajax({
    url : "https://api.npoint.io/1f7ea8eeaa8996ad0d71",
    type : "POST",
    dataType: "json",
    success : function(data){
      console.log(data);

      var reg_date = [];
      var datetime = [];
      var temperature = [];
      var humidity = [];
      var effluent_level = [];

      for(var i in data) {
        reg_date.push(new Date(data[i].reg_date));
        temperature.push(data[i].temperature);
        humidity.push(data[i].humidity);
        effluent_level.push(data[i].effluent_level);
      }

      var chartdata = {
        labels: reg_date,
        type: 'time',
        distribution: 'linear',
        datasets: [
          {
            label: "Temperature",
            fill: false,
            //lineTension: 0.1,
            backgroundColor: "rgba(59, 89, 152, 0.75)",
            borderColor: "rgba(59, 89, 152, 1)",
            pointHoverBackgroundColor: "rgba(59, 89, 152, 1)",
            pointHoverBorderColor: "rgba(59, 89, 152, 1)",
            data: temperature
          },
          {
            label: "Humidity",
            fill: false,
            //lineTension: 0.1,
            backgroundColor: "rgba(29, 202, 255, 0.75)",
            borderColor: "rgba(29, 202, 255, 1)",
            pointHoverBackgroundColor: "rgba(29, 202, 255, 1)",
            pointHoverBorderColor: "rgba(29, 202, 255, 1)",
            data: humidity
          },
          {
            label: "Effluent Level",
            fill: false,
            //lineTension: 0.1,
            backgroundColor: "rgba(211, 72, 54, 0.75)",
            borderColor: "rgba(211, 72, 54, 1)",
            pointHoverBackgroundColor: "rgba(211, 72, 54, 1)",
            pointHoverBorderColor: "rgba(211, 72, 54, 1)",
            data: effluent_level
          }
        ]
      };

      var ctx = $("#mycanvas");

      var LineGraph = new Chart(ctx, {
        type: 'line',
        data: chartdata
      });
    },
    error : function(data) {

    }
  });
});
<!DOCTYPE html>
<html>
  <head>
    <title>ChartJS - LineGraph</title>
    <style>
      .chart-container {
        width: 640px;
        height: auto;
      }
    </style>
  </head>
  <body>
    <div class="chart-container">
      <canvas id="mycanvas"></canvas>
    </div>

    <!-- javascript -->
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
    <script type="text/javascript" src="linegraph.js"></script>
  </body>
</html>

Output Image:

But I want to show only time values in X-AXIS (not losing date data). How to plot the graph in an effective way to represent the data?

A: You can use a time axis:

const options = {
  type: 'line',
  data: {
    labels: ["Fri Feb 11 2022 00:59:07 GMT+0530 (Indian Standard Time)", "Fri Feb 11 2022 00:59:17 GMT+0530 (Indian Standard Time)", "Fri Feb 11 2022 00:59:27 GMT+0530 (Indian Standard Time)"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
    }]
  },
  options: {
    scales: {
      x: {
        type: 'time'
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/moment@^2"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>
</body>

or you can use a custom tick callback to achieve this

const options = {
  type: 'line',
  data: {
    labels: ["Fri Feb 11 2022 00:59:07 GMT+0530 (Indian Standard Time)", "Fri Feb 11 2022 00:59:17 GMT+0530 (Indian Standard Time)", "Fri Feb 11 2022 00:59:27 GMT+0530 (Indian Standard Time)"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
    }]
  },
  options: {
    scales: {
      x: {
        ticks: {
          callback: function(val) {
            return this.getLabelForValue(val).substring(16, 24);
          }
        }
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"></script>
</body>

Documentation: https://www.chartjs.org/docs/master/axes/labelling.html#creating-custom-tick-formats


text:
Q: Increase alert (locally) when beamercounter increases Sometimes in an item I increase the beamer counter, which controls when text is uncovered. I'd like to affect "alert" at the same time.
For example, I often do something like the following:
\documentclass{beamer}

\begin{document}
\begin{frame}[<alert@+|+->]{Using information under uncertainty}
\begin{itemize}
\item One item.
\item<alert@+-.(2)|+-> What is the answer to this fascinating question? \uncover<+->{\textcolor{green}{A (fascinating) answer}, but I want the question
still alerted in addition to this part.}
\item Another item.
\end{itemize}
\end{frame}

\end{document}

I like this PDF output.
I am looking for a way to achieve the same PDF output, but without having to specify the <alert@+-.(2)|+->. That is, I'm looking for a way for alert to be automatically adjusted according to when the beamercounter is increased in the item.
EDIT: Ideally, I think I would like to switch this alert-automatically-adapting behavior on/off at the itemize level and/or the document level (i.e., preamble). However, if I can at least remove that hardcoded 2 I would already be happier. That is, if I have multiple uncovers in the same itemize, I currently need to adapt 2 accordingly. If I still have to specify something for each \item where I want this behavior, as long as I could do something like ``<alert@+-.(Q)|+->` where Q is automatically replaced accordingly, that would be a nice improvement.


text:
Q: Splitting records and duplicating data into split records (odd table structure) I have a table that looks like this (Don't ask. I didn't create it but I have to work with it). Let's call it OddTable...
Heading     Details           Issue1   Issue2   Issue3   Comments   BatchId
ItemID      SN1001                                                  10
Date Done   2018-12-18                                              10
Section1                        1         1        1                10
AreaA                           1         1                         10
AreaB                                                               10
ItemID      SN1002                                                  11
ItemID      SN1003                                                  11
ItemID      SN1004                                                  11
Date Done   2018-12-11                                              11
Section1                                                  Test      11
AreaA                                     1               Stuff     11
AreaB                           1         1               Even More 11
ItemID      SN1005                                                  12
ItemID      SN1006                                                  12
Date Done   2018-12-11                                              12
Section1                                           1                12
AreaA                                     1        1      Blah      12
AreaB                           1                         Yada      12

Looking to select results that look like this (Separate each ItemID into it's own set of records duplicated from the batch):
Heading     Details           Issue1   Issue2   Issue3   Comments
ItemID      SN1001
Date Done   2018-12-18
Section1                        1         1        1
AreaA                           1         1
AreaB
ItemID      SN1002
Date Done   2018-12-11
Section1                                                  Test
AreaA                                     1               Stuff
AreaB                           1         1               Even More
ItemID      SN1003
Date Done   2018-12-11
Section1                                                  Test
AreaA                                     1               Stuff
AreaB                           1         1               Even More
ItemID      SN1004
Date Done   2018-12-11
Section1                                                  Test
AreaA                                     1               Stuff
AreaB                           1         1               Even More
ItemID      SN1005
Date Done   2018-12-11
Section1                                           1
AreaA                                     1        1      Blah
AreaB                           1                         Yada
ItemID      SN1006
Date Done   2018-12-11
Section1                                           1
AreaA                                     1        1      Blah
AreaB                           1                         Yada

NOTE: The BatchId column is not required in the result and is used only to distinguish the group where the data needs to be duplicated.
Thank you so very much for your help.

A: Try using cross apply
select t2.*
from table t1
cross apply (
  select 'ItemID' Heading, t1.Details, null Issue1, null Issue2, null Issue3, null Comments
  union all
  select *
  from table t3
  where t1.BatchId = t3.BathId and Heading in ('Date Done', 'Section1', 'AreaA', 'AreaB')
) t2
where t1.heading = 'ItemID'

However, the problem is that the result of the SELECT is not implicitly ordered. Therefore, you may obtain the result rows swapped somehow. Assigning some ID in order to ensure the requested order would require more effort.

A: Had some time to think about it and came up with this solution (along the lines-ish of what was suggested by @Sean Lange). What I came up with was to split the same table up into 2 parts and then inner join them both so I'd get the repeated data. I'm sure someone will point out a more efficient way to do this but until then this is what I've got. Query is as follows:
SELECT
    Part1.ItemId
    ,Part1.DateDone
    ,Part2.Area
    ,Issue1
    ,Issue2
    ,Issue3
    ,Comments
    ,Part2.BatchId
FROM
(SELECT
    *
FROM(
    SELECT
        CASE WHEN Heading = 'ItemID' THEN Details END as ItemId
        ,MAX(CASE WHEN Heading = 'Date Done' THEN Details END) OVER (PARTITION BY BatchId) as DateDone
        ,BatchId
    FROM
        dbo.OddTable
) as StartingData
WHERE ItemId not like 'NULL'
) as Part1
inner join
(SELECT
    Heading as Area
    ,Issue1
    ,Issue2
    ,Issue3
    ,Comment
    ,BatchId
FROM
    dbo.OddTable
WHERE Heading in ('Section1','AreaA','AreaB')
) as Part2
ON Part1.BatchId = Part2.BatchId

ORDER BY Part1.ItemId,Part1.BatchId


text:
Q: Access constant of a class member object doesn't work if I try the following example (PHP 5.4) I get the following error:

Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM), expecting ',' or ';'

class a {
    public $p;
    public function __construct() {
        $this->p = new b;
    }
    public function giveout() {
        echo $this->p::c;
    }
}
class b {
    const c = '234';
}
$obj = new a;
$obj->giveout();

But why? Isn't it possible to use the double colon and arrow in one expression?
I know I could also use a getter method in class b and then call $this->p->get(), but I'd rather like to use the above syntax.

A: Rewrite
echo $this->p::c;

to
echo $this->p=b::c;

and..
$a->giveout();

to
$obj->giveout();

Putting it all together...
<?php
class a {
public $p;
public function __construct() {
$this->p = new b;
}
public function giveout() {
echo $this->p=b::c;
}
}
class b {
const c = '234';
}
$obj = new a;
$obj->giveout();

OUTPUT :
234


text:
Q: Cannot display comments with CakePHP Comments Plugin I have the CakePHP Comments Plugin set-up correctly, I believe.  I've followed the poorly-written instructions [here] to the point where it's requiring me to login to add a comment.  When I click "add a comment", it gives me the title and body form fields.
It's even submitting and saving the data just fine.  Then, the data comes across when I debug($article); - I see the comment(s) for that article in the data.
But - the only thing that appears when I have this in my view:
<? $commentWidget->options(array('allowAnonymousComment' => false));?>
<? echo $commentWidget->display();?>

Is the "Add a comment" button.
How do I display the comments?  The plugin has views for index, edit, view...etc all seem to be laid out ok and for me to use, but... I tried a straight include, and it's missing lots of variables..etc, so - assume there's some kind of method or something to display the comments, like... echo $commentWidget->comments; or something?
UPDATE:
When I debug($result); from comment_widget.php, I still just get an "Add comment" link (so there are two on the page now - one from the actual ->display() and one from my new debug.
Below is what I'm getting when I debug($article); from my articles_controller.php.
I built the table myself, based on a few things I found online - and it appears to be populating (mostly) - maybe I did something wrong w/ the db setup?
[Comment] => Array
    (
        [0] => Array
            (
                [id] => 7
                [title] => dave test 2
                [created] => 2011-07-10 20:28:31
                [modified] => 2011-07-10 20:28:31
                [user_id] => 67
                [foreign_key] => 683
                [approved] => 1
                [slug] => dave_test_2
                [body] => test
                [rght] => 2
                [model] => Article
                [is_spam] =>
                [lft] => 1
                [parent_id] => 0
                [author_name] =>
                [author_url] =>
                [author_email] =>
                [language] => en-us
                [comment_type] =>
            )

        [1] => Array
            (
                [id] => 8
                [title] => blah blah blah 6523dkaljlkfsjdsfaljsd
                [created] => 2011-07-10 21:33:43
                [modified] => 2011-07-10 21:33:43
                [user_id] => 67
                [foreign_key] => 683
                ...

A: Build the table structure per the schema.php (plugins/comments/config/schema/schema.php) making sure to use their default values.  In my case, I left out the default values of 'comment' for comment_type, and 'clean' for the default of is_spam.
Fixing both of these makes it so the comments now appear correctly!  They're ugly with no CSS, so - any suggestions on that is more than welcome, but... they work!


text:
Q: attribute is missing the android namespace prefix Im creating an android app which uses a menu.xml file in the res folder. But I'm getting the above error. What does it mean? How can I fix it?
menu.xml:
<?xml version="1.0" encoding= "utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item id="@+id/my_location"
android:icon="@drawable/my_location"
android:title:="Current location" />

<item id="@+id/mapview_satellite"
android:icon="@drawable/satelliteview"
android:title="Satellite View" />

<item id="@+id/mapview_normal"
android:icon="@drawable/normalview"
android:title="Normal view" />
</menu>

A: Believe it or not, for anyone who tries to work through examples in downloaded books, you may need to make sure you have true quotation marks as the compiler understands them.  I'd been getting the same error as the OP, and many similar parse errors as I tried to modify an XML  file in small ways.  I noticed then that quote marks from the pasted code snippets were different from the ones on my keyboard (in the snippets they leaned to the right, and if I typed them myself they were straight up and down).
I know this sounds nuts and I could hardly believe it myself, but when I retyped my quotes it worked fine.

A: Change <item id="@+id/my_location" to <item android:id="@+id/my_location". This in all three places.
Also, in here: android:title:="Current location" remove the colon after title.

A: Adding android: before the attribute solved my problem.

A: You also need to make sure the following two lines are in your attributes list:
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"

If you omit those, Eclipse will just give you the "missing android prefix" error.

A: create an XML file inside your project's res/menu/ directory Not in in res folder
&
dont forget to prefix the id attributes.
Try like this:
<?xml version="1.0" encoding= "utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/my_location"
        android:icon="@drawable/my_location"
        android:title="Current location" />

    <item android:id="@+id/mapview_satellite"
        android:icon="@drawable/satelliteview"
        android:title="Satellite View" />

    <item android:id="@+id/mapview_normal"
        android:icon="@drawable/normalview"
        android:title="Normal view" />
</menu>

A: Some times the XML code might be written correctly so you need to simply cut what you currently have and then delete it from the line numbers then re-paste it and the error should be fixed. If it doesn't then you know your code is wrong. The xml default is to recognize what you have put at first and needs to be removed in order to begin again. Trust me I just spent 3 days on that very problem and did exactly what is said above, good luck.

A: If you have something like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
   <data>
        <variable  name="person" type="com.abc.PersonEntity"/>
    </data>

Move your data inside layout tag:
<layout xmlns:android="http://schemas.android.com/apk/res/android"  >
       <data>
          <variable  name="person" type="com.abc.PersonEntity"/>
       </data>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
...

A: You've forgotten to prefix the id attributes. Try to do it like this:
<?xml version="1.0" encoding= "utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/my_location"
        android:icon="@drawable/my_location"
        android:title="Current location" />

    <item android:id="@+id/mapview_satellite"
        android:icon="@drawable/satelliteview"
        android:title="Satellite View" />

    <item android:id="@+id/mapview_normal"
        android:icon="@drawable/normalview"
        android:title="Normal view" />
</menu>

A: there was two error silly error
- id isn't it attribute is android:id
- First itme android:title:= you have written extra colon after title

here is implemented code
<?xml version="1.0" encoding= "utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/my_location"
        android:icon="@drawable/my_location"
        android:title="Current location"/>
    <item
        android:id="@+id/mapview_satellite"
        android:icon="@drawable/satelliteview"
        android:title="Satellite View"/>
    <item
        android:id="@+id/mapview_normal"
        android:icon="@drawable/normalview"
        android:title="Normal view"/>

</menu>


text:
Q: LLVM - convert const void * to LLVMValRef I need to cast const void * to LLVMValRef ,like this
const void * context;
args[0] = LLVMCastPtrToBoolType((void *) context);

I get the following warning.

warning: cast from type 'const void*' to type 'void*' casts away qualifiers


text:
Q: Checking if a user has already voted, returns true even when they haven't? The user enters their userid and then votes either 'yes' or 'no' but the code returns true and the if statement is executed even when the user hasn't voted.
For example - doing userid = 1 and voting, userid = 1 and voting. The second time userid tries to vote it does say you've already voted but if you then do userid = 2 for the third iteration it says you've already voted, which isn't true.
import sqlite3

conn = sqlite3.connect(":memory:")
cur = conn.cursor()

with conn:
    cur.execute("CREATE TABLE users(votes, userid INTEGER)")

for i in range(3):
    userid = input("Enter your user id: ")
    votes = input("Vote yes or no: ")
    with conn:
        cur.execute("SELECT * FROM users WHERE votes = 'yes' OR 'no' AND userid = ?", (userid,))
        user_voted = cur.fetchall()

        if user_voted:
            print("You have already voted")

        else:
            cur.execute("INSERT into users(userid, votes) VALUES(?, ?)", (userid, votes))
            print(cur.fetchall())

with conn:
    cur.execute("SELECT * FROM users")
    print(cur.fetchall())

There are no error messages, it just produces the wrong result

A:
WHERE votes = 'yes' OR 'no'

If you don't want repeated mention of the votes column,
then phrase it as:
WHERE votes in ('yes', 'no')


text:
Q: How can I tell when the ItemsSource of my Custom control has changed I have a custom control in the early stages of development as I endeavour to learn about wpf custom control development.  The custom control inherits from ItemsControls which gives me access to an ItemsSource property to which I am binding an enumerable collection.
Currently I have a simple two project solution comprising my custom control in one and a test project in the other to test the former.  In my test project I have a simple mainwindow onto which I have put my custom control and bound its ItemsSource.
    <WpfControls:VtlDataNavigator x:Name="MyDataNavigator"
                                      ItemsSource="{Binding ElementName=MainWindow, Path=Orders}" />

In the loaded event of the main window (which implements INotifyPropertyChanged) I instantiate the Orders collection.  The customcontrols gets initialised before the main window loads but I can see from examining the Live Visual Tree in visual studio that once the main form loads the custom controls Items Source property is indeed set to Orders.  Now of course I'd actually like to count the orders and have my custom control display that (it's a simple data navigator so what I'm after is the record count).  I know how to get the count but how do I know when the itemsSource has changed so that I can react to it and get the count. There's no itemsSourceChanged event that I can see.
I've seen this blog article, but I'm wondering if there is a more straightforward approach to this as it seems such an obvious thing to want to know about.

A: You can do that using OverrideMetaData.
Try this:
public class Class1 : ItemsControl
{
    static Class1()
    {
        ItemsSourceProperty.OverrideMetadata(typeof(Class1),
        new FrameworkPropertyMetadata(null, OnItemSourceChanged));
    }

    private static void OnItemSourceChanged(DependencyObject d,
                                            DependencyPropertyChangedEventArgs e)
    {
        Debug.WriteLine("Why you haz Changed me!");
    }
}

A: The ItemsSource is a DependencyProperty, and when creating DPs you can optionally specify a "property changed" event. Unfortunately ItemsSource is locked away in the base class, so I started wondering if there might be a way to add your own event to an existing DP. I came across this article that looks promising. Basically you would do something like this (untested so read the article!):-
var dpd = DependencyPropertyDescriptor.FromProperty(
    VtlDataNavigator.ItemsSourceProperty,
    typeof(VtlDataNavigator));

if (dpd != null)
{
    dpd.AddValueChanged(
        vtlDataNavigatorInstance,
        delegate
          {
              var count = VtlDataNavigatorInstance.ItemsSource.Count; // Or whatever...
          });
}


text:
Q: Selecting some part of a string from a column in hive and getting a count I have a column 'Platform' with rows as below.
name3:"string1/string2/string3/s:1.2.1/ABCD/XYZ".
And i have another column name with name 'name2'. My table looks like this
' id       |    name2     |   name3
-----------+--------------+---------------------
 1         |      x1      | string1/string2/string3/s:1.2.1/ABCD/XYZ
 2         |      x1      | string1/string2/string3/S:2.2.1/ABCD/XYZ
 3         |      x2      | string5/string4/string3/s:1.1/ABCD/XYZ
 4         |      x3      | string1/string6/string7/m:0.2.2/ABCD/XYZ
 5         |      x2      | string1/string2/string3/S:2.2.0/ABCD/XYZ'

I want to get counts of event based on substrings of platform. like
'name3     | X1    |   X2 |    X3    |

string4        |       |   1  |          |
string6        |       |      |   1      |'

or if i want to get the count based on just 'android' or 'iOS', how can i do that?
'name3     | X1    |   X2 |    X3    |

 string4          |       |   1  |          |
 string1      |   2   |   1  |   1      |'

The query i am using for counts is below. It is working fine for getting the counts of events but unable to figure out how the get the counts based on substrings.
'select name2,
    count(1) AS total
from table1 where name2='x1' OR name2='x2' OR name2='x3'
group by name2;'

Any suggestions?

A: Hope this helps...
Query:
 select a.platforms, a.event, count(1) as count from
 (select regexp_extract(platform, '^(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)$',1)
 as platforms, event from table1) a group by a.platforms, a.event;

Output:
platforms       event   count
android         x1      2
android         x2      1
android         x3      1
ios             x2      1

A: First of all, I would split that string up into a view with actual columns. Something like:
create view my_view as select
id,
event,
regexp_extract(platform, '^(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)$', 1) as os,
regexp_extract(platform, '^(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)$', 2) as brand,
regexp_extract(platform, '^(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)$', 3) as model,
regexp_extract(platform, '^(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)$', 4) as lte,
regexp_extract(platform, '^(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)$', 5) as abcd,
regexp_extract(platform, '^(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)$', 6) as user,
regexp_extract(platform, '^(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)$', 7) as xyz
from my_table;

Then querying that view is easier. You could also just have this as an inner-query. This sort of "count-where" query where you want different counts in different columns is a pretty common use. The best way I know of to do it is with the pattern:
sum(if( [condition] , 1, 0))

So for your examples, it would be:
select os,
sum(if(event = 'x1', 1, 0)) as x1,
sum(if(event = 'x2', 1, 0)) as x2,
sum(if(event = 'x3', 1, 0)) as x3
from my_view
group by os;

Or:
select brand,
sum(if(event = 'x1', 1, 0)) as x1,
sum(if(event = 'x2', 1, 0)) as x2,
sum(if(event = 'x3', 1, 0)) as x3
from my_view
group by brand;

And here's the above query, but using that view as an inner query instead of an actual view:
select brand,
sum(if(event = 'x1', 1, 0)) as x1,
sum(if(event = 'x2', 1, 0)) as x2,
sum(if(event = 'x3', 1, 0)) as x3
from (
  select
  id,
  event,
  regexp_extract(platform, '^(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)$', 1) as os,
  regexp_extract(platform, '^(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)$', 2) as brand,
  regexp_extract(platform, '^(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)$', 3) as model,
  regexp_extract(platform, '^(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)$', 4) as lte,
  regexp_extract(platform, '^(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)$', 5) as abcd,
  regexp_extract(platform, '^(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)$', 6) as user,
  regexp_extract(platform, '^(.*)/(.*)/(.*)/(.*)/(.*)/(.*)/(.*)$', 7) as xyz
  from my_table
) t
group by brand;


text:
Q: Parsing and count words from multi lines text in Lua Say I have the multi-lines text:
  str = [[
  The lazy dog sleeping on the yard.
  While a lazy old man smoking.
  The yard never green again.
  ]]

I can split each words using:
 for w in str:gmatch("%S+") do print(w) end

But how I can get results as an example:
The = 3 words, line 1,3
Lazy = 2 words, line 1,2
Dog = 1 word, line 1
..and so on?

Thank you

A: You could detect the \n using gmatch like you are already to count the words.
The pattern would be something like "[^\n]+" and the code something like this:
local str = [[
The lazy dog sleeping on the yard.
While a lazy old man smoking.
The yard never green again.
]]
local words = {}
local lines = {}
local line_count = 0

for l in str:gmatch("[^\n]+") do
  line_count = line_count + 1
  for w in l:gmatch("[^%s%p]+") do
    w = w:lower()
    words[w] = words[w] and words[w] + 1 or 1
    lines[w] = lines[w] or {}
    if lines[w][#lines[w]] ~= line_count then
      lines[w][#lines[w] + 1] = line_count
    end
  end
end

for w, count in pairs(words) do
  local the_lines = ""
  for _,line in ipairs(lines[w]) do
    the_lines = the_lines .. line .. ','
  end
  --The = 3 words, line 1,3
  print(w .." = " .. count .. " words , lines " .. the_lines)
end

Full output, note i also changed the pattern you used for capturing the words to "[^%s%p]+" i did this to remove the . that was getting attached to smoking, again, and yard.
smoking = 1 words , lines 2,
while = 1 words , lines 2,
green = 1 words , lines 3,
never = 1 words , lines 3,
on = 1 words , lines 1,
lazy = 2 words , lines 1,2,
the = 3 words , lines 1,3,
again = 1 words , lines 3,
man = 1 words , lines 2,
yard = 2 words , lines 1,3,
dog = 1 words , lines 1,
old = 1 words , lines 2,
a = 1 words , lines 2,
sleeping = 1 words , lines 1,