how to rescan m4 data for recursive macro inplace substitution

Question: I have this very simple code.
define(`S',`some')
define(`T',`thing')
define(`D',`doing')
define(`something',`st_todo')
define(`st_tododoing',`done!')
S`'T
OR
S()T()

the actual end result is
something
OR
something

but expected recursive substitution result as
st_todo

how I can rescan the code to the input again ?
maybe the "indir", But its A crooked nasty solution:
indir(S()`'T()`'D())

the result is:
--NOTHING--

maybe the so called command "divert", can make the output, recycled to input ?
of course the reviews says it is "inplace macro substitution",
BUT the result are different.
of course we can use "C" language primitive macro solution. EG:
define(`concat',`$1$2$2$4$5')

BUT this "concat" "solution", will increase the code NESTING complexity, in a large code reconstruction. EG:
concat(concat(S1,T1),concat(S2,T2,more1,more2,...))

WHAT if we have "concat" of 10 words OR more OR with conditionals "ifelse" ?.
M4 concept is beyond the old "C" preprocessor!
the real solution must come from the macro "inside core system"
any idea ?
Answer: M4 does rescan. However, the empty string `' ends the preceding token, and thus prevents some and thing from being recognised as a single token.
Instead, concatenate the macro expansions using another macro:
define(`concat',`$1$2')
define(`S',`some')
define(`T',`thing')
define(`something',`st_todo')
concat(S,T)

$ m4<<"EOF"
> define(`concat',`$1$2')dnl
> define(`S',`some')dnl
> define(`T',`thing')dnl
> define(`something',`st_todo')dnl
> concat(S,T)
> EOF
st_todo

Comment: the result of S()T  => someT .
Comment: @contenta: Oops. OK, a more complicated solution.
Comment: Which triggers another question: why does `S()T` not expand the T?  After m4 parses the final `)`, that macro expansion is complete.  It should read `T` and expand it.
Comment: THIS IS "C" primitive macro solution! this "concat" "solution", make it very complex, in a large code reconstruction. M4 concept is beyond "C" preprocessor!!!. WHAT if  we have "concat" of 10  words ?. the real solution must be in the macro "core system".
Comment: @contenta I don't understand your comment.  But note that rather than the `concat` that rici uses, you could use the builtin `indir` and write `indir(S[]T)`.  (I changequoted to [] to avoid SO comment markup).
Comment: @WilliamPursell: After `S()` expands to `some`, the scan is reset to where the `S` was encountered, so the input is now `someT`. That's a single token, and it has no definition. With the original `S[]T`, after the substitution of `S` the input was `some[]T`; after resetting the scan, m4 sees the token `some`, an empty string, and the token `T`. It expands `T` to `thing` and then resets the scan to where the `T` started.
Comment: @contenta: if you read through the [Gnu m4 manual](https://www.gnu.org/software/m4/manual/m4-1.4.15/html_node/index.html) you'll see that a large number of the documented macros are not built-in.this includes `join`, which is a general form of my little `concat`, allowing a delimiter and any number of arguments. The fact that it is possible to write such a macro shows the difference with the C preprocessor: m4 has recursion, conditionals and loops. But it doesn't free you from writing (or finding) utility macros.
Comment: Somewhere I read that there is some PRECEDENCE. the quote sequence (`'), are processed AFTER expansions layer, and not BEFOR.  even in "C" quotes are processed LAST.


Interpret effect of covariates in linear model with log-transformed response variable

Question: I am having difficulty interpreting the effects of the covariates of a linear model with log-transformed response for two specific time points.
This is the model: $log(Y_t) = \beta_0 + \beta_1 * X_{1t} + \beta_2 * X_{2t}$
Let's say I have $Y_t = 100$ and $Y_{t+1} = 110$. Now I want to explain this increase in $Y$ from $t$ to $t+1$ in terms of the explanatory variables. Is it possible to split this $10$ units increase in $Y$ between $X_1$ and $X_2$, e.g. $Y$ increased by $7$ units due to $X_1$ and by $3$ units due to $X_2$?
How could I mathematically split the increase in $Y$ between the covariates for two specific time points?
Comment: No you can't. Y could increase 10 units due to a change in X1 irrespective of X2, and Y could increase 10 units due to a change in X2 irrespective of X1.
Comment: Would you please post the data (or a link to the data) before transform?
Answer: This is known as an Accelerated Failure Time model.
https://en.wikipedia.org/wiki/Accelerated_failure_time_model
From wiki:

The interpretation of ${\displaystyle \theta }$   in accelerated failure time models is straightforward: ${\displaystyle \theta =2}$ means that everything in the relevant life history of an individual happens twice as fast. For example, if the model concerns the development of a tumor, it means that all of the pre-stages progress twice as fast as for the unexposed individual, implying that the expected time until a clinical disease is 0.5 of the baseline time. However, this does not mean that the hazard function ${\displaystyle \lambda (t|\theta )}$ is always twice as high - that would be the proportional hazards model.

A textbook reference on this sort of models is

Kalbfleisch & Prentice (2002). The Statistical Analysis of Failure Time Data (2nd ed.). Hoboken, NJ: Wiley Series in Probability and Statistics.
Comment: The response is not a time-to-event. Even if it was, a time-to-event model does not have the ability to attribute hazard differences to two or more covariates.


How do I embed a view inside a node?

Question: In Drupal 6 a view can be embedded into a node as follows:
$viewName = 'LatestNews';
print views_embed_view($viewName);

This does not work for drupal 7.  What is the function to embed views in drupal 7?
Comment: According to [this documentation link](http://drupalcontrib.org/api/drupal/contributions--views--views.module/function/views_embed_view/7) of views module this function is equally available on Drupal 6 and 7. Try with second param as $display_id of your view.
Answer: In Drupal 7 you can use this code.

For a view page
print views_embed_view('name_of_view','page_1', $node->nid);

For a view block
print views_embed_view('faculty_core','block_1', $node->nid);

Comment: https://api.drupal.org/api/views/views.module/function/views_embed_view/7.x-3.x
Answer: The EVA module can also attach views to nodes.
Answer: To display a view in a node template, you use the following code.
// Load the view.
$view = views_get_view('machine_name_of_view');
// Set the active display.
$view->set_display('your_view_display_name');
// Set any needed argument.
$view->set_arguments(array(arg(0), arg(1)));
// Execute the view.
$view->execute();
// Render the view.
print $view->render();

Comment: You should always call $view->pre_execute(); before $view->execute();
Comment: @Teegan - Didn't know that, using only execute seems to work, but I will look into using `pre_execute()` prior to `execute()`.
Answer: Why not:
print views_embed_view($view_machine_name, $view_display_name, $arg1, $arg2);

where $arg, $arg2, etc are optional.
Or use Viewfield module to embed a view as a field.
Comment: VIEWFIELD!!!! OMG!!! I have looked for days for this functionality, trying many modules, this saves me! :D thanks!
Comment: @DrCord, also see Eva and views_field_view modules, they're pretty much the same thing.
Comment: I couldn't get EVA to do what I wanted.
Answer: One solution is to use Panelizer to override the content of the respective node.
Lets say for example you have a handfull of one-off pages that need a view attached.
1) You could use the Page content type or maybe create a new content type that will specifically be panelized.
2) Enable Panelizer for that content type, make sure to set it up to "Allow per-record display choice" that way you can setup multiple panelizer displays that will be tailored to each one off page.  (each panelizer display can have it's own set of views attached)
3) From here you simply create a view (I like to use Content Panes for this) and add it to the Panelizer content display of choice.
This allows you to re-use a single content type that doesn't really need it's own set of fields, but might potentially be used for either referencing other entities (as a field) or referencing views.
Throw in the Paragraphs module and you have a Swiss Army Knife content type.  Speaking of, that would make a perfect name for the custom content type used for this purpose... Hmm....
Answer: Let's just mention that first parameter is view name, second display name and after that you can pass contextual filter parameters.
So that "$node-nid", the third parameter depends on you view...what it expects for first contextual filter - id doesn't have to be node id. Of course, you are not limited to one parameter - pass as many as you have in view...or pass none if your view doesn't have contextual filters.
Answer: A very configurable Drupal 7 and 8 module is views_field_formatter which allows you to embed a view as a fields formatter

How do I embed a view inside a node?


Feature selection and training on the same sample

Question: Is feature selection and training on the same sample a bad idea?
I want to emphasize that I am not going to use test set for feature selection.
If I use the whole train set for feature selection and then for training the model then the training sample is larger.
Any drawbacks of such approach?
Comment: Can you edit your post to comment a bit more on what exactly you are doing to chose features?  You don't mention cross validation, so I would conclude that you are using the training error rate to select features.  In this case, any time your model complexity increases, the training error will decrease by mathematical necessity (at least for the objective function of the optimization), so there are real and unavoidable issues with that approach.
Answer: I think you can try to see these questions:
Can I perform an exhaustive search with cross-validation for feature selection?
Feature selection and cross-validation
It is talked about CV there, but it mostly same idea, when you reuse the data from train set for model fitting after feature selection algorithm it's basically like you train first simple algorithm with this data and then using it's results (via zeroing some non-random variables) again fit other model.
In real life it often can be not so criminal because with feature selection is not so easy to overfit unless you don't have model with millions noisy features.


How to plot China map with South China Sea in base R

Question: I want to get a China map with South China Sea frame as the attach.
The China boundary line and administrative shapefiles can be download from
https://github.com/jimrpy/jimrpy.github.io/blob/master/epidemiology/Archive.zip.
My code is as follows, I don't know how to set the "usr", how to modify the code?
library(maps)
library(rgdal)

china_blank <- readOGR(dsn = "~/China/",
                      layer = "China_Province")
china_line <- readOGR(dsn = "~/China/",
                      layer = "China_Boundary_Nineline")

china_blank <- spTransform(china_blank, CRS("+init=epsg:4326"))
china_line <- spTransform(china_line, CRS("+init=epsg:4326"))

map(china_blank)
map.axes()
par(usr = c(73, 136, 0, 54))
rect(xleft = 107, ybottom = 0, xright = 122, ytop = 21, col = "white")
map(china_line, xlim = c(108, 122), ylim = c(0, 21), add =T)

Comment: What exactly do you want that's different from this?
Comment: @aldo_tapia could you give some suggestion about 'usr'
Answer: The usr graphics parameter defines the area of a system of coordinates that you want plotted, not the area of the canvas where you want the plot. That area is controlled by the plt graphics parameter.
For details, see the help(par):

(...)
'plt' A vector of the form 'c(x1, x2, y1, y2)' giving the
      coordinates of the plot region as fractions of the current
      figure region.
(...)
'usr' A vector of the form 'c(x1, x2, y1, y2)' giving the extremes
      of the user coordinates of the plotting region.  When a
      logarithmic scale is in use (i.e., 'par("xlog")' is true, see
      below), then the x-limits will be '10 ^ par("usr")[1:2]'.
      Similarly for the y-axis.
(...)

You can see the current set of parameters by calling par() (or, if you only want to see specific parameters, par(c("plt","usr")).
In your case, you seem to want to plot the range given by your rectangle (xleft = 107, ybottom = 0, xright = 122, ytop = 21) in the inset, so you will want to define usr using these values. With regard to the area of the canvas where you want the plot you may need to experiment a bit. c(0.76, 0.935, 0.195, 0.45) works nicely for me, but I am guessing that this may depend on various settings and may be different for you.
In any case, try something like this:
par(plt = c(0.76, 0.935, 0.195, 0.45))
par(usr = c(107, 122, 0, 21))


jQuery live html editor not working?

Question: I was trying to make a simple html editor, but it is not working.
It should show all of the HTML and CSS inputted in the iframe every time you press a key, but it isn't
This is my code

    <textarea id="html"></textarea>
    <textarea id="css"></textarea>

Comment: Maybe have a look at `$.parseHTML()` http://api.jquery.com/jquery.parsehtml/ ... you can do stuff like `$.parseHTML($(this).val())` and then work with it in terms of DOM
Comment: This worked in this guy's video https://www.youtube.com/watch?v=MhODHoaats0
Answer: AFAIK, you can't see what's inside an iframe. Iframe contents can't interact with outer page's contents. //Edit: previous applies when iframe is from different domain (thanks for the video.)
Your script should be declared AFTER the DOM it wants to parse. otherwise you should use $.ready() to ensure that the page is completely loaded when you execute your function. Yu are defining the function that tries to find DOM elements before those elements actually exist.
This works:

Comment: Thanks! please note that it's allowed "...if the iframe is on the same domain..."

jQuery live html editor not working?


Why is $T(v_k) \in \textrm{Span}(u_1, ... , u_n,v_1, ... , v_k)$?

Question: I found a proof on Math Stackexchange that a matrix can be upper triangularized, but I was confused by the proof they gave.  I copy pasted it:
**
I know of a theorem from Axler's Linear Algebra Done Right which says that if $T$ is a linear operator on a complex finite dimensional vector space $V$, then there exists a basis $B$ for $V$ such that the matrix of $T$ with respect to the basis $B$ is upper triangular.
The proof of this theorem is by induction on the dimension of $V$. For dim $V = 1$ the result clearly holds, so suppose that the result holds for vector spaces of dimension less than $V$. Let $\lambda$ be an eigenvalue of $T$, which we know exists for $V$ is a complex vector space.
Consider $U = $ Im $(T - \lambda I)$. It is not hard to show that Im $(T - \lambda I)$ is an invariant subspace under $T$ of dimension less than $V$.
So by the induction hypothesis, $T|_U$ is an upper triangular matrix. So let $u_1 \ldots u_n$ be a basis for $U$. Extending this to a basis $u_1 \ldots u_n, v_1 \ldots v_m$ of $V$, the proof is complete by noting that for each $k$ such that $1 \leq k \leq m$, $T(v_k) \in $ span $\{u_1 \ldots u_n, v_1 \ldots v_k\}$.
**
Why that last step?  Is this really a correct proof?
Comment: Are you asking why is $T(v_k)$ in the span? Isn't that a basis of the space?
Comment: Yes, but why do $v_{k+1}, ... , v_m$ not show up?
Answer: Yes, this is a correct proof but it omits a few details that are included in the proof in the book. In the book, this is Theorem 5. 13 and it is preceded by Proposition 5. 12:

Suppose $T \in \mathcal L(V)$ and $(v_1, \dots, v_n)$ is a basis of
  $V$. Then the following are equivalent:
(a) the matrix of $T$ with respect to $(v_1, \dots, v_n)$ is upper
  triangular
(b) $Tv_k\in \text{span} (v_1, \dots, v_n)$ for each $k = 1, \dots, n$
(c) $\text{span} (v_1, \dots, v_n)$ is invariant under $T$ for each $k
 =1, \dots, n$

This proposition is used in the proof of theorem 5. 13:
First show that $T u_i \in \text{span} (u_1, \dots, u_n)$ then show that $T v_i \in \text{span} (u_1, \dots, u_n, v_1, \dots, v_m)$.
Together these mean that $Tx \in \text{span} (u_1, \dots, u_n, v_1, \dots, v_m)$ for all $x \in (u_1, \dots, u_n, v_1, \dots, v_m)$ hence $T$ is upper triangular.


Right or wrong syncope

Question:
Is the fourth note syncopated or not?
Comment: @NeilMeyer - looks o.k. to me. The tie is across the middle of the bar, which then divides exactly in two.
Comment: It's quite acceptable, and I for one would rather read it as such - it shows  syncopation better this way. I know the rule always used to be 'make sure a 4/4 bar can be seen to be split in two equal parts', but sadly this seems to be ignored in a lot of modern printed sheet music.
Comment: No, this is correctly notated, although the use of the C clef is idiosyncratic, to say the least (I'd prefer the usual G and F clefs, and more space between the staves). Whether the 4th crochet is perceived as a syncope will depend on what precedes and follows this passage. If this single line is an opening, then the meter will be _ambiguous_ until the real meter kicks in and forces a perception of syncopation in retrospect. If this passage comes after a passage of clear 4/4, and passes back to clear 4/4 on a strong beat, then the crochet will be perceived directly as a syncope.
Comment: The use of tied notes is incorrect in this passage.
Comment: No it should be a dotted crotchet. There is no need to use two tied notes there when a dotted noted would suffice. It looks like it does it wrong again at the end as well.
Comment: @Patrx2 Seems like a comment worthy of being an answer to me.
Answer: The example, as it stands, is ambiguous. The way this passage will be perceived is going to be heavily dependent on what (if anything) precedes it, and what follows it.
Pace Sandra-Émilie, syncopation is a bit broader and more complex than "tones entering where there is no pulse." The Wikipedia page gives some idea of just how broad the definition can be, but, if we were to put it simply, we could say that syncopation is the de-emphasis of, or elision over, the strong beats by a variety of means. Note that this means that there is an implicit or explicit background of strong beats to work against.
Suspension as Sandra-Émilie uses the term is a bit iffy: for the usual definition of suspension, a change of harmony is implied over which the note is suspended. It is hard to say that this is the case for this example.
I say that this passage is ambiguous taken out of context because a) it is a single line, so there is no accompaniment to measure the melody against, and b)
we have no way of knowing what surrounds the passage. If the strong beats were clearly marked in bars leading up to this passage, then yes, this may well be the start of syncopation, because the melody will be perceived as pulling against the implicit background meter.
If this is the opening of the piece, however, then the meter of the melody is ambiguous until some event (perhaps the entrance of a regular accompaniment on a strong beat, perhaps that the melody falls back into the base meter on a strong beat) serves to establish clearly what the meter is. At that point, the listener will be able make sense of the melody's rhythm after the fact. The listener may perceive polymeter (if the unaccompanied melody tends to group its events into either a consistent cross-meter, frequently 3 in a situation like this, or an apparently shifting meter) or syncopation (if the perception of beat has just been shifted onto off-beats), so what we have starting here with the tie depends on what follows.
So, to summarise, that tied crochet's function may be metrically ambiguous, it may be the start of syncopation, it may be the start of an implied polymeter: we can't tell without more of the preceding music and more of what follows these bars. Determining musical function relies heavily on context. Ambiguity itself is one of the composer's tools of the trade: there are going to be times when we want you scratching your head about a passage until such time as we bring about an "Aha!" moment and show how everything fits into the metrical framework.
As an aside, I'd strongly suggest against emulating the use of the C clef here. For one, the regular clefs used in the usual spots allow for noticeable changes of clef when the hands move across the range of the keyboard. For another, when using the regular clefs, a wider space is possible between the staves. There are times when multiple ledger line above the bass clef or below the treble clef are a more legible notation than cross-stave notes or a momentary change of clef, especially when working with multiple voices in each stave (i.e., contrapuntal music).
Answer: According to G. Cooper and L.B. Meyer in The Rhythmic Structure of Music, a syncopation is "a tone which enters where there is no pulse" and which is followed, on the next beat, by a rest or a suppressed tone (a tied note). Therefore, this is not a syncopation, according to these authors.
This is what is called "suspension" because it starts on a weak beat and it continues on the next beat.
Comment: I'm sorry, but I don't agree with this assessment, for reasons outlined in Patrx2's answer.

Right or wrong syncope


IncompatibleClassChangeError on Android Things

Question: After updating to the latest Android Things preview, my app is crashing when
setting a callback on by button GPIO. I have the following button callback defined:
private class ButtonCallback extends GpioCallback {
    @Override
    public boolean onGpioEdge(Gpio gpio) {
        boolean isPressed = false;
        try {
            isPressed = gpio.getValue();
        } catch (IOException e) {
            Log.w(TAG, "Error", e);
        }

        if (isPressed) {
            ...
        }
        return true;
    }
}

I am registering it with the GPIO in the application as follows:
Gpio button = ...;
try {
    button.registerGpioCallback(new ButtonCallback());
} catch (IOException e) {
    Log.w(TAG, "Error configuring GPIO pins", e);
}

When I run my app, I get an IncompatibleClassChangeError and the app crashes:
java.lang.IncompatibleClassChangeError: Superclass com.google.android.things.pio.GpioCallback of com.google.android.things.example.MainActivity$ButtonCallback is an interface (...)

This code was working before, why has this started happening after the update?
Answer: Starting in Preview 7, many of the Peripheral I/O interfaces were converted from
abstract classes to interfaces. This was done to better facilitate testability
in apps, as interfaces are easier to mock.
Be sure to update your app to use the Preview 7 SDK:
dependencies {
    compileOnly 'com.google.android.things:androidthings:0.7-devpreview'
}

Then modify your callback to implement the interface instead:
private class ButtonCallback implements GpioCallback {
    @Override
    public boolean onGpioEdge(Gpio gpio) {
        boolean isPressed = false;
        try {
            isPressed = gpio.getValue();
        } catch (IOException e) {
            Log.w(TAG, "Error", e);
        }

        if (isPressed) {
            ...
        }
        return true;
    }
}

Review the Android Things API reference
to verify if any of the other APIs you are calling have changed.


How do many keyboard players sound different in each song?

Question: Something I find truly intriguing, is when a keyboard player sounds completely different in each song they play. The band ∆ (Alt-J) is a good example of this.
I'm a one-man recording band myself, and looking to make my music more interesting by trying this as well. Which is why I am wondering how people usually do this. Do they simply use the Midi signal from their keyboard and feed it through a laptop? Do they use keyboards that have the necessary software and hardware (sliders, buttons, etc) to alter their sound to their liking? Or do the keyboards simply have a wide array of pre-defined sounds that can be used?
I'll take the freedom to anticipate the "all of those things you mentioned" answer, by also asking which of these options would be easiest to start out with for somebody who has never played keyboards or synthesizers. I do play the piano well enough to make the switch technically, but I'm absolutely uneducated about how to get the sound I'd want.
Comment: This is sort of like asking how to make spiced chicken taste different.  Yes, different spices are different.  I don't think it's much of a question.
Comment: Updated the headline to reflect the actual question you are asking. I agree with Matthew that this is not really a good question here, as there are an infinite number of ways to do this, but the edit may at least help stop people downvoting just for the headline.
Comment: By the way, I have nothing against downvotes, but it would be nice if you could leave a comment when downvoting, so that I'll know how to edit and improve this question
Answer: Playing for recording is not necessarily the same as playing live, sound-wise. In a studio situation, you can mess about with all sorts of sounds and the mixes you can achieve with them.
Live, you could just use a piano sound - if you only had a piano, then that's what would happen. However, keyboards now have a plethora of different sounds, so players will tend to use them.When I'm out on keys, I'll use maybe half a dozen main sounds : piano, electric piano, vibes, several (Hammond) organ sounds, strings and a couple of 'synth' sounds. Let alone the occasional horn sound - trumpet, sax, flute.
Listen carefully to lots of recordings and you'll hear these coming and going throughout the song. So, given the opportunity to emulate this sort of variety, we do.
Often, I'll listen to the sound palette of what's going on in a song, and try to fill it with the 'missing bits'.Obviously, it's not clever to fill up all the spaces, but complementing the existing sound is easier when one has a big choice of noises to use. So we do.
Answer: First of all, yes you anticipated correctly: all those things you mentioned are used to control the program/patch/timbre of the instrument. Hardware synths, software synths, DAWs, etc, have a way to program, save, and change their settings. Once saved, you can recall these settings at will. This set of settings is called a patch. Some instruments will also have a bank of pre-defined patches. You just tell your platform "I want this patch", and load it, then play it.
Non-digital instruments without some kind of setting recall feature will need their patches to be set manually between songs and/or as needed. I've seen this being done in a live setting, with modular synths.
I think that as a beginner the easiest option is to use a DAW and a software synth. In particular, a non-linear DAW tailored for live performance specifically, like Ableton Live or Bitwig Studio.
With this setup, you can switch between patches using the tools provided by your software synth, or you can set one patch per MIDI track, and just arm the MIDI track that you want to play (which means that you can move between patches with just one click).
All these can be achieved with any DAW, but Ableton Live offers some fun tools that will help you go crazy patch-wise, like Instrument Rack (where you can group many synths, audio effects, and MIDI effects together into one single patch) and clip view (non-linear playback of MIDI and audio tracks).
Answer: The existing answers are very good, and I'd like to add that in some genres, the role of the keyboardist is not only to compose and/or play the keyboard part, but also to create the synth sounds (patches) that actually define the  band's sound. This is true not only for synth pop, but often in rock music as well (Bon Jovi, Toto etc.) and other genres.
Sometimes the keyboardist is not that much a synth geek, and others help them in the synth programming; in Toto there is one keyboardist for the piano parts, and another for all the synths and organs.
If you get a relatively better (=more expensive) hardware keyboard, it will probably have thousands of factory patches, and hopefully an easy way to start editing them.
Answer: In your question you talk about differing sounds of bands like alt-j, so I believe we need to talk about keyboards and synths. A common misconception is that keyboards are the same thing as a synth. Keyboards are often shipped out with permanent patches and that's it, some will have recordings of a sound that are played back when you press the key.
A synth is an actual sound generator. It has oscillators that generate waves that are then mixed and put through FX and other tools to create an enormous palate of sounds (a bit like mixing paints for new colours). A good synth is specifically designed to shape the sound quickly and easily with lots of relevant knobs to access the parameters.
A synth is a sound creating tool that you can program for the perfect sound. Creating a perfect sound is an art in itself and can take many hours, weeks even for each patch. Music with defining synth sounds will usually have been designed by someone with a lot of thought, care and attention.
To get the sound you want, you need to go through some tutorials. Google "Synth ADSR tutorial" or something similar to get you started. Be careful with software synths as a lot can be weak sounding but there are some good ones. What you need to look for is something that allows you to EDIT the sound dramatically and not be confined to the parameters of a patch. (you will probably need a midi keyboard for this but some let you use your computer keyboard)
Next up from software is a hardware synth. Depending on your style, you need to pick the right synth for your sound as there are substantial differences between makes and models.


Deixar todos LI com a altura do maior usando CSS

Question: Tenho alguns elementos
 que oriento para ficar inline-block. Porém, como o conteudo de cada
 é diferente, eles acabam ficando com ALTURA diferente. Tipo assim:

Porém, o correto é que o
 com menos conteúdo pegue a mesma altura do
 maior, e ficar alinhado, tipo assim:

Como resolver isso?
Comment: coloque se código css e html
Comment: CSS do LI: width: 200px; position: relative; height: 100%; border: 1px solid #ccc; padding: 5px; text-align: center; display: inline-block;
Comment: Até onde eu sei `height: 100%` só funciona se os elementos superiores tiverem altura definida.
Comment: coloca o seu código para podermos ajudar
Comment: De todas as linhas apenas com CSS não sei se é possível, mas deixar do mesmo tamanho por linha você pode conseguir utilizando `flex`.
Answer: Deixar TODOS os blocos do mesmo tamanho utilizando apenas CSS não sei se é possível (desconheço) já que cada linha passa a se tornar independente, mas cada elemento de uma linha tem uma certa ligação e podem ser usadas como parâmetro para manter todos os outros (da mesma linha) com o mesmo tamanho.
A forma mais fácil de conseguir esse resultado é utilizando o Flex:

ul{
  list-style: none;
  padding: 0;margin: 0;
  display: flex;
  flex-wrap: wrap;
}

li{
  width: 25%;
  border: 5px solid black;
  margin: 5px;
  padding: 3px;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi rerum doloremque laborum?

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et quasi corporis sed fugit quibusdam, possimus ipsam animi ab molestias. Eos qui id sint mollitia amet officiis, commodi natus officia libero.

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

o display: flex por padrão já deixará todos os elementos com o mesmo tamanho, mas você perde o controle sobre sua largura ele tentará deixar tudo na mesma linha, desrespeitando a largura definida ou os limites da página ou elemento pai, que pode ser resolvido utilizando o flex-wrap, que permite quebrar a linha assim que os elementos ultrapassem a tela.
Fica aí uma alternativa, porém não resolve 100%.
Answer: Você pode definir a propriedade min-height um valor de acordo com o conteúdo. Ex.: se sua li maior possui 200px, defina:
   li {
       min-height: 200px;
    }

Comment: Elementos com muito conteúdo podem passar de 200px de altura, enquanto elementos com pouco conteúdo ficariam com exato 200px. Isso só resolveria o problema se a altura definida é, com certeza, maior que a altura do maior elemento e isso não há como garantir.
Comment: O valor de 200px foi só um exemplo. Se é pra todos os elemento ficarem iguais, de qualquer jeito elementos com pouco conteúdo ficaria com espaço vazio. Acredito que, mesmo com conteúdo dinâmico, há um limite para o elemento, caso contrário, não ficaria bom visualmente.
Comment: Mas se todos os elementos possuírem pouco conteúdo, tambẽm não ficará legal, pois todos terão o espaço em branco.
Comment: Mas é isso que o usuário quer, ele quer que o tamanho das  fiquem iguais.
Comment: Quer que fiquem da mesma altura que a maior, mas se nenhuma ultrapassar os 200px, todas ficarão com 200px, ou seja, da mesma altura, mas sobrando um espaço em branco na página.
Answer: Você pode utilizar um javascript para isso
Seleciona o elemento de maior alutura e retorna o valor
function getMaiorTamanho(element) {
    var maiorTamanho = 0;
    $(element).each(function(){
        var height = $(this).css('min-height');
        height = parseFloat(height.replace('px',''));
        if(maiorTamanho<height)
        {
            maiorTamanho = height;
        }
    });
    return maiorTamanho
}

Como usar
$('.card-footer p').each(function(){
      $(this).css('min-height',getMaiorTamanho('.card-footer p'));
});

Espero que ajude


não importar linhas em branco - php

Question: estou com esse código, mas deve ter algum erro. Quando tento abrir o arquivo o navegador não dá resposta.
 $lines = file($_FILES['arquivo']['tmp_name'],FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
 $fp = fopen($_FILES['arquivo']['tmp_name'], 'w');
 fwrite($fp, implode(PHP_EOL, $lines));
 var_dump($lines);

        while(!feof($lines)) {
            $linhas = fgets($lines);
            $dados = explode(";", $linhas);
            $conteudo = array();

            $conteudo[] = [
                'funcionario_cargo' => $dados[0],
                'funcionario_matricula' => $dados[1],
                'funcionario_nome' => $dados[2],
                'funcionario_title' => Check::Name($dados[2]),
                'funcionario_cpf' => $dados[3],
                'funcionario_data_nascimento' => $dados[4],
                'funcionario_portaria' => $dados[5],
                'funcionario_data_beneficio' => $dados[6],
                'funcionario_data_beneficio_publicacao' => $dados[7],
                'funcionario_situacao' => $dados[8],
                'funcionario_regra' => $dados[9],
                'funcionario_regramunicipal' => $dados[10],
                'funcionario_valor' => $dados[11],
                'funcionario_reajuste' => $dados[12],
                'funcionario_processo' => $dados[13],
                'funcionario_data_falecimento' => $dados[14],
                'funcionario_data_termino_pensao' => $dados[15],
                'funcionario_views' => 0,
                'funcionario_status' => 1,
                'funcionario_date' => date('Y-m-d H:i:s'),
                'funcionario_author' => 1,
            ];

            $Create->ExeCreateMulti(DB_FUNCIONARIO, $conteudo);
            $jSON['content'] =  "Arquivo Importado com Sucesso!";

        }

Answer: Adiciona esta condição logo asseguir de $linhas = fgets($lines);, com esta condição irá ignorar as linhas em branco.
Escolhe uma das duas condições ambas resultam, na minha opinião prefiro a primeira.
if ($linha[0] == "\n") continue;

// ou esta

if (trim($linha[0]) == '') continue;

Comment: Depois de:
`dados = explode(";", $linhas);`

fiz assim:

`if (!$linhas == ""):`
Comment: le a minha solução, resultou assim como fizeste ?
Comment: 13dev, não consegui resultado favorável com a solução que apresentou.

Fiz assim e deu certo. Inseri depois dessa linha: `$dados = explode(";", $linhas);`
`if ($linhas != "\n" && $linhas != ""):`
Comment: apenas insere isto: `if ($linha[0] == "\n") continue;`

não importar linhas em branco - php


Typescript: Call static method inside the class (Angular HttpInterceptor)

Question: I'm currently working on an http interceptor that worked well until yesterday.
It defines static methods and one of them does not want to be recognized.
The console says:

my.component.ts:162 Error in PUT Request TypeError: HttpInterceptorService_1.httpInterceptorService.createHttpErrorMessage is not a function

at TapSubscriber._tapNext (http-interceptor.service.ts:113)
at TapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/tap.js.TapSubscriber._next (tap.js:45)
at TapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
at TakeSubscriber.push../node_modules/rxjs/_esm5/internal/operators/take.js.TakeSubscriber._next (take.js:40)
at TakeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
at Notification.push../node_modules/rxjs/_esm5/internal/Notification.js.Notification.observe (Notification.js:15)
at AsyncAction.push../node_modules/rxjs/_esm5/internal/operators/delay.js.DelaySubscriber.dispatch [as work] (delay.js:42)
at AsyncAction.push../node_modules/rxjs/_esm5/internal/scheduler/AsyncAction.js.AsyncAction._execute (AsyncAction.js:63)
at AsyncAction.push../node_modules/rxjs/_esm5/internal/scheduler/AsyncAction.js.AsyncAction.execute (AsyncAction.js:51)
at AsyncScheduler.push../node_modules/rxjs/_esm5/internal/scheduler/AsyncScheduler.js.AsyncScheduler.flush (AsyncScheduler.js:43)

My interceptor looks like this (I have reduced it to the parts that are interesting for the bug):
// My imports

@Injectable({
  providedIn: 'root'
})
export class HttpInterceptorService implements HttpInterceptor {
  // Other static stuff and below my httpInterceptorService
  static httpInterceptorService: HttpInterceptorService;

  constructor(
    httpInterceptorService: HttpInterceptorService,
  ) {
    HttpInterceptorService.httpInterceptorService = httpInterceptorService;;
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const headers = new HttpHeaders({
      // Some headers
    });

    const clone = req.clone({
      // ..
    });

    return next.handle(clone).pipe(
      // ..
    );
  }

  createHttpErrorMessage(error: HttpErrorResponse, statusText: string) {
    const msg: string = error.status + ' ' + error.statusText + ' - ' + statusText;
    switch (error.status) {
      case 404:
        this.showError('Error ID: ' + this.id, msg);
        break;
      default:
        break;
    }
    console.error(
      // Some error messages
    );
  }

  handleHttpError(error: HttpErrorResponse) {
    if (my condition) {
      // some logic
    } else {
      return throwError(error).pipe(
        retryWhen(errors => errors.pipe(
          delay(1000),
          take(1),
          tap(() => {
            switch (error.status) {
              case 404: // This method is not recognized anymore..
                HttpInterceptorService.httpInterceptorService.createHttpErrorMessage(
                  error, HttpInterceptorService.otherService.doSomething());
                break;
              default:
                console.error(error);
                break;
              }
            }),
          ),
        )
      );
    }
  }
}

As I said, the Interceptor has worked without any problems so far, until this error appeared yesterday.
What am I doing wrong?
Comment: Change it to `this.createHttpErrorMessage(...)` OR make the method static and invoke it using `HttpInterceptorService.createHttpErrorMessage(...)`
Comment: ++ Why do you *really* need a static reference in your service class?
Comment: If you want you can post your comment as an answer to let me confirm it :)
Comment: The part where I commented "This method is not recognized anymore.."
Comment: With this.createHttpErrorMessage the console says: _this.createHttpErrorMessage is not a function. It seem to work with making the method static and move it to the top. I also had to make another method static in order to make it work. I had to make it static because a lot of other stuff is going on in that service and it was the only way to make it work :(
Answer: You can make one of the following changes in order to fix the compilation issues.

Invoke it using
this.createHttpErrorMessage(...)

OR

Make the method static and invoke it using
HttpInterceptorService.createHttpErrorMessage(...)


Implementation of agent based model

Question: I'm trying to implement an agent based model in python (without using the Mesa package) as practice. I've written code that describes an observer (containing all the agents) which can help the neighbour agents and tells each agent to do a step. The step is saved in a new list before its copied to a list containing the previous situation.
The agents (domain models essentially) are either of the type: 'T' (Tree), 'S' (Soil), 'B' (Burning tree) and 'Bd' (Burned tree).
The concept is simple: we start with a number of trees, a number of burning trees and the rest is soil.
- Soil doesn't burn.
- Trees that have been burned remain burned trees
- Burning trees ignite the trees directly next to it (left, right, up or down) and become burned trees in the next step
- Trees remain trees unless they get ignited by a neighbouring burning tree.
Below the code for this. I've had a few versions but none seem to work. When I run the below version I get an error.
import os
import sys
from copy import deepcopy
import random

# observer class
class Obs:
    def __init__(self, max_iters=10):
        self.agents = []
        self.max_iters = max_iters

    def run(self):
        self.history = []
        self.prev_agents = None
        self.iters = 0

        while self.iters < self.max_iters:
            print(self.iters)
            self.history.append(deepcopy(self.agents))
            self.prev_agents = deepcopy(self.agents)
            for agent in self.prev_agents:
                agent.step()
            self.iters += 1

    def add_agent(self, x, y, agent_type, num_agent):
        self.agents.append(
            Agent(
                agent_type=agent_type,
                x=x,
                y=y,
                observer=self,
                agent_id=num_agent
            ))

    def get_neighbours(self, x, y):
        # items do not move so use current_situation
        nbs = []
        for agent in self.agents:
            if (abs(agent.x-x) == 1) & (abs(agent.y-y) == 1) & (abs(agent.x-x) == abs(agent.y-y)):
                nbs.append(agent)
        return nbs

    def set_agent(self, index, agent):
        self.agents[index] = agent

    def changed(self, agent_id):
        if self.prev_agents[agent_id].agent_type != self.agents[agent_id].agent_type:
            # been changed, can't change it back so skip it
            return True
        return False

class Agent:
    def __init__(self, agent_type, x, y, observer, agent_id):
        self.agent_type = agent_type
        self.x = x
        self.y = y
        self.observer = observer
        self.agent_id = agent_id

    def step(self):
        # perform action
        if self.agent_type == 'B':
            # burning
            nbs = self.observer.get_neighbours(self.x, self.y)
            for nb in nbs:
                if nb.agent_type == 'T':
                    self.observer.set_agent(
                        nb.agent_id,
                        Agent('B',
                          nb.x,
                          nb.y,
                          nb.observer,
                          nb.agent_id))

            # set to burned
            self.agent_type = 'Bd'
            self.observer.set_agent(
                self.agent_id,
                self)
        elif self.agent_type == 'T':
            if not self.observer.changed(self.agent_id):
                self.observer.set_agent(
                    self.agent_id,
                    self)
        else:
            # nothing happens to soil or burned trees
            self.observer.set_agent(
                    self.agent_id,
                    self)

xsize, ysize = 10, 10
num_trees = 40
num_burning = 10
num_soil = (xsize * ysize) - num_trees - num_burning

items = ['T'] * num_trees + ['B'] * num_burning + ['S'] * num_soil
random.shuffle(items)
observer = Obs(10)

for i, item in enumerate(items):
    x = i % xsize
    y = i // xsize
    observer.add_agent(x=x, y=y, agent_type=item, num_agent=i)

observer.run()

The error I get:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-26-74779de210e4> in <module>
    104     observer.add_agent(x=x, y=y, agent_type=item, num_agent=i)
    105
--> 106 observer.run()

<ipython-input-26-74779de210e4> in run(self)
     20             self.prev_agents = deepcopy(self.agents)
     21             for agent in self.prev_agents:
---> 22                 agent.step()
     23             self.iters += 1
     24

<ipython-input-26-74779de210e4> in step(self)
     79                 self)
     80         elif self.agent_type == 'T':
---> 81             if not self.observer.changed(self.agent_id):
     82                 self.observer.set_agent(
     83                     self.agent_id,

<ipython-input-26-74779de210e4> in changed(self, agent_id)
     45
     46     def changed(self, agent_id):
---> 47         if self.prev_agents[agent_id].agent_type != self.agents[agent_id].agent_type:
     48             # been changed, can't change it back so skip it
     49             return True

TypeError: 'NoneType' object is not subscriptable

Answer: The problem is that with deepcopy you are copying the observer itself which is a reference on each of the agents, and those observer copies have self.prev_agents = None as you are about to set this attribute. In detail, line 20 self.prev_agents = deepcopy(self.agents):

For each agent in self.agents, create a copy.
Each agent stores a reference self.observer.
Because we are doing a deep copy, we need to copy that observer as well.
The observer has various attributes among which there is self.prev_agents.
Since we are still computing the right hand side of self.prev_agents = deepcopy(self.agents), self.prev_agents is still None (line 14).
So each of the agent copies now has a reference self.observer which is a copy of the original observer and that copy has self.prev_agents is None.

That's why in the subsequent call to step the agent references the wrong observer and thus the error. I don't see why you would want to copy the observer at all, so using copy.copy instead of copy.deepcopy should solve the problem.
Side note: deep copying each agent will also encounter a reference cycle of the form agent -> observer -> self.agents -> agent but copy.deepcopy avoids this problem by keeping a memo dict of already copied objects.

Implementation of agent based model


Boost Accessing TCP client IP address + Port from TCP server after connection

Question: I have implemented a tcp client and tcp server using boost asio. The code is given below. (test.cpp, test.hpp and makefile)
The executable can be run as
(server side)
$ ./client_server 1 5005

(client side)
$ ./client_server 0 5005

The tcp_server class, when it accepts the connection should become aware of the remote end point(client_ip address + client port address).
However there doesn't seem to be variable that seems to store that on the server side.I would like to store the client end point information. how do I do this?
test.cpp
#include "test.hpp"
#include <iostream>
#include <exception>
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <algorithm>
#include <sstream>
#include <iomanip>

const int ARG_COUNT = 2;
const int MAX_PACKETS = 25;
const int LOWEST_PORT = 1024;
const int HIGHEST_PORT = 65000;

static char message_array[8192];

void gen_random_string(char *s, const int len)
{
    static const char alphanum[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";

    for (int i = 0; i < len; ++i) {
        s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
    }
    s[len] = 0;
}

class tcp_connection :public boost::enable_shared_from_this<tcp_connection>
{
public:
    typedef boost::shared_ptr<tcp_connection> pointer;

    static pointer create(boost::asio::io_service& io_service)
    {
        return pointer(new tcp_connection(io_service));
    }

    boost::asio::ip::tcp::tcp::socket& socket()
    {
        return socket_;
    }

    void start()
    {
        gen_random_string(message_array, 8192);
        std::string message(message_array);

        boost::asio::async_write(socket_, boost::asio::buffer(message),
                                 boost::bind(&tcp_connection::handle_write, shared_from_this(),
                                             boost::asio::placeholders::error,
                                             boost::asio::placeholders::bytes_transferred));
    }

private:
    tcp_connection(boost::asio::io_service& io_service)
        : socket_(io_service)
    {
    }

    void handle_write(const boost::system::error_code& /*error*/,
                      size_t /*bytes_transferred*/)
    {
    }

    boost::asio::ip::tcp::socket socket_;
    std::string message;
};

class tcp_server
{
public:
    tcp_server(boost::asio::io_service& io_service,int port_number)
        : acceptor_(io_service, boost::asio::ip::tcp::tcp::endpoint(boost::asio::ip::tcp::tcp::v4(), port_number))
    {
        std::cout << "TCP server listening on " << port_number << std::endl;
        start_accept();
    }

private:
    void start_accept()
    {
        tcp_connection::pointer new_connection =
            tcp_connection::create(acceptor_.get_io_service());

        acceptor_.async_accept(new_connection->socket(),
                               boost::bind(&tcp_server::handle_accept, this, new_connection,
                                           boost::asio::placeholders::error));
    }

    void handle_accept(tcp_connection::pointer new_connection,
                       const boost::system::error_code& error)
    {
        if (!error)
        {
            new_connection->start();
            start_accept();
        }
    }

    boost::asio::ip::tcp::tcp::acceptor acceptor_;
};

void runTCPServer ( CmdLineOpts input )
{
    try
    {
        boost::asio::io_service io_service;
        tcp_server server(io_service,input.port);
        io_service.run();
    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }
}

class tcp_client
{
public:
    tcp_client(
        boost::asio::io_service& io_service,
        const std::string& host,
        const std::string& port
    ) : io_service_(io_service), socket_(io_service, boost::asio::ip::tcp::tcp::endpoint(boost::asio::ip::tcp::tcp::v4(), 0))
    {
        boost::asio::ip::tcp::tcp::resolver resolver(io_service_);
        boost::asio::ip::tcp::tcp::resolver::query query(boost::asio::ip::tcp::tcp::v4(), host, port);
        boost::asio::ip::tcp::tcp::resolver::iterator iter = resolver.resolve(query);
        endpoint_ = *iter;
        boost::asio::connect(socket_, iter);
    }

    ~tcp_client()
    {
        socket_.close();
    }

    void recieve_from() {
        /*Initialize our endpoint*/
        size_t len = socket_.read_some(
                         boost::asio::buffer(recv_buf), error);

        if (error == boost::asio::error::eof)
            std::cout << "Connction close cleanly by peer" << std::cout;
        else if (error)
            throw boost::system::system_error(error); // Some other error.

        std::cout.write(recv_buf.data(), len) << std::endl;

    }

private:
    boost::asio::io_service& io_service_;
    boost::asio::ip::tcp::tcp::socket socket_;
    boost::asio::ip::tcp::tcp::endpoint endpoint_;
    boost::array<char, 2048> recv_buf;
    boost::asio::ip::tcp::endpoint sender_endpoint;
    boost::system::error_code error;

};

void runTCPClient(std::string portStr)
{
    try
    {
        boost::asio::io_service io_service;
        tcp_client client(io_service, "localhost", portStr);
        client.recieve_from();
    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }

}

void runClient( CmdLineOpts input )
{
    runTCPClient(input.portStr);

}

void runServer( CmdLineOpts input )
{
    runTCPServer(input);
}

/**
 * * Usage: client_server <protocol> <port> <num of packets>
 * */
bool cmdline_parse ( int argc, char *argv[], CmdLineOpts *input )
{
    bool result = true;
    if (argc - 1 == ARG_COUNT)
    {
        // arg 1: server or client
        int arg1 = std::stoi(argv[1]);
        if (arg1 == 0 || arg1 == 1)
        {
            input->servOrClient = arg1;
        }
        else
        {
            std::cout << "Invalid client server choice.\nUsage: client_server <client (0) or server(1)> <protocol> <port>" << std::endl;
            result = false;
        }
        // arg 3: port
        int arg2 = std::stoi(argv[2]);
        if (arg2 > LOWEST_PORT && arg2 < HIGHEST_PORT )
        {
            input->port = arg2;
            input->portStr = argv[2];
        }
        else
        {
            std::cout << "Invalid port, must be between " << LOWEST_PORT << " and " << HIGHEST_PORT << std::endl;
            std::cout << "Usage: client_server <client (0) or server(1)> <protocol> <port>" << std::endl;
            result = false;
        }

    }
    else
    {
        std::cout << "Usage: client_server <client (0) or server(1)> <protocol> <port>" << std::endl;
        result = false;
    }

    return result;
}

int main ( int argc, char *argv[] )
{
    CmdLineOpts input;
    if (cmdline_parse(argc, argv, &input))
    {
        if(input.servOrClient == 1)
        {
            runServer(input);
        }
        else if(input.servOrClient == 0)
        {
            runClient(input);
        }
    }
    else
    {
        return 1;
    }

    return 0;
}

test.hpp
#ifndef CLIENT_SERVER_H_INCLUDED
#define CLIENT_SERVER_H_INCLUDED

#include <string>

struct CmdLineOpts
{
    std::string portStr;
    int port;
    int servOrClient;
};

void runTCPServer ( CmdLineOpts input );

void runTCPClient ( std::string port_str);

bool cmdline_parse ( int argc, char *argv[], CmdLineOpts input );
#endif

Makefile
TARGET = client_server
LIBS = -lboost_system -lpthread
CXX = g++
CXXFLAGS = -std=c++11 -g -Wall -pedantic

.PHONY: default all clean

default: $(TARGET)
all: default

OBJECTS = $(patsubst %.cpp, %.o, $(wildcard *.cpp))
HEADERS = $(wildcard *.hpp)

%.o: %.cpp $(HEADERS)
  $(CXX) $(CXXFLAGS) -c $< -o $@

.PRECIOUS: $(TARGET) $(OBJECTS)

$(TARGET): $(OBJECTS)
  $(CXX) $(OBJECTS) $(LIBS) -o $@

clean:
      -rm -f *.o
      -rm -f $(TARGET)

Answer: You can call socket_.remote_endpoint() to get it.  See:
http://www.boost.org/doc/libs/1_47_0/doc/html/boost_asio/reference/basic_stream_socket/remote_endpoint.html


Variable size in c++

Question: I am writing a cuda C program. So, in order to put each variable in the appropriate  memory, I am looking for a tool that can give me the memory size of a c++ variable,  object, structure...
Comment: This question has nothing to do with CUDA.
Answer: sizeof(my_type) will give you the size of my_type in bytes

Variable size in c++


(File) File: Path outputs only first item

Question: I have a view that renders a node page as a view, that node has e.g. 100 images, so technically they are all on same node, so then we go to views fields settings and untick the option to show images in same row. So now each image has it's own row.
Now we add the relationship for file to enable extra fields. We add the File field and it also gets printed next to every image.
Except problem is that it prints the same and only path of the very first image under every other image. It should print the path of each image in the same row.

EDIT: tried the https://www.drupal.org/project/image_url_formatter module, same. It outputs the very same first image field only.
View:
Comment: Could you post a bit more info about your View? I am not sure how to replicate your setup.
Comment: A screenshot of your views config would also help. Cheers!
Comment: Hi. See update, please.
Answer: This is expected behaviour following from your Views configuration, there is no way to instruct Views to maintain a 1-1 relation between the (File) File: Path (which gives you one file path for each image) and the Content: Image (which gives you one image formatted field with multiple images included). As a result, they are 'combined' (cartesian product) and you should actually be getting a very long list of all combinations of images and image paths.
By using the Image URL Formatter module you should be able to do what you need, here is a screenshot:

I added the "Content: Image" field twice, each time unticking the "show images in same row" option. The first one was formatted as an Image, the second one as an Image URL. And things worked as expected.
Good luck!


Can't get data from class

Question: I have a problem, when i put data to the public instance of the class in function =>
 static async Task _MainAsync()
        {

            Form1 info = new Form1();

             info.decoded = JsonConvert.DeserializeObject<Rootobject>(msg);

        }// the code is simplified

and when i use it in another function, the instance of the class becomes null, How can i fix it?
private async void button1_Click(object sender, EventArgs e)
        {

                       await _MainAsync();
                    coin.Text = decoded.message;

            }

Comment: In your first block of code, `info` is only referenced in that method. You don't store it anywhere more permanent. You might be confused about what an instance is. Imagine there's a model of car: Toyota Prius (this is `Form1`). I buy one (`new Form1();`), and you buy one (`new Form1();`). I have a cool wrap done on mine (`myForm.Title = "hello";`), but yours is still as you bought it, as it came from the factory. Why? Well, we both have a different car.
Comment: Why is `_MainAsync` static? Perhaps it should *return* the decoded message?  Or perhaps it should not be static?  Or perhaps it should take an container object as an argument, into which it will write the decoded message.  Not sure how _simplified_ that method is.
Answer: The instance Form1 info = new Form1(); you created in _MainAsync() is local. You can't access it from outside the method.
One way you can change its property is to create the instance in button1_Click, send the instance as a method parameter to _MainAsync() change the propery in there and continue working in button1_Click.
static async Task _MainAsync(Form1 form1Instance)
{
    ...
    form1Instance.decoded = JsonConvert.DeserializeObject<Rootobject>(msg);
    ...
}

private async void button1_Click(object sender, EventArgs e)
{
    ...
    Form1 info = new Form1();
    await _MainAsync(info);
    coin.Text = info.decoded.message;
    ...
}

Can't get data from class


How many roots has $x^a=b$ where $a$ is a real number?

Question: I know that $x^a=b$ has $a$ complex roots if $a$ is an entire number. What can I say about $a$ real?
I've tried some Wolfram Calculations with exponent $n \pi$ and had $[n\pi]+1$ complex roots... So I've thought about $[a]+1$, but cannot prove it.
Thank you so much!
Comment: What have you tried?  You need to give some explanation of what you have done and where you are stuck in this.
Comment: What is your definition of $x^a$ when $a$ is not an integer? Say a fraction, or even $a=\pi.$
Comment: I still think irrational exponents can be defined, but it gets complicated as far as I know.
Comment: Irrational exponents are taken as the continuous limit of rational exponents, and these are well defined for $x\geqslant 0$.
Comment: @N.Owad I've edited, thanks
Comment: @coffeemath, well... When a fraction, $x^{p/q}=\sqrt[q]{x^p}$... $a$ not rational by limits on rationals... So I could conclude that I can only look to rationals? Thank you!
Answer: if $x=re^{i\phi}$
then:
$$r^ae^{i\phi a}=b$$
since:
$$|e^{i\phi a}|=1$$ be must have that:
$$|r^a|=|b|$$
or:
$$r=|b|^{1/a}$$
now roots will repeat at a point since $e^{iz}$ has a period of $2\pi$ and so you want to find all $\phi$ which satisfy the equation:
$$e^{i\phi a}=1=e^{2\pi i}=e^{0i}$$
in other words, find all unique $\phi$ for integer $k$ such that:
$$\phi a=2k\pi$$

From all of this we get:
$$\phi=\frac{2k\pi}{a},\qquad 0\le\phi\le2\pi$$
Hopefully you can see where this is going
Comment: This assumes $b$ is real, but the gist of it is correct.
Comment: @Fimpellizieri yeah I'm a little rusty on this area haha but It seemed to be okay for $b\in\mathbb{R}$
Comment: yes that is correct
Comment: @Quiet_waters : As in [your other Question](https://math.stackexchange.com/questions/4171374/why-wolfram-do-18-9-so-strange), Wolfram Alpha is giving what amounts to "the small roots" (the roots with complex argument in $[-\pi, \pi]$ (and it may exclude one of those endpoints; I don't recall)).  However, there are countably infinitely many solutions.  The set of such solutions is being described in this Answer.
Comment: @HenryLee thank you so much! But I think you considered $b$ positive. If $b$ negative, so $\phi a=2k\pi+\pi,$ am I right? Thank you!
Comment: @HenryLee I am sorry if I am stucked with this... But if $a$ is irrational, so $2\pi k/a$ is not a periodic function, so there's infinite many roots...? But why the roots of $x^e=2$ are $3$ and the roots of $x^{2e}=2$ are $5$, for instance? Thank you so much! https://www.wolframalpha.com/input/?i=x%5Ee%3D2; https://www.wolframalpha.com/input/?i=x%5E%282e%29%3D2
Comment: @HenryLee: other doubt: Why this equation has no complex root? https://www.wolframalpha.com/input/?i=x%5E%280.2%29%3D-1 I could take $k=0$, so $\phi=\pi $... Why $e^{\pi i}=-1$ is not a solution? I imagine that this relation with my other question https://math.stackexchange.com/questions/4171374/why-wolfram-do-18-9-so-strange?noredirect=1#comment8640687_4171374, but not sure
Comment: Thank you so much @EricTowers


How do I add a variant programmatically?

Question: I have many sites in an installation that have many Panels pages. Many of them need a HTTP Response (404) variant added to them, which I would like to do programmatically.
Assume I have the page already via:
$page = page_manager_page_load($pageName);

Modifying something in the page is easy. Make the change then call page_manager_page_save($page);
It seemed the easiest way to accomplish adding a variant was to take an exported variant and import it. This is what the clone function does.
Here is an exported variant:
$handler = new stdClass();
$handler->disabled = FALSE; /* Edit this to true to make a default handler disabled initially */
$handler->api_version = 1;
$handler->name = 'page_bes_homepage__http_response_0ab6f1a9-9c98-459c-b4d3-10f63ddace56';
$handler->task = 'page';
$handler->subtask = '';
$handler->handler = 'http_response';
$handler->weight = 1;
$handler->conf = array(
  'title' => '404 Error',
  'contexts' => array(),
  'relationships' => array(),
  'code' => '404',
  'destination' => '',
  'name' => '',
);

It doesn't appear necessary to set the subtask or provide a new name since the page_manager_handler_add_to_page() appears to handle that (though at first I set those myself; didn't help).
Attempting to add and save via:
page_manager_handler_add_to_page($page, $handler);
page_manager_page_save($page);

doesn't work. Some code in page_manager.module had me think that the failure might might be because of ctools caching so I tried this:
page_manager_save_page_cache($page);
page_manager_clear_page_cache($pageName);
page_manager_page_save($page);

and that doesn't work either. Scouring the web for an example of this has not turned up anything in code snippets, tutorials or books and ctools doesn't provide this level of documentation.
How does one add a variant programmatically? Note that I do not want this in Features and I do not want this stored in code via the ctools api. I just want to run through a list of Panels pages programmatically and add a variant.
Answer: You can try this:
I found how to store manually created variants in code for custom pages (e.g. '/node/%node/test')
function MODULE_default_page_manager_pages() {
  // Copy exported page code here.

  $pages['UNIQUE_PAGE_ID_HERE'] = $page;

  return $pages;
}

Putting everthing in a file called 'MODULE.pages_default.inc' in your MODULE's main folder, and link that file with my MODULE.module via
/**
 * Implement hook_ctools_plugin_api().
 *
 * If you do this, CTools will pick up default panels pages in
 * MODULE.pages_default.inc
 */
function MODULE_ctools_plugin_api($module, $api) {
  if ($module == 'page_manager' && $api == 'pages_default') {
    return array('version' => 1);
  }
}

Source: https://www.drupal.org/node/579036


Is there such a thing as an ineligible runner in football?

Question: In American football, there is such a thing as an ineligible (pass) receiver. That is, a "lineman" (center, guard, tackle) is not allowed to catch forward passes. Are they similarly prohibited from running with the ball? I can see two cases:
1) A "back" (or pass receiver) drops or fumbles the ball, a lineman picks it up and runs with it.
2) The quarterback (or runner) hands the ball to a lineman.
I see the second happening in the case of a "quarterback sneak," that is, the quarterback allows the center to keep the ball and "plunge" for short yardage. Does this mean that a runner can hand the ball to a lineman if it is convenient? Why is this not done occasionally to "mix things up" if it is allowed? Or is such "mixing things up" something rules are designed to prevent?
Answer: No, they are not prohibited from doing that.
The rule you stated applies only to forward passes. A Hand-Off is by its definition not a pass, since the ball is not advanced (forward), but handed over instead. That said, any player is eligible to take it.
Going by the following rule they are also eligible to pick up the ball from the ground.

Article 4: Legal Snap. A snap is a backward pass. The snap must be
  received by a player who is not on the line at the snap, unless the
  ball first strikes the ground. If the ball first strikes the ground,
  or is muffed by an eligible backfield receiver, or quarterback under
  center, it can be recovered and advanced by any player.

And here is a video of a lineman scoring a TD after taking a Hand-Off.
Answer: Fundamentally, a lineman is not allowed to go more than one yard past the line of scrimmage for blocking, or other purposes.
There is a major exception to the rule, which is related to other, minor exceptions.
Major exception: If a lineman begins a block against a defender no more than one yard past the line of scrimmage, he is allowed to continue blocking that (and only that) defender as long as he maintains contact.
Minor exception: From the above, it follows that a lineman, such as a center on a quarterback sneak, who began "operations" no more than one yard past the line of scrimmage is allowed to continue such an operation, such as running.  Moreover, most handoffs take place no more than one yard past the line of scrimmage.
Minor exception: If the ball becomes "loose" anywhere on the field, anyone can try to pick it up and run.
Minor exception: No forward passes are allowed past the line of scrimmage but a lineman can catch a lateral (backward or sideward) pass anywhere, and run.


Enforce Profile Path Windows Server 2008

Question: Is there a way to enforce a profile path in active directory on win server 08 (or set a default one) so that when a user is added the profile path is automatically filled in in the profile tab.
The reason I want to do this is that I am setting up the server and then it's going to be managed by other people. I want to make sure that setting the profile path isn't forgotten because I think it's something that could easily be missed. Also it seems pointless to have to remember to set it each time when it should be the same for each user.
Thanks.
Answer: That is not possible. You can, however, configure the profile path via group policies. In that case it is tied to the computer object and not to the user account and thus cannot be forgotten when creating new users.
Comment: Thanks. I thought of this but the problem is that I think it applies to local users as well. So every time I logon to the local administrator on a computer it will try and create a roaming profile and mess things up. Let me know if I'm wrong though.
Comment: You are right, the policy applies to local user accounts, too, as documented here: http://support.microsoft.com/kb/958736.
Comment: I think I might end up doing that. If I set the permissions on the share for domain users only I guess that will mean that local accounts will just get temporary profiles and it shouldn't mess anything up.
Comment: Would you mind marking my answer as correct?
Comment: I want to leave it a few more days first to see if anyone else has any info.


Size of FITS file different before and after processing

Question: I have problem with file size after processing...I wrote script which create edited image...(From raw image data deduct flat field image data and dark image data)...Here is code Convert float NumPy array to big endian  And my problem is...At the beggining I have fits file with size 2.8MiB with type >2i...After processing I have fits file with 11MiB and type float64 and I dont know why?
In IDL is some fix method http://www.exelisvis.com/docs/FIX.html . In Python I use imgg=imgg.astype(np.int16,copy=False).So I get image file with 2.8MiB but only in white a black color...
Any suggestion please?
Answer: From http://docs.astropy.org/en/stable/io/fits/appendix/faq.html#why-is-an-image-containing-integer-data-being-converted-unexpectedly-to-floats
If the header for your image contains non-trivial values for the optional BSCALE and/or BZERO keywords (that is, BSCALE != 1 and/or BZERO != 0), then the raw data in the file must be rescaled to its physical values according to the formula:
<code>physical_value = BZERO + BSCALE * array_value
</code>
As BZERO and BSCALE are floating point values, the resulting value must be a float as well. If the original values were 16-bit integers, the resulting values are single-precision (32-bit) floats. If the original values were 32-bit integers the resulting values are double-precision (64-bit floats).
This automatic scaling can easily catch you of guard if you're not expecting it, because it doesn't happen until the data portion of the HDU is accessed (to allow things like updating the header without rescaling the data). For example:
<code>>>> hdul = fits.open('scaled.fits')
>>> image = hdul['SCI', 1]
>>> image.header['BITPIX']
32
>>> image.header['BSCALE']
2.0
>>> data = image.data  # Read the data into memory
>>> data.dtype
dtype('float64')  # Got float64 despite BITPIX = 32 (32-bit int)
>>> image.header['BITPIX']  # The BITPIX will automatically update too
-64
>>> 'BSCALE' in image.header  # And the BSCALE keyword removed
False
</code>
The reason for this is that once a user accesses the data they may also manipulate it and perform calculations on it. If the data were forced to remain as integers, a great deal of precision is lost. So it is best to err on the side of not losing data, at the cost of causing some confusion at first.
If the data must be returned to integers before saving, use the ImageHDU.scale method:
<code>>>> image.scale('int32')
>>> image.header['BITPIX']
32
</code>
Alternatively, if a file is opened with mode='update' along with the scale_back=True argument, the original BSCALE and BZERO scaling will be automatically re-applied to the data before saving. Usually this is not desirable, especially when converting from floating point back to unsigned integer values. But this may be useful in cases where the raw data needs to be modified corresponding to changes in the physical values.
To prevent rescaling from occurring at all (good for updating headers–even if you don't intend for the code to access the data, it's good to err on the side of caution here), use the do_not_scale_image_data argument when opening the file:
<code>>>> hdul = fits.open('scaled.fits', do_not_scale_image_data=True)
>>> image = hdul['SCI', 1]
>>> image.data.dtype
dtype('int32')
</code>
Comment: Thank you very much ...This is it what I want


Exporting a view from one site to another

Question: I'm a Drupal beginner with a problem.
I'm gonna do some updates on a live site which requires some new views to be created, and with that some new content types and blocks. I'm working off my local dev site doing these changes there first and then I'd like to be able to export these views as a package with the content types and blocks that they handle. Is this possible?
Of course I could just export my local database and import it on the live site, but the problem is that the live site is very active so the database is always changing. And my updates will take at least a week to do, so I can't keep up.
Any suggestions?
Answer: By Default views have option to import and export. By using that we can do it.
In drupal7 views3.x has option of import link in this url admin/structure/views
With this image you will get clear view of how to import and export a view.
Comment: where is this in 8?
Comment: Thanks! I missed that option since I was hanging around inside the view to be exported. Does this export bring all associated data with it, like the block and new content types?
Comment: it just export the views structure. Like pages, block, feeds..in your views. Not include content types. To include content types you need Feature moudule like @Rotem answer
Comment: To add to stone vo's comments, you can use a simpler way to export/import content types (not their data). The module name is `bundle_copy`
Answer: In addition to the views module I also recommend you to use the Features module that allows you to export your content types and lot more to code and then just commit the new code and revert it to DB on production.
Answer: Surely, Import/Export of Views will do the job (for exporting views only), but I would invest time in Configuration Management module. It has ALL the possible options, not only for views, but also for nodes, content types.
I don't recommend using Features module, since I experienced a lot of bugs and unexpected behaviour with it.
In case you want to copy content types (quick-dirty solution), I recommend the module BundleCopy
Regards.


Por que os booleanos não tem uma classe em comum em Ruby?

Question: O Ruby não tem uma classe Boolean. Percebi que os objetos booleanos são de classes específicas dependendo do valor, veja:
true.class  => TrueClass
false.class => FalseClass

Diferente de outras linguagens, como C# e Java, em que true e false são do tipo bool, em Ruby é TrueClass ou FalseClass.
Isso implica em: se eu quero verificar se um objeto é booleano, tenho que fazer algo como:
def boolean?(value)
  [TrueClass, FalseClass].include? value.class
end

No caso, vejo como a única forma de ver se um objeto é de um tipo booleano. De outra forma, seria verificar somente se um objeto é truthy ou falsy.
!!nil #=> false
boolean?(nil) #=> false

!!"Olá!" #=> true
boolean?("Olá!") #=> false

!!false #=> false
boolean?(false) #=> true

!!true #=> true
boolean?(true) #=> true

Por que foi arquitetado assim? Que vantagens variar o tipo em questão do valor traz no contexto Ruby?
Comment: Não precisa porque pode usar `true` e `false` como qualquer linguagem (https://docs.ruby-lang.org/en/2.2.0/keywords_rdoc.html)
Comment: Tem algum contexto? Porque não precisa fazer isto.
Comment: Não preciso por conta do _duck typing_, né? @Maniero
Comment: O problema não é nem a validação de tipo, foi um exemplo que tentei dar para contextualizar. Eu me deparei com `TrueClass` e `FalseClass` e questionei essa escolha. @Maniero
Answer: Em um e-mail questionando o mesmo para Yukihiro "Matz" Matsumoto, criador do Ruby, ele responde:

Algum bom motivo para que esses [TrueClass e FalseClass] não herdarem Bool ou algo do tipo?

Existe alguma razão para herdarem Bool, onde true e false são só representações de valores verdadeiros?

Meu entendimento sobre isso é que uma classe é feita para agrupar objetos semelhantes em questão de valor, semântica e/ou comportamento.
No que disse Matz, ele não viu semelhança a partir desses critérios entre true e false. De fato eles são até opostos.
Para quem quiser ler mais sobre esse assunto, existe uma thread no Ruby-Forum que trata da mesma questão, onde Matsumoto também se prontifica.

Não existe nada que true e false compartilham, portanto sem classe Boolean. Além disso, em Ruby, tudo se comporta como um valor booleano.


Drupal extra subdomains for some special nodes

Question: I have the following in mind and I'm not sure how to realize it nicely.

Drupal 7 serves many nodes from several different taxonomies
If I visit a taxonomy page e.g. example.com/category-one/taxonomy-term-one I get a list of all the corresponding nodes
If I click on one of the list nodes, I get to the page example.com/content-type/node-name
There are some special nodes in this list, when I click on them, I get to the following special page node-name.example.com. This page is exactly the content like example.com/content-type/node-name but in this case, only the subdomain URL is accessible and example.com/content-type/node-name doesn't exist to avoid content duplication.

The first 3 items are easy standard tasks: The Pathauto module handles all the taxonomy url alias tasks etc.
The 4th item is my problem. My idea so far: The subdomain node-name.example.com just references a special folder under the drupal root, which contains some logic to determine the name of the node according to the subdomain. With the given subdomain I get the node id and just load all the stuff from drupals db with a service implemented for this usecase.
Questions:

Ist it possible to give a drupal node an absolute url alias like node-name.example.com just like node-category/node-name?
Are there any problems going to be concerning drupals $baseurl/site configuration?
As I'm editing everything just over the example.com/node/node-id/edit there should be no problems with the editing functionality, no?
What remains to be done?

Did anybody had to fulfill a similar apporach and could share some thoughts regarding my approach?
Answer: Have you looked at the Domain Access module?

The Domain Access project is a suite of modules that provide tools for
  running a group of affiliated sites from one Drupal installation and a
  single shared database. The module allows you to share users, content,
  and configurations across a group of sites such as:

example.com
one.example.com
two.example.com
my.example.com
thisexample.com <-- can use any domain string
example.com:3000 <-- treats non-standard ports as unique

By default, these sites share all tables in your Drupal installation.
  The Domain Prefix module (for Drupal 6) allows for selective, dynamic
  table prefixing for advanced users.

Basically you can assign a Node across any number of configured subdomains you've made drupal aware of.
Comment: Thank you for the suggestion! I'm not sure if I should use this module. I don't want to share nodes across multiple subdomains, I want to replace the nodes url with the one special subdomain covering this node. So I want it to get listed under node-name.example.com and to be listed with this link under its category f.e. example.com/category-one/taxonomy-term-one. I don't want my whole drupal site to be available under node-name.example.com, I just want the one exact node page to be available there. If I take domain access, I get the whole stuff 'copied' and shared... Perhaps Global Redirect?
Comment: you can "share" the node(s) into any subdomain. You can share only 1 node, or any number of nodes to a domain. You may want to install it in a test setup locally and try it out for yourself for an hour or two. I believe Domain will also create the list of subdomain(s) the node is used in as well from the source domain.


Securing admin account, silly "solution" found

Question: Hello fellow Drupalers,
I've been given the task of securing our admin account, on our websites (drupal 7) from outsiders.
My first thought was 2FA and I looked at some of the modules (tfa, google auth, etc) and they seem to be doing the job okay.
But as I was fiddling around I accidentally deleted the admin password.
Now I cannot login through the website with the admin account, but I can via drush uli.
Do you guys consider this to be an okay solution for securing the admin account?
I personally have my doubts about it, because it seems so simple...
Comment: How exactly did you delete the password?
Comment: Via the database, just fiddling around.
Comment: It was on my local dev version...
Comment: Curious, if you inspect element on password field and remove the `required="required"` and leave password empty does it log you in?
Comment: That was a good question. I've tested it, and I still cannot login even though the required has been removed.
Answer: Definitely not a solution I would rely on. "Securing admin account" is a wide topic that needs to be handled carefully, but answering specifically to your question, if what you want is to "protect" the password, you can run a cronjob that changes the password string to a random, SHA value, every X time. I've seen that in some clients.
Talking about MFA (2FA), yes, this adds a pretty solid and common layer of security. Also implemented it for some clients.
Comment: I think I've found part of the solution here: https://www.drupal.org/project/restrict_by_ip

I've also found this page: https://www.drupal.org/node/947312 It has some good tips for securing the admin user.

Thank you for your answer.


Given $ x^m=y^m ; so \; x=y \;or\; -y$ when m is even. Now $ 2^0 = 3^0 \; but \; 2 \neq 3 $ . How to reason mathematically

Question: The question may sound silly but is there a simple logic to counter the paradox.I will be glad to know if there is. Thank You.
Edit: x,y $\in R\;\; x,y \neq 0$, m is a integer.
Now x = y when m is odd
x = y or -y when m is even. and x and y cant be related when m = o.
I didn't mean to say there is a paradox. The question asked above is asked in one of my interview and I was asked to explain mathematically. I gave the above reply but they didn't seem to be satisfied. That is the reason I posted this question to know if there is any mathematical reason. Sorry if anyone thinks such questions shouldn't be posted and thank you everyone for taking their time in commenting.
Comment: It will help to define the intervals on which $x,y$ and $m$ are defined on - there are many cases in which your statement "if $x^m = y^m$, then $x=y$ or $x=-y$ when $m$ is even" fail. The "paradox" is in the statement being imprecise.
Comment: Thank you @IrregularUser x,y and m are real. and  x, y  $\neq$ 0
Answer: You can reason the same as why $2\neq3$ when $2\cdot0=3\cdot0$. This is because the step you performed is irreversible. It is not allowed to divide by zero to get $2=3$.
In the case $2^0=3^0$, to get a form $2=3$ you would need to take the $0$th root. But remember that $\sqrt[0]{2}=\sqrt[0]{3}$ is equivalent to $2^\frac10=3^\frac10$ with a division by zero, so that is not valid.
Answer: If $m \geq 2$ and $m$ is even, $x$ and $y$ are real, then $x^m=y^m \implies x=y$ or $x=-y$.
$x^0=1 ,\forall x \neq 0, x \in \mathbb{R}$.
There is no contradiction.
Comment: Thank You @SiongthyeGoh for writing my statement in a precise manner. I didnt mean to say there is a paradox. As when m is 0 , x and y cant be related. Since m = 0 is even how can we write that there is no contradiction.
Comment: add more conditinons such as $m$ is even and non-zero?
Comment: Actually this is a question asked in an interview. And they have asked it in the same manner I asked above. I think it is my mistake to post such question in this forum. But Thank You for your time and patience.
Answer: If they were interested in in hearing reasoning around why the claim "$x^m = y^m \implies |x| = |y|$ (if $m$ even)" fails, perhaps you could take a logarithm of each side and note that it is only possible to divide $m$ out of $$m \log(|x|) = m \log(|y|)$$ when $m$ is nonzero (and here we're also assuming that $x$ and $y$ are both nonzero). This is exactly the same reasoning as in other folks' answers, but it's possible that it might be more satisfying to an interviewer because it allows you to go into more detail about why $x^0 = y^0 \not \implies |x| = |y|$.


How to take JSON objects one by one from response object and display in table in Angular?

Question: The JSON Array get into typescript as response Object from my Java application. I need to pick each object and display into html page corresponding to that typescript page in angular.
list-user.component.ts
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { Router } from '@angular/router';

@Component({
  selector: 'app-list-user',
  templateUrl: './list-user.component.html',
  styleUrls: ['./list-user.component.css']
})
export class ListUserComponent implements OnInit {
  loginForm!: FormGroup;
  submitted = false;
  jdbc: any;
  username:any

  constructor(private http: HttpClient, private router: Router) { }

  ngOnInit() {
    this.username = JSON.parse(localStorage.getItem("session") || "");
    let listuser: any = {
      username: this.username,
    }
    this.http.post('http://localhost:8080/demoprojectjava/list-user/',
      listuser, { observe: 'response' }).subscribe(res => {
          console.log(res);
  });
  }
}

list-user.component.html

 Display Data from Json File

            User Id
            Lastname

            {{--Here I need value from Json array}}
            {{--Here I need value from Json array}}

When I run my code, in console I got the output as a result for console.log(res); as :
{"user_data":[{"user_id":"111","username":"Hridya"},{"user_id":"222","username":"Rizz"}]}

Answer: Store the http request as Observable in a property (here userData$). Then use the async pipe in your template to have angular automatically subscribe to it.
Then use ngFor to iterate over all the elements inside the response and display the data accordingly.
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';

type ResponseTypeFromYourBackend = any;

@Component({
  selector: 'app-list-user',
  templateUrl: './list-user.component.html',
  styleUrls: ['./list-user.component.css']
})
export class ListUserComponent implements OnInit {
  loginForm!: FormGroup;
  submitted = false;
  jdbc: any;
  username:any
  userData$: Observable<ResponseTypeFromYourBackend>;

  constructor(private http: HttpClient, private router: Router) { }

  ngOnInit() {
    this.username = JSON.parse(localStorage.getItem("session") || "");
    let listuser: any = {
      username: this.username,
    }
    this.userData$ = this.http.post('http://localhost:8080/demoprojectjava/list-user/',
      listuser,
      { observe: 'response' }
    );
  }
}

 Display Data from Json File

      User Id
      Lastname

      {{ user.user_id}}
      {{ user.username}}

Comment: Wow, astonishing how similar our answers are :D Guess this can really be seen as a best practice then :D
Comment: Yes, I really like that you re-mapped `user_data` outside the template already. Good job :)
Answer: The best way to do this would be to do the following:

Define an observable on class level:

userData$: Observable<YourType>;
...
ngOnInit() {
   ...
   this.userData$ = this.http.post('http://localhost:8080/demoprojectjava/list-user/',
      listuser).pipe(map(item => item.user_data));
  }

Subscribe to this observable using async pipe and iterate over the array:

  {{item.user_id}}
  {{item.username}}

Answer: Create a variable to store the response and use ngFor to loop through the array.

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { Router } from '@angular/router';

@Component({
  selector: 'app-upload-active-census',
  templateUrl: './upload-active-census.component.html',
  styleUrls: ['./upload-active-census.component.css'],
})
export class UploadActiveCensusComponent implements OnInit {
  loginForm!: FormGroup;
  submitted = false;
  jdbc: any;
  username: any;
  data: any;

  constructor(private http: HttpClient, private router: Router) {}

  ngOnInit() {
    this.username = JSON.parse(localStorage.getItem('session') || '');
    let listuser: any = {
      username: this.username,
    };
    this.http
      .post('http://localhost:8080/demoprojectjava/list-user/', listuser, {
        observe: 'response',
      })
      .subscribe((res) => {
        console.log(res);
        return this.data = res;
      });
  }
}

 Display Data from Json File

                User Id
                Lastname

                {{item.user_id}}
                {{item.username}}

Comment: This will cause a runtime error the moment `data.user_data` gets evaluated before the request was finished.
Comment: @Vishnu Prabhu. Your Typescript code worked smoothly... But I didn't got value with your html code and made a small change as
            `` . Then I got the values in table
Answer: @Vishnu Prabhu. Thanks for the answer.
 Your Typescript code worked smoothly... But I didn't get value with your html code and made a small change. Then I got the values in the table. So I'm posting the entire code that worked well for me, to anyone else for future reference.
list-user.component.ts

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { Router } from '@angular/router';

@Component({
  selector: 'app-list-user',
  templateUrl: './list-user.component.html',
  styleUrls: ['./list-user.component.css']
})
export class ListUserComponent implements OnInit {
  loginForm!: FormGroup;
  submitted = false;
  jdbc: any;
  username: any;
  data: any;

  constructor(private http: HttpClient, private router: Router) { }

  ngOnInit(): void {
    this.username = JSON.parse(localStorage.getItem("session") || "");
    let listuser: any = {
      username: this.username
    }

    this.http.post('http://localhost:8080/demoprojectjava/list-user/',
      listuser, { observe: 'response' }).subscribe(res => {
        console.log(res.body);
        return this.data = res;
      },
      );
  }
}

list-user.component.html

 Display Data from Json File

                User Id
                Lastname

                {{user.user_id}}
                {{user.username}}


Link static HTML, Javascript and CSS3 in a Drupal Site

Question: I am trying to have collaborative development of a HTML5 web app which people could navigate too through my drupal site. I was planning on putting the html, JS and CSS3 files in my sites/default/files folder and just passing a link. I am curious how i perform to things
How can I put an alias over the html file so i can have url mysite/demo
also I want to block people from reading my JS and CSS3 files so the source code is just not purely out in the open is there a way to do this.
I know inspect html on most browsers give you a lot but I do not want them to find my .js file and then request that and have my source code.
Any assistance or guidance would be very helpful
Comment: If you are going to down grade me at least explain why. I think this is a novel question.
Answer: I think the best option for what your describing is to take a screen shot of the site and use that; as an image will not display the html/css/js. https://www.drupal.org/project/phantomjs_capture is the project I would use; this is a very odd request so in order to achieve this you'll have to do some custom coding.
If your looking to obfuscate the JavaScript by minification AdvAgg can help but it's not setup to fully obfuscate the JS as it will point to the source file by default (for GPL compliance). This could be changed; if you do decide to go down this route open up a request in the advagg issue queue and I'll add in a hidden option to allow this to happen.
Comment: Thanks a lot. I am stuck between a rock and a hard place as I want people to see where I am at but not steal my source code. I will check out your suggestions.
Comment: im using 7.x-2.7, is the fully obfuscate available now? or can you point me which part of the code i should look into it? Thanks!
Comment: @Kent The latest dev has it and 2.8 will be coming out very soon. Drupal.org is actaully using the dev version currently. Go to admin/config/development/performance/advagg/js-compress and uncheck "Add licensing comments".


bootgrid with editable textbox

Question: How do I add an editable textbox in my BootGrid with the column's text, so that in it opens the textbox for editing, and if I change it moving to the next line or losing focus of the textbox will cause a save to the database?
How do I do that?
Comment: You have to use bootgrid formatter for adding the textbox inside table, and you should create a script to do your saving mechanism for losing focus. :)
Comment: Could you put that as an answer with a simple example? Thx
Answer:

            #
            Seçili

        @foreach (var item in Model)
        {

                @i

            i += 1;
        }

    $("#grid-keep-selection").bootgrid({
        formatters: {
            "commands": function (column, row) {
                return "<input type=\"number\" class=\"form-control\" name=\"txtSoru\" id=\"txtSoru" + row + "\" value=\"0\" min=\"0\" max=\"" + row + "\" />";
            }
        }
    });

bootgrid with editable textbox


How to display page loading time in drupal 7 for each page

Question: I want to display page loading time in every page in the footer. I can do this through some custom php script but want to know that is there any drupal way to achieve this
Answer: The Devel module will show queries and their execution time in the footer which will get you an idea of how long the page is loading.
Comment: @MdEqbalAhmad Yep - for _exactly_ the same reason you wouldn't put your load times at the bottom of the page on a production site - you'd use proper analytics software (think New Relic). You're either developing or you're not!
Comment: Well! For acheiving better page loading optimization the all heavy modules (specially devel module) is always remain disabled in production enviroment
Answer: This is a custom one line php script to display the page loading time in every page.
<?php
 printf('
Page loaded in %.3f seconds.
',  (microtime(TRUE) - $_SERVER['REQUEST_TIME_FLOAT']));

?>

put this at last line in html.tpl.php
Answer: In addition to Devel, the core statistics module has a report on pages taking the most time.
However, from your response to @ScottJoudry, I gather that you're not looking for a diagnostic tool, but something lightweight that just displays this data to entertain you and the site's users.
In that case, you need to roll your own PHP script.