text:
Q: Problem with using glossaries-extra with ocgcolorlinks option of the ocgx2 package and scalebox-based glsabbrvsmfont/glsnamefont commands The following example causes problem:
\documentclass{article}

\usepackage[colorlinks,linkcolor=blue]{hyperref}
\usepackage[ocgcolorlinks]{ocgx2}

\usepackage[record,acronym,shortcuts=ac]{glossaries-extra}

\usepackage{relsize}
\setabbreviationstyle[\acronymtype]{long-short-sm}

\usepackage{graphicx}
\newcommand{\myfmt}[1]{\scalebox{.35}{#1}}
\renewcommand*{\glsabbrvsmfont}[1]{\myfmt{#1}}%\renewcommand*{\glsnamefont}[1]{\myfmt{#1}}

\newcommand{\glspr}[1]{\glsxtrp{long}{#1}}

\GlsXtrLoadResources[src={entries}, selection={all}, type=\acronymtype, sort={letternumber-upperlower}]

\usepackage{filecontents}
\begin{filecontents}{entries.bib}
    @Acronym{c,
        long  = {ccc},
        short = {C}}
    @Acronym{bc,
        long   = {bbb \glspr{c}},
        parent = {c},
        short  = {BC}}
    @Acronym{abc,
        long   = {aaa \glspr{bc}},
        parent = {bc},
        short  = {ABC}}
    @Acronym{abc-d,
        description = {{}\glspr{abc}~--~\emph{ddd}},
        long        = {{}\glspr{abc} (d)},
        parent      = {abc},
        short       = {ABC-d}}
    @Acronym{abc-d-f,
        description = {{}\glspr{abc-d}~--~fff},
        long        = {{}\glspr{abc} (d, f)},
        parent      = {abc-d},
        short       = {ABC-d-f}}
    @Acronym{abc-d-g,
        description = {{}\glspr{abc-d}~--~ggg},
        long        = {{}\glspr{abc} (d, g)},
        parent      = {abc-d},
        short       = {ABC-d-g}}
    @Acronym{abc-e,
        description = {{}\glspr{abc}~--~\emph{eee}},
        long        = {{}\glspr{abc} (e)},
        parent      = {abc},
        short       = {ABC-e}}
    @Acronym{abc-e-f,
        description = {{}\glspr{abc-e}~--~fff},
        long        = {{}\glspr{abc} (e, f)},
        parent      = {abc-e},
        short       = {ABC-e-f}}
    @Acronym{abc-e-g,
        description = {{}\glspr{abc-e}~--~ggg},
        long        = {{}\glspr{abc} (e, g)},
        parent      = {abc-e},
        short       = {ABC-e-g}}
    @Acronym{h-bc,
        long   = {hhh \glspr{bc}},
        parent = {bc},
        short  = {H-BC}}
    @Acronym{iiii,
        long  = {ii ii ii ii},
        short = {IIII}}
    @Acronym{aaa,
        long  = {aaa aaa aaa},
        short = {AAA}}
    @Acronym{aab,
        long  = {aaa aaa bbb},
        short = {AAB}}
\end{filecontents}

\begin{document}

    \noindent Test: \ac{aab}, \ac{abc-e}, \ac{abc-e-g}.

    \printunsrtglossary[type=\acronymtype,style=treegroup]

\end{document}

While the desired result should look like this:

One thing is that acronyms referred to using \ac command in the document body are not visible in the resulting PDF. Though, they still occupy required space and their text is present in the output (as it can be copied and pasted elsewhere).
Also, the acronyms list is broken in the middle of the first entry that has description field starting with \gls-like command (abc-d, in this case). It is stated in the glossaries-extra manual that the package may have problems with such entries (and also that these commands should be preceded by empty groups {}):

If you really need nested commands, the safest method is
\newabbreviation{shtml}{shtml}{{}\glsxtrp{short}{ssi} enabled \glsxtrp{short}{html}}
but be aware that it may have some unexpected results occasionally.

Nevertheless, it does not seem to be the core issue here, because the provided MWE works properly after slight modifications in declarations not related directly to the nesting commands (as described below).

Some observations:

*

*Removing ocgcolorlinks option from ocgx2 package is a kind of a workaround, but definitely not a complete solution.

*Changing  \scalebox{.35}{#1} to \scalebox{1}{#1} is a workaround as well, but the required effect is not achieved (probably in such case the unnecessary \scalebox command is just not applied at all).

*Importing glossaries-extra package before hyperref also seems to help, but then the colored links for acronyms are lost.

*Changing \newcommand{\glspr}[1]{\glsxtrp{long}{#1}} to, e.g., \newcommand{\glspr}[1]{SOMETEXT\glsxtrp{long}{#1}} seems to repair the problem with broken acronym list, but then SOMETEXT is shown multiple times within the list and the acronyms in document body still do not show up.

*Might be quite obvious, but changing \renewcommand*{\glsabbrvsmfont}[1]{\myfmt{#1}} to \renewcommand*{\glsnamefont}[1]{\myfmt{#1}} solves the problem with acronyms in the document body (as graphicx's \scalebox-based \myfmt command is no longer appied to them), but the underlying problem persists and the acronyms list is still affected (broken).

A: The same problem can be demonstrated with a much smaller example:
\documentclass{article}

\usepackage[colorlinks,linkcolor=blue]{hyperref}
\usepackage[ocgcolorlinks]{ocgx2}

\usepackage{graphicx}
\newcommand{\myfmt}[1]{\scalebox{.35}{#1}}

\begin{document}
\hypertarget{test}{Test Target}.

\hyperlink{test}{Test Link}.

\hyperlink{test}{\myfmt{Test Link}}.

\myfmt{\hyperlink{test}{Test Link}}.

\end{document}

The second link is present but invisible:

The link text can still be copied, so it's present in the PDF.
The third link is visible and has the desired effect.
Returning to glossaries-extra, unfortunately the abbreviation font is inside the hyperlink, replicating the second link example above, so the same result occurs.
The only way of shifting a formatting command outside the hyperlink is when the formatting command is part of \glstextformat (or given by the textformat attribute) combined with the hyperoutside=false setting. This would affect the full form on first use and so can't be used for just the short form format.
If you only have text in your short form (and don't need to scale images), then I recommend that you use \textscale instead of \scalebox. For example:
\documentclass{article}

\usepackage[colorlinks,linkcolor=blue]{hyperref}
\usepackage[ocgcolorlinks]{ocgx2}

\usepackage{relsize}
\newcommand{\myfmt}[1]{\textscale{.35}{#1}}

\begin{document}
\hypertarget{test}{Test Target}.

\hyperlink{test}{Test Link}.

\hyperlink{test}{\myfmt{Test Link}}.

\myfmt{\hyperlink{test}{Test Link}}.
\end{document}

This works both when it's inside and outside of the hyperlink.
\documentclass{article}

\usepackage[colorlinks,linkcolor=blue]{hyperref}
\usepackage[ocgcolorlinks]{ocgx2}

\usepackage[record,acronym,shortcuts=ac]{glossaries-extra}

\usepackage{relsize}
\setabbreviationstyle[acronym]{long-short-sm}

\newcommand{\myfmt}[1]{\textscale{.35}{#1}}
\renewcommand*{\glsabbrvsmfont}[1]{\myfmt{#1}}

\newcommand{\glspr}[1]{\glsxtrp{long}{#1}}

\GlsXtrLoadResources[src={entries}, selection={all}, type=\acronymtype, sort={letternumber-upperlower}]

\usepackage{filecontents}
\begin{filecontents}{entries.bib}
    @Acronym{c,
        long  = {ccc},
        short = {C}}
    @Acronym{bc,
        long   = {bbb \glspr{c}},
        parent = {c},
        short  = {BC}}
    @Acronym{abc,
        long   = {aaa \glspr{bc}},
        parent = {bc},
        short  = {ABC}}
    @Acronym{abc-d,
        description = {{}\glspr{abc}~--~\emph{ddd}},
        long        = {{}\glspr{abc} (d)},
        parent      = {abc},
        short       = {ABC-d}}
    @Acronym{abc-d-f,
        description = {{}\glspr{abc-d}~--~fff},
        long        = {{}\glspr{abc} (d, f)},
        parent      = {abc-d},
        short       = {ABC-d-f}}
    @Acronym{abc-d-g,
        description = {{}\glspr{abc-d}~--~ggg},
        long        = {{}\glspr{abc} (d, g)},
        parent      = {abc-d},
        short       = {ABC-d-g}}
    @Acronym{abc-e,
        description = {{}\glspr{abc}~--~\emph{eee}},
        long        = {{}\glspr{abc} (e)},
        parent      = {abc},
        short       = {ABC-e}}
    @Acronym{abc-e-f,
        description = {{}\glspr{abc-e}~--~fff},
        long        = {{}\glspr{abc} (e, f)},
        parent      = {abc-e},
        short       = {ABC-e-f}}
    @Acronym{abc-e-g,
        description = {{}\glspr{abc-e}~--~ggg},
        long        = {{}\glspr{abc} (e, g)},
        parent      = {abc-e},
        short       = {ABC-e-g}}
    @Acronym{h-bc,
        long   = {hhh \glspr{bc}},
        parent = {bc},
        short  = {H-BC}}
    @Acronym{iiii,
        long  = {ii ii ii ii},
        short = {IIII}}
    @Acronym{aaa,
        long  = {aaa aaa aaa},
        short = {AAA}}
    @Acronym{aab,
        long  = {aaa aaa bbb},
        short = {AAB}}
\end{filecontents}

\begin{document}

    \noindent Test: \ac{aab}, \ac{abc-e}, \ac{abc-e-g}.

    \printunsrtglossary[type=\acronymtype,style=treegroup]

\end{document}

(Unrelated: the optional argument of \setabbreviationstyle should be a category label. The command \acronymtype is used to reference a glossary not a category. In the original MWE, \acronymtype happens to expand to the same value as the required category label, but they aren't necessarily the same so it's best not to use \acronymtype in contexts that expect a category label.)

A: With ocgx2 package option ocgcolorlinks, portions of the link text that are scaled or put in frameboxes, as well as graphics included with \includegraphics need special treatment. Just put \ocglinkprotect{...} around them.
In the present case:
\newcommand{\myfmt}[1]{\ocglinkprotect{\scalebox{.35}{#1}}}


text:
Q: Problem installing a program A program I need to use wont install.  It comes as a .deb file but when I try to install it says "wrong architecture i386".  How can I get it to work.  This is with ubuntu 11.10 (dual core version).
I did get the program to run on a version of 10.10 (single core) running on virtual box.

A: It seems you are trying to install a 32 bit program on a 64 bit ubuntu. You need to find 64 bit version of your program or try to use 32 bit version of ubuntu.

A: If you have a 64-bit architecture, you can still install and run 32-bit programs if your processor supports it (which it probably does). To do so, run sudo dpkg --force-architecture -i yourpackage.deb.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to plot only the max Y-value for each corresponding x-value I have data where there are multiple values for a single date. I want to plot only the max Y-value for each given date. Here is my full data set (I am plotting Date (X) vs Cumulative PnL (Y)):

And here is my current graph:

I want to make it such that only the maximum Y-value is used for each X-value, such that there are no vertical line son the graph. How do I do this?

A: Standard charting is very limited when you want to manipulate the data.
I recommend to create a Pivot Table and change the Value Field Setting to "MAX", this will show only the max value for duplicate dates. Now you can plot without the spike lines.


text:
Q: Error in kile about unable to open PDF file I've been having a problem with kile and for a long time, I've just ignored it but it's now getting annoying...
While typing in the editor window, I get a message that says, "Could not open file:///tmp/kile-livepreview.RDNKpj/p.pdf".  So, when I look for this file, I do have permissions to access it -- it is the PDF version of what I am typing.
The other strange thing is I only have the editor open; I've closed the preview window.  So, I guess there are two issues:

*

*Why is it generating previews when I didn't ask it to (has it been turned 'on' somewhere which I don't know about?)?

*How come it's complaining about access to a file which I clearly have access to?  Both the file and the path to the file is accessible by my user ID.

Also, it doesn't happen all the time.  Only sometimes...I cannot figure out the pattern of when it appears.  Maybe once every 5 minutes as I type?
It's somewhat annoying that this error pops up while I'm typing.  Has anyone experienced this and/or know what I should do?
This is Ubuntu 19.10, so kile is version 2.9.92 .
Thank you!

A: Not a solution, but I had the same problem, and this the first google result, so this might be helpful for future people:

*

*The problem seems to happen when you type while the document is already compiling, thus triggering a new compilation. This seems to confuse kile about which pdf is ready when.

*Here is a bug-report for the problem: https://bugs.kde.org/show_bug.cgi?id=417757

*Switching the setting from "compile documents whenever there are changes after X" to "compile documents after saving" circumvents the problem. Of course thats somewhat less convenient, but at least not annying you with popups.

A: Deleting the pdf file '/tmp/kile-livepreview.RDNKpj/p.pdf' worked for me as a workaround whenever that happens. For example you could do in a terminal:
rm /tmp/kile-livepreview.RDNKpj/p.pdf

hope this helps :)


text:
Q: How to auto sync local SQl Database with Microsoft Azure Sql database? I have a ADO.net application which generates some data in regular intervals that is stored in a local SQL server. I want that database to sync with Microsoft azure SQL database automatically. What would be the best process to make it happen?

A: You have two options. One of them is SQL Data Sync which will sync you local database with an Azure SQL Database and viceversa. It is a bi-directional replication that works best with SQL Server 2008 R2 (and later) on-premises databases. This service is in preview and you can get started with it by visiting this documentation.
Your second option is Snapshot and one-way replication that works with SQL Server 2012 and later. You can get started with it on this documentation.
Hope this helps.


text:
Q: Find all minima and maxima of $f(x) = (x+1)^{1/3}(x^2-2x+1)^{1/5}$ Find all minima and maxima of :
$f(x) = (x+1)^{1/3}(x^2-2x+1)^{1/5}$
I feel kind of ashamed by posting such a question but I am not able to get the right answer. I've tried to do it the Fichtenholtz way - probably the most uncreative one and still it didn't work for me.

*

*I calculate the derivative $f'(x) = \dfrac{11x^2-10x-1}{15((x-1)^{8/5}(x+1)^{2/3}} $

*I check how all the constituent functions behave in certain intervals. In that case we can suspect $x=\frac{-1}{11}$, $-1$ , $1$. Let's call the function in the numarator $a$ and take $b$, $c$ for two separate "brackets" in the denominator.
Then we get:
$(-\infty,-1)$: $a -$ , $b -$ , $c +$ , $d +$, so $f'(x) > 0$
$(-1 , -\frac{1}{11})$: $a -$ , $b -$ , $c +$ , $d +$, so $f'(x) > 0$
$(-\frac{1}{11}, 1)$: $a+$ , $b-$ , $c +$ , $d +$, so $f'(x) < 0$
$(1 , + \infty)$: $a,b,c,d$ are positive, so $f'(x) > 0$
Therefore when we look at the signs we can say that there's a minimum at $1$ and a maximum at $-\frac{1}{11}$ which is not true. I realise that's somehow really basic problem but could you tell what I'am doing wrong?

A: Let's compute the derivative of
$$
f(x)=\sqrt[3]{x+1}\cdot\sqrt[5]{x^2-2x+1}
$$
with the (formal) method of the logarithmic derivative:
$$
\log f(x)=\frac{1}{3}\log(x+1)+\frac{2}{5}\log(x-1)
$$
and therefore
$$
\frac{f'(x)}{f(x)}=\frac{1}{3(x+1)}+\frac{2}{5(x-1)}=
\frac{5x-5+6x+6}{15(x+1)(x-1)}=\frac{11x+1}{15(x+1)(x-1)}
$$
so that
$$
f'(x)=\frac{11x+1}{15\sqrt[3]{(x+1)^2}\cdot\sqrt[5]{(x-1)^3}}
$$
Note that the derivative is correct for all $x$, even when its value is negative. Note also that the function is not differentiable at $-1$ and $1$.
We can easily see that the derivative has the same signs as $(11x+1)(x-1)$ (where it exists), so the derivative is

*

*positive in $(-\infty,-1/11)$ (excluding $-1$),

*negative in $(-1/11,1)$,

*positive in $(1,\infty)$

Thus $-1/11$ is a point of maximum, while $1$ is a point of minimum.
You're right: there can be no change in sign around $-1$. This is the graph drawn by GeoGebra

A: The Mathematica plot gives roots at $ x=\pm 1 $ with vertical tangents.The former,a multiple "root", the latter is a cusp/multiple "root". These can be confirmed by conventional maxima/minima calculation.
"Root" in the sense for $ y = 1/x $ passing between $ - \infty \; to -\infty, $ derivative not zero, but $\infty$.
Maximum value at $ ( -1/11,\approx 1.00304) $


text:
Q: How to decide on a new Hard drive for macbook pro I have been using my Macbook Pro for about 5 years, it was the first model with the Intel chip. The 100GB hard drive is starting to go and I'm ready to replace it. I went over to Cnet to see what looks good. Oops. There are about 2,000 products to choose from, and I don't even know how to determine compatibility with my laptop.
What are the steps I should follow to narrow in on a new hard drive?
This machine does a lot of heavy lifting: audio, video, and image processing, etc.
My goals are to increase storage to 250GB minimum (pref. 500+), improve performance, extend my Macbook's life by at least 18 months, spend less than 400$, and easy home install (youtube videos look do-able). I can spend more if there's a good reason to; just wanted to make the question specific.
Follow-up: Is it a given that I should upgrade memory at the same time? (Currently at 2GB SDRAM)

A: I would head on over to a Mac Specific reseller like OWC MacSales, RamJet or   where a company has figured which models are the best to sell based on your specific model.
http://www.ramjet.com/sata.asp
You will see that you have many choices for well under your budget. Also you are spared the SSD/HD decision since your size/price constraint means the quality SSD are not priced in your range.
When you buy from someone that has done the work, they will support you and help you should you run into issues. Get a few options and make the call if you want to buy from someone that will also answer your questions or if you are comfortable buying a community part and ensuring the firmware works, etc...
Since RAM is so easy to swap, you really don't need to include it in the HD exchange other than your budget may be fixed. It's hard to give advice on that front, since your budget is yours and not something that transfers to an internet forum where this question and answer might apply to anyone. Without knowing your specific model and how much RAM is in use routinely based on your apps, it's not possible to advise what the most cost effective combination might be.

A: You would need a 2.5" hard drive to fit in your MBP. Since your MBP is quite old, you have a SATA1 interface. Due to backward compatibility, it is fine to use hard drives with a SATA2 or even SATA3 interface.
In order to most efficiently improve the performance, I would recommend using a SSD because of their high IOPS . Since you are willing to spend up to 400$, there are options to get 250GB of storage. If you need more space, you could buy an enclosure for your old hard drive in order to make use of it.
An upgrade to more than 2GB of RAM is dependent on your usage - but generally recommended. Do you have lots of (large) programs open at the same time? Then yes. But I can tell, that my sister is using 2GB of RAM with Lion an quite happy with. You can monitor your RAM usage with iStat Pro or the Activity Monitor.app to see if your amount of RAM is sufficient.


text:
Q: I don't understand how I am getting segmentation fault When I try to print each character of the file, I get segmentation fault. I don't understand why.
void parseStringAndDelete(char *file)
{
// I a passing "drwxr-xr-x 1 ftp ftp              0 Mar 07 12:34 A_Folder"
// as an argument for the function
 int i = 0;
 int k = 0;
 int len = strlen(file);
 int startIndex = 0;

 //printf("%s\n", file);
 //printf("%d\n", len);
 if(file[0] == 'd')
  {
      for(i = 0; i<len; i++)
      {
        printf("%s\n", file[i]);
      }
  }

}

A: If you want to print each character of the string, then you should use %c and not %s.
printf("%c\n", file[i]);

Additionally,
When printing a string using printf("%s", ..), you need to pass an address where the string is residing, not the content of the address.
So, for a char* str = "hello", print statement would be
printf("%s\n", str);

and NOT
printf("%s\n", str[0]);


text:
Q: Does Django's 'exact' field lookup perform a case-insensitive search? From what I read on the Django manual, I thought that the exact field lookup would perform a case-SENSITIVE search, yet, when I do this
FormZBaseElementExtraLabel.objects.filter(label__exact='his6')
I get the following output
<QuerySet [<FormZBaseElementExtraLabel: HIS6>]>
clearly not case-sensitive, and in fact identical to the default filter  or iexact.
Any ideas as to what could be the problem?
Thank you

A: Thanks to all for the answers. Indeed, I've realized that I use MySQL (MariaDB) with collation utf8mb4_unicode_ci, which explains why the exact query lookup works case-insensitively.
Without changing the collation of the underlying database (or some of its columns specifically), as pointed out, the following search is case-sensitive FormZBaseElementExtraLabel.objects.filter(label__contains = 'his6').filter(label = 'his6'). Alternatively, one could run a custom query using the raw method as explained here.

A: Actually __exact is for Exact match
And __iexact is for Case-insensitive exact match
for more info you can visit the django documentation queryset page

A: Try this:
To case-SENSITIVE search
FormZBaseElementExtraLabel.objects.filter(**{'label__contains': 'his6'})

A: I made this one which utilizes BINARY expr for MySQL string case-sensitive match:
from django.db.models.fields import Field
from django.db.models import Lookup

@Field.register_lookup
class StrExact(Lookup):
    """
    MySQL string case sensitive string lookup
    """

    lookup_name = 'str_exact'

    def as_sql(self, compiler, connection):
        lhs, lhs_params = self.process_lhs(compiler, connection)
        rhs, rhs_params = self.process_rhs(compiler, connection)
        params = lhs_params + rhs_params
        return "%s = binary %s" % (lhs, rhs), params

Usage:
FormZBaseElementExtraLabel.objects.filter(label__str_exact='his6').count()

Read more about Custom Lookup https://docs.djangoproject.com/en/3.0/howto/custom-lookups/


text:
Q: Remove Fujitsu Lifebook Bios Password on Startup I Tried to remove the Boot up Bios password in a Fujitsu Lifebook Bios SH530 Model. But it still asking for password on bootup and now may password did not work. Can anybody help me? Here's what I did:

*

*Press F12 on Bootup

*Sign in using the old password

*Go to Security Settings Tab

*Change the Boot up Password by Typing in the Current Password and leaving the New Password Inputbox Blank. I just press enter 2x.

*exit the bios screen and save settings

*<-- The Worst next time I Boot up it still ask for password but my old password did not work. I tried just leaving it blank and press enter but it is Invalid! I tried 3x and wooops a non stop long beepp sounded with SYSTEM DISABLED on screen no Hash code or what so ever.

What did I do Wrong? Do anyone have this experience? What did you do to solve this problem?
PS. I do not know the supervisor password for it.
UPDATE:

*

*It seems the Master Password will only show up on boot before loading windows 7. If will not show up on Bios Settings. I'm currently using this page to decrypt the hash code http://bios-pw.org/

*My question now is how do you display the Master Password Hash in Bios Setup? If I can get it I can decrypt it and hopefully remove the password.

A: I finally solved my problem after 9hrs :)
I did not know why my BIOS locked up suddenly (I posted the step by step procedure of what I done before this thing happen. see my question)
Laptop Model: Fujitsu Lifebook Bios SH530 (Acquired late 2010)
Fujitsu-Siemens use many different algorithms to calculate master password. But it can be decrypted using the master password hash on wrong password attempts after 3x
Solution:

*

*On boot screen Press F2. You must be in Bios Setup Screen which is (Phoenix SecureCore(tm) Setup Utility)

*Attempt to login using this passwords: "3hqgo3", "jqw534", "0qww294e" (Do not enter again passwords until you get master password)

*If a Master Password is displayed copy it and use this windows binary script sites.google.com/site/dogber1/blag/pwgen-fsi-5x4dec.zip  or using this website bios-pw.org/ Enter the Hash Codes

*On the Master Password Input Box use the decrypted code if you use the online site use the Fujitsu-Siemens

*You should be able to access the bios screen and change the settings make sure to remove the Password on Hard Disk and Supervisor Password

*Use the Decrypted hash code as your current password To Clear the Supervisor Password

Sources:
http://dogber1.blogspot.com/2009/05/table-of-reverse-engineered-bios.html
http://www.edaboard.com/thread285866.html (See Fujitsu-Siemens Part)
Also thanks to Karan for pointing out the link for reverse engineered bios...
What a day..

A: Use 33537441 as the Master Password corresponding to the 1E37-9837-02D6-735F-9984 code.
Sources: 1, 2


text:
Q: Emit function on sinon mock I have a function that I need to test using sinon. It takes two arguments and has different events that can be raised. I'm trying to simulate the 'ready' evet made to simulate a successful SFTP connection
function configureSFTPConnection(conn, connectionSettings) {
    'use strict';

    return new Promise(function(resolve, reject) {
        conn.on('ready', function() {
            resolve(conn);
        }).on('error', function(err) {
            reject(err);
        }).connect(connectionSettings);
    });
}

I can simulate the exterior connect function.
configureSftpStub = sinon.stub(clientObject, 'connect');

How can I force the ready callback to execute, completing the promise?
This is what I'm trying:
clientObject = new client();
configureSftpStub = sinon.stub(clientObject, 'connect');
configureSftpStub.onCall(0).returns(function() {
    console.log('trying to do something');
    resolve();
});

The .onCall() never seems to run.

A: What was needed was rather than trying to return something I needed to replace the function that was called and do a simple .emit call within the function.
configureSftpStub = sinon.stub(clientObject, 'connect', function() {
    this.emit('ready');
});


text:
Q: How to retrieve xml data with value specified Hi I'm new to Oracle 10g. I need retrieve the all the sublist from 'fl1'. I know to retrieve tagwise.. How to retrieve tagwise with value specified?
 <lists> <Firstlist name = 'fl1'>
     <sublist>s1</sublist>
     <sublist>s2</sublist>
     <sublist>s3</sublist>
 </firstlist>
 <Firstlist name = 'fl2'>
     <sublist>sb1</sublist>
     <sublist>sb2</sublist>
     <sublist>sb3</sublist>
 </firstlist> </lists>

A: Actually it's more of a XPATH question:
//Firstlist [@name = "fl1"]/sublist

So the query could be something like this:
SELECT xmlelement("r",xmltype(xmlstr)).extract('//Firstlist [@name = "fl1"]/sublist').getstringval() FROM your_table

Here is a fiddle


text:
Q: how to make TextField validations start with 10 number and end with 99 in Ios Hi i am beginner in Ios and in my project login page there is textfields validations(here i have two textfields they are medicaId,password)
my medicaid must allows only numbers and medicaId starts with 10 and ends with 99 if not then i want show alert Invalid medicaId
but according to my experience i could able to do only textfield allows numbers but i am not understand how to do that textfield(my medicaid) starts with 10 and ends with 99 please help me some one
my code:-
#import "ViewController.h"

@interface ViewController ()

#define ACCEPTABLE_CHARECTERS @"0123456789"

@end

@implementation ViewController

@synthesize textfield;

- (void)viewDidLoad {
    [super viewDidLoad];
    textfield.delegate = self;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {

    if (textField==textfield)
    {
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS] invertedSet];

        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

        return [string isEqualToString:filtered];
    }
    return YES;
}

-(IBAction)CickMe:(id)sender{

    if (success) {

        NSLog(@"validations are perfect");
    }else{

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"MedicaId must starts with 10 and ends with 99" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Cancel", nil];
        [alert show];
    }

}

A: My answer works perfectly.
- (IBAction)ClickMe:(id)sender
{
  NSString *strID = textFieldUserID.text;
  NSString *strLastTwoIndex = [strID substringFromIndex: [strID length] - 2];
  NSLog(@"The strJoinedStr is - %@",strLastTwoIndex);
  if([strID hasPrefix:@"10"] && [strLastTwoIndex isEqualToString:@"99"])
  {
    NSLog(@"Success");

  }
  else{
    NSLog(@"Failure");
  }
}

The console output is
Success

A: You can take string from text field and check using set operation that if it contains only number or not.
Then use the NSString function like hasPrefix and hasSuffix to check, if it has certain value at start or end.
-(void) validate
{
    BOOL isSuccess = FALSE;
    NSString *input = textField.text;
    if(input.length > 4)
    {
        if([input hasPrefix:@"10"] && [input hasSuffix:@"99"])
            isSuccess = TRUE;
    }
}

A: In general these kind of constraints can easily be solved using regular expressions. They allow you to easily specify quite complex constraints on a given input string. (as long as you do not want to count). Take a look here for how to use regular expressions in Objective-C.
BUT you have a slightly different situation here that you have to deal with: the user is not going to input the entire string at once - he will input character after character. It is pretty much impossible to check during the user input wether or not what he is going to end up with might be a valid input. For example there will not be a leading 99 when the user types in the first few chars. You can certainly prevent him from typing in anything else other than numbers since they will ne never be a valid character anywhere in the entire input.
If you implement the entire validation inside shouldChangeCharactersInRange you are going to have a bad day:
Imagine the user starts typing

1 - does not start with 10 and does not end with 99 -> reject
  10 - does not end with 99 -> reject
  102 - does not end with 99 -> reject
  1029 - does not end with 99 -> reject
  10299 - approve
  1299 - does no longer start with 10 -> reject

If you actually reject invalid input the user would never be able to get to a valid input since the starting point always will be invalid.
All you can do is perform a check and notify the user that the input is invalid - but you must not reject the input. (You can display an exclamation mark, change the font color, etc.)
As @Apurv wrote, in your "simple" situation you would probably not even need to use a regular expression but could use basic string operations. But the above statements regarding not rejecting the user input during the input remains true.
A slight variation of the strict statement above is that you can actually reject any non-number character since they will always create an invalid input.

A: Instead of dealing with hand-made methods you should really use Cocoa's core technologies.
A. Number Formatters
You should read the introduction to number formatters. Instances of NSNumberFormatter  support a range with minimum and maximum values. Moreover, they transform strings to numbers and back.
B. Key-Value-Validation
The intended concept for value validation is key-value validation. You should alway implement this instead of custom-made methods. (I. e. you get the benefit, that technologies in Cocoa uses this methods, when doing its own validation.)
After allowing only numbers, you only have to filter out illegal values. In your case it would be:
-(BOOL)validateYourPropertyNameHere:(id *)ioValue error:(NSError * __autoreleasing *)outError {
  // Do some checking, i. e. …

}

Typed in Safari.
It is a littlebit tricky, because you have three options:

*

*The value is correct: Simply return YES.

*The value is incorrect, but can be converted to a correct value (i. e. input is 103 and you want to convert it to 99): create a new object and assign the reference to ioValue, return YES.

*The value is incorrect and you cannot or don't want to convert it to a correct value: return NO.

C. Using
You use your validation method from everywhere you deal with the take-over of the input. simply:
NSError *error;
if( [self validateYourPropertyNameHere:&userInput error:&error] == NO )
{
  // Display error or whatever
}
else
{
  // Use value
}

Don't hesitate to add comments, if you have more questions.
BTW:
#define ACCEPTABLE_CHARECTERS @"0123456789."
#define MAX_LENGTH 5

… is really no good style. But this is another Q. Maybe you should have a look at least at NSCharacterSet.


text:
Q: How to make the movement of the circles smoother? I would like to make the movement of the three randomly generated circles smoother. Can anyone help me with that? Thank you in advance :) Here is my current code:
import tkinter
from time import sleep
from random import randrange

class Circle:
    def __init__(self, color):
        a = randrange(250)
        b = randrange(250)

        self.color = color
        self.id = canvas.create_oval(a,b,a+40,b+40, fill=self.color)

    def move(self):
        canvas.move(self.id, 5,15)

window = tkinter.Tk()
window.geometry("500x400")
canvas = tkinter.Canvas(width=400, height=300)
canvas.pack()

circle1 = Circle('red')
circle2 = Circle('yellow')
circle3 = Circle('blue')

while(3):
    canvas.update()
    sleep(1)
    circle1.move()
    circle2.move()
    circle3.move()

window.mainloop()

A: Use tkinter.after instead of sleep, and let the mainloop do its work, instead of a while loop and canvas.update().
something like this:
import tkinter
from random import randrange

class Circle:
    def __init__(self, color):
        a = randrange(250)
        b = randrange(250)

        self.color = color
        self.id = canvas.create_oval(a,b,a+40,b+40, fill=self.color)

    def move(self):
        canvas.move(self.id, 1, 1)

def move_circles(circles):
    for circle in circles:
        circle.move()
    window.after(10, move_circles, circles)

window = tkinter.Tk()
window.geometry("500x400")
canvas = tkinter.Canvas(width=400, height=300)
canvas.pack(expand=True, fill=tkinter.BOTH)

circle1 = Circle('red')
circle2 = Circle('yellow')
circle3 = Circle('blue')

circles = [circle1, circle2, circle3]

move_circles(circles)

window.mainloop()


text:
Q: Kubernetes how to have pods initiate only during runtime through python? In kubernetes, if I desired to have pods for a specific task not always required is it possible to have the system spin pods up for a given task when needed? Can this be managed through the backend code (in my instance python)? Do services need to be defined in a certain way in advance?
I found an api for docker management in Python, would this work for Kubernetes?

A: If i have understood correctly you want to run the PODs when required not all the time.
in that case you can use the python client library of Kubernetes and manage the PODs or replicas of deployment.
you can deploy your service with replica count zero and once required you can scale up the pods using the client to as much required.
Kubernetes python client: https://github.com/kubernetes-client/python
if your service is already running you can use this API :
GET /apis/extensions/v1beta1/namespaces/{namespace}/deployments/{name}/scale

here using just curl also you can spin up the replicas
API_URL="http://kubernetes:8080/apis/extensions/v1beta1/namespaces/{namespace}/deployments/{name}/scale"
curl  -H 'Accept: application/json' $API_URL > scale.json
# edit scale.json
curl -X PUT -d@scale.json -H 'Content-Type: application/json' $API_URL

A: I don't know exactly what you want to achieve because you are not giving enough information. Here are some tools you migh want to check:
keda - event driven autoscaler, can scale down to zero
k8s jobs - runs one time jobs
knative - can scale down to zero
You can also just use k8s python client library to run a pod, make it do whatever you want and then delete it.


text:
Q: accesskey internet explorer I have a weird problem, I can not mek work the accesskey on any version of Internet Explorer.
My code :
<a href="<?php echo get_site_url(); ?>/accessibilite" accesskey="0">

The accesskey work on chrome and firefox but not in intenet explorer, if anybo have a solution, thanks !

A: To access the shortcut key in IE, you should press Alt + accesskey.
Prevent using the existing shortcut keys in the IE's menu and also, try to use other characters like "s"
In my case, I've tested it with IE11 and it works for character "s" but not "0" for some reason
StackOverflow


text:
Q: Apache tomcat server 7.0.42 fails to start after running ant build script I am using apache ant 1.9.4. I have written build xml for starting apache tomcat server 7.0.42. But the server closes as soon it gets started. Also the build is showing successfull.
My build.xml is.,

<property name="build.dir" value="aar" />
<property name="deploy-location" value="D:\EIT SOFTWARES\apache-tomcat-7.0.42_aqar\webapps" />
<property name="catalina.home" value="D:\EIT SOFTWARES\apache-tomcat-7.0.42_aqar"/>
<property name="tomcat" value="${catalina.home}" />
<target name="start-tomcat">
    <echo message="Starting tomcat">
    </echo>
    <exec executable="${catalina.home}\bin\startup.bat"></exec>
    </echo>
</target>

What i am making wrong. Ant experts please help me.


text:
Q: Css3 - first-child and last-child selector issues I am having trouble coding my first and last child selectors.
Firstly I would like to remove the right border off the last child of the parent navigation menu only (not the drop down menus), my current code is affecting the drop down menu also. I am having the same issue with removing the left border off the first child.
Secondly, I wanted to add a box shadow to the left and right of the parent navigation menu, but this is also impacting on the drop down menu.
I would appreciate some advice on where i am going wrong. Thanks
My CSS3 code is:
 ul#navmenu li:last-child a  {border-right: none;}

 ul#navmenu li:first-child a {border-left: none;}

 ul#navmenu li:last-child {box-shadow: 200px 0px 0px 0px white;}

 ul#navmenu li:first-child {box-shadow:-200px 0px 0px 0px white;}

A: Access the direct child of the ul elements like below using > for direct child selector
 ul#navmenu > li:last-child a  {border-right: none;}

 ul#navmenu > li:first-child a {border-left: none;}

 ul#navmenu > li:last-child {box-shadow: 200px 0px 0px 0px white;}

 ul#navmenu > li:first-child {box-shadow:-200px 0px 0px 0px white;}

Your current selector is ul#navmenu li this means to select all the li tags that come under the ul which can be at any level deep.
But this selector ul#navmenu > li restricts the selection to only the immediate child of ul#navmenu and this is what you need.


text:
Q: Options for sessions handling in IIS What options are there for session handling with a modern .NET IIS Web architecture?
I understand that IIS' native session support loses sessions upon restart.  Furthermore, Microsoft recommends sessions be stored in the database, which is my preferred solution.
I am attempting to architect a highly available .NET IIS platform, which scales horizontally for a third party application.  The application is developed externally and while I can push for storing in a database but that will not be possible for an immediate deadline.
The third party recommends using persistent sessions, which is something I avoid.  Sticky sessions will lessen availability, as when the Web server becomes unavailable it will cause accessibility issues to the clients that were previously using it.  Moreover, it lessens the load balancing functionality, as a single server may receive potentially more requests than the others.  IIS will still lose sessions upon restart, which is something I would prefer to eliminate.  I also do not want to store the session in a cookie on the client side.
I want to enable complete high availability, while still allowing application deployment to idle servers without impact.  Additionally, full load balancing.  Can I enable this functionality on this technology platform without rewriting the application?  What options do I have?

A: ASP.net 2.0 and above supports storing session in SQL server simply by changing the SessionState provider in web.config and using aspnet_regsql.exe to setup the SQL database. You can read more about configuring the Session State Provider at the MSDN - Session State Providers page.
Update: A much easier read with step-by-step instructions is also available at the MSDN - Session State Modes page.

A: We talked about the modularity of the .NET Session State Providers at the Ohio Linux Fest and I mentioned that somebody could create a distributed in-memory cache for .NET Session State. A Customer asked me about it earlier today and I found this product that appears to do just that.


text:
Q: How to handle (complete or totally remove) incomplete trajectories drawn in a phase portrait? For the following nonlinear system
xdot = x + exp(-y)
ydot = -y

whose phase portrait is:
import numpy as np
import matplotlib.pyplot as plt

xvalues, yvalues = np.meshgrid(np.arange(-5, 5, 0.1), np.arange(-5, 5, 0.1))
xdot = xvalues - np.exp(-yvalues)
ydot = - yvalues
plt.streamplot(xvalues, yvalues, xdot, ydot, color='r', linewidth=0.5, density=1.2)
plt.show()

However, some of the trajectories are (visually-unappealing) incomplete arcs like the blue ones highlighted below:

I need to (i) eliminate those arcs off the plot or (ii) make them complete just like, e.g., the black one. How can I achieve this?
can I achieve the following changes

A: As of Matplotlib version 3.6.0, an optional parameter broken_streamlines has been added for disabling streamline breaks.
Adding it to your snippet (and halving the density to compensate for the visual clutter) produces the following result:
import numpy as np
import matplotlib.pyplot as plt

xvalues, yvalues = np.meshgrid(np.arange(-5, 5, 0.1), np.arange(-5, 5, 0.1))
xdot = xvalues - np.exp(-yvalues)
ydot = - yvalues
plt.streamplot(xvalues, yvalues, xdot, ydot, color='r', linewidth=0.5, density=0.6, broken_streamlines=False)
plt.show()

Note
This parameter just extends the streamlines which were originally drawn (as in the question). This means that the streamlines in the modified plot above look uneven, due to the way the streamline start points are chosen (see the documentation for the density parameter of matplotlib.pyplot.streamplot for more details on how streamline start points are chosen).
For accurate streamline density, consider using matplotlib.pyplot.contour, but be aware that contour does not show arrows.


text:
Q: How to know if there are two identical elements in the same map in Java I used nested map,
Map<String,Map<String,List<String>>> scheduleMap = new HashMap<>();

and I put three elements in the map, studentId, subject, major.
As examples for input,
    scheduleMap1.add("30600001", "INFO1105", "IT");
    scheduleMap1.add("30600001", "ELEC1603", "ElecEng");
    scheduleMap1.add("30600002", "INFO1103", "IT");
    scheduleMap1.add("30600003", "INFO1003", "IT");
    scheduleMap1.add("30600001", "ELEC1601", "ElecEng");
    scheduleMap1.add("30600002", "INFO1003", "IT");
    scheduleMap1.add("30600002", "ELEC1603", "ElecEng");
    scheduleMap1.add("30600001", "INFO1003", "IT");

were put in the map.
The final purpose was that, for each student id, 30600001, 30600002 and 30600003, if there are two identical majors stored in whichever in the key, the count should be increased.
For example, as shown in the example, 30600001 has two "IT" and two "ElecEng" each as its major element. So the count should be equal to 2.
For studentId, 30600002, it has two "IT" but has only one "ElecEng" as its major element so the count should be 1.
I could achieve my goal by coding like this:
for(Entry<String, Map<String, List<String>>> studentId : scheduleMap.entrySet()) {

 for(Entry<String, List<String>> subject : studentId.getValue().entrySet())
 {
    for(String major : subject.getValue())
    {
      if(major.contains("IT"))
      {
         it++;
      } else if(major.contains("ElecEng")) {
          elec++;

        }
          if(it >= 2 || elec >= 2)
          {
            count++;
          }
    }

however, is there any way to get the counts by not pointing out the finding major like major.contains("IT") and major.contains("ElecEng")?
I really want to get the count increased by doing like,
if(everytime key.subject.major has two identical elements)
{
   count++;
}

Any help would be great. Thanks!

A: Map in general don't support two key-value set with the same key. Each and every key must be unique.
Refer to this.


text:
Q: Webmaster randomly reporting a massive increase in 404s (apparently from old sitemaps) Well, I'm stumped. Several months back, we launched a totally new website, replacing a legacy system that was pretty messy. Part of the mess was many, many pages created that really didn't need to be there or be crawled by Google. There was a lot of duplicate and shell data that resulted in extra URLs crawled and indexed by Google. With the site transition, we of course broke some of these URLs, but it didn't seem to be too much concern. I blocked ones I knew should be blocked in robots.txt, 301 redirected as much duplicate data as I could (this is still an ongoing process), and simply returned 404 for any others that should have never really been there.
For the last 3 months, I've been monitoring the 404s Google reports in Webmaster, and while we had a few thousand due to the gradual removal of shell and duplicate data, I wasn't too concerned. I've been generating updated sitemaps for Google multiple times a week with any updated URLs. Then, about a week ago, Webmaster started to report a massive increase in 404s, somewhere around 30,000 new 404s a day (making it impossible for me to keep up). My updated sitemaps don't even have 30,000 URLs in them. The 404s are indeed for incorrect URLs, and for URLs that haven't existed for months and haven't been in a sitemap for as long. It's like Google decided to randomly use a sitemap from many months ago, as I have no other idea why it'd all of a sudden crawl a URL for data that hasn't existed for many months and is definitely not linked anywhere (although Webmaster claims it's linked in the sitemap....which it is not).
Does anyone have an explanation for this? I even got an auto message from Webmaster Tools this morning reporting that it has seen a significant increase in 404s from my site. I'm not quite sure how concerned I should really be about this...

A: Are the 404 errors all from Google Bot or are they real users? If the former, you might be right that they've used an old sitemap or that they're re-crawling old URLs to check that they are indeed invalid. Who knows how the Bot works, but it generally does the right thing - your 404 pages won't appear in the search results, so who cares?
If they are real users, you should look into where they came from using the referrer header. Hopefully you can then find the source of the problem. The referrer header is sometimes blank but for a sample this big, I'd expect quite a lot of data to be available.


text:
Q: get the exact width of an image with height:100%; using jquery When I set the height of an image 100%, the width is calculated automatically in order to keep the image aspect ratio.
Most of the times the width of such image is not an integer but double (like 645.34).
$("#myImg").width() returns me always an integer.
How can I get the exact width of such an image using jquery?

A: The actual applied width will always be equated to an integer value of pixels by the browser. There is no renderable half-pixel. We can specify 22.5px etc, but it will be rounded to the nearest integer by the browser. Some browsers may however anti-alias the edge pixels to simulate half-pixels, still the applied width/height value will always be an integer.


text:
Q: How to handle Java method calls from XSLT while debugging XSL files? I am trying to debug an XSLT in Eclipse using Xalan 2.7.1 processor. But whenever it comes to a point where there is a call made to any Java method, it terminates with the exception saying could not find perticular method.
I have searched this forum thoroughly but didn't find any question/answer which addresses this type of issue.
Is there any other way we can debug XSLT with java calls , can we use intellj-xslt debugger here ?


text:
Q: Symlink to Files & Dirs in Dropbox I just installed Dropbox on my Mac, so now I have this Dropbox folder in my home directory.
I only have the free plan (2 GB), so I can't just throw all my files & directories in there.
I currently store all my projects in my ~/Projects directory.
Should I just move files I want to store into Dropbox, or should I also create a symlink ln -s (or should I use Mac Alias instead?) so that I can also access the file outside of my Dropbox directory?
I'm thinking if I move a whole project to the dropbox that's cool. But, in some cases, I might only want to Dropbox some of the files in a project, in which case I'll also want to have those files inside the project directory, esp. since I usually track my individual projects with Git.
How do you do it?

A: I just keep my git repositories in Dropbox. Dropbox doesn't seem to have any issue with conflicts... or at least I haven't experienced any problems with keeping git repos on Dropbox for the last year or so.
Why would you want to access files outside the Dropbox directory?

A: The Dropbox help has an article about this.
The rest of your question is subjective and argumentative. Do you have more specific requirements?


text:
Q: Show email as starred How can I show email as starred using javascript?Suppose I have an email
abcdefg@stackoverflow.com, I am to show it as a*****g@stackoverflow.com. Can someone help me achieve this?
I can do this but I want a better method to achieve this
email = email.split('@');
username = email[0];
var str = '',i;
for(i=0;i<username.length;i++){
    if(i!=0) {
        str+= '*'
     }
     else
        str+=username[i]
};
email[0] = str;
var result = email.join('@');

A: If you're looking for brevity:
ES6:
email.replace(/^(.)(.*)(.@.*)/, (...a) => a[1] + a[2].replace(/./g, '*') + a[3]);

ES5:
email.replace(/^(.)(.*)(.@.*)/,
    function(m, a1, a2, a3) { return a1 + a2.replace(/./g, '*') + a3 }
);

Given an email abcdef@example.com, the regex splits the string into 3 parts: ['a', 'bcde', 'f@example.com']. The callback then puts it back together, replacing all characters of the second chunk with asterisks.

A: Better as in shorter? More readable? This is the shortest I could come up with that is not very readable:
let email = "abcdefg@stackoverflow.com"
let at = email.indexOf("@")
return email[0]
       + email.substring(1, at).replace(/./g, "*")
       + email.substring(at, email.length)


text:
Q: how to create transition system/automata for modulo 4 I don't know how to think when to build a transition system/automata to calculate modulo 4 a of binary numbers.
I know that the last two binary digits gives the rest but I need to go through  hole numbers like 1100010.


text:
Q: I want to find the number of days between two dates Here is some prototyping code that given two dates will print the time between them:
from datetime import datetime
date_format= "%m/%d/%y"
now=datetime.now()
print now
d1=datetime.now()
d2=datetime.strptime('07/21/14',date_format)
delta= d2-d1
print delta

I'd like to modify this, such that it asks the user for two dates, instead of hardcoding the date in the source code.
So far, I've written:
date1=raw_input("What is date 1 ?:")
print date1
date2=raw_input("What is date 2 ?:")
print date2
delta=date2-date1
print delta

But after I type in my dates, I get the error:
Traceback (most recent call last):
  File "C:/Python27/datetimetest.py", line 17, in <module>
    delta=date2-date1
TypeError: unsupported operand type(s) for -: 'str' and 'str'

A: You need to convert the strings that you get from raw_input() into date objects. Like you do in the original code.
from datetime import datetime

date_format= "%m/%d/%y"

date1 = raw_input("What is date 1: ")
date1 = datetime.strptime(date1, date_format)

date2 = raw_input("What is date 2: ")
date2 = datetime.strptime(date2, date_format)

print
print 'Date 1:', date1
print 'Date 2:', date2
print 'Delta: ', date2 - date1

If we run this:
What is date 1: 3/14/12
What is date 2: 3/16/12

Date 1: 2012-03-14 00:00:00
Date 2: 2012-03-16 00:00:00
Delta:  2 days, 0:00:00


text:
Q: Trying to get a fibonacci numbers lower than a input number in a fibonacci loop in c++ I'm trying to build a program that asks a user for a number "k" and print a series of numbers lower than the number k.
For example if the user writes 20 the output has to be:
0, 1, 1, 2, 3, 5, 8, 13

Instead I got:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181

This means that are printing 20 Fibonacci numbers.
#include <iostream>

using std::cin;
using std::cout;
using std::endl;

unsigned int fib(unsigned int num)
{
    if (num == 0 || num == 1)
    {
        return num;
    }
    else
    {
        return (fib(num - 1) + fib(num - 2));
    }
}

int main()
{
    int k = 0;

    cout << "White a number k ";
    cin >> k;

    for (int i = 0; i < k; i++)
        cout << fib(i) << endl;

    return 0;
}

I tried using "break;" but is does not work. How can I break the loop?

A: You are comparing the inputed k limit with the iterator i, so the input is read as the quantity of numbers in the fibonacci sequence you want to output, not the upper limit.
To do what you want you need to compare the limit k with the fib function returned result so that you can stop the loop as soon as the limit is exceeded.
Live demo
Keeping the for loop:
int main()
{
    int k = 0;
    int res = 0; // store the result of fib(i) to avoid duplicate calls

    cout << "White a number k: ";
    cin >> k;

    for (int i = 0; (res = fib(i)) < k; i++){ //assign fib(i) to res
        cout << res << endl;                  //when res is larger than k exits the loop
    }
    return 0;
}

Or using a while loop:
int main()
{
    int k = 0;
    cout << "White a number k: ";
    cin >> k;
    int res;
    int i = 0; //iterator

    while((res = fib(i++)) < k) { //assign result to res and compare it with the limit k
        cout << res << endl; //output the result while it's smaller than k
    }
    return 0;
}

Sample run:
White a number k: 20
0
1
1
2
3
5
8
13

A:   for (int i=0; i<k; i++){
      if(fib(i)<k)    //while fib(i) is less than k,it prints fib(i)
       cout << fib(i) << endl;
      else            //if number becomes greater than k,then it will break out from the loop.
       break;
    }

Hope it helps!!


text:
Q: Search people in Twitter in Java (Twitter4j) Does anyone know a way to use Twitter4j or any other lib in order to search people in Twitter through its API? I am trying to find out if specific people have Twitter accounts.
Thanks for the help.

A: This should answer your question. This should help you build a basic query

A: This is the API for searching users in twitter:
https://api.twitter.com/1.1/users/search.json?q=UserName


text:
Q: Getting stuck with sending password reset email in django I am trying to add user password reset functionality in my Django app using its core password reset functionality, with the help of a tutorial from Corey MS's youtube channel. I did exactly what he did. I am getting no error, but no emails are being sent.
I have tried with my personal email server. I checked it using another python script using python smtplib and MIME, sending emails for me perfectly. But in Django, nothing happening.
Then, I have gone through several articles and QAs. At last, I set up a local email server using the command-line with this
python -m smtpd -n -c DebuggingServer localhost:1025 command. But the result is the same. Command-line says an email sent. But its not actually.
Here are my screenshots and relevant codes.
my app says, email sent.

success message and project structure:

settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_PORT = 1025

urls.py
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from users import views as user_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('register/', user_views.register, name='register'),
    path('profile/', user_views.profile, name='profile'),
    path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
    path('password-reset/',
         auth_views.PasswordResetView.as_view(
             template_name='users/password_reset.html'
         ),
         name='password_reset'),
    path('password-reset/done/',
         auth_views.PasswordResetDoneView.as_view(
             template_name='users/password_reset_done.html'
         ),
         name='password_reset_done'),
    path('password-reset-confirm/<uidb64>/<token>/',
         auth_views.PasswordResetConfirmView.as_view(
             template_name='users/password_reset_confirm.html'
         ),
         name='password_reset_confirm'),
    path('password-reset-complete/',
         auth_views.PasswordResetCompleteView.as_view(
             template_name='users/password_reset_complete.html'
         ),
         name='password_reset_complete'),
    path('', include('blog.urls')),
]

password_reset.html
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}

        <form method="POST">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">Reset Password</legend>
                {{ form|crispy }}
            </fieldset>

                <button class="btn btn-outline-info" type="submit">Request Password Reset</button>

        </form>

{% endblock content %}

password_reset_done.html
{% extends "blog/base.html" %}
{% block content %}

        An email has been sent with instructions to reset your password

{% endblock content %}

password_reset_confirm.html
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}

        <form method="POST">
            {% csrf_token %}
            <fieldset class="form-group">
                <legend class="border-bottom mb-4">Reset Password</legend>
                {{ form|crispy }}
            </fieldset>

                <button class="btn btn-outline-info" type="submit">Reset Password</button>

        </form>

{% endblock content %}

password_reset_complete.html
{% extends "blog/base.html" %}
{% block content %}

        Your password has been set.

    Sign In Here
{% endblock content %}

Please comment if I need to add more details.
Please let me know, why my code is not working? what else I need to do?

A: First i would test your email settings with a simple test mail doku.
At my server i set following varibles in the settings.py file:

*

*EMAIL_HOST,

*EMAIL_PORT,

*EMAIL_HOST_USER

*EMAIL_HOST_PASSWORD

*EMAIL_USE_TLS

A: Since we are using the auth users of Django, then all we know is that the User model comes with the built in Django view, then if we are using the email address for receiving Django reset password link, we should write the same email that we registered when we create account.
EMAIL_HOST_USER : 'youremail@gmail.com'

This email should be the same as the one you registered with, I mean the one that you use when you registered and that is in the database under using of a specific user.
So use this email also when you are sending a password reset from Django to the Gmail server.


text:
Q: click event for LWUIT label I am new to LWUIT platform. I am developing an application and I
want to add click events to Label and a container.
Is it possible or not?

A: No, Labelis not for clickable events. Use a Button with an aspect of a Label. It will be more easy for you. Containerscould have click events but It will be harder.


text:
Q: Will an application launch if it is already running? I am making an app and I am putting the final touches on it and i was wondering, if the user presses the "home" button while the application is running, then clicks on the icon to try to run it again, what will the app do? Will it bring the current app to the front? Will it run a new instance? I am wondering because my app has a lot of threads and if the user was running 2 instances of my app it would kill their battery life.

A: It depends on the android:launchMode of your activity, set in the Manifest.
With the default setting the system always creates a new instance of the activity in the target task and routes the intent to it.
See the reference for detailed info.


text:
Q: How can I interpret the "controlling terminal" code of ps output? The controlling terminal output of ps lists things "Ss+". How can I determine what these codes mean? I tried looking through the ps manual, which is a 30-page document, I found no explanation.

A: From man ps:
PROCESS STATE CODES
       Here are the different values that the s, stat and state output specifiers (header "STAT" or "S") will display to describe the state of a process:

           D    uninterruptible sleep (usually IO)
           R    running or runnable (on run queue)
           S    interruptible sleep (waiting for an event to complete)
           T    stopped by job control signal
           t    stopped by debugger during the tracing
           W    paging (not valid since the 2.6.xx kernel)
           X    dead (should never be seen)
           Z    defunct ("zombie") process, terminated but not reaped by its parent

       For BSD formats and when the stat keyword is used, additional characters may be displayed:

           <    high-priority (not nice to other users)
           N    low-priority (nice to other users)
           L    has pages locked into memory (for real-time and custom IO)
           s    is a session leader
           l    is multi-threaded (using CLONE_THREAD, like NPTL pthreads do)
           +    is in the foreground process group

A: Look for the tt column from ps output and use tty command like so:
$ps ax |more
  PID   TT  STAT      TIME COMMAND
    1   ??  Ss     4:58.84 /sbin/launchd
   66   ??  Ss     1:05.03 /usr/sbin/syslogd
   67   ??  Ss     0:21.62 /usr/libexec/UserEventAgent (System)

$ps ax |grep bash
81939 s000  S+     0:00.09 -bash
82152 s001  S      0:00.04 -bash
82228 s001  S+     0:00.00 grep -I bash

$tty
/dev/ttys001

$ps ax |grep offlineimap-load
82261 s000  S+     0:00.02 /bin/bash /Users/pbarganski/Documents/bin/offlineimap-load
82417 s001  R+     0:00.01 grep -i offlineimap-load

From the above, tty command tells me which terminal I am currently in - terminal 's000' in this case.
From the last command, you'll notice that the grep -i command was run from terminal s001, my current terminal window, however, the offlineimap-load script is running from controlling terminal s000 - my first terminal session - which in this case, is simply the first tab terminal in terminal.app.


text:
Q: How to use Polly with Flurl.Http? Currently I have this request:
await url
    .SetQueryParams(queryString)
    .SetClaimsToken()
    .GetJsonAsync<T>()

I'd like to start using Polly (https://github.com/App-vNext/Polly) now to handle retries and provide a better user experience. For instance, not "hanging up" on the user on the first attempt due to bad network connection. This is the example I was trying to use:
int[] httpStatusCodesWorthRetrying = { 408, 500, 502, 503, 504 };
Policy
    .Handle<HttpException>()
    .OrResult<HttpResponse>(r => httpStatusCodesWorthRetrying.Contains(r.StatusCode))
    .WaitAndRetryAsync(new[] {
                    TimeSpan.FromSeconds(1),
                    TimeSpan.FromSeconds(2),
                    TimeSpan.FromSeconds(3)
                })
    .ExecuteAsync( await url... )

But it requires HttpResponse to be the return type. As you can see from my Flurl example, it's returning T, even though it is an HttpResponse. The T is just the type used to deserialize the StringContent.
This first example is not working at all since I'm using it inside a PCL and I can't get a reference to System.Web there. So I tried this:
Policy
    .HandleResult(HttpStatusCode.InternalServerError)
    .OrResult(HttpStatusCode.BadGateway)
    .OrResult(HttpStatusCode.BadRequest)
    .WaitAndRetryAsync(new[] {
        TimeSpan.FromSeconds(1),
        TimeSpan.FromSeconds(2),
        TimeSpan.FromSeconds(3)
    })
    .ExecuteAsync(async () =>
    {
        await url...
    });

But this one also doesn't work because Polly expects HttpStatusCode as return type. So my question is: How can I tell polly to handle those HttpStatusCodes and still allow my return of type T?

A: Configure Flurl by setting the HttpClientFactory that can be configured with Polly and create a custom HttpClientFactory:
public class MyCustomHttpClientFactory : DefaultHttpClientFactory, IMyCustomHttpClientFactory
{
    private readonly HttpClient _httpClient;
    public MyCustomHttpClientFactory(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }
    public override HttpClient CreateHttpClient(HttpMessageHandler handler)
    {
        return _httpClient;
    }
}

Register that Service in ConfigureServices with:
public void ConfigureServices(IServiceCollection services)
{
    services
        .AddHttpClient<IMyCustomHttpClientFactory, MyCustomHttpClientFactory>()
        .SetHandlerLifetime(...)
        .AddPolicyHandler(....);
}

And assign that Factory to Flurl:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Get HttpClientFactory and Configure Flurl to use it.
    var factory = (IMyCustomHttpClientFactory)app.ApplicationServices.GetService(typeof(IMyCustomHttpClientFactory));
    FlurlHttp.Configure((settings) => settings.HttpClientFactory = factory);
}

A: You shouldn't need to break from using convenience methods like GetJsonAsync<T>(), because Flurl throws an exception on non-2XX responses (or however you configure it), which should allow it to play very nicely with Polly. Just remove the .Handle<HttpException> and .OrResult<HttpResponse> parts in your original code and handle FlurlHttpException instead:
T poco = await Policy
    .Handle<FlurlHttpException>(ex => httpStatusCodesWorthRetrying.Contains((int)ex.Call.Response.StatusCode))
    .WaitAndRetryAsync(...)
    .ExecuteAsync(() => url
        .SetQueryParams(queryString)
        .SetClaimsToken()
        .GetJsonAsync<T>());

And just a suggestion for cleaning that up further:
T poco = await Policy
    .Handle<FlurlHttpException>(IsWorthRetrying)
    .WaitAndRetryAsync(...)
    .ExecuteAsync(() => url
        .SetQueryParams(queryString)
        .SetClaimsToken()
        .GetJsonAsync<T>());

private bool IsWorthRetrying(FlurlHttpException ex) {
    switch ((int)ex.Call.Response.StatusCode) {
        case 408:
        case 500:
        case 502:
        case 504:
            return true;
        default:
            return false;
    }
}

A: Polly can interpret any value returned by a delegate executed through a policy, as a fault.  However, as you observed, the call to .GetJsonAsync<T>() in your posted example:
await url
    .SetQueryParams(queryString)
    .SetClaimsToken()
    .GetJsonAsync<T>()

is returning T.  The call hides HttpResponseMessage by going straight to Json deserialization to T.
You'd need to use an overload in flurl which returns something around HttpResponseMessage. I haven't used flurl, but this overload returning Task<HttpResponseMessage> looks promising.  You could probably do something like:
List<int> httpStatusCodesWorthRetrying = new List<int>(new[] {408, 500, 502, 503, 504});
HttpResponseMessage response = await Policy
    .Handle<HttpRequestException>()
    .Or<OtherExceptions>() // add other exceptions if you find your call may throw them, eg FlurlHttpException
    .OrResult<HttpResponseMessage>(r => httpStatusCodesWorthRetrying.Contains((int)r.StatusCode))
    .WaitAndRetryAsync(new[] {
                    TimeSpan.FromSeconds(1),
                    TimeSpan.FromSeconds(2),
                    TimeSpan.FromSeconds(3)
                })
    .ExecuteAsync(() =>
       url
        .SetQueryParams(queryString)
        .SetClaimsToken()
        .GetAsync()
    );

T responseAsT = await Task.FromResult(response).ReceiveJson<T>();

The call to .ReceiveJson<T>() at the end is suggested simply be comparing the flurl source code for your original call .GetJsonAsync<T>() here with the substituted .GetAsync(); here.
Of course you could wrap it all into a concise extension helper method on flurl, perhaps something like this:
async T GetJsonAsyncResiliently<T>(this IFlurlClient client, Policy policy) // OR (if preferred): this Url url instead of IFlurlClient client
{
    return await Task.FromResult(policy.ExecuteAsync(() => client.GetAsync())).ReceiveJson<T>();
}

EDIT: I may have pointed to the wrong flurl overloads for your case, in pointing to methods on IFlurlClient.  However, a parallel set of extension methods exist within flurl on Url and string, so the same principles apply.


text:
Q: Unable to find org.talend.ci:builder-maven-plugin:7.1.1 on the server I am setting up CICD based on Talend's specifications using Jenkins and Nexus. I get that plugin can not be found on the server but how do I handle the retry because based on below message resolution will not be attempted until the update interval of central has elapsed or updates are forced. How do I clean cache or force update? I get this error when building pipeline in jenkins
[INFO] [jenkins-event-spy] Generated /var/lib/jenkins/workspace/test_pipeline@tmp/withMaven9b3f95a4/maven-spy-20190809-185900-6572328407965718335374.log
[ERROR] Plugin org.talend.ci:builder-maven-plugin:7.1.1 or one of its dependencies could not be resolved: Failure to find org.talend.ci:builder-maven-plugin:jar:7.1.1 in http://XXXXXXXXX/repository/maven-central/ was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced -> [Help 1]
org.apache.maven.plugin.PluginResolutionException: Plugin org.talend.ci:builder-maven-plugin:7.1.1 or one of its dependencies could not be resolved: Failure to find org.talend.ci:builder-maven-plugin:jar:7.1.1 in http://XXXXX/repository/maven-central/ was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced
    at org.apache.maven.plugin.internal.DefaultPluginDependenciesResolver.resolve (DefaultPluginDependenciesResolver.java:128)
    at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getPluginDescriptor (DefaultMavenPluginManager.java:182)
    at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getMojoDescriptor (DefaultMavenPluginManager.java:286)
    at org.apache.maven.plugin.DefaultBuildPluginManager.getMojoDescriptor (DefaultBuildPluginManager.java:244)
    at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.setupMojoExecution (DefaultLifecycleExecutionPlanCalculator.java:169)
    at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.setupMojoExecutions (DefaultLifecycleExecutionPlanCalculator.java:154)
    at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.calculateExecutionPlan (DefaultLifecycleExecutionPlanCalculator.java:130)
    at org.apache.maven.lifecycle.internal.DefaultLifecycleExecutionPlanCalculator.calculateExecutionPlan (DefaultLifecycleExecutionPlanCalculator.java:144)
    at org.apache.maven.lifecycle.internal.builder.BuilderCommon.resolveBuildPlan (BuilderCommon.java:97)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:111)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)

A: Why is it looking in maven central? Seems like you missed something..
Did you follow the instructions to Set up Talend Nexus

*Create a third repository, choose maven2 (hosted) and configure it, as shown below. This repository is used by Talend CI Builder and is
  defined later in the maven_user_settings.xml file.

And Install and configure Talend CommandLine

*Edit the commandlinePath/configuration/maven_user_settings.xml file and add the connection information to the Nexus repositories. In your
  case, Nexus is on a remote server where you installed the Talend
  platform, so replace localhost with the private EC2 IP address.


text:
Q: Design Patterns for a Visual Editor I'm creating an visual editor for Box2D ( an 2d physics engine for games).
Like the most tools out there, my program has editor tools, that currently support two kind: polygon and circle tools
Here it is ( I'm using Qt to design the application)

As you can see, the two selectable tools are in the left.
The question is : Qt sends signals to QGraphicItem ( something that has already been drawn to the screen) when the item is clicked. However the behaviour of the program depends on which tool is selected. Which is the best way to solve this problem? Each drawing has to know which tool is selected? This doesn't sound good for me...
Exemplifying:
If I selected Polygon and I click into somewhere , it should start to draw a polygon. If I click into a Polygon vertex, it should edit it. If I selected circle tool and I click in a polygon vertex, it should start drawing a circle instead of editing the polygon.


text:
Q: Tamanho de arquivos no windows e linux Estou transferindo arquivos atraves do (FILEZILLA FTP Client) de minha maquina local que roda XAMPP/Windows8, porem ao colocar o arquivo no servidor LINUX os arquivos sofrem uma variação de tamanho.
Ex:
c:\xampp\htdocs\app\arquivo.php :: Filesize 3.110 kb no windows
#apos fazer o upload par o servidor linux fica assim:
/home/app/public_html/arquivo.php :: Filesize 3.018 kb no linux

O arquivo continua igual, roda o script normal, sem erros
A pergunta é:
Essa mudança no tamanho do arquivo ao ser tranferido é normal? E porque acontece isso?

A: Parece que você está fazendo uma transferência no modo texto e o Filezilla está mudando os caracteres que indicam o fim de linha do padrão Windows ("\r\n") para o Linux ("\n").
Tente mudar o modo de transferência para binário. Assim o arquivo manterá o formato e tamanho originais.
Same file, different file size
ASCII vs Binary vs Auto?
DOS vs. Unix Line Endings


text:
Q: ClickOnce publish for multiple environments (TFS Build) I have a clickonce application that I am trying to get published to multiple directories (one fore each environment) during the same build. Im having trouble figuring out the timing of every thing.
So far I have:
<Target Name="PublishForEachEnv">
    <Message Text="TEST PublishForEachEnv" />
    <Message Text="$(MSBuildProjectFile)" />
    <Message Text="$(MSBuildProjectDirectory)" />

    <MSBuild Projects ="$(MSBuildProjectFile)"
             Properties ="PublishDir=$(PublishDir)\dev;"
             Targets="Publish" />

    <MSBuild Projects ="$(MSBuildProjectFile)"
             Properties ="PublishDir=$(PublishDir)\qa;"
             Targets="Publish" />
</Target>

I call this target from the csproj file:
<Target Name="ClientPublish"
      AfterTargets="Build">

     <CallTarget Targets="PublishForEachEnv" />
</Target>

I have tried multiple varations of this but the most current error I get is:
 There is a circular dependency in the target dependency graph involving target "PublishForEachEnv".
On the line:
    Targets="Publish" />
The only other way I can think to do this would be to create a csproj file for each environment. I was hoping there was a better way.


text:
Q: Xcode cannot find path to my database im searching for some hours now but i cant find the path to my database created with xcode for iOS app. The Database exists, cause its loading the data into my app but i cannot find the path to my database. im using xcode 4.5 and ios-simulator 6.0.
I found some folders under Xcode/contents/ i searched ther for my database but it wasnt successfully ^^.
So where is it stored now?
- (void)createOrOpenDB {
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docPath = [path objectAtIndex:0];

    dbPathString = [docPath stringByAppendingPathComponent:@"WorkoutPlans.db"];

    char *error;

    NSFileManager *fileManager = [NSFileManager defaultManager];

    //[fileManager removeItemAtPath:dbPathString error:nil];

    if(![fileManager fileExistsAtPath:dbPathString]) {
        const char *dbPath = [dbPathString UTF8String];

        if (sqlite3_open(dbPath, &workoutPlansDB) == SQLITE_OK) {
            const char *sql_cr_wp = "CREATE TABLE IF NOT EXISTS WORKOUTPLANS (ID INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE , NAME TEXT NOT NULL  UNIQUE , DESCRIPTION TEXT NOT NULL  UNIQUE)";
            const char *sql_cr_en = "CREATE TABLE IF NOT EXISTS ENTITY (ID INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE , NAME TEXT NOT NULL  UNIQUE , DESCRIPTION TEXT NOT NULL  UNIQUE )";
            const char *sql_cr_ex = "CREATE TABLE IF NOT EXISTS EXERCISE (ID INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE , NAME TEXT NOT NULL  UNIQUE , DESCRIPTION TEXT NOT NULL  UNIQUE , REPS TEXT NOT NULL , WEIGHT TEXT NOT NULL)";
            const char *sql_cr_plen = "CREATE TABLE IF NOT EXISTS WPEN (PLANID, ENID, FOREIGN KEY(PLANID) REFERENCES WORKOUTPLANS(ID) ON DELETE CASCADE, FOREIGN KEY(ENID) REFERENCES ENTITY(ID) ON DELETE CASCADE)";
            const char *sql_cr_enex = "CREATE TABLE IF NOT EXISTS ENEX (ENTITYID, EXERCISEID, FOREIGN KEY(ENTITYID) REFERENCES ENTITY(ID) ON DELETE CASCADE, FOREIGN KEY(EXERCISEID) REFERENCES EXERCISE(ID) ON DELETE CASCADE)";

            sqlite3_exec(workoutPlansDB, sql_cr_wp, NULL, NULL, &error);
            sqlite3_exec(workoutPlansDB, sql_cr_ex, NULL, NULL, &error);
            sqlite3_exec(workoutPlansDB, sql_cr_en, NULL, NULL, &error);
            sqlite3_exec(workoutPlansDB, sql_cr_plen, NULL, NULL, &error);
            sqlite3_exec(workoutPlansDB, sql_cr_enex, NULL, NULL, &error);
            sqlite3_close(workoutPlansDB);
        }
    }
}

A: Your database will be stored in the following path
/Users/SystemName/Library/Application\ Support/iPhone\ Simulator/6.1/Applications/Application UniqueName/Documents\databasename
Xcode, in conjunction with the iPhone Simulator, creates a new app folder for each build of your app and will move the the old documents folder and its contents over to the new app folder. It is up to you to check the contents of the documents folder and decide whether a file you have in your Bundle is preferable for use over the one that is in the documents folder. You should make this decision wisely and not lightly.
This is the right behavior. The user of your software may have made some significant changes and modifications to the database. They probably would not like it if, when upgrading for a minor bug fix or even for feature enhancements, their database changes, their high scores, their modified images, or whatever your app saves, suddenly gets replaced with a generic version.
What you should do is to compare the data in your new database, vs the data the user has, and in the case of SQLite, your should import or copy the user's entry into your new database, and then you can move your new database over to the documents folder, removing the user's but replacing it with one that has the user's data and your new data.
In short: make sure you don't replace an existing database with a new one from your bundle, since that will blow away the user's changes.


text:
Q: SQL - how to select rows that do not contain a certain ID So I have the table flag_counts with the following columns:
flag_id content_id
1       10
2       10
2       11

and the following query
SELECT flag_id, content_id FROM flag_counts
WHERE flag_id != 1

and of course it returns
flag_id content_id
2       10
2       11

How can I change my query so that it returns all content_ids that were not flagged with "1". In this example, I would like the query to return only the last row of the table since the content_id "10" was flagged once with "1".

A: Group by the content_id and take only those having zero records with flag_id = 1
SELECT content_id
FROM flag_count
GROUP BY content_id
HAVING sum(flag_id = 1) = 0

A: SELECT whatever
FROM flag_counts
WHERE content_id NOT IN (
   SELECT content_id
   FROM flag_counts
   WHERE flag_id = 1
)

or via JOIN
SELECT DISTINCT c1.*
FROM flag_counts c1
LEFT JOIN flag_counts c2
 ON c1.content_id = c2.content_id and c2.flag_id = 1
WHERE c2.content_id IS NULL;

A: This addresses the question:  How to change my query so that it returns all content_ids that were not flagged with "1"?  The "clarification" is actually more confusing, because SQL tables represent unordered sets, so there is no "last" row.
If you have a separate table of content ids, then the fastest approach might be:
select c.*
from contents c
where not exists (select 1
                  from flag_count fc
                  where fc.content_id = c.content_id and flag_id = 1
                 );

For this, you would want an index on flag_count(content_id, flag_id).
If you use flag_count instead of contents, then you might get duplicates.

A: One of the following method can be used to solve this.
SELECT  DISTINCT a.content_id
FROM
    flag_counts a
LEFT JOIN flag_counts b
ON  (a.content_id = b.content_id AND b.flag_id = 1)
WHERE   b.content_id IS NULL;

SELECT  DISTINCT a.content_id FROM flag_counts a
WHERE NOT EXISTS (SELECT 1 FROM flag_counts b WHERE a.content_id = b.content_id AND b.flag_id = 1)


text:
Q: Access class function inside lambda which is executed in an instance Context
In a header-file matrix.h I defined a struct holding a matrix.
A special feature is a function inside this struct which allows for iterating over the rows and columns and apply a function to each iteration step. The idea is to not have to write that loop a thousand times.
template <class T>
struct Matrix{
    T* matrix;
    int columns, rows;

    Matrix(int rows, int columns) : rows(rows), columns(columns)
        matrix = new T[columns * rows];
    }

    template<typename Func>
    void iterate_over_matrix(Func function) {

        for (std::size_t row = 0; row < rows; ++row) {
            for (std::size_t column = 0; column < columns; ++column) {
                function(row, column);
            }
        }
    }
}

Using this works without any problem, e.g.:
/*Initialize the matrix with the numbers 0..N for type T*/
template <class T>
void Matrix<T>::init_dummy_matrix(){

    iterate_over_matrix(
        [this](std::size_t& row, std::size_t& col) {
            set_element<T>(
                row, col,
                col + columns * row // Same result as having a counter -> 0..N
            );
        }
    );
}

Problem
I want to reuse this functionality on instances of the matrix-class. E.g. while calculating the outer_product in a class LinearAlgebra:
/*Set the element at position [row] and [col]umn with given [val]ue.*/
template <class T>
void Matrix<T>::set_element(const int &row, const int &col, T val) {
    matrix[col + columns * row] = val;
}

/** Calculate the outer product [vector_1]T * [vector_2]. */
template <class T>
Matrix<T> LinAlg::outer_product(
        const std::vector<T> &vector_1
        , const std::vector<T> &vector_2
    ) {

        Matrix matrix = Matrix<T>(
            vector_1.size()
            , vector_2.size()
        );

        matrix.iterate_over_matrix(
            [this, &vector_1, &vector_2](std::size_t& row, std::size_t& col) {
                set_element<T>(
                    row, col,
                    vector_1[row] * vector_2[col]
                );
            }
        );

        return matrix;
}

Anyhow, this fails with 'set_element': identifier not found.

Question
While the error-message is pretty clear in stating the problem, I have no clue how to come around this - Especially since passing the context via this does not help...
How can I access a class-function inside a lambda which is called on an instance of that object?


text: Q: Nominal voltage of a battery with or without ESR? I am reading a calculation document which has calculated nominal voltage at MPV(50%) with the open circuit voltage from the datasheet, but from what I have read so far on different forums its the voltage which we should observe for most of the use of the battery at the terminals which means that the nominal voltage also includes the drop across the internal resistance and not just an OCV, is my assumption correct ?


text:
Q: Security issues for quantum computers Although quantum computers might be highly efficient at hacking conventional computers, might they have an Achilles heel that makes them easily hacked?

A: By continuous time evolution of wave function:
Since QC's require a superposition of memory eigenstates to evolve in real time prior to returning a result by the collapse of the superposition, it seems that if an external agency could, from a remote location, introduce stealth perturbations to the computers internal Hamiltonian, it could be caused to alter the  program in progress to return any desired result.
By discontinuous time evolution of wave function:
Perhaps an acoustic beam directed at the computers hardware would shake things up in such a way that it constitutes a measurement event shutting down the program before it can be officially collapsed.


text:
Q: Correct way to use done() while testing asyc/await with mocha I am practicing basic unit test cases with mocha and a bit confused HOW and WHEN to use done() handler.

*

*How to use done() ?
Below is my sample code where I am not able to use done:
it('Testing insertDocumentWithIndex', async (done) => {
  try{
    var data = await db.insertDocumentWithIndex('inspections', {
      "inspectorId" : 1,
      "curStatus" : 1,
      "lastUpdatedTS" : 1535222623216,
      "entryTS" : 1535222623216,
      "venueTypeId" : 1,
      "location" : [
        45.5891279,
        -45.0446183
      ]
    })
    expect(data.result.n).to.equal(1);
    expect(data.result.ok).to.equal(1);
  }
  catch(e){
    logger.error(e);
    done(e);
  }
})

When I run, it fails and throws an error-

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure
"done()" is called; if returning a Promise, ensure it resolves.

But done should be called in case of failure only(Please correct me If I am missing something, I am a beginner), which I have done in catch block and coming to the second point of returning a Promise, well that works fine. See below code
it('Testing insertDocumentWithIndex', async () => {
  return new Promise(async (resolve, reject) => {
    try{
      var data = await db.insertDocumentWithIndex('inspections', {
        "inspectorId" : 1,
        "curStatus" : 1,
        "lastUpdatedTS" : 1535222623216,
        "entryTS" : 1535222623216,
        "venueTypeId" : 1,
        "location" : [
          45.5891279,
          -45.0446183
        ]
      })
      expect(data.result.n).to.equal(1);
      expect(data.result.ok).to.equal(1);
      resolve()
    }
    catch(e){
      reject(e);
    }
  })
});

But this requires an additional Promise construction code which is antipattern. But it raises another question

*WHEN done should be used ?
Any help or suggestion for a better approach for writing test cases with mocha will help.

A: The correct way is to not use done with async..await. Mocha supports promises and is able to chain a promise that is returned from it, etc. functions. And async function is syntactic sugar for a function that always returns a promise:
it('Testing insertDocumentWithIndex', async () => {
    var data = await db.insertDocumentWithIndex('inspections', {
      "inspectorId" : 1,
      "curStatus" : 1,
      "lastUpdatedTS" : 1535222623216,
      "entryTS" : 1535222623216,
      "venueTypeId" : 1,
      "location" : [
        45.5891279,
        -45.0446183
      ]
    })
    expect(data.result.n).to.equal(1);
    expect(data.result.ok).to.equal(1);
})

done is needed only for testing asynchronous APIs than don't involve promises. Even then, converting to promises often results in cleaner control flow.
And this
it('Testing insertDocumentWithIndex', async () => {
  return new Promise(async (resolve, reject) => {
  ...

is promise construction antipattern, which is even worse because of async promise constructor callback.
These concerns also apply to other JS testing frameworks with similar API, Jest and Jasmine.


text:
Q: r DT::datatable with formatStyle - apply nested css element 'hover' Hello everyone You need to implement such a css construction via FormatStyle.
nav a:hover {
    text-decoration: underline;
}

For some reason, this design does not work:
formatStyle(
    'colname',
    # working
    cursor          = 'pointer',
    # not working
    hover           = list('text-decoration' = 'underline'))

Which one will work?

A: Limitations of css itself. You need to declare a class to the column and write properties to this class in style.css.


text:
Q: wxBusyInfo Alternative in wxWidgets 2.8 I'm running wxWidgets 2.8 and I need to disable my GUI while I'm waiting for an update from my business logic.
I set out to use wxBusyInfo but I was disappointed to find that it is only in wxWidgets 3.1.
In 2.8 what is the best way to pop up a dialog which disables user input until a signal is received from the business logic?

A: You can use wxWindowDisabler with an info window of your choice.
OR
You can copy the files for wxBusyInfo from 3.1 to your project. They need only minor adjustment (like the include list) but other than that they look pretty self contained.
Just for the record, it is there since 2.9.0, only that particular constructor is since 3.1.


text:
Q: With my script is sending Error: connect ETIMEDOUT? I have an error when I try to make a connection with my BD. It's working but it appears to be losing the connection after a few seconds.
I added some parameters fallowing similar subject on google like path port .... I also changed the port from 8080 to 8081 and its still not working.
I've started with nodeJS 2 days and need some advise.
Could you check my code ?
Thanks in advance

const express = require('express');
    mysql = require('mysql'),
    ejs = require('ejs'),
    app = express(),
    port = 8081,
    connect = mysql.createConnection({
        host: "localhost",
        user: "root",
        password: "",
        database: "api_school",
        path: "http://localhost:8081",
        port: 8081
    });

connect.connect();

app.get('/', function(req, res) {
  res.render('index.ejs')
});

app.listen(port, () => console.log(`Example app listening on port 8081!`));

new config :
const express = require('express');
    mysql = require('mysql'),
    ejs = require('ejs'),
    app = express(),
    port = 8080,
    connect = mysql.createConnection({
        host: "localhost",
        user: "root",
        password: "",
        database: "api_school",
        port: 3306
    });

connect.connect();

A: The error is showing because your app couldn't connect to your MySQL database within given time hence throwing ETIMEDOUT.
It can't be that your node server port and MySQL port same. Also path is not required. You need to change the port of MySQL configuration to correct one. (Default MySQL post is 3306).
The createConnection config will look like this with default parameters-
connect = mysql.createConnection({
        host: "localhost",
        user: "root",
        password: "",
        database: "api_school",
        port: 3306
    });


text:
Q: XPath identification for a Selenium Test I am new to Selenium and XPath. Can you please help me I identified the XPath correctly for the following structure:

Automation
»
»

UFT

I have identified the XPath as:
("//div[@class='menutext']/descendant::ul[@class='children sub-menu']/a[@href='http://www.ufthelp.com/p/uft.html']"));

But I'm running into NoSuchElementException. Please help me with the same. Thanks

A: U can get Xpath easily using firebug Extension in firofox browser . Just selecting by the the element u can get the xpath value . FirePath is a Firebug extension that adds a development tool to edit, inspect and generate XPath .

A: *

*the class "menutext" is missing.

*if your aim is to get a lock on the anchor tag, then I would suggest an alternate rather than xpath. Please try

`
driver.findElement(By.tagName("a")) then(function(anchorTags) {
  anchorTags.getText().then(function(anchorText) {
    if (anchorText == UFT) {
      // do your thing here
    }
  })
})

`

A: XPATH :
//a[@title='UFT']
or
//a[text()='UFT']
CSS:
a[title='UFT']


text:
Q: Session becomes null on first request in MVC application I have a Silverlight application from where I navigate to my MVC Application. The problem is for the very first time when I navigate to my MVC application, the Session expires. But for subsequent requests, the Session works perfectly fine. On debugging, I found that on the first request the following flow happens:
Application_Start (Global.asax) is called, then OnActionExecuting is called, which sets all the Sessions, then Application_End (Global.asax) is called. So for the next immediate request, the Sessions becomes null.
Global.asax
    protected void Application_Start()
    {
        // Register the default hubs route: ~/signalr
        RouteTable.Routes.MapHubs();

        AreaRegistration.RegisterAllAreas();
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        //Start SqlDependency with application initialization
        SqlDependency.Start(connString);
    }

    protected void Application_End(object sender, EventArgs e)
    {
        //Stop SQL dependency
        SqlDependency.Stop(connString);
    }

FilterConfig.cs
 public static void RegisterGlobalFilters(GlobalFilterCollection filters)
 {
     filters.Add(new HandleErrorAttribute());
 }

OnActionExecuting Function
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
        RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
        redirectTargetDictionary.Add("action", "SessionExpire");
        redirectTargetDictionary.Add("controller", "Home");
        redirectTargetDictionary.Add("area", "");
        if (!(string.IsNullOrEmpty(Convert.ToString(HttpContext.Current.Session["SID"]))))
        {
            sessionId = Convert.ToString(HttpContext.Current.Session["SID"]);
            HttpContext.Current.Session["SID"] = sessionId;
        }
        else if (!(string.IsNullOrEmpty(Convert.ToString(HttpContext.Current.Request.QueryString["SID"]))))
        {
            sessionId = Convert.ToString(HttpContext.Current.Request.QueryString["SID"]);
            HttpContext.Current.Session["SID"] = sessionId;
        }
        if (string.IsNullOrEmpty(Convert.ToString(HttpContext.CurrentSession["SID"])))
        {
           filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
        }
    return;
}

Is there something wrong with my code? Any help is appreciated.