text:
Q: Python for loop range with times instead of adding index Is there any easier way to achieve the following code in C++ as Python?
for(long a = 1; a <= INT_MAX; a*=2)
    for(long b = a; b <= INT_MAX; b*=2)
        for(long c = b; c <= INT_MAX; c*=2)

I can only rewrite as while loop since Python seems doesn't support it.
Like
a = 1
while(a <= INT_MAX):
  b = a
  while(b <= INT_MAX):
    c = b
    while(c <= INT_MAX):
      c *= 2
    b *= 2
  a *= 2

I have a hard time reading this and wonder if there's a better way to achieve it.

A: It reads better if you factor it out in a generator.
def geometric_range(start, end, step):
    n = start
    while n < end:
        yield n
        n *= step

for a in geometric_range(1, INT_MAX + 1, 2):
    for b in geometric_range(a, INT_MAX + 1, 2):
        for c in geometric_range(b, INT_MAX + 1, 2):
            pass # or whatever

A: You will be able to do the following in Python 3.8, using the assignment expressions:
i = 1
while (i := i*2) < INT_MAX:
   ...

A: For this particular code, it may be more obvious to iterate over the bits:
INT_MAX = (1<<31) - 1

def highest_bit(x):
    return len(bin(x)) - 3

def bitfor(start, end=INT_MAX):
    start =  highest_bit(start)
    end = highest_bit(end) + 1
    for i in range(start, end):
        yield 1 << i

for a in bitfor(1):
    for b in bitfor(a):
        for c in bitfor(b):
            pass


text:
Q: Firefox not handling Applescript to select from drop down list same as Google Chrome I am using an Applescript to tab to and select an item from a dropdown box on a form, and return to the starting field. Using Firefox 57.0, both "Cakes, large" (the first item with the first letter "C") and "Cocktails" get selected.  Using Google Chrome 63.0 only "Cocktails" gets selected, which is what I want.  Any ideas how to get the desired result in Firefox?
Applescript:
tell application "System Events"
    tell application "System Events" to key code 48
    tell application "System Events" to key code 49
    keystroke "Cocktails"
    tell application "System Events" to key code 48 using shift down
    tell application "System Events" to key code 124 using command down
end tell

HTML code:
<div class="editor-field">
    <select class="category-multi" id="RecipeTypes" multiple="multiple" name="RecipeTypes" style="display: none"><option selected="selected" value="85">Fried doughs</option>
<option selected="selected" value="64">Mousses, trifles, custards & creams</option>
</select>
    <select class="form-control category-ddl" id="RecipeTypesDDL" name="RecipeTypesDDL"><option value=""></option>
<option value="41">Baked & steamed desserts</option>
<option value="42">Beverages / drinks (no-alcohol)</option>
<option value="82">Bread & buns, sweet</option>
<option value="43">Bread & rolls, savory</option>
<option value="44">Brownies, slices & bars</option>
<option value="45">Cakes, large</option>
<option value="46">Cakes, small</option>
<option value="47">Candy / sweets</option>
<option value="49">Cheesecakes</option>
<option value="50">Children & baby food</option>
<option value="51">Chili</option>
<option value="52">Chutneys, pickles & relishes</option>
<option value="53">Cocktails / drinks (with alcohol)</option>
<option value="54">Cookies, biscuits & crackers</option>
<option value="55">Crumbles, cobblers, crisps & bettys</option>
<option value="56">Curry</option>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to split theorem environment into two frames? I am using
\newtheorem{thm}{theorem}
\begin{frame}
\begin{thm}

\end{thm}
\end{frame}

but when theorem is long and frame doesn't have enough space then I used a next frame like,
\begin{frame}
\end{frame}

but in the second frame theorem environment is not continue...
I need a theorem environment in both frames for long statements of my theorem for the presentation of slides.


text:
Q: Does the TIBCO EMS server manage reconnection? or does the client? The TIBCO EMS .NET reference guide says (pg 134)

To enable reconnection behavior and fault tolerance, the serverURL parameter  must be a comma-separated list of two or more URLs. In a situation with only one  server, you may supply two copies of that server's URL to enable client  reconnection (for example, tcp://localhost:7222,tcp://localhost:7222).

The TIBCO EMS user's guide (pg 292) talks about failover scenarios, client notification, and automatic transfer of clients to the backup server, but nothing specifically "reconnect" related.
In a "reconnect" scenario, does the server handle everything? or does the client have to do something with it's TIBCO.EMS.Connection instances?

A: Looks like from our testing that the there are settings on both the server and the client that enable this feature.  On the client side, the SetReconnAttemptCount, Delay, Timeout govern the attempts the client tries to reconnect once its aware of a server failover / connection failover.
In our testing, we used a single server environment, listed the server twice in the connection string (using the trick you outlined above) and when that server was taken offline, we received a client notification of the failover process taking affect (we enabled Tibems.SetExceptionOnFTSwitch(true)) and when the server was brought back online, our client seemlessly reconnected without missing a beat.  We didn't need to code anything, the internal reconnect logic worked its magic.
On the server side, fault tolerance needs to be enabled and I believe server-client and client-server heartbeats need to be enabled (though this has not yet been verified).
Hope this helps.


text:
Q: Scatterplot gene coexpression with 2 variables on X and Y I have a matrix with 2 variables ( A and B),
and the expression of two genes which I would like to plot in relationship to this variables.
Data:
A = c(1.16, 1.16,   0.96,   0.96,   0.96,   0.67,   0.67,   0.67,   0.78,   0.78,   0.55,   0.3,    0.3,    0.3,    0.26,   0.26,   0.26)
B = c(6.513421667,  6.513421667,    4.981984615,    4.981984615,    4.981984615,    2.858295,   2.858295,   2.858295,   3.19875,    3.19875,    3.604918,   10.82963857,    10.82963857,    10.82963857,    8.607186667,    8.607186667,    8.607186667)
gene1 = c(0.007614672,  0.007632451,    0.007066506,    0.007524053,    0.008337992,    0.012520277,    0.012249,   0.011351902,    0.01263021, 0.009969673,    0.008850031,    0.007290232,    0.00724349, 0.007161781,    0.004299581,    0.004896156,    0.005970637)
gene2 = c(0.019649471,  0.015339387,    0.0180094,  0.018787749,    0.014556951,    0.011603994,    0.012012431,    0.011189356,    0.012666218,    0.01472512, 0.016299402,    0.017398006,    0.021602747,    0.019780361,    0.014182726,    0.015611876,    0.018550423)

This is what I have done:
df = data.frame(A, B, gene1, gene2)
df <- data.frame(A = rep(A, 3), B= rep(B, 3), y = c(gene1, gene2), genes = rep(c("gene1", "gene2", each = 17))
plot(A,B, pch=unclass(genes))  # different symbol
legend("bottomright", legend=levels(genes), pch=c(1:3))

I would like to plot the genes on the graph so they correspond to variable A (x-axis) and variable B (y-axis) and so it would look something like this Thanks!:


text:
Q: Javascript ternary if statement, assigning it to a variable and incrementation So, I have this piece of code, which actually works:
(hash would be an object like this: {"bob" => "12, "Roger" => "15", etc}, and isGood(key) is a calling the function isGood that just returns if the player is good or bad)
let score = 0;
Object.keys(hash).forEach((key) => {
  isGood(key) === true ? score += parseInt(hash[key], 10) : score -= parseInt(hash[key], 10);
});
return score;

for which I get this error message:
Expected an assignment or function call and instead saw an expression

And I managed to make it work without getting this error message, like this:
let score = 0;
Object.keys(hash).forEach((key) => {
  score = isGood(key) ? score + parseInt(hash[key], 10) : score - parseInt(hash[key], 10);
});
return score;

But, why would the first one not be a proper way to do it, eventhough it works? I am sorry I have problems with conventions in Javascript.
Thanks in advance!
Olivier

A: It is valid JavaScript code. I believe the error messages comes from jshint, which is a linter.
Here is a related answer:
Ternary operator displays error in JSHint - Expected an assignment or function call and instead saw an expression
In the end it is a matter of style, but having side-effects in a ternary operator is unexpected, which explains why a linter has rules to point it out. It makes it harder to reason about the code, so you would normally see an if-then-else construct instead.


text:
Q: "Wrote it I did" Is this grammatical? Are the following two examples grammatical?

*

*Write it I have.

*Wrote it I did.

Consider as possible contexts:

*

*They said that I have to write it, and write it I have. -- (for #1)

*They said that I wrote it, and wrote it I did. -- (for #2)

MAIN QUESTION: What reasons are there to think that examples #1 and #2 are grammatical or ungrammatical?
These two examples involve preposed verb phrases, which could be used as a form of topicalisation. But what I'm  wondering about, here,  is the grammar in relation to the forms of the verb WRITE.

MINOR QUESTION: As a very small secondary concern, is a comma required after it in those two examples, and why or why not? (See the various comments by Curiousdannii below.)

A: Technically they are incorrect and should have been:

Written it I have. = I have written it.
Write it I did. = I did write it. = I wrote it.

It is the same reason we would say "Done it I have" rather than "*Did it I have".
The second one could for even more emphasis or rhetorical effect be phrased:

I wrote it, yes I did. ("did" here is a pro-verb, grammatically separate from the earlier phrase.)

People often make mistakes with the tense because the verb is rarely fronted in English. It is more common to front other things like nouns or adjectives:

Many books I have read.
Truly surprised I was.

I disagree that fronting verbs is invalid English because they are indeed used, though mostly found in poetry. Here are some non-poetry examples I found:

And escape he did. (some random written piece)
And come they did. (some BBC blog article)

It is also not a recent phenomenon (as some might claim started with Yoda).

And come he did. (History of English (1730))

To clarify my answer, I consider legal writings or news publications from the US or the UK as a reference point for standard English, because there is a whole spectrum of dialectical variants of English. For example in some places "I have went" is commonly used among the native English speakers, even though it would be considered incorrect in most other places.

A:
Are the following two examples grammatical?

*

*Write it I have.

*Wrote it I did.

Consider as possible contexts:

*

*They said that I have to write it, and write it I have. -- (for #1)

*They said that I wrote it, and wrote it I did. -- (for #2)

ANSWER TO MAIN QUESTION: In the appropriate context, those two expressions (#1 and #2) would most likely be acceptable in informal or colloquial spoken English, and would be considered to be grammatical by many native English speakers--though, many speakers might consider the usage of "wrote" in #2 to be nonstandard for spoken and written English.
In each of the two sentences for the example contexts, the last coordinate clause has a preposed verb phrase (VP): the VP "write it" in #1, and the VP "wrote it" in #2. Both preposed VPs have verbs that have the identical shape of a verb used in an earlier clause in the sentence; and because of this, that could produce a rhetorical effect which would often be desired by the speaker.
For version #1 in its given context, there usually wouldn't be much doubt as to its grammaticality, since it would be considered to be grammatical in today's standard English according to the 2002 reference grammar CGEL.
For version #2 in its given context, it seems in my opinion to be acceptable, and it would probably be quite reasonable to consider it to be grammatical in today's informal English, and maybe even in today's standard English. But it might be a bit harder to present an iron-clad supporting argument for that position, because it seems that this specific type of construction isn't explicitly discussed in the general vetted grammar sources that are easily available, such as the 2002 reference grammar CGEL or the 1985 reference grammar by Quirk et al.
ANSWER TO MINOR QUESTION: Usually in those types of constructions, a comma is not used to separate the preposed element from the rest of the clause when that element is a complement (which it happens to be in the OP's two examples). Often it would be less acceptable, or even unacceptable, to use a comma in that situation.
Consider the original two examples:

*

*They said that I have to write it, and write it I have.

*They said that I wrote it, and wrote it I did.
and compare them to versions with a separating comma after the preposed element:

*

*They said that I have to write it, and write it, I have.

*They said that I wrote it, and wrote it, I did.
The original versions seem much better to me. In general, though, it will depend on the specific sentence and its context, and on the speaker or writer w.r.t. what they want to accomplish, as to whether or not the use of that kind of comma is acceptable.

Note: Another answer post which has info related to the OP's grammar question is: "and build upon that, but build they have": Should that 2nd "build" be "built"?

LONG VERSION:

INFORMATION PACKAGING:
The OP's examples are using information packaging constructions. These are constructions that have words and phrases that are not in their canonical or expected "normal" order. Often, these constructions will move elements (word or phrases or constituents) around. Usually there are more constraints and restrictions on these types of constructions, w.r.t. their level of acceptability in the contexts where they are used, than there are on more "normally ordered" constructions.
The two examples (the full sentences which provide some context) are:

*

*1.b. They said that I have to write it, and [write it] I have. -- (for OP's #1)

*2.b. They said that I wrote it, and [wrote it] I did. -- (for OP's #2)

Both of the OP's examples (#1.b and #2.b) are using the information packaging construction of complement preposing (2002 CGEL pages 1372-82). And more specifically, they are using VP preposing, which are the VPs "write it" and "wrote it". The following are the more normally ordered versions that would correspond to them:

*

*1.c. They said that I have to write it, and I have [written it].

*2.c. They said that I wrote it, and I did [write it].
Notice that the verbs in these two normally ordered versions use the grammatical "written" and "write": "written" is the past-participle verb form for the perfect construction ("have written"); and "write" is the plain form of a verb that heads the VP that is the complement for the matrix verb "did", where the verb "did" is the auxiliary verb "DO" (not the lexical verb "DO").
[Aside: Notice that there's usually another normally ordered version that would also correspond to #2.b which wouldn't use the auxiliary verb "DO": "They said that I wrote it, and I wrote it", which uses the preterite "wrote" instead of the expression "did write". But in this specific case, it doesn't seem to work for the given context.]
In general, there seems to be two factors at work here which are influencing the form that the preposed verb will be taking:

*

*One: the form that the verb would have if it was in the normally ordered construction.

*Two: the form that would more closely match the shape of the verb form that was used by an earlier use of the verb.
As to which form would be more preferable in a specific context, that would usually depend on the context and also on the speaker or writer as to the rhetorical effect that they are trying to accomplish.
Since the OP's two examples are involving two different types of construction (perfect vs auxiliary-DO), I'll split the discussion into two major parts. I'll first discuss the OP's #1 example which involves the perfect construction, since it should be the less controversial of the two. And then after that, I'll discuss the OP's #2 example which involves the auxiliary-DO construction.

EXAMPLE #1: THE PERFECT CONSTRUCTION

*

*1.b.i. They said that I have to write it, and [write it I have]. -- (OP's original #1)

*1.b.ii. They said that I have to write it, and [written it I have].
In general, both versions are acceptable in today's standard English. But in this specific context, there would often be a preference for the first version (#1.b.i) which uses "write", and that was what was used in the OP's original #1 version:

*

*1.b.i. They said that I have to write it, and [write it I have]. -- (OP's original #1)

The OP's use of the plain form "write" of the verb would probably often be preferred here (over the past-participle form "written") because the second "write" would then match the shape of the first "write" which was used in the previous clause, and that would give a rhetorical effect which would often be desirable by the speaker.
The two factors influencing the selection of the form of the preposed verb, w.r.t. "written" versus "write", are:

*

*One: the form that the verb would have if it was in the normally ordered construction -- for example #1, it is the past-participle "written".

*Two: the form that would more closely match the shape of the verb form that was used in an earlier use of the verb -- for example #1, the plain form "write", which had headed an infinitival clause located earlier in the example sentence.
As to which form would be more preferable, then, in general, that will depend on the context and on the speaker or writer as to the rhetorical effect that they are trying to accomplish.
This specific issue related to the perfect construction is discussed by the 2002 CGEL on page 1381 (a related excerpt is provided near the bottom of this answer post).

EXAMPLE #2: THE AUXILIARY "DO" CONSTRUCTION

*

*2.b.i. They said that I wrote it, and [wrote it I did]. -- (OP's original #2)

*2.b.ii. They said that I wrote it, and [write it I did].
The OP's preterite verb form "wrote" might be preferred here (over the plain form "write") by some speakers because the second "wrote" would then match the shape of the first "wrote" which was used in the previous clause, and that would give a rhetorical effect which would often be desirable by the speaker. Though, some speakers might consider "wrote" to be ungrammatical here (i.e. nonstandard), and they might only consider "write" to be acceptable.
The two factors influencing the selection of the form of the preposed verb, w.r.t. "write" versus "wrote", are:

*

*One: the form that the verb would have if it was in the normally ordered construction -- for example #2, the plain form "write", which heads an infinitival clause.

*Two: the form that would more closely match the shape of the verb form that was used in an earlier use of the verb -- for example #2, the preterite "wrote", which was located earlier in the example sentence.
As to which form would be more preferable, then, in general, that will depend on the context and on the speaker or writer as to the rhetorical effect that they are trying to accomplish (and also on the register).

GRAMMAR INFO FROM VETTED GRAMMAR SOURCES:

The OP's two examples use complement preposing in their second clauses, where the preposed element is a verb phrase (VP). Usually the second clause will involve an auxiliary verb when the preposed element is a VP.
Here are some typical examples. The 2002 CGEL, page 1376:

*

*[11.i ] I've promised to help them [ and help them I will ].

*[11.ii ] It's odd that Diane should have said that, if [ say it she did ].

The preposed VP in [11.i ] is "help them", and in [11.ii ] it is "say it". Notice that the nucleus of the second clause in both examples ends with an auxiliary: "will" for [11.i ], and "did" for [11.ii ]:

*

*help them I will

*say it she did
where the nucleus of each of those clauses would be "I will" and "she did". (note: The nucleus of a clause is the rest of the clause that hadn't been preposed.)
Here are their corresponding versions that don't have the preposing:

*

*A.i. I've promised to help them and I will help them.

*A.ii. It's odd that Diane should have said that, if [ she said it ] / [ she did say it ].
But when the auxiliary verb is the perfect "have" and the preposed element is its complement, then both the past-participle form and the plain form of the verb are acceptable.
The 2002 CGEL page 1381:

Inflection with perfect have
A special issue arises when the preposed element is a complement of perfect have. Compare:
[25]

*

*i. He said he wouldn't tell them, [ but tell/told them he has ].

*ii. He denies he has told them, [ but tell/told them he has ].
Although have normally takes a past participle, it is the plain form of the verb that is preferred in [i ]. The past participle is preferred in [ii ], where it has been used in the preceding clause, but even here the plain form tell is acceptable.

NOTE: The 2002 CGEL is the 2002 reference grammar by Huddleston and Pullum (et al.), The Cambridge Grammar of the English Language.
Pages 1372-82 (2002 CGEL), which deal with complement preposing, are within chapter 16 "Information packaging" pages 1363-1447, and the major contributors to that chapter are Gregory Ward, Betty Birner, and Rodney Huddleston. Birner and Ward are the authors of the 1998 book Information Status and Noncanonical Word Order in English, and much of chapter 16 was based on their work.
NOTE: The 1985 Quirk et al. is the reference grammar by Quirk, Greenbaum, Leech, Svartvik, A Comprehensive Grammar of the English Language.

A: Both are examples of hyperbaton. You can read more about it here, hyperbaton. In their current form, both sentences are ungrammatical. Correct them for tense as follows.

Write it I have.

should be

Written it I have.

Next,

Wrote it I did.

should be

Write it I did.

Once corrected for tense, both sentences can be acceptable English usage, despite the unusual word order.
See too the question and answers to Why is this a hyperbaton?  One of the answers even mentions why so called Yoda-speak can be grammatically acceptable!


text:
Q: Form output not showing I have a simple app for adding reviews to movies (using TMDb API). The problem is that when I try to save the review, I don't see it on the movie show page. This has happened to me with other apps - some field outputs not showing on the show page.
Controller
def show
  @movie = Tmdb::Movie.detail(params[:id])
   ...
  @movie_reviews = MovieReview.where(movie_id: params[:id])
end

Show
<% @movie_reviews.each do |movie_review| %>
  <%= movie_review.title %>
  <%= movie_review.content %>
<% end %>

Form
<%= form_for :movie_review, url: movie_movie_reviews_path(params[:movie_id]) do |f| %>

  <%= f.label :title %>

  <%= f.text_field :title %>

  <%= f.label :content %>

  <%= f.text_area :content %>

<%= f.submit %>
<% end %>

A: I don't know how you save, but you should have the @movie=Movie.find(..) and then @movie_review=@movie.movie_reviews.create(params)
Which means you probably need a hidden field in your form for the movie_id or assign it before rendering the form.
Edit:
You are passing the form action url as follows:
movie_movie_reviews_path(params[:movie_id])

Posting to the reviews index path is the correct action for create, but you still need to tell the controller what you are trying to say. So, you should just do:
movie_movie_reviews_path

and then, in your form, add the id of the movie for which the review will be:
<%= form_for...
<%= f.hidden_field :movie_id, :value => @movie.id %>

So, you will now have a param mapping the movie_id for the movie_review (@movie comes from the controller, remember?)
Finally, in your create action:
Either a) you permit :movie_id in your movie_review_params and do nothing more
def movie_review_params
  params.require(:movie_review).permit(:title, :content, :movie_id)
end

b) Or you don't touch your movie_review_params and instead of:
@movie_review = MovieReview.new(movie_review_params)

do
@movie_review = Movie.find(params[:movie_id]).movie_reviews.new(movie_review_params)


text:
Q: Include third party DLL Amyuni PDFCreator in my Qt project I download this
third party SDK I want to use in my C++ Qt project. If you download the zip you get some documentation, samples and there is a SDK folder with 3 DLLs.
I followed these steps from the documentation:

*

*I registered PDFCreactiveX.dll via regsvr32 - OK

*I import the file like this: #import "Amyuni/SDK/Win32/PDFCreactiveX.dll" to my stdafx.h because according to documentation I want to use it in multiple files.
But when I include stdafx.h in my global.h header (which is my header where I include my all third party SDKs and instantiate them) it doesn't work for me like the documentation said.
IPDFCreactiveXPtr gPDFptr;

The Compiler does not know what IPDFCreactiveXPtr is and I also need make it a global variable to work with the same instance in other .cpp files.


text:
Q: Export RSA public key to PEM String using java So I'm using Spongy Castle (Android) to generate a PEM encoded string for an RSA public key that will be uploaded to a server.
This is what I'm currently doing:
    PublicKey publicKey = keyPair.getPublic();
    StringWriter writer = new StringWriter();
    PemWriter pemWriter = new PemWriter(writer);
    pemWriter.writeObject(new PemObject("RSA PUBLIC KEY", publicKey.getEncoded()));
    pemWriter.flush();
    pemWriter.close();
    return writer.toString();

Now as you can probably tell I'm not sure how to construct the PemObject or if there is an easier way to do this.
When using Bouncy Case I used to do this like this
    StringWriter writer = new StringWriter();
    PEMWriter pemWriter = new PEMWriter(writer);
    pemWriter.writeObject(keyPair.getPublic());
    pemWriter.flush();
    pemWriter.close();
    return writer.toString();

But for some reason the PEMWriter class does not exist in Spongy Castle

A: The reason you might be running into issues is because Android uses Bouncy Castle internally as JCA provider. But the version that is included varies over the various Android versions.
You might be interested in the Spongy Castle project, which "simply" repacks Bouncy Castle in a different package so that you can include your own libraries with your Android application.
Using the latest version (1.51.0.0) of Spongy Castle, the following works as intended (on my workstation, no device at hand to test on a device):
import java.security.PublicKey;
import org.spongycastle.openssl.jcajce.JcaPEMWriter;

class PEMConverter {

    public static String toPEM(PublicKey pubKey) {
        StringWriter sw = new StringWriter();
        JcaPEMWriter pemWriter = new JcaPEMWriter(sw);
        pemWriter.writeObject(pubKey);
        pemWriter.close();
        return sw.toString();
    }
}

A: Ok So this is probably not the smartest way (or maybe it is?) to do it, but after checking out the sources for PEMWriter this class basically does this under the hood:

*

*when calling writeObject it creates an instance of MiscPEMGenerator

*MiscPEMGenerator then creates the PemObject by checking the type of the constructor's argument, the following is an excerpt from MiscPEMGenerator's source:
private PemObject createPemObject(Object o){
  ...
  else if (o instanceof PublicKey)
  {
      type = "PUBLIC KEY";

      encoding = ((PublicKey)o).getEncoded();
  }
  ...
  return new PemObject(type, encoding);
}

So as can be seen from the MiscPEMGenerator code the only thing I had to change was the type parameter from "RSA PUBLIC KEY" to just "PUBLIC KEY". Here is the final code.
PublicKey publicKey = keyPair.getPublic();
StringWriter writer = new StringWriter();
PemWriter pemWriter = new PemWriter(writer);
pemWriter.writeObject(new PemObject("PUBLIC KEY", publicKey.getEncoded()));
pemWriter.flush();
pemWriter.close();
return writer.toString();


text:
Q: subrocess.Popen user -dir not supported I am using a program (Owasp Zap in this case) in daemon mode on ubuntu. Using python I have to change the -dir of the configuration files. By doing so:
proc = subprocess.Popen(["./zap.sh","-dir ../../../home/ubuntu/Owasp/testConfig","-daemon"])

this error comes out in console.
10318 [ZAP-daemon] ERROR org.zaproxy.zap.DaemonBootstrap - Unsupported option '-dir ../../../home/ubuntu/Owasp/testConfig'.;

Can you tell me how I can run in daemon mode by changing the -dir? Thank you


text:
Q: Debug code with in curly braces - c-sharp Typically we use F11 and F10 for debugging in visual studio, but when the code section is within curly braces { we may not be able to debug inside lines (refer the attached screen shot lines 36, 37, 38).
How do we debug those sub lines during debugging ?

A: As mentioned by Phuzi in a comment. You are pointing to a lambda statement block. This is used to specify some piece of code to be called later from some other code. The common name for this is delegate, and functions somewhat similar to the native concept of 'function pointer'.
So when you step thru the code there will only be a single method call that is stepped over in one step. You can add a breakpoint to one of the lines in this lambda statement, and the debugger will break when this line is called. This might happen when you step over the function call, but it might also happen at some later time, or not at all. It all depends on the implementation of AddAuthentication.


text:
Q: How to access windows Active Directory anonymously? In my Java web (JBoss) application, I need to get data from Active Directory. Basically, I know the employee's userID (windows login ID), and I need to know his/her office phone number. I think the only place that contains employee's phone # is Windows Active Directory. So I tried some sample java code and try to get access to Active Directory. Here is a sample code (http://myjeeva.com/querying-active-directory-using-java.html)
public ActiveDirectory(String username, String password, String domainController) {
    properties = new Properties();

    properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    properties.put(Context.PROVIDER_URL, "LDAP://" + domainController);
    properties.put(Context.SECURITY_PRINCIPAL, username + "@" + domainController);
    properties.put(Context.SECURITY_CREDENTIALS, password);

    // initializing active directory LDAP connection
    try {
        dirContext = new InitialDirContext(properties);
    } catch (NamingException e) {
        LOG.severe(e.getMessage());
    }

    // default domain base for search
    domainBase = getDomainBase(domainController);

    // initializing search controls
    searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchCtls.setReturningAttributes(returnAttributes);
}

We can see that I need to have user name and password in order to query user's data in active directory, but it is not possible for me to get all user's password. I also tried to set "password" to "none" which tried to use anonymous access, but it does not work.
Does anybody know if it's possible to access Active directory anonymously? I was told in asp.net, it is possible to access active directory without providing user id and password. I am wondering it should be working in Java as well. I appreciate any help or examples. Thanks a lot.

A: *

*AFAIK nowadays it's pretty uncommon to allow an anonymous login to an ldap server

*Ask the admin of the Active Directory server, if 1) is (partially) allowed

*You don't need to have the passwords of every user to access anybodies phone number; try to impersonate your JBoss app with a single account specifically setup for you web app, having just enough rights to read what you need

*Before doing any LDAP programming use a good LDAP editor to see whether you can gain access to the things you need. Try e.g. http://directory.apache.org/studio.


text:
Q: How to get a region list in IBM cloud object storage using Rest API I need a Get Region List in IBM Cloud Object Storage using Rest API. For Example :us-east,au-syd etc.I didn't find any API references related to get Region List.

A: You may want to retrieve the region endpoints.
Try using the following rest api call:
https://[username]:[apiKey]@api.softlayer.com/rest/v3/SoftLayer_Network_Storage_Hub_Cleversafe_Account/[accountId]/getEndpoints

Output:
[
  {
        "legacy": true,
        "location": "us-south",
        "region": "regional",
        "type": "public",
        "url": "s3.us-south.objectstorage.softlayer.net"
    },
    {
        "legacy": true,
        "location": "us-east",
        "region": "regional",
        "type": "public",
        "url": "s3.us-east.objectstorage.softlayer.net"
    },
    {
        "legacy": true,
        "location": "eu-gb",
        "region": "regional",
        "type": "public",
        "url": "s3.eu-gb.objectstorage.softlayer.net"
    },
]

Reference:
https://sldn.softlayer.com/reference/services/SoftLayer_Network_Storage_Hub_Cleversafe_Account/getEndpoints/
Hope this helps.


text:
Q: Is it possible to disable/enable a jquery function on change of radio button I am working on the checkout part of an online store. I created a script to be triggered once a form was submitted. i want this script to activate only if the selected payment method is not paypal since i want to skip the ajax process.
I am using codeigniter framework
Here's the code for the view
<form  action="<?php echo site_url('products/order')?>" method="post" id="checkoutForm" name="checkoutForm">
   ...
   <input type="radio" name="paymentMethod" value="cod">CASH ON DELIVERY
   <input type="radio" name="paymentMethod" value="paypal">PAYPAL
   ...
   <input type="submit" id="btnOrder" value="ORDER NOW">
</form>

<script type="text/javascript">
  var paymentMethod = '';
  $(document).ready(function(){
      $('input:radio[name="paymentMethod"]').change(function(){
           paymentMethod = $(this).val();

      });

   if(paymentMethod != 'paypal' && paymentMethod != ''){
      $('#checkoutForm').submit(function(){
         ...
         $.post($('#checkoutForm').attr('action'), $('#checkoutForm').serialize(), function( data ) {
           ...
         }, 'json');
      return false;
      });
    }
  });
</script>

Here's the code for the function in my controller (products.php)
public function order() {
    $paymentMethod = $this->input->post('paymentMethod');
    ...
    if($paymentMethod != 'paypal'){
        echo json_encode(array('stat' => 1,'msg' => 'Registered Successfully', 'order_id' => $order_id));

     }else{
        // ... Some paypal configurations
        $this->paypal->pay(); //Proccess the payment
    }

} # End order

What i've tried so far was to put an if statement outside the $('#checkoutForm').submit to check if radio button value is not paypal, but it's not working.
Thanks in advance

A: You'll have to get the value, and do the checks, when the form is submitted. Right now you're doing the checks when the page first loads, before the value is even changed.
$('#checkoutForm').submit(function(e){
     e.preventDefault();

     var paymentMethod = $('input:radio[name="paymentMethod"]').val();

     if(paymentMethod != 'paypal' && paymentMethod != ''){

         $.post($(this).attr('action'), $(this).serialize(), function( data ) {
           ...
         }, 'json');
     }
});


text:
Q: TypeError: Cannot read properties of null (reading 'createEvent') I have written a simple test case which checks the tooltip value on mouse hover in a react component
it("displays XYZ Information with 'Code' in a tooltip", async () => {
    (useRouter as jest.Mock).mockImplementation(() => ({ locale: "en-us" }));
    ....
    const { container } = renderPage(<Comp {...comprops} FLAG={true} />);
    await screen.findByRole("button", { name: /settings/i });
    const creatorCodeTooltip = container.querySelector(".tooltip-element");
    expect(creatorCodeTooltip).toBeInTheDocument();

    userEvent.hover(creatorCodeTooltip);

    waitFor(() => {
      expect(screen.queryByText(/TESTCREATORCODE1P8/i)).toBeInTheDocument();
    });
  });

But getting this error
node_modules/react-dom/cjs/react-dom.development.js:3905
      var evt = document.createEvent('Event');
                         ^

TypeError: Cannot read properties of null (reading 'createEvent')
    at Object.invokeGuardedCallbackDev (.../node_modules/react-dom/cjs/react-dom.development.js:3905:26)
    at invokeGuardedCallback (.../node_modules/react-dom/cjs/react-dom.development.js:4056:31)
    at flushPassiveEffectsImpl (.../node_modules/react-dom/cjs/react-dom.development.js:23543:11)
    at unstable_runWithPriority (.../node_modules/scheduler/cjs/scheduler.development.js:468:12)
    at runWithPriority$1 (.../node_modules/react-dom/cjs/react-dom.development.js:11276:10)
    at flushPassiveEffects (.../node_modules/react-dom/cjs/react-dom.development.js:23447:14)
    at Object.<anonymous>.flushWork (.../node_modules/react-dom/cjs/react-dom-test-utils.development.js:992:10)
    at Immediate.<anonymous> (.../node_modules/react-dom/cjs/react-dom-test-utils.development.js:1003:11)
    at processImmediate (node:internal/timers:466:21)

A: This issue generally comes with async code in test cases, whenever one is using async code, they have to use await keyword at the function level.
Here I was using async but "await" was missing before "waitfor" which was causing the issue
await waitFor(() => {
  expect(screen.queryByText(/TESTCREATORCODE1P8/i)).toBeInTheDocument();
});

https://github.com/testing-library/react-testing-library/issues/1027


text:
Q: Elasticsearch Master node confusion Running elastic search with 2, 3 and 4 nodes.  Configuration is generic recommended to insure the cluster can respond to requests if all but one node goes down.
For 3 and 4 node configurations, I'm seeing some serious issues. There are multiple nodes electing themselves as master.  What's worse, sometimes those master nodes only know about N-1 of the other nodes.
My cluster is named the same in every configuration file, and each node was given a unique name as well.  The query performance is taking a hit because multiple nodes think it's only an N-1 cluster, and it's impossible to guess which node is going to decide to elect itself as a dumber master.
Any ideas?

A: Are you using multicast? Disable that and list your hostnames in "discovery.zen.ping.unicast.hosts".
While you're at it I recommend you check this out https://www.elastic.co/webinars/elasticsearch-pre-flight-checklist/
One thing I'd like to change from the recommendations in the above link is to have dedicated master nodes.


text:
Q: USB disk not recognized by Linux I have a Raspberry Pi running a Debian based linux distribution (Raspbmc).
I have a ext4 formatted 1 TB usb disk connected to it, mounted under this path: /media/Monolite
with this line in the /etc/fstab:
UUID=683ff60f-5d1a-4cc2-99bd-b0f146a4362a /media/Monolite ext4 rw,user,exec

Suddendly, the disk is no more recognized.
I unmounted it, unplugged it and plugged it again. Still not showing up.
If I run sudo mount -a I get this error:
mount: special device UUID=683ff60f-5d1a-4cc2-99bd-b0f146a4362a does not exist

Output of sudo lsusb contains:
Bus 001 Device 017: ID 059f:0951 LaCie, Ltd

which is the disk, so it is recognized in some way, I think.
Output of dmesg contains this:
usb 1-1.2.4.3: new high-speed USB device number 12 using dwc_otg
usb 1-1.2.4.3: New USB device found, idVendor=059f, idProduct=0951
usb 1-1.2.4.3: New USB device strings: Mfr=10, Product=11, SerialNumber=5
usb 1-1.2.4.3: Product: LaCie Hard Drive USB
usb 1-1.2.4.3: Manufacturer: LaCie
usb 1-1.2.4.3: SerialNumber: 152D203380B6
usb-storage 1-1.2.4.3:1.0: USB Mass Storage device detected
scsi5 : usb-storage 1-1.2.4.3:1.0
usb 1-1.2.4.3: reset high-speed USB device number 12 using dwc_otg
usb 1-1.2.4.3: reset high-speed USB device number 12 using dwc_otg
usb 1-1.2.4.3: reset high-speed USB device number 12 using dwc_otg
usb 1-1.2.4.3: device descriptor read/64, error -71
usb 1-1.2.4.3: device descriptor read/64, error -71
usb 1-1.2.4.3: reset high-speed USB device number 12 using dwc_otg
usb 1-1.2.4.3: device descriptor read/64, error -71
usb 1-1.2.4.3: device descriptor read/64, error -71
usb 1-1.2.4.3: reset high-speed USB device number 12 using dwc_otg
usb 1-1.2.4.3: device not accepting address 12, error -71
usb 1-1.2.4.3: reset high-speed USB device number 12 using dwc_otg
usb 1-1.2.4.3: device not accepting address 12, error -71
scsi 5:0:0:0: Device offlined - not ready after error recovery
usb 1-1.2.4.3: USB disconnect, device number 12
usb 1-1.2.4.3: new high-speed USB device number 13 using dwc_otg
usb 1-1.2.4.3: device descriptor read/64, error -71
usb 1-1.2.4.3: device descriptor read/64, error -71
usb 1-1.2.4.3: new high-speed USB device number 14 using dwc_otg
usb 1-1.2.4.3: device descriptor read/64, error -71
usb 1-1.2.4.3: device descriptor read/64, error -71
usb 1-1.2.4.3: new high-speed USB device number 15 using dwc_otg
usb 1-1.2.4.3: device not accepting address 15, error -71
usb 1-1.2.4.3: new high-speed USB device number 16 using dwc_otg
usb 1-1.2.4.3: device not accepting address 16, error -71
hub 1-1.2.4:1.0: unable to enumerate USB device on port 3
usb 1-1.2.4.3: new high-speed USB device number 17 using dwc_otg

Also, the disk is making a funny noise, which I suppose is not a good sign.
Is there any way I can read the data in the disk, or is it gone?
Thanks.

A: Gpart  NOT Gparted  OR  testdisk (and its other included tool photorec) are great BUT as with everything of this nature do it unmounted (from an installer or other OS) and with as little writing to the drive as possible in the interim

A: Connect to the manufacturer's site and look for the disk recovery software. Almost all manufacturers have such a tool (Western Digital's is called DLG if I recall correctly). It might be a tool which runs in DOS or windows. These tools are able to switch bad sectors for spare ones, and get the disk at least logically correct again. There might be some files which have now bad sectors replaced by new ones, but at least the space is usable again.
Then run fsck.ext4 on the driver - this does not mount the disk (which should not be mounted either) and checks for the file structure. If the superblock is damaged, it can use a backup copy, and maybe get access close to normal again. See the man page and Wikipedia
If you get access, backup everything and run a diagnostic on the disk to decide if you're going to be able to continue using it. Also check the power supply cables to see if they're reliable - they're frequently the cause for such problems. If that's the problem, it's not the disk's fault!


text:
Q: How to download bittorrent form ppa? I am using this command to try to download qBittorrent
sudo add-apt-repository ppa:qbittorrent-team/qbittorrent-stable
However, I am getting this error:
Hit:1 http://dl.google.com/linux/chrome/deb stable InRelease
Hit:2 http://us.archive.ubuntu.com/ubuntu focal InRelease
Get:3 http://us.archive.ubuntu.com/ubuntu focal-updates InRelease [114 kB]
Get:4 http://us.archive.ubuntu.com/ubuntu focal-backports InRelease [101 kB]
Get:5 http://us.archive.ubuntu.com/ubuntu focal-updates/main amd64 Packages [1,031 kB]
Get:6 http://us.archive.ubuntu.com/ubuntu focal-updates/main i386 Packages [490 kB]
Get:7 http://us.archive.ubuntu.com/ubuntu focal-updates/main amd64 DEP-11 Metadata [283 kB]
Get:8 http://us.archive.ubuntu.com/ubuntu focal-updates/universe amd64 Packages [781 kB]
Get:9 http://us.archive.ubuntu.com/ubuntu focal-updates/universe amd64 DEP-11 Metadata [330 kB]
Get:10 http://us.archive.ubuntu.com/ubuntu focal-updates/universe DEP-11 48x48 Icons [205 kB]
Get:11 http://us.archive.ubuntu.com/ubuntu focal-updates/multiverse amd64 DEP-11 Metadata [2,468 B]
Get:12 http://us.archive.ubuntu.com/ubuntu focal-backports/universe amd64 DEP-11 Metadata [1,768 B]
Hit:13 https://packagecloud.io/slacktechnologies/slack/debian jessie InRelease
Get:14 http://security.ubuntu.com/ubuntu focal-security InRelease [114 kB]
Ign:15 https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 InRelease
Get:16 https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 Release [5,378 B]
Get:17 https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 Release.gpg [801 B]
Get:18 https://brave-browser-apt-release.s3.brave.com stable InRelease [4,317 B]
Get:19 https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4/multiverse arm64 Packages [9,065 B]
Hit:20 http://ppa.launchpad.net/apandada1/brightness-controller/ubuntu focal InRelease
Get:21 https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4/multiverse amd64 Packages [12.2 kB]
Get:22 https://brave-browser-apt-release.s3.brave.com stable/main amd64 Packages [4,887 B]
Get:23 http://security.ubuntu.com/ubuntu focal-security/main amd64 Packages [704 kB]
Ign:24 http://ppa.launchpad.net/bitcoin/bitcoin/ubuntu focal InRelease
Get:25 http://security.ubuntu.com/ubuntu focal-security/main Translation-en [141 kB]
Get:26 http://security.ubuntu.com/ubuntu focal-security/main amd64 DEP-11 Metadata [24.5 kB]
Get:27 http://security.ubuntu.com/ubuntu focal-security/restricted amd64 Packages [251 kB]
Get:28 http://security.ubuntu.com/ubuntu focal-security/restricted Translation-en [36.5 kB]
Get:29 http://security.ubuntu.com/ubuntu focal-security/universe amd64 DEP-11 Metadata [58.3 kB]
Get:30 http://security.ubuntu.com/ubuntu focal-security/multiverse amd64 DEP-11 Metadata [2,464 B]
Get:31 http://ppa.launchpad.net/ethereum/ethereum/ubuntu focal InRelease [17.5 kB]
Hit:32 http://ppa.launchpad.net/obsproject/obs-studio/ubuntu focal InRelease
Hit:33 http://ppa.launchpad.net/qbittorrent-team/qbittorrent-stable/ubuntu focal InRelease
Hit:34 http://ppa.launchpad.net/wireshark-dev/stable/ubuntu focal InRelease
Err:35 http://ppa.launchpad.net/bitcoin/bitcoin/ubuntu focal Release
  404  Not Found [IP: 91.189.95.85 80]
Get:36 http://ppa.launchpad.net/ethereum/ethereum/ubuntu focal/main amd64 Packages [2,808 B]
Hit:37 https://repo.windscribe.com/ubuntu bionic InRelease
Reading package lists... Done
E: The repository 'http://ppa.launchpad.net/bitcoin/bitcoin/ubuntu focal Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

Why does the "bitcoin" repository cause an error for bittorrent, which is something totally different? Obviously, there is something I don't understand here about packages/repositories, but why does this request for many other applications (ubuntu, mongodb, ethereum, etc.)?


text:
Q: Grub not showing in Lubuntu-OpenELEC dual boot I'm building an HTPC from an old desktop computer.  My plan was to dual-boot LUBUNTU and openELEC.  Being kind of new to Linux, I've been working over a week on this project and now I'm stuck.  I've followed the instruction from http://wiki.openelec.tv/index.php/Dual_Boot (the 4.1 "old" section) to the letter.  My Lubuntu worked very well, then install OpenELEC which also work very well, but my Grub interface is not showing up.  Since I've install OpenELEC, I don't have access to Lubuntu anymore.
I've reinstall/repair grub with a live cd following: http://howtoubuntu.org/how-to-repair-restore-reinstall-grub-2-with-a-ubuntu-live-cd but it didn't help.  I've look around online but most people having this problem are dual booting Windows, which I don't.
Here is some info:
Device     Boot     Start       End   Sectors   Size Id Type
/dev/sda1 *         2048 293083135 293081088 139.8G 83 Linux
/dev/sda2       293083136 298942463   5859328   2.8G 82 Linux swap / Solaris
/dev/sda3       480204800 488396799   8192000   3.9G 83 Linux
/dev/sda4       298942464 480204799 181262336  86.4G 83 Linux

My Lubuntu is on sda1 and my OpenELEC System is on sda3.
The 40_custom file:
#!/bin/sh
exec tail -n +3 $0
# This file provides an easy way to add custom menu entries.  Simply type the
# menu entries you want to add after this comment.  Be careful not to change
# the 'exec tail' line above.

menuentry "OpenELEC.tv" {
   set root=(hd0,3)
   linux /KERNEL boot=/dev/sda3 disk=/dev/sda4 quiet
}

menuentry "OpenELEC.tv (Textmode)" {
   set root=(hd0,3)
   linux /KERNEL boot=/dev/sda3 disk=/dev/sda4 textmode quiet
}

menuentry "OpenELEC.tv (Debugmode)" {
   set root=(hd0,3)
   linux /KERNEL boot=/dev/sda3 disk=/dev/sda4 debugging textmode quiet
}

And finally the default:
GRUB_DEFAULT="0"
GRUB_HIDDEN_TIMEOUT=0
GRUB_HIDDEN_TIMEOUT_QUIET=true
GRUB_TIMEOUT=5
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
GRUB_CMDLINE_LINUX=""

FYI, I've started with GRUB_DEFAULT="OpenELEC.tv" but it wasn't working, I've put "0" with the hope it would boot Lubuntu by default at least.
I've also tried to boot with holding down shift but it didn't help.
Any idea what my next step could be? I'm stuck...  Thanks

A: Try holding shift while booting up, this is the solution I see everywhere. OR if you don't care about data (or you could get a liveboot and copy files from your home directory to a thumb drive), just reinstall ubuntu beside WinXP and copy your /boot dir to a data disk in case this were to happen again, then you would have a quite handy liveboot disk and an extra /boot partition to copy/ use to fix broken files
good luck fixing your grub installation


text:
Q: Bitbucket Webhook is not triggering Jenkins job even webhook returns 200 I am using bitbucket cloud and jenkins is running on ec2 instance on the private network.
Connection is well established between bitbucket and jenkins as when i run the job manually, the job shows the green status. However when i made the changes in the repo and it gets merged the webhook is not using my app password and as a result the job is getting failed.
I am getting authentication failed and It's basically asking me to use the app password. I have already created it but still webhook is not using it. I am getting the response 200 now in webhook means my webhook is able to reach the jenkins server but i am not sure why i am getting authentication failed.

A: Can you confirm that:

*

*Your credentials are correctly placed under the credentials section of Jenkins. The username should be the username of the account you are using, and the password should be the app password. It should be present like this:

*The ID of the credentials should be used within your pipeline script anywhere you want access to the Bitbucket repository.

*Ensure that Bitbucket has access to your EC2 instance that runs Jenkins.

Basically, these are the 3 points where authentication can fail. Checking each point should reveal the problem.


text:
Q: Unable to render text properly Kannada(Indian language) to Image using PHP Here is my php code
$text = 'ಕನ್ನಡ';
$txt_color1 = 'red';
imagettftext($handle, 30, 0, 25, 60, $txt_color1, 'fonts\akshar.ttf', $text);

It results:
enter image description here
*I tried available fonts(kannada) but I'm getting same result.


text:
Q: dotnet publish changes assembly version of assemblies under the same solution I have 3 projects.
MicroService1
MicroService1.Core
MicroService1.Web

MicroService.Web references both MicroService 1 and MicroService1.Core.
In MicroService1.Web I have the following under the project file

When I run dotnet.exe publish ./MicroService1.Web/MicroService1.Web.csproj --framework net6.0 --configuration Release --runtime win-x64 --self-contained true it creates three assemblies MicroService1.dll, MicroService1.Core.dll and MicroService1.Web.dll
Inspecting version of all of them (using right click => details) returns the following
MicroService1.dll - 1.0.0.0
MicroService1.Core.dll - 1.0.0.0
MicroService1.Web.dll - 2.1.1.1

Which is correct since we only set version for MicroService1.Web
using exactly the same script in azure devops pipeline produces the following:
MicroService1.dll - 2.1.1.1
MicroService1.Core.dll - 2.1.1.1
MicroService1.Web.dll - 2.1.1.1

Why does this happen? How can I stop this?


text:
Q: Converting multi dimensional array to single dimensional array using Dataweave Need to convert multi-dimensional array (json) into single dimensional array by repeating parent attribute with child attribute.
Condition is that parent may have child or may not have child.
There is 100s of attribute that needs to map so would be great if I can map every attribute without defining individual attribute names (if feasible).
It would be great if this problem could be solved by only using .dwl
Original payload:
[
  {
    "id": "1",
    "parentAttribute1": "parent1-1",
    "parentAttribute2": "parent1-2",
    "parentAttribute3": "parent1-3",
    "child": [
      {
        "childAttribute1": "inner1-1-1",
        "childAttribute2": "inner1-1-2"
      },
      {
        "childAttribute1": "inner1-2-1",
        "childAttribute2": "inner1-2-2"
      },
      {
        "childAttribute1": "inner1-3-1",
        "childAttribute2": "inner1-3-2"
      }
    ]
  },
  {
    "id": "2",
    "parentAttribute1": "parent2-1",
    "parentAttribute2": "parent2-2",
    "parentAttribute3": "parent2-3",
    "child": [
      {
        "childAttribute1": "inner2-1-1",
        "childAttribute2": "inner2-1-2"
      }
    ]
  },
  {
    "id": "3",
    "parentAttribute1": "parent3-1",
    "parentAttribute2": "parent3-2",
    "parentAttribute3": "parent3-3"
  }
]

Expected payload after translation - Scenario 1 - All attributes
[
  {
    "id": "1",
    "parentAttribute1": "parent1-1",
    "parentAttribute2": "parent1-2",
    "parentAttribute3": "parent1-3",
    "childAttribute1": "inner1-1-1",
    "childAttribute2": "inner1-1-2"
  },
  {
    "id": "1",
    "parentAttribute1": "parent1-1",
    "parentAttribute2": "parent1-2",
    "parentAttribute3": "parent1-3",
    "childAttribute1": "inner1-2-1",
    "childAttribute2": "inner1-2-2"
  },
  {
    "id": "1",
    "parentAttribute1": "parent1-1",
    "parentAttribute2": "parent1-2",
    "parentAttribute3": "parent1-3",
    "childAttribute1": "inner1-3-1",
    "childAttribute2": "inner1-3-2"
  },
  {
    "id": "2",
    "parentAttribute1": "parent2-1",
    "parentAttribute2": "parent2-2",
    "parentAttribute3": "parent2-3",
    "childAttribute1": "inner2-1-1",
    "childAttribute2": "inner2-1-2"
  },
  {
    "id": "3",
    "parentAttribute1": "parent3-1",
    "parentAttribute2": "parent3-2",
    "parentAttribute3": "parent3-3"
  }
]

Expected payload after translation - Scenario 2 - Some attributes only
[
  {
    "id": "1",
    "parentAttribute1": "parent1-1",
    "childAttribute1": "inner1-1-1"
  },
  {
    "id": "1",
    "parentAttribute1": "parent1-1",
    "childAttribute1": "inner1-2-1"
  },
  {
    "id": "1",
    "parentAttribute1": "parent1-1",
    "childAttribute1": "inner1-3-1"
  },
  {
    "id": "2",
    "parentAttribute1": "parent2-1",
    "childAttribute1": "inner2-1-1"
  },
  {
    "id": "3",
    "parentAttribute1": "parent3-1",
  }
]

Tried to use reduce, group functions but was unable to merge them.
n/a
n/a

A: The key is to use the flatten plus a nested map. This way you can access both levels so you can operate with them.
%dw 2.0
output application/json
---
flatten(payload map
    ((parent, index) ->
        if (parent.child?)
            parent.child map ((child, index) -> (parent - "child") ++ child)
        else
          [parent]
    )
 )

For dw 1 this is the solution
%dw 1.0

    %output application/json
    ---
    flatten (payload map
        ((parent, index) ->

                parent.child map ((child, index) -> (parent - "child") ++ child) when  (parent.child?)
            otherwise
              [parent]
        )
     )


text:
Q: Angular2: ng2-img-cropper does not crop url image I am using ng2-img-cropper to crop a photo (not avatar).
https://github.com/cstefanache/angular2-img-cropper
I followed the example:
https://embed.plnkr.co/V91mKCNkBQZB5QO2MUP4/
I saw that it seems not to support url image, only local image. Is there anyway to make it work with url image?
If not, is there any alternative which can work with url image?
Thanks for any suggestion.

A: please check the discussion in the following thread: https://github.com/cstefanache/angular2-img-cropper/issues/110
The idea is to work with something like:
var image:HTMLImageElement = new Image();
    this.image.crossOrigin = 'Anonymous';
    image.src ='https://www.google.ro/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';
    image.addEventListener('load', (data) => {
        this.cropper.setImage(image);
    });


text:
Q: HAML: How do I generate a self-closing (href-lang) link tag? I need to generate this exact (href-lang) link  HAML:
<link rel="alternate" hreflang="es" href="http://es.example.com/" />

This HAML code:
%link{href: "http://es.example.com/", hreflang: "es", rel: "alternate"}

gets converted to:
<link href="http://es.example.com/" hreflang="es" rel="alternate"></link>

Any ideas anyone?

A: Can you post what version of HAML you are running? Also make sure that your list of auto closed tags has not been altered.
I would also double check that your link tags are not just HTML5 "assumed closed" w/ no trailing / at the end of the tag.
https://github.com/haml/haml/blob/master/REFERENCE.md#empty-void-tags-


text:
Q: MS Word 2010 mail merge: dynamic url, same text I have a MS word 2010 mail merge that needs a personal url as href and a generic title for all users
i can send a url that displays as the full url, but i want a generic display text so users dont see all the parameters or a gigantic url
i have attempted to first insert the hyperlink then ALT+F9, this did not pass the mergefield
 {HYPERLINK "http://domain.wufoo.com/form1/def/Field1={MERGEFIELD id_number}" }

I then attempted after inserting the hyperlink to call a new field as the url, this did not remove the original inserted hyperlink as it seems to require a url value on inserting
 {HYPERLINK {MERGEFIELD url} \* MERGEFORMAT }

I attempted to follow the instructions here http://support.microsoft.com/kb/912679 method #1 but the word 2002-2003 menus are different, i havent been able to insert a hyperlink without a url ('"Error! Hyperlink reference not valid" appears in the document.")
I am just not sure how to go about this

A: Once i figured out how to insert a hyperlink without a url from http://support.microsoft.com/kb/912679 method #1, this went off without a hitch
In Word 2010, goto Insert -> Quick parts -> Field and select Hyperlink then hit OK
This inserts a URL without a link address, which you can then follow the rest of the steps to place the mergefield as the url

A: The { HYPERLINK { MERGEFIELD url } } approach should work, but to get the right displaytext, select the hyperlink field (whether the field or result is displaying, and run the following VBA in the VB Editor's immediate window:
selection.Fields(1).Result.Text = "the display text you want"


text: Q: Close Google Chrome tab remotely from another device I often forget a music/video stream open in a Chrome tab on another device. Chrome's device listing at chrome://history/syncedTabs lets me reopen the tab on the current device. However, this opens a duplicate of the tab and leaves the remote tab open. I'm looking for a Chrome feature or extension that would let me close the original tab remotely. Would be nice if the extension would work on both Mac and Windows. The extension can use Internet for communication.


text:
Q: OpenSuse switches GPUs mid-setup While installing OpenSuse Tumbleweed on an Optimus-equipped laptop, I have the problem that mid-setup (without a fixed time) the setup switches from the external GPU (which is used while booting) to the internal GPU, thus freezing the whole setup. Is there a way to prevent that? Otherwise I can not install the OS.

A: There are two possibilities -> texmode installation or specify BrokenModules.
Both are possible to specify in Boot options line of Bootloader screen.

*

*texmode is specifieed by texmode=1

*BrokenModules - BrokenModules=i915 -- this prevents intel gpu driver from loading.

More information about linuxrc in openSUSE : https://en.opensuse.org/SDB:Linuxrc#Parameter_Reference


text:
Q: VBA for each loop iteration returns empty value I'm new to Excel VBA. I've learned Python and Ruby before so any analogy to these languages are welcome.
While I was working on For Each loop, I keep gets Empty value for each iteration.
i.e,
Sub testfield()
Dim testEach As Range
Dim testRange As Range

Set testRange = Worksheets(2).Range("O2:O76")

For Each testEach In testRange.Cells
    MsgBox (testEach.Value)

Next
End Sub

Range("O2:O76")
When I run this code, MsgBox returns empty space and the debugger also says testEach.Value is Empty.
What did I do wrong? How do I get the values out of that iteration?
I'm working on a project and it's driving me crazy. Please help me.


text:
Q: Recognize keystrokes using getch() [AT&T C++ 2.1] I am making a C++ program on C++ 2.1 (Yeah the one that uses iostream.h) on Turbo C++. I am forced to use such an old software that works on DOS because I am supposed to use it for a school project (SORRY). The question is, I am forced to use getch() from conio.h as a method for detecting keystrokes as I am oblivious for other methods. Sadly, I recognizes one key at a time, making it impossible to recognize multi-key strokes (I am trying to develop a multiplayer single-keyboard game). Please help me and tell me if there is a way of achieving the desired functionality in my obsolete version of C++. Thanks in advance.
Link to the code (Input related functions are in input.h file)


text:
Q: Spawned Node (.exe) process doesnt catch stderr messages So I am having some trouble with Node and spawning processes here..
I am spawning an external exe process as such:
            var writeStream = fs.createWriteStream(logPath);

            writeStream.write(new Date().toString() + " : " + type + " : LOG STARTED ");

            var process = cp.spawn(fileNameExecutable, paramArray, {
                cwd: pathToExecutable
            });

            process.stdout.on('data', function (data) {
                writeStream.write(new Date().toString() + " : " + type + " stdout : " + string);
            });

            var errorLog = "";
            process.stderr.on('data', function (data) {
                errorLog += data;
                writeStream.write(new Date().toString() + " : " + type + " stderr : " + data );
            });

            process.on("exit", function (exitcode) {
                if (exitcode === 1) {
                    done(new Error(errorLog));
                } else {
                    done();
                }
            });

Problem is that this code only catches the stdout of the process for some reason.. Everything which is outputted over stderr doesnt arrive at the listener.
I know there is stderr output because when I am running the same command over commandline and attach
> stdout.txt 2> stderr.txt

to redirect both streams into a textfile, I am getting messages in both my stderr.txt and stdout.txt
Does anybody have any ideas why the stderr listener is not getting these messages in my JS code ?

A: Ok, so I finally found the solution..
The application is a QT based C++ app with the following behavior:
Where is located the qDebug qWarning qCritical and qFatal log by default on Qt?
In short: by setting QT_LOGGING_TO_CONSOLE to 1 before node startup it gets logged correctly.


text:
Q: Onclick function inside blade check box I am using blade template check box. I want to make it checked and readonly. So that i find other way to make it readonly by using onclick function. On onclick function using Jquery make the checkbox readonly. But how to assign function inside blade checkbox ?. Is there any way to make it both checked and readonly.
{{Form::checkbox('allRole[]', $allRole->name,true)}}

A: Try this :
{{Form::checkbox('allRole[]', $allRole->name,true,array('disabled'))}}

A: Try to add readonly in options:
{{Form::checkbox('allRole[]', $allRole->name, true, ['readonly'=>true])}}

A: You can write onlcick function for the checkbox to get checked first and then make it readonly. You can use onclick as,
{{ Form::checkbox('name', 'value', true, ['onClick' => 'alert(123)']) }}

A: I found the answer by Mr. Zoltan Toth:
<input type='checkbox' />

$('input[type="checkbox"]').on('click', function(event) {
event.preventDefault();
event.stopPropagation();

return false;

alert('Break');
)};

preventing checkbox from changing


text:
Q: convert string to date without time This line
System.DateTime.Parse("09/12/2009");

convert date (string) to 9/12/2009 12:00:00 AM. How can I get a date in the form 9/12/2009.
after explanations I do:
DateTime dt = System.DateTime.Parse(Request.Form["datepicker"]);
dt.ToString("dd/mm/yyyy");
/* and this code have time, why???*/

A: Anything parsed to a DateTime object will contain date+time. If no time is sepcified, the assumed value will be 0000hr.
To get the date-only representation, it's up to how you format it to string.
E.g. theDate.ToString("dd/MM/yyyy")
Refer to the MSDN Date and Time Format Strings.

A: Your problem is not with the parsing but with the output. Look at how ToString works for DateTime, or use this example:
using System;

class Program
{
    static void Main(string[] args)
    {
        DateTime dt = DateTime.Parse("09/12/2009");
        Console.WriteLine(dt.ToString("dd/MM/yyyy"));
    }
}

Or to get something in your locale:
Console.WriteLine(dt.ToShortDateString());

Update: Your update to the question implies that you do not understand fully my answer yet, so I'll add a little more explanation. There is no Date in .NET - there is only DateTime. If you want to represent a date in .NET, you do so by storing the time midnight at the start of that day. The time must always be stored, even if you don't need it. You cannot remove it. The important point is that when you display this DateTime to a user, you only show them the Date part.

A: if you want to convert gridview datetime column to date only column use this code :
raddgvDaybook.Rows.ToList().ForEach(x =>
{
    DateTime dt = DateTime.Parse(x.Cells["Vocdate"].Value.ToString());
    string str = string.Format("{0:MM/dd/yyyy}", dt);
    x.Cells["Vocdate"].Value = str;
});

I tested the code it will work if you bind the datetime as string in dgv.


text:
Q: Disappearing Images I am still new to Sharepoint and I am trying to upload some files from my staging area to production. Everything work in staging however when I move the files to production, I noticed that there are two images that are displaying on some pages and not others. Does anyone have an idea why this would be happening?

A: Most of the times this issue is related to some permission problem.
A) If it's a picture library, check if your pictures are published.
B) Check if the picture library has the appropriate permissions.


text:
Q: Can I filter mac addresses within DNS? is it possible to setup dns in such a way that only predefined mac addresses are allowed access? Thus meaning only my laptop and cellphone will be able to login?
The service and system to which the dns points is VNC on debian linux.
My router through which the port is forwarded is a D-link router.


text:
Q: FabricJS generating PNG in nodeJS, but sometimes images show as black rectangles. Cause and options to fix/handle? We generate PNGs from the canvas in nodeJS, but usually when there are many images, sometimes some of the images just display as black rectangles. We assume those images timeout and so the black rectangles are there.
What is the cause?
What are the timeouts (nodejs, express, fabricjs,... ) and values and configurations?
What are the best options and workarounds?
Thanks!


text:
Q: Simple Qt app doesn't open on Mac OSX Yosemite Environment

*

*Mac OSX Yosemite

*Qt5

*3 files

*

*main.cpp

*main.qml

*webengine.pro

main.cpp
#include <QtGui/QGuiApplication>
#include <QtQml/QQmlApplicationEngine>
#include <QtWebEngine/qtwebengineglobal.h>

int main(int argc, char *argv[])
{
  QGuiApplication app(argc, argv);
  QtWebEngine::initialize();

  QQmlApplicationEngine engine;
  engine.load(QUrl("main.qml"));

  return app.exec();
}

main.qml
import QtQuick 2.0
import QtWebEngine 1.0
import QtQuick.Controls 1.3
import QtQuick.Window 2.0

ApplicationWindow {
    title: qsTr("Test")
    width: 1200
    height: 800
    visible: true

    WebEngineView {
      width: Screen.width
      height: Screen.height
      anchors.fill: parent
      url: 'http://duckduckgo.com'
    }
}

webengine.pro
TARGET = browser
TEMPLATE = app
SOURCES = main.cpp
QT += qml quick webengine

Running QML - PASS
/usr/local/Cellar/qt5/5.4.0/bin/qmlscene main.qml

Compiling and running Mac App - FAIL
qmake
make

then I clicked on browser.app, the application starts but no window opened.
Any hint about what I am doing wrong?

A: I guess the file main.qml is not found. You should get an error message "... File not found" in the console.
To solve this problem either supply a valid path on your drive or use Qt's resource management.
This is documented here, I'll outline the steps:
1) Create file test.qrc with the following contents:
<!DOCTYPE RCC>
<RCC version="1.0">
<qresource prefix="/">
    <file>main.qml</file>
</qresource>
</RCC>

2) Add test.qrc to webengine.pro
RESOURCES += test.qrc

3) Modify main.cpp to load the qml file from the resources:
engine.load(QUrl("qrc:/main.qml"));


text:
Q: Download localfile through html I have a problem: I want to download a file from my website using this link:
Attachment

But when i click this URL the link gets changed to:
localhost:9000/path/to/file

That means that my firefox does not find the file and cant download it, is there any fix for this?

A: use the full path in the href of a tag.
like this.
 Click Here to download

A: hmm Have you tried forcing the download as such:
Save GIF

If this does not help, it most certantly means that your path is wrong. Are you forcing the real filesystem path?
echo realpath(dirname(__FILE__));


text:
Q: Can someone criticise my incorrect proof about a set being open? In the question I have to decide whether the set $S=\{(x,y)\in\mathbb{R}^2\;|\;x/y\leq 7\}$ is open, closed or neither. I attempted to prove it was closed but it turns out it is neither can someone tell me whats wrong here.
So let $A=\{(x,y)\in\mathbb{R}^2\;|\;x/y > 7\}=\{(x,y)\in\mathbb{R}^2\;|\;y>0,\;x -7y > 0\}\cup\{(x,y)\in\mathbb{R}^2\;|\;y<0,\;x -7y < 0\}$
Set $g(x,y)=y$,  $ f(x,y)=x-7g$ then g and f are cts functions. Then
$A=(g^{-1}(0,\infty)\cap f^{-1}(0,\infty))\cup(g^{-1}(-\infty,0)\cap f^{-1}(-\infty,0))$
So A open by cty of f and g so $\mathbb{R}^2$ \ $A=S$ is closed.

A: At the very end of the proof, you said that $\mathbb R^2\setminus A=S$.  You overlooked the fact that points where $y=0$ are in neither $A$ nor $S$, because $x/y$ is undefined there.


text:
Q: Receive URL in Ionic for ios I am using ionic framework. I'm trying to set up a way to receive a url from another app. Like, you are in browser, click share, and send the link to another app (my app). I found this cordova plugin, and have integrated it in my app. But this is pulgin for Android. I need same functionality in IOS.
Any idea which plugin i need to use for ios.

A: I think you are looking for the Custom URL Scheme plugin.

This plugin allows you to start your app by calling it with a URL like mycoolapp://path?foo=bar

Maybe this article is also in your interest (about deeplinking an Ionic with a Ionic app).


text:
Q: PHP : PDO connection SQL and Missing Returned Data Please find below a script that scrapes an HTML table that should return data in my Database ( SQL|PhpMyAdmin ). I run the script in my browser using ( XAMPP)
The scraper works fine, it can display data in the browser or download as an excel file. I added a connection String to SQL using   [ $conn = mysql_connect ], However, I read this method its been deprecated and its better to use [mysqli_connect ] or PDO.
Questions :

*

*If I use mysqli_connect, I dont encounter problems connecting to my database but the returned data is missing some rows. For example the table has 100 rows and I would just find 80 rows in the database. What could be causing that ? I dont think from the script otherwise I wouldn't see the complete results in the browser

*I tried the PDO ( see code below ) , the connection is successfull however no data is entered in my database. Is there any syntax Error ?
I don't mind using mysql_connect , mysqli_connect or PDO as long as I have all rows in my database without anything missing.
Please advise what connection String to use and why there are missing rows . The script is working well and returned data in browser is the same as the URL scraped.
Code 1 : Using mysqli_connect Method + Script overview
 $connection = mysqli_connect("localhost", "username", "password", "test");

 if (!$connection) {
printf("Connect failed: %s\n", mysqli_connect_error());
 exit();
  }

printf("Host information: %s\n", mysqli_get_host_info($connection));

$OutPut_Excel = $_GET['xls'];// 0 web page or 1 output excel
$show_Country = $_GET['show'];// 0 or 1
$urls = "
http://www.URL.com
";

 //output excel
if($OutPut_Excel == "1")
{
header("Content-Type: application/vnd.ms-execl;charset=iso-8859-1");
header("Content-Disposition: attachment; filename=data.xls");
header("Pragma: no-cache");
header("Expires: 0");
 }

set_time_limit(0);
ini_set('memory_limit', '-1');
ini_set('display_errors',true);

//output html
if($OutPut_Excel == "0")
{
?>

<title>scraper</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<?php
 }

 if($OutPut_Excel == "0")
{
if($show_Country)
{
    $nameCountry = 'Country	';
}
 echo "

Name	Surname
Email	Address	City	Profession	        Phone	$Country
";
 }
 else
 {
echo "Name"."\t";
echo "Surname"."\t";
echo "Email"."\t";
echo "Address"."\t";
echo "City"."\t";
echo "Profession"."\t";
echo "Phone"."\t";
if($show_Country)
{
    echo "Country"."\t";
}

echo "\t\n";
    }

   include 'dom.php';
   $arrurl = explode(';',$urls);
   foreach ($arrurl as $u)
    {
$url = trim($u);
$html = file_get_html($url);
$string = $html->find("table[width=720]",0)->find("font[size=5]",0)->plaintext;
$arr = explode(' at ',$string);
$Satellite = trim($arr[0]);
$Degree = trim($arr[1]);

$k = 0;
foreach ($html->find("table[width=720]") as $d)
{
    $text = $d->outertext;
    $arr = explode('<td',$text);
    $out = "";
    foreach ($arr as $t)
    {
        $arr1 = explode('<font',$t);
        $count_font = count($arr1);
        $arr2 = explode('',$t);
        $count_end_font = count($arr2);
        $need_count = $count_font-$count_end_font;
        $str = "";
        for($j=1;$j<=$need_count;$j++)
        {
            $str=$str."";
        }
        if($out == "")
        {
            $out .= str_replace('	',$str,$t);
        }
        else
        {
            $out .= "<td".str_replace('	',$str,$t);
        }
    }

ECT... Some more code
                            echo "$Name"."\t";
                            echo "$Surname"."\t";
                            echo "$Email"."\t";
                            echo "$Address"."\t";
                            echo "$City"."\t";
                            echo "$Profession"."\t";
                            echo "$Phone"."\t";
                            if($show_Country)
                            {
                                echo   "$Country"."\t";

    // SQL QUERY - WORKS FINE BUT SOME ROWS MISSING
                        }
 $connection->query("INSERT INTO Directory (Name,Surname,Email,Address,City,Profession,Phone,Country) VALUES('$Name','$Surname','$Email','$Address','$City','$Profession','$Phone','$Country')");

CODE 2 - PDO Connection - Returned Data is not entered in database
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');

try{

                         $stmt = $db->prepare('INSERT INTO Directory(Name,Surname,Email,Address,City,Profession,Phone,Country) VALUES($Name, $Surname, $Email, $Address, $City, $Profession, $Phone, $Country)');
                         $stmt->execute(array('Name' => $Name, 'Surname' => $Surname, 'Email' => $Email, 'Address' => $Address, 'City' => $City, 'Profession' => $Profession, 'Phone' => $Phone, 'Country' => $Country));
                         $affected_rows = $stmt->rowCount();

                         } catch(PDOException $ex) {
                         echo "An Error occured!";
                         some_logging_function($ex->getMessage());
                         }

A: On your mysql_query() function call you need to provide the database connection $conn.
It should be like this:
$sql = mysql_query("your sql query", $conn);

Re not all rows being inserted, it must be an error during the insert. Try modifying you code like this so MySQL errors are printed:
$connection->query("your sql query") or die(mysqli_error($connection));

Most likely it is an apostrophe ( ' ) somewhere in one of the values you are inserting. You may need to remove or escape them.

A: Try
$stmt = $db->prepare('INSERT INTO Directory(Name,Surname,Email,Address,City,Profession,Phone,Country) VALUES($Name, $Surname, $Email, $Address, $City, $Profession, $Phone, $Country)');
                         $stmt->execute(array('Name' => $Name, 'Surname' => $Surname, 'Email' => $Email, 'Address' => $Address, 'City' => $City, 'Profession' => $Profession, 'Phone' => $Phone, 'Country' => $Country));

to
$stmt = $db->prepare('INSERT INTO Directory(Name,Surname,Email,Address,City,Profession,Phone,Country) VALUES(:Name, :Surname, :Email, :Address, :City, :Profession, :Phone, :Country)');
                         $stmt->execute(array(':Name' => $Name, ':Surname' => $Surname, ':Email' => $Email, ':Address' => $Address, ':City' => $City, ':Profession' => $Profession, ':Phone' => $Phone, ':Country' => $Country));

http://www.php.net/manual/fr/pdo.prepare.php


text:
Q: Date calculations without daylight savings time I'm trying to perform date calculations for a scheduling app but am running into issues with daylight savings time.  I'm trying to determine the number of days between two dates with:
NSDateComponents *activityComponents = [[NSDateComponents alloc]init];
activityComponents = [self.calendar components:NSDayCalendarUnit
                                      fromDate:self.viewBeginDate
                                        toDate:item.ES
                                       options:0];
NSLog(@"Days: %d and hours: %d", [activityComponents day], [activityComponents hour]);

where self.viewBeginDate and item.ES are both NSDate objects and self.calendar is a gregorian calendar.

*

*When calculating between Nov 1, 2013 and Nov 1, 2013, it provides 0.

*When calculating between Nov 1, 2013 and Nov 2, 2013, it provides 1.

*When calculating between Nov 1, 2013 and Nov 3, 2013, it provides 2.

*When calculating between Nov 1, 2013 and Nov 4, 2013, it provides 2
again!

Here is my output:
    Days: 0 and hours: 0
    Days: 1 and hours: 0
    Days: 2 and hours: 0
    Days: 2 and hours: 24
    Days: 3 and hours: 23

I'd like to be able to determine the number of days between 2 NSDate objects without impact by Daylight Savings Time, as my app doesn't care what local or timezone the user is in.  I just want it to tell me that there are 3 days between Nov 1, 2013 and Nov 4, 2013.  Any thoughts?
My NSDate objects are created from strings in the format of: 2013-11-01 00:00:00 +0000.  Each date has the time set to 00:00:00 with the GMT offset of +0000.
I've thought of two possible options:

*

*Use isDaylightSavingTime to check each date and create a new (modified) date offset by 1 hour if it the date is Daylight Savings Time.  I'm worried about the added calculation time as my app calculates the date between a given begin date and an array of other dates.  This array may have up to 2,000 dates in it.  I'm not sure if that's a legit concern or not...

*create a custom timezone that is not affected by DST.  Is this even possible?

A: I can confirm your observations using dates around the 27 October (when British Summer Time started) and setting the time zone to Europe/London. The "n days 24 hours" seems to be a quirk (kind word for a bug, somebody forgot to carry).
Solution 1: Use an NSCalendar set to UTC. UTC has no daylight savings.
Solution 2: As all your times are at midnight and the maximum daylight savings shift is 1 hours then a "day" is between 23 and 25 hours. To allow for this, and handle the quirk at the same time simply:
daysBetween = [activityComponents day] + ([activityComponents hour] >= 23 ? 1 : 0);

Note that this only works because time is the same in the two dates!


text:
Q: Difference between std::cin and scanf() applied to string I am trying to get the first character of a string written to a variable of type char. With std::cin (commented out) it works fine, but with scanf() I get runtime error. It crushes when I enter "LLUUUR". Why is it so? Using MinGW.
#include <cstdio>
#include <string>
#include <iostream>
int main() {
    std::string s;
    scanf("%s", &s);
    //std::cin >> s;
    char c = s[0];
}

A: scanf knows nothing about std::string. If you want to read into the underlying character array you must write scanf("%s", s.data());. But do make sure that the string's underlying buffer is large enough by using std::string::resize(number)!
Generally: don't use scanf with std::string.
Another alternative if you want to use scanf and std::string
int main()
{
    char myText[64];
    scanf("%s", myText);

    std::string newString(myText);
    std::cout << newString << '\n';

    return 0;
}

Construct the string after reading.
Now for the way directly on the string:
int main()
{
    std::string newString;
    newString.resize(100); // Or whatever size
    scanf("%s", newString.data());

    std::cout << newString << '\n';

    return 0;
}

Although this will of course only read until the next space. So if you want to read a whole line, you would be better off with:
std::string s;
std::getline(std::cin, s);


text:
Q: rc.local not running on server boot I have an issue with my rc.local, which isn't running automatically the command line contained inside, on server boot. However, running manually rc.local works fine and starts the script.
Operating System: Ubuntu 20.04.2 LTS
Here is my rc.local
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

sh '/home/[user]/azerothcore-wotlk/reboot.sh'

exit 0

And my reboot.sh
#!/bin/sh

/usr/bin/screen -AmdS world /home/[user]/azerothcore-wotlk/acore.sh run-worldserver
/usr/bin/screen -AmdS auth /home/[user]/azerothcore-wotlk/acore.sh run-authserver

Status of the rc.local service:
$ systemctl status rc-local.service
● rc-local.service - /etc/rc.local Compatibility
     Loaded: loaded (/lib/systemd/system/rc-local.service; enabled-runtime; vendor preset: enabled)
    Drop-In: /usr/lib/systemd/system/rc-local.service.d
             └─debian.conf
     Active: active (exited) since Wed 2021-05-19 22:01:41 IST; 2 days ago
       Docs: man:systemd-rc-local-generator(8)
    Process: 500 ExecStart=/etc/rc.local start (code=exited, status=0/SUCCESS)

Warning: some journal files were not opened due to insufficient permissions.

rc.local and reboot.sh both have permissions:
$ ls -l /etc/rc.local
-rwxr-xr-x 1 root root 718 May 16 01:13 /etc/rc.local
$ ls -l reboot.sh
-rwxrwxr-x 1 [user] [user] 179 May 16 01:16 reboot.sh

By the way rc.local used to work awhile ago, but suddenly stopped for an unknown reason. I'm not an experienced Linux user, so I've read a lot of posts about this problem, and the most often recommendations was to: check if the rc.local has a shebang line (check!); Set proper permissions to rc.local and the script (check!); check the status of the service (check!).
After hitting a rock with rc.local, I decided to give a try to some other methods.
I tried with crontab:
crontab -e

@reboot sh /home/[user]/azerothcore-wotlk/reboot.sh

Not starting on server boot. Starting normally if run manually.
Also tried init.d
sudo su
nano /etc/init.d/reboot

contents:
#!/bin/sh
/home/[user]/azerothcore-wotlk/reboot.sh

Then:
chmod ugo+x /etc/init.d/reboot
update-rc.d reboot defaults

Same result - not starting on boot.
Then tried to create a service:
sudo nano /usr/bin/acore.sh

contents:
#!/bin/sh

screen -AmdS world /home/[user]/azerothcore-wotlk/acore.sh run-worldserver
screen -AmdS auth /home/[user]/azerothcore-wotlk/acore.sh run-authserver

sudo chmod +x /usr/bin/acore.sh

sudo nano /etc/systemd/system/acore.service

contents:
[Unit]
Description=My daemon

[Service]
ExecStart=/usr/bin/acore.sh
Restart=on-failure

[Install]
WantedBy=multi-user.target

$ systemctl start acore.service

==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ===
Authentication is required to start 'acore.service'.
Authenticating as: ,,, ([user])
Password:
==== AUTHENTICATION COMPLETE ===
systemctl enable mydaemon.service

systemctl enable acore.service

Not working either.
At this point I have absolutely no idea what to do. As I mentioned above, I'm not an experienced Linux user, so any help will be appreciated!
Thank you!
Edit: As @terdon suggested, I added the lines
/usr/bin/touch /tmp/rc.has.run

to the beginning of the rc file)
and
/usr/bin/touch /tmp/reboot.has.run

to the beginning of the reboot script
Both files have been created in the /tmp folder after rebooting the server.
Edit2: Thanks to @terdon the problem is solved by adding 'sleep 60' in the beginning of the rc.local.

A: It looks like the problem isn't that the script isn't running, but that it is running too soon, before the system has finished setting everything up, and therefore fails because your machine isn't ready to run it yet. So a simple solution is to add a delay to the script so that it waits a bit before launching.
Edit your reboot.sh script, and add a sleep call:
#!/bin/sh

## wait for 60 seconds
sleep 60

/usr/bin/screen -AmdS world /home/[user]/azerothcore-wotlk/acore.sh run-worldserver
/usr/bin/screen -AmdS auth /home/[user]/azerothcore-wotlk/acore.sh run-authserver

You can experiment with the sleep value to find something that works and doesn't feel slow.


text:
Q: What does this notation mean? $\frac{\partial f}{\partial x}(x+y)=\frac{\partial }{\partial x}f(x+y)$
$$\frac{\partial f}{\partial x}(x+y)=\frac{\partial }{\partial x}f(x+y)$$

I was just wondering what the left-hand side mean. (or how to do the operation based on the notation of the LHS, given a specific function $f$)
In addition, when is such commutation true? Under what conditions?

A: If $f$ is some function, then we may define $f_y : x\mapsto f(x+y)$.  It is basically a shifted version of the function $f$.
Your equality says that (with $D$ the derivation operator):
$$ Df(x+y) = Df_{y}(x), $$
or, if you prefer
$$ (Df)_y = D(f_y). $$
In other words: "shifting" or "translating" a function commutes with taking derivatives. If we denote by $T_y$ the operator $f\mapsto f_y$, then we could write this as
$$T_y\circ D = D\circ T_y $$
In the language of systems one says that derivation is a time-invariant system. In my opinion it's also a good example of how the $\frac{\partial}{\partial x}$  can sometimes obscure things.

This is always true (if the derived function exists), because (intuitively) derivation only depends on a neighbourhood of the function, and not on the ordinate. In other words, if I give you a picture of a function but forget to draw the $y$-axis, you could still sketch the derived function. (This would be different if I asked you to, for instance, draw $xf(x)$.)
For a more rigorous derivation of this property: let $f$ be any (differentiable) function, then we have that
$$ \begin{align*} Df_y(x) &= \lim_{h\to 0}\frac{f_y(x+h)-f_y(h)}{h} \\ &= \lim_{h\to 0} \frac{f(x+h+y)-f(x+y)}{h} \end{align*}$$
and
$$ \begin{align*} (Df)_y(x) &= Df(x+y)\\ &= (Df)(z)|_{z=x+y} \\ &= \lim_{h\to 0}\left.\frac{f(z+h)-f(z)}{h} \right|_{z=x+y} \\ &= \lim_{h\to 0} \frac{f(x+y+h)-f(x+y)}{h} \end{align*} $$


text:
Q: Create new variable or make multiple chained calls? What is the best way to get this attributes, thinking in performance and code quality?
Using chained calls:
    name = this.product.getStock().getItems().get(index).getName();
    id = this.product.getStock().getItems().get(index).getId();

Creating new variable:
    final item = this.product.getStock().getItems().get(index);
    name = item.getName();
    it = item.getId();

I prefer the second way, to let the code cleaner. But I would like to see some opinions about it.
Thank you!

A: Your chained approach isn't so bad (I admit I've done it for short and simple chains) but the question is what happens when one of the items in the middle of this get-chain you're trying to get returns null?
I recently had to debug something similar and it was a pain. I eventually split it up into something like this:
a = incomingObject.getA();
b = a.getB();
c = b.getC();

...well actually the chain I was dealing with was 7 gets deep. And then once that was resolved (tried and caught) I discovered that a different method (not a get, but it was used like one) was throwing a webservice exception. Re-writing it as multiple statements was tedious but much easier to debug when things went wrong.

A: I like niether, personnaly.
If any of them returns a null you get a nullpointer exception on the line...
Now... which one of them did go wrong ?
Now, method chaining can be and is very usefull with some specific usage patterns.  Say for example in a fluent type interface (most mocking framework will do this, at least the ones I`ve seen).
Ideally one should strive to reduce coupling and this pattern does exactly the opposite.
From experience when I find myself having to dig deep in my object structure to do a task it usually is an indicator that my object structure or my business logic is not right.  Perhaps the work could be buried deeper through  some kind of wrapper object / facade /  delegate and just call that instead.  Perhaps your function or method is doing too much and should be split in smaller, more specialized chunks.  Perhaps the object needs to expose properties of the items inside instead of exposing the item as a whole.  It all depends on your architecture and use cases.
That said, software needs to be shipped and that usually means some parts will be more hackish than others, Ideally these should be well isolated bounded and boxed and method chaining like this weather done through successive variable assignement or directly tends to break these boundaries reducing the overall stability.

A: Well I think that the second option you posted is cleaner, and sometimes the compiler might just do it for you in the background as an optimization. Because one pointer jump (or function call) is better that 5. So the code is cleaner and quicker.
So the only question you should ask yourself is: Could it be that one object in the chain changes its result? If the answer is No, just go with the short and nice way. If its Yes, its simply the correctness of the program.
Edit
I was just studying for an exam, and came across the Introduce Explaining Variable refactoring, which reminded me of your question. I think you will find the discussion there interesting. The main points are:

*

*Your second option is the preferred one.

*If Extract Method is applicable, do it instead. And create a general accessor method for the desired objects. (That way you have more readable code, and less copy-paste code)

A: I prefer the second way as well because it shows intent. You are getting the name and it off of a single item you have retrieved.
In the first way, could there exist a possibility (e.g. via another thread) that .get(index) returns a different item between the two calls? If that could happen now, or in some future iteration of the software, the second way not only has the benefit I talk about above, but it may become necessary.


text:
Q: C# simple exception output I am making a program of which needs to output any errors that occur but in a timely fashion, it is a program for password recovery.
How can I change the exception text variable which is probably a string to only the actual exception minus all the unneeded stuff.
 catch(Exception EX)
 {
     Console.ForegroundColor = ConsoleColor.Red;
     Console.WriteLine("AN ERROR OCCURED IN COPYING CHROMEPASSFILE: " + EX);
     Console.ForegroundColor = ConsoleColor.Green;
 }

Output:
AN ERROR OCCURED IN COPYING CHROMEPASSFILE: System.IO.IOException: The file 'C:\Users\Anonymous\Desktop\E_TEST\logindata.' already exists.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)
at System.IO.File.Copy(String sourceFileName, String destFileName)
at Recover_All_Passwords.Program.Main(String[] args) in C:\Users\Anonymous\Documents\Visual Studio 2015\Projects\Recover_All_Passwords\Recover_All_Passwords\Program.cs:line 27

How can I output only that first line and none of those "At(s)"?
Just noticed the tag for exception says, I quote "An exception is a rarely occurring (exceptional!) condition that requires deviation from the program's normal flow."
Edit
Yes, the stacktrace is very helpful however I had only require the error message because the user will not be interested in anything but what had actually failed.

A: Rather than using EX, use the Message property on the Exception.
So your code becomes:
 Console.WriteLine("AN ERROR OCCURED IN COPYING CHROMEPASSFILE: " + EX.Message);

For future reference, the "at(s)" are the StackTrace and are extremely useful for determining where your application is breaking..


text:
Q: Tomcat Request postData null My web app works fine in local tomcat server test. But when deploy to a test environment, the app not work right.
So I remote debug the app, just found postData of tomcat request is null, while it does have data in local debug.
That's very weird. I got nothing clue with google.

A: I finally found the answer by adding tomcat jar in my runtime and tracing the code.
It was because the test environment tomcat had a wrong configuration.
It sets maxPostSize=0 of connector in conf/server.xml, so it causes FailReason.POST_TOO_LARGE error and would't parse the post data and get a null postData.


text:
Q: Can I use maybe on multiple inputs in Haskell? Suppose I wanted to test that both my inputs are positive. Can I do something like this?
test :: Float -> Float -> Maybe Float Float
test a b
    | a>0 && b>0 = a b
    | otherwise = Nothing

I thought I would have this function test that the inputs for the next function were positive. So two floats go in and two come out.
What's an alternative to this?

A: The code is morally correct but lacking in a few places. The conditional stuff is actually fine, the part that's tripping you up is

*

*Indicating that you want a tuple

*Constructing a Maybe value

First of all, the type Maybe Float Float is ill-formed, Maybe takes one type argument not two, I think you mean Maybe (Float, Float) which should be read as "A Maybe of a pair of floats". Then to construct a single expression of type (Float, Float) we use (-, -). So instead of a b which really means "a applied as a function to b" we'd have (a, b), a pair of a and b. Last but not least, we want to construct a Maybe in the end so we need to explicitly wrap the whole tuple in the Just constructor leaving us with Just (a, b).
test :: Float -> Float -> Maybe (Float, Float)
test a b
    | a>0 && b>0 = Just (a, b)
    | otherwise = Nothing


text:
Q: How do I do a Crosstab in Vertica What is the Vertica equivalent of crosstab or pivot table found in PostgreSQL and other RDBMS's?

A: Vertica doesn't currently (release 3.5.9 for future reference) have that capability. I talked with a co-worker and his suggestion was to play around with "cross join."
The other option would be to distill your results as far as you could and then run a process outside of the database (perl, Java, C#, etc) that manipulated the data.
Vertica is open to feature requests however.
I don't believe this will be available in the upcoming 4.0 release either.

A: Vertica can do a cross-tab using the basic sql-92 syntax:
select
   DIM1
   ,DIM2
   ,DIM3
   ,SUM(MEASURE1)
   ,SUM(MEASURE2)
   ,SUM(MEASURE3)
from
 (select
   DIM1
   ,DIM2
   ,DIM3
   ,MAX(CASE WHEN MEASURE = 'MEASURE1' then MEASURE1_VALUE else null end) MEASURE1
   ,MAX(CASE WHEN MEASURE = 'MEASURE2' then MEASURE2_VALUE else null end) MEASURE2
   ,MAX(CASE WHEN MEASURE = 'MEASURE3' then MEASURE3_VALUE else null end) MEASURE3
from SOME_TABLE
group by DIM1, DIM2, DIM3
) as a
group by DIM1, DIM2, DIM3


text:
Q: Unable to load XML on Internet Explorer with jQuery (locally) I have trouble loading an xml file stored on my local network... (you could say... local HDD... it doesn't matter I guess).
I have the piece of code that you find everywhere online:
$.ajax({
   url: "data\raportfile.xml",
   dataType: ($.browser.msie) ? "text" : "xml",
   error: function(data){
      alert('ma-sa de treaba');
},
   success: function(data){
     var xml;
     if (typeof data == "string") {
       xml = new ActiveXObject("Microsoft.XMLDOM");
       xml.async = false;
       xml.loadXML(data);
     } else {
       xml = data;
     }
     // Returned data available in object "xml"
   }
 });

But I don't know why... I get the error message... that this stuff doesn't work...
Are there any ways besides this one? Is there something I do wrong here? Thanks a lot!

A: The path data\raportfile.xml looks like a filesystem path. Your file needs to be accessible over http.
Put the file somewhere in the site root, and address it using forward slashes ie /path/to/file.xml