Expected amount of increments of a base-4 number until it has 5 digits, when each digit has a 1/6 chance of being reset to 0

Question: Let's say I have a base-4 number $N$, with the initial value of $N = 00000$. The following function is applied to $N$ iteratively:

$N$ is incremented by 1 (i.e. if $N = 02033$, on the next iteration it will be $02100$)
Then, each digit has a 1/6 chance of being reset back to 0 ($03210$ might become $00210$, $03010$, $03000$, etc.)
Repeat.

On average, how many iterations will it take until $N$ becomes $10000$ (1024) after the first step of the function?
In case it helps at all with clarity, here is a JavaScript equivalent to this scenario:
const array = [0, 0, 0, 0];
function findRight(arr) {
    let index = -1;
    for (let i = 0; i < arr.length; i++) {
    if (arr[i] !== 3) {
        index = i;
        break;
    }
    }
    return index;
}
function next() {
    const val = findRight(array);
    if (val !== -1) {
        array[val] += 1;
        if (val !== 0) array[val - 1] = 0;
    } else {
        return true; // all digits are 3; N = 1024
    }
    array.forEach((val, index) => {
        if (Math.floor(Math.random() * 6) == 5) {
            array[index] = 0;
        }
    })
}

(Apologies if the formatting/writing of this question is strange; I just have no idea how to explain this in proper math format, so a bit of code-like syntax is mixed in. Any edits to make this question more clear or more "mathy" would be greatly appreciated!)
Answer: There are two main approaches here, and under the hood they'll both come down to very similar systems of equations. Either way, I'm going to swap the order of your two steps, so we think of one "turn" as a) possibly resetting some digits to 0 and then b) adding 1.
First, you could let $f(n) = $ expected turns until victory if you start with score $n$, and start writing equations involving values of $f$. For example, $f(0) = 1 + f(1)$ since if you're in state 0 you will always move to state 1. $f(1) = 1 + \frac{5}{6} f(2) + \frac 1 6 f(1)$ since after 1 step you have $\frac 1 6$ chance to reset your value and end up at 1 again, and otherwise you'd end up at 2. And so on. This will eventually give a linear system of 1024 equations and you could solve it to compute all the $f$ values. Then $f(0)$ is the answer you want.
Alternatively, you can view this as a Markov chain with 1025 states (from 0 through 1024) where the "10000" state is absorbing. If you build (or write code to build) that transition matrix, then the Wikipedia article I just linked provides a formula for the expected time until reaching the absorbing state. Note for runtime purposes: The formula involves inverting a matrix $Q$ and then multiplying $Q^{-1}$ by a vector of all 1s. Inverting a $1025 \times 1025$ matrix may take a little while depending what solver you're using. Instead of computing that inverse, you could view this as solving a linear system like $Qx = $(vector of all 1s), which can be solved much faster than fully computing $Q^{-1}$.
I don't know whether you're hoping for an exact (fraction) answer vs whether floating point precision is good enough for you, so I won't go further into implementation details. If I were solving this and I wanted an exact answer I'd use Mathematica; if I wanted a floating point answer I'd use Python.
For problems of this type, we could normally at least get a not very accurate floating point answer much more easily, just by actually simulating the process a bunch of times and averaging the result. Unfortunately that doesn't work for this problem because the typical length of one game is so long that you may not even be able to simulate a single full game.
EDIT: Exact answer and implementation
In the question, OP stated: "until N becomes 10000 (1024)". Those numbers don't match up: 10000 would be 256. This makes me not sure whether they meant 10000 (256) vs. 100000 (1024), so I'll include both answers. I'll give the exact answers as fractions just so you can compute more decimal places on the approximations if you want.
For the case where we count up to 10000 (state 256), the answer is
$$\frac{399133152090263798547275810543929312656142607992620861180133849347900262273754411261298344932889461431684886365835989699995774143723698586853636562275485685037972443082743099909180178510859768240848030490764236712524498516633924676371154504435198888483674168096706303551884261740641455076970582573137341225096881125208741956251788936041104456847354920594579981542374188762515921164989173186499638395623887695308088079005239108382609367590084940057842559356576274701464339090526846087258769900599300646141837035853769421179528841696271382585325743321817493675959458354318001076191959964304601}{644114876959713330822703650336885250520481331443965633584307570993229323626932756036964628972522561260668856218084914667149474722719046257464573459045222137454532953759080605088049278870725910028634380270567174784034802342593206960279969607058553576679307732915217675557931021411215816397236838071898745173884690323577135426648799114768526685244835066509405979977223259685362507168686533456482953943779752922755991991988237792160551359607713702272919367243410144597503677298931451300659543763292048945690027039745473302900791168212890625}$$
or approximately $\boxed{6.197 \times 10^{53}.}$
For the case where we count up to 100000 (state 1024), the answer is even bigger! It's
$$\frac{6327062043854864349490533490775065161766252759298440924496738600000275381712466248096235866756883208444457339775361821129155380965549001060041268860914310793891336362235685316536583917723154807529143379937090258118909872991475682654059807923312020283347055933474181146832379436341018611257277536338307387632085955301590034338252933189667627230367180082881968036483363797441820592401498562418868069562814863760237771034817219903764733204927919963337432735522272206501808452521918354755014670359961514214771351176963753085674450848289787324723262626854509146611336662374744296915328358754177209637586228696517188345942107257858693907663792123685216711315135673809260983585045291409902293097323605753341126813570939465233717676449935382047755727755730807707103021771324473375795697082039107645416457094238517678941590521538452745524788646553647071954490226438609593840339804453656896577905749099810492750716430222154263911287694696980769274891712129634070087307850760582186459149540993838247984789761980605160507196824922256000140416632395514317825732901015012352472611699871755054119008956640040746640264819206814364827986610641138146697711542665419780141104602615683208943774019973927469498542324731331492470219996336221913575707771320624431213030925377883539013665692821467531341236483870605530877839656768636195303668509010950588619196704868773905403532690826735016129132108594813717244683499386492781407119658634027584453963775374500774039784456075281964304070012142180021100994294460021947140236102594422703112980278653887797348099042588581829202902027866990327650318965776720875534193056844621388769323470109511385014661607728071307523039152624162866736806173435359602082386625177894665808436165280432900615191223161489309557652867541592589487241361847095022672048267468510194191342203600214699288356916901261750710035531038440336901075885174846575030237800305350936641864709888982819843994883231405984598432054496120930995224635203854785855785343842350272027466304128152824155620196882555992497416054896800501586320741075139268007215611950626425803697506758865929113590521105846941639500679725244287209512441134782649133941426061131269295453840132698595079084579498580712084554171977574934424652189415990220234243540035040366611459648097446100293159819500678263454496348381237602976952690724064689402172870371364881647012056056381759850594080862166102853118830547404561367673360937744685314701469280387684812381991372590158780726960429057864133531094509449801174656991144166792012356815976041000497280395613920187723015585951766817292741837327637038815181297350953869042097025763157294536544505950839477864893173395565582385657257583002701037651928484074531025075319938761833321531223123557009931795885770958825675171603639341319974585898575009423975338418975275541433920005120489379752556604089416793569368095330322960186463924484371764220806563708369289704210492589042370542619468064294566105313538625356873410031565388169432345425607121977651048281271748371}{110870664460386669401148107528716844199483478539697735775314489588277341473540810508071241213432970834293163741131052295414359445765475494383015341602105474898916797535252132162562253896891890932970680613176120095672183211459748561093828941125651420210458360860300431522878564355560714450041106779035406515939842811954585662117919808325285384086883606846242868326545195353209189664923123037968598669436576513961470320049698936131671479467923703846123174987660987673026519936040191458431124483539930967788648920159159880020905061745603105037649290382813682294673795616228623543963273332503757072694958271477566541003899114604853597333492876765002482510448071851388634582727285459341983242200249677213884394442494999450740895304478485387063984685364575781294593081983111974333825676368502703248301230452091306293845791820014878407234945192770606438613643366184551784275182321716698845716400242315944464444737544027915055945652589029768438589570004942828360885471512909827230119199379136448535654681099622593937852669427035825102773229333593215297011002430525095973394022966357545955937239472721073596602250153491338714888871470939171863318702271495564075747650443780710418851143863363517862876563089799904308352217597219226812358586799708644833907078618419981078680522489837541792454436430521776461061356177123584173939412109940212122326064655559697195766979541250360315795361723273451766887253415181851365749310676269595503787830816660869879548819800761461374773740531135589295961560574191823251607105553234589685188193801804435369634144128491033394158802875427278291158262996257834933851457685220734960953695338136080800943089498374684052719038361209467707009067372906954095179890278316735366834770089066135641826183070300795666069035527007369025976320289562001905299390570711364887047136534065276929886709343657143505536761280543681719516646792313644730154905127726926249936843552661597596276272805170773001392512542024354800388837472305178204632073845923843206663783454961014056302075843758520624203943707909128966362555429165274139223793574086213642043885923343473815168354730808358888656038606592978242659871768311176856639941055275858134620100419899571318780928150704632653744028210480066343312937542971779285540761680084459314815975321843310659886594597113464457932411213164134059264679758527614689449127230167179922244964200293456172313393380880068614658637774360686443607106603643862994850927847696069869521709273436118306533278118383923389244769184872562729339863089453296660913336709517537430992528747444164582973155734969460273365182660299044837586675095224365235080429002799077737021011496973502024108959935929378281979983432298784463976293324094513081945478916168212890625}$$
or approximately $\boxed{5.707 \times 10^{280}.}$
Here is the exact Python code I used to build the transition matrix and dumps it to disk:
import itertools
import copy
from fractions import Fraction as frac

def build_transition_matrix(N, B):
    def sid_to_state(n):
        out = []
        for k in range(N):
            out.append(n % B)
            n //= B
        out.reverse()
        return out, n

    def state_to_sid(q):
        return sum(B**k * q[N-1-k] for k in range(N))

    D = B ** N + 1  # dimension
#     mat = np.zeros((D, D))
    mat = [[frac(0) for k in range(D)] for j in range(D)]

    # handle the last state separately.
    mat[D-1][D-1] = frac(1)
    for sid in range(D-1):
        state, leftover = sid_to_state(sid)
        for revert in itertools.product(range(2), repeat=N):
            curr = copy.deepcopy(state)
            p = 1
            for k in range(N):
                if revert[k]:
                    p *= frac(1)/6
                    curr[k] = 0
                else:
                    p *= frac(5)/6
            # increment the state.
            curr[-1] += 1
            carry_pos = N-1
            while curr[carry_pos] == B:
                curr[carry_pos] = 0
                carry_pos -= 1
                if carry_pos < 0: break
                curr[carry_pos] += 1
            if carry_pos == -1: new_sid = B**N
            else: new_sid = state_to_sid(curr)
            mat[sid][new_sid] += p

    # convert to strings.
    sout = []
    sout.append('dat = {')
    for q in mat:
        scurr = ','
        if len(sout) == 1: scurr = ''
        scurr += '{' + ', '.join(str(x) for x in q) + '}'
        sout.append(scurr)
    sout.append('}')
    sall = '\n'.join(sout) + '\n'

    # dump for mathematica.
    with open('mathdat.dat', 'w') as f:
        f.write(sall)

    return

# build_transition_matrix(4, 4)
build_transition_matrix(5, 4)

and here is the Mathematica code I used to load that result from disk and then solve the system of equations:
ToExpression[ReadString["mathdat.dat"]];
Q = dat[[;; -2, ;; -2]];
Ninv = IdentityMatrix[Length[Q]] - Q;
v = Table[1, {k, 1, Length[Ninv]}];
out = LinearSolve[Ninv, v];
out[[1]]
out[[1]] // N

Comment: @Lemondoge Done, see the new section I've edited into the bottom of my answer.
Comment: I'd be happy with just about any level of precision, even just order-of-magnitude; if possible, could you please run a calculation for this / provide an estimate?
Answer: Calculate the expected number of moves for the lowest digit, starting at 0, to change from 3 to 0.
Calculate the expected number of moves until the second digit changes from 3 to 0. That will be a large number, because the first number has to change from 3 to 0 four times without the 2nd digit changing to 0. That might be a three digit number.
Then the third digit - that will take ages to change from 3 to 0 because it must survive a few hundred moves without being changed back to 0.
The fourth digit will take a massive time. If you simulate it, it's unlikely to succeed in your lifetime.
Comment: I've already tried finding the average with JavaScript via brute force, and the 3 digit case alone takes too many iterations to simulate once, let alone multiple times.


Reading Apache error log from PHP

Question: I want to read the apache2 error log file from PHP (it is currently owned by the www-data user)
Is it safe to change the owner of this file, or to give it less restrictive permissions ?
Answer: The reason the default configuration is to restrict access to the error log is that it can contain sensitive information regarding either your configuration, or records of warnings/errors that contain usernames, passwords, database connection strings etc.
Allowing the webserver itself (read-only) access to that error log increases the risk for unauthorized access to such information.
But only you can do a risk analysis and judge if the benefits outweigh the risks.
Comment: I know it's raise up security issue.
If I do change permission, what is going to happen with the log rotate ?
Comment: Unless you take specific measures, the log files get re-created after rotating them by reloading the apache server. That results in  them getting default permissions. A `create 0123 username groupname` will create the new log files with specific permissions and owner before running the post rotate script, allowing you to override apache defaults.

Reading Apache error log from PHP


How do you Set cookie to remember open tab? Tabs are created with Coldfusion & Javascript

Question: This is probably more simple than I'm making it but I just can't figure out how to do it. What I've got are tabbed sections created in Coldfusion. The output is that the selected section has a class name that contains the string "tab_selected (+ the UUID created in coldfusion)" versus the unselected tab sections whose class names contain the string "tab_unselected (+ the UUID created in coldfusion)". When you click on the unselected tabs the class is changed to "tab_selected (+ the UUID)" and all the other tabs are set accordingly.
What I'm attempting to do is, using javascript, when you exit the page it searches for the element that has the class that contains the string "tab_selected" and then sets the cookie with the id of that element...
This is all I have at this point (in JQuery)...And it could be terribly wrong. Please help.
<code>        $(window).unload( function () {
        $("selector[name*='tab_selected_text']").cookie("TABS_REMEMBER", 1, { expires: null });
        });
</code>
Answer: Since you're using jquery and its cookie plugin, it's very easy and automatic.
When you declare your tabs use this:
<code><script type="text/javascript">
  $(function () {
    $("#tabs").tabs({
      cookie: {
        // store cookie for a day, without, it would be a session cookie
        expires: 1
      }
    });
  });
</script>
</code>
It will cause to tabs component memorize the last used tab.


First / Last child for margin not working in the Next.js, Tailwindcss environment

Question: The same thing happened with this github issue.
https://github.com/tailwindlabs/tailwindcss/issues/1930
First / Last child for margin not working in the Next.js, Tailwindcss environment.
<code># not working
mt-4 first:mt-0
</code>
I would like to know the solution.
thanks.
Comment: Did you enable the `first-child` variant for `margin` like it's mentioned in the GitHub issue you linked?
Comment: You are required to post a [mcve] here, **within your question**, and [not a link](https://meta.stackoverflow.com/a/254430/162698) to any other site.
Comment: I added it, but I couldn't.

I decided that the current version of Next.js and Tailwindcss do not mix well, so I gave up.
Answer: you could try using the space-y utitlity class


Is there a token I can use to display a node's view mode?

Question: I am trying to use Rules to send an email with the results of the submission of a node. Is there any way to place the entire contents of the node using a token?
<code>e.g. [node:teaser]
</code>
Answer: Look at the Advanced Entity Tokens module.

Advanced Entity Tokens (AET) Creates a Token for each of your entity
  items.
Through AET you can query the DB for entities using Tokens.
Examples

[aet:node:1] will return the 1st node with the token view mode (or
  full if token is not available).
[aet:file:1:view-original] will
  return the 1st file entity with the original view mode.
[aet:taxonomy_term:1:name] will return the 1st node title field (note
  that this level of chaining is done by the formal token implementation
  of the node entity in token/token.tokens.inc -> token_token_info()).

Real World Examples

Displaying a node inside a block: This could be done using Node Block
  OR you could insert a token inside a block you create through the
  Blocks interface that retrieves a certain node (or a property inside a
  node, [aet:node:] or [aet:node::body]) with no extra code.
Displaying a File Entity (image) inside a title field: I'm not sure
  how this could have been done without custom code, BUT with AET you
  could easily insert the Token for a specific File Entity
  ([aet:file:]) and your entity will be displayed. AET defaults to
  the Token view mode if available (full otherwise), but you could just
  as easily specify a view mode of your own
  ([aet:file::view-teaser]).
I'm saving this spot for real life
  examples other Drupal users had (or thought of having) for this
  module.


Storage Error - First Depth Search Algorithm

Question: I'm currently working on a algorithm which should solve a 3D puzzle.
However I've encountered a problem, the algorithm I use is a First Search Depth and it seems to be working well until I get "raised STORAGE_ERROR : EXCEPTION_STACK_OVERFLOW". I'm not quite sure why it is not working. Any guesses to why this isn't working?
What I want this algorithm to do:
It takes a List, a figure, and a goal. For this example the list is 7 parts long. It tries to enter the part in the first coord. If it doesn't fit, it rotates until it does fit, it then calls on it self with the rest (6 parts). If the part rotates all 24 ways (all possible ways to rotate a 3D part) then it moves to another coordinate and starts again with trying to fit. When all the parts are gone or nothing works it should just quit and I have another algorithm that sends in the same list with another order into this algorithm.
I would also like the algorithm to see if the last coordinate doesn't match with the Goal then it should just backtrack and try to find another solution.
Here is some of the code:

procedure Pseudo(Parts : in out List_Type; Figure : in out Figure_Type; Goal : in out Figure_Type; LastCoord : in out Integer) is
        Unchanged : Part_Type := Parts.Data;
        Next : boolean := False;
        UnchangedFigure : Figure_Type;
    begin
    UnchangedFigure := Figure;
        if Empty(Parts) then
            raise Finished;
        else
            for I in 1..24 loop
                RotNumber(Parts.Data,I); -- rotera
                if Check(Parts.Data,Figure) then -- test om den platsar
                    Maincheck(Parts.Data,Figure,Goal,Next);
                    if Next then
                        Unchanged := Parts.Data;
                        Append_Part(Parts.Data,Figure);
                        Remove_First(Parts);
                        Next := False;
                        Pseudo(Parts,Figure,Goal,LastCoord);
                        Next := False;
                        Figure := UnchangedFigure;
                        Insert_First(Unchanged,Parts);
                        Figure.CoordX := 0;
                        Figure.CoordY := 0;
                        Figure.CoordZ := 0;
                    end if;
                end if;
                Parts.Data := Unchanged;
            end loop;
        end if;
        -- if LastCoord /= 7 then --(Original
            -- if To_String(Figure.Data)(LastCoord) /= To_String(Goal.Data)(LastCoord) then
                -- Put("over");
                -- return;
            -- end if;
        -- end if;
        LastCoord := Figure.CoordZ*Figure.X*Figure.Y + (Figure.Y-Figure.CoordY-1)*(Figure.X) + Figure.CoordX +1;
        if Figure.CoordY < Figure.Y-1 then
            Figure.CoordY := Figure.CoordY +1;
            Pseudo(Parts,Figure,Goal,LastCoord);
        elsif Figure.CoordY = Figure.Y-1 then
            if Figure.CoordX < Figure.X-1 then
                Figure.CoordX := Figure.CoordX +1;
                Figure.CoordY := 0;
                Pseudo(Parts,Figure,Goal,LastCoord);
            elsif Figure.CoordX = Figure.X-1 then
                if Figure.CoordZ < Figure.Z-1 then
                    Figure.CoordZ := Figure.CoordZ +1;
                    Figure.CoordX := 0;
                    Figure.CoordY := 0;
                    Pseudo(Parts,Figure,Goal,LastCoord);
                elsif Figure.CoordZ = Figure.Z-1 then
                    return;
                end if;
            end if;
        end if;
    end Pseudo;

Comment: Just off the top of my head, I'd suggest you verify that your recursion is properly terminating. Out of control recursion is a trivially easy way to blow the stack and raise a Storage_Error.
Comment: Hello, I think you were right, it was probably a infinite recursion somewhere. However I'm still not quite sure if it works as intended due to the insane amount of possible "branches".
Comment: @user2207734, you need to review the way you are branching then
Answer: First, do not use exceptions to control program flow, it's bad practice. Consider using an additional out parameter instead of raise Finished.
I think it's also an error to declare all parameters as in out. Look at Parts: In your loop, you append the figure to its Data member, then remove the first element of the list. After that, you call Pseudo which will mangle with the list again, and if it doesn't succeed, Parts will possible have entirely different contents than before the call. You restore the first element after that, but whatever Append_Part does stays permanent. I cannot tell for sure if this is actually a problem. The effort to restore the list and the figure after the call to Pseudo is also an obvious sign that you do not want these parameters to be in out.
Another thing that looks fishy is that after the loop, you change the coordinates of the figure and then call Pseudo again - which will reset the coordinates at the end of its first iteration to 0 (if conditions match). A possible control flow will be:

Pseudo starts, Parts is not empty. Loop starts. Let's assume that the figure's Coord values are initially 0.
No iteration of the loop leads to Finished. Loop ends.
The algorithm changes some coordinate and calls Pseudo. Let's assume for now that Parts still has the same value as it had when Pseudo was called the first time. As I wrote, this does not seem to be the case, but it should be if I understand your description correctly.
The second call to Pseudo it identical to the first one, except that some coord of the figure differs (and possibly Last_Coord, which doesn't seem to matter).
Parts cannot be empty, loop starts.
Now let's assume that at some point in the loop, conditions match, but the call to Pseudo fails (as in "doesn't raise Finished"). Coordinates will be reset to 0.
From there on, the execution is identical to that of the first Pseudo call, because the data it operates on is now identical. So no Finished will be raised in the loop, and after that, Pseudo will be called a third time with exactly the same parameters as before.

As you see, this will lead to an endless recursion. I cannot tell for sure if this can happen because I don't know anything about your types or the subprograms you call.
In its current condition, your code is hard to understand because it has a very complex control flow. If you take away some of your code's complexity, it will be easier to track down errors. I suggest using loops to iterate over the coordinates rather than recursion. This may solve your problem.


Avoiding repetition in R

Question: Here is a typical problem that I have:
replace_letters <- function(string){
  gsub("x", "a", string)
}

string_x_new <- replace_letters("string_x")
string_y_new <- replace_letters("strxng_y")
string_z_new <- replace_letters("xstring_z")
...

Meaning that I'm writing a function (the function in the example is arbitrary) and then I want to apply that to an arbitrary set of objects. What is a neater way of doing this without having to repeat the function multiple times (sometimes I have long lists of 10-15 calls to the same function for different objects)?
Comment: Why are the objects not in a vector?
Comment: Because I'm a noob. Care to illustrate?
Comment: `chartr('x', 'a', strings)` using `strings` in @CactusWoman 's answer
Answer: Put your strings in a vector using c("string_x", "strxng_y", "xstring_z") then use an apply function
Example:
strings<-c("string_x", "strxng_y", "xstring_z")

replace_letters <- function(string){
  gsub("x", "a", string)
}

strings <- sapply(strings, replace_letters)

Comment: `gsub("x","a",strings)` also works (though your answer illustrates an approach that will work more generally).
Comment: Yeah, but I think the asker was looking for a more general answer. That works for gsub but not for all functions
Comment: @Frank, @CactusWoman: yes, `gsub` is not the point of the question, rather how to avoid calling functions multiple times manually
Answer: You can create a vectors of the objects you'd like to apply the function to. Let's take your example:
new.strings <- sapply(c("string_x", "string_y", "string_z"), replace_letters)

Answer: You can make use of R's vectorization:
strings<-c("string_x", "strxng_y", "xstring_z")
replace_letters(strings)
## [1] "string_a"  "strang_y"  "astring_z"

Comment: does this mean that the `sapply` proposed by others is unnecessary?

Avoiding repetition in R


How to do this guitar technique?

Question: I'm a beginner, what is the name of this technique?

Can someone tell me how to do this ? Actually, I've an idea, but it's not working, so I don't know if I'm right or not.
Comment: Is this a piece that is to be played with a bottle neck?
Comment: So, what is your idea?
Comment: It come from https://www.songsterr.com/a/wsa/albert-gyorfi-the-scientist-tab-s402338t0
Answer: Looks like a slide up and down to me, but from 0 fret to 2 and back to 0 isn't easy. So, it , being legato playing, might be a hammer on and pull off. On 3rd string, play open, then hammer on to 2nd fret, then pull off, using the fretting finger, back to open note.
Comment: The notation certainly calls for a slide and not hammer-on/pull-off. Slides from open strings are common in playing with bottlenecks. I have never seen it elsewhere though, hence my question above.
Comment: It's totally hammer on and pull off: https://www.youtube.com/watch?v=bhD9wjuw33E
Comment: It would explain why I'm not able to do it if it's not so easy. :/
Comment: It doesn't sound like a slide to me. Hammer and pull off .

How to do this guitar technique?


Service is being killed by Os when app is finished, How can I avoid to this

Question: My service is being killed by os when I kill application which I don't want . I want to run background service for some job. Please guide me how can I do this.
Here is service class code:
public class MyThreadClass extends Service {
    Handler handler;
    Runnable runnable;
    private static final String TAG = "MyThreadClass";
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        handler=new Handler();
      runnable=new Runnable() {
       @Override
       public void run() {
           Log.d(TAG, "run: Runnging in Background");
           handler.postDelayed(this,1000);
       }
   };
   handler.postDelayed(runnable,1000);
   return START_STICKY;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: Called");
        //handler.removeCallbacks(runnable);
    }
}

manifest declaration :
<service android:name=".MyThreadClass"></service>

please guide me how can I run my service on background properly thanks
Comment: Are you Having Target API level version higher than 26? if yes then it is compulsory to make service in the foreground because the system imposes restrictions on running background services when the app itself isn't in the foreground.
Comment: I didn't code for startForground because I don't know too much about service I am new one to android
Comment: Please check this link - https://stackoverflow.com/questions/9740593/android-create-service-that-runs-when-application-stops
Comment: yes I am targeting API 27 but does it mean I can't use service for background job?
Comment: I need unending background service  but when I need to stop, I can stop through any button something like that
Comment: There is no longer such a thing as an unending background service. Either make it a foreground service or switch to jobs.
Comment: Then how can I check my nearby locations around after 5 minutes when I am travelling please suggest something
Answer: You can use CountDownTimer, below is the code for same, hope it helps.
public class MyThreadClass extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        CountDownTimer countDownTimer = new CountDownTimer(5000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                //calls after every 500ms
                // do something
            }

            @Override
            public void onFinish() {
                //calls after finishtime 5000ms
                //do something
            }
        };
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: Called");

    }
}


PHP: cant insert a value of 0 (zero)

Question: hello guys I have a problem when I am inserting with a value of zero.
when I am trying to insert a zero value in [score] field it returning me with this result

additional info:
the data type of [score] field is int
and here is my code:
<?php

    require("config.inc.php");
    if(!empty($_POST)){

            if(empty($_POST['quiz_list_id']) || empty($_POST['stud_name']) || empty($_POST['score']) || empty($_POST['term']) || empty($_POST['quiz_date'])){
                $response["Success"] = 0;
                $response["Message"] = "Please complete all fields.";
                die(json_encode($response));
            }

            $query = "SELECT 3 FROM tb_quiz WHERE quiz_list_id = :quiz_list_id AND stud_name = :stud_name AND term = :term";
            $query_params = array(
                                    ':quiz_list_id'=> $_POST['quiz_list_id'],
                                    ':stud_name'=> $_POST['stud_name'],
                                    ':term'=> $_POST['term']
                                    );

            try{
                $stmt = $db->prepare($query);
                $result = $stmt->execute($query_params);
            }
            catch(PDOException $ex){
                $response["Success"] = 0;
                $response["Message"] = "Database Error. Please Try Again...";
                die(json_encode($response));
            }

            $row = $stmt->fetch();
                if($row){
                    $response["Success"] = 0;
                    $response["Message"] = "I'm sorry, this Record is already existed.";
                    die(json_encode($response));
                }

                $query = "INSERT INTO tb_quiz (quiz_list_id, stud_name, score, equivalent, term, quiz_date) VALUES(:quiz_list_id, :stud_name, :score, :equivalent, :term, :quiz_date)";
                $query_params = array(
                                        ':quiz_list_id'=> $_POST['quiz_list_id'],
                                        ':stud_name' => $_POST['stud_name'],
                                        ':score' => $_POST['score'],
                                        ':equivalent' => $_POST['equivalent'],
                                        ':term'=> $_POST['term'],
                                        ':quiz_date'=> $_POST['quiz_date']

                                      );
            try{
                        $stmt = $db->prepare($query);
                        $result = $stmt->execute($query_params);
                }
                catch(PDOException $ex){
                    $response["Success"] = 0;
                    $response["Message"] = "Database Error1. Please Try Again...";
                    die(json_encode($response));
                }
                    $response["Success"] = 1;
                    $response["Message"] = "Quiz Successfully Recorded.";
                    echo json_encode($response);

    }else{
?>

        <form action="addQuiz.php" method="post">
        Quiz List: <input type="text" name="quiz_list_id">

        Stud Name: <input type="text" name="stud_name">

        Score: <input type="text" name="score">

        Equivalent: <input type="text" name="equivalent">

        Term: <input type="text" name="term">

        Date: <input type="text" name="quiz_date">

        <input type="submit">
        </form>
        <?php
    }

?>

Answer: empty() function consider zero empty, so it return TRUE.
The following things are considered to be empty:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

here is fixed code:
you can use this condition:
$_POST['score'] == ""

Here is the full code
<?php

    require("config.inc.php");
    if(!empty($_POST)){

            if(empty($_POST['quiz_list_id']) || empty($_POST['stud_name']) || $_POST['score'] == "" || empty($_POST['term']) || empty($_POST['quiz_date'])){
                $response["Success"] = 0;
                $response["Message"] = "Please complete all fields.";
                die(json_encode($response));
            }

            $query = "SELECT 3 FROM tb_quiz WHERE quiz_list_id = :quiz_list_id AND stud_name = :stud_name AND term = :term";
            $query_params = array(
                                    ':quiz_list_id'=> $_POST['quiz_list_id'],
                                    ':stud_name'=> $_POST['stud_name'],
                                    ':term'=> $_POST['term']
                                    );

            try{
                $stmt = $db->prepare($query);
                $result = $stmt->execute($query_params);
            }
            catch(PDOException $ex){
                $response["Success"] = 0;
                $response["Message"] = "Database Error. Please Try Again...";
                die(json_encode($response));
            }

            $row = $stmt->fetch();
                if($row){
                    $response["Success"] = 0;
                    $response["Message"] = "I'm sorry, this Record is already existed.";
                    die(json_encode($response));
                }

                $query = "INSERT INTO tb_quiz (quiz_list_id, stud_name, score, equivalent, term, quiz_date) VALUES(:quiz_list_id, :stud_name, :score, :equivalent, :term, :quiz_date)";
                $query_params = array(
                                        ':quiz_list_id'=> $_POST['quiz_list_id'],
                                        ':stud_name' => $_POST['stud_name'],
                                        ':score' => $_POST['score'],
                                        ':equivalent' => $_POST['equivalent'],
                                        ':term'=> $_POST['term'],
                                        ':quiz_date'=> $_POST['quiz_date']

                                      );
            try{
                        $stmt = $db->prepare($query);
                        $result = $stmt->execute($query_params);
                }
                catch(PDOException $ex){
                    $response["Success"] = 0;
                    $response["Message"] = "Database Error1. Please Try Again...";
                    die(json_encode($response));
                }
                    $response["Success"] = 1;
                    $response["Message"] = "Quiz Successfully Recorded.";
                    echo json_encode($response);

    }else{
?>

        <form action="addQuiz.php" method="post">
        Quiz List: <input type="text" name="quiz_list_id">

        Stud Name: <input type="text" name="stud_name">

        Score: <input type="text" name="score">

        Equivalent: <input type="text" name="equivalent">

        Term: <input type="text" name="term">

        Date: <input type="text" name="quiz_date">

        <input type="submit">
        </form>
        <?php
    }

?>

Comment: @Burki Thank you, I will explain it.
Comment: I think an explanation why your code works and the original doesn't (i.e. what was wrong) would amke your answer mcuh better.
Answer: All variations of 0 - both 0 as integer and "0" as string are considered empty.
So empty("0") will return true. In your case I suppose you'd better compare your values with "" (empty string)
if ($_POST['score'] != "") // for example

Answer: You have used empty() to check $_POST['score'] and its definition is -

Determine whether a variable is considered to be empty. A variable is
  considered empty if it does not exist or if its value equals FALSE.
  empty() does not generate a warning if the variable does not exist.

You should use isset() instead of empty() or use parameter as string like below :
empty("$_POST['score']")

PHP: cant insert a value of 0 (zero)


How do I manage select options on a multi page webform?

Question: With a multi-page webform.

Page 1: choose country
Page 2: choose industry
Page 3: choose from a list of people that support the country and industry.

#validate handler added
<code>$form['#validate'][] = '_cbifasttrackcert_webform_validate_sector_country';
</code>
Adding the items to the list
<code>$verifier_options = $verifierHandler->formatVerifierOptions($verifiers);
$form['#node']->webform['components'][$choose_verifiers_cid]['extra']['items'] =
$verifier_options;
$form_state['webform']['component_tree']['children'][$choose_verifiers_cid]['extra']['items'] = $verifier_options;
</code>
Which is fine throughout the form, the values don't get submitted as there is a check that values are in the node list.
The challenge is to email a response based on the values, as only $submission is available.
When submitting a webform, node_load is used to load a clean version of the options in select.inc. These options are used to check whether any valid options have been submitted, with options not in the list being discarded.
web/sites/all/modules/contrib/webform/components/select.inc has _webform_select_options() with options to provide a callback or filter based on a token.
I'm not sure how to access form_state using either of these options? Similarly hook node_load does have form_state to allow the options to be discovered?
How to filter a select list based on a token? How to load the form data in a callback?
Answer: The secret is to load all the possible responses in hook_node_load. They are a valid choice, even if submitted. I made it an associative array so that the indexes don't change.
<code>function module_node_load($nodes, $types) {
  $choose_verifier_no_verifier_cid = webform_get_cid($webform_node, MyModuleHelper::CHOOSE_VERIFIER_NO_VERIFIER_WEBFORM_KEY)[0];

  $verifier_options = MyModuleHelper::chooseAllVerifiers();
  $webform_node->webform['components'][$choose_verifiers_cid]['extra']['items'] = $verifier_options;
  $webform_node->webform['components'][$choose_verifier_no_verifier_cid]['extra']['items'] = $verifier_options;
</code>


(direct) sum vs span of subspaces

Question: Is there a difference between the span of subspaces and the sum of them in linear algebra?  They both seem to just be the set of all linear combinations.
Answer: The sum of linear subspaces is again a subspace (state the proof!). As you pointed out, this resulting subspace is precisely their span, i.e. for a vector space $V$ and subspaces $U_1,\dots,U_r \subset V$ with $r \in \mathbb{N}$ the following holds:
$$
\operatorname{span}(U_1 \cup \dots \cup U_r)
= \sum_{i = 1}^r U_i
= \left\{\sum_{i=1}^r b_i : b_i \in U_i\right\}.
$$
As a matter of fact, every subspace $U \subset V$ generates itself, i.e.
$$ \operatorname{span}(U) = U. $$
EDIT: As @ErikWong pointed out, the above equality may lead to conflicts with the definition of direct sums if you consider the direct sum of an arbitrary family of subspaces $(U_i)_{i \in I}$. On the one side the span of the elements of this family, $\operatorname{span}_{i \in I}(U_i)$, will always be well defined, whereas on the other side, in order to be allowed to construct the direct sum, you additionally have to assure the linear independence of all involved subspaces.
Comment: Yeah, the [direct sum](http://en.wikipedia.org/wiki/Direct_sum) is also defined in terms of sums of _finite_ subsets, so the two definitions are compatible.  It depends a little on whether the OP really means direct sum.  If the $U_i$ contain linear dependencies, I'd avoid calling it the direct sum of subspaces because it conflicts with the notion of direct sum of vector spaces.  But it would still make sense to talk about their span.
Comment: Would be nice to also address the case of $\{U_i : i \in I\}$ where $I$ is an infinite index set.
Comment: Thanks for the observation. I think the statement about the union of subspaces will continue to hold for arbitrary unions. However, I'm not sure about how the sum of a family of subspaces $\left(U_i\right)_{i \in I}$ would be defined, as the span of a subspace is defined as a finite linear combination. Maybe something like this: $\sum_{i \in I} U_i := \left\{ \sum_{j = 1}^r b_j : b_j \in U_{i_j} \text{ for } i_j  \in I \right\}$?
Comment: @ErickWong: I edited the post trying to reflect the point you made.
Comment: do you happen to have a link to proving the above statement? thanks
Comment: @jamesblack No. It just made (and still makes) sense, therefore I did not spend time researching it. Is there anything unclear from the post?

(direct) sum vs span of subspaces


Como organizar o desenvolvimento de um projeto

Question: Pergunto de maneira bem abrangente aplicado tanto a Desktop quanto Web, se for muito diferente os métodos, peço que me orientem.
Possuo alguns clientes, e com o passar de alguns meses, vejo que ao crescer dos projetos (Tanto web quanto desktop) fica difícil de outros trabalharem no mesmo projeto, e difícil até para mim me encontrar e me organizar no próprio projeto.
No caso do WEB: Como dividir o arquivos php, jquery e html nas pastas e subpastas? E como documentar algo do tipo? Existe documentação?
No caso do Desktop: Como dividir o banco de dados, das validações e da programação daquele determinado formulário?
Pois bem, gostaria que me dissessem quais são os passos para uma perfeita organização e desenvolvimento de um projeto. Seria o UML? Apenas isso bastaria?
Comment: UML é uma linguagem visual para modelar diversos conceitos ou processos de uma aplicação. Não é necessário para a organização de um projeto, é apenas uma forma de duas ou mais pessoas conseguirem botar seus pensamentos de nível mais baixo sobre desenvolvimento no papel.
Comment: Se o software a ser desenvolvido cresceu então é conveniente você estudar o SWEBOK (Guide to the Software Engineering Body of Knowledge) http://www.computer.org/portal/web/swebok. Se você tem uma equipe então tem um projeto e precisa das técnicas de gerenciamento de projetos como o conjunto de práticas descritas no PMBOK (Project Management Body of Knowledge) da PMI (Project Management Institute).
Comment: Não estou pedindo opinião. Estou querendo saber que meios, que programas, que padrões podem ser utilizados para ter um projeto organizado onde qualquer programador novo que entre na empresa consiga entender e tocar o projeto adiante, ou até, eu mesmo consiga facilmente fazer manutenção sem ficar extenso e complicado. O único meio que já ouvi falar foi UML e aparentemente não é essa a proposta dele, pelo que li no comentário acima.
Answer: MVC
Uma prática amplamente adotada no mercado atual é a utilização do modelo MVC (Model-view-controller).
Basicamente você separa seus arquivos em pastas diferentes, separando a camada de visualização/apresentação (html, js, css), da camada de negócios (banco de dados, lógica de negócios), da camada de controle, que faz a ponte entre a camada de negócios e apresentação.
Frameworks
A utilização de frameworks full-stack tabém facilita e muito na organização dos projetos, já que os mesmo já vem modelados utilizando todos esses conceitos.
Tente usar um framework e observe sua estrutura.
Em php, aconselho o Yii ou Laravel.
Rails tem ditado muitas tendências em relação a organização dos frameworks, além de ter uma comunidade muito ativa, que está sempre tentando resolver esses tipos de problemas, convido você a conhecer também.
Como você citou problemas com validações, segue o link de como o Rails encara as validações de formulários.
Comment: Queria adicionar o Framework Cakephp, aconselho bastante.
Comment: +1 para o Laravel, se não for possível usar o Rails.


Sorting in Filed Collection Views

Question: I am using Field Collection Views in Drupal and everything works fine, except Sorting. I am able to rearrange the Field Collection items in Edit form using both drag-and-drop also manually using Row weights option.
I would like the the Field Collection View results to be sorted by this Row weight, could you please guide how I could acheive this.
Answer: This could be achieved by creating a relationship, and using Delta to sort. Let us say that the field collection field's name in the entity is field_slides.
Create a relationship with 'Field collection item: Entity with the Slides (field_slides)'. Check the box for - Require this relationship
Comment: This worked for me. I created a relationship for the field collection first, then created another relationship with the individual field collection field.
Comment: +1, after creating the relationship, it does the magic. I did not need to add the sort criteria. Adding sort criteria shows duplicate record for me as delta for that field collection field is different for a same record.
Answer: Found a very easy workaround via DraggableViews module and it works just fine.. the step-by-step instructions could be found here..
Custom Sort Drupal Content with the Draggable Views Module
Thanks to the Author - Kronda Adair. :-)

Sorting in Filed Collection Views


Batch file left string trim not working

Question: huge newbe.
I have two batch files that are working but when i try to combine them it fails.
First batch file searches a directory and copies file names as a variable...
@echo off
setlocal disableDelayedExpansion
cd I:\Test\Batches\New folder (2)\New folder
set "files="
for /r %%F in (*) do call set files=%%files%% "%%F"
echo %files% | clip

In my case there is one file in the folder and it copies
"I:\Test\Batches\New folder (2)\New folder\Fotolia_93178533_Subscription_Monthly_M.jpg"
to the clipboard
The second batch file is meant to left trim a variable to just the left four characters. It works on its own.
set str=politic
echo.%str%
set str=%str:~0,4%
echo.%str%

But when I try to combine the two it is not working. Nothing gets written the the clipboard.
@echo off
setlocal disableDelayedExpansion
cd I:\Test\Batches\New folder (2)\New folder
set "files="
for /r %%F in (*) do call set files=%%files%% "%%F"
echo %files%
set files=%files:~0,4%
echo %files% | clip

Where is the error? Thanks, James
Comment: If there was only ever one file then you wouldn't [**1.**] be using a recursive directory search [**2.**] calling the variable %files% [**3.**] adding %%F to the existing content of %files% after already ensuring that %files% starts empty.
Comment: please explain what your expected output and end result is supposed to be. _You are aware that the %%F will be a full path, aren't you?. This means that %files% will be a probably extremely long single line list of filepath recursive files which will both quickly reach a limit and having the first four characters of the first full path will not achieve what you think you need._
Comment: @Compo everything you say is correct, but for all we know the OP could be just experimenting at this stage and he says there is only one file retrieved in the `for` command, so his variable is not going to overflow, but it is still not returning the expected result of the first four characters of the (one and only) path. (Actually the first two characters should be the space and the quote - but it's not even returning those for some reason.)
Comment: Hi again, Thanks for responses. Our system is set up so that there will only ever be one file in the examined folder. So the variable files should essentially be a text string which I then want to trim and then copy to the clipboard. I can get the files name to appear on the clipboard (it actually has a whitespace then the speech marks then the file name) But when I try to trim using set files=%files:~0,4% it all goes wrong.
Comment: That's a right trim.
Answer: The cause of the problem is the way CMD.EXE works with variable expansion: it performs the expansion before it parses the command. So you have the variable files set to
"I:\Test\Batches\New folder (2)\New folder\Fotolia_93178533_Subscription_Monthly_M.jpg"
and then the command set files=%files:~0,4% sets it to "I: - so it is missing the closing quote.
Then the command
echo %files% | clip

is actually seen as
echo  "I: | clip

and the pipe character | is treated as being part of the (unclosed) string.
I expect you probably don't want to clip the quote character, but the four characters after it: set files=files:~2,4% should do it. Otherwise, enable delayed expansion and use ! instead of %.
Comment: Brilliant, that was the problem - removing the quotation marks surrounding the %%f at the end of line 5 seems to have worked - it's producing the expected result now. Many thanks!
Answer: Are you sure you don't just want to do this at the cmd.exe prompt?
@For %A In ("I:\Test\Batches\New folder (2)\New folder\*.*") Do @Echo(%~dpnA|Clip

or with quotes:
@For %A In ("I:\Test\Batches\New folder (2)\New folder\*.*") Do @Echo("%~dpnA"|Clip

or even:
@For %A In ("I:\Test\Batches\New folder (2)\New folder\*.*") Do @Echo(%~pnxA|Clip

or with quotes:
@For %A In ("I:\Test\Batches\New folder (2)\New folder\*.*") Do @Echo("%~pnxA"|Clip

Comment: `set files=%files:~0,4%` sounds more like `%~dA\ ` only. But I might have misinterpreted the question.
Comment: The problem with that is that those are known without the loop, as is what they're getting . My guess therefore is that they only wanted the path minus the drive letter i.e. "**%files:~4%**
Comment: yeah, that's also a possible interpretion. But `set files=files:~2,4%` seems to solve the issue (see the Klitos' answer) - which would be `%~dA` - which (as you say) is pointless, as the drive letter is explicitely defined before, so well-known.

Batch file left string trim not working


Trocar texto ao clicar sobre o mesmo para apresentar/esconder um elemento

Question: Possuo o seguinte exemplo feito em JavaScript, do qual é um texto escrito "See more", que ao clicar nele ele você é possibilitado de ver mais texto:
Exemplo no JSFiddle
Código

  <title>
    Javascript demo - expand/collapse text
  </title>

  See more...

    Pardus is a GNU/Linux distribution developed in Turkey, as a product of the Pardus Project. It was named after the Anatolian Leopard.

    Pardus is an easy-to-install and -use operating system, with many enhancements to desktop usability, compatibility and security. With Pardus 1.0 (and the now-released Pardus 2007 version), users can connect to Internet, read e-mails, securely communicate with others and exploit the computer's multimedia capabilities by listening to music and watching movies.

    Ladislav Bodnar, the creator of DistroWatch, wrote in his round-up of Linux/*nix in 2006 that Pardus is one of the distros he was most impressed by this year "...thanks to unique package management ideas, innovative start-up sequence and general desktop polish..."

    Pardus is open source and freely distributed as a GPL (General Public License) product. It can be installed in Turkish, English, Spanish, German or Dutch.

Mas tenho uma questão, quando clico em "See more" o texto é mostrado, até aí tudo bem.
Pergunta
O código que tenho está a funcionar, mas eu gostaria que ao clicar em "See more", o texto mudasse para "Hide" no lugar de "See more". Como atingir este objectivo?
Answer: Podes utilizar a função .text() (Inglês) do JQuery.
Fiz um JSFiddle para veres como funciona, onde no mesmo estou a alterar o texto do elemento HTML com o id="see":
if ($("#see").text() == "See more...")
{
    $("#see").text("hide");
}
else {
    $("#see").text("See more...");
}

Exemplo no JSFiddle para uso do .text()
Answer: Além da opção dada pelo @CesarMiguel, se deseja usar apenas JavaScript, você pode fazer assim:
function blocking(nr, click) {
    var elementStyle = document.getElementById(nr).style.display;
    var displayNew = 'none';
    var text = 'See more...';
    if (elementStyle == 'none') {
        displayNew = 'block';
        text = 'Hide text';
    }
    document.getElementById(nr).style.display = displayNew;
    document.getElementById(click).innerHTML = text;
}

Exemplo no JSFiddle
Answer: Para o caso de pretenderes manter o anonimato do elemento que recebeu o clique, podes passar o mesmo para dentro da função blocking, e a partir dai verificar e atualizar o texto do mesmo em conformidade:
Exemplo a funcionar no JSFiddle
JavaScript
function blocking(nr, e) {

    // trocar texto
    if (typeof e !== 'undefined' && e!='') {
        e.innerHTML = (e.innerHTML=='See more...') ? 'Hide' : 'See more...';
    }

    displayNew = (document.getElementById(nr).style.display == 'none') ? 'block' : 'none';
    document.getElementById(nr).style.display = displayNew;
}

HTML
See more...

Explicação

No atributo onclick, estamos a passar um segundo parâmetro this, que representa o elemento em si.
onclick="blocking('whatItIs', this); return false;"

Na função blocking recebemos o elemento na variável e.
function blocking(nr, e)

Verificamos se a mesma está definida e não é vazia pois na tag body estás a chamar a função para esconder o texto ao inicio.
if (typeof e !== 'undefined' && e!='') {

Numa só linha fazemos a actualização do texto, verificando o atual.
e.innerHTML = (e.innerHTML=='See more...') ? 'Hide' : 'See more...';

Answer: Você pode utilizar o .html() também caso queria colocar marcadores HTML. A deferença entre .html() e .text() é que o primeiro aceita tags HMLT e XML. Já o segundo vai converter as tags HMLT para textos.
Exemplo
$(this).html('Linkhello')

O resultado do script acima seria Exatamente o texto descrito:
Linkhello

Agora com o outro exemplo
$(this).text('Linkhello')

Já o resultado do script acima seria
<a href="example.html">Link</a><b>hello</b>

Com escapes
Credito da explicação


Two questions about conditional expectations

Question:
When $Y$ is $\mathcal{F}$-measurable, what are the minimal conditions for $E[XY|\mathcal{F}]=YE[X|\mathcal{F}]$ to hold? Is it enough to know that both $X$ and $XY$ are $L^1$ or do we need some condition on $Y$ as well, besides measurability (e.g. $Y\in L^1$)?
Building on the previous question, when considering the transform $(Y_n)_{n\in\mathbb{N}}$ of a martingale $(X_n)_{n\in\mathbb{N_0}}$ by a predictable $(H_n)_{n\in\mathbb{N}}$, i.e. $Y_n=X_0+\sum_{i=1}^{n}H_i(X_i-X_{i-1})$, why do we need boundedness assumptions on $H_n$ to prove $(Y_n)_{n\in\mathbb{N}}$ is a martingale (e.g. the $H_n$ are uniformly bounded or at the very least individually bounded)? In the proof the boundedness assumption seems to be used only to pull $H_n$ out of the conditional expectations, but, assuming that for this to work we'd only need measurability of $H_n$, why assume boundedness (and hence $H_n\in L^1$)?
Answer: (1). The most general formulation of the property I am aware of states that over a $\sigma$-finite measure space $(X,\mathscr{A},\mu)$, if $\mathscr{G}\subseteq \mathscr{A}$ is a sub-$\sigma$-algebra then $E[gu|\mathscr{G}]=gE[u|\mathscr{G}]$ for all functions $g $ which are $\mathscr{G}$-measurable and all $u \in L^{\mathscr{G}}(\mathscr{A})$, which is the maximal set of $\mathscr{A}$-measurable functions for which the conditional expectation is defined (ref. Schilling, 2017, Th. 27.11.(vii)).
(2). Recall martingales need to be $\mathscr{F}_n$-adapted, integrable $\forall n$ and the martingale property must hold. If $X_n,H_n$ are adapted, then $Y_n$ as defined is adapted as it is a linear combination of $\mathscr{F}_n$-measurable functions. Boundedness of $H_n$ (i.e. $|H_n|\leq M_n<\infty,\,M_n \in \mathbb{R}$) is used to prove integrability:
$$E[|Y_n|]\leq E[|X_0|]+\sum_{k\leq n}E[|H_k||X_k-X_{k-1}|]\leq E[|X_0|]+\sum_{k\leq n }M_k(E[|X_{k}|]+E[|X_{k-1}|])<\infty$$
for the martingale property, just use the predictability of $H_n$ and you obtain $E[Y_n-Y_{n-1}|\mathscr{F}_{n-1}]=H_nE[X_n-X_{n-1}|\mathscr{F}_{n-1}]=0$ which shows the martingale property.
Comment: In the context of the probability space $(\Omega,\mathscr{F},P)$ with a random variable $X\in L^1$ and a sub sigma algebra $\mathscr{G}\subseteq \mathscr{F}$, then $E[X|\mathscr{G}]$ is defined, so $X \in L^\mathscr{G}(\mathscr{F})$ and the property holds. @V.Ch.
Comment: (1). Did I understand you correctly in that we don't even need to assume $XY\in L^1$ and it is enough for $X\in L^1$?
(2). I see, so we don't need the integrability of $H_n$ to prove the martingale property itself, just to show that the transformed variables are $L^1$.


Motion detection using only video clips

Question: I am trying to do motion detection of whether the person is walking or running. However I got only 40 short video clips of a single person walking or running. How to do the motion detection using video data? Can anyone please specify or point to any papers or implementation.
Answer: OpenCV has many trackers (https://docs.opencv.org/3.4.1/d9/df8/group__tracking.html). For instance: cv2.TrackerKCF_create().
You may find some comprehensive tutorials on the subject, like this one: https://www.pyimagesearch.com/2015/09/21/opencv-track-object-movement/

Motion detection using only video clips


sqlcode -117 - ibm mainframe

Question: The first image is of the table. I keep getting an error saying what im trying to insert into the table is not the same as what is in
the table. I
The second image is where I have inserted into the table.
[1]: https://i.stack.imgur.com/kIFw6.png
[2]: https://i.stack.imgur.com/ZD8Pv.png
Comment: DSNT408I SQLCODE = -117, ERROR:  THE NUMBER OF ASSIGNED VALUES IS NOT THE SAME AS THE NUMBER OF SPECIFIED OR IMPLIED COLUMNS                              DSNT418I SQLSTATE   = 42802 SQLSTATE RETURN CODE
DSNT415I SQLERRP    = DSNXOIN SQL PROCEDURE DETECTING ERROR
DSNT416I SQLERRD    = -111  0  0  -1  0  0 SQL DIAGNOSTIC INFORMATION
DSNT416I SQLERRD    = X'FFFFFF91'  X'00000000'  X'00000000'  X'FFFFFFFF'
         X'00000000'  X'00000000' SQL DIAGNOSTIC INFORMATION
Comment: This appears to have nothing to do with [tag:mysql]. Are you sure you have tagged this question accurately?
Comment: You create table __INVOICE_P__  but you insert into __INVOICE__  .   Fix your code.
Answer: the screenshots show that you are inserting into a different table than the one you are creating.
You create table INVOICE_P but you insert into INVOICE.
Most likely the table INVOICE has a different number or type of columns than INVOICE_P, so Db2 will throw the sqlcode -117 exception.
Try inserting into INVOICE_P  instead.

sqlcode -117 - ibm mainframe


Linking two Dell switch stacks with LAG / LACP

Question: Right now we have two independent switch stacks jointed with a single ethernet cable. For throughput and redundancy I would like to join them with a LAG. One switch stack is made up of Dell 7048's, the other is Dell 8132's (now called N4000 I believe). See diagram below.

I cannot for the life of me figure out how to create a LAG between these switches. The ports in question are all on the same subnet (marked blue in the diagram) so there is no VLAN tagging / trunking required, I think. I just want all the blue ports to behave as one switch. I also cannot figure out how and whether LACP comes into play.
Can someone please either provide me with specific instructions or guide me to a specific tutorial about what settings I should be using? I prefer using the web admin GUI but I do have serial access to the devices if need be. Any advice or guidance would be much appreciated.
Comment: Don't use LACP between switches if they are in same places. LACP won't give you the best load-balance. Use LAG without LACP, it's the same as roundrobin.
Comment: I have no idea what this other guy is saying,  if you want the bandwidth,  put all ports in the same port channel(1/1,1/2,2/1,2/2),  I'd recommend static lag.
Comment: I erased my other comment as I didnt realized the switch were stacked. I would do like Jacob's told
Answer: In the GUI it's simple to create the LAG, check the below print screen. You need to add the port you need to the same group, by clicking and adding each ports.

Note: In the GUI when you create the LAG you can click to enable LACP, be advised that once the LAG is created you can't enable LACP without destroying the LAG first.
In the CLI: (without LACP)

console# configure
Enter configuration mode.
console(config)# interface range gi1/0/1-4
Enter interface-range configuration mode by entering the range of
  interfaces to be configured. Range command is optional.
console(config-if)# channel-group 1 mode on
Assign Group and mode static. This creates port-channel 1 as static
  LAG. The number is only relevant to this specific switch. Although it
  best practice to match the number on the corresponding switch for ease
  of management.
console(config-if)# end
Exit configure mode.
console# copy running-config startup-config
(Optional) Save your entries in the configuration file.

Don't forget to configure both switch.
Some reference: How to create Link Aggregation Groups (LAGs) on Dell Networking PowerConnect Switches
Comment: Thank you for your answer, this is helpful. A followup question: Do I need to do anything special to allow specific VLAN traffic on the new "port-channel 1" or will it just assume the same VLAN settings as the individual ports had?
Comment: @HenryJackson You need to doublecheck there for VLAN assignment to a LAG; *Network Administration > Spanning Tree and LAG > Link Aggregation (LAG) > VLAN LAG Settings*.
Answer: without access to the switch, generally this is the process for a lag.

remove all interface configuration for lag members
join the lag
chanel-group 1 mode on

static: mode on
lacp: mode auto

configure your lag (pass vlans or access ports,  the config is the same as an interface)
interface port-channel 1
switchport mode trunk

whatever you do on the top stack, do the same for the bottom.
depending on your needs, you typically want static lag,  unless you use virtual port channels, vlt, or the endpoints only support one or the other.


Macros Retains Static Values

Question: Below is a Macro which i use to select the IP. An alertview is popped up user tries to login based on that the respective IP is set to fetch the data from the Server.
static NSString *updateProfileDetails_URL=@"http://%@/api/Home/editProfile/ios/1";

#define getServerURl(url,selectdServer)[[NSString stringWithFormat:@"%@",url] stringByReplacingOccurrencesOfString:@"%@"
withString:([selectdServer isEqualToString:@"live"] ?@"live_ip/folder_name":@"demo_ip/folder_name" )]

I selected the 'demo_ip' option login.
Logged out.
Selected 'live' option now.
Problem here is that the demo_ip is called at certain places. Kindly help.

Thanks
Answer: You can try like this:
#define USE_TEST_URL 1   // use 1 for test and 0 for live

#if USE_TEST_URL  // define test urls here

#define API_URL @"http://...<TEST URL>"

#else  // define live urls here

#define API_URL @"http://... <LIVE URL>"

#endif

and
NSString *url =[[NSString stringWithFormat:@"%@",API_URL] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

Answer: There is none of the issue with Macro, There might've been a problem with your passing parameters, when you calling getServerURl(...)
When you need live, Make sure you passing 'live' in second parameter of getServerURl(...)! Because you are conditionally comparing 'live' lowercase value.
For more information: Macros are replaced by the preprocessor by their value before your source file even compiles. So There is no way you'd be able to change the value of the macro at runtime.

Macros Retains Static Values


How can I engrave consecutive rehearsal marks now that the multi-mark engraver does not work anymore for this purpose in Lilypond 2.24.1?

Question: In 2011, Xavier Scheuer published a code snippet allowing consecutive rehearsal marks using the multi-mark engraver. The code worked until now. In Lilypond 2.24.1 it fails. Here is an example that worked before (sorry, a lot of code):
\version "2.22.1"
\language "italiano"

#(set-global-staff-size 18)

openBracket =
    \tweak self-alignment-X #'()
    \tweak break-visibility #end-of-line-invisible
    \mark \markup {
        \path #0.2 #'((moveto 0 0) (lineto 0 2) (lineto 1.3 2))
    }
closeBracket =
    \tweak self-alignment-X #'()
    \tweak break-visibility #begin-of-line-invisible
    \mark \markup {
        \path #0.2 #'((moveto 0 0) (lineto 0 2) (lineto -1.3 2))
    }
doubleBracket =
    \tweak self-alignment-X #'()
    \tweak break-visibility #begin-of-line-invisible
    \mark \markup {
        \path #0.2 #'((moveto -0.2 0) (lineto -0.2 2) (lineto -1.5 2)
                      (moveto  0.2 0) (lineto  0.2 2) (lineto  1.5 2))
    }

#(define (multi-mark-engraver ctx)
    (let
        ((texts '())
         (final-texts '())
         (events '()))

      `(
            (start-translation-timestep
                . ,(lambda (trans)
                (set! final-texts '())))

            (listeners
                (mark-event
                    . ,(lambda (trans ev)
                    (set! events (cons ev events)))))

            (acknowledgers
                (break-alignment-interface
                    . ,(lambda (trans grob source)
                        (for-each
                            (lambda (mark)
                                (set! (ly:grob-parent mark X) grob))
                            texts))))

            (process-music
                . ,(lambda (trans)
                    (for-each
                        (lambda (ev)
                            (let*
                                (
                                    (mark-grob (ly:engraver-make-grob trans 'RehearsalMark ev))
                                    (label (ly:event-property ev 'label))
                                    (formatter (ly:context-property ctx 'markFormatter))
                                )

                                (if
                                    (and (procedure? formatter) (not (markup? label)))
                                    (begin
                                        (if (not (number? label))
                                            (set! label
                                                (ly:context-property ctx 'rehearsalMark)))

                                        (if (and (integer? label)
                                            (exact? label))
                                            (set!
                                                (ly:context-property ctx 'rehearsalMark)
                                                (1+ label)))

                                        (if (number? label)
                                            (set! label (apply formatter (list label ctx)))
                                            (ly:warning "rehearsalMark must have integer value"))))

                                (if (markup? label)
                                    (begin
                                        (set! (ly:grob-property mark-grob 'text) label)
                                        (let ((dir (ly:event-property ev 'direction)))
                                            (and (ly:dir? dir)
                                                (set! (ly:grob-property mark-grob 'direction) dir))))
                                    (ly:warning "mark label must be a markup object"))

                                (set! texts (cons mark-grob texts))))
                        (reverse events))))

            (stop-translation-timestep
                . ,(lambda (trans)
                    (if (pair? texts)
                        (let
                            ((staves (ly:context-property ctx 'stavesFound)) (priority-index 0))
                            (for-each
                                (lambda (grob)
                                    (let
                                        ((my-priority (ly:grob-property grob 'outside-staff-priority 1500)))
                                        (for-each (lambda (stave) (ly:pointer-group-interface::add-grob grob 'side-support-elements stave)) staves)
                                        (set! (ly:grob-property grob 'outside-staff-priority) (+ my-priority priority-index))
                                        (set! priority-index (1+ priority-index))
                                        (set! final-texts (cons grob final-texts))))
                                (reverse texts))
                            (set! texts '())
                            (set! events '())))))

            (finalize
                . ,(lambda (trans)
                    (and
                        (pair? final-texts)
                        (for-each
                            (lambda (grob)
                                (set! (ly:grob-property grob 'break-visibility) end-of-line-visible))
                            final-texts)))))))

\score {
    \header {
        opus = "Op. 261 №7"
    }
    \new PianoStaff \with {
        instrumentName = "11."
        \override InstrumentName.font-size = #6
        \override InstrumentName.self-alignment-X = #RIGHT
    } <<
        \new Staff = "правая" \with {}
        \relative do' {
            \key do \major
            \time 2/4
            \tempo "Allegretto vivace"
            \set Timing.baseMoment = #(ly:make-moment 1/32)
            \set Timing.beatStructure = 4, 4, 4, 4
            \openBracket
            do'32-3 (_[sol-1 re'-4 sol,-1]) mi'16-!-5 \noBeam r16 mi32-3 (_[do-1 fa-4 do-1]) sol'16-!-5 \noBeam r16 |
            do,32-3 (_[sol-1 re'-4 sol,-1]) mi'16-!-5 \noBeam r16 mi32-3 (_[do-1 fa-4 do-1]) sol'16-!-5 \noBeam r16 |
            fa32-4 (_[sol-5 mi-3 sol-5]) re16-!-2 \noBeam r16 mi32-3 (_[sol-5 re-2 sol-5]) do,16-!-1 \noBeam r16 |
            \once \override Fingering.avoid-slur = #'inside
            re32-2 (sol-5 re-2 sol-5 si,-1 re-4 si-2 re-4) sol,16-!-1 [sol-!-3 sol-!-2 sol-!-1] \closeBracket |
            \openBracket
            do32-3 (_[sol-1 re'-4 sol,-1]) mi'16-!-5 \noBeam r16 mi32-3 (_[do fa-4 do]) sol'16-!-5 \noBeam r16 |
            \ottava #1 do32-3 (_[sol re'-4 sol,]) mi'16-!-5 \noBeam r16 mi32-3 (_[do fa-4 do]) sol'16-!-5 \noBeam r16 |
            \tweak outside-staff-priority #100 \doubleBracket
            \once \override Fingering.avoid-slur = #'inside
            la32-5 (la,-1 la'-5 sol fa-3 mi re-1 do-4 \ottava #0 si-3 la sol-1 fa-4 mi-3 re do-1 si-2 |
            do-1 re mi-3 fa-1 sol-2 la si do-5 do,16-.-1) r r8 \closeBracket
            \bar "|."
        }
        \new Dynamics {
            s16
            s32 s32 s8 s4 | s2 | s2 |
            s32 \> s32 s32 s32 s32 s32 s32 s32 s16 s16 s16 s16 \! |
            s32 \p s32 s32 s32 s16 s16 s32 s32 s32 s32 s16 s16 |
            s32 \mf s32 s32 s32 s16 s16 s32 s32 s32 s32 s16 s16 |
            s32 \f s32 s32 s32 s32 s32 s32 s32 s32 s32 s32 s32 s32 s32 s32 s32 |
        }
        \new Staff = "левая" \with {}
        \relative do {
            \clef bass
            \set fingeringOrientations = #'(down)
            <do-4>16-. _[r <mi-2 sol-1>-.] r do-. _[r <mi sol>-.] r |
            <do-4>-. _[r <mi-2 sol-1>-.] r do-. _[r <mi sol>-.] r |
            <do-5>-. _[r <re-3 sol-1>-.] r <do-4>-. _[r <mi-2 sol-1>-.] r |
            <sol-3 si-1>8-> r8 r4 |
            <do,-4>16-. _[r <mi-2 sol-1>-.] r do-. _[r <mi sol>-.] r |
            <do-4>-. _[r <mi-2 sol-1>-.] r do-. _[r <mi sol>-.] r |
            <fa-5 la-3 re-1>8 r <sol-5 re'-2 fa-1> r |
            <do-3 mi-1>16-. r <do mi>-. r <do mi>-. r r8
        }
    >>
    \layout {
        \context {
            \Score
            \override SpacingSpanner.spacing-increment = 1.1
            \remove "Mark_engraver"
            \consists #multi-mark-engraver
        }
    }
}

This is where it explodes:
(if (markup? label)
    (begin
        (set! (ly:grob-property mark-grob 'text) label)
        (let ((dir (ly:event-property ev 'direction)))
            (and (ly:dir? dir)
                (set! (ly:grob-property mark-grob 'direction) dir))))
    (ly:warning "mark label must be a markup object"))

The test if the label is a markup fails and the code prints "warning: mark label must be a markup object". Later Lilypond also prints a number of
programming error: Trying to interpret a non-markup object: ()
continuing, cross fingers

I am not sure where this is coming from at all. There is no line reference.
I tried convert-ly. It was supposed to convert an outdated version of .ly to an up-to-date one. The resulting .ly produced fewer errors, but it engraved A, B, C, D, E as marks instead of brackets.
How can I replace the functionality of this script?
Comment: While convert-ly usually does a good job on pure LilyPond code, Scheme code is far trickier to convert since Scheme is a full-fledged programming language. convert-ly does have some heuristics, but they remain heuristics. All code needs maintenance and Scheme code in LilyPond files is no exception.
Comment: @jeanas The real problem wasn't in the Scheme code. `convert-ly` should have changed `\mark` to `\textMark` because `\mark` accepts only numbers now as an argument.
Comment: Nope, there is no bug. \mark still does accept a markup argument, for compatibility. If \mark  were converted to \textMark, it would invalidate user overrides to the RehearsalMark grob, which we cannot change to TextMark unconditionally because norma rehearsal marks remain RehearsalMark grobs. (The addition of \textMark was contributed by me, FWIW.)
Comment: @jeanas Thank you for \textMark!
Answer: After reading the release notes, I have found a solution. It turned out we don't need anymore to use \mark to place our custom symbols and text above notes. Thus, multi-mark-engraver is not needed anymore as well. All one has to do is to use \textMark instead of \mark. The full solution for the code in the question:
\version "2.24.1"
\language "italiano"

#(set-global-staff-size 18)

openBracket =
    \tweak self-alignment-X #'()
    \tweak break-visibility #end-of-line-invisible
    \textMark \markup {
        \path #0.2 #'((moveto 0 0) (lineto 0 2) (lineto 1.3 2))
    }
closeBracket =
    \tweak self-alignment-X #'()
    \tweak break-visibility #begin-of-line-invisible
    \textMark \markup {
        \path #0.2 #'((moveto 0 0) (lineto 0 2) (lineto -1.3 2))
    }
doubleBracket =
    \tweak self-alignment-X #'()
    \tweak break-visibility #begin-of-line-invisible
    \textMark \markup {
        \path #0.2 #'((moveto -0.2 0) (lineto -0.2 2) (lineto -1.5 2)
                      (moveto  0.2 0) (lineto  0.2 2) (lineto  1.5 2))
    }

\score {
    \header {
        opus = "Op. 261 №7"
    }
    \new PianoStaff \with {
        instrumentName = "11."
        \override InstrumentName.font-size = #6
        \override InstrumentName.self-alignment-X = #RIGHT
    } <<
        \new Staff = "правая" \with {}
        \relative do' {
            \key do \major
            \time 2/4
            \tempo "Allegretto vivace"
            \set Timing.baseMoment = #(ly:make-moment 1/32)
            \set Timing.beatStructure = 4, 4, 4, 4
            \openBracket
            do'32-3 (_[sol-1 re'-4 sol,-1]) mi'16-!-5 \noBeam r16 mi32-3 (_[do-1 fa-4 do-1]) sol'16-!-5 \noBeam r16 |
            do,32-3 (_[sol-1 re'-4 sol,-1]) mi'16-!-5 \noBeam r16 mi32-3 (_[do-1 fa-4 do-1]) sol'16-!-5 \noBeam r16 |
            fa32-4 (_[sol-5 mi-3 sol-5]) re16-!-2 \noBeam r16 mi32-3 (_[sol-5 re-2 sol-5]) do,16-!-1 \noBeam r16 |
            \once \override Fingering.avoid-slur = #'inside
            re32-2 (sol-5 re-2 sol-5 si,-1 re-4 si-2 re-4) sol,16-!-1 [sol-!-3 sol-!-2 sol-!-1] \closeBracket |
            \openBracket
            do32-3 (_[sol-1 re'-4 sol,-1]) mi'16-!-5 \noBeam r16 mi32-3 (_[do fa-4 do]) sol'16-!-5 \noBeam r16 |
            \ottava #1 do32-3 (_[sol re'-4 sol,]) mi'16-!-5 \noBeam r16 mi32-3 (_[do fa-4 do]) sol'16-!-5 \noBeam r16 |
            \tweak outside-staff-priority #100 \doubleBracket
            \once \override Fingering.avoid-slur = #'inside
            la32-5 (la,-1 la'-5 sol fa-3 mi re-1 do-4 \ottava #0 si-3 la sol-1 fa-4 mi-3 re do-1 si-2 |
            do-1 re mi-3 fa-1 sol-2 la si do-5 do,16-.-1) r r8 \closeBracket
            \bar "|."
        }
        \new Dynamics {
            s16
            s32 s32 s8 s4 | s2 | s2 |
            s32 \> s32 s32 s32 s32 s32 s32 s32 s16 s16 s16 s16 \! |
            s32 \p s32 s32 s32 s16 s16 s32 s32 s32 s32 s16 s16 |
            s32 \mf s32 s32 s32 s16 s16 s32 s32 s32 s32 s16 s16 |
            s32 \f s32 s32 s32 s32 s32 s32 s32 s32 s32 s32 s32 s32 s32 s32 s32 |
        }
        \new Staff = "левая" \with {}
        \relative do {
            \clef bass
            \set fingeringOrientations = #'(down)
            <do-4>16-. _[r <mi-2 sol-1>-.] r do-. _[r <mi sol>-.] r |
            <do-4>-. _[r <mi-2 sol-1>-.] r do-. _[r <mi sol>-.] r |
            <do-5>-. _[r <re-3 sol-1>-.] r <do-4>-. _[r <mi-2 sol-1>-.] r |
            <sol-3 si-1>8-> r8 r4 |
            <do,-4>16-. _[r <mi-2 sol-1>-.] r do-. _[r <mi sol>-.] r |
            <do-4>-. _[r <mi-2 sol-1>-.] r do-. _[r <mi sol>-.] r |
            <fa-5 la-3 re-1>8 r <sol-5 re'-2 fa-1> r |
            <do-3 mi-1>16-. r <do mi>-. r <do mi>-. r r8
        }
    >>
}


Show a homomorphism of local rings of two varieties

Question: Shafarevich, Basic Algebraic Geometry 1, II.1.1
"Prove that the local ring $\mathcal O_x$ of the curve $xy=0$ at $(0,0)$ is isomorphic to the subring $\mathcal O \subset \mathcal O_1 \oplus \mathcal O_2$, where $\mathcal O_1$ and $\mathcal O_2$ are copies of the local ring of $0$ in $\mathbb A^1$ consisting of functions $f_1,f_2$ with $f_1\in \mathcal O_1$ and $f_2\in\mathcal O_2$ such that $f_1(0)=f_2(0)$."
I know that $\mathcal O_1=\mathcal O_2=\mathbb C[t]_{(t)}$ and that $\mathcal O=(k[x,y]/(x,y))_{(x,y)}=\{\frac{p(x)+q(y)}{r(x)+t(y)}:r(0)+t(0)\neq 0\}$.
I can't figure out the isomorphism, though. I was thinking $\frac{p+q}{r+t}\to (\frac{p}{r},\frac{q}{t})$. I think I've shown this is a homomorphism, but I can't figure out what the kernel has to do with the hint in the problem. Thanks!
Answer: Let $f \in  {k[x,y]/(x,y)}_{(x,y)}=\mathscr O$ (the local ring at the origin of the curve $xy=0$.
Then define a map $\mathscr O \to \mathscr O_1 \times \mathscr O_2$ by $f(x,y) \mapsto (f(x,0),f(0,y))$.  This is a well-defined ring homomorphism.
The kernel consists of all $f$ such that $f(x,0)=f(0,y)=0$. The first condition implies that $f \equiv 0 \pmod y$, and the second condition implies that $f \equiv 0 \pmod x$. Thus $f \in (y) \cap (x)=(xy)$, meaning that $f$ is already zero in the quotient. Hence the map is injective.
That the map lands in $\mathscr O$ is obvious, and that it is surjective onto $\mathscr O$ is also easy to see, since the condition is  for $f_1,f_2$ to have the same constant term.


How to prove a claim about LCM?

Question: Prove that LCM$(\frac{n}{a}, \frac{n}{b}) = n$ if $(a,b)=1$.
Let us assume the factorization of $n = p_1^{\alpha_1} p_2^{\alpha_2} \cdots p_k^{\alpha_k}$ and  $a=q_1^{\beta_1} q_2^{\beta_2} \cdots q_k^{\beta_k}$ and $b = r_1^{\gamma_1} r_2^{\gamma_2} \cdots p_k^{\gamma_k}$.
Please note that both $a$ and $b$ divide $n$.
Case 1: If both $a$ and $b$ divide $n$ then I am getting that $\frac{n}{a}$ will divide $n$ and $\frac{n}{b}$ will also divide $n$ but why it will be the minimum multiple?
Comment: I only know the lcm of integers. what is the lcm of two fractions?
Comment: @miracle173 this doesn't arise, since $a,b|n$
Comment: @StellaBiderman I see now that this was introduced in the second version of post.
Comment: What do you mean? $2$ and $3$ divide $6$.
Comment: @StellaBiderman sorry, I misread the post
Answer: Suppose $n/a$ divides $x$ and $n/b$ divides $m$, say $m=xn/a=yn/b$, for some integers $x,y$.
Then we have $xb=ya$. Since $a$ is co-prime to $b$, this implies $a$ divides $x$; similarly $b$ divides $y$. Consequently $m=xn/a=n\cdot x/a$ is a multiple of $n$.
Thus $n$ is the least common multiple of $n/a$ and $n/b$.

Hope this helps.
Answer: I find it easier to work with gcd. The following 2 lemmas are useful and not hard to prove.
Lemma 1. If $ (a,b) = 1 $, then $ (ak,bk) = k $ for any integer $ k $.
Lemma 2. $ \gcd(a,b) \text{ lcm}(a,b) = ab $.
Given these two results, we can now prove as follows: let $ k = \frac{n}{ab} $ in Lemma 1. Note that $ ab $ divides $ n $ since $ a $ and $ b $ are coprime. Then $ \gcd(\frac{n}{a}, \frac{n}{b} ) = ( \frac{bn}{ab}, \frac{an}{ab}) = \frac{n}{ab} $. Now use lemma 2:
$$ \frac{n^2}{ab} = \frac{n}{a} \frac{n}{b} = \gcd(\frac{n}{a}, \frac{n}{b}) \text{lcm}(\frac{n}{a}, \frac{n}{b}), $$
and since $ \gcd = \frac{n}{ab} $ we get $ \text{lcm} = n $.

How to prove a claim about LCM?


OpenVZ Container Restart

Question: I'm wondering if there are any public scripts to automatically restart OpenVZ containers on certain load amount / high cpu. Trying to limit my containers on my personal machine, thanks.
Comment: this is hammer approach, if you wan't to script it really you can see my answer
Answer: As seen on : http://openvz.org/Loadavg ; load average of some container can be acquired with

vzctl exec $CTID cat /proc/loadavg

you can script this easily with something like
<code>#!/bin/bash

# loop over all OpenVZ containers
for container in $(vzlist -o ctid | egrep -o '[0-9]+')
do
  if (( $(bc <<< "$(vzctl exec $container cat /proc/loadavg | cut -d' ' -f1) <= 0.2") == 1 ))
  then
        echo "Load is less than 0.2"
  else
        echo "Load is above 0.2, stopping container $container"
        vzctl stop $container

  fi
done
</code>
It uses the fact that load averages of respective intervals 1 5 and 15 can be read from /proc/loadavg
Comment: Thank you. I'm unfamiliar with bash scripting. How would I make it kill the process?
Comment: if this script is ran inside OpenVZ container as I understood from your question, you adjust load which is too high and restart with 'reboot' command; just add it below echo command in the script.
Comment: I want to run it on the host node to check for containers load. Sorry if I wasn't clear.
Comment: I've updated answer with more specific approach to run on system which hosts OpenVZ containers
Comment: Awesome, thank you. I'll give this a try. Would the best way to keep it running is with a cronjob?
Comment: sure you can add it to run as cronjob every few min; also please don't forget to upvote/accept answer if you found it helpful :))
Comment: Will do, thank you. Would it possible to do with process percentages and stop them?
Comment: what kind of percentage? please expand your question or add new comment with details and I'll do my best to help
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/18541/discussion-between-user44754-and-hrvoje-spoljar).
Comment: I opened up a chat.
Comment: Yea, I was there but nobody responded...

OpenVZ Container Restart


AWS - Previous admin gone, I don't have the .pem, am I screwed?

Question: I've been asked to edit the html of a splash screen on a static temporary site for a client (its super simple). I have full access to the AWS portal where the instance is hosted but appear to be unable to access the instance as I do not have the .pem.
It is presently not possible to contact the former dev of the site.
Is there anything I can do to gain access to the VM so that I might inspect the contents and work out what I need to change?
I did try to create an AMI from that instance but when I request the password its now telling me:

Instances launched from a custom AMI will inherit the User and Password of the AMI's parent instance

Is there anything I can do outside of completely recreating the site????
Comment: Create a snapshot of the EBS volume attached to the instance, and create a new EBS volume from that. Launch a new instance, and attach the newly created EBS volume to the new instance. 1) If you just want a copy of the files, then simply copy them from the newly attached EBS volume. 2) If you want to keep the existing server configuration: Find the username (e.g. from etc/passwd and etc/sudoers); Generate a new SSH and set it up. Detach your EBS volume, and attach it as the root volume to another instance - login with the SSH key you generated.
Comment: You can mount the EBS to a new instance with a new .pem and change the authorized keys, then re-mount it to the old instance.
Answer: Yes, it is possible to recover the access to your files, but only for EBS disks. The following method doesn't work if you want to recover files in a root device that is of type Instance Store. You can find your storage type in EC2 console, clicking at the Instance and looking in the info for "Root device type".
Note: You can get a more detailed guide here or here.
Steps using AWS EC2 Console:

Stop the instance that you've lost access.
Create an AMI from it.
Create a new instance using this AMI and safely store your new .pem file.
Go to Volumes and detach the volume used in the original instance.
Attach this volume to the new instance.
Mount the new attached volume.

If you want just to copy the files, you can stop from here. But if you want to use the old machine, continue:

Copy the authorized_keys from the new instance root device and replace the old EBS authorized_keys that you have just attached.

<code>[ec2-user ~]$ cp .ssh/authorized_keys /mnt/tempvol/home/ec2-user/.ssh/authorized_keys</code>

Unmount the volume.
Terminate the machine that was created just to recover the EBS.
Attach the volume to the old machine and start it.
Connect to the old machine using the credentials that you've created for the temporary instance.


Guardar todos os tipos de variáveis em um vetor/array?

Question: Como posso armazenar dentro de um vetor valores e variáveis de todo os tipos? Ex:
vetor1.Add("valor em string");
vetor1.Add(100);
vetor1.Add(100.10);
vetor1.Add(-100);

Não tenho ideia de como posso fazer isso.
Comment: Tem certeza que é isso que você quer? Recuperar esses dados depois pode ser trabalhoso
Comment: Sim, conforme a resposta abaixo do Maniero, descobri que para recuperar os dados do `object` é só dar um `cast`.
Answer: Isso não parece um array e sim uma lista. O tipo geral para todos os tipos é o object, então é só usá-lo.
var vetor = new List<object>() { "string", 100, 100.10, -100 };

Coloquei no GitHub para referência futura.


FnMut seems to capture it's call parameters?

Question: In an ffi (embedded) environment a trampoline is usually used when the C code expects a function pointer (and an optional, usually *void argument), but we want to have it call a rust closure instead.
The trampoline is an fn, while a boxed closure is supplied as the argument. The fn code simply calls the closure.
However it seems that I can't convince the borrow checker that the following code is safe, and it seems to think that a reference given to the closure as parameter (not captured by the closure) remains borrowed after the call to the closure returns.
I'm not sure why this is the case, can someone help out on how to make this compile?
// Workaround for unstable feature 'trait_alias'
pub trait Callback<'a>: FnMut(&'a mut Context<'a>) {}

impl<'a, T> Callback<'a> for T where T: FnMut(&'a mut Context<'a>) {}

pub fn trampoline(cb_ptr: *mut c_void ) {
    let s = "foo";
    let mut ctx = Context { s };

    unsafe {
        let cb = cb_ptr as *mut Box<dyn Callback<'_>>;
        (*cb)(&mut ctx);
    }

    let Context { s, .. } = ctx;

    info!("s = {}", &s);

}

Error:
error[E0503]: cannot use `ctx.s` because it was mutably borrowed
  --> temp.rs:91:19
   |
88 |         (*cb)(&mut ctx);
   |               -------- borrow of `ctx` occurs here
...
91 |     let Context { s, .. } = ctx;
   |                   ^
   |                   |
   |                   use of borrowed `ctx`
   |                   borrow later used here

For more information about this error, try `rustc --explain E0503`.

Answer: The problem appears to be with &'a mut Context<'a>. This is saying that the reference to the context needs to live as long as the reference within the context. However, you actually don't care about the lifetime of the reference to the context; it only needs to last for the duration of the call to the closure.
Changing &'a mut to just &mut appears to fix the issue:
// Workaround for unstable feature 'trait_alias'
pub trait Callback<'a>: FnMut(&mut Context<'a>) {}

impl<'a, T> Callback<'a> for T where T: FnMut(&mut Context<'a>) {}

pub fn trampoline(cb_ptr: *mut c_void ) {
    let s = "foo";
    let mut ctx = Context { s };

    unsafe {
        let cb = cb_ptr as *mut Box<dyn Callback<'_>>;
        (*cb)(&mut ctx);
    }

    let Context { s, .. } = ctx;

    info!("s = {}", &s);

}

playground
Comment: Hmm. I did try something like this, but explicitly naming it 'b, but it did not compile. I'll try again tomorrow.
Comment: Btw you mean the context needs to live as long as the reference within the context, right? Which doesn't hold, because the reference within the context is 'static, while the context is not
Comment: Adding a second lifetime parameter `'b` to `Callback` probably won't work the same, because `&mut` in parameter position desugars to something like `for<'b> &'b mut`, meaning "this must be valid for any possible lifetime of the reference", rather than a specific lifetime.
Comment: No, I mean the reference to the context (`&'a mut Context<'a>`) must life as long as the reference within that context (`&'a str`).
Comment: I would go one step further and decouple the lifetime of the arguments from the lifetime of the callback altogether: `pub trait Callback: for<'a> Fn(&mut Context<'a>) {}`
Comment: How do I implement such a trait? `impl<'a, T> Callback for <'a> T where T:FnMut(...)` seems to not be the correct syntax.
Comment: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=259d7dd7680bbe50ca5e4b1628f3efca


seleção de um item no combobox

Question: Tenho o seguinte combobox como mostro abaixo, ele é preenchido com os dados vindo de uma tabela de um banco de dados, até ai tudo bem, gostaria que quando fosse selecionado um item do combobox fosse exibido um input, e quando não fosse selecionado nenhum item o input ficasse oculto. É possível fazer isso com javascript?

  EMPRESA *

     <select name="empresa" id="empresa"
      onchange="ExibirDiv(this.value)" class="form-control">
       <option value="">SELECIONE</option>
          <?php
             $parametro_empresa = filter_input(INPUT_GET,"parametro_empresa");
             $empresa = "SELECT * FROM tb_empresa WHERE
             razaosocial_pessoafisica LIKE '%" . $parametro_empresa . "%'";
             $recebe_empresas = mysqli_query($con, $empresa);
              while ($linha = mysqli_fetch_array($recebe_empresas)) {
               echo '<option value="' . $linha['codigo_empresa'] . '">' .
               $linha['razaosocial_pessoafisica'] . '</option>';
             }
          ?>
     </select>

Comment: Sim. É possível
Answer: Com display block no jquery você consegue
Dá uma olhada

$('.combo').on('change', function(){
    if( $(this).val() != ""){
       $('#campo').css('display','block')
       $('#campo').val( $(".combo option:selected").text() )
    }else{
      $('#campo').css('display','none')
     }
})

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

  <select class="form-control combo" >
    <option value="">Selecione</option>
    <option value="1">Valor 1</option>
    <option value="2">Valor 2</option>
    <option value="3">Valor 3</option>
    <option value="4">Valor 4</option>
    <option value="5">Valor 5</option>
  </select>

<input id="campo" class="form-control" style="display: none" >

Espero que ajude
Comment: O código pode ser melhorado usando os métodos `.show()` e `.hide()` do jQuery, veja: https://jsfiddle.net/us920Ly4/1/

seleção de um item no combobox


Localizing DataAnnotations Custom Validation Attribute

Question: I'm currently working in an MVC 2 app which has to have everything localized in n-languages (currently 2, none of them english btw). I validate my model classes with DataAnnotations but when I wanted to validate a DateTime field found out that the DataTypeAttribute returns always true, no matter it was a valid date or not (that's because when I enter a random string "foo", the IsValid() method checks against "01/01/0001 ", dont know why).
Decided to write my own validator extending ValidationAtribute class:
public class DateTimeAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        DateTime result;
        if (value.ToString().Equals("01/01/0001 0:00:00"))
        {
                return false;
        }
        return DateTime.TryParse(value.ToString(), out result);
    }
}

Now it checks OK when is valid and when it's not, but my problem starts when I try to localize it:
[Required(ErrorMessageResourceType = typeof(MSG), ErrorMessageResourceName = "INS_DATA_Required")]
[CustomValidation.DateTime(ErrorMessageResourceType = typeof(MSG), ErrorMessageResourceName = "INS_DATA_DataType")]
public DateTime INS_DATA { get; set; }

If I put nothing in the field I get a localized MSG (MSG being my resource class) for the key=INS_DATA_Required but if I put a bad-formatted date I get the "The value 'foo' is not valid for INS_DATA" default message and not the localized MSG.
What am I misssing?
Answer: It could be that your ToString() is using a 'localized' format so your hard coded string will not match.
try replacing your "if" condition with:
if((DateTime)value == DateTime.MinValue)

Comment: That "if" works fine as is, btw yours is more polite. My question refered more to the fact that, even though I'm specifying both ErrorMessageResourceType and ErrorMessageResourceName in the Model field I still get the default error message in english "The value 'blah' is not valid for INS_DATA" which isn't what I hard-coded in my resource file.
Comment: Oh right. I'm not sure, *lame answer follows:* it sounds like it can't find the resource  :-]