text:
Q: Emacs cond, possible to have things happen between clauses? I programmed some months ago some code with a lot of if statements. If region-active-p, if beginning-of-line, those kind of things.
Having learned about the cond lisp, I was wondering if I could improve my code a lot.
The problem is that this cond is only doing things when "true" as far as I see it, while I actually need the move back-to-indentation in between these checks.
In order to properly skip the last clause, I even have to set variable values.
(defun uncomment-mode-specific ()
  "Uncomment region OR uncomment beginning of line comment OR uncomment end"
  (interactive)
  (let ((scvar 0) (scskipvar 0))
    (save-excursion
      (if (region-active-p)
         (progn (uncomment-region (region-beginning) (region-end))
         (setq scskipvar 1))
        (back-to-indentation))   ; this is that "else" part that doesn't fit in cond

      (while (string= (byte-to-string (following-char)) comment-start)
       (delete-char 1)
       (setq scskipvar 1))
      (indent-for-tab-command)

      (when (= scskipvar 0)
         (search-forward comment-start nil t)
         (backward-char 1)
         (kill-line))
    )))
)

So basically my question is, I would kind of like to have some consequences of not giving "true" to a clause, before the check of another clause. Is this possible? If not, what would be the best thing to do?
EDIT: Since we are using this as the example case for a solution, I wrote it down so it is easier to understand.
If region is active, remove comments from region. If not, move point to intendation.
For as long as the following character is a comment character, delete it. Afterwards, indent this line.
If it didn't do any of the above, search forward for a comment character, and kill that line.

A: (defmacro fcond (&rest body)
  (labels ((%substitute-last-or-fail
            (new old seq)
            (loop for elt on seq
                  nconc
                  (if (eql (car elt) old)
                      (when (cdr elt)
                        (error "`%S' must be the last experssion in the clause"
                               (car elt)))
                    (list new)
                    (list (car elt))))))
    (loop with matched = (gensym)
          with catcher = (gensym)
          for (head . rest) in body
          collect
          `(when (or ,head ,matched)
             (setq ,matched t)
             ,@(%substitute-last-or-fail `(throw ',catcher nil) 'return rest))
          into clauses
          finally
          (return `(let (,matched) (catch ',catcher ,@clauses))))))

(macroexpand '(fcond
               ((= 1 2) (message "1 = 2"))
               ((= 1 1) (message "1 = 1"))
               ((= 1 3) (message "1 = 3") return)
               ((= 1 4) (message "1 = 4"))))
(let (G36434)
  (catch (quote G36435)
    (when (or (= 1 2) G36434)
      (setq G36434 t)
      (message "1 = 2"))
    (when (or (= 1 1) G36434)
      (setq G36434 t)
      (message "1 = 1"))
    (when (or (= 1 3) G36434)
      (setq G36434 t)
      (message "1 = 3")
      (throw (quote G36435) nil))
    (when (or (= 1 4) G36434)
      (setq G36434 t)
      (message "1 = 4"))))

Here's something quick to do, what I think you may be after, i.e. something that would mimic the behaviour switch in C.
The idea is that all clauses are tested sequentially for equality, and if one matches, then all following clauses are executed, until the return keyword (it would be break in C, but Lisp uses return for the similar purpose in the loop, so I thought that return would be better). The code above thus will print:
1 = 1
1 = 3

Technically, this is not how switch works in C, but it will produce the same effect.
One thing I did here for simplicity, which you want to avoid / solve differently - the use of return keyword, you probably want to impose stricter rules on how it should be searched for.

A: (defun delete-on-this-line (regex)
  (replace-regexp regex "" nil (line-beginning-position) (line-end-position)))

(defun delete-leading-comment-chars ()
  (delete-on-this-line (eval `(rx bol (* space) (group (+ ,comment-start))))))

(defun delete-trailing-comment-chars ()
  (delete-on-this-line (eval `(rx (group (+ ,comment-end)) (* space) eol))))

(defun delete-trailing-comment ()
  (delete-on-this-line (eval `(rx (group (+ ,comment-start) (* anything) eol)))))

(defun uncomment-dwim ()
  (interactive)
  (save-excursion
    (if (region-active-p)
        (uncomment-region (region-beginning) (region-end))
      (or (delete-leading-comment-chars)
          (delete-trailing-comment-chars)
          (delete-trailing-comment)))))

Edit: A little explanation:
It's a lot easier to do regex replacements than manage loops to do deletion, so that gets rid of the state. And the steps are all mutually exclusive, so you can just use or for each option.
The rx macro is a little DSL that compiles down to valid regexes, and it's also amenable to lispy syntax transforms, so I can dynamically build a regex using the comment chars for the current mode.

A: cond
Cond evaluates a series of conditions in a list, each item in a list can be a condition, and then executable instructions.
The example in the Emacs Lisp manual is adequate to demonstrate how it works, I've annotated it here to help you understand how it works.
  (cond ((numberp x) x) ;; is x a number? return x
        ((stringp x) x) ;; is x a string? return x
        ((bufferp x) ;; is x a buffer?
         (setq temporary-hack x) ;; set temporary-hack to buffer x
         (buffer-name x))        ;; return the buffer-name for buffer x
        ((symbolp x) (symbol-value x))) ;; is x a symbol? return the value of x

Each part of the condition can be evaluated any way you like, the fact x above is in each condition is coincidental.
For example:
 (cond ((eq 1 2) "Omg equality borked!") ;; Will never be true
       (t "default")) ;; always true

So comparisons with switch are a bit limited, it's essentially a list of if statements, that executes/returns the first true condition's body list.
Hopefully this helps you understand cond a bit better.
 (cond (condition body ... ) ;; execute body of 1st passing
       (condition body ... ) ;; condition and return result
       (condition body ... ) ;; of the final evaluation.
       ;; etc
 )

OR
You can do things similar to switch with OR, depending on how you structure the code.
This isn't functional style, because it relies on side-effects to do what you want, then returns a boolean value for flow control, here's an example in pseudo lisp.
(or)
(or
     (lambda() (do something)
            (evaluate t or nil) ; nil to continue; t to quit.
     )
     (lambda() (do something)
            (evaluate t or nil) ; nil to continue; t to quit.
     )
     (lambda() (do something)
            (evaluate t or nil) ; nil to continue; t to quit.
     )
     (lambda() (do something)
            (evaluate t or nil) ; nil to continue; t to quit.
     )
)

Here's working example of a switch like structure using or
(or
 (when (= 1 1)
   (progn
   (insert "hello\n")
           nil))
 (when (= 1 2)  ;; condition fails.
   (progn
   (insert "hello\n")
           nil)) ;; returns false (nil)
 (when (= 1 1)
   (progn
   (insert "hello\n")
           t)) ;; returns true, so we bail.
 (when (= 1 1)
   (progn
   (insert "hello\n")
           nil))
)

Inserts :
hello
hello

(and)
The and operator (not just in Lisp) is also very useful, instead of evaluating everything until true, it evaluates conditions that are true, until a false is evaluated.
Both or & and can be used to build useful logic trees.

A: This is how I did it now according to Chris' idea that breaking it down into seperate functions would make it easier.
EDIT: Now also applied the or knowledge gained in this thread gained from Slomojo (no more variables!)
(defun sc-uncomment ()
  (interactive)
  (or
   (if (region-active-p)
     (uncomment-region (region-beginning) (region-end))
    (back-to-indentation)
    nil)
   (if (string= (byte-to-string (following-char)) comment-start)
     (sc-check-start)
    (sc-end))))

(defun sc-check-start ()
  (interactive)
  (while (string= (byte-to-string (following-char)) comment-start)
    (delete-char 1))
)

(defun sc-end ()
  (interactive)
  (search-forward comment-start nil t)
  (backward-char 1)
  (kill-line))
)


text:
Q: Is this html necessary at all? <link rel="shortcut icon" href="/favicon.ico">
<link rel="Bookmark" href="/favicon.ico">

I saw it somewhere,but is <link rel="Bookmark".. necessary?

A: This is the cross-browser way of adding favicons:
<link rel="icon" href="/favicon.ico" />
<link rel="Shortcut Icon" href="/favicon.ico" type="image/x-icon" />

the icon file itself would preferably be 16x16 pixels and in gif format (IE6 wont use transparent png) and under 500 bytes. Though most modern browsers now accept practically anything, though of course it will be your bandwidth and their waiting.
i googled  for a page stating this.
link
as cletus mentions, the Bookmark link is not for favicon and the code you provided is actually wrong.
EDIT: the favicon link does not influence your bookmarking itself, yet it helps the browser store a little icon on the tabs or your browser's bookmarks' menu. StackOverflow uses this icon.
But Is It necessary? If your icon is located at /favicon.ico, no it is not absolutely critical at all. Most browsers check that path by default, but if you like me put your favicon in a directory like /images/favicon.ico you would need to tell the browser to get it from there or your server will build up alot of 404-Not Found errors in its log. Which will slow things down (a bit). Also you might want to have different icons for different directories etc.

A: That bookmark link is incorrect. It should be:
<link rel="bookmark" href="http://my.site.com/some/path/permalink.html">

ie a perma-link and not the icon. See 6.12 Link types from the HTML 4.01 specification:

Bookmark Refers to a bookmark. A bookmark is a link to a key entry
  point within an extended document. The
  title attribute may be used, for
  example, to label the bookmark. Note
  that several bookmarks may be defined
  in each document.

A: This is a crossbrowser way to make sure the browser knows where your favicon is located for both viewing the page and bookmarking the page. Chances are, if you don't know what that code is, you don't have a favicon. The easiest way to make on is to make a 16x16px gif and change its extension to '.ico' - then you'll get your little icon in the corner of the browser bar (depending on your browser).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deprecated attempt to access property 'userAgent' on a non-Navigator object I am developing an app with ionic, cordova 4.3, angular and firebase.
When i run my app on ios i get always those two messages:
Deprecated attempt to access property 'userAgent' on a non-Navigator object.
Deprecated attempt to access property 'language' on a non-Navigator object.

I have read around and cordova should have solved the problem with the 3.7 version but it doesn't look like that.
I think the second one is when i try to read the language of the browser but i don't understand the first one.
Thanks

A: I think 3.7 fixed it for iOS 7, but then it didn't "Stay Fixed" on iOS8. Seems like it doesn't effect execution, so the word on the street is that everyone is ignoring it.  Doesn't seem like an answer, I agree, but just my two cents.


text:
Q: Bitcast requires both operands to be pointer or neither error with Swift compiler I had a terrible error with Swift and I didn't find any help on Google despite a lot of researches.

Bitcast requires both operands to be pointer or neither   %116 =
  bitcast i8* %115 to %SS, !dbg !249 Invalid operand types for ICmp
  instruction   %117 = icmp ne %SS %116, null, !dbg !249 PHI nodes must
  have at least one entry.  If the block is dead, the PHI should be
  removed!   %120 = phi i32  PHI node operands are not the same type as
  the result!   %119 = phi i8* [ %116, %108 ] LLVM ERROR: Broken
  function found, compilation aborted!

I really didn't know where this error occured because after some refactoring, I made changes in a lot of file.
I decided to create a post in Q&A-style to help other developers to find what this error means.
Hope it helps !

A: After I commented/de-commented all the code of my project during hours, I finally found the line which causes the error posted in my original post.
class LoginAccountViewController : UIViewController
{
    @IBOutlet var loginFacebook : UIButton?
    @IBOutlet var emailField : UITextField?

    override func viewDidLoad()
    {
        super.viewDidLoad()
    }

    override func viewWillAppear(animated: Bool)
    {
        super.viewWillAppear(animated)
    }

    @IBAction func loginEmail(sender: AnyObject)
    {
        if let emailAddress = emailField?.text as? String // THIS IS THE BAD LINE
        {
        }
    }
}

The error was that I tried to make an unwrap downcast to an attribute named text which is not optional, because of the object which contains the attribute is optional. This was a big mistake.
The good solution was to make an unwrap downcast to the emailField attribute and then, the text attribute doesn't need to be unwrapped to access to its value.
if let emailAddress = emailField as? UITextField
{
    println(emailAddress.text)
}

A: I had this issue once. Suddenly I fixed it when I replaced line (skipBtn is an UIButton)
skipBtn.setTitleColor(.whiteColor(), forState: .Normal)

with
skipBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)

I don't know why but it seems to me that this feature when you remove extra class name is not supported for 100% yet.


text:
Q: Amazon CloudFront CORS specific delay I am experiencing a delay between the serving of CORS requests but direct requests are served fine. I am using this to distribute media streams via HTTP so it is very important to reduce the startup delay.
There is approximately 90-180 seconds between when a media manifest is available via the CloudFront distribution (via a direct request from the browser or curl) and when the CORS requests from the player on our website return success. I have enabled OPTIONS request forwarding in the CloudFront distribution and have included the results of an OPTIONS request too. I have included the result of a curl request and the corresponding result from the network tab from Chrome Dev tools below. Note that these requests were made from the same client within 15 seconds of each other (the curl request was sent first).
=== CURL request ===
*   Trying 54.192.135.101...
* Connected to <exampleDistributionID>.cloudfront.net (1.1.1.1) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /opt/local/share/curl/curl-ca-bundle.crt
  CApath: none
* TLSv1.2 (OUT), TLS header, Certificate Status (22):
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Client hello (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS change cipher, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server accepted to use http/1.1
* Server certificate:
*    subject: C=US; ST=Washington; L=Seattle; O=Amazon.com, Inc.; CN=*.cloudfront.net
*    start date: Sep 17 00:00:00 2015 GMT
*    expire date: Dec 15 23:59:59 2016 GMT
*    subjectAltName: <exampleDistributionID>.cloudfront.net matched
*    issuer: C=US; O=Symantec Corporation; OU=Symantec Trust Network; CN=Symantec Class 3 Secure Server CA - G4
*    SSL certificate verify ok.
> GET /path/to/manifest/stream.m3u8 HTTP/1.1
> Host: <exampleDistributionID>.cloudfront.net
> User-Agent: curl/7.47.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/vnd.apple.mpegurl
< Content-Length: 1435
< Connection: keep-alive
< Server: nginx/1.9.10
< Date: Sun, 17 Apr 2016 00:26:06 GMT
< Last-Modified: Sun, 17 Apr 2016 00:26:05 GMT
< ETag: "5712d81d-59b"
< Cache-Control: no-cache
< Access-Control-Allow-Origin: *
< Accept-Ranges: bytes
< X-Cache: Miss from cloudfront
< Via: 1.1 f687c6e8ce478528ab87681ac35779ab.cloudfront.net (CloudFront)
< X-Amz-Cf-Id: P01_dDWZRWZ0lzAqROqOMnaipstK484vPWnicw3F0kcG_7elxBGNkQ==

<...Content of stream.m3u8...>

===Chrome Request===
Screenshot of the Chrome Dev tools network tab showing the 404 error received
===OPTIONS Request===
*   Trying 1.1.1.1...
* Connected to <exampleDistributionID>.cloudfront.net (1.1.1.1) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /opt/local/share/curl/curl-ca-bundle.crt
  CApath: none
* TLSv1.2 (OUT), TLS header, Certificate Status (22):
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Client hello (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS change cipher, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server accepted to use http/1.1
* Server certificate:
*    subject: C=US; ST=Washington; L=Seattle; O=Amazon.com, Inc.; CN=*.cloudfront.net
*    start date: Sep 17 00:00:00 2015 GMT
*    expire date: Dec 15 23:59:59 2016 GMT
*    subjectAltName: <exampleDistributionID>.cloudfront.net matched
*    issuer: C=US; O=Symantec Corporation; OU=Symantec Trust Network; CN=Symantec Class 3 Secure Server CA - G4
*    SSL certificate verify ok.
> OPTIONS /path/to/manifest/stream.m3u8 HTTP/1.1
> Host: <exampleDistributionID>.cloudfront.net
> User-Agent: curl/7.47.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: text/plain
< Content-Length: 0
< Connection: keep-alive
< Server: nginx/1.9.10
< Date: Sun, 17 Apr 2016 22:05:15 GMT
< Access-Control-Allow-Origin: http://my.origin.com
< Access-Control-Allow-Methods: GET, OPTIONS
< Access-Control-Allow-Headers: Authorization
< Access-Control-Allow-Credentials: true
< X-Cache: Miss from cloudfront
< Via: 1.1 ed2825b48bb51b4febd93a82e71f7ed9.cloudfront.net (CloudFront)
< X-Amz-Cf-Id: WY-KPfTlNTenTjWyYF9GS4ikyrGMQONAm4mXpbuKpHzfBk_xKfxG2w==
<
* Connection #0 to host <exampleDistributionID>.cloudfront.net left intact

At a loss to see the error in my config, any help would be greatly appreciated.

A: CloudFront tries to protect the origin server from unnecessary requests for unavailable objects by caching error responses for 5 minutes, by default.
It seemed apparent from the question that the most likely explanation would be that the object was being requested (for whatever reason) before it actually existed, and the error response was being cached for a few minutes, leading to what appeared to be a "delay" in the object's availability.  But CloudFront has no propagation delays, because CloudFront is a pull-through cache -- there's nothing to propagate.
Your curl test appears to succeed, but fails to actually prove anything, apparently because (among other potential reasons) you didn't include an Origin: header in your curl request.  This makes the curl request semantically different than the one sent by the browser.
When evaluating whether an object is available to be served from the cache, CloudFront doesn't only consider the path.  Most of the headers that are forwarded to the origin server are also compared, and if the headers to be forwarded with this request don't match the headers sent with a prior request with a cached response available, the cached response won't be used, and a request will instead be sent to the origin.  Its response will be cached along with the headers that were sent.
So, the following two requests:
GET /object HTTP/1.1
Host: www.example.com

and
GET /object HTTP/1.1
Host: www.example.com
Origin: http://www.example.com

...are (assuming the Origin: header is being forwarded to the origin server, as it would need to be for CORS) treated as two different, essentially unrelated requests, by necessity -- CloudFront doesn't know whether the origin server might modify its responses based on the request headers sent.  The responses to these two requests would be cached separately, and each of them would only served be up in response to future, matching requests.
If the distribution is configured to forward cookies or query strings, these are also stored along with the cached response, which will only be served up in response to requests that exactly match the original request that generated the cached response -- based on all of the forwarded parameters.  (This is why unnecessarily forwarding information your origin server doesn't need will hurt your cache ratio.)
Setting the distribution's Error Caching Minimum TTL for 404 errors down to 0 resolves this issue, by preventing caching of the 404 responses.


text:
Q: Invalid IPA: missing embedded provisioning profile. Are you sure this is an ad hoc? I have searched a lot on internet but non of the solutions work for me. I create an ipa with Xcode Maven Plugin It successfully builds my application and creates an ipa but when I want to upload it on testflightapp it gives me this error:
Invalid IPA: missing embedded provisioning profile. Are you sure this is an ad hoc?

I have added provisioning profile in build settings like the following pic

If I create ipa manually with Xcode>Product>Archive I can successfully upload ipa on testflightapp. So my guess is that Xcode Maven Plugin cannot read my provisioning profile. I tried to force using provisioning profile by specifying it in pom file like bellow:
<configuration>
          <configurations>
            <configuration>Debug</configuration>
            <configuration>Release</configuration>
          </configurations>
          <provisioningProfile>42CB38B0-62BB-4242-BD03-72EDB7570842</provisioningProfile>
</configuration>

Any help would be appreciated.

A: This is an old question but may help others.
From the screenshot I see you have selected iPhone device and not Generic iOS Device that's why it is giving you provisioning profile error.
Select Generic iOS device and then build the project.
I got this error and it catches my eyes.

A: I figured out the problem. I was using wrong ipa file from maven target. I was using ipa from this path:
/target/checkout/src/xcode/build/Debug-iphonesimulator

I had to use this path
/target/checkout/src/xcode/build/Release-iphoneos

It was stupid mistake.

A: Make sure that while creating an .ipa file you must need to select Generic iOS Device as a Target
/i.stack.imgur.com/LsqBS.png

A: I changed build system to Legacy Build System and it was resolved.
To change it go to File -> Workspace Settings


text:
Q: Nested \ifdefined statements I am trying to populate a list of variables (in the attached example starting with \@addressone) with the values obtained from a set of commands. The first variable will get the first of whatever values I have, the second the second, etc. until values run out and from then on all the variables shall be empty. I am trying to do this with nested if statements:
\def \mystreet#1{\def\@mystreet{#1}} % Defines the \name command to set name
\def \mycity#1{\def\@mycity{#1}} % Defines the \name command to set name
\def \myphone#1{\def\@myphone{#1}} % Defines the \name command to set name
\def \myemail#1{\def\@myemail{#1}} % Defines the \name command to set name
\def \myurl#1{\def\@myurl{#1}} % Defines the \name command to set name

\let \@mystreet \relax
\let \@mycity \relax
\let \@myphone \relax
\let \@myemail \relax
\let \@myurl \relax

\ifdefined\@mystreet
    \def \@addressone {\@mystreet}
\else
    \ifdefined\@mycity
        \def \@addressone {\@mycity}
    \else
        \ifdefined\@myphone
            \def \@addressone {\@myphone}
        \else
            \ifdefined\@myemail
                \def \@addressone {\@myemail}
            \else
                \ifdefined\@myurl
                    \def \@addressone {\@myurl}
                \else
                    \def \@addressone {}
                \fi
            \fi
        \fi
    \fi
\fi

All of this seems to be ignored beyond the first if statement. If \@mystreet is undefined \@addressone will be empty, even if say \@mycity is defined.
COMMENT: it turns out my issue had nothing to do with the nested \ifdefined statements (which work just as you would expect them to) but rather with how and when LaTeX decided that my user input from files using this class counts as having defined the variables.

A: The main error is that \relax isn't undefined. This test file is complete and can be run through latex, the terminal output is
macro:->
macro:->streeeet
macro:->ciiity2222

which is (I think) what you want in each of the three cases.
\makeatletter

\def \mystreet#1{\def\@mystreet{#1}} % Defines the \name command to set name
\def \mycity#1{\def\@mycity{#1}} % Defines the \name command to set name
\def \myphone#1{\def\@myphone{#1}} % Defines the \name command to set name
\def \myemail#1{\def\@myemail{#1}} % Defines the \name command to set name
\def \myurl#1{\def\@myurl{#1}} % Defines the \name command to set name

\def\test#1{%
\let \@mystreet \@undefined
\let \@mycity \@undefined
\let \@myphone \@undefined
\let \@myemail \@undefined
\let \@myurl \@undefined
#1%
\ifdefined\@mystreet
    \let\@addressone\@mystreet
\else%
    \ifdefined\@mycity
        \let\@addressone\@mycity
    \else%
        \ifdefined\@myphone
            \ley\@addressone\@myphone
        \else%
            \ifdefined\@myemail
                \let\@addressone \@myemail
            \else%
                \ifdefined\@myurl
                    \let\@addressone\@myurl
                \else
                    \let\@addressone\@empty
                \fi
            \fi
        \fi
    \fi
\fi}

\test{}
\typeout{\meaning\@addressone}

\test{\mystreet{streeeet}\mycity{ciiity}}
\typeout{\meaning\@addressone}

\test{\mycity{ciiity2222}}
\typeout{\meaning\@addressone}

\stop


text:
Q: NestJS - Metadata in grpc microservice I am looking for a way to authorize an rpc via NestJS grpc microservices. Basically I want to attach a token in the grpc client, which has to be validated by the grpc server. I found this issue, but I did not get where exactly grpc.Metadata pass as a second argument.

A: I found a way to solve this. For sure not the most elegant solution, but it works for now. A simplified example:
// gRPC client
@Get(':id')
async call(@Param() params) {
    const metadata = new grpc.Metadata();
    // add relevant data to the metadata object (e.g from request header)
    metadata.add('role', 'admin');
    return this.userService.findOne({ id: +params.id}, metadata);
}

// Service
interface UserService {
    findOne(data: {id: number}, metadata: grpc.Metadata): Observable<any>;
}

// gRPC server
@GrpcMethod('UserService', 'FindOne')
async findOne(data: UserById, metadata: grpc.Metadata) {
    const meta = metadata.getMap();
    // do something with the metadata...
    console.log(meta.role);
    const items: User= [
        { id: 1, name: 'User 1' },
        { id: 2, name: 'User 2' },
        { id: 3, name: 'User 3' },
    ];
    return items.find(({ id }) => id === data.id);
}


text:
Q: Set Javascript time with php server time? I have a situation where I want the server time to be displayed on a web page.
At present I keep it simple and just do this
<?php
$CTIME=date ("g:i a");
?>

This works great- except I would prefer it if it updated by itself without the need to refresh the page.  I was thinking perhaps there is a way I can set the javascript time function with the time from a php script- but I've got no idea as to how I could go about doing this.
Perhaps I'm thinking about this wrong... maybe there is another solutions I'm not thinking of, Any ideas ??

A: Here is a jQuery plugin for displaying a clock:
http://plugins.jquery.com/project/jqClock
Just initialize it using the time coming back from the server.  It automatically updates every second on the client side.

A: Try this:
<javascript>
var ctime = '<?php echo date ("g:i a"); ?>';
</javascript>

Then let a timer increase the value on the javascript side. It's not very precise, but if I saw that right you need minutes only, not seconds, so precision is probably not an issue.

A: Use your base-time to calculate the current time on the fly (without using any additional and potentially slow/expensive request; it does not even require jQuery):
var getServerTime = (function () {
    var baseTime = <?php echo time() * 1000; /* convert to milliseconds */ ?>,
        startTime = new Date().getTime();

    return function () {
        return baseTime + (new Date().getTime() - startTime);
    };
}());

This function returns the current time (in milliseconds) based on the server-side time. You can update your site an a regular interval and use this function to determine the current server-side time like this:
// update the site every minute
setInterval(function () {
    var currentServerTime = getServerTime();
    // update everything (format date or something)
}, 60 * 1000);

A: I believe you can easily find some javascript code over the internet which shows a running clock on your site. On load of the page have PHP set the initial start time for this javascript snippet and i believe you are good to go.


text:
Q: How to fix the error Cannot destructure property temperatureData of 'undefined' or 'null' in react without class CODE:
const { temperatureData } = state;

return (
    <>

        {temperatureData.map((item, i) => (

                    {format(new Date(item.date * 1000), 'EEEE')}

                    {format(new Date(item.date * 1000), 'MMM dd')}

                    <img className="h-20" src={`/images/icons/weather/${getIcon(item.img)}.svg`} key={i} />

{item.temp}

        ))}

    </>
);

How to fix the error Cannot destructure property temperatureData of 'undefined' or 'null'.
The problem is when I reload the app the error will just appear.
do I need to put a condition inside the return?
if (state) {....HTML CODE}

A: For some reason, your state variable itself is not initialized when the app bootstraps.  I presume you're using a functional component since you said in the title "Without class", so to initialize state you'd need your useState declaration to look something like this:

    const [state, setState] = useState({ temperatureData: [] })

Note the param of the useState function is the initial state, so if you just called useState() with no arguments the inital value would be undefined.
Although with functional components, multiple independent state variables are more common, so perhaps a better pattern might be this:

    const [temperatures, setTemperatures] = useState([])

    return <>{temperatures.map(t => <> ... </>)}</>


text:
Q: Vector space over $\mathbb{R}$ implies Vector space over $\mathbb{C}$ If $V$ is a finite dimensional space over $\mathbb{R}$ then is it also a vector space over $\mathbb{C}$.Also is the converse true ?
I was thinking of using Countability argument to disprove this ,but I can't seem to find any way. Please give some hint.

A: Any vector space over $\mathbb C$ is automatically a vector space over $\mathbb R$, since multiplication by scalars is well defined.
Moreover, if $v_1,..., v_n$ is a basis of $V$ over $\mathbb C$ then $v_1,..,v_n, iv_1,.., iv_n$ is a basis of $V$ over $\mathbb R$.
This tells you not only that for a vector space over $\mathbb R$ the scalar multiplication to make it a vector space over $\mathbb C$ is not typically defined, but more, for a vector space of ODD dimension, we cannot even extend the scalar multiplication to make it a vector space over $\mathbb C$.


text:
Q: Unable to load script. Make sure you're either running Metro Unable to load script. Make sure you're either running Metro (run 'npx react-native start') or that your bundle 'index.android.bundle' is packaged correctly for release.SCREEN SHOT

I facing this while running a react native app in windows, using android studio, I have connected my real device for running that usb via android studio PLEASE HELP

PROJECT FILE

A: I followed these steps
1st step : yarn install
2nd step : npx react-native start
inside project folder
3rd step : yarn start
4th step : npx react-native run-android
also update gradles in android Studio

A: When running on a physical device you will often need to run the adb command:
adb reverse tcp:8081 tcp:8081

This will allow your device to communicate with the Metro instance.


text:
Q: insertar datos desde python a myslq flaks estoy ingresando datos a mysql desde python usando flask pero al ingresar los datos apartir de una consuta previa y ingresar este campo a una llave foranea me da el siguiente error
Capturo info desde html
 Nombre_cap= request.form['Nombre_cap']
 Id_cap= request.form['Id_cap']
 Correo_cap=request.form['Correo_cap']

#Guardo info en myslq
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('INSERT INTO equipo
(Nombre_Equipo,numero_integrantes,nombre_capitan,LenguajeProgramacion)
VALUES(%s,%s,%s,%s)',
(Nombre_de_equipo,N_integrantes,Nombre_cap,Lenguaje,))
mysql.connection.commit()
cursor.close

realizo consulta para traer el ID de equipo
cursor1 = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor1.execute('select  Id_Equipo from equipo where nombre_capitan = %s',(Nombre_cap,))

quito los espacios devueltos por la tupla para solo obtener el id equipo
            ID = cursor1.fetchone()
            print(ID,"//////////////////////////////////////////////")
            print(len(ID))
            #print(ID[1])
            ID = "".join(str(ID))
            x = ID.replace("Id_Equipo", " ")
            x2 = x.replace("' '"," ")
            x3 = x2.replace(":"," ")
            x4=x3.replace("{"," ")
            x5=x4.replace("}"," ")
            nume=str(x5)
            print(nume)
            cursor1.close

realizo una insert para almacenar en otra tabla "usuarios" donde equipo es llae foranea y debe ir con la info que anteriormente se obtuvo y se guardo en "nume"
  cursor2 = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
  cursor2.execute('INSERT INTO Usuario
  (Id_Usuario,Nombre_Usuario,rol_usuario,equipo,Correo_Usuario,Contraseña)
  VALUES(%s,%s,11,%s,%s,%s)',
  (Id_cap,Nombre_cap,Correo_cap,nume,result_str))
  mysql.connection.commit()

al hacer el inserte genera el siguiente error


text:
Q: Converting String to Int32 Trouble I'm having trouble converting an string to Int32 when calling it. This is what I'm struggling with.
public static int GetProgramLength()
{
    Console.WriteLine("Please enter program length:");
    return Int32.TryParse(Console.ReadLine);
}

Its telling me,

No overload for method, "Try Parse" takes 1 argument.

A:
You need to specify the out value to use Int32.TryParse() the result
  of TryParse is stored to the out parameter(outParam will be 0 if it failed to convert the input string),and also it will return
  a boolean value to indicate whether the conversion is success or a
  failure;

So you have to correct your code as like the following:
int outParam=0;
Console.WriteLine("Please enter program length:");
Int32.TryParse(Console.ReadLine(),out outParam);
return outParam;


text:
Q: DSpace Mirage2 - Where do I place a variable override? I would like to override a Sass variable in my DSpace Mirage 2 theme to understand how to customize the theme.
If I want to make the following changes, where should I place them?

$brand-primary: #607890;
$navbar-inverse-bg: #607890;
$navbar-inverse-link-color: yellow;

I have tried adding a variable declaration in several locations, but it is not included in the compiled CSS file.
I am able to add new CSS rules to styles/_styles.scss and those rules are built into the the final CSS.

A: In the classic_mirage_color_scheme the Bootstrap variables are set in classic_mirage_color_scheme/bootstrap_variables so you could simply copy the file to /dspace/modules/xmlui-mirage2/src/main/webapp/themes/Mirage2/styles/classic_mirage_color_scheme/_bootstrap_variables.scss.
The classic_mirage_color_scheme also defines a couple of its own variables in classic_mirage_color_scheme/_dspace_variables.scss. This would be a good place to add your non-bootstrap variables too.
The bootstrap_color_scheme doesn't override or define any variables. So when you start from the bootstrap_color_scheme you'd need to override in bootstrap_color_scheme/_main.scss like you did. (Beware the relative paths for importing files cfr. a related question)
The variables are all set with !default, this means they're only set if they haven't been set before. That's why overriding the variables only works before the imports.
Because the classic_mirage_color_scheme imports _bootstrap_variables.scss before _dspace_variables.scss, variables set in the latter won't be set if they have been set in the first.

A: The following seems to work.
COPY
/dspace-xmlui-mirage2/src/main/webapps/styles/classic_mirage_color_scheme/_main.scss
TO
/dspace/modules/xmlui-mirage2/src/main/webapp/themes/Mirage2/styles/classic_mirage_color/scheme/_main.scss
And add the variable declaration at the top before the includes.


text:
Q: Mocha test failing using typescript I have a project where I am using TS and Rollup. My code builds and run fine but when I run the tests via npm run test they fail with a SyntaxError: Unexpected token { error message.
Now I know that the issue is with the ES6 syntax because I am using import in my test file and it seems that the test is not getting transpiled but not sure why.
My relevant part of package.json:
 "main": "./dist/index.js",
  "module": "dist/index.es.js",
  "types": "./dist/index.d.ts",
  "scripts": {
    "build": "rollup -c",
    "watch": "rollup -cw",
    "prepublish": "rollup -c > index.js && BROWSER=true rollup -c > browser.js",
    "clean": "rm -rf dist/",
    "test": "mocha -r ts-node/register src/**/*.spec.ts",
    "testdebug": "mocha --inspect-brk --colors --recursive --require ts-node/register --watch-extensions ts \"**/*spec.ts\" --exclude \"node_modules/**\"",
    "lint": "tslint --project tsconfig.json -t codeFrame"
  },
  "devDependencies": {
    "@types/chai": "4.1.7",
    "@types/chai-as-promised": "7.1.0",
    "@types/long": "4.0.0",
    "@types/mocha": "5.2.6",
    "@types/node": "11.9.4",
    "@types/sinon": "7.0.6",
    "@types/sinon-chai": "3.2.2",
    "@types/supertest": "2.0.7",
    "@types/uuid": "3.4.4",
    "chai": "4.2.0",
    "chai-as-promised": "7.1.1",
    "husky": "1.3.1",
    "lint-staged": "8.1.4",
    "mocha": "5.2.0",
    "mocha-jenkins-reporter": "0.4.1",
    "prettier": "1.16.4",
    "rollup": "^1.10.0",
    "rollup-plugin-replace": "^2.2.0",
    "rollup-plugin-typescript2": "^0.20.1",
    "sinon": "7.2.3",
    "sinon-chai": "3.3.0",
    "supertest": "3.4.2",
    "ts-node": "8.0.2",
    "tslint": "5.12.1",
    "tslint-config-prettier": "1.18.0",
    "tslint-config-standard": "8.0.1",
    "tslint-microsoft-contrib": "6.0.0",
    "typescript": "^3.3.3"
  },

My test.spec.ts file:
    import { loginUser } from './loginUser'

    console.log(loginUser)

My tsconfig file: (I already tried to remove the spec files from exclude but its the same unfortunately)
{
  "compilerOptions": {
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
    "module": "es6",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    "outDir": "./dist",                        /* Redirect output structure to the directory. */
    "strict": true,                           /* Enable all strict type-checking options. */
    "skipLibCheck": true,
    "sourceMap": true,
    "moduleResolution": "node"
   },
   "exclude":[
     "node_modules",
     "dist",
     "./**/*.spec.ts",
     "./test/**/*.ts"
   ]
  }

My rollup.config file
import typescript from 'rollup-plugin-typescript2'
import replace from 'rollup-plugin-replace'
import pkg from './package.json'
export default {
    input: 'src/index.ts',
    output: [
        {
            file: pkg.main,
            format: 'cjs',
        },
        {
            file: pkg.module,
            format: 'es',
        },
    ],
    external: [
        ...Object.keys(pkg.dependencies || {}),
        ...Object.keys(pkg.peerDependencies || {}),
    ],
    plugins: [
        typescript({
            typescript: require('typescript'),
        }),
        replace({
            'process.browser': !!process.env.BROWSER
        })
    ],
}

A: Your mocha setup looks correct.
./node_modules/mocha/bin/mocha --inspect-brk=9230 -r ts-node/register tests/**/*spec.ts"

*

*Did you install npm i ts-node?

*Did you consider that inspect-brk stops the execution until you continue the execution in the inspector? + check also the port

A: Solved this issue by using: TS_NODE_COMPILER_OPTIONS={\\\"module\\\":\\\"commonjs\\\"} mocha -r ts-node/register test/**/*.spec.ts
more details: Overriding `tsconfig.json` for ts-node in mocha


text:
Q: Submit data without refreshing page and display the data live in below of form Someone know how to show the data after submit below the form ?
I have a code like below that function to save the data, but I want after save the data, it will show into below of form. I think like facebook posting wall.
<script type="text/javascript" >
$(function() {
   $(".submit").click(function() {
        var name = $("#name").val();
        var username = $("#username").val();
        var password = $("#password").val();
        var gender = $("#gender").val();
        var dataString = 'name='+ name + '&username=' + username + '&password=' + password + '&gender=' + gender;

        if(name=='' || username=='' || password=='' || gender=='')
        {
            $('.success').fadeOut(200).hide();
            $('.error').fadeOut(200).show();
        }
        else
        {
           $.ajax({
               type: "POST",
               url: "result.php",
               data: dataString,
               success: function(){
                  $('.success').fadeIn(200).show();
                  $('.error').fadeOut(200).hide();
               }
            });
         }
return false;
});

});
    </script>

A: Just append your response to your specified HTML element( div,span etc ) after success of your ajax requrest.
    $.ajax({
           type: "POST",
           url: "result.php",
           data: dataString,
           success: function(response){

              $('.success').fadeIn(200).show();
              $('#response').append(response);
              $('.error').fadeOut(200).hide();
           }
        });

Response will get appended to your specified HTML element.


text:
Q: Datasheet with dynamic recordsource shows no records in Access 2007, but works in Access 2003 I have an Access 2003 database which uses a main form with a datasheet in a subform. The main form allows the user to select from a menu which updates the recordsource of the subform. The subform also updates the number and type of fields available for editing based on the number and types of fields in the form's recordsource. It's basically a dynamic datasheet generator. This works just fine in Access 2003 and has been for years. If I open the same database in Access 2007 (full or runtime), most of the menu selections work. However, if I choose any menu option that references one particular table, the subform shows column headers, but does not show any rows of data or display any errors.  It's as if the query is returning zero rows.  Why would there be a difference in Access 2007? Did they add new reserved words?
Things I've tried:

*

*Updated every field in the table to ensure there are no null values (no change)

*Renamed every field and the table name just in case there are new reserved words (no change)

*Compacted and repaired the front end and back end (no change)

*Tried including and excluding fields one by one to see if anything changed (no change)

*Put the form's recordsource in a new query. (it returned the expected number of rows)

*Checked to make sure the form is not set to data entry mode. (It's not)

*Checked to ensure that no filters were being applied in code. (none were)

*Checked to make sure the query is updateable in Access 2007. (It is)

*Selectively deleted chunks of data from the source table. (no change)

I'm stumped.

A: I was able to finally resolve the issue. As I noted above, my datasheet is a subform. The parent form sets the options that determine how the subform will be built. While the datasheet is being built, the subform's sourceobject is replaced with a blank form to hide the prior datasheet and present a smooth transition to the new datasheet. It works beautifully in Access 2000/2003.
When the blank form is replaced with the new datasheet in Access 2007, I found that Access is automatically assigning the primary key of the subform data to the LinkMasterFields and LinkChildFields properties of the unbound parent form. Those properties had previously been blank, and I never set them in code. Perhaps this is as an attempt by Access 2007 to be helpful rather than a bug, but the behavior difference is not noted in any tech reference I can find, including the built-in help file. Since the parent form is unbound, it has the effect of filtering out all of my subform records. If I explicitly set LinkMasterFields="" and LinkMChildFields="" during the form substitution step, everything works as it did before. Hooray!
Again, the solution is that when setting the sourceobject of a subform, be sure to explicitly set the linkmastfields and linkchildfields properties to prevent Access from doing it for you. I hope this saves someone the hours of frustration I experienced.


text:
Q: How to add a hover effect on a dropdown? I'm currently designing a new website and I added a dropdown which works perfectly fine when clicked. I basically want it to show that dropdown when hovered.
What I tried was:

{% include 'currency-picker' %}


text:
Q: Textbox event for autocomplete for gridview in winform I've been looking online for the correct event to use for a textbox to auto-generate suggestions like google.com so I don't have to type the whole cell value to find what I'm looking for.  Currently, I have a button where when clicked it will filter the grid to what I ask for, but not just using the textbox to filter.  I know there's Keypress, textchanged, etc. and I tried the different events to see if the datagridview filters as I type.  No success.  The key press event doesn't filter as I type.  The textchanged event won't let me type in the textbox.  So how can I accomplish this?
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SampleARDUserGroup
{
    public partial class FirstPage : Form
    {
        SqlConnection con;
        SqlDataAdapter adap;
        DataSet ds;
        SqlCommandBuilder cmbl;
        public FirstPage()
        {
            InitializeComponent();
        }

        private void FirstPage_Load(object sender, EventArgs e)
        {

            try
            {
                con = new SqlConnection();
                con.ConnectionString = "My Data Source";
                con.Open();
                adap = new SqlDataAdapter("select RowID as 'ID',UserID as 'User ID', FirstName as 'First Name', LastName as 'Last Name', email as 'E-mail' from JoshTestTable", con);
                ds = new System.Data.DataSet();
                adap.Fill(ds, "User_Details");
                DGV1.DataSource = ds.Tables[0];
                DGV1.Columns[0].Visible = false;
                DGV1.Columns[2].Visible = false;
                DGV1.Columns[3].Visible = false;
                DGV1.Columns[4].Visible = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            con = new SqlConnection();
            con.ConnectionString = "My Data Source";
            SqlDataAdapter sda = new SqlDataAdapter("Select UserID,FirstName,LastName,Email FROM JoshTestTable where UserID like '%" + txtSearch.Text.Trim() + "%' OR FirstName like '%" + txtSearch.Text.Trim() + "%' OR FirstName like '%" + txtSearch.Text.Trim() + "%' OR LastName like '%" + txtSearch.Text.Trim() + "%' OR Email like '%" + txtSearch.Text.Trim() + "%'", con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            DGV1.DataSource = dt;
            DGV1.Columns[1].Visible = false;
            DGV1.Columns[2].Visible = false;
            DGV1.Columns[3].Visible = false;

        }

        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            AddDeleteUsers f2 = new AddDeleteUsers();
            f2.ShowDialog();
        }

        private void AddUsersToGroupsLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            AddUsersToGroups f3 = new AddUsersToGroups();
            f3.ShowDialog();
        }

        private void AddGroupsToUsersLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            AddGroupsToUsers f4 = new AddGroupsToUsers();
            f4.ShowDialog();
        }

        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            AutoCompleteStringCollection namesCollection = new AutoCompleteStringCollection();

            SqlConnection con = new SqlConnection();
            con.ConnectionString = "My Data Source";
            con.Open();
            String query = "select UserID from JoshTestTable  where UserID like '%" + txtSearch.Text + "%'";
            SqlCommand cmd = new SqlCommand(query, con);
            SqlDataReader rr = cmd.ExecuteReader();
            rr.Read();
            while (rr.Read())
                namesCollection.Add(rr["UserID"].ToString());
            rr.Close();
            txtSearch.AutoCompleteMode = AutoCompleteMode.Suggest;
            txtSearch.AutoCompleteSource = AutoCompleteSource.CustomSource;
            txtSearch.AutoCompleteCustomSource = namesCollection;
        }
    }
}

A: Because, apparently, your where conditions in the query in your txtSearch_TextChanged event should be like that
String query =
    "select UserID from JoshTestTable where UserID like '%" +
    txtSearch.Text.Trim() + "%' OR FirstName like '%" +
    txtSearch.Text.Trim() + "%' OR FirstName like '%" +
    txtSearch.Text.Trim() + "%' OR LastName like '%" +
    txtSearch.Text.Trim() + "%' OR Email like '%" +
    txtSearch.Text.Trim() + "%'";

as your btnSearch_Click event. Or simply you can query the database from a single point like:
private void txtSearch_TextChanged(object sender, EventArgs e)
{
    btnSearch_Click(null, null);
}

UPDATE
You must fill the custom source with what you typed. For example I used the Last Name field in my example and it's worked for me:
private void txtSearch_TextChanged(object sender, EventArgs e)
{
    var con = new SqlConnection("{your connection string}");
    con.Open();
    String query = "select LastName from JoshTestTable where LastName like '%" + txtSearch.Text.Trim() + "%'";
    var cmd = new SqlCommand(query, con);
    var rr = cmd.ExecuteReader();
    var namesCollection = new AutoCompleteStringCollection();
    while (rr.Read())
        namesCollection.Add(rr["LastName"].ToString());
    rr.Close();
    con.Close();
    txtSearch.AutoCompleteCustomSource = namesCollection;
    txtSearch.AutoCompleteMode = AutoCompleteMode.Suggest;
    txtSearch.AutoCompleteSource = AutoCompleteSource.CustomSource;
}


text:
Q: Simple Factorial Finder function Here is my code :
#include <iostream>
using namespace std;

int factorialFinder(int x){
    if (x==1){
        return 1;
        }else{
            return x*factorialFinder(x-1);
            }
    }

int main()
{
 cout << factorialFinder(5) << endl;
}

I have currently hard time to exactly understand how the programs makes 5*4*3*2*1 = 120
For me if we take each line of the program it would do :
5*factorialFinder(5-1) is 5*4
4*factorialFinder(4-1) is 4*3
3*factorialFinder(3-1) is 3*2
2*factorialFinder(2-1) is 2*1
so 5*4*4*3*3*2*2*1 = 2880

Sorry I feel dumb, I tried to wait some days and think again about it.
I'm begginer in c++.
Does it has anything to do with callstack ?
Like i was thinking about this also :
Original function make :
5*4 = 20 20 is the returned value
4*3 = 12 12 is the returned value
3*2 = 6 6 is the returned value
2*1 = 2 2 is the returned value
1*1 = 1 STOP BECAUSE x == 1

call stack pop off
1*1=1 1 is the returned value
2*1=2 2 is the returned value
3*2=6 6 is the returned value
4*6=24 24 is the returned value
5*24=120 120 is the returned value

I would be glad if someone can explain me exactly what does the function exactly line by line...
Thanks a lot for helping.

A: Your reasoning is flawed.
5*factorialFinder(5-1) is 5*4

Not it is not. When you expand the function call you also have to do that recursively. The recursive rule is
factorialFinder(x) == x * factorialFinder(x-1)

Convince yourself that this is correct. Then apply it to your example:
5*factorialFinder(5-1) == 5* 4*factorialFinder(4-1)
                       == 5*4* 3*factorialFinder(3-1)
                       == 5*4*3* 2*factorialFinder(2-1)
                       == 5*4*3*2*1

A: just printing rather than compute, using an equivalent definition :
#include <iostream>
using namespace std;

void factorialFinder(int x){
    if (x==1){
      cout << 1;
    } else {
      factorialFinder(x-1);
      cout << " * " << x;
    }
}

int main()
{
  factorialFinder(5);
  cout << endl;
}

Execution :
1 * 2 * 3 * 4 * 5

Or
#include <iostream>
using namespace std;

void factorialFinder(int x){
    if (x==1){
      cout << 1;
    } else {
      cout << x << " * ";
      factorialFinder(x-1);
    }
}

int main()
{
  factorialFinder(5);
  cout << endl;
}

Execution :
5 * 4 * 3 * 2 * 1

Or if you prefer to see all :
#include <iostream>
using namespace std;

int factorialFinder(int x) {
  cout << "fact(" << x << ") = ";
  if (x==1){
    cout << 1;
    return 1;
  } else {
    cout << x << " * (";

    int v = factorialFinder(x-1);

    cout << ") = " << x << "*" << v << " = " << x*v;
    return x*v;
  }
}

int main()
{
  factorialFinder(5);
  cout << endl;
}

Execution :
fact(5) = 5 * (fact(4) = 4 * (fact(3) = 3 * (fact(2) = 2 * (fact(1) = 1) = 2*1 = 2) = 3*2 = 6) = 4*6 = 24) = 5*24 = 120

A: Here's something that helped me a long time ago.
This is a traditional non-recursive factorial function
int trad_fact(int n)
{
    int res = 1;
    for (int i = 2; i <= n; ++i)
         res *= n;
    return res;
}

Now here our first attempt to write a recusrive factorial function
int recur_fact(int n)
{
    return trad_fact(n);
}

Not very good, it's not even recursive, all it does is use the trad_fact function we've already written. But I hope you agree that it will give the right result (assuming trad_fact does).
Now lets make a special case out of 1.
int recur_fact(int n)
{
    if (n == 1)
        return 1;
    else
        return trad_fact(n);
}

Not much better, we've still using trad_fact for every case except 1, and still not recursive, but still returns the right result.
Here's another change, this time we've going to do the first multiplication in recur_fact but use trad_fact for the rest of the calculation
int recur_fact(int n)
{
    if (n == 1)
        return 1;
    else
        return n * trad_fact(n - 1);
}

Now recur_fact is doing a bit more work than previously, for instance recur_fact(5) ==> 5 * trad_fact(4) ==> 5 * 24 ==> 120, which is the right answer but there's still no recursion.
Now think about this. We have two functions trad_fact and recur_fact, both work out factorials, they do it in a different way, but given the same parameter both will return the same result. In other words the functions are equivalent. Now if they are equivalent then any place you see one function being used you can substitute the other function and the program won't change. And that applies even inside the recur_fact function! So we can do this
int recur_fact(int n)
{
    if (n == 1)
        return 1;
    else
        return n * recur_fact(n - 1);
}                  ^^^^^^^^^^

And as if by magic we've suddenly got a recursive function. And we've proved it's correct every step of the way!

A: As everybody here says, why do you assume
5*factorialFinder(5-1) is 5*4 beforehand
Recursion is a dynamic programming technique. So here, factorialFinder(4) method calls returned value will be substituted. Instead of just 5 * 4, THe stack trace would reverse like this :
factorialFinder(5) = 5 * factorialFinder(5-1) = 5 * factorialFinder(4)

Now you need to find factorialFinder(4) :
factorialFinder(4) = 4 * factorialFinder(3)
factorialFinder(3) = 3 * factorialFinder(2)
factorialFinder(2) = 2 * factorialFinder(1)
factorialFinder(1) = 1

Now we got a value lets return to the called function which is factorialFinder(2)) :
factorialFinder(2) = 2 * factorialFinder(1) = 2*1 = 2
factorialFinder(2) = 2

So let's solve for factorialFinder(3) and so on:
factorialFinder(5) = 5 * factorialFinder(4)
factorialFinder(4) = 4 * factorialFinder(3)
factorialFinder(3) = 3 * 2 = 6
factorialFinder(2) = 2

Up one return :
factorialFinder(5) = 5 * factorialFinder(4)
factorialFinder(4) = 4 * 6 = 24
factorialFinder(3) = 6
factorialFinder(2) = 2

Substituting factorialFinder(4)=24 in the factorialFinder(5) solves the function:
factorialFinder(5) = 5 * 24 = 120
factorialFinder(4) = 24
factorialFinder(3) = 6
factorialFinder(2) = 2

Now you have the result as factorialFinder(5) = 120

when doing recursion, remember you have to do reverse lookup only if you have a value instead of a function/equation.

A: The key to recursion is understanding recursion. In this case, you know that 5! is
5*4*3*2*1

The recursion AHA! moment comes in noticing that this is the same as
5 * (4*3*2*1) = 5 * 4!

So then you can note that 4! = 4 * 3! and 3! = 3 * 2! and you can make the general formula
n! = n * (n-1)!

with a starting point of 1! defined to be 1
This general case is exactly modeled in your program.
return x*factorialFinder(x-1);

with the base case handled by
if (x==1) return 1;


text:
Q: Django multi table inheritance: Find and change parent model Suppose I have the following model structure in django:
class A(models.Model):
    x = models.IntegerField()

    def copy(self):
        obj = self
        obj.pk = None
        obj.save()

        return obj

class B(A):
    y = models.IntegerField()

    def copy(self):
        # this method is what I am confused about
        new_parent = super(B, self).copy()  # not sure about this
        obj = self
        obj.pk = None
        # how to set obj's parent model to 'new_parent'
        obj.save()
        return obj

I am not sure on how I can access the parent model's object, and how can I make this copy method work?
I have searched quite a bit and couldn't find any answer. Should I just use a one-to-one relation instead?

A: If you have a normal parent-child models you will get attribute in child to access parent. You can update this attribute with new parent object.
Also, the way you create parent object may not work, you need to call method on that object.
So I will update child's copy() method as:
class B(A):

    def copy(self):
        # this method is what I am confused about
        new_parent = self.a.copy()  # change 'a' with appropriate attribute name
        obj = self
        obj.pk = None
        # set obj's parent model to 'new_parent'
        obj.a = new_parent
        obj.save()
        return obj


text:
Q: Filter to intercept server output I have to write a filter that will change the server's output. Here is my code:
@WebServlet("/ServerClass")
public class ServerClass extends HttpServlet {

private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String text = request.getParameter("text");

        PrintWriter pw = new PrintWriter(response.getOutputStream());
        pw.write(text);
        pw.close();
    }
}

The filter implementation:
@WebFilter("/TextFilter")
public class TextFilter implements Filter {

    public TextFilter() {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
         PrintWriter out = response.getWriter();
         TextResponseWrapper wrapper = new TextResponseWrapper((HttpServletResponse)response);

         chain.doFilter(request, wrapper);

         String responseText = wrapper.toString();
         responseText.replaceAll("text", "****");

         response.setContentLength(responseText.getBytes().length);
         out.println(responseText);
         out.close();
     }

    public void init(FilterConfig fConfig) throws ServletException {
    }
}

class TextResponseWrapper extends HttpServletResponseWrapper {

    private CharArrayWriter output;

    public String toString() {
        return output.toString();
    }

    public TextResponseWrapper(HttpServletResponse response){
        super(response);
        output = new CharArrayWriter();
    }

    public PrintWriter getWriter(){
        return new PrintWriter(output);
    }
}

web.xml
<filter>
    <filter-name>TextFilter</filter-name>
    <filter-class>TextFilter</filter-class>
</filter>
<filter-mapping>
        <filter-name>TextFilter</filter-name>
        <servlet-name>ServerClass</servlet-name>
</filter-mapping>

The problem is that I am getting the following error:
java.lang.IllegalStateException: getWriter() has already been called for this response
at org.apache.catalina.connector.Response.getOutputStream(Response.java:604)
at org.apache.catalina.connector.ResponseFacade.getOutputStream(ResponseFacade.java:197)
at javax.servlet.ServletResponseWrapper.getOutputStream(ServletResponseWrapper.java:96)
at ServerClass.doPost(ServerClass.java:19)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at TextFilter.doFilter(TextFilter.java:33)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

So from what I understood after some research, is that this error is caused by the fact that I open the OutputStream from both ServerClass and TextFilter. But how can I intercept the server output without doing so? Which is the correct approach in this situation?

A: The servlet is calling getOutputStream, not getWriter. Your class TextResponseWrapper does not override getOutputStream.
So you have two choices:

*

*Override getOutputStream to return your wrapping stream.

*Change the servlet's code from PrintWriter pw = new PrintWriter(response.getOutputStream()); to PrintWriter pw = new PrintWriter(response.getWriter());


text:
Q: ListPicker Items not being shown in FullScreen Mode I used a TOOLKIT ListPicker . But the items are not being shown in FullScreen Mode. Its a Blank Page on clicking ListPicker  but the items are present transparent and can even be selected. it seems blank page but items are there.
<phone:PhoneApplicationPage
x:Class="Sunder_Gutka.SettingPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"

FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d"
shell:SystemTray.IsVisible="True">

<phone:PhoneApplicationPage.Resources>

    <DataTemplate x:Name="PickerItemTemplate">
        <TextBlock Text="{Binding BackGroundColorArray}" />
    </DataTemplate>

    <DataTemplate x:Name="PickerFullModeItemTemplate" >
        <TextBlock Name="BackgroundColor"

    Text="{Binding BackGroundColorArray}"
                   />
    </DataTemplate>
</phone:PhoneApplicationPage.Resources>

<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <!--TitlePanel contains the name of the application and page title-->
    <StackPanel Grid.Row="0" Margin="12,17,0,28">
        <TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
        <TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
    </StackPanel>

    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

        <toolkit:ListPicker x:Name="BackgroundColor"  FullModeHeader="Select Background Color:" Header="Background Color:" BorderThickness="0" FullModeItemTemplate="{StaticResource PickerFullModeItemTemplate}" ItemTemplate="{StaticResource PickerItemTemplate}" Background="#FF09043C" SelectionChanged="BackgroundColor_SelectionChanged" >

        </toolkit:ListPicker>

    </Grid>
</Grid>

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace Sunder_Gutka
{
    public partial class SettingPage : PhoneApplicationPage
    {
        String[] BackGroundColorArray = { "Black", "Light Grey", "White[Default]", "Blue", "Green", "Saffron", "Yellow", "Magenta", "Dark Grey", "Red" }; //To be used in LISTPICKER

        public SettingPage()
        {
            InitializeComponent();
            this.BackgroundColor.ItemsSource = BackGroundColorArray; //Item Source  of listpicker

        }
        string SelectedBackgroundColor;

        private void BackgroundColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
             SelectedBackgroundColor = BackgroundColor.SelectedItem.ToString();
        }

    }

A: Update your DataTemplate:
<phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Name="PickerItemTemplate">
        <TextBlock Text="{Binding}" />
    </DataTemplate>
    <DataTemplate x:Name="PickerFullModeItemTemplate" >
        <TextBlock Name="BackgroundColor" Text="{Binding}"/>
    </DataTemplate>
</phone:PhoneApplicationPage.Resources>

Its working now. I have Implemented this.

A: By default when you display items in the FullScreen mode your items are displayed with smaller font size. So what you have to do is to change the DataTampleate of the FullScreen mode ItemTempate to following.. I have only increased the FontSize here.. You can do any styling you like.
<phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Name="PickerItemTemplate">
        <TextBlock Text="{Binding}" />
    </DataTemplate>

    <DataTemplate x:Name="PickerFullModeItemTemplate" >
        <TextBlock Name="BackgroundColor" Text="{Binding}" FontSize="{StaticResource PhoneFontSizeLarge}" />
    </DataTemplate>
</phone:PhoneApplicationPage.Resources>

Its up to you to style the Template appropriately. Also im hoping that you are aware that ListPicker would only go to FullScreen mode only if you have more that 5 items in the ListPicker. If not you need to manually set  ExpansionMode="FullScreenOnly" to get it full screen.


text: Q: When is Cost Based Optimization used and when is Heuristic Rules are used in Query Optimization in RDBMS? I was wondering when does the Query Processing Engine use Heuristic Rules and when Cost Based while optimizing queries?


text:
Q: Error 403: Permission iam.serviceAccounts.create is required to perform this operation on project projects/, forbidden I am trying to create GKE cluster from terraform. I have an existing service account and I don't want to create any new service account instead use the one which I have.
I am getting error while running my terraform script, can you please suggest.
I am referring to this link here:
https://registry.terraform.io/modules/terraform-google-modules/kubernetes-engine/google/latest
provider "google" {
  credentials =file("xxx.json")
  project     = "myproject"
  region      = "us-east1"
}

module "gke" {
  source                     = "terraform-google-modules/kubernetes-engine/google"
  project_id                 = "myproject_id"
  name                       = "gke-test-2"
  region                     = "us-east1-c"
  zones                      = ["us-east1-b","us-east1-d"]
  network                    = "VPC"
  subnetwork                 = "VPC_SUBNET"
  ip_range_pods              = "us-east-1-subnet1"
  ip_range_services          = "us-east-1-subnet2"
  http_load_balancing        = false
  network_policy             = false
  horizontal_pod_autoscaling = true
  filestore_csi_driver       = false

  node_pools = [
    {
      name                      = "default-node-pool"
      machine_type              = "e2-medium"
      min_count                 = 1
      max_count                 = 2
      local_ssd_count           = 0
      disk_size_gb              = 100
      disk_type                 = "pd-standard"
      image_type                = "COS_CONTAINERD"
      auto_repair               = true
      auto_upgrade              = true
      service_account           = "XXXXX@myproject.iam.gserviceaccount.com"
      preemptible               = false
      initial_node_count        = 2
    },
  ]

  node_pools_oauth_scopes = {
    all = []

    default-node-pool = [
      "https://www.googleapis.com/auth/cloud-platform",
    ]
  }

  node_pools_labels = {
    all = {}

  }

  node_pools_metadata = {
    all = {}

    default-node-pool = {
      node-pool-metadata-custom-value = "my-node-pool"
    }
  }

  node_pools_taints = {
    all = []

  }

  node_pools_tags = {
    all = []

  }
}

A: You need to add the role Create Service Accounts (iam.serviceAccounts.create) to your service account to create service accounts when creating the cluster.
Or else you can assign the Service account Admin role to the existing service account.


text:
Q: не распознаются устройства Ubuntu 16.04 и отладка по usb [andoid studio]
 $ adb devices
List of devices attached

Само устройство распознается системой, а вот android studio отказывается видеть устройства. Файл прав прописан
Опции разработчика включены, провода usb исправны

A: Все проблема решена, adb требовал прав администратора для прослушивания порта...
$ sudo su
$ adb kill-server
$ adb start-server

или
$ adb root


text:
Q: Text Expansion on Ubuntu 17.10 Wayland Because Autokey, Snippy, and Texpander all rely on the X11 windowing system (or indirectly on xdotool), they do not fully function on Artful's default Wayland session.
Is there  any alternative software that provides 1) simple text expansion that is 2) system-wide (browser, shell, editor, etc.)?

A: Wayland is coming back as the default for Ubuntu 21.04, but I've long since switched to Espanso as my text-expansion tool.


text:
Q: How do I remotely fix a malware-infected Windows XP PC? Someone I know has got their Windows XP PC infected with malware.
Are there any tools I can use to disinfect the PC remotely? It would have to be a boot CD because XP is completely hosed.

A: Removing malware by remote:

*

*Remote access by you using a live CD and with this connecting to your friends computer and then you removing the malware.
To do it this, you would require a live CD OS (Ubuntu, etc.) or a rescue CD that has a browser that can get internet access and has anti-malware software installed to it.  You could from your computer, using the live CD, use your friends system to connect to MSE or any anti-malware site.

*Remote access by you giving advice and they burn, insert and use the live CD:
This has a list of live CD anti-malware options and this is from the 'Live CD list'. I have used Kaspersky rescue CD and have read/ heard good things about Panda and AVG.
I have not needed to use any, but would try open diagnostics from the 'live cd list- windows antivirus'. This may not sound like good advice, but I would go with any free CD first and see if it removes anything and then possibly look at a 'try before you buy' and so on.
If you do not have a CD burner, Imgburn is a good selection and the guides tell you all you need to know when burning an ISO.
Other remote as in advice:

*

*With Internet access (I would try this first):
Using this option, your friend could connect to  SE and use/ install the free service and remove the malware that way.

*The last, but possibly the best, is to re-install the OS:

*

*First run a full backup (the malware will be backed up and this is as a 'just in case).

*Copy all data to CD/DVD (documents, music, video, etc.).

*Reformat, reinstall and update - this wipes the drive and takes it back to a clean OS.

*Install the anti-malware of your choice, update it.

*Reinstall all programs from the programs websites and copy the data off the CD/DVD and back to the OS.

The malware should get picked up by your new anti-malware system. If your friend does not have an install CD, you can use any XP install disk and use the product code from your friend's computer (this is legal, or so I have been told).


text:
Q: run nutch2.3.1 on hadoop2 I want to run nutch2.3.1 to crawl data on hadoop2. I have 3 nodes for hadoop2:

*

*crawler1:master

*crawler2:slave

*crawler3:slave

I deployed nutch2.3.1 to crawler1 and run it with following command:
/usr/local/nutch/deploy/bin/crawl  hdfs://xxx.xxx.xxx.xxx/urls/seed.txt test 5
It works and can crawl data ,but it looks like the crawl job only run on crawler1, the others nodes did not do any job for nutch.
my questions are:

*

*do I need deploy nutch  to crawler2 and crawler3?

*do I need run crawl command on 3 nodes?

*if my steps are wrong ,what are the right steps?

Sorry for my poor English, I really appreciate any help you can provide.


text:
Q: Can code that doesn't execute cause segmentation fault? I have this piece of code working just fine. Statement in if is true which leads me to printing TRUE. However when I remove the content of else statement, this gives me segmentation fault, even if it doesn't execute (still prints TRUE).
Does anybody have any idea why whould it be that way?
if(parser->checkToken(Token::Type::Int)) {
        std::cout << "TRUE" << std::endl;
        parser->scanner->getToken().getNumber();
        parser->advance();
} else {
        std::cout << "FALSE" << std::endl;
        parser->requireToken(Token::Type::String);
}

p.s. parser is unique_ptr

A: No, code which doesn't execute can't cause a segmentation fault.
Some other code (executed before the code you have shown) will be the cause.
The other code is exhibiting undefined behaviour (as per the meaning of "undefined" in the C++ standard), and overwriting some area of memory it shouldn't.   Removing the else block from your code can cause an implementation (compiler, linker, etc) to restructure how your program and data it uses is laid out in memory (e.g. where code and data are located in memory).   That can, in turn, change the effects of your offending code overwriting memory (e.g. it changes whether the overwritten memory is being used to store a variable, or it is some area of memory that your operating system deems your program should not access).

A: Without seeing the complete code it is hard to tell, but my guess would be that
parser->scanner->getToken().getNumber();
parser->advance();

(or other code that is not attached here) has some sort of undefined behavior related to it and it is just a matter of luck that you are experiencing segmentation fault with the else section (yes, you are lucky in that regard. Think about what would have happened if you were unable to reproduce it).
Try and see what scanner, getToken(), and getNumber() do in their implementation and locate any operation that may lead to undefined behavior (Maybe getToken() returns a reference to an object that is initialized inside the function?).

A: Sure it can.
Adding/subtracting code, and so it's associated data, moves stuff around in memory to different places, even if, in one case, the code not actually executed itself.
If your code has undefined behaviour, the above can switch the operation of your process between 'working', crashing, nasal demons etc.


text:
Q: jQuery jPicker reset completely If anyone experienced with jPicker, I would really like some help on this. I have a jPicker input box in a form, and when I post the form with Ajax, I try to reset the form back to it's original values. Except that I have no idea how to reset the jPicker box to it's original state, does anyone know how to do this?

A: jPicker maintains the information for its control in the $.jPicker.List[] array. To remove the jPicker association with the control you will need to destroy its corresponding entry in the $.jPicker.List[] array.
Loop through the list of items in the array to find the one that references the control with
$.jPicker.List[index].id

When you find your control in the array, destroy it with
$.jPicker.List[index].destroy()

After destroying the array element, you will need to remove the SPAN jPicker html object associated with the control. If there is only one you can
$('span.jPicker').remove()

otherwise you will need to discover the specific html element
$(rowParent).find('span.jPicker').remove();

Optionally: if you are using class reference vs. id reference, use the .data() function to tag your control and use the following statement to retrieve the unique value
$( $.jPicker.List[index] ).data()

A: You can try to unbind the jPicker from the element and then rebind it after you want to reset it, should make it back to default settings.

A: As explained above you could try something like this :
var id =$.jPicker.List[i].id; //getting the id of the element you've binded jpicker with
$.jPicker.List[i].destroy(); //destroying the instance in the jPicker List
$("#"+id).parent().find('span.jPicker').remove(); // destroying the span containing the graphical jPicker
$("#"+id).jPicker(); // And finally reinstancing the jPicker instance on your element

It should make blink your picker (removing then recreating).


text:
Q: Angular 2+ Using Variable over components (e.g. global) In Angular 2+ I use a navigation component with a button and a click event like the following:
<button (click)="navlnk(about, $event)">About</button>

In the app.component.html I want to use the variable (here variable: about) from click event, like the following:
<article #about class="about active">
 lorem ipsum
</article>

Actually I have the following code in app.component.ts
navlnk(page: any, event: any) {
    page.classList.add('active'); // Show 'About' <article>
}

The code works fine, when all the code is placed in one component.
But how can I export the navigation to it's own component and call variable 'about' in main app.component.html ?
Can anybody help?


text:
Q: Possible options to calculate a part of paralleled Program over GPU Hi I am not so familiar with gpu and I Just have a theoretical question.
So I am working on an application called Sassena, which calculates Neutron scattering from Molecular dynamics trajectories. This application is written in parallel with MPI and works for CPUs very well. But I am willing to run this app over GPU to make it faster. ofcourse not all of it but partly. when I look at the Source Code, The way it works is typical MPI, meaning the first rank send the data to each node individually and then each nodes does the calculation. Now, there is a part of calculation which is using Fast Fourier Transform(FFT), which consumes the most time and I want to send this part to GPU.
I see 2 Solutions ahead of me:

*

*when the nodes reach the FFT part, they should send back the data to the main node, and when the main node gathered all the data it sends them to GPU, then GPU does the FFT, sends it back to cpu and cpu does the rest.

*Each node would dynamically send the data to GPU and after the GPU does the FFT, it sends back to each node and they do the rest of their job.
So my Question is which one of these two are possible. I know first one is doable but it is having a lot of communication which is time consuming. But the second way I don't know if it is possible at all or not. I know in the second case it will be dependent on the Computer architecture as well. But is CUDA or OpenCL capable of this at all??
Thanks for any idea.

A: To my knowledge you are not restricted by CUDA. What you are restricted here is the number of GPUs you have. You need to create some sort of queue that distributes your work to the available GPUs and keeps track of free resources. Depending on ratio between the number of CPUs to the number of GPUs and the amount of time each FFT takes, you may be waiting longer for each FFT to be passed to the GPU compared to just doing it on each core.
What I mean is that you lose the asynchronous computation of FFT which is performed on each core. Rather, CPU 2 have to wait for CPU 1 to finish its FFT computation to be able to initiate a new kernel on GPU.
Other than what I have said, it is possible to create a simple mutex which is locked when a CPU starts computing its FFT and is unlocked when it finishes so that the next CPU can use the GPU.
You can look at StarPU. It is a task based api which can handle sending tasks to GPUs. It is also designed for distributed memory models.


text:
Q: While loop not properly checking all conditions? So the assignment is as follows: you can enter all sorts of numbers but when you enter 0 two times in a row it needs to stop. The first time you enter a number your not allowed to enter 0.
This is the code I have setup:
class MainClass
{
    public static void Main (string[] args)
    {
        int givenNumber, prevNumber;
        Console.WriteLine ("Enter a number: ");
        int.TryParse (Console.ReadLine (), out givenNumber);
        // I've set the prevNumber to givenNumber because the variable has to be initialized
        // before I can use it in the condition below. I thought setting it to the giveNumber
        // wouldn't harm. Note that the first time your not allowed to enter 0
        prevNumber = givenNumber;
        while (givenNumber != 0 && prevNumber != 0) {
            prevNumber = givenNumber; //Here is where they both are 0 at a given moment, but only after the condition.
            Console.WriteLine ("Enter a number: ");
            int.TryParse (Console.ReadLine (), out givenNumber);
        }
        Console.WriteLine ("Tada");
    }
}

The problem is that it already stops when you've only entered one 0. For example if I'd first enter a 7 to start with, and my next number would be 0. When I debug it it says that my givenNumber is 0 and prevNumber is 7, when it goes back to the while condition it stops and finishes. When the program finishes the debug clearly says prevNumber = 7 and givenNumber = 0. I am using the conditional AND correct am I not?
Any clue? I'm not allowed to use arrays for this matter.
Thanks in advance

A: Ooh, right, you've got the logic wrong.  It should be this:
while ((givenNumber != 0) || (prevNumber != 0)) {

Look up DeMorgan's laws to see why...

A: Your problem is with your conditional statement.
Right now you're checking whether both the givenNumber and the PrevNumber DO NOT equal 0.
So, if neither of them equals 0 then the statement will evaluate to TRUE. However, if either one of the numbers is 0 then the statement will evaluate to FALSE, since (TRUE) && (FALSE) evaluates to FALSE.
There are two ways to fix this: You can either use || (the "OR" operator) with the two "!=" statements, or you can negate the whole thing and use regular equality rather than "!=" as such: !(givenNumber == 0 && prevNumber == 0)

A: while (givenNumber != 0 && prevNumber != 0)
For first read value from console - number 7
givenNumer will be 7
prevNumber will be 7 too (because of assignment prevNumber = givenNumber;)
Thus while (7 != 0 && 7 != 0) will pass
Second read from Console - number 0
Thus while (0 != 0 && 7 != 0) will not pass because 0 != 0 is FALSE and while loop ends if condition is result is FALSE


text:
Q: ¿Se puede hostear una pagina web en .NET a Firebase? Mi pregunta es sí ¿alguien probó hostear una aplicación en asp.net en el hosting gratuito de firebase?
Aclaro que en mi caso es una pagina estática, sin base de datos (solo paginas aspx, HTML, JavaScript, CSS)


text:
Q: Why im getting an infinite loop and how could i solve it? Im pretty new to programming so i probably made lots of mistakes helllpppp
Im writing a program where user should enter number of integers , then the program should print out how many even numbers are there in those integers and there sum
#include <iostream>
using namespace std;
int main()
{

    int n=3;
    int counteven;
    int count=1;
    int sum=0;
    cout<<"Enter the number of integers: ";
    cin>>n;
    while(count<=n)

        cin>>n;
        count++;
        if (n%2==0);
        {
        counteven;
        sum=sum+n;

        cout<<"The even numbers are:"<<counteven<<endl;
        cout<<"The sum of eve numbers is:"<<sum<<endl;}
        system("pause");
        return 0;
        }

thankss

A: It looks like you don't have any braces ({}) for your while loop which is probably causing it to loop over the line:
while(count<=n)

An example of a correct while loop (taken from here):
// custom countdown using while
#include <iostream>
using namespace std;

int main ()
{
  int n = 10;
  while (n>0) {
    cout << n << ", ";
    --n;
  }
  cout << "liftoff!\n";
}


text:
Q: Why do I get a circle when I try to buffer a squared polygon with turf.js? I have created the following node.js code with turf.js:
const turf = require('@turf/turf')

let polygon = [
  [
    [ -46.70527960466082, -23.515693805007327 ],
    [ -46.70525061354379, -23.515706130219414 ],
    [ -46.70521688456519, -23.515720493550234 ],
    [ -46.70515408370665, -23.51574718295358 ],
    [ -46.70514380411614, -23.51575153885141 ],
    [ -46.70534467952754, -23.51614450729978 ],
    [ -46.70550423529982, -23.516075408203687 ],
    [ -46.705303857919084, -23.515683517916514 ],
    [ -46.70527960466082, -23.515693805007327 ]
  ]
]
let turfPolygon = turf.polygon(polygon)
let bufferedPolygon = turf.buffer(turfPolygon, 500, {units: 'meters'})

console.log(JSON.stringify(bufferedPolygon))

On this code, polygon is a polygon that doesn`t have a circular shape. However, the result that I get from this code is the following JSON:
{"type":"Feature","properties":{},"geometry":{"type":"Polygon","coordinates":[[[-46.70322088458993,-23.511612661040875],[-46.70324513725736,-23.511602374268882],[-46.70414989865253,-23.511313190193746],[-46.70509871194889,-23.51119085258346],[-46.70605535658333,-23.51124003161756],[-46.70698331312504,-23.51145884991158],[-46.70784715697299,-23.511838954163927],[-46.70861391032006,-23.51236583394781],[-46.70925430084214,-23.51301937549594],[-46.70974387910988,-23.51377462936544],[-46.709944266799546,-23.514166513971112],[-46.71026468528243,-23.51499591890971],[-46.710402822262445,-23.515866661757098],[-46.71035338468864,-23.516745400734823],[-46.71011826193278,-23.517598487221015],[-46.70970645400013,-23.51839325424125],[-46.70913372739746,-23.519099267466057],[-46.70842201176066,-23.51968949079388],[-46.70759856029236,-23.520141321856958],[-46.70743900069192,-23.52021042308697],[-46.70653192465988,-23.520507341986136],[-46.70557904934411,-23.520635970913354],[-46.704617132929336,-23.520591347859405],[-46.70368328247596,-23.520375194211702],[-46.702813522046306,-23.5199958483299],[-46.70204140267023,-23.519467943791756],[-46.70139670784378,-23.518811844738906],[-46.70090430454788,-23.51805286013362],[-46.70070343947814,-23.517659885989946],[-46.70038195533657,-23.516825929817898],[-46.700244732646844,-23.51595040311668],[-46.700297077557394,-23.515067184373397],[-46.700536960877805,-23.514210449042604],[-46.700955097169526,-23.513413347175494],[-46.701535304545,-23.51270672082495],[-46.70225513117563,-23.51211791083629],[-46.703086724211424,-23.511669699162645],[-46.70309392009424,-23.511666649982637],[-46.703187958960925,-23.511626656930865],[-46.70322088458993,-23.511612661040875]]]}}

Going on https://geojson.io and seeing its result I see the following shape:

I don't get why I'm getting a circle instead of a polygon that follows the shape of my input polygon. What am I getting wrong? Why turf.buffer is returning a circular shaped polygon?


text:
Q: Reaching elements with finite applications of the successor relation in well-ordered sets Given an well-ordered class $(A,\leq)$ we want to proof that every element $a \in A$ can be reached by applying the successor relation on a the smallest element of $A$ or on an limes element of $A$ finitely often.
I tryed to construct an infinite decreasing sequence $a_{n+1} \leq a_n$ with $a_i \in A$ and no $m$ such that $a_m = a_{m+1}$. But my problem is that I cannot define a limes element $b \in A$ with $b < a$ and no limes element $c$ with $b < c < a$. Any hints?

A: You do it by induction.
Suppose that for all $\beta<\alpha$ we have that there is a minimal or limit $\gamma<\beta$ and a finite sequence $\gamma=\beta_0\leq\ldots\beta_n=\beta$, where $\beta_{i+1}$ is the successor of $\beta_i$.
If $\alpha$ is a limit point then we are done. It is itself a limit. Otherwise $\alpha$ is the successor of $\beta$, and simply add to the sequence from $\gamma$ that we already have the new point, $\alpha$.

A: HINT: Say that an element of $A$ is bad if it cannot be reached by applying the successor operation a finite number of times to $\min A$ or a limit element of $A$, and let $B=\{a\in A:a\text{ is bad}\}$. If $B\ne\varnothing$, let $b=\min B$, and derive a contradiction.


text:
Q: KeyUp vs KeyDown for enter-detection in .NET
*

*I have a textbox

*User enters some value

*User presses Enter

*System does some stuff

A pretty standard sequence of actions and I was wondering whether to use the KeyDown or KeyUp-event. Now, almost all examples I found on this, used the KeyDown event to detect whether the enter-key has been pressed. However, according to this article, the KeyDown event is triggered multiple times when a key is held down for a while. Which raises my question: why would I use KeyDown? My event will be triggered multiple times if the user accidentally holds down the enter-key, which is not something I want.
Is there some reason why I would use KeyDown over KeyUp?

A: Well, it matters.  If you use KeyUp then you'll have to deal with also getting the KeyPress event for the Enter key.  Which, it not intercepted, produces a nasty BEEP to slap the user.  Boilerplate is to always use KeyDown so you can stop the KeyPress event from firing:
    private void textBox1_KeyDown(object sender, KeyEventArgs e) {
        if (e.KeyData == Keys.Enter) {
            e.Handled = e.SuppressKeyPress = true;
            // Something special ...
            //...
        }
    }

The SuppressKeyPress assignment prevents the KeyPress event from firing.
Do keep in mind that handling Enter is normally fairly gauche and indicates that you might be trying too hard to make your GUI resemble a console mode app.  What Enter is supposed to do is operate the default accept button on a window.  Supported by the Form.AcceptButton property.  The Escape key is special that way as well, it operates the Form.CancelButton button.  Only truly meaningful things to do for a dialog-style window however.
If used on a regular window then the typical problem is that the user has no idea that pressing the Enter key is what he's supposed to do.  He'll mouse to another textbox and completely miss the intended usage of your UI design, that's a problem with discoverability.  You can't do the equivalent of ToolStripMenuItem.ShortcutKeyDisplayString in this case.

A: You can add some boolean field (enterInProcessed) and check:
 if (e.KeyCode == Keys.Enter && !enterProcessed){
     enterProcessed = true;
     ...
 }
 enterProcessed = false;

To prevent processing of the event multiple times.