Update SQLite com EditText Android

Question: Bom dia senhores, estou tentando fazer um update no meu banco de dados no SQLite através do meu EditText porém ele apresenta erro, alguém poderia me dizer no que estou errando ?
public void insererazaosocial (SQLiteDatabase db){
        db.execSQL( "UPDATE emitente SET razaosocial='"+selecinfo2.getText().toString()+"' WHERE id = 1");
    }

Answer: Pessoal consegui resolver o problema, caso queiram um exemplo podem pegar o meu código para vocês. Forte abraço :D
public void insererazaosocial (SQLiteDatabase db){

        String valor = selecinfo2.getText().toString();
        if (valor != null) {
            db.execSQL("UPDATE emitente SET razaosocial='"+valor+"' WHERE id = 1");
            Toast.makeText(getApplicationContext(), "O registro foi gravado no Banco de Dados", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(getApplicationContext(), "Verifique as informações e tente novamente", Toast.LENGTH_SHORT).show();
        }
    }

Update SQLite com EditText Android


Can someone explain why this spacing is preferred for III-VI progression

Question: I was studying from walter piston's harmony and came across this. Can someone explain why the first progression is unusual while the second one is preferred?
Comment: @MichaelCurtis In the fifth edition, it's in Chapter 3, example 3–27, page 34.
Comment: What edition is this from? I don't see it in the first edition.
Answer: Note: All page references are to the fifth edition of Walter Piston's Harmony (rev. Mark DeVoto, W.W.Norton & Co., 1987).

Piston sets things up in Chapter 3, "Harmonic Progression in the Major Mode: Principles of Voice Leading" with his "Rule of Thumb 2":

If the two triads have no tones in common, the upper three voices move in opposite direction to the motion of the bass, but always to the nearest available position. (26)

By this rule, the "unusual" voicing is almost perfect: there's one common tone, and all other voices move to the nearest available position.
The key element is that the upper voices do not move in contrary motion with the bass.
The problem with the "unusual" progression comes through Piston's discussion of "The Direct Octave and Fifth" (32 – 34).

The prominence of [direct octaves and fifths] ..., especially when located between the outside voices, bass and soprano, requires special attention in elementary harmony. (32; emphasis mine)

The "unusual" voicing contains a hidden parallel octave between the bass and soprano, while the "preferred" voicing, by the upper voices moving in contrary motion with the bass, avoids it. In this case, the direct octave between bass and soprano is noticeable enough that it takes precedence over the otherwise reasonable voice leading.

A general comment:
In counterpoint, it's generally poor style for all moving voices to move simultaneously in the same direction, which occurs in the "unusual" voicing, but not in the "preferred".
Comment: @Aaron - In the *unusual* voicing, the motion is actually "oblique", not similar as you ascribe.
Comment: @nuggethead Horn fifths are a feature of natural brass instruments, not of Mozart's compositional style.  Mozart was certainly neither the first nor the last to employ them.
Comment: I agree with @Aaron that the hidden octaves in the first example are its worst feature.  I would add to this two thoughts.  First, that hidden octaves are generally considered OK if one part (especially the lower) moves by skip or leap.  Mozart's "horn fifths" are an example of this.  Second, the second example is not perfect either.  There is a hidden parallel fifth between soprano and tenor.
Comment: Agreed @phoog .
Comment: "Rule of thumb 2" sounds like what Piston gives for a progression like `IV V` step wise roots. I expect that edition must have a rule of thumb for one common tone, two voices move by step (root descending fourth or fifth) which would be the OP's "usual" move.
Comment: @MichaelCurtis Spot on. "Rule of Thumb 1. If two triads have one or more tones in common, these common tones are usually repeated in the same voice, the remaining voice or voices moving to the nearest tones of the second chord."
Comment: Right, so like jjmusicnotes pointed out, the progression in question is covered by that rule of thumb 1 as "usual" and "preferred" as an alternative for certain situations.
Comment: @MichaelCurtis No, because the common tones don't repeat in the same voice and the soprano doesn't move to the nearest chord tone. jjmusicnotes was just pointing out some poor wording in an earlier edit of my post.
Comment: @MichaelCurtis I wonder if you're misreading "unusual" as "usual"?
Comment: Yes, I did. But I get that the book is saying to use the 'preferred'
Comment: The "unusual" example, the `E4` is held, the other two upper voices move my step. That voice leading is rule of thumb #1. The "preferred" is an alternative, and in that voice leading the common tone changes voices. I don't know how that alternative/preferred voice leading is presented in the 5th edition, but in 1st edition, all voices moving to nearest next tone, contrary to bass, is given first for root progression by step like `IV V` and later as an alternative for `II V`.
Comment: @MichaelCurtis The fifth edition presents the two voicings as given in the OP. The key element here is the "contrary to the bass" aspect. In the "unusual" voicing the upper voices and bass all move similarly, creating a soprano-bass hidden octave, which is why the second voicing is preferred.
Comment: Are you talking about example 3-27 `g`?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/144340/discussion-between-aaron-and-michael-curtis).
Answer: The root progression is a descending fifth and the normal voice leading for that is hold the common tone, move the other two voices by step.
My first edition of Piston's Harmony does not have these exact examples you give (either I can't find them or you have another edition) but he addresses part of your question in the section THE DIRECT OCTAVE AND FIFTH.
Piston explains about the direct octave in the outer voices:

it is usually avoided in upward movement
except when the upper voice moves by a minor second, acting as a leading tone

Your "unusual" example shows a direct octave in the outer voices, and the upper voice moves by a whole step, and so should be avoided.
This is similar to advice he gives about II V (the first edition uses all upper case Roman numerals) where rather than holding the common tone Piston says to move the upper voices down to the next available position. This is what your "preferred" example does except on roots III VI.
Piston does not connect these two ideas explicitly, but II V does not have any half step movements, so there is some overlap in the two guidelines.
It would help to have the text that goes with your examples, because Piston seemed pretty good at explaining his ideas in both words and notation. It seems to me you could also avoid the direct octave issue by either making the bass descend or putting the tenor part B C into the soprano. The "preferred" solution given in example h may be meant to illustrate one particular point of the text and not the only way to voice lead III VI.

I found a copy of the 5th edition online.
The full chart for ex. 3-27 is...

The order of examples in the chart seems a little confusing to me, so I'll describe it with a slightly different order.

a is the Rule of Thumb 1, but deemed "unusual" because in II V when the soprano is scale degree ^4 it should descend, so b is "preferred" where the upper voices all descend to the next closest tones.

In terms of root progression c is the same as a and b, the reason that this example follows Rule of Thumb 1 as "usual" is because the soprano is not scale degree ^4, but #^4 acting as a leading tone.

g is the application of Rule of Thumb 1, but deemed "unusual" because in upward movement, the preferred motion to a direct octave is with the soprano moving by a minor second, acting as a leading tone, so h is given as "preferred", because it avoids the direct octave.

f is the same root progression of a descending fifth which is found in all the other examples above, and is exhibits Rule of Thumb 1, and is deemed "acceptable despite the soprano moving by whole step and not acting as a leading tone.
Unless I missed something the text really doesn't explain the difference between f and g. They are the same in terms or root progression and voice leading. Except for changing the octave of the held voice, all the internals are the same, the two are just an exact transposition. The only difference is the chord and scale degree relationships to the tonic. At first the "acceptable" and "unusual" labels seem contradictory, but the difference probably lies in treatment of scale degrees.
Later in the text there is a section Tonality and Modality in which the importance of the various scale degrees and chords are discussed with the very broad generalization that tonal degrees are more important than, and get emphasized more than, modal degrees. F may be "acceptable", because the direct octave, which is a kind of emphasizing, moves to scale degree ^2, which is generally considered tonal or between tonal and modal. By comparison g is a direct octave to scale degree ^6, a modal degree that perhaps should not be emphasized. This is just my speculation, but I'm trying to keep within the overall sense of Piston's text. Scale degree function and tonal/modal distinctions are important concepts in the book.
I think some mention of the descending fifths sequence needs to be made in relation to this question. A descending fifth root progression uses the Rule of Thumb 1 for basic voice leading. The "preferred" voice leading is an alternative to Rule of Thumb 1 which moves the voices in a descending fashion. It is common for a descending fifths sequence to use both voice leading patterns in an alternating pattern. In a sequence the "rule", "unusual", and "preferred" don't apply, the two voice leading patterns are on equal footing. Sequential passages are often regarded as tonally ambiguous which removes a clear sense of scale degree identities. Those identities are a driving factor in the labeling of acceptability in example 3-27.
Comment: Ah, I saw your question about which edition as I was logging in to update my answer.  Seeing that, it didn't dawn on me to look for an answer from you. In my edition, I don't find the comment about the soprano moving my half step. Allowing I might have missed it, that's a valuable distinction. Anyway, +1.
Answer: Piston's book establishes the "rules" of basic harmony. In the spirit of "breaking all the rules" it would depend on what voicing came before and what came after and how that feels to you should you be the composer.
Comment: Yes.   Theory is descriptive,  not prescriptive.
Comment: IMO, Piston's _Harmony_ is more about essential guidelines (not rules), the main ones being: root progression, voice leading, tone doubling, scale degree function. When he deviates from those essential guidelines, it's usually for the sake of melody, and an artistic choice. "Breaking all the rules" is vague and not really how Piston talks about harmony.


How to remove a module with command line?

Question: After uninstalling all relevant modules with drush un I have tried the following input and got the following output, but I don't think I did it correctly.
composer remove vendor/panels

vendor/panels is not required in your composer.json and has not been removed
./composer.json has been updated
Running composer update vendor/panels
Loading composer repositories with package information
Package "vendor/panels" listed for update is not locked.
Updating dependencies
Nothing to modify in lock file
Installing dependencies from lock file (including require-dev)
Nothing to install, update or remove
Package doctrine/reflection is abandoned, you should avoid using it. Use roave/better-reflection instead.
Package symfony/debug is abandoned, you should avoid using it. Use symfony/error-handler instead.
Package webmozart/path-util is abandoned, you should avoid using it. Use symfony/filesystem instead.
Generating autoload files
48 packages you are using are looking for funding.
Use the composer fund command to find out more!
Comment: You can only remove packages that exist. You probably mean to type `drupal/panels`.
https://getcomposer.org/doc/
Answer: Check the composer.json for the actual package name.  In this case, for the panels module, it should be drupal/panels, so the command is composer remove drupal/panels.
Comment: In composer.json for my project I have found, under `"require": {` this: `"drupal/panels": "^4.6",`.
Comment: After running the command you shown I no longer found it !
Comment: I recommend the concise and useful official Composer documentation: https://getcomposer.org/doc/


OpenGL ES to video in iOS (rendering to a texture with iOS 5 texture cache)

Question: You know the sample code of Apple with the CameraRipple effect? Well I'm trying to record  the camera output in a file after openGL has done all the cool effect of water.
I've done it with glReadPixels, where I read all the pixels in a void * buffer , create  CVPixelBufferRef and append it to the AVAssetWriterInputPixelBufferAdaptor, but it's too slow, coz readPixels takes tons of time. I found out that using FBO and texture cash you can do the same, but faster. Here is my code in drawInRect method that Apple use:
CVReturn err = CVOpenGLESTextureCacheCreate(kCFAllocatorDefault, NULL, (__bridge void *)_context, NULL, &coreVideoTextureCashe);
if (err)
{
    NSAssert(NO, @"Error at CVOpenGLESTextureCacheCreate %d");
}

CFDictionaryRef empty; // empty value for attr value.
CFMutableDictionaryRef attrs2;
empty = CFDictionaryCreate(kCFAllocatorDefault, // our empty IOSurface properties dictionary
                           NULL,
                           NULL,
                           0,
                           &kCFTypeDictionaryKeyCallBacks,
                           &kCFTypeDictionaryValueCallBacks);
attrs2 = CFDictionaryCreateMutable(kCFAllocatorDefault,
                                  1,
                                  &kCFTypeDictionaryKeyCallBacks,
                                  &kCFTypeDictionaryValueCallBacks);

CFDictionarySetValue(attrs2,
                     kCVPixelBufferIOSurfacePropertiesKey,
                     empty);

//CVPixelBufferPoolCreatePixelBuffer (NULL, [assetWriterPixelBufferInput pixelBufferPool], &renderTarget);
CVPixelBufferRef pixiel_bufer4e = NULL;

CVPixelBufferCreate(kCFAllocatorDefault,
                    (int)_screenWidth,
                    (int)_screenHeight,
                    kCVPixelFormatType_32BGRA,
                    attrs2,
                    &pixiel_bufer4e);
CVOpenGLESTextureRef renderTexture;
CVOpenGLESTextureCacheCreateTextureFromImage (kCFAllocatorDefault,
                                              coreVideoTextureCashe, pixiel_bufer4e,
                                              NULL, // texture attributes
                                              GL_TEXTURE_2D,
                                              GL_RGBA, // opengl format
                                              (int)_screenWidth,
                                              (int)_screenHeight,
                                              GL_BGRA, // native iOS format
                                              GL_UNSIGNED_BYTE,
                                              0,
                                              &renderTexture);
CFRelease(attrs2);
CFRelease(empty);
glBindTexture(CVOpenGLESTextureGetTarget(renderTexture), CVOpenGLESTextureGetName(renderTexture));
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, CVOpenGLESTextureGetName(renderTexture), 0);

CVPixelBufferLockBaseAddress(pixiel_bufer4e, 0);

if([pixelAdapter appendPixelBuffer:pixiel_bufer4e withPresentationTime:currentTime]) {
                float result = currentTime.value;
            NSLog(@"\n\n\4eta danni i current time e : %f \n\n",result);
                currentTime = CMTimeAdd(currentTime, frameLength);
        }

CVPixelBufferUnlockBaseAddress(pixiel_bufer4e, 0);
CVPixelBufferRelease(pixiel_bufer4e);
CFRelease(renderTexture);
CFRelease(coreVideoTextureCashe);

It records a video and it's pretty quick, yet the video is just black I think the textureCasheRef is not the right one or am I filling it wrong.
As an update, here is another way I've tried. I must be missing something. In viewDidLoad, after I set the openGL context I do this:
CVOpenGLESTextureCacheCreate(kCFAllocatorDefault, NULL, (__bridge   void *)_context, NULL, &coreVideoTextureCashe);

    if (err)
    {
        NSAssert(NO, @"Error at CVOpenGLESTextureCacheCreate %d");
    }

    //creats the pixel buffer

    pixel_buffer = NULL;
    CVPixelBufferPoolCreatePixelBuffer (NULL, [pixelAdapter pixelBufferPool], &pixel_buffer);

    CVOpenGLESTextureRef renderTexture;
    CVOpenGLESTextureCacheCreateTextureFromImage (kCFAllocatorDefault, coreVideoTextureCashe, pixel_buffer,
                                                  NULL, // texture attributes
                                                  GL_TEXTURE_2D,
                                                  GL_RGBA, //  opengl format
                                                   (int)screenWidth,
                                                  (int)screenHeight,
                                                  GL_BGRA, // native iOS format
                                                  GL_UNSIGNED_BYTE,
                                                  0,
                                                  &renderTexture);

    glBindTexture(CVOpenGLESTextureGetTarget(renderTexture), CVOpenGLESTextureGetName(renderTexture));
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, CVOpenGLESTextureGetName(renderTexture), 0);

Then in drawInRect: I do this:
 if(isRecording&&writerInput.readyForMoreMediaData) {
    CVPixelBufferLockBaseAddress(pixel_buffer, 0);

    if([pixelAdapter appendPixelBuffer:pixel_buffer withPresentationTime:currentTime]) {
        currentTime = CMTimeAdd(currentTime, frameLength);
    }
    CVPixelBufferLockBaseAddress(pixel_buffer, 0);
    CVPixelBufferRelease(pixel_buffer);
}

Yet it crashes with bad_acsess on the renderTexture, which is not nil but 0x000000001.
UPDATE
With the code below I actually managed to pull the video file, but there are some green and red flashes. I use BGRA pixelFormatType.
Here I create the texture Cache:
CVReturn err2 = CVOpenGLESTextureCacheCreate(kCFAllocatorDefault, NULL, (__bridge void *)_context, NULL, &coreVideoTextureCashe);
if (err2)
{
    NSLog(@"Error at CVOpenGLESTextureCacheCreate %d", err);
    return;
}

And then in drawInRect I call this:
if(isRecording&&writerInput.readyForMoreMediaData) {
    [self cleanUpTextures];

    CFDictionaryRef empty; // empty value for attr value.
    CFMutableDictionaryRef attrs2;
    empty = CFDictionaryCreate(kCFAllocatorDefault, // our empty IOSurface properties dictionary
                           NULL,
                           NULL,
                           0,
                           &kCFTypeDictionaryKeyCallBacks,
                           &kCFTypeDictionaryValueCallBacks);
    attrs2 = CFDictionaryCreateMutable(kCFAllocatorDefault,
                                   1,
                                   &kCFTypeDictionaryKeyCallBacks,
                                   &kCFTypeDictionaryValueCallBacks);

    CFDictionarySetValue(attrs2,
                     kCVPixelBufferIOSurfacePropertiesKey,
                     empty);

//CVPixelBufferPoolCreatePixelBuffer (NULL, [assetWriterPixelBufferInput pixelBufferPool], &renderTarget);
    CVPixelBufferRef pixiel_bufer4e = NULL;

    CVPixelBufferCreate(kCFAllocatorDefault,
                    (int)_screenWidth,
                    (int)_screenHeight,
                    kCVPixelFormatType_32BGRA,
                    attrs2,
                    &pixiel_bufer4e);
    CVOpenGLESTextureRef renderTexture;
    CVOpenGLESTextureCacheCreateTextureFromImage (kCFAllocatorDefault,
                                              coreVideoTextureCashe, pixiel_bufer4e,
                                              NULL, // texture attributes
                                              GL_TEXTURE_2D,
                                              GL_RGBA, // opengl format
                                              (int)_screenWidth,
                                              (int)_screenHeight,
                                              GL_BGRA, // native iOS format
                                              GL_UNSIGNED_BYTE,
                                              0,
                                              &renderTexture);
    CFRelease(attrs2);
    CFRelease(empty);
    glBindTexture(CVOpenGLESTextureGetTarget(renderTexture), CVOpenGLESTextureGetName(renderTexture));
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, CVOpenGLESTextureGetName(renderTexture), 0);

    CVPixelBufferLockBaseAddress(pixiel_bufer4e, 0);

    if([pixelAdapter appendPixelBuffer:pixiel_bufer4e withPresentationTime:currentTime]) {
        float result = currentTime.value;
        NSLog(@"\n\n\4eta danni i current time e : %f \n\n",result);
        currentTime = CMTimeAdd(currentTime, frameLength);
    }

    CVPixelBufferUnlockBaseAddress(pixiel_bufer4e, 0);
    CVPixelBufferRelease(pixiel_bufer4e);
    CFRelease(renderTexture);
  //  CFRelease(coreVideoTextureCashe);
}

I know I can optimize this a lot by not doing all these things here, yet I use wanted to make it work. In cleanUpTextures I flush the textureCache with:
 CVOpenGLESTextureCacheFlush(coreVideoTextureCashe, 0);

Something might be wrong with the RGBA stuff or I don't know but it seems that it's still getting kind of wrong Cache.
Comment: Please provide the memory warning you receive, or a screenshot of the crash.
Comment: When I hit the record button, which calls startWriting to my AssetWriter, it just freezes for a second and Received memory warning. appears
Comment: Are you able to record video using this method and display the contents to screen at the same time?
Answer: For recording video, this isn't the approach I'd use. You're creating a new pixel buffer for each rendered frame, which will be slow, and you're never releasing it, so it's no surprise you're getting memory warnings.
Instead, follow what I describe in this answer. I create a pixel buffer for the cached texture once, assign that texture to the FBO I'm rendering to, then append that pixel buffer using the AVAssetWriter's pixel buffer input on every frame. It's far faster to use the single pixel buffer than recreating one every frame. You also want to leave the pixel buffer associated with your FBO's texture target, rather than associating it on every frame.
I encapsulate this recording code within the GPUImageMovieWriter in my open source GPUImage framework, if you want to see how this works in practice. As I indicate in the above-linked answer, doing the recording in this fashion leads to extremely fast encodes.
Comment: ok, here's what i do in drawInRect and it's fast but it records black video. I think the textureCasheRef it's getting is empty or not the right one , dunno

I updated the question
Comment: @user1562826 - In the future, feel free to just update your original question with the new information. I've done that here for you. You aren't trying to access this pixel buffer and its bound texture on a different thread than your rendering, are you? Simultaneous access to an OpenGL ES context from multiple threads can lead to crashes.
Comment: No, I use only one thread. I managed to get the video file, yet I still think the texture Cache is not properly extracted from the OpenGL context because in the video there is this line from the two corners of the screen, and its kinda red above the line and kinda green below and there are these strange flashes. I update my question. Thanks for the help!
Comment: @BradLarson "I create a pixel buffer for the cached texture once" -- how does this work? Why does Apple create and destroy it all every single frame in their sample code? It seems to me horribly inefficient, but with zero docs from Apple, I don't see any alternative. I want to understand the simple case here, but I keep hitting your answers (it's impressive what you've worked out!) that go in circles x-referencing each other, and saying "this is a replacement for glReadPixels", but not explaining the other uses.
Comment: @Adam - I'm not sure what Apple sample code you're referring to, but they didn't have any examples that did this at the time that I wrote the above-linked answer (and the code there). For the texture caches, there's overhead in setting up the pixel buffer, which is why you do it once, but after that point the internal bytes are directly mapped to your texture. You then want to reuse the pixel buffer for maximum performance when recording, as the texture bytes within it will be updated as the texture contents are.


How can we calculate the side $AC$?

Question: In the triangle $ABC$ it holds that $|AB| = 10$, for the midpoint $C'$ of the side $AB$ it holds that $|CC'| = 8$ and the interior angle at $C$ at the triangle $BCC'$ is $\frac{\pi}{6}$.
(a) What can we say about the distance between $A$ and $C$?
(b) Let $M$ be the midpoint ofthe circumcenter of the triangle. Determine all possibilities for the angle $\angle AMB$.
Using the cosine law we could calculate the side $BC$, right?
But how can we calculate the side $AC$?
Comment: Once you find $BC$, use the formula for median.
Comment: $4CC'^2 = 2(AC^2+BC^2) - AB^2$
Answer: a) Apply the sine rule to $BCC'$
$$\sin B= \frac85\sin\frac\pi6=\frac45,\>\>\>\>\>\cos B = \pm\frac35
$$
Then, apply the cosine rule to $ACC'$
$$AC^2 = 8^2+ 5^2 - 2\cdot8\cdot 5\cos(B+\frac\pi6)=121\pm24\sqrt3
$$
Thus, two possibilities for the distance $AC = \sqrt{ 121\pm24\sqrt3} $.
b) Note $\angle AMB =2C$ and apply the sine rule to $ABC$
$$ {\sin C}=\frac {AB}{AC}\sin B = \frac{10}{ \sqrt{ 121\pm24\sqrt3} }\cdot \frac45= \frac8{ \sqrt{ 121\pm24\sqrt3} }$$
Thus, two possible anglular values
$$\angle AMB = 2C = 2\arcsin \frac8{\sqrt{ 121\pm24\sqrt3} }$$
Comment: @MaryStar - correct. you're welcome
Comment: Thank you so much!! It is very clear!! Just a question... It should be ${\sin C}=\frac {AB}{AC}\sin B $ instead of ${\sin C}=\frac {AC}{AB}\sin B $ right?
Answer: $\sin (\pi/6)/5=\sin \beta  /8$, then third angle in the triangle is $\tau=180-\beta-30$, then angle $\rho=180-\tau$. We have now the second triangle, there is the angle $\rho$, and $AC'=5,CC'=8$, we can use cosine formula $(AC)^2=8^2+5^2-80*\cos \rho$.

How can we calculate the side $AC$?


Create objects in pre-allocated memory

Question: We can use placement new to create an object in pre-allocated memory.
Let's consider the following example:
char *buf  = new char[1000];   //pre-allocated buffer
string *p = new (buf) MyObject();  //placement new
string *q = new (buf) MyObject();  //placement new

I've created two objects in the pre-allocated buffer. Are the two objects created randomly within the buffer or created in contiguous memory blocks? If we keep creating more objects in the buffer and want them to be stored in contiguous memory blocks, what should we do? Create an array in the buffer first and then create each object in the element slots of the array?
Comment: "If we keep creating more objects in the buffer and want them to be stored in contiguous memory blocks, what should we do?" Use `std::vector`, it is a contiguously stored dynamic array.
Answer: The two objects are both created at the same memory location, namely buf. This is undefined behaviour (unless the objects are POD).
If you want to allocate several objects, you have to increment the pointer, e.g. buf + n * sizeof(MyObject), but beware of alignment issues
Also don't forget to call destructors when you're done.
Comment: Because the buffer was allocated with `new`, it has alignment to support any type (including arrays). (Not that you're wrong in general, just in this case he's safe.)
Comment: @GMan: Thanks, good point. I suppose extra attention is needed if you want to put objects of different types in the memory.
Comment: "Plain old data", i.e. a fundamental type, or arrays of PODs, or classes without constructors etc containing only PODs. Anything that's determined by its binary representation alone and can be memcopied.
Answer: The following line of code:
string *p = new(adr) MyObject();

will create a MyObject object at the address adr. Then next time you create another object, you will know that the memory at adr is being used by the first object, so your next object will have to be created at adr + sizeof(MyObject):
string *q = new(adr + sizeof(MyObject)) MyObject();

The point of pre-allocated memory is so that you aren't allocating at runtime, which is pretty slow. You do one big allocation at the beginning of the loop/program and then you just have to use chunks of that allocation. The down side is that you have to manage your own memory which means you have to figure out where to put your objects which gets tricky when your memory pool gets fragmented!
Comment: if adr = static_cast(byteaddr) then you would do: string *q = new(adr+1)MyObject();

Create objects in pre-allocated memory


How can I remove the duplicate value from the first column only and then arrange the data in second column horizontally?

Question: I want to remove the duplicate value from the first column only and then arrange the data in second column horizontally using value of first column as the first value for each row where each column would align with each other.
blunt-snouted_clingfish rdh14b
blunt-snouted_clingfish LOC114457682
blunt-snouted_clingfish rngtt
blunt-snouted_clingfish cnr1
blunt-snouted_clingfish akirin2
blunt-snouted_clingfish rars2
blunt-snouted_clingfish slc35a1
blunt-snouted_clingfish LOC114457715
blunt-snouted_clingfish rhag

Chinese_tongue_sole nt5c1bb
Chinese_tongue_sole si:dkey-174m14.3
Chinese_tongue_sole rdh14b
Chinese_tongue_sole LOC103381225
Chinese_tongue_sole rngtt
Chinese_tongue_sole cnr1
Chinese_tongue_sole akirin2
Chinese_tongue_sole rars2
Chinese_tongue_sole riox1
Chinese_tongue_sole ndufb1
Chinese_tongue_sole cpsf2

Helicophagus_hypophthalmus_Sauvage,_1878 myo6a
Helicophagus_hypophthalmus_Sauvage,_1878 LOC113528782
Helicophagus_hypophthalmus_Sauvage,_1878 mei4
Helicophagus_hypophthalmus_Sauvage,_1878 nt5e
Helicophagus_hypophthalmus_Sauvage,_1878 snx14
Helicophagus_hypophthalmus_Sauvage,_1878 cnr1
Helicophagus_hypophthalmus_Sauvage,_1878 rngtt
Helicophagus_hypophthalmus_Sauvage,_1878 pnrc1
Helicophagus_hypophthalmus_Sauvage,_1878 LOC113528790
Helicophagus_hypophthalmus_Sauvage,_1878 LOC113529170
Helicophagus_hypophthalmus_Sauvage,_1878 c30h8orf82

The output should be:
blunt-snouted_clingfish rdh14b LOC114457682 rngtt cnr1 akirin2 rars2 slc35a1 LOC114457715 rhag

Chinese_tongue_sole nt5c1bb si:dkey-174m14.3 rdh14b LOC103381225 rngtt cnr1 akirin2 rars2 riox1 ndufb1 cpsf2

Helicophagus_hypophthalmus_Sauvage,_1878 myo6a LOC113528782 mei4 nt5e snx14 cnr1 rngtt pnrc1 LOC113528790 LOC113529170 c30h8orf82

It would be better if the columns align with themselves and there is a space between each row. It would help me visualise it better.
I tried using:
awk '{if (!seen[$1]++) {print $1, $2}}'

But it only removes all the duplicates from the first row and removing the values from second column.
blunt-snouted_clingfish LOC114457607
Chinese_tongue_sole nt5c1bb
Helicophagus_hypophthalmus_Sauvage,_1878 myo6a

Comment: You're leaving a lot of potentially important details out. Where does the input data come from ? Is it supposed to be read from a file or is it piped into stdin by another process or ? And is the input always pre-sorted already like your example is ? or could there for example be another `Chinese_tongue_sole` line at the very bottom. Also are you looking for a script or a command
Answer: Assuming you don't REALLY have a blank character in every line that otherwise appears to be empty in your input (if you do, just do sed 's/^  *$//' or similar to remove them), then using any awk:
$ awk -v RS= -v ORS='\n\n' '{str=$1; for (i=2; i<=NF; i+=2) str=str OFS $i; print str}' file
blunt-snouted_clingfish rdh14b LOC114457682 rngtt cnr1 akirin2 rars2 slc35a1 LOC114457715 rhag

Chinese_tongue_sole nt5c1bb si:dkey-174m14.3 rdh14b LOC103381225 rngtt cnr1 akirin2 rars2 riox1 ndufb1 cpsf2

Helicophagus_hypophthalmus_Sauvage,_1878 myo6a LOC113528782 mei4 nt5e snx14 cnr1 rngtt pnrc1 LOC113528790 LOC113529170 c30h8orf82

and piping to column to get the column alignment you asked for:
$ awk -v RS= '{str=$1; for (i=2; i<=NF; i+=2) str=str OFS $i; print str}' file | column -t | awk -v ORS='\n\n' '1'
blunt-snouted_clingfish                   rdh14b   LOC114457682      rngtt   cnr1          akirin2  rars2  slc35a1  LOC114457715  rhag

Chinese_tongue_sole                       nt5c1bb  si:dkey-174m14.3  rdh14b  LOC103381225  rngtt    cnr1   akirin2  rars2         riox1         ndufb1        cpsf2

Helicophagus_hypophthalmus_Sauvage,_1878  myo6a    LOC113528782      mei4    nt5e          snx14    cnr1   rngtt    pnrc1         LOC113528790  LOC113529170  c30h8orf82


Flutter: How to stop showing mobile App when running the Web version in browser

Question: I am building an application using Flutter in both the Mobile and Web platforms. I have a few different UI to show from Web to Mobile. In the Web version running on the chrome when I change the size of the browser, it shows the mobile app pages.
How to stop this, so that the Web version should not show the mobile version when the browser layout gets changed.
Answer: I assume that you check the size of the layout like:
if (layoutSize <= someValue) {
  switchToSmallerLayout();
}

You can try to do like this if you want to prevent switching on mobile devices
bool get _isMobile => Platform.isIOS || Platform.isAndroid;

if (layoutSize <= someValue && !_isMobile) {
  switchToSmallerLayout();
}

This should solve your problem.


Can a free product of groups be co-Hopfian?

Question: A group $G$ is called co-Hopfian if it is not isomorphic to a proper subgroup of itself; equivalently, every injective group homomorphism $\varphi : G \to G$ is surjective and hence an isomorphism. Examples of co-Hopfian groups include finite groups, $\mathbb{Q}$, $\mathbb{Q}/\mathbb{Z}$, and fundamental groups of closed hyperbolic manifolds. Examples of groups which are not co-Hopfian include free groups, free abelian groups, $\mathbb{R}$, and $\mathbb{Q}^*$ (take $\varphi(x) = x^3$).
In this MathOverflow answer, Ian Agol shows that if a group $C$ is freely indecomposable (i.e. not a non-trivial free product) and co-Hopfian, then $A\ast C \cong B\ast C$ implies $A\cong B$. As all the examples of co-Hopfian groups I have been able to find are freely indecomposable, I wonder if they all must be, in which case the first condition on $C$ is superfluous.

Is a co-Hopfian group necessarily freely indecomposable?

Note, answering this question is equivalent to answering the question in the title.
I've seen it claimed in a couple of papers that the answer is yes, but references weren't provided which makes me think that this should be fairly elementary. If $G \cong A\ast B$ is co-Hopfian, then there is a proper subgroup $H$ with $H\cong G$. By the Kurosh subgroup theorem, there is a set $X \subseteq G$, a family of subgroups $(A_i)_{i\in I}$ of $A$, a family of subgroups $(B_j)_{j\in J}$ of $B$, and families of elements $(g_i)_{i\in I}$, $(f_j)_{j\in J}$ of $G$ such that $H = F(X)\ast\left(\ast_{i\in I}g_iA_ig_i^{-1}\right)\ast\left(\ast_{j\in J}f_jB_jf_j^{-1}\right)$. I don't know where to go from this point. In particular, I don't know if the fact that $H$ is a proper subgroup yields any information about the cardinalities of $X$, $I$, and $J$.
Answer: $A*B$ is never co-hopfian, as it contains as a proper (isomorphic) subgroup $A*(ba)B{(ba)}^{-1}$, where $a, b$ are two arbitrary non trivial elements in $A$ and $B$ respectively.
Comment: Very nice. One way to see that the subgroup $A\ast(ba)B(ba)^{-1}$ is proper is to note that it does not contain any non-identity element of $B$. Is this something you just came up with or have you seen it before in a book or course?


User cannot view their Orders in Ubercart

Question: For Drupal (v7.22) I have a basic install of Ubercart (v7.x-3.4) and have set the permissions to allow an authenticated user to 'View own orders' and View own invoices'. But if an authenticated user visits an order page (for an order they made) they get the error:
page: example.com/user/user_name/orders/1

Access denied
You are not authorized to access this page.

I've been though all of the settings and googled this but cannot see what I've missed. Does anyone know if I've missed a permission/setting somewhere?
Comment: @Bala with "View own orders" set to true, how "access denied" is not an error? I mean, it's not an error in the module, it works for way to many people, but it is something wrong with OP's setup, and if you have a clue what it might be, please share.
Comment: Please use http://example.com and http://example.org in examples, not commercial domains.
Comment: this is not an error, its an permission issue
Comment: @Mołot it encourage me to post answer
Answer: Enable the Allow customers to view order invoices from their order history in Order settings, see the below image may be this will be the problem for you and i am not sure because i have drupal 6 installation only.


Simple, step-by-step excercises for those who wants to learn to play sheet music?

Question: Let's say I'm a newbie at playing sheet music and want to learn how to read, and more essentially, play sheet music.
Is there exists any step-by-step exercises, starting from simple and advancing to complicated, for those who wants to learn how to play a sheet music?
Software, which proposes such a learning will be ok too.
Comment: Each instrument will have its own peculiarities appertaining to reading printed music. Which particular instrument is in question?
Comment: @Tim, I'm mainly interested in guitar
Answer: There is plenty of software out there that will help you to learn to read score.
Try some of these:
https://play.google.com/store/apps/details?id=rylee.gaddict.gfba
https://play.google.com/store/apps/details?id=com.punktumsoft.android.guitarnotetrainer
Answer: Most guitar sight-reading courses seem to start using open strings, and the C scale notes. At some point, one has to move away from open strings - in fact good players will rarely use them.
I advocate learning the major and minor scales up and down the neck, 2 octaves each, in one shape initially, so that if for example, the piece is in A, you'll be playing from fret 4 to fret 7 in major, and 5 to 8 in minor.This gives a good scope for most tunes, as most tunes don't encompass more than an octave or so. At least not in the easier, learner stages.Once you've found the first note, try to think along the lines of - the next note is 2 notes up from that one, so I move to the note 2 notes up in the scale.
To a great extent this obviates the need to keep thinking 'I must remember which notes are sharp/flat in this key'.You will know the notes that are relevant to the key you're in, so it will happen automatically. Obviously, accidentals will need to be addressed, but in the early stages they are not going to be that common. Once you get used to the concept, you'll be able to compensate.
After a while, move to other scale pattern in different places on the neck - bearing in mind the next one up will have its lower notes in the same place as the higher notes of the pattern below.
The 'problem' with guitars is that there are often several different places to play the same note. This can be alleviated using tab., but then you get to play where the tab says, which may not be the optimum place.
Answer: The best step-by-step method would be one tailored specifically to you by a good teacher of the style you're interested in, at least to get started.  He or she can assess where you are currently and help you make the quickest progress with respect to reading.  Make sure to let the teacher know this is one of your goals.  A good teacher can help you make steady progress without losing interest, which I think is a major risk factor in learning to read, depending on the style your interested in.
If you're not interested in working with a teacher, or can't find the right one, the best step-by-step method I've seen for the guitar (for popular music) is the "Modern Method for Guitar" by William Leavitt.  It starts out in the open positions, then moves up position by position.  The early exercises are relatively easy, though not terribly inspiring, but if you stick to it you will definitely learn to read anything anywhere on the neck.  Be sure to balance it with other types of material that you find interesting.
For Classical music, take a look at beginner books by Fredrick  M. Noad, such as "Solo Guitar Playing I".


Javascript em popup não enxerga os campos da página pai

Question: Tenho uma consulta em uma popup que o resultado é retornado em uma gridview. Na gridview eu tenho um botão onde eu chamo uma função javascript que insere o resultado correlacionando o retorno da consulta com os campos da página principal. Estou conseguindo entrar na função, mas quando eu chego na parte que faz o relacionamento, surge o erro:

window.opener.document.frm is undefined

O trecho:
 window.opener.document.frm.txtDS_PES.value = trim(pesnm);

No firebug eu indentifiquei que a partir do frm.txtDES_PES.value ele da undefined.
<form id="frm" runat="server">

Comment: Tente verificar se você pode acessar o opener com var opener = window.opener;
if(opener) {//Teste}
Comment: Não é o caso. Pois consigo acessar a outra página, só não os objetos.
Answer: Cria uma função na sua página normal (sem ser a popup) pra atualizar os valores de acordo com o ids.
function atualizaValor(id, value)
{
    document.getElementById(id).value = value;
}

E depois na sua popup é só chamar:
window.opener.atualizaValor('txtDS_PES', trim(pesnm));

Comment: tenho uns 20 campos para fazer essa atualização. Não vai ficar pesado?
Comment: Acredito que não, afinal são 20 `tags` diferentes né?
Comment: Da o erro: TypeError: document.getElementById(...) is null, engraçado é que ele reconhece a outra página e ainda reconhece a função.
Comment: como tu sabe que reconhece a outra página?
Comment: Porque eu tô fazendo o Debug do fire bug! Inclusive eu coloquei um break point na pagina principal e ele entra no atualizarValor.
Comment: então o problema está nas suas tags, você tem algum input com o **ID** txtDS_PES?
Comment: ou esse txtDS_PES é o name?
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/25248/discussion-between-maicon-carraro-and-germano-sampaio).
Comment: o problema é que além de está passando o valor para um textbox visible=false, eu estava passando o nome do ID corretamente. Pois quando o site é renderizado, os componentes mudam de nome. A solução foi passar o ContentPlaceHolder1_ na frente do campo. Exemplo: ContentPlaceHolder1_txtDS_PES e na página, ao invés de passar um campo visible=false, eu utilizei o componente asp:HiddenField. Agora o problema é que quando eu fecho a popup os dados da que foram para tela principal desaparece.
Comment: Quando tu fecha a `popup` não está fazendo algum postback pra tela anterior, não?
Comment: Atualiza as tags  mas quando dou um window.close() na popup as informações na tela pai n permanecem. Eu não quero que a tela pai dê o refresh, pois tenho mais dois acessos a popup a fazer antes de jogar no banco. Eu não quero ter que ir ao servidor para fazer isso!
Comment: Tenta utilizar `UpdatePanel` pra não forçar a atualização, se quiser podemos ir chat
Comment: Deu certo com o UpdatePanel . Obrigado!


Is it possible to have two different apps with thinking sphinx pointing to the same database?

Question: I inherited a legacy app running Thinking Sphinx v3. I've been working on a large update for it, upgrading rails, etc.
My updated app now has a different Thinking Sphinx index, but it shares the same schema. It also uses delta indexing with Delayed Job.
I have a beta environment fully up and running but I now want to point the beta app to the production database so my colleagues can test the update safe in the knowledge that if anything goes awry they can always fallback to the live app.
Is it possible for these two environments to co-exist? How should I be configuring my app or the database server?
Answer: It's generally possible to have two apps pointing to the same database, yes. Of course, there may be behaviours in one that impact the other, so you'd want to consider that complication!
With regards to Thinking Sphinx: each app's daemon and index data will be separate from the other, so that won't be a problem either. If you're running both apps on the same machine, though, you'll want to make sure the daemons are using different ports through the mysql41 setting.
Comment: Upon deliberation we decided against this setup, as the two apps would effectively be fighting over the database. We were admittedly confused about having multiple daemons, indexes, etc, sharing a box, so it's good to know it's possible. Thanks for the response!


For and If in R data programming

Question: I want to evaluate the distance between non-zero data. So if i have 50 data, and only the first and last data is non-zero, thus i want the result to be 49.
For example, my data is:
1. 0
2. 0
3. 5
4. 6
5. 0
6. 1
7. 0

Based on my data above, i want to get 4 variables:
v0 = 3 (because the distance between 0th to 3rd data is 3 jumps)
v1 = 1 (because the distance between 3rd to 4th data is 1 jump)
v2 = 2 (because the distance between 4rd to 6th data is 2 jump)
v3 = 1 (because the distance between 6rd to 7th data is 1 jump)

This is my code:
data=c(0,0,5,6,0,1,0)

t=1
for (i in data) {
  if (i == 0) {
    t[i]=t+1
  }
  else {
    t[i]=1
  }
}

t

The result is:
[1]  1 NA NA NA  1  1

Could you help me in figuring out this problem? I also hope that the code is using some kind of loop, so that it can be applied to any other data.
Comment: I cannot understand why v0 is jump from 0th to 3rd?
Comment: In your code you are using i to set the value of t[i]. But i assumes all values in your vector data (and not the values from 1 to the length of the vector data. So this means only the values t[0], t[1], t[5], and t[6] will be assigned a value and the rest will be undefined (NA). So your code is working as expected. I am uncertain what you are exactly trying to get as an output though, so I can't help there.
Answer: The general rule is not clear from the question but if x is the input we assume that:

the input is non-negative
the first element in output is the position of the first +ve element in x
subsequent elements of output are distances between successive +ve elements of x
if that results in a vector whose sum is less than length(x) append the remainder

To do that determine the positions of the positive elements of c(1, x), calculate the differences between successive elements in that reduced vector using diff and then if they don't sum to length(x) append the remainder.
dists <- function(x) {
  d <- diff(which(c(1, x) > 0))
  if (sum(d) < length(x)) c(d, length(x) - sum(d)) else d
}

# distance to 5 is 3 and then to 6 is 1 and then to 1 is 2 and 1 is left
x1 <- c(0, 0, 5, 6, 0, 1, 0)
dists(x1)
## [1] 3 1 2 1

# distance to first 1 is 1 and from that to second 1 is 3
x2 <- c(1, 0, 0, 1)
dists(x2)
## [1] 1 3

Here it is redone using a loop:
dists2 <- function(x) {
  pos <- 0
  out <- numeric(0)
  for(i in seq_along(x)) {
    if (x[i]) {
      out <- c(out, i - pos)
      pos <- i
    }
  }
  if (sum(out) < length(x)) out <- c(out, length(x) - sum(out))
  out
}

dists2(x1)
## [1] 3 1 2 1

dists2(x2)
## [1] 1 3

Updates
Simplification based on comments below answer.  Added loop approach.
Comment: As good as answer as any. Minor quibble: "nonzero" *might* be "less than zero" in some contexts. Also, your `d` can be defined more simply as `diff(which(c(1,x) != 0))`.
Comment: Based on the examples in the question that input is non-negative. Have added your simplification using `which`.

For and If in R data programming


jQuery post data to the database?

Question: I'm creating a system on D7 that tracks how much progress users have made watching various videos on the site. I've set up the jQuery that stores the percentage progress in an array with a modified version of the process at https://www.urbaninsight.com/2014/10/06/tracking-progress-embedded-vimeo-videos. Where I'm lost is where I actually post the data using:
$.post('/callback', {
   progress: myProgressVariable
});
I realized that '/callback' is just a placeholder, but I don't know what to sub in there. Should I designate a callback() function in a custom module that does something with the progress data and just place the function name into the javascript -- and what might that look like? Or do I need to do something something else entirely?
Comment: The counterpart for the callback in Drupal would be a Controller defined in a route (or the hook in D7 that can do anything, not only menus). But better deliver the content in a form and trigger the submit, this is more secure.
Comment: So if the best way is to deliver the data via a form, how would I get the data from my jQuery object into the form if the form doesn't live on the active page? I'm assuming that the form doesn't need to be on the active page. I'd rather not have it there, actually, so that users couldn't manually submit values if they found it.
Comment: You can approach this from three sides. 1) Use the form api which includes the built-in mechanism to handle the form submits. You can hide the form if you want to keep it in the background. 2) Define your own controller and handle the post data yourself (which is IMHO more work to do if you want to do it right). 3) Keep Drupal out of it and use a standalone php file as callback.
Comment: I see you've added a D7 tag. The concept there was the same, you have to assign a php function to the path `/callback` and then check what post data comes in. What the php function returns doesn't matter, because your js code ignores it.
Answer: Ended up just using a custom hidden form as suggested by 4k4 and am populating/submitting it via jquery/ajax.

jQuery post data to the database?


Use JavaScript to Wrap Unique Groups of Elements with DIVs

Question: I am using a WordPress plugin that dynamically creates the following list on the fly:

I need to wrap specific lis in unique divs like this:

I've read about using the wrapall() function but I can't find instructions on how to wrap a group of elements that do not have the same class.
Comment: `$(".technique, .special, .servings").wrapAll("", {'class': 'other'});` and similar for the rest
Comment: How do you (intend to) define which element-classes should be added to which `div`? And, incidentally, a `div` is ***not*** a valid child of a `ul` element.
Answer: Assuming that you take the time to define the relationship between the class-names and the eventual id under which they should appear, and that you use valid HTML, the following plain JavaScript works (albeit I think it could be refined):
var grouped = {
    'main' : ['proteins','seafood','dairy','veggies','fruit'],
    'carbs' : ['nuts-seeds','grains','pasta'],
    'spice' : ['spices','herbs'],
    'other' : ['technique','special','servings']
};

function groupBy(el, map) {
    var els,
        newList = document.createElement('ul'),
        newListItem = document.createElement('li'),
        tmpList, tmpLI;
    for (var key in map) {
        if (map.hasOwnProperty(key)){
            els = el.querySelectorAll('.' + map[key].join(', .'));
            tmpList = newList.cloneNode();
            tmpLI = newListItem.cloneNode();
            tmpLI.appendChild(tmpList);
            tmpLI.id = key;
            for (var i = 0, len = els.length; i < len; i++){
                tmpList.appendChild(els[i]);
            }
            el.appendChild(tmpLI);
        }
    }
}

groupBy(document.querySelector('ul'),grouped);

JS Fiddle demo.
The above function converts:

Into:


How to Retrieve Env Var in Drush

Question: Is there a way to retrieve shell variables in Drush? I cannot find anything in Drush API docs. If there is no way, how does one handle environment (dev, staging, testing etc.) configurations? Any help is much appreciated. Thank you.
Answer: What do you mean by "in Drush"?
If you are working in a Drush commandfile (e.g. writing your own Drush command), then you can get environment variables via php using the getenv function.
If you are calling Drush from bash, then you can use bash to expand environment variables (e.g. drush dl --destination=$HOME/.drush)
If you are wondering what to do because you have set up your web server to define environment variables that you are using in settings.php to bootstrap Drupal, then you cannot read these from Drush or bash, because they are only defined by your webserver.  Try defining equivalent variables in your .bashrc.
Comment: By 'in drush' i mean i have script that is interpreted by drush(i.e#!/usr/bin/env drush) and in this script I am utilizing drush commands. I was hoping there is drush command like Node.js have process.env.VAR_NAME to grab env variables
Comment: Writing Drush commands sound fun. I will look into. The 'getenv' is not working for my zsh setup. I guess i will have to figure that out, so I can use 'getenv'.
Comment: I guess i am not clear about the approach "If you are calling Drush from bash...", is there more info in this like a blog post, etc. Any blog post on handling environments with drush would help.
Comment: You need to be more clear about your question and your environment. If getenv is not working, then it is likely that the environment variable you are trying to check has not been set -- for example, if you set environment variables in the Web Server, then Drush will not see these.  Look for some articles on defining environment variables in zsh, and then set the variables you need in the appropriate configuration file.
Comment: Thanks Greg on feedback for me better presenting question. It helps me get better.
Comment: " Try defining equivalent variables in your .bashrc." was useful

How to Retrieve Env Var in Drush


The results of logistic regression with glmer and glm are quite different

Question: I'm trying to analyze the longitudinal data of clinical trial.
The variables are
event: Dichotomous (1, 0) variable indicating whether event occured.
treat: Dichotomous (1, 0) variable indicating whether patients were assigned to treatment group or control group.
time: The time point indicating when the patients were observed. We observed the patient at 1week, 1month, 3months from baseline.
id: The id of individual patient
For example, the data of patient1 is constructed as follows
id time treat event
patient1 1week 1 0
patient1 1month 1 1
patient1 3months 1 0

I analyze the model with generalized linear-mixed effect model using glmer function. Also, I analyzed it with glm function. Both model use binomial distribution with logit link. To analyzed the difference in change according to time from baseline, the model includes interaction term.
model1<-glmer(event~time+treat+time:treat+(1|id), data, family="binomial",
             control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e5)),nAGQ = 10)

model2<-glm(event~time+treat+time:treat, data, family="binomial")

However, both model outputs very different results. For example, the coefficient of treat*3months in model1 was 1.25, and in the model2, it was 0.81. When exponentiated, the odds ratio became 3.5 and 2.2.
What's even stranger is, when I fitted both model with poisson distribution, the results are identical (0.51).
How this happened? I would really appreciate for all your help.
Comment: While waiting help, I found some hints for the mismatch.

1) First, the output of GLM is 'marginal effect' and GLMM is 'subject-specific effect'. Those effects are different, especially in non-linear outcome
2) The non-collapsibility is also an issue. Following link handles this problem

https://thestatsgeek.com/2017/05/11/odds-ratios-collapsibility-marginal-vs-conditional-gee-vs-glmms/
Comment: I found the answer. It is explained well in following text. https://quantscience.rbind.io/2020/12/28/unit-specific-vs-population-average-models/
Answer: The glmer() model includes a random intercept for id, and the glm() model does not. The random intercept eliminates some variance between subjects to account for the nested nature of your data. If you have repeated measures nested in id, the preferred model is likely glmer().
I don't have an answer for why the Poisson model was the same, but it doesn't seem like Poisson is an appropriate model for your dependent variable. It could be related to this misspecification.


will git record the time when I write the code? or only record the time when I git add

Question: I want to know when I writing the code and will git record the time I write which line of code. Or It just record the time when I git add . and git commit.
Comment: git records the time you `git commit`
Answer: Unless you make a commit for every line of code you write (which would be incredibly pedantic), Git will only record the time in which you've committed the actual code into the repository - that is, only when you've run git commit successfully.
Comment: So git add won't record the time?
Comment: You've only staged it at that point, and it's not part of the formal history of your project yet.  So no, I wouldn't believe that it would.
Comment: @yongho `git add` will update your `.git/index` file; as such you could probably take a look at the modification date of the file. But this will only inform you about the last modification and `git add` isn't the only command which touches `.git/index` so there is no guarantee that this was truly the time `git add` was used.


Incorrect URL paths

Question: I am using Drupal on this website.
On this page you will see that the URL is pointing to a page under another sub page as opposed to the programmes page.
When I changed the URL alias of one of the pages under the incorrect path it did not like it and now redirects to the page called Membership/routes which is part of the incorrect URL
http://www.ciob.org.uk/membership/routes/epa-resources-2012
How can I change this to actualy be this url, which would make far more sense?
http://www.ciob.org.uk/membership/programmes/epa-resources-2012
Answer: I think that by having a page actually aliased with programmes everything that you alias with programmes/something is resolving to plain programmes. That's maybe why the programmes/epa-resources-2012 that you are trying to use "won't stick".
I would suggest that you try moving programmes to -> programmes/index or something like that. That way nothing will be "owning" the programmes path, and you will be able to have programmes/anything... paths.
Comment: I will look again at the alias set up on programs you may be right, If I can change that back to /membership/programmes then I could start adding pages under that url, I will try this and get back
Comment: I am taking this as answer as the url was being specfied ciob.org.uk/programmes and it should have been /membership/programmes. This is what prompted the change.
Answer: There is nothing I can think of that would cause Drupal out of the box to redirect "programmes/something" to "programmes," assuming both are node paths. A bad path should return a 404 error. If "programmes" is the path for a view, it would take "something" as an argument, and finding no results it would use the default value for the argument, but that does not appear to be the case here.
What are your alias and redirection settings? For example, if you have Drupal set to keep and redirect old aliases, you'll have to delete the unwanted bad paths under URL Aliases or correct them under URL Redirects, depending on what you have installed. If you have it set to keep old aliases but do not have Path_Redirect installed, the old alias gets treated as canonical. Any newly created aliases will bring up the correct node, but the location in the browser bar will be the older one.
I would also investigate whether any global redirection is set on /membership*.
Comment: There is no global redirection from membership, I will investigate using your suggestions
Answer: I'm not 100% sure I understand the issue, but if I do: are you using path_redirect? This has an option to automatically create a redirect when a node's URL alias is altered. It can be very useful, but it can trip you up in this situation (and also lead to an over-populated URL-space if your clients like to rename pages a lot:). To find out, you can go to the redirects config screen and search for programme.

Incorrect URL paths


Remove a string from a list of list

Question: I am trying to remove a string from a list of list while keeping the internal list.
Example:
Input
x = [["banana", "dog", "potato"], ["dog", "potato"], ["banana"], ["dog", "potato"]]

I use a function
x.remove_from_internal_lists("banana") # Invented function

Output I would like:
x = [["dog", "potato"], ["dog", "potato"], ["dog", "potato"]]

I know about .remove() and other methods on a single list but I am not sure how to use them to remove a string and keep the inside lists.
Comment: have you tried anything yourself before asking to write code for you?
Comment: loop through and remove the string from sub lists
Comment: remove_from_internal_lists should iterate over each internal list, test to see if the target item is in the target internal list, and remove it if it is - Ha!  @SuperStew beat me to the punch.
Comment: Can your list have repeated values like `['dog', 'dog', 'banana']`?
Comment: Yes, they can have repeated value but there will be not the case because in the original list there are no repeated value in the inner lists
Comment: If the nesting level is likely to vary, you can take a look at my answer.
Answer: You can use a list-comprehension:
lst = [["banana", "dog", "potato"], ["dog", "potato"], ["banana"], ["dog", "potato"]]

lst = [[y for y in x if y != 'banana'] for x in lst if x != ['banana']]
# [['dog', 'potato'], ['dog', 'potato'], ['dog', 'potato']]

Comment: list comprehensions should be short and readable, this is not readable at all
Comment: The OP said he/she wants to keep the original lists I think
Comment: @Steve wouldn't the original list be maintained as `lst` and the altered list as `output`??
Comment: @Steve, both input and output says `x = ..`, so replace original maybe?
Comment: And what if we do not know what the initial item to remove is? What if each list item is different..?
Comment: sorry folks.  forget my comment.  misread question - upvoted ypercy
Comment: @GerhardBarnard, 1. there is no case like you don't know what to remove. 2. Does not matter what the list contains.
Comment: Austin you should refactor the answer to for in line with his question. They have a fair point. And you should know it's bad practice to change the values of a list that you are iterating
Comment: @Swift, disagree on the bad practice. There is no wrong in iterating over list and modifying unless you are removing anything using `pop` or `remove`. Here it's creating a new list from an already existing list by checking conditions.
Comment: Not quite. I know i want to remove the first item only whether banana or avocado.
Comment: You have a fair point there Austin, but I'm not accusing you of bad practice, but rather stating that it is bad practice to *change the values of a list during iteration*. I agree that creating a mew list with the same variable name is essentially the same as doing it with another variable, except that it will reduce the overhead on bigger datasets
Answer: You need to iterate over each list in x, and check to see if the value is in the sublist. If it is, remove it. If not, continue.
def remove_from_internal_lists(l, value):
    for y in l:
        if value in y:
            y.remove(value)
    return [x for x in l if x]  # removes any empty lists

and call it like
>>> new_x = remove_from_internal_lists(x, "banana")
>>> new_x
[['dog', 'potato'], ['dog', 'potato'], ['dog', 'potato']]

Comment: Author doesn't want an empty list, he wants the entire list removed
Comment: @LukeNing yup, updated my function when I saw OP's expected output and forgot to edit the sample
Answer: Other answers have covered how to replicate this behavior, but the way to add functions to a type is to subclass:
class NestedList(list):
    def remove_from_internal_lists(self, word):
        forward_final_index = len(self) - 1
        for reversed_index, sub_list in enumerate(reversed(self)):
            if isinstance(sub_list, list) and word in sub_list:
                if len(sub_list) == 1:
                    # Modifying a list under iteration is normally a Bad Idea(tm):
                    # This is possible because we are iterating in reverse which
                    # guarantees all invalidated indices have already been processed
                    # and allows for multiple copies of [word] in our outer list.
                    # Additionally, we preserve any empty lists already present
                    del self[forward_final_index - reversed_index]
                else:
                    sub_list.remove(word)

Note: That large comment is necessary: you're doing something that is normally a Bad Ideatm and should explain yourself so future maintainers (including yourself) aren't misled.
This allows us to use your "Invented function", and NestedLists will act in every way like lists plus:
>>> lst = [["banana", "dog", "potato"], ["dog", "potato"], ["banana"], ["dog", "potato"]]
>>> nlst = NestedList(lst)
>>> nlst.remove_from_internal_lists("banana")
>>> nlst
[['dog', 'potato'], ['dog', 'potato'], ['dog', 'potato']]

Answer: Here's a solution using recursion that works with any depth of nesting in the lists, and also removes all occurrences of the specified item in case of duplicates. Also works with "hybrid" lists that consist of a mix of inner lists and non-lists:
def remove_from_inner_lists(the_list, the_item):
    for e in reversed(the_list):
        if (type(e)) == list:
            remove_from_inner_lists(e, the_item)
        elif e == the_item:
            the_list.remove(e)

Output:
x = [[["banana", "dog", "potato"], ["dog", "potato"], "banana"], ["banana"], ["dog", "potato"]]

remove_from_inner_lists(x, "banana")

print (x)

[[['dog', 'potato'], ['dog', 'potato']], [], ['dog', 'potato']]

Remove a string from a list of list


Java, proper approach for controlling Linux server from within Java code?

Question: I've been tasked with setting up an automated system that will have to do some things on the Linux server that, from my understanding and research thus far are not able to easily be done from within Java, such as mounting a hard drive on the linux server. I have used some SSH over Java libraries but found them a bit difficult to use reliably. I can run the java app directly on the linux server so I'm wondering if there is a better way to make the needed calls to the server than over SSH. Any advice would be appreciated
Answer: Runtime.getRuntime().exec("some linux command");

Example:
<code>jcomeau@intrepid:/tmp$ cat /tmp/test.java; javac test.java; java test
import java.net.*;
import java.io.*;
public class test {
 public static void main(String args[]) throws Exception {
  String line;
  Process process = Runtime.getRuntime().exec("ls");
  BufferedReader process_out = new BufferedReader(
   new InputStreamReader(process.getInputStream()));
  while ((line = process_out.readLine()) != null)
   System.out.println(line);
  process.waitFor();
 }
}
bin
hash.class
hash.java
hsperfdata_jcomeau
profile
test.class
test.java
tmpe66f4e
tmplvOd2n
tmpn8FI2Q
tmpoYaciK
tmpx27knK
vmlinux
繁體中文.txt
</code>
Comment: The response come in the usual way for Unix programs.  You can read the standard output and standard error from the program, and get the exit code.
Comment: Also, can this give the response back from the server?
Comment: It works for me, however I'm wondering is there a way I can do a command like `"cd /some/directory"` to where it will go into that directory for the next time I run a command. Also, I am wondering if I can do something as `su someuser` then be able to enter the password so I can continue doing inputs as that user, I have tried this but its not working
Comment: I think I found an answer to the above question: http://www.webmasterworld.com/linux/3613813.htm allows me to run a terminal basically from Java, really cool.. thanks for all the help, this will make my life a lot easier :)
Answer: There are plenty of Linux webadmin tools that allow this sort of administration - Google's top hit is Webmin - written in Perl or PHP. Unless you need to integrate with existing a java code on the server I think I'd look at adapting one of these rather than starting from scratch in a language that really isn't well suited to this type of task.
Don't underestimate the potential security risks of this system - another advantage to building on the work of others.
Comment: I just need a way to control it from Java code, if a tool such as Webmin has an API I can access through Java then thats all I would need


Quotient groups and dihedral groups

Question: I came across a question asking for me to find all the possible quotient groups for the dihedral group $D_6$. How must I go about this?
Answer: I assume that your definition of $D_6$ is
$$D_6=\{1,r,r^2,s,sr,sr^2\}$$
where $r^3=s^2=rsrs=1$.
A quotient set $D_6/N$ is a group if and only if $N\lhd D_6$. Hence, we want to find all normal subgroups of $D_6$. We always have the trivial ones
$$D_6/D_6\cong\{1\}$$
and
$$D_6/\{1\}\cong D_6.$$
The subgroup $\langle r\rangle = \langle r^2\rangle= \{1,r,r^2\}$ is of index $2$ and thus normal. So
$$D_6/\langle r\rangle$$
is a quotient group also. If $N\lhd D_6$ is a different normal subgroup, then $|N|=2$, so either $N=\langle s \rangle$, $N=\langle sr\rangle$ or $N=\langle sr^2\rangle$. But none of them are normal. For example $\langle s \rangle$ is not normal since $(sr)s(sr)^{-1}=sr^2\notin\langle s \rangle$. Hence, the only non-trivial quotient group is
$$D_6/\langle r\rangle\cong\mathbb{Z}/2\mathbb{Z}$$
Comment: How can we just assume $D_6$?
Comment: I meant: "I assume that your definition of $D_6$ is the following..." I will clarify.

Quotient groups and dihedral groups


compute maximum f1 score using precision_recall_curve?

Question: For a simple binary classification problem, I would like to find what threshold setting maximizes the f1 score, which is the harmonic mean of precision and recall. Is there any built-in in scikit learn that does this? Right now, I am simply calling
precision, recall, thresholds = precision_recall_curve(y_test, y_test_predicted_probas)

And then, I can compute the f1 score using the information at each index in the triplet of arrays:
curr_f1 = compute_f1(precision[index], recall[index])

Is there a better way of doing this, or is this how the library was intended to be used? Thanks.
Comment: Note I am using an XGBoost classifier with binary logistic output if that changes anything
Answer: After calculating the precision, recall and threshold scores you get NumPy arrays.
Just use the NumPy functions to find the threshold that maximizes the F1-Score:
f1_scores = 2*recall*precision/(recall+precision)
print('Best threshold: ', thresholds[np.argmax(f1_scores)])
print('Best F1-Score: ', np.max(f1_scores))

Comment: what if we care about the "weighted f1 score"? To account for unbalanced classes
Answer: Sometimes precision_recall_curve picks a few thresholds that are too high for the data  so you end up with points where both precision and recall are zero. This can result in nans when computing F1 scores. To ensure correct output, use np.divide to only divide where the denominator is nonzero:
precision, recall, thresholds = precision_recall_curve(y_test, y_test_predicted_probas)
numerator = 2 * recall * precision
denom = recall + precision
f1_scores = np.divide(numerator, denom, out=np.zeros_like(denom), where=(denom!=0))
max_f1 = np.max(f1_scores)
max_f1_thresh = thresholds[np.argmax(f1_scores)]

Comment: That's a nifty usage of the out argument -- for other people who were briefly confused like me, f1_scores will default to zero where denom is not zero.


How to convert pokémon to accent e

Question: I'm receiving string from the back-end which is pokémon but it should be pokémon this is why I'm trying to find a way to convert é in the string to é but couldn't find any solution for that

My meta tag is utf-8
Tried normalizer
Comment: But do you _really_ need to decode it? Showing this text in HTML will display `é`
Comment: I'm using react and I'm receiving string from the back end I need to send it to a deeper child component and display it I can not directly display it in the HTML this is why I'm trying to transform before sending to child component
Answer: You could just use the browsers built in DOM parser.  Basically set the innerHTML of a DOM element, and then read with the innerText.  Your then free to use this string inside your React control.
eg.

const d = document.createElement('div');

d.innerHTML = 'pokémon';

console.log(d.innerText);

To make the above code more re-usable you could do ->

const normalizeText = (() => {
  const d = document.createElement('div');
  return t => {
    d.innerHTML = t;
    return d.innerText;
  }
})();

console.log(normalizeText('pokémon'));
Comment: I'm not sure what I can receive from back end so it's okay to create reusable function thank you
Comment: Yes, that works thank you!!!. Is there any simpler way like using regex
Comment: @BarışBabahan  If you was only checking for é, then you could just do a simple replace with regex, but if there lots of different ones, regex would become much more complicated, you could wrap what I've done into a simple function to make using it much easier.  I'll do another snippet showing this.

How to convert pokémon to accent e


jquery flicker on load in conjunction with fadeTo

Question: I've seen a few posts on this, but none with a solution that works for me - and I've tried a lot. I'm just executing a simple sequence - fade div out, load content, fade dive in, but the content that is loaded appears for a moment in full opacity and then disappears, then executes the fade. I've tried setting the display property of the loaded div to none and then showing it in the fade in function, setting delays, for showing, etc. I've tried fadeTo, fadeOut, etc. Incidentally, hide() works fine, but it's not the effect I want.
Here's my code:
...
<code>$('#bio_container').fadeOut(500,loadContent(ident));
});

function loadContent(ident){
    $('#bio_container').load('/index.php/ajax/bios/' + ident,showContent);
}

function showContent(){
    $('#bio_container').fadeIn(500);
}
</code>
Any ideas would be appreciated.
Answer: Try this.
<code>$('#bio_container').fadeOut(500, function(){
     loadContent(ident)
});
</code>
Edit: If you look at fadeOut's definition it accepts a callback as an argument and invokes that function when the animation has finished. So a callback reference is either an inline function definition like the above one or just a function name without paranthesis. If you give something like this someFunction() it evaluates the function and then takes the return value as an argument. And possibily throws a suppressed exception when the animation is finished and invoking the result.
Comment: @mheavers i edited the answer and added some information from an untrained perspective :)
Answer: It's happend, because javascript is executed in lineal form, and fadeOut(time,fn) execute the fn and THEN execute te fade.
To fix this i use some JQuery plugins, for your case i suggest this simple slideshow, or if you are looking for something more specific see this list.
PS: Sorry for my bad english.


PHP file upload system security implications

Question: i've build a small upload system using PHP, it is working just fine for now however, the problem i have is the way i've got it to work.
I don't have much of a background in security, but is what i'm trying to learn at the moment.
So in order to get the file upload system to work i needed to change the permissions for a folder that i wanted to put the file into.
So i have a windows server, i located the folder > right click > properties > security > edit
Here there is a list of 5 groups

CREATOR
SYSTEM
Administrators
Users
TrustedInstaller

So When i'm uploading a file, it uploads to temps files, then the system moves the file to the right location lets say /vids .
Originally the "Users" group permissions were set to "deny" on the write permission meaning the users group could not write files to this location, this means that when the system tries to move the file it gets a permission error.
So i change the "Users" group write permission to "allow" write and it the file upload and move works just fine. However i am worried that this is bad practice from a security stand point?
From what i would see was that if it has the write permission an attacker could put a script in that location and then execute it, is this correct? If so how do i get around this and make it more secure?
Comment: This question is rather vague, can you ask it more clearly?
Comment: Hey @RobbieMckennie I updated the question and tried to make it a little less vague but i'm struggling a little bit. Is that any better? Thanks.
Answer: An attacker could certainly upload some form of malicious code and run it, but there are a few ways to mitigate this. Do not allow access to the files directly, but only through some kinda of intermediate script. Restrict uploads to only a selected few file types (image types, or only text files, etc). And if i understand your question, permissions are not the thing to worry about.
Comment: Although this is no alternative to getting a professional to pentest your system, i see no gaping security holes.
Comment: Well the benefit of this system in only trusted users will have access to the upload page (Members on a small company). I only allow uploads of MP4 or mp4 files as well. So the fact that i set that permission isn't a security flaw? the upload system itself could be the potential security flaw?
Comment: It's okay, i won't hold you personally responsible if something goes wrong :P Thanks a lot for you help, i really appreciate it.


XSLT 2.0 Replace all occurrences of '&' (if any) from xml with 'and'

Question: I am very new to xslt and need some help with some string manipulation. I am trying to work on a xslt where i want to replace all occurrences of special character '&' with 'and' in xml. One of the few things i have tried
<xsl:template match="Model">
    <Model>
       <xsl:value-of select="replace(//P1/P2/Vehicles/Vehicle/Model, '&','and')"/>
    </Model>
</xsl:template>

it is working fine if there is only one vehicle, however if there are multiple vehicles it is not working.
The xml:
<P1>
  <someNode>
  <P2>
    <Vehicles>
        <Vehicle>
           <Id>1</Id>
           <Make>My car</Make>
           <Model>my model & something</Model>
        </Vehicle>
        <Vehicle>
            <Id>2</Id>
            <Make>My car2</Make>
            <Model>my model2</Model>
        </Vehicle>
    </Vehicles>
  </P2>
 <P1>

Any help is highly appreciated. Thanks!
Answer: The provided XML is not well-formed. I had to fix it.
The XSLT is using Identity Transform pattern.
XML
<P1>
    <someNode/>
    <P2>
        <Vehicles>
            <Vehicle>
                <Id>1</Id>
                <Make>My car</Make>
                <Model>my model & something</Model>
            </Vehicle>
            <Vehicle>
                <Id>2</Id>
                <Make>My car2</Make>
                <Model>dog & pony</Model>
            </Vehicle>
        </Vehicles>
    </P2>
</P1>

XSLT
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" encoding="utf-8" indent="yes" omit-xml-declaration="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Model">
        <xsl:copy>
            <xsl:value-of select="replace(., '&','and')"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Comment: thanks a lot that actually worked. i invested like 3 hours yesterday trying to figure out. really appreciate it.
Answer: If you want to replace all occurrences of &, another option is to use an xsl:character-map...
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes" use-character-maps="cmap"/>
    <xsl:strip-space elements="*"/>

    <xsl:character-map name="cmap">
        <xsl:output-character character="&" string="and"/>
    </xsl:character-map>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Working fiddle: http://xsltfiddle.liberty-development.net/93wniTP


Unable to Reload friend list table from google plus call back function from another view controller

Question: I'm trying to fetch all the people list in google plus and it works but the problem is that it works fine only for a already logged in user, if a user attempts a fresh login the table doesnt get reloaded I need to go back and click on the G+ friends button again to load the data. I've noticed that if the user session status is not authenticated and when he clicks on the G+ friends button he is prompted with login and the call back function (finishedWithAuth) which is in my SignupViewController gets called. So what I did was created an object for my FrienListViewController which displays the friend list and call its viewdidLoad method in the G+ call back function, every function seems to get called and on NSLog I'm also getting the people list and images but the table doesnt get reloaded at all, it doesnt call any tableview methods when the call is made from viewDidLoad, I did some search and tried to implement the NSNotification Center, but the selector method never gets called. May be I'm implementing it in wrong way. Can you check my code and help me with any suitable workaround?
SignupViewController.m
<code>//Google Plus callback method

-(void)finishedWithAuth:(GTMOAuth2Authentication *)auth error:(NSError *)error
{

    AppDelegate * appdelegate =  [UIApplication sharedApplication].delegate;
    [[[GPPSignIn sharedInstance] plusService] executeQuery:[GTLQueryPlus queryForPeopleGetWithUserId:@"me"] completionHandler:^(GTLServiceTicket *ticket, GTLPlusPerson *person, NSError *error)
     {
         [appdelegate hideLoading];
         if(error)
         {
             NSLog(@"Authentication Error: %@", error);
         }
         else
         {

           if([Reusables getDefaultValue:@"fetchGoogleFriends"])
             {
                 FriendListViewController *ob= [[FriendListViewController alloc]init];
                 [ob viewDidLoad];
                 [[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification" object:self];
             }

         }

     }];

}
</code>
FriendListViewController.m
<code>- (void)viewDidLoad
{
    [super viewDidLoad];

    self.friendListSection = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil];

    listType=[Reusables getDefaultValue:@"friendListType"];

    AppDelegate * appdelegate =  [UIApplication sharedApplication].delegate;
    [appdelegate showLoading];

    [self fetchFriendList];
    [self performSelectorInBackground:@selector(fetchPeopleImagesInBackground) withObject:nil];
    //[friendsTable reloadData];
    [NSNotificationCenter defaultCenter];

    NSNotification* notification = [NSNotification notificationWithName:@"MyNotification" object:self];
    [[NSNotificationCenter defaultCenter] postNotification:notification];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (objFirstViewController) name:@"MyNotification" object:self];

//This logs returns <Friendviewcontroller> in beginning but returns null when the view didload is called from the G+ callback function, Any suggestions ?
        NSLog(@"Table Delegate: %@",friendsTable.delegate);

}

//This method doesnt get called
-(void)objFirstViewController:(NSNotification *)notification
{
    [friendsTable reloadData];
}
</code>
These are some other important function for fetching friends, look this if u cant able to figure out error in previous methods
<code>-(void)fetchFriendList
{
     if ([listType isEqualToString:@"GooglePlus"])
    {
        if ([GPPSignIn sharedInstance].authentication)
        {
            NSLog(@"Status is authenticated, fetching friends!!");
        [self fetchGooglePlusFriends:kGTLPlusCollectionVisible];
        }
        else
        {
       [Reusables storeDataToDefaults:@"fetchGoogleFriends" objectToAdd:@"Enabled"];
        [[GPPSignIn sharedInstance]authenticate];

        }

    }

//Google Plus Fetching friends function
- (void)fetchGooglePlusFriends:(NSString *)collection {

    AppDelegate * appdelegate =  [UIApplication sharedApplication].delegate;

    // 1. Create a |GTLQuery| object to list people that are visible to this
    // sample app.
    GTLQueryPlus *query =
    [GTLQueryPlus queryForPeopleListWithUserId:@"me"
                                    collection:collection];

    // 2. Execute the query.
    [[[GPPSignIn sharedInstance] plusService] executeQuery:query
                                         completionHandler:^(GTLServiceTicket *ticket,
                                                             GTLPlusPeopleFeed *peopleFeed,
                                                             NSError *error) {
                                             if (error) {
                                                 if ([listType isEqualToString:@"GooglePlus"])
                                                 {
                                                     NSLog(@"Error: %@", error);

                                                     [appdelegate hideLoading];
                                                 }

                                             } else {
                                                 // Get an array of people from |GTLPlusPeopleFeed| and reload
                                                 // the table view.
                                                 _peopleList = peopleFeed.items;

                                                 // Render the status of the Google+ request.
                                                 NSNumber *count = peopleFeed.totalItems;
                                                 if (count.intValue == 1) {

                                                 } else {
                                                                                NSLog(@"Status: Listed %@ people, listtype:%@, gplusshow:%@", count,listType,[Reusables getDefaultValue:@"fetchGoogleFriends"]);
                                                 }
                                                 if ([listType isEqualToString:@"GooglePlus"]||[Reusables getDefaultValue:@"fetchGoogleFriends"])
                                                 {

                                                     [self performSelectorInBackground:@selector(fetchPeopleImagesInBackground) withObject:nil];
                                                     [friendsTable reloadData];
                                                     [appdelegate hideLoading];
                                                 }

                                             }
                                         }];
}
</code>
NSLog(@"Table Delegate: %@",friendsTable.delegate); returns Friendviewcontroller in beginning but returns null when the view didload is called from the G+ callback function, this is the main problem. Any suggestions ?
Answer: Try  this........
<code> if([Reusables getDefaultValue:@"fetchGoogleFriends"])
    {

    FriendListViewController *ob= (FriendListViewController*)[self.navigationController topViewController];
    [ob viewDidLoad];
    [ob.friendsTable reloadData];

    }
</code>


Node.js: How does process.env differ from global?

Question: How is setting an environment variable like process.env.thing = 42 different from creating a global variable like global.thing = 42?
When would prefer process.env.thing over global? What are the pros/cons of both objects?
Comment: Both `process` and `globals` are globally accessible variables in node.  Attaching `thing` to either just means that `thing` is attached to different objects.  Can you clarify your question a little?  What exactly are you asking?
Comment: As you say one is an environment variable and the other is set by your program. With process.env you can read the variables set in the system's environmnet. For example... THING=42 node server.js
Answer: global is the global object. process is available globally, because it is a property of global. In fact:
global.process === process //-> true

process.env has properties set to the environment variables of the system.  These can be set a variety of ways outside of node itself, and read in by accessing properties of process.env.
At the command line try:
FOO=bar node -e "process.env.FOO"

The process module is just a globally available thing.
Answer: The choice in my opinion must be something like this.
1)If the variable depends on the environment it must be set in process.env
2)If the variable is just a constant that is accessible from the entire application it must be set to global.
I think if you don't face these 2 points you don't have a need to store some value in both
Answer: If you start your node.js application you may want to use some different "environments", like API-URLs and stuff like this, because in a production / live environment those URLs are usually different in comparision to your local development environment.
This means that you can inject those paths using a .env file for example BEFORE starting your application.
This is an example:
NODE_API_URL=https://myApi.com/myEndpoints myApp.js

The global.thing = bla line will be read after the environment variables were set.
Once the application is running the environment variables and the other global definitions can be accessed by the app.
Answer: from the docs NodeAPI

The process object is a global that provides information about, and
  control over, the current Node.js process. As a global, it is always
  available to Node.js applications without using require().

You want to attach your environment variables to this object to make sure that there is no other pollution of globals.


Variable count of 'for' cycles - Objective-C

Question: I want to put N for cycles in context:
for (NSInteger i=0; i<someCount; i++) {
    for(NSInteger j=i+1; j<someCount; j++){
       for(NSInteger z=j+1; z<someCount; z++){

       // my code here

       }
    }
}

I found the solution like here, but don't understand how to transform it into Objective-C
Comment: Your question makes no sense. The posted code is Objective-C. What issue do you have with the posted code?
Comment: Do you mean you want to convert this code to use recursion? That is the technique used in the answer you linked. If so, what have you tried already?
Comment: I wrote something wrong may be, but it's not a solution yet. Yes, i need recursion, but how to rewrite it with Objective?
Answer: Guess - but maybe it will help.
In the title you write:

Variable count

then in the question:

I want to put N for cycles in context

and finally write the code:

for (NSInteger i=0; i<someCount; i++)

Are you maybe asking about the use of literal values vs. variables in for loop conditions?
The code fragment:
i < someCount

is an expression which is evaluated before every iteration to the loop to determine whether the iteration should take place. It is not "pre-evaluated" in any way before the loop as a whole is executed.
If you write:
i < 42

then the condition will always test for the current value of i being less than 42 and execute an iteration if so. So the limit is a constant. You can also write something like:
i < j

then the limit is a variable - one possible interpretation of your question. The condition will evaluate whether the current value of i is less than the current value of j.
However ff the value of j changes during an iteration then the value that is used in the condition also changes - you have a "variable" limit - a different possible interpretation of your question, in this case rather than the limit being obtained from a variable - as in the programming language construct - the limit itself is variable - as in it changes. This is valid as well, though you have to be careful that the loop terminates, e.g.:
NSInteger j = 1;
for( NSInteger i = 0; i < j, i++)
{
   j++;
}

will keep going (until overflow and wrap around occurs anyway!).
HTH
Answer: Here Is a substitute for recursion, hope it Helps:
First you need to make three new properties in your @interface
@property int a; //a variable for your loops do not edit its value other than what I say
@property int numberOfLoops;//the number of loops to nest inside each other
@property int someCount;//how many times each loop should repeat

Now in your @implementation:
-(void)repeatloops
{
for (int i = 0; i < self.someCount; i++){
if (self.a < self.numberOfLoops){
    self.a += 1;
    [self repeatloops];
}else{
    //do something for this loop, i'm gonna call this "sector a"
    //this would be the code you want to put inside each 'for' statement
}
}
self.a -= 1;
}

Now to call the loops:
self.a = 0; //don't forget this
self.numberOfLoops = N; //N was your example variable, don't forget to change this
self.someCount = X;//X is also an example variable, you can change it to a constant etc.
[self repeatloops];//call the method

This makes something loop exponentially. eg:self.numberOfLoops = 5, self.someCount = 1,NSLog("a"); in "sector a"   -> The result is (self.numberOfLoops^self.someCount)-- That many "a"s in your log window, don't make self.someCount to big!!
Comment: "Note: in my code _ represents self. no need to replace though, it works anyway" - the two are not the same thing at all. The use of `_property` rather than `self.property` bypasses the settler/getter and breaks KVO. If something is not a property but just a variable you'd be better of using an instance variable... but then you are passing arguments (`N`, `X`) to `repeatLoops` via instance variables... But you did figure out what the question was, which I did not, well done!
Comment: @АндрейБронников -No Problem!