Q:

url query parameter parsing , best option

I have in my url this
http://www.test.com/?jjjanu@gmail.com&tid=RetEm_Welcome_resp_05232012

issue isn that it is not
http://www.test.com/?email = jjjanu@gmail.com&tid=RetEm_Welcome_resp_05232012

notice email = jjjanu@gmail.com

so I can't do $_GET['email']
how can I get the email address from the above string?

A:

Both examples given will not work with the desired $_GET['email'].
The first example, http://www.test.com/?jjjanu@gmail.com&tid=RetEm_Welcome_resp_05232012, has no "key" for the email address, so the only way to get it would be to iterate through each query-string parameter and either assume that a no-key value is an email address or do a regex-match on it. Something (very) basic would be:
$email = '';
foreach ($_GET as $key => $val) {
    if (strpos($key, '@') && ($val == '')) {
        // assume this is an email address
        $email = $key;
        break;
    }
}

The second example, http://www.test.com/?email = jjjanu@gmail.com&tid=RetEm_Welcome_resp_05232012, the space after the word "email" counts in the name. It could be retrieved with:
$email = $_GET['email '];
Is there a specific reason why a regular ?email=[email address] query-string won't work?


Q:

My husband wants to register as a UK citizen (born to a British mother in South Africa in 1964). Do we need her passport?

The documentation listed as acceptable on uk.gov is:
• Your passport; and
• Your full birth certificate (one which includes the name of your parent(s), (which
should be requested from the relevant authorities in your country of origin); and
• Your mother’s full birth certificate; and either
• Her certificate of naturalisation or registration as a citizen of the United Kingdom and Colonies (or, before 1 January 1949, as a British subject); or
• Papers showing her legal adoption; or
• Her expired citizen of the United Kingdom and Colonies passport.
The problem is, his mother died in 1979, when he was a teenager. Due to circumstances beyond his control, her birth certificate and passport are lost. I know we can order a copy of the birth certificate (hopefully as easy as paying the cost of it and shipping, or are there hoops to jump through?), and as she was born in the UK, I can't see her having any other naturalization or registration documents.
Her passport was thrown away by her husband's next wife, and so is unrecoverable. Can one order a copy of her passport, or do I need it if her birth certificate shows she was born in England? I don't see how they can expect people to have their parents' passports. What happens if their parents are dead? Do we really need her passport? Do we have a chance of making a successful application?

A:

Although the guidance doesn't specifically mention it, in my opinion, your mother's birth certificate showing that your mother was born in the UK before 1983 should be sufficient by itself. Her passport should not be necessary.
Anyone born in the UK before 1983 was automatically a Citizen of the United Kingdom and Colonies at birth with right of abode in the UK (which became "British citizen" in 1983). And since she was born in the UK, her connection to the UK was "otherwise than by descent", and so she would have been able to pass citizenship and right of abode onto you had women able to pass citizenship before 1983; therefore, you are eligible to register as a British citizen now.


Q:

How to add image and text into table

I am trying to make a 1x2 table and include a picture into one cell and some text into the other. I am not sure if I am doing this correctly or am missing something. But the image appears but the text doesn't...
HTML Code:

         This is a test

Thanks

A:

I would recommend using  instead of in case you want a paragraph or more since  is for a header in the table.
So it should be like this:

         This is a test


Q:

Print output until key pressed

This seems like a simple problem, but I can't seem to solve it. I need to print output (from a variable) to the console, until the user presses any key. The printing is done in a while loop as such:
int i;
while((i=input.read())!=-1){
  System.out.print((char)i);
}
input.close();

The problem is that the input stream never reaches it's end, only waits for more characters to come in, thus blocking any more code from executing. It will be quite obvious to the user when to stop the output, so I am fine with giving that responsibility to the user. It doesn't matter how the user tells the application to stop, as long as it is quick, (eg pressing space, enter, or any other specific key is fine).
Thanks in advance,
vikarjramun

A:

The first solution I came up with was threading the console input. The thread updates a variable accessable by the printing code so you can check it before each print statement.
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicBoolean;

public class RunUntilKeyPressed {
    static AtomicBoolean hasUserPressedKey = new AtomicBoolean(false);

    public static void main(String[] args) {

        Thread t = new Thread(() -> {
            Scanner scan = new Scanner(System.in);
            System.out.println(scan.next());
            hasUserPressedKey.set(true);
            scan.close();
        });
        t.start();

        while(!hasUserPressedKey.get()) {
           System.out.println(hasUserPressedKey);
        }
    }
}

This code will run until the user presses Any Key (except space) and Enter as that is when the scan.next() method gets input.


Q:

Where does the expression “spill the tea” come from?

According to Wiktionary, spill the tea (idiomatic, informal) means:

To disclose information, especially of a sensitive nature.

Apparently, the expression appears to be a recent one.

2012, Demetria L. Lucas, "Should I Worry That He Earns Less Money?", CARE, Issue #18, October 2012, page 18:

They are up in your business because you invited them in by spilling the tea on what you and your man earn.

And recently on YouTube, I read this comment

Can anyone tell me where it comes from? Is it British or American in origin?

A:

The expression appears to have originated in  American black drag culture:

It appears that T, also spelled tea, had a double-edged meaning in black drag culture. It could refer to a hidden truth, as Chablis uses it, and it could also refer to someone else's hidden truth—that is, gossip:

Straight life must be so boring. Because everyone conforms. These gay kids carry on. ... They give you dance and great tea [gossip].
  — "Nate" quoted in One of the Children: An Ethnography of Identity and Gay Black Men, William G. Hawkeswood, 1991

As drag culture—and particularly black drag culture—gained prominence, so too did this dual meaning use of tea. It's spread far beyond black drag culture at this point. The phrase "spill the tea," used as an encouragement to gossip, has been used in everything from Harlequin romance novels to "RuPaul's Drag Race"; "no tea, no shade" has been featured in explainers on black gay slang;  comedian Larry Wilmore used "weak tea" regularly on his 2015-16 Comedy Central show in response to people who weren't telling the absolute truth.

(Merriam-Webster)
The expression is American:
Spilling  tea (American Slang)

On the day that I was working on this video, I searched ‘spilling tea’ online and found that it was in the headlines.  “Rob Kardashian’s Instagram Is Disabled, But His Tea Spilling Continues On Twitter”.  Spilling tea means to gossip about someone.  So here, Kardashian was gossiping about his ex-fiance, which included posting naked pictures of her.  Not good.

(Rachel's English.com)


Q:

Why isn't this reassigning working

I have an arraylist called election(). Why isn't code this reassigning the name variable like it should.
private static void replaceName(String oldName, String newName){
    Candidate c;
    for(int i = 0;i<election().size();i++){
        c = election().get(i);
        if(c.name == oldName){
            election().get(0).name = newName;
            System.out.println(election().get(0).getName());
        }
    }
}

A:

You are incorrectly comparing strings in your if statement. Instead of c.name == oldName, it should be c.name.equals(oldName).
Also, you're assigning the new name to the wrong object.
Instead of elections.get(0).name = newName, it should be c.name = newName since c is a reference to the object stored in your ArrayList. Changes made to c will be reflected in your list. Your current code changes the name of the first candidate in your ArrayList, since you always call get() with 0 rather than i.


Q:

How to SELECT with all index of SUBSTRING_INDEX

I have a table like this
table foo1
+----+------------------------------+
| Id | Content                      |
+----+------------------------------+
| 1  | Hello World                  |
+----+------------------------------+
| 2  | Hello Users                  |
+----+------------------------------+
| 3  | This post submitted by users |
+----+------------------------------+
| 4  | C# Programming               |
+----+------------------------------+

I send a parameter to stored procedure like 'Hello,users,post'. I want to split parameter with comma(,) and get all rows which contains this indexes (Hello or users or post). If i send 'Hello,users' return table should be like this (contains hello or users)
+----+------------------------------+
| 1  | Hello World                  |
+----+------------------------------+
| 2  | Hello Users                  |
+----+------------------------------+
| 3  | This post submitted by users |
+----+------------------------------+

I have tried this query
SELECT
    *
FROM foo1
WHERE foo1.Content
LIKE CONCAT('%',SUBSTRING_INDEX('Hello, Users, Post', ',', 1),'%');

but it returns rows which contain just 'Hello'. Parameter's word is flexible. It can contains countless word. It can be 'Hello, post, users' or 'Hello' or 'Hello,post'. How can I solve this?
Thanks.

A:

Use the REGEXP function.
SELECT *
FROm foo1
WHERE foo1.Content REGEXP 'Hello|Users|Post';


Q:

How to search and export value with python and re?

I'm trying to export some value from the text to a txt file.
my text has this form:
"a='one' b='2' c='3' a='two' b='8' c='3'"

I want to export all the value of the key "a"
The result must be like
one
two

A:

The other answers are correct for your particular case, but I think a regex with lookbehind/lookahead is a more general solution, i.e.:
import re

text = "a='one' b='2' c='3' a='two' b='8' c='3'"

expr = r"(?<=a=')[^']*(?=')"

matches = re.findall(expr,text)
for m in matches:
    print m  ##or whatever

This will match for any expression between single quotes preceded by a=, i.e. a='xyz', a='my#1.abcd' and a='a=5%' will all match

A:

This regex is very easy to understand:
pattern = r"a='(.*?)'"

It doesn't use lookarounds (like (?<=a=')[^']*(?=') ) - so it's very simple ..
Whole program:
#!/usr/bin/python

import re

text = "a='one' b='2' c='3' a='two' b='8' c='3'"
pattern = r"a='(.*?)'"

for m in re.findall( pattern, text ):
  print m


Q:

Select all first elements with specific attribute value

On a form, I have to select all first  elements with a specific attribute value from all the list items present in the form. For instance, in the below code, I have to select  elements with the content xxx and zzz — or in other words, the first  element with data-role="modal" from all list items.

console.log($('ul li a[data-role="modal"]:first'));

    xxx
    yyy

    abc
    zzz
    xyz

The jQuery I tried is only selecting the one with xxx.

A:

You can use .find() to get all a elements with attribute data-role=modal in ul li and apply :eq to get first for each match:

$('ul li').find('a[data-role="modal"]:eq(0)').css('color', 'red');

    xxx
    yyy

    abc
    zzz
    xyz

References
.find()
:eq


Q:

Calculating distance to points in QGIS

Is there a way of calculating the distance to the nearest points in QGIS? In ArcGIS there is a function called Euclidean Distance, which can take an input vector or raster, and generate a raster of distances.

Is there a similar function in QGIS? I could not find one in the documentation. I did explore the Raster functions in QGIS, and also the Hub Distance calculation fromMMGIS (for a non-raster solution) but I was not able to figure out how do this using either. If a vector approach is the only solution, that could be fine also.

A:

First, rasterize your vector layer. You can do it using Rasterize under Raster menu.
Before rasterizing, I'd recommend to create an additional field and fill it with '1' and then select this field when rasterizing.
Second, Raster\Analysis\Proximity
Note that you should have GDALTools turned on in plugins.


Q:

Sphinx4 Speech Recognition from a video

Does Sphinx4 support Speech-to-Text processing on video files? If yes, Does it need JMF?
Is there any tutorials ??
I couldn't find anything, not in their forum, and nobody is responding in their IRC Channel!

A:

Does Sphinx4 support Speech-to-Text
  processing on video files?

Yes. There is no specifics of the video. You need to extract the audio track and pass it to recognizer.

If yes, Does it need JMF?

There could be different way to extract audio track from the video. It can be JMF or just mplayer

Is there any tutorials ??

http://cmusphinx.sourceforge.net/wiki/tutorial


Q:

Link to duplicate answer in 'marked as duplicate' section

Using your typical duplicate answer as a reference:

I think that the "has an answer" text of the duplicate section should either be linked to the duplicate answer.
Or, if that's untenable, clicking the "has an answer" text could cause the browser to scroll up to the "This question already has an answer here" box and highlight it or something like that.
Why?

Banner blindness is a real thing, and so some people might miss the block up top.
It's not intuitive to tell someone there's a link but have that link be somewhere else. Even if I know that I would need to scroll up from the "marked as duplicate" section to get to the duplicate link, that's just not good UX.
No real change in front end design other than wrapping three words with an anchor. Unless this would be a huge pain to implement on the back end, it's a minimal change with a big upside.

A:

I think this is a problem as well.
First, no one reads the answer before they read a question. So placement before the question text is counter intuitive. It asks users to back up, rewind,and look before the question for an answer.
The example used in this thread/question/answer is a simple one - easily viewable "above the fold" as it were. However, imagine a longer question which a user scrolls to read.... they get to the bottom, see it's marked as a duplicate.... then have no clue where the duplicate may be.
While not expressed in the best of ways, we had a user post a comment on meta.graphicdesign.stackexchange.com who was clearly frustrated by this very thing. I can imagine for the reason I've posted above.
Second, The placement of the duplicate link is positioned, and often colored, in a manner which promotes user blindness. I've found this true across all SE sites. It's visually a banner, and as such easily falls into the "content blindness" experience many users get while viewing any site.
Combine #1 and #2 above and it's completely disregarded by many new users more than it's noticed.
Sure, those who have experience with SE sites are used to it and know it's there and overcome the "banner blindness" consciously when we need to.
But that does not help new users.
The link should be moved, in my opinion, and be made visually more prominent.
After the question text, within the actual question, would be one of the optimum positions in my opinion.
Possible Example...

This would clearly allow the message and link to be seen after a user has read the question, which is when they are seeking the answer.
Even moving it below the tags, and above the "marked as" message would be better - provided it is visually different than the "marked as" message below it.

A:

It would be more intuitive if the duplicate would be listed in the lower banner.
I have prepared the following image showing where it would be, in my mind, the most intuitive. Now the sentence is complete in one place and it's still visible.

Obviously I didn't spend very long thinking of the idea so the real, or best, design might differ. The problem that has been solved is that it is no longer confusing having the data in 2 places at the same time. However, the closers could be possibly be less prominent.
Additional thoughts
The [duplicate] itself should probably also be a link. The text in the duplicate box instructing you to ask a new question should be different. It should instead say 'ask a new question that clearly clarifies how it's different' or something similar, with links to FAQ or instructions about research.

A:

For me, the word Duplicate itself should be the link itself to the question and the has an answer part should be linked to the accepted answer or the top answer of the original question to avoid confusion. That is just for better UX and user experience.
Like @joojaa, the bottom block should be a complete sentence:

Marked as duplicate of {insert link here} by so and so

This should be to avoid confusion and to make a more visual statement to other users. Now if we add the features suggested by me, the top block (just assume some other question is a duplicate of this one) would be like this:

This question already has an answer here:
Link to duplicate answer in 'marked as duplicate' section 3 answers

And the bottom one:

Marked as duplicate of Link to duplicate answer in 'marked as duplicate' section by so and so by so and so

Here is the offending code for the above text feature for the original one:

This question already has an answer here:

            New profile pages are out - bugs and feedback master list

                    75 answers

and the one for the bottom:

                    marked as duplicate by Al E., Infinite Recursion, tchrist, doppelgreener, Martijn Pieters Apr 17 '15 at 12:20

Now all we need is to change the above to add some links there and there and problem solved! (Question used is my own, which has been marked as duplicate)...
And if we edit this a little bit more, we can change this:

This question already has an answer here:

To this:

This question already <a href="<insert question link">has an answer here:

And this:
marked as duplicate by Al E., Infinite Recursion, tchrist, doppelgreener, Martijn Pieters Apr 17 '15 at 12:20

To this:
marked as duplicate of {insert question title here} by Al E., Infinite Recursion, tchrist, doppelgreener, Martijn Pieters Apr 17 '15 at 12:20

The above are examples but it should be how things should go applying the features and making BalusC satisfied...
EDIT: With the newer duplicate text at the bottom:

Specifically:

This question was marked as an exact duplicate of an existing question. If this question is different, please edit it to explain how it is different or ask a new question.

Instead of "an exact duplicate of an existing question", we can do "an exact duplicate of an existing question." So basically, something like this:

marked as duplicate by Sha Wiz Dow Ard, Nathan Tuggy, Werner, ale, MichaelT Jan 19 '16 at 23:02
This question was marked as an exact duplicate of an existing question. If this question is different, please edit it to explain how it is different or ask a new question.

and if in conjunction with previous statements:

Marked as duplicate of Link to duplicate answer in 'marked as duplicate' section by so and so by so and so on this date
This question was marked as an exact duplicate of an existing question. If this question is different, please edit it to explain how it is different or ask a new question.

if necessary. I support everything made before this edit and I do understand if adding the link in three different places might be too much. But I think the third link to the duplicate should help.


Q:

python subprocess "mount" does not prompt for password

I just learned subprocess.check_call() function today. I intend to use it to replace my os.system command.
Originally, I have my command as such:
os.system("mount -t cifs //source/share /mnt/share -o username=user")

The command above will prompt for password and it will mount the drive if the password is correct.
However, if I tried:
cmd_string="mount -t cifs //source/share /mnt/share -o username=user"

subprocess.check_call(cmd_string.split(" "), shell=True, stdin=sys.stdin)

It would not ask for password. Instead, it just print the partitions. It's like invoke "mount" command without parameters.
Any idea how I can use check_call and still receive interactive input from user?

A:

You are invoking mount without parameters.  If you specify shell=True, subprocess expects the entire command including arguments is passed to the shell as one big string.  If you specify shell=False (the default if not specified), the command and its arguments are passed as a list of strings, as you have done by using split. By mixing the two forms, you are effectively only passing the string mount as the command to be executed.   Either remove shell=True or remove the .split(" ").  The first choice is usually better unless there is some reason you need shell parsing to be involved, normally something to be avoided.


Q:

mysql Workbench - Error Code: 1267 inside a function

I have developed a function with an IF statement inside. The function works fine, until it gets inside the IF, where I get the error:
Error Code: 1267. Illegal mix of collations (utf8_bin,IMPLICIT) and (latin1_swedish_ci,NUMERIC) for operation '<=' .
If I suppress the '<=', everything works fine.
I check the collation of the tables and database, it is utf8_bin, so many advices already read did not work.
Any ideas?
CREATE DEFINER=`root`@`localhost` FUNCTION `mutare_interval`(v_id_inspectie INT(10), v_user varchar(100),new_start_time varchar(100), new_end_time varchar(100), new_date DATE) RETURNS varchar(100)
DETERMINISTIC
BEGIN

DECLARE v_mesaj VARCHAR(100);
DECLARE v_count VARCHAR(100);
DECLARE v_test VARCHAR(100);
DECLARE new_interval VARCHAR(100);
DECLARE old_start_time TIME;
DECLARE old_end_time TIME;
DECLARE old_date DATE;
DECLARE old_interval VARCHAR(100);
DECLARE old_user VARCHAR(100);

SET new_interval=concat ( left(new_start_time,5),'..',left(new_end_time,5),' ', new_date) COLLATE utf8_bin;

SELECT
    start_time, end_time , start_date , CONCAT(LEFT(old_start_time, 5),
            '..',
            LEFT(old_end_time, 5),
            ' ',
            old_date) ,user INTO old_start_time, old_end_time, old_date, old_interval,old_user
FROM
    calendar
WHERE
    id_inspectie = v_id_inspectie;

SELECT
    COUNT(*)
INTO v_count FROM
    calendar
WHERE
    user = v_user AND start_date = new_date
        AND (start_time<=new_end_time AND new_start_time<=end_time);

IF v_count=0 THEN

-- facem update in Calendar pentru ca avem loc

UPDATE calendar SET start_time=new_start_time, end_time=new_end_time, start_date=new_date, end_date=new_date, user=v_user,
start_date_time=CONCAT(new_date,' ',new_start_time), end_date_time=CONCAT(new_date,' ',new_end_time) WHERE id_inspectie=v_id_inspectie;

-- stergem intervalul vechi si cel nou in free time frames

DELETE FROM free_time_frames
WHERE
    user_name = v_user
    AND LEFT(datestart , 10) = old_date
    AND (time_start<=old_end_time  AND old_start_time<=time_end);

DELETE FROM free_time_frames
WHERE
    user_name = v_user
    AND LEFT(datestart , 10) = new_date
    AND (time_start <= new_end_time AND new_start_time <= time_end);

-- inserez intervale libere pe intervalul ramas liber (old)

INSERT INTO free_time_frames (interval_showv2,interval_show,id_activitate,durata_interval,time_start,time_end,datestart,
        dateend,dateendx,id,StartBreakLunch,EndBreakLunch,hh_name,wd,day_period,generation_time,user_name)
        SELECT interval_showv2,interval_show,id_activitate,durata_interval,time_start,time_end,datestart,
        dateend,dateendx,id,StartBreakLunch,EndBreakLunch,hh_name,wd,day_period,generation_time,  old_user
        FROM gth_ir.free_time_frames WHERE user_name='%ghost' AND LEFT(datestart,10)=old_date
        AND (time_start <= old_end_time AND old_start_time <= time_end);

SET v_mesaj='Intervalul a fost modificat! ';

ELSE

SET v_mesaj='Intervalul nu este eligibil! ';

END IF;
RETURN v_mesaj;
END

A:

The problem was that I had time values that were compared. As soon as I treated the time as seconds (TIME_TO_SEC(time value)), the error disappeared.
The correct code replaced all conditions where "<", ">", "=", "<=", "=>" operators where used in combination with time values with TIME_TO_SEC.
Example:
From:  AND (start_time<=new_end_time AND new_start_time<=end_time);
To:  AND (TIME_TO_SEC(start_time)<=TIME_TO_SEC(new_end_time) AND TIME_TO_SEC(new_start_time)<=TIME_TO_SEC(end_time));


Q:

compojure wrap-json-body not working

I'm using the below code to try and access some json input in a PUT request however what I get returned has :body {}, I'm not sure what I'm doing wrong?
(ns compliant-rest.handler
  (:use compojure.core ring.middleware.json)
  (:require [compojure.handler :as handler]
            [compojure.route :as route]
            [ring.util.response :refer [response]]
            [clojure.data.json :refer [json-str]]))

(defroutes app-routes
  (PUT "/searches" {body :params} (response body))
  (route/resources "/")
  (route/not-found "Not Found"))

(def app
  (-> (handler/site app-routes)
      (wrap-json-body)
      (wrap-json-response)))

(app {
      :request-method :put
      :uri "/searches"
      :content-type "application/json"
      :body (with-in-str (json-str {:field "value"}))
      })

;; {:status 200, :headers {"Content-Type" "application/json; charset=utf-8"}, :body "{}"}

Also, I'm new to Clojure/Lisp, any comments about my syntax and style would be appreciated.

A:

Two things stand out:
The unparsed request body is not supposed to be a string, but an InputStream. This means your test expression won't work as is.
wrap-json-body replaces (:body request) with a clojure data structure. It does not put anything in (:params request) or (:body (:params request)). You want wrap-json-params for that.

A:

Thanks to Joost and the comments I found there is a ring function ring.util.io.string-input-stream that does what I mistakenly thought with-in-str did.  Finally I had the following working:
(ns compliant-rest.handler
  (:use compojure.core ring.middleware.json)
  (:require [compojure.handler :as handler]
            [compojure.route :as route]
            [ring.util.response :refer [response]]
            [ring.util.io :refer [string-input-stream]]
            [clojure.data.json :refer [json-str]]))

(defroutes app-routes
  (PUT "/searches/:id" {params :params body :body}
       (response body))
  (route/resources "/")
  (route/not-found "Not Found"))

(def app
  (-> (handler/site app-routes)
      (wrap-json-body)
      (wrap-json-response)))

;; Example request
(app {
      :request-method :put
      :uri "/searches/1"
      :content-type "application/json"
      :body (string-input-stream (json-str {:key1 "val1"}))
      })
;; {:status 200, :headers {"Content-Type" "application/json; charset=utf-8"}, :body "{\"key1\":\"val1\"}"}

It's so awesome that I can just create a simple map and call my api's entry point without needing any sort of server or mocking.  I'm totally being pulled into this whole dynamic languages thing with Clojure, the repl and light table!


Q:

Extract a Node from XML based on KeyWord

The goal of my question is to take the URL of XML file and a Keyword (Name of a Node) from the user through a aspx Page.

If node has a Value then print the Value.
If node has child elements then print the set of Child Elements.
If node is Leaf Node print the Parent Node.

My XML File:-
     <document-metadata xmlns="http://breeze.macromedia.com/" version="1.0">
     <document-info>
         <title>Harry Potter</title>

         <author/>
         <keywords/>
         <thumbnail href="data/thumb/thumb_slide_000001.jpg"/>
         <view-link href="/Viewer.swf?slide={position}"/>
     </document-info>

         <title>Part 1</title>
         <content>XYZ</content>
         <related-content/>
         <thumbnail href="data/thumb/thumb_slide_000001.jpg"/>

         <title>Part 2</title>
         <content> PQRS</content>
         <related-content/>
         <thumbnail href="data/thumb/thumb_slide_000002.jpg"/>

     </document-info>
     </document-metadata>

My C# Code:-
public string XmlNodeFind(string xmlUrl, string keyword)
{
    XmlDocument xdoc = new XmlDocument();
    xdoc.Load(xmlUrl);
    try
    {
        XmlNodeList nodes = xdoc.GetElementsByTagName(keyword);
        string result = "";
        foreach (XmlNode node in nodes)
            result = OutputNode(node);
        return result;
    }
    catch(Exception e)
    {
        return "No Node Exists";
    }
}
public string OutputNode(XmlNode node)
{
    try
    {
        if (node.Value == null)
        {
            if (node.HasChildNodes)
            {
                XmlNodeList childern = node.ChildNodes;
                string str = "";
                foreach (XmlNode child in childern)
                    str = str + child.Name.ToString() + " <> ";
                //OutputNode(child);
            }
            else if (node.ParentNode != null)
            {
                return node.ParentNode.Name.ToString();
            }
            else
            {
                return node.Name.ToString();
            }
        }
        else
        {
            return node.Value.ToString();
        }
    }
    catch(Exception e)
    {
        return "Error Occured";
    }
    return node.Value.ToString();
}

The Problem with my code is that when I submit my URl of XML and Keyword through an aspx page the output is always "No Node Exists."
I read few posts ton extracting nodes based on Keywords and prior they were advises to check namespace. But my XML file is not the same always. The URL will change the XML file being used to check the node.
THIS IS FINAL CODE THAT I FIXED:-
public string XmlNodeFind(string xmlUrl, string keyword)
{
    XmlDocument xdoc = new XmlDocument();
    xdoc.Load(xmlUrl);
    XmlNodeList nodes = xdoc.GetElementsByTagName(keyword);
    string result = "";
    XmlNode node = nodes[0];
    if (node != null)
    {
            result = OutputNode(node);
            return result;
    }
    else
      return "Node Does Not Exist !!! Try with a Valid Node.";
}
public string OutputNode(XmlNode node)
{
    try
    {
        if (node.HasChildNodes && node.FirstChild.Name != "#text")
        {
            XmlNodeList childern = node.ChildNodes;
            string str = "Child Nodes are:-";
            foreach (XmlNode child in childern)
                str += "<" + child.Name + ">";
            return str;
        }
        else if ( node.OuterXml!=null && node.InnerText.ToString() != String.Empty)
            return node.InnerText.ToString();
        else if (node.ParentNode != null)
            return node.ParentNode.Name;
        else
            return node.Name;
    }
    catch(Exception e)
    {
        return "Error Occured : Try Again with New Input Set";
    }

}

A:

public string XmlNodeFind(string xmlUrl, string keyword)
{
    XmlDocument xdoc = new XmlDocument();
    xdoc.Load(xmlUrl);
    XmlNodeList nodes = xdoc.GetElementsByTagName(keyword);
    string result = "";
    XmlNode node = nodes[0];
    //result = node.LocalName + " - - " + node.Name + " - - " + node.NodeType + " - - " + node.OuterXml;
    //return result;
    //foreach (XmlNode node in nodes){
    if (node != null)
    {
            result = OutputNode(node);
            return result;
    }
    else
      return "Node Does Not Exist !!! Try with a Valid Node.";
}
public string OutputNode(XmlNode node)
{
    try
    {
        if (node.HasChildNodes && node.FirstChild.Name != "#text")
        {
            XmlNodeList childern = node.ChildNodes;
            string str = "Child Nodes are:-";
            foreach (XmlNode child in childern)
                str += "<" + child.Name + ">";
            return str;
        }
        else if ( node.OuterXml!=null && node.InnerText.ToString() != String.Empty)
        {
            return node.InnerText.ToString();
        }
        /*else if (node.OuterXml != "" && node.Value != null)
        {
            string result;
            result = node.LocalName + " - - " + node.Name + " - - " + node.NodeType + " - - " + node.OuterXml;
            return result;
        }*/
        else if (node.ParentNode != null)
            return node.ParentNode.Name;
        else
            return node.Name;

        /*
        if (node.OuterXml != "")
        {
            if (node.HasChildNodes && node.FirstChild.Name != "#text")
            {
                XmlNodeList childern = node.ChildNodes;
                string str = "Child Nodes are:-";
                foreach (XmlNode child in childern)
                    str += "<" + child.Name + ">";
                return str;
            }
            else
            {
                if (node.OuterXml == string.Empty)
                    return node.ParentNode.Name;
                else
                    return node.OuterXml;
                //return "Outer Xml null part";
                //return node.OuterXml;
            }
        }
        else
        {
            //return "Outer Xml null part";
            //string result;
            // = node.LocalName + " - - " + node.Name + " - - " + node.NodeType + " - - " + node.OuterXml;
            //return result;
            if (node.ParentNode != null)
            {
                string str = "Parent Node is :-";
                str += node.ParentNode.Name.ToString();
                return str;
            }
            else
                return node.Name;
            //return node.OuterXml;
        }
    */
    }
    catch(Exception e)
    {
        return "Error Occured : Try Again with New Input Set";
    }
}


Q:

Devops with Xamarin and hockeyapp

We are trying to implement devops with xamarin and hockeyapp. Basically we would like to automate the build process for all platforms(iOS,Android and Windows). When we have searched for this we can see that it goes with continuous delivery and integration. Means the build will be automatically pushed to HockeyApp after code checked in.
However, can we go in other way instead of CI/CD? Like through power shell script to automate the deployment.
How can we do this from VSTS ?

A:

You could use Jenkins for that, it has a Hockeyapp Plugin that allows you to upload your build to your users.
Here is a quick article about that: https://blog.entelect.co.za/view/9973/using-hockey-app-with-jenkins-for-continuous-mobile-app-deployment


Q:

OpenGL named textures not working

glBindTexture(GL_TEXTURE_2D, texidx);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 512, 512, 0, GL_RGBA, GL_FLOAT, texdata);

If texidx == 0 everything works perfectly, but if texidx != 0, or is generated using glGenTexture(&texidx,1), the eventual rendering shows just solid color (last glColor) instead of the texture. I've been debugging for over a day (glGetError shows no trouble) and am running out of ideas. Any thoughts? I can post more code as needed.
Setup code:
glEnable (GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

glEnable(GL_TEXTURE_2D);
glShadeModel(GL_SMOOTH);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

glDisable(GL_LIGHTING);

glClearColor(0.5,0.5,0.5,0);
glClearDepth(1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDisable(GL_COLOR_MATERIAL);

glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

A:

TexID can't be zero, that's the default texture or meaning no texture.
The problem is that the default OpenGL minification filter uses mipmaps, but a common error is not provide them, change the MIN/MAG filters to something usable, like GL_LINEAR or GL_NEAREST, and your texture will work.
More information (and other common errors) are discussed in http://www.opengl.org/wiki/Common_Mistakes#Creating_a_Texture


Q:

Compare RMSE between original and logged time series data

I have some time series data, both in the original form $y$ and in logged form $\log(y)$. I should compare the models generated by applying neural networks and find the best one.
How to decide which one is better since the two values are in different units?
Would it be useful to normalize the RMSEs over the standard deviation?

A:

If you are ultimately interested in $y$ (rather than $\log(y))$, then I would suggest transforming the fitted values of $\log(y)$ back to the original scale and calculating RMSE for them. (Note that simple exponentiation may or may not be a good idea; see Dave Giles' blog post "More on Prediction From Log-Linear Regressions" and paper by Bårdsen & Lütkepohl "Forecasting levels of log variables in vector autoregressions" (2011).) That should be directly comparable with the RMSE from the other model where the dependent variable is $y$.


Q:

Cross Browser Selection Range Library?

Does anyone know of any cross-browser user selection range libraries written in javascript?
I found a few jQuery plugins, (which quite frankly are too limiting and very buggy).
I would just like to know what you have found out there. Don't send me googling this again, (I've spent days working on all this). Hopefully, this can be where future programmers can find the answer.

A:

I've developed a cross-browser Range and selection library called Rangy. Its core is not dissimilar in concept to IERange but goes beyond it in terms of implementation of the DOM level 2 Range and HTML5 selection specifications, and also in terms of stability and workarounds for browser bugs. I think it's the best there is out there.
There are also extra modules for saving, restoring and serializing selections and applying CSS class to ranges and selections.
https://github.com/timdown/rangy
The following uses some Rangy extensions to Ranges to easily iterate over text nodes within a selection and surround each one:
function surroundSelectedText(templateElement){
    var range, sel = rangy.getSelection();
    var ranges = sel.getAllRanges();
    var textNodes, textNode, el, i, len, j, jLen;
    for (i = 0, len = ranges.length; i < len; ++i) {
        range = ranges[i];
        // If one or both of the range boundaries falls in the middle
        // of a text node, the following line splits the text node at the
        // boundary
        range.splitBoundaries();

        // The first parameter below is an array of valid nodeTypes
        // (in this case, text nodes only)
        textNodes = range.getNodes([3]);

        for (j = 0, jLen = textNodes.length; j < jLen; ++j) {
            textNode = textNodes[j];
            el = templateElement.cloneNode(false);
            textNode.parentNode.insertBefore(el, textNode);
            el.appendChild(textNode);
        }
    }
}

var span = document.createElement("span");
span.style.color = "green";
span.style.fontWeight = "bold";

surroundSelectedText(span);


Q:

Preposition "to" in "join (to) a noun"

Prepositions are the words that join a noun, pronoun or the noun phrases and make each sentence complete. However, learning preposition is little tricky and hence, students should be conscious while reading a book or other documents and check the usage of the preposition.
  (Medium)

Why is the preposition "to" not used in this sentence? Like this:

Prepositions are the words that join to a noun, pronoun or the noun phrases and make each sentence complete.

A:

I suspect the sentence was written by someone whose first language is not English. Use of the verb "join" in that way, reads a little oddly. But "join" used in this way as an intransitive verb does not demand "to". You join a club or society, a couple might be joined in matrimony. As a transitive verb, "to" is appropriate when identifying direct and indirect objects - I joined the wires to the light fitting.


Q:

xampp - linking to directory not in root

I have just installed xampp and would like to link to some dev websites on a separate(not c) drive.
Previously in IIS, I would add a virtual directory in the default website. How do I do the equivalent in xampp. Any pointers appreciated.

A:

Have a look at VHosts, or mod_alias.


Q:

Must Declare Scalar Variable?

Ok I'm having a hard time with this one, I've spent a couple days with google etc trying to figure out where I'm screwing up.
I'm extremely new to C# and what I'm doing is trying to grab the Customer_ID (Primary Key) From my SQL Server, add 1 to the value, then enter that as the next customer id.  If i Take out the part that adds the value to the Customer_ID field i get an error saying I can't insert a null value.  Any help would be greatly appreciated.
The error is:

Must declare the scalar variable "@custID".

Here is my code:
string firstName = fName.Text;
string lastName = lName.Text;
string address1 = address.Text;
string city = addressCity.Text;
string state = addressState.Text;
string zip1 = addressZip.Text;
string phoneNum = phone.Text;
string emailadd = custEmail.Text;
int finalCustID = 0;

SqlCommand getMaxCustID = new SqlCommand("SELECT MAX(Customer_ID) FROM dbo.Customers", Form1.sqlConnection);
getMaxCustID.Parameters.AddWithValue("@custID", finalCustID);
Int32 count = Convert.ToInt32(getMaxCustID.ExecuteScalar());
finalCustID = (int)count + 1;
//Int32 newCustID = count + 1;

SqlCommand saveRecord = new SqlCommand("INSERT INTO dbo.Customers (Customer_ID,First_Name, Last_Name, Customer_Address,City,St,Zip,Phone,Email)" + "Values (@custID'firstName','lastName','address1','city','state','zip1','phoneNum','emailadd')", Form1.sqlConnection);

Console.Write(" This is the final ID " + finalCustID + " \n");
try
{
    saveRecord.ExecuteNonQuery();
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
    Console.Write(saveRecord);
}

Here is what I ended up with.  I don't think it's the best but it's working properly.  Thanks all for the help:
        string firstName = fName.Text;
        string lastName = lName.Text;
        string address1 = address.Text;
        string city = addressCity.Text;
        string state = addressState.Text;
        string zip1 = addressZip.Text;
        string phoneNum = phone.Text;
        string emailadd = custEmail.Text;
        int finalCustID = 0;

        SqlCommand getMaxCustID = new SqlCommand("SELECT MAX(Customer_ID) FROM dbo.Customers", Form1.sqlConnection);
        //getMaxCustID.Parameters.AddWithValue("@custID", finalCustID);
        Int32 count = Convert.ToInt32(getMaxCustID.ExecuteScalar());
        finalCustID = (int)count + 1;
        //Int32 newCustID = count + 1;

        SqlCommand saveRecord = new SqlCommand("INSERT INTO dbo.Customers " + "(Customer_ID,First_Name, Last_Name, Customer_Address,City,St,Zip,Phone,Email)" + " Values (@custID,@fName,@lName,@address,@city,@state," + "@zip,@phoneNumber,@custEmail)", Form1.sqlConnection); ;
        Console.Write(" This is the final ID " + finalCustID + " \n");
        try
        {
            saveRecord.Parameters.AddWithValue("@custID", finalCustID);
            saveRecord.Parameters.AddWithValue("@fName", firstName);
            saveRecord.Parameters.AddWithValue("@lName", lastName);
            saveRecord.Parameters.AddWithValue("@address", address1);
            saveRecord.Parameters.AddWithValue("@city", city);
            saveRecord.Parameters.AddWithValue("@state", city);
            saveRecord.Parameters.AddWithValue("@zip", zip1);
            saveRecord.Parameters.AddWithValue("@phoneNumber", phoneNum);
            saveRecord.Parameters.AddWithValue("@custEmail", emailadd);

            saveRecord.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.Write(saveRecord);
        }

A:

You are adding parameter to the command but you haven't specified it in your command text at all.
SqlCommand getMaxCustID = new SqlCommand("SELECT MAX(Customer_ID) FROM dbo.Customers",
                                  Form1.sqlConnection);
//getMaxCustID.Parameters.AddWithValue("@custID", finalCustID); //Comment that out

Since you are not using your parameter @custID, you don't need to pass that to your command. Just comment that out or remove that line.
Later you are using the parameter @custID in yoru insert statement you need to add the parameter to that command object.
saveRecord.Parameters.AddWithValue("@custID", finalCustID);

(Thanks to @N55PEC), You are missing a comma between in your INSERT Command Text between your parameter and next value. It should be like:
NOTE: Additional formatting is used to keep the answer within the viewport.
SqlCommand saveRecord = new SqlCommand("INSERT INTO dbo.Customers " +
       "(Customer_ID,First_Name, Last_Name, Customer_Address,City,St,Zip,Phone,Email)" +
       " Values (@custID,'firstName','lastName','address1','city','state'," +
       "'zip1','phoneNum','emailadd')", Form1.sqlConnection);


Q:

C# Pairing HTML Tags to check if they are properly balanced

Thanks for the tip below
•   You need to go through the string one character at a time (for loop or while loop) When you hit a < you know you have hit a tag, so store the position of this character
•   Keep going (in a sub-loop, preferably) until you hit a >, that's your end marker
•   Now check the character immediately before the >. Is it /?
•   YES: Peek at the top of the stack. Is that string the same as the one between < and />?
If yes, pop that item and break out of the subloop (you found a match!).
If no, return false from the method - your work is done (the HTML is not valid).
•   NO: then push the whole string between < and > onto the stack and break out of this subloop, and continue the main loop.
As @seesharper suggested, turn the above into psuedocode then into C#.
Good luck on your journey learning to program!

A:

Your current code simply checks that "{open}" is complete, and that whatever the next tag is, is also complete, not that it is paired with its close tag.
You need to be operating with strings instead of characters.  You're going to read in "{open}" and "{/open}" and you need to operate on them.
Start by making a list of your use cases:

You start with a close tag - Work out how do identify it is a close tag, and then when you try to pop your empty stack you know it fails your check.
You start with an open tag - Work out how to identify it is an open tag, and then push it onto your stack.
You find a "complete tag" - one in this format "" - Work out how to identify this type of tag.  Do nothing with it, he does not need to be paired once identified correctly.
You encounter multiple open tags in succession.  push each onto the stack.
You encounter a close tag - determine if it is properly paired with the top element of the stack - pop and continue if they are properly paired - fail if they are not.
You encounter multiple close tags in succession.  Rinse and repeat 5 until tags do not match or you have an empty stack and an unmatched close.

You have a lot of good logic in your current code, but it needs to be expanded to properly perform the task assigned.
NOTE:  I have intentionally not provided code, but some logic to help you toward your solution because this is a homework assignment.  You will be working almost exclusively with 1) Reading a file.  2) Strings.  3) Stack.  Resources for syntax, properties, and methods of each are readily available should you need to look them up.
Also, I used the wrong braces because just tags weren't showing up and it was a quick edit.

A:

Here's my analysis of the problem (I'm not going to give you the code solution to the problem, as others have pointed out this defeats the purpose of this sort of exercise).  I'm also not dealing with inconsistently formatted (but still valid) HTML and open-close tag special cases such as <br />, which are common in real HTML:

You need to go through the string one character at a time (for loop
or while loop) When you hit a < you know you have hit a tag, so
store the position of this character
Keep going (in a sub-loop, preferably) until you hit a >, that's
your end marker
Now check the character immediately before the >.  Is it /?
YES: Peek at the top of the stack.  Is that string the same as the one between < and />?

If yes, pop that item and break out of the subloop (you found a
match!).
If no, return false from the method - your work is done
(the HTML is not valid).

NO: then push the whole string between < and > onto the stack and
break out of this subloop, and continue the main loop.

As @seesharper suggested, turn the above into psuedocode then into C#.
Good luck on your journey learning to program!


Q:

Items added to list are non-reactive in version 2 of Vue.js

In Vue 1.0 I used to add items to an array used in a v-for by simply calling items.push({}) as you can see here:
http://jsbin.com/figiluteni/1/edit?html,js,output
The exact same code in Vue 2.0 inserts a non-reactive object to the array:
http://jsbin.com/zuwihahiwa/1/edit?html,js,output
(Note that the newly added items are not live updated when edited)
    <button @click="items.push({})">Add item</button>

I know that Vue inserts hooks on arrays when initialized, but being a Vue model binding that creates the new item's "name" property, I thought it could be automatically hooked like in Vue 1.
I find this new behavior very inconvenient, for it forces me to add a prototype of the object I want to add in Vue's data and clone it:
http://jsbin.com/bamasobuti/1/edit?html,js,output
In Vue's data:
    item_prototype: {id: null, name: ""}

In the template:
    <button @click="items.push(_.clone(item_prototype))">Add item</button>

My question is:  Is there a recommended way of adding elements without having to keep a prototype of an empty element?

A:

According Vue's documentation, v-model="item.prop" is just syntactic sugar for:
v-bind:value="item.prop" v-on:input="item.prop = $event.target.value".
To make it work, just stop using
v-model="item.prop" and use this instead:
:value="item.prop" @input="$set(item,'prop',$event.target.value)"


Q:

How can I write to a text file using Oracle?

I have a select query in Oracle. I want to write query results in a txt file with CRLF (end of line) char. How can I do this?

A:

You can use the utl_file package.
Code fragment:
l_output        utl_file.file_type;
l_output := utl_file.fopen( p_dir, p_filename, 'w' );
utl_file.put(l_output, 'Hello' );
...
utl_file.new_line( l_output );
utl_file.fflush( l_output );
utl_file.fclose( l_output );

First of all create a directory object (the p_dir parameter of the fopen) and grant it read and write privileges.
See also at http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/u_file.htm


Q:

Cannot set default terminal to PowerShell 6.0

I am trying to set the default terminal in vscode to PowerShell 6.0. However, after restarting vscode, the following message appears and a terminal is not started.
ERROR  e.executable.toLowerCase is not a function

Here is the user settings override code I have tried using. NOTE: backslash path separators must be escaped.
vscode 1.18.1
PSVersion 6.0.0-rc
"C:\Program Files\PowerShell\6.0.0-rc\pwsh.exe"

{
    "window.zoomLevel": 1,
    "terminal.integrated.shell.windows": {
        "C:\\Program Files\\PowerShell\\6.0.0-rc\\pwsh.exe"
    }
}

A:

"terminal.integrated.env.windows" is not the correct property to use.
This works.
{
    "window.zoomLevel": 1,
    "terminal.integrated.shell.windows": "C:\\Program Files\\PowerShell\\6.0.0-rc\\pwsh.exe"
}

This also works.
{
    "window.zoomLevel": 1,
    "terminal.integrated.shell.windows":
        "C:/Program Files/PowerShell/6.0.0-rc/pwsh.exe"
}


Q:

Can't stop firing ASP.NET Module for static content

I have a module in an ASP.NET MVC application. The module is working fine, but it's firing for every type of file including static content even though I have:
<modules  runAllManagedModulesForAllRequests="false">
    <add name="MyModule" ... / >
</modules>

The module hooks AcquireRequestState and PostRequestHandlerExecute events and both show static content firing (.htm, .css, .png etc.).
I was under the impression that runAllManagedModulesForAllRequests="false" should keep modules from firing on non-ASP.NET content.
To clarify:
I can set preCondition="managedHandler" like this:
<add name="MyModule" type="MyApp.MyModule" preCondition="managedHandler" />

and get my module to fire only managed requests.
However, I'm trying to understand why the IIS pipeline in general is firing managed module hits for every request. I think this used to work just fine in older versions where unless runAllManagedModulesForAllRequests="true" it wasn't firing unmanaged content into ASP.NET modules.
Running on IIS8 on Windows 8 64 bit mode, with integrated pipeline mode.
Update:
After some more research it turns out that the following is true:

if runAllManagedModulesForAllRequests="true" all modules - regardless of their preCondition attribute setting fire on all requests. This also true for Application_XXXX events implement on the HttpApplication
runAllManagedModulesForAllRequests="false" has no effect of keeping unmanaged requests from hitting modules, unless preCondition="managedHandler" is set
runAllManagedModulesForAllRequests="false" does affect Application_XXXX events, causing those events to only fire on managed requests then. IOW, Application_XXXX behaves as if the 'module' implementation had a preCondition="managedHandler"

For more detailed information on this I posted a blog entry:
http://www.west-wind.com/weblog/posts/2012/Oct/25/Caveats-with-the-runAllManagedModulesForAllRequests-in-IIS-78

A:

In IIS7 Microsoft introduced a new way of developing modules and handlers by using managed (.NET) code, not just native code. Problem is switching a request between managed and native code is very expensive, so Microsoft introduced the preCondition="managedHandler". It flags the module as only available for managed content requests (.aspx, .asmx, ...) so IIS avoids firing it for static content.
Now, you can have a situation where you want to modify an static content request, such as minifying JavaScript on the fly. You can write the module using C# and compile it as a managed module, but you want it to be fired for static content, so you simply do not mark it as managedHandler.
Finally, runAllManagedModulesForAllRequests="true" is used to override preCondition="managedHandler" so all of them get fired.
There is more info available at:
http://www.iis.net/learn/get-started/introduction-to-iis/iis-modules-overview#Precondition


Q:

W2012R2 ISCSI MutualAuth: "Initiator CHAP secret given is invalid"

When trying to add a new iSCSI-TargetPortal using the New-IscsiTargetPortal command it simply refuses, telling me the password is not valid and has to be between 12 and 16 bytes.
my command:
New-IscsiTargetPortal -TargetPortalAddress "myServer.Domain.Forest" -AuthenticationType MUTUALCHAP -ChapUsername init -ChapSecret NNBGphGAWEYbDyyJ

This returns the following error:

New-IscsiTargetPortal : Initiator CHAP secret given is invalid. Maximum size of CHAP secret is 16 bytes. Minimum size is 12 bytes if IPSec is not used.
      + CategoryInfo          : NotSpecified: MSFT_iSCSITargetPortal:ROOT/Microsoft/...CSITargetPortal) [New-IscsiTargetPortal], CimException
      + FullyQualifiedErrorId : HRESULT 0xefff004c,New-IscsiTargetPortal

This when iSCSI target (also win2012R2) accepted the password without any issues, so I have no clue why it's throwing this error.

A:

As it turns out. CHAP is not required for discovery.
I did everything again, without the CHAP credentials for discovery and it all worked just fine.


Q:

Turning off Deprecation warnings in PHP.ini file WAMP

I am working on project @ home and using WAMP for development. Currently the php.ini file has the following lines set like this:
error_reporting = E_ALL & ~E_DEPRECATED
display_errors = On

I had hoped in doing so it would prevent deprecation warnings from showing up. However it is not. Is there a way I can adjust error_reporting to ignore deprecated warnings.
Output I am getting currently:

A:

You can use this function :
error_reporting(E_ALL ^ E_DEPRECATED);

http://www.php.net/manual/en/function.error-reporting.php
Or use "@" operator before function name.
@mysql_connect();

A:

In your php.ini file change the following.. (note wamp has 2 different php.ini files so make the changes on both)
from this
error_reporting = E_ALL

to this
error_reporting = E_ALL & ~E_DEPRECATED

A:

I had the same problem. It turned out however, that I edited wrong php.ini file. In my case the correct one was
C:\wamp64\bin\php\php5.6.25\phpForApache.ini
and in this file I have changed this line to:
error_reporting = E_ALL & ~E_DEPRECATED.
It didn't make any difference what I had changed in that "obvious" php.ini file.


Q:

How to find out if Android Studio is actually using the Intel HAXM accelerator?

I have Intel HAXM installed on my machine along with Atom image. When I fire-up emulator in Android Studio, don't see anything that would tell me if Intel HAXM is being utilized or not.
According to the screenshots on Intel's website, in Starting Android Emulation window in Eclipse, it show a message, informing that Intel HAXM is being utilized.

A:

If your emulator is running with HAXM, you'll see output like this in your run console in Android Studio, with the relevant line being the "HAX is working" bit:
Waiting for device.
/Users/sbarta/sdk/tools/emulator -avd x86-API10 -netspeed full -netdelay none

HAX is working and emulator runs in fast virt mode
Device connected: emulator-5554

Or, according to Intel's official Installation Instructions for Intel® Hardware Accelerated Execution Manager:

To verify that Intel HAXM is running, open a Command Prompt window with administrator privileges (Run as Administrator) and execute the following command:
sc query intelhaxm

If Intel HAXM is working, the command will show a status message indicating that the state is: "4 RUNNING".

A:

According to this page you can run the following:
$ ./sdk/emulator/emulator -accel-check

And if you see the following you have it installed:
accel:
0
HAXM version 6.0.3 (3) is installed and usable.
accel


Q:

Laravel Email Validation letting "user@hotmail" through

I am using Laravel's Validation through FormRequest. An extract of the code is here. It seems laravel's validation is letting email addresses like "user@hotmail" through.
namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class DirectorForm extends FormRequest
{
    public function rules()
    {
        return [
            'email' => 'required|email',
        ];
    }
}

it seems the above validation allows "username@hotmail", which isn't a valid email address.
Did i set it up wrongly

A:

Use the regex from: https://emailregex.com/
And combine with Laravel regex rule: https://laravel.com/docs/5.8/validation#rule-regex


Q:

What is a radio echo?

Simply that: what is a radio echo? And when it was first discovered?
By searching on Google I get results like Amazon Echo and Echo (radio station)

A:

When a pulse of radio waves strikes an object which is electrically conductive, a portion of the wave train bounces off the object and returns towards its original source. That portion of the wave pulse is referred to as the echo or the return. A search on RADAR will furnish a detailed explanation, including the history of this phenomenon.


Q:

Laravel Eloquent: how to get related records via whereHas() method?

For example, I can check every post with concrete date.
$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();

But suppose, what to do, if I want to compare a post model date (created_at) with the date attribute of user model?
For example:
$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', ** $user->customDate ** ← look this);
})->get();

upd.
I use Eloquent outside of Laravel.

A:

You can use a raw expression on the Eloquent sub query, by using $q->whereRaw.
In your example:
$users = User::whereHas('posts', function($q){
    $q->whereRaw("created_at >= users.customDate");
})->get();

Unlike DB::raw, this can be used without Laravel's dependency injection of Illuminate\Database facade.


Q:

angular-datetime-picker not work in modal

I inject a module call angular-datetime-picker into my Angular app.
This module is easy to use, as I only need to include js and css code in my index.html, then I can put
<input ng-model="$parent.date5" datetime-picker date-format="dd-MM-yyyy HH:mm" />

It working fine, but not in my modal. Below is my modal open scope:
$scope.addNewSchedule = function() {
      var dailog = $uibModal.open({
          templateUrl: 'app/partials/add-new-schedule.html',
          controller: addNewScheduleController,
          size: 'lg',
          scope: $scope
      });
    };

And of course, I have
<input ng-model="$parent.date5" datetime-picker date-format="dd-MM-yyyy HH:mm" />

in my add-new-schedule.html template, however, it not working. I'm sure I might just missout something simple and wish someone can advise me on this, many thanks~~~

A:

This is a common problem with modal. As z-index of modal is higher tha z-index of datepicker. So, just inspect the code, find the class used by modal, datepicker and adjust the z-index.
Keep z-index of datepicker higher.


Q:

Azure Web Jobs, Azure Service Bus Queue Trigger prevent message from getting deleted

I am looking into setting up a web job trigger to read message from service bus queue. What would be the best practice to implement a retry logic in case of any errors handling the downstream systems.
Would we be able to throw an exception so that the message will not be deleted from the queue and will be retried after certain time period?
Appreciate your feedback.

A:

You don't need to define retry logic explicitly. When the message is de-queued from service bus , it gets invisible from queue for certain time period (lock time default 30secs , you can configure it). You try to process the message , if it gets successful you simply call BrokeredMessage.CompleteAsync which means i am done and mark this message as completed. If you have some problem in down stream you can abandon the message by calling BrokeredMessage.AbandonAsync . This will unlock the message and the message appears back in the queue. The message will be picked up by the worker again and process it. Until you get successful or reach the max retry limit after which the message is send to dead letter queue.


Q:

SQLite Database Download From URl for Android

how can I download sqlite database from url for android? I have big one database.
For Example;
Someone first time open the app. Then my db file download from url to assets.

A:

You can not download a file in asset folder because this folder is bundled with the apk. That means its read only.
So you have two option in hand:

use getCacheDir() (on internal memory) or getExternalCacheDir() (on
SD card ) to download and retrieve your files.
Add your db file in asset folder before making the apk.


Q:

Why is there a lack of games for Linux?

What is wrong with the Linux/*nix family for games? What makes the development of games for this platform too slow compared to Windows or even OS X?

A:

What is wrong with the Linux/*nix
  family for games?

'Wrong' is a strong word, but I'll list a few things that hold games developers back from working on Linux.
Culture - Linux people tend more to believe software should be free - this isn't conducive to making a profit off selling your software. This may change in the future with online games being 'software as a service' in a sense.
Market share - The market share of Linux on the desktop has always been quite small. Now that the market share has finally crept up from 'negligible' to 'pitifully low' you could make a small argument for targetting that platform - if the previous point wasn't at all true, that is. This has also come a bit too late - the non-console game market is really quite small these days when you exclude MMOs.
Developer support - Microsoft have poured a lot of time and money into DirectX, and more recently into XNA. With one download, you had all the APIs and documentation you needed to make games. Linux has no central body to do this, nor even one single product that could be used instead. SDL doesn't do 3D graphics, OpenGL doesn't do anything but graphics, neither have had a very credible upgrade strategy in recent years, and there are a billion other libraries (many of which can be found on a list I maintain here) you can throw into the mix without any clear leaders. It's just a lot more hassle. On top of that a lot of leading middleware doesn't work on Linux, so instead of tried and tested code with paid support you have to consider using abandoned open source that's never been used in a shipped game.
OS support - Linux can do everything Windows does, but it certainly makes it hard sometimes. Sound support in particular is awful. Video support is awkward due to the legalities around codecs. Distribution of your binaries can be fiddly when you consider the different packaging types you need to support. All these things can be overcome if you know what you're doing, but most Windows developers won't know what they're doing with Linux so they aren't able to smoothly port their product to Linux.

A:

For game clients, it mostly has to do with culture, leading to difficult monetization strategies.
Servers for multiplayer games, on the other hand, have gotten a lot of traction for linux/nix, it is a very attractive platform for developing server technology.
There is hope that eventual release of Steam for Linux will help change that culture when it comes to clients, and provide developers and publishers a more monetarily viable platform for distributing games.

A:

Linux accounts for roughly 1% of total end users accessing the internet (OS Marketshare). It's usage increases significantly when talking about servers, but it's just not a big consumer OS.


Q:

Can't get ImagickDraw setStrokeOpactiy to work

I'm not sure if this is a bug, or my method.  I believe that the example below should show a red square with a barely visible (if at all) X across it.  What's actually happening is the X (made of two lines) is fully opaque.
<?php
$draw = new ImagickDraw();
$draw->setStrokeWidth(1);
$draw->setStrokeOpacity(0.1);
$draw->setStrokeColor("black");
$draw->line(0, 0, 500, 500);
$draw->line(500, 0, 0, 500);

$drawing = new Imagick();
$drawing->newImage(500, 500, "red");
$drawing->setImageFormat("png");
$drawing->drawImage($draw);

header("Content-Disposition: attachment; filename=test.png");
echo $drawing->getImageBlob();
?>

A:

There's two issues.
i) You also need to set the fill color for a line stroke, not just the stroke color. Lines are drawn with a fill width of 1 pixel.
ii) Setting the color overwrites the opacity, as the color 'black' has it's opacity set to fully opaque. Switching the order of the commands, stops the opacity being changed by the set color command.
i.e. the setStrokeOpacity modifies the strokes colour. It does not get batched up and modify the draw command.
<?php

$draw = new ImagickDraw();
$draw->setStrokeWidth(1);

$draw->setStrokeColor("black");
$draw->setStrokeOpacity(0.1);

$draw->setFillColor('black');
$draw->setfillopacity(0.1);

$draw->line(0, 0, 500, 500);
$draw->line(500, 0, 0, 500);

$drawing = new Imagick();
$drawing->newImage(500, 500, "red");
$drawing->setImageFormat("png");
$drawing->drawImage($draw);

header("Content-Disposition: attachment; filename=test.png");
//header("Content-Type: image/png");
echo $drawing->getImageBlob();


Q:

Trying to connect rails app to trello APi

I am trying to connect my rails app to the trello API. I have asked for tokens and secrets at
https://trello.com/app-key
I have installed the ruby gem 'ruby-trello' in my gemfile.
I need to generate a trello card with on submit of my contact form with the email submitted, the message's object and the message content. This is my create method in contact_controller.rb
def create
    @contact = Contact.new(contact_params)
    if @contact.save
      redirect_to root_path
      flash[:alert] = "Votre message a bien été envoyé à l'équipe TennisMatch, nous vous contacterons dans les plus brefs délais !"

        Trello.configure do |config|
          config.developer_public_key = ENV['PUBLIC_TRELLO_KEY']
          config.member_token = ENV['MEMBER_TRELLO_TOKEN']
        end
        me = Trello::Member.find("david_geismar")

      # find first board
      board = me.boards.first
      puts board.name
      # puts "Lists: #{board.lists.map {|x| x.name}.join(', ')}"
      # puts "Members: #{board.members.map {|x| x.full_name}.join(', ')}"
      board.cards.each do |card|
            puts "fu"
            # puts "-- Actions: #{card.actions.nil? ? 0 : card.actions.count}"
            # puts "-- Members: #{card.members.count}"
            # puts "-- Labels: #{card.labels.count}"
      end
    else
      render 'new'
    end
  end

my application.yml file looks like this:
development:
      PUBLIC_TRELLO_KEY: "******"
      MEMBER_TRELLO_TOKEN: "******"

But everytime I am submitting my contact form I get the error :
invalid token
here's the actual log:
Redirected to http://localhost:3000/
E, [2015-06-17T01:47:19.732876 #11385] ERROR -- : [401 GET https://api.trello.com/1/members/david_geismar]: invalid token
Completed 500 Internal Server Error in 475ms
Trello::Error - invalid token
:
  ruby-trello (1.2.1) lib/trello/client.rb:99:in invoke_verb'
  ruby-trello (1.2.1) lib/trello/client.rb:19:inget'
  ruby-trello (1.2.1) lib/trello/client.rb:44:in find'
  ruby-trello (1.2.1) lib/trello/member.rb:33:infind'
  app/controllers/contacts_controller.rb:14:in create'
  actionpack (4.2.0) lib/action_controller/metal/implicit_render.rb:4:insend_action'
  actionpack (4.2.0) lib/abstract_controller/base.rb:198:in process_action'
  actionpack (4.2.0) lib/action_controller/metal/rendering.rb:10:inprocess_action'
  actionpack (4.2.0) lib/abstract_controller/callbacks.rb:20:in block in process_action'
  activesupport (4.2.0) lib/active_support/callbacks.rb:117:incall'
  activesupport (4.2.0) lib/active_support/callbacks.rb:219:in block in halting_and_conditional'
  activesupport (4.2.0) lib/active_support/callbacks.rb:151:inblock in halting_and_conditional'
  activesupport (4.2.0) lib/active_support/callbacks.rb:151:in block in halting_and_conditional'
  activesupport (4.2.0) lib/active_support/callbacks.rb:234:inblock in halting'
  activesupport (4.2.0) lib/active_support/callbacks.rb:169:in block in halting'
  activesupport (4.2.0) lib/active_support/callbacks.rb:92:in_run_callbacks'
  activesupport (4.2.0) lib/active_support/callbacks.rb:734:in _run_process_action_callbacks'
  activesupport (4.2.0) lib/active_support/callbacks.rb:81:inrun_callbacks'
  actionpack (4.2.0) lib/abstract_controller/callbacks.rb:19:in process_action'
  actionpack (4.2.0) lib/action_controller/metal/rescue.rb:29:inprocess_action'
  actionpack (4.2.0) lib/action_controller/metal/instrumentation.rb:31:in block in process_action'
  activesupport (4.2.0) lib/active_support/notifications.rb:164:inblock in instrument'
  activesupport (4.2.0) lib/active_support/notifications/instrumenter.rb:20:in instrument'
  activesupport (4.2.0) lib/active_support/notifications.rb:164:ininstrument'
  actionpack (4.2.0) lib/action_controller/metal/instrumentation.rb:30:in process_action'
  actionpack (4.2.0) lib/action_controller/metal/params_wrapper.rb:250:inprocess_action'
  activerecord (4.2.0) lib/active_record/railties/controller_runtime.rb:18:in process_action'
  actionpack (4.2.0) lib/abstract_controller/base.rb:137:inprocess'
  actionview (4.2.0) lib/action_view/rendering.rb:30:in process'
  actionpack (4.2.0) lib/action_controller/metal.rb:195:indispatch'
  actionpack (4.2.0) lib/action_controller/metal/rack_delegation.rb:13:in dispatch'
  actionpack (4.2.0) lib/action_controller/metal.rb:236:inblock in action'
  actionpack (4.2.0) lib/action_dispatch/routing/route_set.rb:73:in dispatch'
  actionpack (4.2.0) lib/action_dispatch/routing/route_set.rb:42:inserve'
  actionpack (4.2.0) lib/action_dispatch/journey/router.rb:43:in block in serve'
  actionpack (4.2.0) lib/action_dispatch/journey/router.rb:30:inserve'
  actionpack (4.2.0) lib/action_dispatch/routing/route_set.rb:802:in call'
  omniauth (1.2.2) lib/omniauth/strategy.rb:186:incall!'
  omniauth (1.2.2) lib/omniauth/strategy.rb:164:in call'
  warden (1.2.3) lib/warden/manager.rb:35:inblock in call'
  warden (1.2.3) lib/warden/manager.rb:34:in call'
  rack (1.6.0) lib/rack/etag.rb:24:incall'
  rack (1.6.0) lib/rack/conditionalget.rb:38:in call'
  rack (1.6.0) lib/rack/head.rb:13:incall'
  actionpack (4.2.0) lib/action_dispatch/middleware/params_parser.rb:27:in call'
  actionpack (4.2.0) lib/action_dispatch/middleware/flash.rb:260:incall'
  rack (1.6.0) lib/rack/session/abstract/id.rb:225:in context'
  rack (1.6.0) lib/rack/session/abstract/id.rb:220:incall'
  actionpack (4.2.0) lib/action_dispatch/middleware/cookies.rb:560:in call'
  activerecord (4.2.0) lib/active_record/query_cache.rb:36:incall'
  activerecord (4.2.0) lib/active_record/connection_adapters/abstract/connection_pool.rb:647:in call'
  activerecord (4.2.0) lib/active_record/migration.rb:378:incall'
  actionpack (4.2.0) lib/action_dispatch/middleware/callbacks.rb:29:in block in call'
  activesupport (4.2.0) lib/active_support/callbacks.rb:88:in_run_callbacks'
  activesupport (4.2.0) lib/active_support/callbacks.rb:734:in _run_call_callbacks'
  activesupport (4.2.0) lib/active_support/callbacks.rb:81:inrun_callbacks'
  actionpack (4.2.0) lib/action_dispatch/middleware/callbacks.rb:27:in call'
  actionpack (4.2.0) lib/action_dispatch/middleware/reloader.rb:73:incall'
  actionpack (4.2.0) lib/action_dispatch/middleware/remote_ip.rb:78:in call'
  better_errors (2.1.1) lib/better_errors/middleware.rb:84:inprotected_app_call'
  better_errors (2.1.1) lib/better_errors/middleware.rb:79:in better_errors_call'
  better_errors (2.1.1) lib/better_errors/middleware.rb:57:incall'
  actionpack (4.2.0) lib/action_dispatch/middleware/debug_exceptions.rb:17:in call'
  actionpack (4.2.0) lib/action_dispatch/middleware/show_exceptions.rb:30:incall'
  railties (4.2.0) lib/rails/rack/logger.rb:38:in call_app'
  railties (4.2.0) lib/rails/rack/logger.rb:20:inblock in call'
  activesupport (4.2.0) lib/active_support/tagged_logging.rb:68:in block in tagged'
  activesupport (4.2.0) lib/active_support/tagged_logging.rb:26:intagged'
  activesupport (4.2.0) lib/active_support/tagged_logging.rb:68:in tagged'
  railties (4.2.0) lib/rails/rack/logger.rb:20:incall'
  quiet_assets (1.1.0) lib/quiet_assets.rb:27:in call_with_quiet_assets'
  actionpack (4.2.0) lib/action_dispatch/middleware/request_id.rb:21:incall'
  rack (1.6.0) lib/rack/methodoverride.rb:22:in call'
  rack (1.6.0) lib/rack/runtime.rb:18:incall'
  activesupport (4.2.0) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in call'
  rack (1.6.0) lib/rack/lock.rb:17:incall'
  actionpack (4.2.0) lib/action_dispatch/middleware/static.rb:113:in call'
  rack (1.6.0) lib/rack/sendfile.rb:113:incall'
  railties (4.2.0) lib/rails/engine.rb:518:in call'
  railties (4.2.0) lib/rails/application.rb:164:incall'
  rack (1.6.0) lib/rack/content_length.rb:15:in call'
  puma (2.11.1) lib/puma/server.rb:507:inhandle_request'
  puma (2.11.1) lib/puma/server.rb:375:in process_client'
  puma (2.11.1) lib/puma/server.rb:262:inblock in run'
  puma (2.11.1) lib/puma/thread_pool.rb:104:in `block in spawn_thread'

A:

You might not be using the correct member token.
The 'secret' displayed on your https://trello.com/app-key page is not a member token.
You can obtain a member token by authorizing your app in a browser and copying the returned string. Use the following URL:
https://trello.com/1/authorize?key=YOUR_API_KEY&scope=read%2Cwrite&name=APP_NAME&expiration=never&response_type=token

key = your developer API key
scope = read,write to give you full access
name = app name that appears in the authorization dialog, seems arbitrary
expiration = never so that you don't need to keep renewing, default is 30 days
response_type = token string that can be copied to your Rails config

The 'secret' is not used here at all. It seems to be only used for the oAuth method of authenticating.


Q:

Which loop has better performance? Increment or decrement?

Possible Duplicate:
Is it faster to count down than it is to count up?

which loop has better performance? I have learnt from some where that second is better. But want to know reason why.
  for(int i=0;i<=10;i++)
      {
               /*This is better ?*/
      }

  for(int i=10;i>=0;i--)
      {
               /*This is better ?*/
      }

A:

The second "may" be better, because it's easier to compare i with 0 than to compare i with 10 but I think you can use any one of these, because compiler will optimize them.

A:

I do not think there is much difference between the performance of both loops.
I suppose, it becomes a different situation when the loops look like this.
for(int i = 0; i < getMaximum(); i++)
{
}

for(int i = getMaximum() - 1; i >= 0; i--)
{
}

As the getMaximum() function is called once or multiple times (assuming it is not an inline function)

A:

Decrement loops down to zero can sometimes be faster if testing against zero is optimised in hardware. But it's a micro-optimisation, and you should profile to see whether it's really worth doing. The compiler will often make the optimisation for you, and given that the decrement loop is arguably a worse expression of intent, you're often better off just sticking with the 'normal' approach.


Q:

Adding RCT3 to Steam

I just found out that Roller Coaster Tycoon 3: Platinum was added to Steam. I bought the game years ago, and unfortunately lost the disk. Is there any way to add RCT3 to Steam w/o the disk?

A:

Roller Coaster Tycoon 3 cannot be added to steam through the activation key.  It must be purchased through Steam to activate it.
For a list of all the games that can be activated on steam, see here:
https://support.steampowered.com/kb_article.php?ref=7480-WUSF-3601#which
If you want to put the game on your Game library as a Non Steam Game, then follow these steps:
Launch Steam.
Click the Games menu, choose Add a Non-Steam Game to My Library.
Browse for games on your computer or put a check next to the game(s) you wish to add to the Library.
Click Add Selected Programs

https://support.steampowered.com/kb_article.php?ref=2219-YDJV-5557


Q:

identifying the input as local folder or s3 bucket

Source could be local folder or s3 bucket. How we can make input parameter to identify entered parameter as local folder or s3 bucket?

A:

s3 bucket is accessed using path style mentioned here:
https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html
You should write pattern check on your input to identify if the input is s3 bucket or bucket object.
Other way, if your input for local path is always going to exists on the system, then you can run path canonicalization commands and get absolute path of the local folder. e.g. on Unix you can run realpath() system api.
http://man7.org/linux/man-pages/man3/realpath.3.html
realpath() api will resolve to actual path only when the input path exists otherwise it returns the error. You can send your input to realpath command, if it passes, it is your local path on the system.


Q:

Why node.js is much slower than Google Chrome?

I've got simple code, that creates a chunk with 16*16*256 boxes of 10 elements array and a bool variable. Method tick increases array elements and changes boolean value for each box in a chunk 100 times.
By measuring time I've got the results:
Windows x64 node.js 7.4.0:
1 tick: 102.85
Total time(100): 10285
Google Chrome 55 on the same machine:
1 tick: 18.08
Total time(100): 1808
Even underlying snippet is an order of magnitude faster than a Node.
Snippet:
1 tick: 22.79
Total time(100): 2279
So, how can I make Node work faster?

(function(){
 class Box {
  constructor() {
   this.data = new Array(10);
   this.state = false;
  }

  tick() {
   this.state = !this.state;
   for(let i = 0; i < this.data.length; i++) {
    this.data[i]++;
   }
  }
 }

 class Chunk {
  constructor() {
   this.data = new Array(256);

   for(let z = 0; z < this.data.length; z++) {
    this.data[z] = new Array(16);

    for(let x = 0; x < this.data[z].length; x++) {
     this.data[z][x] = new Array(16);

     for(let y = 0; y < this.data[z][x].length; y++) {
      this.data[z][x][y] = new Box();
     }
    }
   }
  }

  tick() {
   for(let z = 0; z < this.data.length; z++) {
    for(let x = 0; x < this.data[z].length; x++) {
     for(let y = 0; y < this.data[z][x].length; y++) {
      this.data[z][x][y].tick();
     }
    }
   }
  }
 }

 var c = new Chunk();
 var count = 100;
 var start = new Date().getTime();

 for(let i = 0; i < count; i++) {
  c.tick();
 }

 var end = new Date().getTime();

 console.log("1 tick: " + (end - start) / count);
 console.log("Total time(" + count + "): " + (end - start));
})();

A:

Pre-filling the arrays gives an order of magnitude improvement in node
The only explanation I can give is that the "conversion" of an empty array slot to a "used" slot is more expensive in nodejs - you may find similar speed up by simply "filling" the array from length-1 to 0 in your original code (not quite as much but close)
The major speed up is the pre-fill of this.data in class Box (but that's probably because this.data[i]++ on an empty array item is used 655360 times)
(function(){
    class Box {
        constructor() {
            this.data = new Array(10).fill(0);
            this.state = false;
        }

        tick() {
            this.state = !this.state;
            for(let i = 0; i < this.data.length; i++) {
                this.data[i]++;
            }
        }
    }

    class Chunk {
        constructor() {
            this.data = new Array(256).fill(null);

            for(let z = 0; z < this.data.length; z++) {
                this.data[z] = new Array(16).fill(null);

                for(let x = 0; x < this.data[z].length; x++) {
                    this.data[z][x] = new Array(16).fill(null);

                    for(let y = 0; y < this.data[z][x].length; y++) {
                        this.data[z][x][y] = new Box();
                    }
                }
            }
        }

        tick() {
            for(let z = 0; z < this.data.length; z++) {
                for(let x = 0; x < this.data[z].length; x++) {
                    for(let y = 0; y < this.data[z][x].length; y++) {
                        this.data[z][x][y].tick();
                    }
                }
            }
        }
    }

    var c = new Chunk();
    var count = 100;
    var start = new Date().getTime();

    for(let i = 0; i < count; i++) {
        c.tick();
    }

    var end = new Date().getTime();

    console.log("1 tick: " + (end - start) / count);
    console.log("Total time(" + count + "): " + (end - start));
})();

as an aside, your Chunk constructor can be "simplified" to

this.data = new Array(256).fill([]).map(item => new Array(16).fill([]).map(item => new Array(16).fill([]).map(item => new Box())));

But this does not make any further improvement
I also tried using .forEach and/or .map where appropriate - but any such change actually slowed down the tick by about 10% in node


Q:

Detect if compositor is running

I want my UI to change design depending on whether the screen is composited (thus supporting certain effects) or not. Is it possible to

Reliably query whether the X server is running a compositing window manager
Get notified when compositing is switched on/off?

Solution:
To elaborate on Andrey Sidorov's correct answer for people not so familiar with the X11 API, this is the code for detecting a EWMH-compliant compositor:
int has_compositor(Display *dpy, int screen) {
    char prop_name[20];
    snprintf(prop_name, 20, "_NET_WM_CM_S%d", screen);
    Atom prop_atom = XInternAtom(dpy, prop_name, False);
    return XGetSelectionOwner(dpy, prop_atom) != None;
}

A:

EWMH-compliant compositors must acquire ownership of a selection named _NET_WM_CM_Sn, where n is the screen number
To track compositor you'll need to check if selection is _NET_WM_CM_S0 is owned by anyone (assuming you are on screen 0) using XGetSelectionOwner. If not owned, acquire ownership yourself and monitor SelectionClear events to detect when compositor is started.


Q:

gcc and clang throw "no matching function call" but msvc (cl) compiles and works as expected

I have written a small function template that joins different containers in a new container:
#include <vector>
#include <unordered_set>
#include <string>
#include <iostream>
#include <iterator>

namespace impl
{
    template <typename OutIterator, typename Container, typename ...Containers>
    void join(OutIterator iterator, const Container& container, const Containers& ...containers)
    {
        for (const auto& item : container)
            *iterator++ = item;

        join(iterator, containers...);  // gcc and clang cannot resolve this call
    }

    template <typename OutIterator, typename Container>
    void join(OutIterator iterator, const Container& container)
    {
        for (const auto& item : container)
            *iterator++ = item;
    }
}

template <typename OutContainer, typename ...Containers>
OutContainer join(const Containers& ...containers)
{
    OutContainer container;
    auto it = std::inserter(container, container.end());
    impl::join(it, containers...);
    return container;
}

int main()
{
    using namespace std;
    vector<string> a = {"one"s, "two"s, "three"s};
    unordered_set<string> b = {"four"s, "five"s };
    auto res = join<unordered_set<string>>(a, b);

    for (auto& i : res)
        cout << i << "\n";

    return 0;
}

Using MSVC (cl.exe) with /std:c++17 the code compiles and works just fine. But when compiling with clang-6.0 or gcc-7.3, a compiler error is thrown. I.e. gcc says
no matching function for call to 'join(std::insert_iterator<std::unordered_set<std::__cxx11::basic_string<char> > >&)'

So obviously a function with this signature is not defined. But I don't get why it tries to call such a function. Shouldn't it be resolved like this
// in main()
join<unordered_set<string>>(a, b);

unordered_set<string> join(const vector<string>& a, const unordered_set<string>& b);
void impl::join(std::insert_iterator<unordered_set<string>> iterator, const vector<string>& a, const unordered_set<string>& b);
void impl::join(std::insert_iterator<unordered_set<string>> iterator, const unordered_set<string>& b);

Why does gcc try to instantiate join(std::insert_iterator<std::unordered_set<std::__cxx11::basic_string<char>>>&) ?
Here is an example using the compiler explorer.

A:

gcc and clang are correct. MSVC still has issues with proper template name lookup (i.e. "two-phase lookup").
join, in join(iterator, containers...), is a dependent name. The candidates for finding that name are:

All names at the point of the template definition. This lookup just finds itself (the variadic overload), not the other overload (the 2-arg one), because it hasn't been declared yet.
All names that can be found by ADL on its arguments. None of those arguments have impl as an associated namespace, so that wouldn't find the other overload either.

In this situation, the fix is trivial: just reorder the two join() overloads. This ensures that the 2-arg join() will be found by that first bullet point.

Note that in C++17, you don't even need two overloads. Just one is fine:
template <typename OutIterator, typename Container, typename... Containers>
void join(OutIterator iterator, Container const& container, Container const&... containers) {
    for (auto const& item : container) {
        *iterator++ = item;
    }

    if constexpr(sizeof...(Containers) > 0) {
        join(iterator, containers...);
    }
}

Also consider using std::copy() instead of the loop. Which would actually allow:
template <typename OutIterator, typename... Containers>
void join(OutIterator iterator, Container const&... containers) {
    using std::begin;
    using std::end;
    (iterator = std::copy(begin(containers), end(containers), iterator), ...);
}


Q:

What difference does a polar protic solvent make in the addition of X2 to alkenes?

After the formation of the cyclic intermediate, $\mathrm{S}_{N}2$ reaction takes place. This reaction would be favored by an aprotic solvent.
How will the products of the reaction be affected if I use a polar protic solvent?
I think that the formation of the cyclic intermediate is independent of the solvent used but I can't figure out what would happen after that.

A:

In the presence of a polar protic solvent, the halogen will react with the solvent to form acids ($\ce{HX}$ and ${HOX}$).
$$\ce{Cl2 + H2O -> HCl + HOCl}$$
The high concentration of the cations formed (the hydrohalic acid and the hypohalous acid will exist as ions in a polar protic solvent) can act as electrophiles and initiate an electrophilic substitution reaction which results in the formation of a range of products.
$$\ce{CH2-CH=CH2 + X2 + H2O -> CH2-CH(Cl)-CH3 + CH2-CH(OH)-CH2(Cl) + CH2-CH(Cl)-CH3(Cl)}$$
This reaction is primarily initiated by the $\ce{H+}$ attacking the electron-rich double bond. This causes an electomeric shift of electrons to a carbon such that the carbocation formed is stable (Markonivkoff's rule). As carbocations are formed, rearrangements are possible. Not only are the mechanisms different, the products will be different too. This reaction is entirely different from a $SN_2$ reaction.


Q:

Google app engine Storage

I created an application that displays emergency numbers and allows the user to add their own emergency numbers to the list.
I also created a web application project to handle the server part of the app.
I can run it locally, but I need to store it globally on the GAE.
I am aware that I need an application ID, but how do I link my android application to that web application that I have deployed?
Do I need to insert the API key somewhere and switch on any services?
Its not creating my numbers now if I deploy so I know Im doing it wrong. Please please help.

A:

In the Api Console you need to enable the "Google Cloud Messaging For Android" service.
Then, In "API Access" tab, you need to add a Server Key, and an Android Key (actually two android keys - one for debug and one later for the released version - don't forget that!)
Then in the Endpoint classes you need to add the following to the @Api annotation:
clientIds - The Ids of the Android Client Keys
audiences - The "Client ID for web applications"
Which will eventually look like this:
@Api(name = "endpoint_name"
    clientIds = {"porject_number-android_debug_key.apps.googleusercontent.com",
                 "porject_number-android_release_key.apps.googleusercontent.com"},
    audiences = {"project_number.apps.googleusercontent.com"})

Above the class declaration.


Q:

How to Use lightning Locker Service in sandbox

I know how to configure security model through OWD, Sharing Rules, Profiles and Roles in salesforce sandbox account but how to use Lightning Security Locker Service instead of OWD, Sharing Rules...etc
I am new to Lightning Locker Service.  Can anybody help me on this.

A:

how to use Lightning Security LockerService instead of OWD, Sharing
  Rules...etc

locker service provides a secure layer when lightning components are built enabling component encapsulation and other security features. The current API version is 43 any component built after API version 40 will have locker service enabled. you dont have to do anything explicit to enable it.
OWD and sharing rules are used to control record access for a user,group. It has nothing to do with locker service.

A:

In general Lightning Locker Service is nothing you can enable/disable by yourself, it enforces enhanced security for Lightning Components automatically as long as you stick to the latest API version for your components.
So: if you don't have a good reason or just start with Lightning Components development go with the latest API version and enable all critical updates and you are ready to go.
More about Locker Service can be found here


Q:

how to pass an array of numbers with typescript and react

I'm using Types in React for the first time and I'm not very familiar with it.
I'm trying to add numbers from a form in a child component to an array of numbers.
Therefor I have created a useState hook:
const [valuesList, setValuesList] = useState<number[]>([]);

Now I'm trying to pass the setValuesList hook to the child component:
<AddNum
        setValues={setValuesList}
      />

In the child component I'm defining an interface for the props:
interface AppProps {
  setValues: (value: number) => void;
}

However when I try to call the setValues hook:
const addNumber = (value: string): undefined => {
const num = parseInt(value);
props.setValues((prevList) => prevList.concat(num));
return undefined;

};
I'm getting this error in the parent component:
/Users/acandael/Tutorials/react/add-nums/src/components/AddNum.tsx
TypeScript error in /Users/acandael/Tutorials/react/add-nums/src/components/AddNum.tsx(21,21):
Argument of type '(prevList: any) => any' is not assignable to parameter of type 'number[]'.
  Type '(prevList: any) => any' is missing the following properties from type 'number[]': pop, push, concat, join, and 27 more.  TS2345

    19 |   const addNumber = (value: string): undefined => {
    20 |     const num = parseInt(value);
  > 21 |     props.setValues((prevList) => prevList.concat(num));
       |                     ^
    22 |     return undefined;
    23 |   };
    24 |

Does anyone know how I can add numbers from a child component to an array of numbers in the parent component, and keep TypeScript happy?
Thanks for your help

A:

You are trying to change the state value of an array of numbers to a number by calling props.setValue(num).
Also the type definition for setValues in interface AppProps is incorrect. TS will infer the type of the setter function setValuesList as React.Dispatch<SetStateAction<number[]>> which is incompatible with the type (value: number) => void.
The correct definition for the setValues function would be if you want to pass the function setValuesList as props.
interface AppProps {
   setValues: React.Dispatch<SetStateAction<number[]>>

   // setValues: (numArr: number[]) => void  ( this will work as well )
}

The solution for updating the state value of valuesList would be to either use functional update or to create another callback function that receives a number as argument and updates the state.
With functional update
setValues(prev => prev.concat(num))

With setValues as a different callback function
// with this solution you don't need to modify the interface AppProps

interface AppProps {
   setValues: (num: number) => void
}

const Foo: React.FC<AppProps> = ({ setValues }) => {

  // component logic

  return (
   <>
   </>
  )
}

// in parent component
const [valuesList, setValuesList] = useState<number[]>([])

const updateWithNewValue = useCallback((num: number) => {
   setValuesList(prev => prev.concat(num))
}, [])

// pass the updateWithNewValue as props

<Foo setValues={updateWithNewValue}/>

A similar example in codesandbox


Q:

Is this theorem equivalent to "existential instantiation" rule?

In Enderton's, There is a theorem called "existential instantiation", it says:

Assume that the constant symbol $c$ does not occur in $\alpha ,\beta , \Gamma$ and that:
  $$ \Gamma\cup\{\alpha^x_c\}\vdash\beta$$
  Then
  $$\Gamma\cup\{\exists\alpha\}\vdash\beta$$

I've googled the name of the theorem but found that on Wikipedia here for example, It says something else namely, Given $\exists x\alpha$ we can infer $\alpha^x_c$ for some contant symbol $c$ that has not been used before in the deduction.
It seems that what wikipedia states is the converse of the EL theorems in Enderton's and I don't see how both forms coincede.
Could anyone clarify for me how they state the same fact?

A:

It is the existential elimination rule of Natural Deduction :

from $\Gamma, \varphi(y/x) \vdash \psi$, infer $\Gamma, \exists x \varphi \vdash \psi$, provided that $y$ is not free in $\psi$, or in any assumption in $\Gamma$.

The other rule of Natural Deduction for $\exists$ is the existential introduction rule :

from $\varphi(t)$, infer $\exists x \varphi(x)$

which in Enderton's system correspons to : $\vdash \alpha^x_t \rightarrow \exists \alpha$, that can be easily derived from Ax.2 : $\forall x \alpha \rightarrow \alpha^x_t$.

In order to understand Enderton's (apparent) "idiosyncratic" approach, we can see the very simple proof of Coroll.24H (Rule EI), page 124 :

Assume that the constant symbol $c$ does not occur in $\varphi, \psi$ or $\Gamma$, and that $\Gamma, \varphi^x_c \vdash \psi$.

By contraposition we have $\Gamma, \lnot \psi \vdash \lnot \varphi^x_c$ and by [previous result] we obtain : $\Gamma, \lnot \psi \vdash \forall \lnot \varphi^x_c$.
Applying contraposition again, we have the desired result.
"Informally", we can rephrase Enderton's proof as follows :

Assume $\Gamma$ and $\exists x \varphi$;
by Existential instantiation we have :

$\exists x \varphi \vdash \varphi^x_c$, where $c$ is an arbitrary constant symbol which does not occur in $\varphi, \psi$ or $\Gamma$.

By hypotheses :

$\Gamma, \varphi^x_c \vdash \psi$;

thus, we can conclude with :

$\Gamma, \exists x \varphi \vdash \psi$.

Why not ? The issue is that the rule :

from $\exists x \varphi$, infer $\varphi^x_c$, for a new constant $c$

is not part of Enderton's Deductive Calculus [see page 109-on].
Why so ? Because, without some "tricky" provisos this rule is not sound in Enderton's calculus.
Assume that we can add this rule to the system; then we can "manufacture" this simple derivation :
1) $\exists x \varphi(x)$ --- assumed
2) $\varphi^x_c$ --- from 1), with a new constant $c$ not occurring in it.
Thus, we have the derivation : $\exists x \varphi(x) \vdash \varphi^x_c$.
Then we apply to it :

Coroll.24G [page 124] : Assume that $\Gamma \vdash \varphi^x_c$, where the constant symbol $c$ does not occur in $\Gamma$ or in $\varphi$. Then $\Gamma \vdash \forall x \varphi$, and there is a deduction of $\forall x \varphi$ from $\Gamma$ in which $c$ does not occur

with $\Gamma = \{ \exists x \varphi(x) \}$, and we have a new derivation :

$\exists x \varphi(x) \vdash \forall x \varphi$.

Finally apply the Deduction Th to get :

$\vdash \exists x \varphi(x) \rightarrow \forall x \varphi$.

But this formula is clearly invalid; consider its arithmetical instance : $\exists x(x \ne 0) \rightarrow \forall x(x \ne 0)$.