text:
Q: Payment Methods In iPhone App? I have an iPhone app where I have a list of items to be sold. For the payment of these items, I have a web service on my sponsor's server that needs to be utilized by sending certain parameters such as amount, userid, discount coupons etc. So should I invoke this in a web view inside the application or should it be invoked in the web-browser? The sponsorer wants to show a message as payment successful or not in the application after everything is done. this information comes from the server itself. But if I invoke the browser i will not be able to track this information about payment successful or not? What should I do? Please help me with this

A: This is particularly interesting with regards to iOS as it gives app developers a fairly easy way to implement an alternative payment solution to the App Store, something that doesn't infringe on Apple's in-app purchasing policy if the goods being sold are physical not digital. It's this scenario that Adyen is targeting.
As for the payment method itself, it accepts credit cards, PayPal and a range of other payments within mobile applications (native apps) and mobile websites. Of course, offering a HTML (browser-based) version of an app or service rather than a dedicated iOS app is another way of bypassing Apple's cut.
Other benefits of Adyen's payment platform is that merchants and developers can take advantage of a "fully integrated service that removes the burden of security and PCI compliance", says the company. In addition, app developers can "skin" the mobile payment and checkout process, gaining control of the look and feel, which is said to be an important driver for increased conversion rates.
Merchants already using the new mobile payment platform include Pathe, the largest chain of cinemas in the Europe, via its iPhone app, and Greetz, the online greetings card retailer.


text:
Q: Why is my list->next pointer affected by free()? I'm trying to implement a linked list and adding nodes to it. I encountered the following problem, when I try to free the pointer n after setting list->next to point to the same address of n, the int value inside the second node also changes to garbage value when I print it again. I want to know if inside the memory, n and list->next is stored as two separate pointers that hold the same value or it is stored as a single pointer? And if they were distinct, then why freeing n also affect list->next? Furthermore if freeing n make the second node became lost, then why I can still use the list->next->next pointer to add a third node, was list->next->next pointer also some random value that points to a random usable location ? Here is my code, sorry if my question is too vague, I'm trying my best to understand all this pointers.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <stdlib.h>

typedef struct node {
    int number;
    struct node *next;
} node;

int main(void) {
    node a;
    a.number = 1;
    a.next = NULL;
    node *list = NULL;
    list = &a;           // the first node
    printf("%i \n", a.number);

    node *n = malloc(sizeof(node)); // creating pointer to the second node
    if (n != NULL) {
        n->number = 2;
        n->next = NULL;
    }

    list->next = n; // add the node to the list

    printf("%p \n%p \n", n, list->next);   // print out the address and value
    printf("%i \n", list->next->number);

    free(n);

    printf("%p \n%p \n", n, list->next);   // print out the address and value
    printf("%i \n", list->next->number);

    n = malloc(sizeof(node));

    printf("%p \n%p \n", n, list->next);
    if (n != NULL) {
        n->number = 3;
        n->next = NULL;
    }
    list->next->next = n;
    printf("%i\n", (*(*(*list).next).next).number);
    return 0;
}

Here is the output
1
0x5562319d62a0
0x5562319d62a0
2
0x5562319d62a0
0x5562319d62a0
1445140950
0x5562319d62a0
0x5562319d62a0
3

A: The assignment
list->next = n

doesn't copy the allocated memory. It just add another pointer pointing to the same memory.
If we "draw" it, before the assignment it looks something like this:

+---+      +-----------------+
| n | ---> | memory for node |
+---+      +-----------------+

Then after the assignment you have:

+---+
| n | -----------\
+---+            |     +-----------------+
                  >--> | memory for node |
+------------+   |     +-----------------+
| list->next | --/
+------------+

Then you pass n to free leading to this situation:

+---+
| n | -----------\
+---+            |
                  >--> ???
+------------+   |
| list->next | --/
+------------+

After the call to free, the pointer list->next is invalid. Any attempt to dereference it will lead to undefined behavior.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exposing spring boot random server port using docker We plan to deploy multiple docker images on same VM running same app. In my knowledge, we need to expose webapp port in docker container. But if we plan to use "random" server port in spring boot (using server.port=0), how we expose that random port at run time?
-=-=
Second question is, does spring boot app picks random port which is available in host VM or just docker container space?

A: Spring-boot allocate the port at the run time, not at the build time. That means, the port selected by spring boot will not be available until you start the application natively or in the docker container.
Answer to your second question is that Docker pick the port inside the Docker Container. So, practically all the ports will be available other than the ones used by OS.
When combining these two statements, unless you have any specific restrictions, you should specify the port manually to spring-boot application and expose it at docker run execution?


text:
Q: Como fazer um programa ser executado dentro de uma janela em pygame? Eu fiz uma janela usando pygame, e tenho um código que queria que fosse executado dentro dela, mas não sei como fazer isso, se alguém puder ajudar eu fico muito grato.
Aqui o código da janela:
pygame.init()
tela = pygame.display.set_mode([500, 400])
pygame.display.set_caption('Redenção')
relogio = pygame.time.Clock()
cor_branca = (255,255,255)
cor_azul = (108, 194, 236)

sair = False

while sair != True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sair = True
    relogio.tick(27)
    tela.fill(cor_azul)
    pygame.display.update()

pygame.quit()

e aqui tem o código que quero que seja executado dentro da janela:
def intro():

    print("▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄\n")
    print("Durante a 3ª guerra mundial, que explodiu no dia 12 de março do ano 2065 entre as nações mundiais...\n")
    time.sleep(5)
    print("A OTAN das quais fazem parte EUA, Europa ocidental e mais alguns países da parte oriental, como Austrália,\n"
          "Japão e Coreia do Sul, entrou em conflito com o B.R.C.I.S a aliança entre Brasil, Rússia, China,\n"
          "Índia e Africa do Sul.\n")
    time.sleep(5)
    print("Como consequência, a fome se espalhou pelo mundo, as intrigas entre as nações aumentaram,\n"
          "surgiram agitações nas grandes cidades e o que todos temiam, a caixa de Pandora foi aberta, as terrivéis\n"
          "bombas atômicas começaram espalhar seu terror pelo mundo...\n")
    time.sleep(5)
    print(
        "O Brasil, por possuir um vasto território e abundantes recursos naturais, se tornou um alvo fácil para as\n"
        "maiores potências mundiais, os países da OTAN temendo uma escassez completa, iniciaram um invasão pelo\n"
        "norte do país, com a intenção de dominar toda a nação e explorar sua grande extensão cultivável...\n")
    time.sleep(6)
    print("O B.R.C.I.S começou um contra-ataque ao saber que o Brasil estava sendo atacado, adentraram o Brasil,\n"
          "inciando pelos estados do nordeste e começam um bombardeio contra a OTAN....\n")
    time.sleep(5)
    print("No dia 25 de novembro de 1965, as nações já se encontravam exaustas em consequência da guerra, veem como\n"
          "última solução, usar as mortais G-BOMBS e o Brasil se torna um cenário de devastação, com milhares de\n"
          "mortos e cidades destruídas.\n")
    time.sleep(5)
    print("Nesse inferno na terra, você é um dos poucos sobreviventes em meio ao caos e irá com o restante das suas\n")

A: O Pygame te dá uma janela para desenhar, e algumas primitivas de desenho.
Não tem uma forma fácil de colocar texto dentro de uma janela de pygame - e  as técnicas de saída de terminal, em que o texto rola pra cima automaticamente não se misturam nem um pouco com a API que o pygame disponibiliza.
A forma de colocar texto numa janela do pygame tem 3 passos:

*

*cria um objeto Fonte, onde você escolhe a fonte em si (typeface e o tamanho)

*cria uma Surface com o texto escrito. Nesse passo você fornece os caractéres que quer escrever na tela e a cor desejada - ele te devolve um retângulo com o texto desenhado e fundo transparente.

*Você "carimba" (método .blit) esse texto desenhado numa posição da tela.

Se o texto for mudar de posição (por que apareceu mais texto embaixo e o texto existente precisa ser empurrado pra cima), você tem que apagar a tela, e repetir os passos 2-3 para o texto que já estava lá.
Tem um problema extra que não aparece aí: o pgame não faz quebra de linha
automática para texto - ele renderiza uma linha. Se a largura máxima do texto na sua janela de jogo for 40 ou 80 caractéres, você que tem que quebrar o texto em pedaços do tamanho apropriado e gerar retângulos com
cada linha, e colar no lugar certo.
Aqui vai o exemplo em código para colocar um "Alô mundo" na tela com pygame:
import pygame
screen = pygame.display.set_mode((800, 600))
pygame.font.init()
font1 = pygame.font.Font(None, 150)
text = font1.render("Alô Mundo", True, (255, 255, 255))
screen.blit(text, (0, 200))
pygame.display.flip()

def principal():
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
               return
        pygame.time.delay(30)

principal()

(O None na chamada a pygame.font.Font faz o pygame usar uma fonte padrão, sem serifa - pode ser um caminho para qualquer arquivo de fotnes do tipo "ttf" (e talvez outros))
Tudo isso é factível com programação, claro - mas é bastante coisa pra fazer, e está entre você e o seu conceito de jogo.
O melhor é usar uma camada intermediária que permita texto no pygame - tem o PGU (Phil's Pygame Utilities)  - ele não tem pacotes - mas é fácil instalar baixando direto do github -
https://github.com/parogers/pgu
Ele permtie a criação de interfaces parecidas com as dos programas de janela dentro da janela do Pygame -  o conceito ainda é diferente do terminal,e não vai funcionar só com "print" e "sleep" - mas  pelo menos ele pode gerenciar a apresentação do texto pra você.
https://github.com/parogers/pgu
Tem um projeto meu também que é o "mapengine"  - ele está bem pouco documentado, mas tem suporte ao que chamo de "cut scenes" - justamente cenas em que dá pra escrever algum texto, e esperar uma ação do usuário, e mudar pra próxima tela - daria pra adaptar fácil esse "contar de história" aí: https://github.com/jsbueno/mapengine/tree/master/mapengine
O mapengine tem suporte para um mapa maior que a tela, e items de "bloco"  como jogos de plataforma  - pode servir bem para desenvolver algum jogo que você tenha em mente sem precisar fazer tudo do zero em cima do pygame. (e se for usar, pode ir me escrevendo pra eu arrumar eventuais problemas/adicionar funcionalidades).  Tem uma pasta de "exemplos" lá.


text:
Q: Solution for $4^{2x+1}-3^{3x+1}=4^{2x+3}-3^{3x+2}$ I'm trying to get a solution for:
$4^{2x+1}-3^{3x+1}=4^{2x+3}-3^{3x+2}$
My main problem is that I don't know how to combine this potencys!
Ive also thought about another function that would bring me same difficulties:
$6^x=36*9.75^{x-2}$
What am I supposed to do?

A: $$4^{2x+1}-3^{3x+1}=4^{2x+3}-3^{3x+2}$$
$$4^{2x+1}-4^{2x+3}=3^{3x+1}-3^{3x+2}$$
$$4\cdot4^{2x}-4^34^{2x}=3\cdot3^{3x}-3^23^{3x}$$
$$60\cdot4^{2x}=6\cdot3^{3x}$$
$$10\cdot4^{2x}=3^{3x}$$
$$10\cdot16^{x}=27^{x}$$
$$10=(27/16)^{x}$$
$$\log_{10} 10=\log_{10} (27/16)^{x}$$
$$1=x\log_{10}(27/16)$$
$$x=\frac{1}{\log_{10}27-\log_{10}16}$$

A: For the first one, we have
$$
4^{2x+1}-3^{3x+1}=4^{2x+3}-3^{3x+2} \implies\\
3^{3x+2}-3^{3x+1} = 4^{2x+3}-4^{2x+1} \implies\\
(3-1)3^{3x+1} = (4^2 - 1)4^{2x+1} \implies\\
2\cdot 3^{3x+1} =  5\cdot 3\cdot4^{2x+1} \implies\\
3^{3x} = 5 \cdot 2^{4x+1}
$$
I think that's the simplest we can get it.  From there, I suppose we'd have to solve using logs.
That is, let $\log(x)$ be the logarithm of your choosing.  We have
$$
\log(3^{3x}) = \log(5 \cdot 2^{4x+1}) \implies\\
3x \log(3) = \log(5) + (4x+1)\log(2) \implies\\
(3 \log 3 - 4 \log 2)x = \log 5 + \log 2 \implies\\
x = \frac{\log 5 + \log 2}{3 \log 3 - 4 \log 2} = \frac{\log(10)}{\log(3^3/2^4)} = \frac{1}{\log_{10}27 - \log_{10}16}
$$


text:
Q: How to build CMakeLists the right way? I have the following issue: I have two different sets of files (main and an additional one), that I would like to keep separate. So, I have one set of files (main), that I configure this way:
set(libplayersource
        ....
        )

add_library( # Sets the name of the library.
        libplayer

        # Sets the library as a shared library.
        SHARED

        # Provides a relative path to your source file(s).
        ${libplayersource})

Then I have second set of files (additional), that I configure this way:
set(codec_source
        ...)

add_library(libcodec SHARED ${codec_source})

Eventually, I need to link these two sets of files:
target_link_libraries( # Specifies the target library.
        libplayer
        libcodec)

And after this configuration, I also need to include log lib in order to make it work. Firstly, I need to find this log lib, and then include it in my native lib.
find_library( # Sets the name of the path variable.
        log-lib

        # Specifies the name of the NDK library that
        # you want CMake to locate.
        log)

Also, I should to edit target_link_libraries to include log lib:
target_link_libraries( # Specifies the target library.
        libplayer
        libcodec
        ${log-lib})

All is fine if you are going to use this log lib in libplayer, but if you are going to use it in libcodec set, you'll get this error:

undefined reference to `__android_log_print'
clang++.exe: error: linker command failed with exit code 1 (use -v to see invocation)

It is means that the linker doesn't see the implementation of this method.
I found this answer on SO:
https://stackoverflow.com/a/47803975/5709159
and in order to solve the issue, I have added to my CMakeLists file this line:
target_link_libraries( # Specifies the target library.
        libcodec
        android
        ${log-lib}
        )

Main CMake file implementation:
...
#Main module
set(libplayersource
        ....
        )

add_library( # Sets the name of the library.
        libplayer

        # Sets the library as a shared library.
        SHARED

        # Provides a relative path to your source file(s).
        ${libplayersource})

#Additional module
set(codec_source
        ...)

add_library(libcodec SHARED ${codec_source})

#Log lib
find_library( # Sets the name of the path variable.
        log-lib

        # Specifies the name of the NDK library that
        # you want CMake to locate.
        log)

#Linking

target_link_libraries( # Specifies the target library.
        libcodec
        ${log-lib}
        )

target_link_libraries( # Specifies the target library.
        libplayer
        libcodec
        ${log-lib})
...

So, I need to mention log lib in both of libraries.
Question is - Why doesn't the linker see log lib in libcodec? Why do I have to add the additional block?
target_link_libraries( # Specifies the target library.
        libcodec
        ${log-lib}
        )

to make log lib visible for linker in libcodec?
P.S In Visual Studio, if you have main project A and two libs B and C,  you include these B and C libs in A, and that is it; everyone knows about everyone. I can call methods in B from C and so on. In order to call a B method from C, I don't need to include C in B. It is enough that both of these libs are included in A as a main project...
If I missed something in the question, feel free to ask.

A: If your libcodec uses the implementations defined in log-lib, you must link log-lib to libcodec explicitly. This call:
target_link_libraries( # Specifies the target library.
        libplayer
        libcodec
        ${log-lib})

links libcodec and log-lib to libplayer, it does not link log-lib to libcodec. It implies this dependency graph:
        libplayer
        /       \
  libcodec     log-lib

The first argument to the target_link_libraries() call is the "linked-to" library, and all the following targets are linked to the first. Thus, you need to link log-lib to libcodec, like this:
target_link_libraries( # Specifies the target library.
        libcodec
        ${log-lib}
        )

Now, libcodec will know about the implementation defined in log-lib, implying the dependency graph here:
        libplayer
        /       \
  libcodec     log-lib
     /
log-lib

You can make this cleaner though. We can remove the direct link between libplayer and log-lib, and allow the log-lib implementation propagate through libcodec to libplayer.
target_link_libraries(libcodec PUBLIC
        ${log-lib}
        )

target_link_libraries(libplayer PRIVATE
        libcodec
        )

This will simplify the dependency graph to the following:
        libplayer
        /
  libcodec
     /
log-lib

See this section in the CMake documentation for how and when to use the PUBLIC and PRIVATE keywords when linking.


text:
Q: vb.net disable runtime created buttons Hey all i have created dynamic buttons at runtime and i would like to disable them when a user clicks on a form button.
This is the code i have for that button:
Dim intXX As Integer = 0

Do Until intXX = intX
    userAvatar(intXX).Enabled = False
    intXX = intXX + 1
Loop

The buttonNames is an array of all populated button names created at runtime. However, trying the .enabled = false at the end of that does not work. What other ways are there to do that with buttons created at runtime?
How i create the buttons are like this:
private sub createButton()
Dim personAvatar As New PictureBox

With personAvatar
        .AutoSize = False                        '>                        ^

        If intX = 7 Then
            thePrviousAvatarImg = 0
        End If

        If intX <= 6 Then
            .Location = New System.Drawing.Point(10 + thePrviousAvatarImg, 10)
        ElseIf intX >= 7 And intX <= 14 Then
            .Location = New System.Drawing.Point(10 + thePrviousAvatarImg, 150)
        Else
            Exit Sub
        End If

        .Name = "cmd" & nameOfPerson
        .Size = New System.Drawing.Size(100, 100)
        .TabStop = False
        .Text = ""
        .BorderStyle = BorderStyle.FixedSingle
        .BackgroundImageLayout = ImageLayout.Center
        .BackColor = Color.LightGray
        .BackgroundImage = Image.FromFile(theAvatarDir)
        .Tag = nameOfPerson
        .BringToFront()
    End With

    AddHandler personAvatar.Click, AddressOf personAvatar_Click
    Me.Controls.Add(personAvatar)
    userAvatar(intX) = personAvatar
    intX = intX + 1
End With
End Sub

Thanks for your time and help!
David

A: You can't refer to button objects using a string representation of their names. Instead of using buttonNames (which I assume is an array of strings), use an array of buttons and add each button to that. Then loop through that array (as you've done here) setting enabled = false on each one.
So before you create each picture box, declare an array to store them:
Dim MyPictureBoxes() as PictureBox

Then as you create each one, add them to the array. When you're done creating them, you can disable them like this:
For Each MyPictureBox In MyPictureBoxes
    Debug.Print(MyPictureBox.Name)
    MyPictureBox.enabled = False
Next

I've created a form with two buttons, cmdGo and cmdDisable, to demonstrate this more completely:
Public Class Form1
    Dim MyPictureBoxes(4) As PictureBox

    Private Sub cmdGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGo.Click
        Dim personAvatar As New PictureBox
        Dim intX As Integer = 0

        While intX < 5
            personAvatar = New PictureBox
            With personAvatar
                .AutoSize = False
                .Left = intX * 100
                .Top = 100
                .Name = "cmd" & intX
                .Size = New System.Drawing.Size(100, 100)
                .TabStop = False
                .Text = ""
                .BorderStyle = BorderStyle.FixedSingle
                .BackgroundImageLayout = ImageLayout.Center
                .BackColor = Color.LightGray
                .BringToFront()
            End With

            Me.Controls.Add(personAvatar)
            MyPictureBoxes(intX) = personAvatar
            intX = intX + 1
        End While
    End Sub

    Private Sub cmdDisable_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDisable.Click
        For Each MyPictureBox In MyPictureBoxes
            Debug.Print(MyPictureBox.Name)
            MyPictureBox.Enabled = False
        Next
    End Sub
End Class

Notice how MyPictureBoxes is scoped for the whole form so it's accessible to both subs.


text:
Q: How to update parent `scrollWidth` and `scrollHeight` after child node become smaller? I have a parent div with height: 120px; width: 120px and a red child div with height: 200px; width: 200px. Now because child node is bigger so it stretch up the scrollWidth and scrollHeight of the parent node, and thus the scrollbar shows.

Then I add transform: scale(0.5) to the red child div to make it smaller, the vertical scrollbar still shows and scrollHeight stays unchanged, while horizontal scrollbar disappears and scrollWidth changes.

My question is: is there a way to automatically hide/show all scrollbars after shrinking/expanding the child node?
In other words, is there a way to update both scrollWidth and scrollHeight according to child node size?
codesandbox demo: https://codesandbox.io/s/scrollwidth-test-bk04o
Thank you in advance.

A: I don't get your goal but I think you can calculate your inner div height and width with your scale
   **Line 17**

   <div
      style={{
        width: 200 * scale,
        height: 200 * scale,
        background: "red",
        transform: `scale(${scale})`,
        transformOrigin: "0 0"
      }}
    />


text:
Q: TypeError: Cannot read property 'length' of undefined angular js client I have a  Web Api  it returns a following json .
[
  {
    "id": 2,
    "body": "This is my first Tweet",
    "author": "Kumar",
    "date": "2017-07-11T00:00:00+05:30",
    "retweets": [
      "Mahela",
      "Sanath"
    ],
    "favorites": [
      "Sanath"
    ]
  },
  {
    "id": 3,
    "body": "This is my first Tweet",
    "author": "Virat",
    "date": "2017-07-11T00:00:00+05:30",
    "retweets": [
      "Mahela",
      "Sanath"
    ],
    "favorites": [
      "Sanath"
    ]
  }
]

I have  a Angular.js  client , after receiving the request i m getting 'Cannot read property 'length' of undefined 'error from   for(let tweet of resp.json().data) belongs to following method .
getCurrentFeed() :Observable<Tweet[]>{

  return this.http.get('/GetTweets').map((resp :Response)=>{

    console.log(resp.json());

    var fetchedTweets=[];

    for(let tweet of resp.json().data)
    {
     fetchedTweets.push(this.getTweetFromJson(tweet));

    }
    return fetchedTweets as Array<Tweet>;
});

}

tweet.ts  is below
export class Tweet {

public avatar;

constructor( public id :number ,public body :string ,public author :string,public date:Date,public retweets:Array<string>,public favorites:Array<string>)
{
 this.avatar=`${author}.jpg`;

}
 }

A: Removing the data   from
for(let tweet of resp.json().data)
{
 fetchedTweets.push(this.getTweetFromJson(tweet));

}

fixed my issue


text:
Q: Difference size vs track_total_hits in Elasticsearch query size in elasticsearch query means no. of documents we want to fetch.
track_total_hits is what ? Both are doing same task if we set track_total_hits 10 and size is 10 then i am getting 10 result.

A: With size: 10 you're asking how many hits you want in the results.
With track_total_hits:...

*

*true you're telling ES that you're interested to know how many total hits your query could return

*false you're telling ES that you're not interested to know how many total hits your query could return

Settings track_total_hits: false is an optimization to prevent ES from having to count all hits if you're only interested in the first N results and are not interested in the total hit count.


text:
Q: NSInteger vs int vs object I'm quite new to objective-C, and as I've been learning I've been trying to make my own program.
The idea is there is a variable (or object?) named totalSave, a method addToTotalSaved with a parameter saveAmount, and multiple objects (each object would give the parameter saveAmount a different value) that when acted on will cause addToTotalSaved to be 'sent', or whatever the terminology is, to totalSave so that totalSave increases by the correct amount.
First of all, if my idea of how the code works is completely wrong could you offer a better way? ...I feel like this shouldn't be complex - but otherwise my question is what should totalSave be? An int? A NSInteger? An object?

A: It does sound like you've made it overly complex. Obviously, the idea is not really "there is a variable named totalSave" since the user could care less about where you store it, and from the rest of your post, you actually don't care about how you store it.
That said, in order to make this a bit more concrete, let's think about a "total score" state that numerous parts of the program might add to. There are a couple of approaches you might take. In any case, you likely have some object somewhere that is keeping track of the score. We'll call it the Game object, but it could be a Level or whatever.
So there are three big schools of thought: you can pass this Game object around to everyone, you can have a Game singleton, or you can use notifications. Each of these approaches has advantages, and any one you pick is probably fine for a simple program (personally, for a very simple program, I'd use a singleton).
In the first scheme, at some point in the program you create a Game object that has some addToScore: method. You assign this object as a property on every other object that needs to update the score. Each of those calls [self.game addToScore:value]. This approach makes unit testing a bit simpler, but can be a bit tedious to implement.
In the second scheme, you have some shared singleton +[Game sharedGame]. When you want to update the score, call [[Game sharedGame] addToScore:value]. This is generally the easiet to implement.
In the third scheme, you have some object (Game) that uses NSNotificationCenter to observe some notification. When you want to update the score, you just post a notification that includes the amount to add in its user dictionary. This is great for keeping things extremely decoupled, but again can be a little tedious in the more usual case.
But as @Chuck notes, you're probably over-thinking this, and you may want to go back and work through some of the tutorials to get a better sense of how these things usually work. The kind of situation you're describing is not very complicated.

A: It sounds like you want a class, containing an integer value with the total.  Then you want to give that class a function addToTotal(somenum).
Conceivably you could do this all procedurally, but if you want to re-use this Total, I'd recommend stuffing it in a class.


text:
Q: HDFS "files" that are directories Background--we are trying to read different file types (csv or parquet) into pyspark, and I have the task of writing a program that will determine file type.
It appears that parquet files are always directories, parquet file appears in HDFS as a directory.
We have some csv files that are also directories, where the file name is the directory name and the directory contains several part files.  What processes do this?
Why are some files --'files' and some files 'directories'?

A: It will depend on what process produced those files. For example, when MapReduce produces output, it always produces a directory and then creates one output file per reducer within that directory. This is done so that each reducer can create its output independently.
Judging from Spark's CSV package, it expects to output to a single file. So perhaps the single-file CSVs are being generated by Spark and the directories by MapReduce.
To be as generic as possible, it may be a good idea to do the following: check if the file in question is a directory. If not, check the extension. If yes, look at the extension of the files inside of the directory. This should work for each of your situations.
Note that some input formats (e.g. MapReduce input formats) will only accept directories as inputs, and some (e.g. Spark's textFile) will only accept files/globs of files. You need to be aware of what is expected from the libraries you are interacting with.

A:
All the data on your hard drive consists of files and folders. The
  basic difference between the two is that files store data, while
  folders store files and other folders.

Hadoop execution engines generally creates a directory and write multiple part files as output based on the number of reducers or executors used.
When you many an output file abc.csv it doesn't mean that its a single file with the data. Its just the output location which MapReduce (generally) interprets as the new directory to be created within which it creates the output files(part files).
In case of Spark when you are writing a file(maybe using .saveAsTextFile) it may creates only a single file.


text:
Q: error in adding row names with duplicates I've read  a big .csv file into R with read.csv() function . my data looks like this
> data[1:6,1:4]
        X       AD AD.1 AD.2
1 A   1    0    0
2 B   1    0    1
3 C   0    0    0
4 D   0    0    0
5 D 115  156  193
6 A   0    0    0

I want to assign column X as row name.
I did following things and I've got error.
name<-data[,1]
data1<-data[,-1]
row.names(data1)<-name

The error I've got is :

Error in `row.names<-.data.fram duplicate 'row.names' are not allowed
  In addition: Warning message: non-unique values when setting
  'row.names'

I know that I might have some rows with the same names, but I have to keep them.
would somebody help me how to solve this problem?


text:
Q: SUMIFs between workbooks I'm looking to conduct a SUMIF between excel workbooks. Ideally, my procedure will count the sum of column J when column H = "Emma" (in the Dataset workbook) and return the value in cell B3 of the Summary sheet in the Monthly Report workbook. Here's what I have so far:
 Sub CalculateEmma()

'range for calc
Dim EmmaBalance As Long

EmmaBalance = Workbooks("Dataset.xlsx").Worksheets("Summary").SumIf(Range("H:H"), "Emma", Range("J:J"))

Workbooks("Monthly Report.xlsm").Worksheets("Summary").Range("B3") = EmmaBalance

End Sub

A: Your second line is wrong. It should be:
EmmaBalance = Application.Worksheetfunction.SumIf(Workbooks("Dataset.xlsx").Worksheets("Summary").Range("H:H"), "Emma", Workbooks("Dataset.xlsx").Worksheets("Summary").Range("J:J"))


text:
Q: How to get even or odd numbers I don't know why this program doesn't works. I get a random number and the computer select what type it is even or odd ?
Dim a As New Random()

    Dim b As Integer
    Dim ca As Integer
    b = a.Next(0, 10)
    Debug.Print(b)

    ca = b / 2

    If ca = 0 Then
        Debug.Print("Even")
    Else
        Debug.Print("Odd")
    End If

A: You could also just check the low order bit, if it is on the number is odd, if it is off the number is even.  Using a function:
    Dim a As New Random()
    Dim b As Integer
    b = a.Next(0, 10)
    Debug.WriteLine(b)
    If isEven(b) Then
        Debug.WriteLine("even")
    Else
        Debug.WriteLine("odd")
    End If

Private Function isEven(numToCheck As Integer) As Boolean
    Return (numToCheck And 1) = 0
End Function

edit: might be faster than mod but haven't checked.

A: You are messing up your operators.
You use division /, but you want to use the modulo operator Mod.
Please note: in C# it is %. In VB.Net it is Mod
Reference: http://msdn.microsoft.com/en-us/library/se0w9esz(v=vs.100).aspx
Dim a As New Random()
Dim b As Integer
Dim ca As Integer
b = a.Next(0, 10)
Debug.Print(b)

ca = b Mod 2

If ca = 0 Then
    Debug.Print("Even")
Else
    Debug.Print("Odd")
End If

Why your code does not work as expected:
The culprit is indeed your if-statement. You are checking if the result of b / 2 is 0. But this can only be true if b itself is 0. Every number greater then 0 devided by half is greater then zero.
Your code looks like you want to check for the rest of a division, hence the solution with the modulo operator.

A: Private sub command1_click()
   Dim a as integer
   a = text1.text
   If a mod 2=0 then
      Print a & " is even"
   Else
      Print a & "is odd"
   Endif
End sub


text:
Q: How to pipe two existing file descriptor (one from socket)? I am doing simple (un)secure shell-like program in C. Server-side is done, it just opens IPv4 socket, listens for connections and when someone connects, std* file descriptors are close()'d, client file descriptors are dup()'ed, and sh is execvp()'ed. Connecting via telnet almost works (telnet additionally sends ^M).
But now i am stuck on client-side - i don't want to use telnet.
I open socket, get file descriptor, connect, but now I want to pipe().
My code now looks like this:
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#include "util.h" /* die(), something like connected perror() and exit() */

int
main(void)
{
    int serverfd;
    struct sockaddr_in serveraddr_in;
    socklen_t serveraddr_len;
    char buf[8192];
    ssize_t rb;

    if ((serverfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
        die("socket:");

    serveraddr_in.sin_port = htons(2221);
    serveraddr_in.sin_addr.s_addr = inet_addr("127.0.0.1");
    serveraddr_in.sin_family = AF_INET;
    serveraddr_len = sizeof(serveraddr_in);

    if (connect(serverfd, (struct sockaddr *)&serveraddr_in, serveraddr_len) < 0)
        die("connect:");

    while (rb = read(0, buf, 8192)) {
        write(serverfd, buf, rb);
        rb = read(serverfd, buf, 8192);
        write(0, buf, rb);
    }

    close(serverfd);
}

I tried many combination of using pipe(), dup(), dup2() and close(), but program always ends after pipe()ing. What should I do to not use write() and buffers, but pipe()?


text:
Q: UI Design Issue I am new to Android. I am creating a layout for a registration form. Base container I am using as relative layout. Inside relative layout i am keeping liner layout container and then inside this all components of a registration form.
But after drooping two edit text field inside liner layout I can see both the edit text field are overlapping each other and it is visible as one and also moving towards center in liner container. Hope so understood. Well I need components one after one horizontally. Help?
 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent"
    >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="30dp"
            android:background="@drawable/l_border"
            android:padding="30dp"
            >

            <EditText
                android:id="@+id/txtMobile"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:background="@drawable/ll_border"
                android:backgroundTint="@color/colorAccent"
                android:hint="Enter Name"
                android:padding="10dp"
                android:textColorHint="@color/colorBlack" />

            <EditText
                android:id="@+id/txtName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:background="@drawable/ll_border"
                android:backgroundTint="@color/colorAccent"
                android:hint="Enter Mobile"
                android:padding="10dp"
                android:textColorHint="@color/colorBlack" />

        </LinearLayout>

</RelativeLayout>

[

A: First of all, unless you want to add something over your inner LinearLayout, there is no point in nesting it inside the RelativeLayout.
Second, your inner LinearLayout has no orientation set, so by default is set to horizontal which means the first edit text (layout_width="match_parent") will push out of the screen the second EditText.
If you set the orientation for the inner LinearLayot, to "vertical", you will be able to see both fields.
If you want to have both edit texts, placed horizontally, set the "layout_width"="0; "weight"="1 on both of the text fields. Or you can play around with the RelativeLayout positioning.
UPDATE -- Suggested by @petey
Here's a way to achieve what you want:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"  // this view is kind of pointless
android:background="@color/colorAccent">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="30dp"
    android:background="@drawable/l_border"
    android:padding="30dp">

    <EditText
        android:id="@+id/txtMobile"
        android:layout_width="0dp" // NOTICE THIS
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_weight="1" // // NOTICE THIS
        android:background="@drawable/ll_border"
        android:backgroundTint="@color/colorAccent"
        android:hint="Enter Name"
        android:padding="10dp"
        android:textColorHint="@color/colorBlack" />

    <EditText
        android:id="@+id/txtName"
        android:layout_width="0dp" // NOTICE THIS
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_weight="1" // NOTICE THIS
        android:background="@drawable/ll_border"
        android:backgroundTint="@color/colorAccent"
        android:hint="Enter Mobile"
        android:padding="10dp"
        android:textColorHint="@color/colorBlack" />

</LinearLayout>


text:
Q: How do I read data from TSPLIB / tsp files? I was looking for traveling salesman problem data sets and found this site.
However, I do not understand how to read the actual data from the extracted "tsp" files on this webpage... how can I go about doing so?
(I'm just a high school student so please excuse me if this is a stupid question)

A: You can read the XML instances (http://www.iwr.uni-heidelberg.de/groups/comopt/software/TSPLIB95/XML-TSPLIB/instances/) using some framework from any language.
XML is easier to understand by humans.


text:
Q: How to get expected output from MongoDB? I'm new to MongoDB aggregation. I am not getting desired output
The output I'm getting from aggregation:-
[
{tweet:{key:value}},
{tweet:{key:value}},
{tweet:{key:value}},
{tweet:{key:value}},
]

but I want the following output from the pipeline:-
[
{key:value},
{key:value},
{key:value},
]

and lastly, pipeline I'm running:-
const pipeline = [[
            {
              $match: {
                $expr: {
                  $in: [
                    Mongoose.Types.ObjectId(userid), '$likedBy.user'
                  ]
                }
              }
            }, {
              $lookup: {
                from: 'tweets',
                localField: 'tweet',
                foreignField: '_id',
                as: 'tweet'
              }
            }, {
              $unwind: {
                path: '$tweet'
              }
            }, {
              $lookup: {
                from: 'users',
                localField: 'tweet.user',
                foreignField: '_id',
                as: 'user'
              }
            }, {
              $unwind: {
                path: '$user'
              }
            }, {
              $addFields: {
                'tweet.user': '$user'
              }
            },
            {
                $addFields: {
                  'tweet.isLiked': true,
                }
              },{
                  $project:{
                      tweet:1,
                  }
              },
          ]
        ];
        const likedTweets = await TweetLike.aggregate(pipeline)

I know I can do this with javascript but I want to do it with the pipeline

A: You can replace your last project stage with the following to achieve what you need:
{$project:{key:"$tweet.key"}}

A: Answering my own question
i wanted to return sub-document so i found this https://stackoverflow.com/a/43411988/12332711
all i had to do is use
{
 $replaceRoot: {newRoot: "$tweet"}
 }

it worked for me


text:
Q: did end on exit not triggering I'm using a method
-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
NSInteger nextTag = textField.tag + 1;
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
    [nextResponder becomeFirstResponder];
} else {
    [textField resignFirstResponder];
}
return NO;
}

Which allows users to jump between text fields on a login page using the "next" button on the keyboard (based on tags).  However, my last UITextfield is not triggering the "did end on exit" event because it is already hooked up to a delegate of file's owner.  I can get it to trigger the "did end on exit" event if I remove the file's owner delegate, but in that case I can't jump to the last text field using the "next" button on the keyboard.  Is there a workaround for this?

A: Instead of writing this code in textFieldShouldReturn, you can write this code in your own method and call this method on next button click.


text:
Q: How to calculate $\int_{0}^{\frac{\pi}{2}}{x(x-\pi)\cot(x)dx}$ I know how to calculate $\int_{0}^{\frac{\pi}{2}}{x\cot(x)dx}$
But when it adds $(x-\pi)$, I don't know how to do.

A: Integration by parts tells that
$$
\int_{0}^{\frac{\pi}{2}} x(x-\pi)\cot x \, dx
= \underbrace{\left[ x(x-\pi) \log\sin x \right]_{0}^{\frac{\pi}{2}}}_{=0} - \int_{0}^{\frac{\pi}{2}} (2x-\pi) \log\sin x \, dx.
$$
Now notice that
$$ -\log\sin x = -\log\left| \frac{1 - e^{2ix}}{2}\right| = \log 2 + \sum_{n=1}^{\infty} \frac{\cos (2nx)}{n} $$
So we have
\begin{align*}
\int_{0}^{\frac{\pi}{2}} x(x-\pi)\cot x \, dx
&= \int_{0}^{\frac{\pi}{2}} (2x-\pi) \left( \log 2 + \sum_{n=1}^{\infty} \frac{\cos (2nx)}{n} \right) \, dx \\
&= -\frac{\pi^2}{4}\log 2 + \sum_{n=1}^{\infty} \frac{(-1)^n - 1}{2n^3} \\
&= -\frac{\pi^2}{4}\log 2 - \frac{7}{8}\zeta(3).
\end{align*}

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\bbox[10px,#ffd]{\ds{\int_{0}^{\pi/2}x\pars{x - \pi}\cot\pars{x}\,\dd x}}
\stackrel{\mrm{IBP}}{=}
-\int_{0}^{\pi/2}\pars{2x - \pi}\ln\pars{\sin\pars{x}}\,\dd x
\\[5mm] \stackrel{x\ \mapsto\ \pi/2 - x}{=}&\
2\int_{0}^{\pi/2}x\ln\pars{\cos\pars{x}}\,\dd x =
\left.2\,\Re\int_{x\ =\ 0}^{x\ =\ \pi/2}
\bracks{-\ic\ln\pars{z}}\ln\pars{1 + z^{2} \over 2z}\,{\dd z \over \ic z}
\,\right\vert_{\ z\ =\ \exp\pars{\ic x}}
\\[5mm] = &\
\left. -2\,\Re\int_{x\ =\ 0}^{x\ =\ \pi/2}
\ln\pars{z}\ln\pars{1 + z^{2} \over 2z}\,{\dd z \over z}
\,\right\vert_{\ z\ =\ \exp\pars{\ic x}}
\\[1cm] \stackrel{\mrm{as}\ \epsilon\ \to\ 0^{\large +}}{\sim}&\
2\,\Re\int_{1}^{\epsilon}
\bracks{\ln\pars{y} + {\pi \over 2}\,\ic}
\bracks{\ln\pars{1 - y^{2} \over 2y} - {\pi \over 2}\,\ic}
\,{\ic\,\dd y \over \ic y}
\\[2mm] &\
+ 2\,\Re\int_{\pi/2}^{0}\bracks{\ln\pars{\epsilon} + \ic\theta}
\bracks{-\ln\pars{2\epsilon} - \ic\theta}\,{\epsilon\expo{\ic\theta}\ic\,\dd\theta \over \epsilon\expo{\ic\theta}} +
2\,\Re\int_{\epsilon}^{1}
\ln\pars{x}\ln\pars{1 + x^{2} \over 2x}\,{\dd x \over x}
\\[1cm] =&\
-2\int_{\epsilon}^{1}
\bracks{\ln\pars{y}\ln\pars{1 - y^{2} \over 2y} + {\pi^{2} \over 4}}
\,{\dd y \over y} -
2\int_{0}^{\pi/2}\bracks{\ln\pars{2} + 2\ln\pars{\epsilon}}\theta\,\dd\theta
\\[2mm] &\
+ 2\int_{\epsilon}^{1}
\ln\pars{x}\ln\pars{1 + x^{2} \over 2x}\,{\dd x \over x}
\\[1cm] \stackrel{\mrm{as}\ \epsilon\ \to\ 0^{\large +}}{\sim}&\
-2\int_{0}^{1}{\ln\pars{y}\ln\pars{1 - y^{2}} \over y}\,\dd y -
2\int_{\epsilon}^{1}{-\ln\pars{y}\ln\pars{2y} + \pi^{2}/4 \over y}\,\dd y -
\bracks{\ln\pars{2} + 2\ln\pars{\epsilon}}\,{\pi^{2} \over 4}
\\[2mm] &\
2\int_{0}^{1}{\ln\pars{x}\ln\pars{1 + x^{2}} \over x}\,\dd x -
2\int_{\epsilon}^{1}{\ln\pars{x}\ln\pars{2x} \over x}\,\dd x
\\[1cm] \stackrel{\mrm{as}\ \epsilon\ \to\ 0^{+}}{\to}&\
-\,{\pi^{2} \over 4}\,\ln\pars{2} -
{1 \over 2}\int_{0}^{1}{\ln\pars{\xi}\ln\pars{1 - \xi} \over \xi}\,\dd\xi +
{1 \over 2}\int_{0}^{1}{\ln\pars{\xi}\ln\pars{1 + \xi} \over \xi}\,\dd\xi
\\[1cm] = &\
-\,{\pi^{2} \over 4}\,\ln\pars{2} -
{1 \over 2}\int_{0}^{1}{\ln\pars{\xi}\ln\pars{1 - \xi} \over \xi}\,\dd\xi +
\left[{1 \over 2}\int_{0}^{1}{\ln\pars{\xi}\ln\pars{1 - \xi^{2}} \over \xi}\,\dd\xi\right.
\\[2mm] &\
\left. - {1 \over 2}\int_{0}^{1}{\ln\pars{\xi}\ln\pars{1 - \xi} \over \xi}\,\dd\xi\right]
\\[1cm] = &\
-\,{\pi^{2} \over 4}\,\ln\pars{2} -
{1 \over 2}\int_{0}^{1}{\ln\pars{\xi}\ln\pars{1 - \xi} \over \xi}\,\dd\xi +
\left[{1 \over 8}\int_{0}^{1}{\ln\pars{\xi}\ln\pars{1 - \xi} \over \xi}\,\dd\xi\right.
\\[2mm] &\
\left. - {1 \over 2}\int_{0}^{1}{\ln\pars{\xi}\ln\pars{1 - \xi} \over \xi}\,\dd\xi\right]
\\[1cm] = &\
-\,{\pi^{2} \over 4}\,\ln\pars{2} -
{7 \over 8}\int_{0}^{1}{\ln\pars{\xi}\ln\pars{1 - \xi} \over \xi}\,\dd\xi =
-\,{\pi^{2} \over 4}\,\ln\pars{2} +
{7 \over 8}\int_{0}^{1}\ln\pars{\xi}\,\mrm{Li}_{2}'\pars{\xi}\,\dd\xi
\\[5mm] = &\
-\,{\pi^{2} \over 4}\,\ln\pars{2} -
{7 \over 8}\int_{0}^{1}\overbrace{\mrm{Li}_{2}\pars{\xi} \over \xi}
^{\ds{\mrm{Li}_{3}'\pars{\xi}}}\,\dd\xi =
-\,{\pi^{2} \over 4}\,\ln\pars{2} - {7 \over 8}\mrm{Li}_{3}\pars{1}
\\[5mm] = &\
\bbx{-\,{\pi^{2} \over 4}\,\ln\pars{2} - {7 \over 8}\,\zeta\pars{3}}
\approx -2.7621
\end{align}


text:
Q: Scroll on bottom divs I am working on my own chat. And on one main window I have more chat windows(divs). And I want when I load my main windows, that my chat divs was scrolled on bottom. Have you any solutions?

A: There's a number of different jQuery solutions that do this, take a look at them here
The general gist of it, is browser detects you're at the bottom of the page, do an ajax query, append onto page.

A: $('#div1').scrollTop($('#div1')[0].scrollHeight);

this is your solution :D
http://jsfiddle.net/emx9D/


text:
Q: Looking for an efficient implementation of the reverse of lzip or interleave in Tcl: Building sublists with every nth item This describes an interleave function that can lzip data:
% interleave {a b c} {1 2 3}
a 1 b 2 c 3

I am looking for the reverse operation. Also I would like to specify into how many sublists the input shall be split. For example:
% lnth {a 1 b 2 c 3}  1
{a 1 b 2 c 3}

% lnth {a 1 b 2 c 3}  2
{a b c} {1 2 3}

% lnth {a 1 b 2 c 3}  3
{a 2} {1 c} {b 3}

% lnth {a 1 b 2 c 3}  6
{a} {1} {b} {2} {c} {3}

For uneven splits, the missing elements shall be just omitted. If you feel like it you could provide a default argument to be filled in, but that's not required. Also I don't mind the exact quotation of the two corner cases where n==1 or n==[llength $L]. Thanks Hai Vu for pointing this out in your earlier answer.
It would be good to have some notion of complexity in time and memory.
I'm on Tcl8.4 (this cannot be changed).
Update
For these kind of benchmark question its always good to have a central summary. All tests ran on the same machine, on the (rather small) example list $L as shown below. It's all highly un-scientific.Good code comes from the answers below, errors are mine.
Test code:
#!/usr/bin/tclsh

proc build_list {len} {
    incr len
    while {[incr len -1]} {
        lappend res {}
    }
    set res
}

proc lnth3_prebuild_no_modulo {L n} {
    # Build empty 2D list to hold result
    set iterations [expr {int(ceil(double([llength $L]) / $n))}]
    set one [build_list $iterations]
    set res [list]
    set cnt [expr {$n+1}]
    while {[incr cnt -1]} {
        lappend res $one
    }

    # Fill in original/real values
    set iteration 0
    set subListNumber 0
    foreach item $L {
        lset res $subListNumber $iteration $item
        if {[incr subListNumber] == $n} {
            set subListNumber 0
            incr iteration
        }
    }
    set res
}

proc lnth3_no_modulo {L n} {
    # Create a list of variables: subList0, subList1, subList2, ...
    for {set subListNumber 0} {$subListNumber < $n} {incr subListNumber} {
        set subList$subListNumber {}
    }

    # Build the sub-lists
    set subListNumber 0
    foreach item $L {
        lappend subList$subListNumber $item
        if {[incr subListNumber] == $n} {
            set subListNumber 0
        }
    }

    # Build the result from all the sub-lists
    set result {}
    for {set subListNumber 0} {$subListNumber < $n} {incr subListNumber} {
        lappend result [set subList$subListNumber]
    }

    return $result
}

proc lnth {L n} {
    set listvars ""
    for {set cnt 0} {$cnt < $n} {incr cnt} {
        lappend listvars "L$cnt"
    }

    set iterations [expr {ceil(double([llength $L]) / $n)}]
    for {set cnt 0} {$cnt < $iterations} {incr cnt} {
        foreach listvar $listvars el [lrange $L [expr {$cnt*$n}] [expr {($cnt+1)*$n-1}] ] {
            lappend $listvar $el
        }
    }

    set res [list]
    foreach listvar $listvars {
        lappend res [eval "join \$$listvar"]
    }
    set res
}

proc lnth_prebuild {L n} {
    set iterations [expr {int(ceil(double([llength $L]) / $n))}]
    set one [build_list $iterations]

    set listvars ""
    for {set cnt 0} {$cnt < $n} {incr cnt} {
        lappend listvars L$cnt
        set L$cnt $one
    }

    for {set cnt 0} {$cnt < $iterations} {incr cnt} {
        foreach listvar $listvars el [lrange $L [expr {$cnt*$n}] [expr {($cnt+1)*$n-1}] ] {
            lset $listvar $cnt $el
        }
    }

    set res [list]
    foreach listvar $listvars {
        lappend res [eval "join \$$listvar"]
    }
    set res
}

proc lnth2 {L n} {
    set listLen [llength $L]
    set subListLen [expr {$listLen / $n}]
    if {$listLen % $n != 0} { incr subListLen }
    set result {}

    for {set iteration 0} {$iteration < $n} {incr iteration} {
        set subList {}
        for {set i $iteration} {$i < $listLen} {incr i $n} {
            lappend subList [lindex $L $i]
        }
        lappend result $subList
    }
    return $result
}

proc lnth3 {L n} {
    # Create a list of variables: subList0, subList1, subList2, ...
    for {set subListNumber 0} {$subListNumber < $n} {incr subListNumber} {
        set subList$subListNumber {}
    }

    # Build the sub-lists
    set i 0
    foreach item $L {
        set subListNumber [expr {$i % $n}]
        lappend subList$subListNumber $item
        incr i
    }

    # Build the result from all the sub-lists
    set result {}
    for {set subListNumber 0} {$subListNumber < $n} {incr subListNumber} {
        lappend result [set subList$subListNumber]
    }

    return $result
}

# stuff subcommands in a namespace
namespace eval ::unlzip {}

proc unlzip {L n} {
   # check if we have the proc already
   set name [format "::unlzip::arity%dunlzip" $n]
   if {[llength [info commands $name]]} {
      return [$name $L]
   } else {
      # create it
      proc $name {V} [::unlzip::createBody $n]
      return [$name $L]
   }
}

proc ::unlzip::createBody {n} {
   for {set i 0} {$i < $n} {incr i} {
       lappend names v$i
       lappend lnames lv$i
   }
   set lbody ""
   set ret {
   return [list }
   foreach lname $lnames name $names {
       append lbody [format {
       lappend %s $%s} $lname $name]
       append ret "\$$lname "
   }
   append ret {]}
   return [format {foreach {%s} $V { %s }
                   %s} $names $lbody $ret]
}

### Tests
set proc_reference lnth
set procs {lnth_prebuild lnth2 lnth3 unlzip lnth3_no_modulo lnth3_prebuild_no_modulo}
set L {a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 j 9 i 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26}
set Ns {1 2 3 4 5 6 7 8 9 10 13 26}

# Functional verification
foreach n $Ns {
    set expected [$proc_reference $L $n]
    foreach p $procs {
        set result [$p $L $n]
        if {$expected ne $result} {
            puts "Wrong result for proc $p, N=$n."
            puts "  Expected: $expected"
            puts "       Got: $result"
        }
    }
}

# Table header
puts -nonewline [format "%30s" {proc_name\N}]
foreach n $Ns {
    puts -nonewline [format "  %7d" $n]
}
puts ""

# Run benchmarks
foreach proc_name [concat $proc_reference $procs] {
    puts -nonewline [format "%30s" $proc_name]
    foreach n $Ns {
        puts -nonewline [format "  %7.2f" [lindex [time "$proc_name \$L $n" 10000] 0]]
    }
    puts ""
}

The results:
               proc_name\N        1        2        3        4        5        6        7        8        9       10       13       26
                      lnth    33.34    23.73    21.88    20.51    21.33    21.33    22.41    23.07    23.36    25.59    26.09    38.39
             lnth_prebuild    41.14    31.00    28.88    27.24    28.48    29.06    30.45    31.46    31.43    34.65    34.45    49.10
                     lnth2     8.56     8.08     8.35     8.78     9.12     9.29     9.66     9.98    10.29    10.61    11.22    14.94
                     lnth3    17.15    18.35    18.91    19.55    20.55    21.42    22.24    23.54    23.71    24.27    25.79    33.78
                    unlzip     5.36     5.25     5.03     4.97     5.27     5.42     5.52     5.43     5.42     5.96     5.51     6.83
           lnth3_no_modulo    14.88    16.56    17.20    17.97    18.63    19.42    19.78    20.74    21.53    21.84    23.60    31.29
  lnth3_prebuild_no_modulo    14.44    13.30    12.83    12.51    12.51    12.43    12.36    12.41    12.41    12.83    12.70    14.09

A: One option would be creating specialized procs on the fly:
Not sure how fast it is for larger N or larger sets, but should be quite fast for repeated runs, as you have nearly no overhead than straight calls to foreach and lappend.
package require Tcl 8.4

# stuff subcommands in a namespace
namespace eval ::unlzip {}

proc unlzip {L n} {
   # check if we have the proc already
   set name [format "::unlzip::arity%dunlzip" $n]
   if {[llength [info commands $name]]} {
      return [$name $L]
   } else {
      # create it
      proc $name {V} [::unlzip::createBody $n]
      return [$name $L]
   }
}

proc ::unlzip::createBody {n} {
   for {set i 0} {$i < $n} {incr i} {
       lappend names v$i
       lappend lnames lv$i
   }
   set lbody ""
   set ret {
   return [list }
   foreach lname $lnames name $names {
       append lbody [format {
       lappend %s $%s} $lname $name]
       append ret "\$$lname "
   }
   append ret {]}
   return [format {foreach {%s} $V { %s }
                   %s} $names $lbody $ret]
}

proc ::unlzip::arity1unlzip {V} {
   return [list $V]
}

# example how the function looks for N=2

proc ::unlzip::arity2unlzip {V} {
   foreach {v1 v2} $V {
      lappend lv1 $v1
      lappend lv2 $v2
   }
   return [list $lv1 $lv2]
}

The disassambled bytecode for Tcl 8.6 for the N=3 proc would look like this (via Tcl 8.6. ::tcl::unsupported::disassemble proc:
ByteCode 0x00667988, refCt 1, epoch 5, interp 0x005E0B70 (epoch 5)
Source "foreach {v0 v1 v2} $V { \n\t      lappend lv0 $v0\n\t      "
Cmds 6, src 149, inst 86, litObjs 1, aux 1, stkDepth 3, code/src 0.00
Proc 0x00694368, refCt 1, args 1, compiled locals 9
  slot 0, scalar, arg, "V"
  slot 1, scalar, temp
  slot 2, scalar, temp
  slot 3, scalar, "v0"
  slot 4, scalar, "v1"
  slot 5, scalar, "v2"
  slot 6, scalar, "lv0"
  slot 7, scalar, "lv1"
  slot 8, scalar, "lv2"
Exception ranges 1, depth 1:
  0: level 0, loop, pc 17-57, continue 10, break 61
Commands 6:
  1: pc 0-63, src 0-94        2: pc 17-30, src 32-46
  3: pc 31-44, src 55-69        4: pc 45-57, src 78-93
  5: pc 64-84, src 120-148        6: pc 73-83, src 128-147
Command 1: "foreach {v0 v1 v2} $V { \n\t      lappend lv0 $v0\n\t      "
  (0) loadScalar1 %v0         # var "V"
  (2) storeScalar1 %v1        # temp var 1
  (4) pop
  (5) foreach_start4 0
            [data=[%v1], loop=%v2
             it%v1  [%v3, %v4, %v5]]
  (10) foreach_step4 0
            [data=[%v1], loop=%v2
             it%v1  [%v3, %v4, %v5]]
  (15) jumpFalse1 +46         # pc 61
Command 2: "lappend lv0 $v0"
  (17) startCommand +13 1     # next cmd at pc 30
  (26) loadScalar1 %v3        # var "v0"
  (28) lappendScalar1 %v6     # var "lv0"
  (30) pop
Command 3: "lappend lv1 $v1"
  (31) startCommand +13 1     # next cmd at pc 44
  (40) loadScalar1 %v4        # var "v1"
  (42) lappendScalar1 %v7     # var "lv1"
  (44) pop
Command 4: "lappend lv2 $v2 "
  (45) startCommand +13 1     # next cmd at pc 58
  (54) loadScalar1 %v5        # var "v2"
  (56) lappendScalar1 %v8     # var "lv2"
  (58) pop
  (59) jump1 -49      # pc 10
  (61) push1 0        # ""
  (63) pop
Command 5: "return [list $lv0 $lv1 $lv2 ]"
  (64) startCommand +21 2     # next cmd at pc 85, 2 cmds start here
Command 6: "list $lv0 $lv1 $lv2 "
  (73) loadScalar1 %v6        # var "lv0"
  (75) loadScalar1 %v7        # var "lv1"
  (77) loadScalar1 %v8        # var "lv2"
  (79) list 3
  (84) done
  (85) done

As straight forward as it gets..., well, if the lists are incomplete (llength $L modulo $n isn't zero) you would need some little extra checks. As long as the lists are balanced, you could als pre populate the lists and use lset instead of lappend, which is faster, as it doesn't reallocate the list array so often.

A: Here is my approach: build one sub-list at a time, then append to the result before building the next one.
proc lnth2 {L n} {
    set listLen [llength $L]
    set subListLen [expr {$listLen / $n}]
    if {$listLen % $n != 0} { incr subListLen }
    set result {}

    for {set iteration 0} {$iteration < $n} {incr iteration} {
        set subList {}
        for {set i $iteration} {$i < $listLen} {incr i $n} {
            lappend subList [lindex $L $i]
        }
        lappend result $subList
    }
    return $result
}

Let say that L = {a 1 b 2 c 3} and n = 2, then I will build the first sub-list {a b c} by picking out the 0th, 2nd, and 4th items from the original list, append that to the result and move on the the second sub-list. Likewise, the second sub-list will be the 1th, 3rd, and 5th items.
Update
After reviewing my solution, I still don't like the fact that I have to use lindex. I imagine lindex has to travese the list in order to find the list item, and my solution placed lindex right inside a loop; which means we traverse the same list several times. The next attempt is to traverse the list only once. This time, I mimic your algorithm, but avoid using the list functions such as lrange.
proc lnth3 {L n} {
    # Create a list of variables: subList0, subList1, subList2, ...
    for {set subListNumber 0} {$subListNumber < $n} {incr subListNumber} {
        set subList$subListNumber {}
    }

    # Build the sub-lists
    set i 0
    foreach item $L {
        set subListNumber [expr {$i % $n}]
        lappend subList$subListNumber $item
        incr i
    }

    # Build the result from all the sub-lists
    set result {}
    for {set subListNumber 0} {$subListNumber < $n} {incr subListNumber} {
        lappend result [set subList$subListNumber]
    }

    return $result
}

Sadly, this attempt performs worse than my first attempt. I still don't understand why.

A: Got something now - but do not like it because it does not seem to be efficient:
proc lnth {L n} {
    set listvars ""
    for {set cnt 0} {$cnt < $n} {incr cnt} {
        lappend listvars "L$cnt"
    }

    set iterations [expr {ceil(double([llength $L]) / $n)}]
    for {set cnt 0} {$cnt < $iterations} {incr cnt} {
        foreach listvar $listvars el [lrange $L [expr {$cnt*$n}] [expr {($cnt+1)*$n-1}] ] {
            lappend $listvar $el
        }
    }

    set res [list]
    foreach listvar $listvars {
        lappend res [eval "join \$$listvar"]
    }
    set res
}

The trick is to have a couple of sublists, stored in variables L0, L1, L2, and to create those sublists dynamically, depending on how many ($n) are wanted.
The number of iterations then depends on len($L)/$n, using the ceil() here to cover incomplete iterations.
The last loop assembles the overall result list.
I simply do not know how to get around constructing the result list more efficiently during the main work loop. And I know too little about the internal efficiencies of Tcl in lappend or alternatives. Also it may be faster to just iterate over L and dole out elements to those sublists...

A: Out of curiosity, and inspired by Donal's comment that linsert is actually O(1) because Tcl lists are implemented with C arrays, I tried to improve Hai Vu's answer a little: First be removing the modulo operation with a simple counter and comparison. And second by replacing the lappend with an lset. This latter change requires to prebuild the result array.
Here's the code:
proc lnth3_no_modulo {L n} {
    # Create a list of variables: subList0, subList1, subList2, ...
    for {set subListNumber 0} {$subListNumber < $n} {incr subListNumber} {
        set subList$subListNumber {}
    }

    # Build the sub-lists
    set subListNumber 0
    foreach item $L {
        lappend subList$subListNumber $item
        if {[incr subListNumber] == $n} {
            set subListNumber 0
        }
    }

    # Build the result from all the sub-lists
    set result {}
    for {set subListNumber 0} {$subListNumber < $n} {incr subListNumber} {
        lappend result [set subList$subListNumber]
    }

    return $result
}

proc build_list {len} {
    incr len
    while {[incr len -1]} {
        lappend res {}
    }
    set res
}
proc lnth3_prebuild_no_modulo {L n} {
    # Build empty 2D list to hold result
    set iterations [expr {int(ceil(double([llength $L]) / $n))}]
    set one [build_list $iterations]
    set res [list]
    set cnt [expr {$n+1}]
    while {[incr cnt -1]} {
        lappend res $one
    }

    # Fill in original/real values
    set iteration 0
    set subListNumber 0
    foreach item $L {
        lset res $subListNumber $iteration $item
        if {[incr subListNumber] == $n} {
            set subListNumber 0
            incr iteration
        }
    }
    set res
}

These two make small improvements on the run time - but not by much:
               proc_name\N        1        2        3        4        5        6        7        8        9       10       13       26
                     lnth3    17.41    18.62    19.07    19.99    21.39    21.45    23.90    23.58    23.62    24.50    25.67    33.91
           lnth3_no_modulo    14.95    16.39    16.95    17.80    18.20    19.17    19.86    20.62    21.23    21.99    23.40    31.71
  lnth3_prebuild_no_modulo    14.46    12.90    12.24    11.85    11.80    11.65    11.61    11.61    11.70    11.81    11.96    13.23

It seems the prebuild alternative becomes more effective the more lappend list operations would have to be done otherwise.

A: A simple and efficient algorithm is something like this:
foreach {a b c} $data {
   lappend ra $a
   lappend rb $b
   lappend rc $c
}
list $ra $rb $rc

The downside is here that you have to specify different variables.
Upside is that it is efficient.


text:
Q: React router dom меняет ссылку, но, не перерисовывает компонент Делаю сайт с фильмами и возникла проблема что react router dom меняет ссылку в url, но компонент не перерисовывается.
Есть главная страница, где показываются популярны фильмы / сериалы и по клику рисуется другой компонент, в конце компонента, есть список похожих фильмов по клику на который он должен перерисовать контент, но ничего не происходит.
Так выглядит компонент для отображения информации о фильме, его url /detail/id
const Detail = () => {
  return (
    <DetailInfo />
    <Similar />
  )
}

Список похожих фильмов
const Similar = () => {
 return (
   <Link to={`/detail/${id}`}>
      какие то изображения, по клику на которые, меняется url
   </Link>
  )
}

При обновлении страницы все перерисовывается, но по клику нет
Github

A: В файле Detail.jsx в useEffect необходимо добавить в массив зависимостей movieId.  Иначе при обновлении movieId не срабатывает useEffect. Так же чтобы страница прокручивалась в начало необходимо добавить window.scrollTo({ top: 0 });.   В итоге имеем useEffect вида:
useEffect(() => {
    window.scrollTo({ top: 0 });
    const getMovieInfo = async () => {
      const movieInfoRes = await axios.get(
        `https://api.themoviedb.org/3/${movieId[1]}/${movieId[0]}?api_key=190eda9df5172483ad9af3e885997915&language=ru`
      );
      const movieInfoPersonRes = await axios.get(
        `https://api.themoviedb.org/3/${movieId[1]}/${movieId[0]}/credits?api_key=190eda9df5172483ad9af3e885997915&language=ru`
      );
      const movieTrailerRes = await axios.get(
        `https://api.themoviedb.org/3/${movieId[1]}/${movieId[0]}/videos?api_key=190eda9df5172483ad9af3e885997915&language=ru`
      );
      const movieSimilarRes = await axios.get(
        `https://api.themoviedb.org/3/${movieId[1]}/${movieId[0]}/similar?api_key=190eda9df5172483ad9af3e885997915&language=ru&page=1`
      );

      setMovieInfo(movieInfoRes.data);
      setMovieInfoPerson(movieInfoPersonRes.data);
      setMovieTrailer(movieTrailerRes.data);
      setMovieSimilar(movieSimilarRes.data);
    };
    getMovieInfo();
  }, [movieId]);


text:
Q: Расчет диапазона значений между двумя ползунками Есть имитация input type="range" на javascript.

function Range(container) {
  this.container = container;
  if (!this.container) return;
  this.inputMin = container.querySelector('[data-type=input-min]');
  this.inputMax = container.querySelector('[data-type=input-max]');
  this.minValue = parseFloat(container.querySelector('[data-type=min-val]').textContent.replace(/\s/g, ''));
  this.maxValue = parseFloat(container.querySelector('[data-type=max-val]').textContent.replace(/\s/g, ''));
  this.inner = container.querySelector('[data-type=range-inner-element]');
  this.valuesElem = container.querySelector('[data-type=range-element]');
  this.minBtn = container.querySelector('[data-type=min-btn]');
  this.maxBtn = container.querySelector('[data-type=max-btn]');

  //console.log(this);
  this.init();
}
Range.prototype.drag = function(event) {
  function move(event) {
    var left = event.pageX - elemX - boxX;
    if (elem == this.minBtn) {
      this.inner.style.left = elem.offsetLeft + elem.offsetWidth / 2 + 'px';
      if (left < 0) {
        left = 0;
      }
      if (left > this.maxBtn.offsetLeft - elem.offsetWidth) {
        left = this.maxBtn.offsetLeft - elem.offsetWidth;
      }
    } else if (elem == this.maxBtn) {
      this.inner.style.right = elem.offsetLeft - elem.offsetWidth / 2 + 'px';
      if (left < this.minBtn.offsetLeft + elem.offsetWidth) {
        left = this.minBtn.offsetLeft + elem.offsetWidth;
      }
      if (left > this.valuesElem.offsetWidth - elem.offsetWidth) {
        left = this.valuesElem.offsetWidth - elem.offsetWidth;
      }
    }
    elem.style.left = left + 'px';
    this.inner.style.width = this.maxBtn.offsetLeft - this.minBtn.offsetLeft + 'px';
  }

  function removeMove() {
    document.removeEventListener('mousemove', move);
    document.removeEventListener('mouseup', removeMove);
  }
  if (event.target == this.minBtn || event.target == this.maxBtn) {
    var elem = event.target;
    var elemX = event.pageX - elem.getBoundingClientRect().left;
    var boxX = this.valuesElem.getBoundingClientRect().left;
    var coord = event.target.offsetLeft;
    move = move.bind(this);
    document.addEventListener('mousemove', move);
    document.addEventListener('mouseup', removeMove);
    event.target.ondragstart = function() {
      return false;
    };
  }
}
Range.prototype.setValue = function() {
  this.inputMin.value = this.minValue;
  this.inputMax.value = this.maxValue;
}
Range.prototype.init = function() {
  this.inner.style.left = this.minBtn.offsetLeft + this.minBtn.offsetWidth / 2 + 'px';
  this.inner.style.right = this.maxBtn.offsetLeft - this.maxBtn.offsetWidth / 2 + 'px';
  this.setValue();
  this.valuesElem.addEventListener('mousedown', this.drag.bind(this));
}
var range = new Range(document.querySelector('[data-type=range]'));
.filters_section_list {
  width: 300px;
  list-style: none
}

.filters_section_item .range {
  height: 6px;
  background-color: #AEAEAE;
  border-radius: 4px;
  position: relative;
}

.filters_section_item .range_inner {
  height: inherit;
  background-color: #FD2016;
}

.filters_section_item .range_btn {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  box-shadow: 0 0 3px rgba(0, 0, 0, 0.6);
  position: absolute;
  top: -7px;
  background-color: #fff;
  cursor: pointer;
}

.filters_section_item .range_inner {
  position: absolute;
  width: 100%;
}

.filters_section_item .range_btn[data-type=min-btn] {
  left: 0;
}

.filters_section_item .range_btn[data-type=max-btn] {
  left: 100%;
}

.filters_section_item .values {
  overflow: hidden;
  margin-top: 40px;
}

.filters_section_item .values .min-value {
  float: left;
  width: 35%;
  text-align: left;
  padding-bottom: 14px;
  padding-left: 10px;
  padding-right: 10px;
  border-bottom: 1px solid #ACACAC;
}

.filters_section_item .values .max-value {
  float: right;
  width: 35%;
  text-align: right;
  padding-bottom: 14px;
  padding-left: 10px;
  padding-right: 10px;
  border-bottom: 1px solid #ACACAC;
}

    <input id="price-min" type="hidden" name="price-min" value="0" data-type="input-min">
    <input id="price-max" type="hidden" name="price-max" value="1000000" data-type="input-max">

      0
      1000000

Подскажите алгоритм как рассчитывать теперь диапазон значений между ползунками при их перемещении?

A:

function Range(container) {
  this.container = container;
  if (!this.container) return;
  this.inputMin = container.querySelector('[data-type=input-min]');
  this.inputMax = container.querySelector('[data-type=input-max]');
  this.minValue = parseFloat(container.querySelector('[data-type=min-val]').textContent.replace(/\s/g, ''));
  this.maxValue = parseFloat(container.querySelector('[data-type=max-val]').textContent.replace(/\s/g, ''));
  this.inner = container.querySelector('[data-type=range-inner-element]');
  this.valuesElem = container.querySelector('[data-type=range-element]');
  this.minBtn = container.querySelector('[data-type=min-btn]');
  this.maxBtn = container.querySelector('[data-type=max-btn]');

  //console.log(this);
  this.init();
}
Range.prototype.drag = function(event) {
  function move(event) {
    var left = event.pageX - elemX - boxX;
    var target;
    if (elem == this.minBtn) {
      this.inner.style.left = elem.offsetLeft + elem.offsetWidth / 2 + 'px';
      if (left < 0) {
        left = 0;
      }
      if (left > this.maxBtn.offsetLeft - elem.offsetWidth) {
        left = this.maxBtn.offsetLeft - elem.offsetWidth;
      }
  target = this.container.querySelector('[data-type=min-val]');
    } else if (elem == this.maxBtn) {
      this.inner.style.right = elem.offsetLeft - elem.offsetWidth / 2 + 'px';
      if (left < this.minBtn.offsetLeft + elem.offsetWidth) {
        left = this.minBtn.offsetLeft + elem.offsetWidth;
      }
      if (left > this.valuesElem.offsetWidth - elem.offsetWidth) {
        left = this.valuesElem.offsetWidth - elem.offsetWidth;
      }
  target = this.container.querySelector('[data-type=max-val]');
    }
    elem.style.left = left + 'px';
    this.inner.style.width = this.maxBtn.offsetLeft - this.minBtn.offsetLeft + 'px';

    target.innerText = this.minValue + (this.maxValue - this.minValue)*(left/this.valuesElem.offsetWidth);
  }

  function removeMove() {
    document.removeEventListener('mousemove', move);
    document.removeEventListener('mouseup', removeMove);
  }
  if (event.target == this.minBtn || event.target == this.maxBtn) {
    var elem = event.target;
    var elemX = event.pageX - elem.getBoundingClientRect().left;
    var boxX = this.valuesElem.getBoundingClientRect().left;
    var coord = event.target.offsetLeft;
    move = move.bind(this);
    document.addEventListener('mousemove', move);
    document.addEventListener('mouseup', removeMove);
    event.target.ondragstart = function() {
      return false;
    };
  }
}
Range.prototype.setValue = function() {
  this.inputMin.value = this.minValue;
  this.inputMax.value = this.maxValue;
}
Range.prototype.init = function() {
  this.inner.style.left = this.minBtn.offsetLeft + this.minBtn.offsetWidth / 2 + 'px';
  this.inner.style.right = this.maxBtn.offsetLeft - this.maxBtn.offsetWidth / 2 + 'px';
  this.setValue();
  this.valuesElem.addEventListener('mousedown', this.drag.bind(this));
}
var range = new Range(document.querySelector('[data-type=range]'));
.filters_section_list {
  width: 300px;
  list-style: none
}

.filters_section_item .range {
  height: 6px;
  background-color: #AEAEAE;
  border-radius: 4px;
  position: relative;
}

.filters_section_item .range_inner {
  height: inherit;
  background-color: #FD2016;
}

.filters_section_item .range_btn {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  box-shadow: 0 0 3px rgba(0, 0, 0, 0.6);
  position: absolute;
  top: -7px;
  background-color: #fff;
  cursor: pointer;
}

.filters_section_item .range_inner {
  position: absolute;
  width: 100%;
}

.filters_section_item .range_btn[data-type=min-btn] {
  left: 0;
}

.filters_section_item .range_btn[data-type=max-btn] {
  left: 100%;
}

.filters_section_item .values {
  overflow: hidden;
  margin-top: 40px;
}

.filters_section_item .values .min-value {
  float: left;
  width: 35%;
  text-align: left;
  padding-bottom: 14px;
  padding-left: 10px;
  padding-right: 10px;
  border-bottom: 1px solid #ACACAC;
}

.filters_section_item .values .max-value {
  float: right;
  width: 35%;
  text-align: right;
  padding-bottom: 14px;
  padding-left: 10px;
  padding-right: 10px;
  border-bottom: 1px solid #ACACAC;
}

    <input id="price-min" type="hidden" name="price-min" value="0" data-type="input-min">
    <input id="price-max" type="hidden" name="price-max" value="1000000" data-type="input-max">

      0
      1000000

UP:
Для тех, кто слишком давно учился в школе:
left //  расстояние от минимального значения до текущего значения в пикселях.
// Всё, что нам нужно сделать - это перевести его из пикселей в шкалу, заданную минимальным и максимальным значением -
this.valuesElem.offsetWidth //размер шкалы в пикселях
scale = maxValue - minValue; // размер шкалы в еденицах шкалы
percent = left/offsetWidth // отношение отрезка значения к размеру шкалы (безразмерное, тк пиксели делим на пиксели - получаем разы)
value = minValue + scale*percent; // осталось домножить эти разы на размер шкалы в нужных единицах и прибавить к значению, с которого шкала начинается.
// Выкидываем лишние промежуточные переменные, получается -
value = this.minValue + (this.maxValue - this.minValue)*(left/this.valuesElem.offsetWidth);


text:
Q: Turning Off Tooltips using Media Queries How can I add in media queries so that the qtip does not display when scaled down to mobile sizes? Here is the jquery I am using.
jQuery.root.find(".tooltip").qtip({
position:{
corner: {
tooltip: "bottomMiddle",
target: "topMiddle"
}
},
style: {
border: {
width: 2,
radius: 3
},
padding: 7,
width: 350,
tip: true,
name: "light"
}
});

Here is the HTML:

    Advanced Track
I've tried the following but it doesn't work:
@media only screen and (max-width: 767px) {
.tooltip {
display: none;
}

}

A: A quick look at the elements that qtip creates shows that the tool tips themselves are created with class .qtip
So
@media only screen and (max-width: 767px) {
    .qtip {
        display: none;
    }
}

Should do the trick


text:
Q: how to execute a oracle sql script form local machine using powershell I have a oracle SQL script which has a select query that spools the data to a CSV file. The SQL script is saved in my local machine in some folder, how to execute this script. I also want to remove the double quotes for char in the CSV file and remove the 1st empty line in the CSV file . My first issue is how to execute the SQL script. I am new to Powershell
I am getting error as sqlplus is not recognized as a cmdlet
$mydata = invoke-sqlplus -inputfile "C:\user\script.sql"
get-content C:\user\script.csv | select-object -skip 1
(Get-Content C:\user\script.csv_1.csv) | % {$_ -replace '"', ""} | out-file -FilePath C:\user\script.csv.csv -Force -Encoding ascii

A: Can you run the sqlplus command from powershell on it's own?
"sqlplus is not recognized as a cmdlet" looks to me like Windows can't find the sqlplus executable. You might need to add it to the PATH if you're going to call it straight from powershell (it's under %ORACLE_HOME%\bin):
https://www.ibm.com/support/knowledgecenter/en/SSFUEU_7.3.0/com.ibm.swg.ba.cognos.op_installation_guide.7.3.0.doc/t_camphor_setting_environment_variables_ora.html


text:
Q: Translate several files in a ZIP file Using the Forge model derivatie API, is it possible to translate several models in a zip file even if the models are not internally linked?
I have some very large Navisworks models and if I link them, the viewer is painfully slow. What I would like to do is to split the model into mutiple smaller models, put them in a zip file and translate them. Then I would like to only display the sub models I choose to. I have tried to do this, but I can only find the model set as root model.

A: You can translate individual split up models, but they have to be in separate uploads. You can aggregate more than one models in one Viewer after you translated them for better performance on large models. There's a blog post on how to do that.


text:
Q: Pole of a free-particle propagator The free-particle propagator is given by
$$\Delta_F(x-y) = \frac{1}{(2\pi)^4} \int \frac{e^{-ik\cdot(x-y)}}{k^2-m^2+i\epsilon} \, d^4k.$$
In the book Quantum Field Theory, Ryder says that $\Delta_F(x-y)$ has a pole at $k^2=m^2$ (page 203).
However, the pole is actually at $k^2=m^2 - i\epsilon$. Why is the $-i\epsilon$ term not mentioned?

A: Well I don't have the book, but usually the $i \epsilon$ is added intentionally (and artificially) to address the pole, and bring it off the real axis.  Somewhere later in the calculation, you take the limit $\epsilon \rightarrow 0$.


text:
Q: How can I expand one axis to 2 axes in NumPy? Let's say I have a string ndarray with any dimension. For example: [["abc", "def"], ["ghi", "jkl"]]. Now, I want to split each string into separate chars, such that basically an axis in the second dimension is added: [[['a', 'd'], ['b', 'e'], ['c', 'f']], [['g', 'j'], ['h', 'k'], ['i', 'l']]]. Or better said, it should behave like MATLAB converting a string array to a char array:
A =
  2×2 string array
    "abc"    "def"
    "ghi"    "jkl"

should become:
  2×3×2 char array
ans(:,:,1) =
    'abc'
    'ghi'
ans(:,:,2) =
    'def'
    'jkl'

I tried functions like np.frompyfunc, np.apply_over_axis and np.apply_from_axis but so far nothing worked for me. Is there a clever trick to do this?
The reverse is actually pretty simple:
def row_to_string(row):
    return ''.join([chr(int(x)) for x in row])

return np.apply_along_axis(row_to_string, 1, np.asarray(x))

EDIT: For a 3D example, see this gist: https://gist.github.com/PeterTillema/215f0a6474849a06001e10804e5a6eca

A: In [159]: alist = [["abc", "def"], ["ghi", "jkl"]]
In [160]: np.frompyfunc(list,1,1)(alist)
Out[160]:
array([[list(['a', 'b', 'c']), list(['d', 'e', 'f'])],
       [list(['g', 'h', 'i']), list(['j', 'k', 'l'])]], dtype=object)
In [161]: np.array(np.frompyfunc(list,1,1)(alist).tolist())
Out[161]:
array([[['a', 'b', 'c'],
        ['d', 'e', 'f']],

       [['g', 'h', 'i'],
        ['j', 'k', 'l']]], dtype='<U1')

From there you can transpose to the desired layout.
Splitting a string into characters is a python task.  Numpy doesn't have special string code, just np.char functions that apply string methods to elements of an string dtype array.
frompyfunc is a convenience tool for applying a python function to elements of an array.  It doesn't compile anything, but usually is comparable to list comprehensions in speed, and may be more convenient.


text:
Q: Install Vuetify 3 with Vue CLI 5.x In vuetify documention:

The current version of Vuetify does not support Vue 3. Support for Vue
3 will come with the release of Vuetify v3. When creating a new
project, please ensure you selected Vue 2 from the Vue CLI prompts, or
that you are installing to an existing Vue 2 project.

Can i use vuetify 3 with Vue CLI 5 (Vue 3)? I installed them but get errors.

A: Yes it is possible, you may have missed a step to define which version.
if you run vue add vuetify and select Vuetify 3, you should be able to install it

it also works with Vuetify3 + Vite setup


text:
Q: MPLAB X IDE v5.40 "Link Error: Could not allocate program memory" How do I correct this? I am new to MPLAB X IDE v5.40 and just finished translating a ton of ladder logic into C.
After correcting all my syntax errors, I am now getting a few hundred errors named "Link Error:"
Below is a small snippet of what I mean: .
........
build/default/production/main.o: Link Error: Could not allocate section .text, size = 6238 PC units, attributes = code
build/default/production/CheckSoliV.o: Link Error: Could not allocate section .text, size = 3164 PC units, attributes = code
build/default/production/Undocking.o: Link Error: Could not allocate section .text, size = 2390 PC units, attributes = code
build/default/production/CIP.o: Link Error: Could not allocate section .text, size = 1824 PC units, attributes = code
build/default/production/Attach.o: Link Error: Could not allocate section .text, size = 1818 PC units, attributes = code
build/default/production/RetractLipseal.o: Link Error: Could not allocate section .text, size = 1506 PC units, attributes = code
build/default/production/Docking.o: Link Error: Could not allocate section .text, size = 1310 PC units, attributes = code
build/default/production/Manual.o: Link Error: Could not allocate section .text, size = 1206 PC units, attributes = code
build/default/production/LiftAdjust.o: Link Error: Could not allocate section .text, size = 970 PC units, attributes = code
build/default/production/Remove.o: Link Error: Could not allocate section .text, size = 870 PC units, attributes = code
build/default/production/Evacuation.o: Link Error: Could not allocate section .text, size = 506 PC units, attributes = code
build/default/production/ProtectHood.o: Link Error: Could not allocate section .text, size = 448 PC units, attributes = code
build/default/production/EndMain.o: Link Error: Could not allocate section .text, size = 316 PC units, attributes = code
build/default/production/EndDischarge.o: Link Error: Could not allocate section .text, size = 304 PC units, attributes = code
data_init: Link Error: Could not allocate section .dinit, size = 284 PC units, attributes = code keep
build/default/production/Discharge.o: Link Error: Could not allocate section .const, size = 72 PC units, attributes = psv page
mulsi3.eo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
brk.Lelo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
c30_uart.Leo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
sbrk.Leo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
remove.Leo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
write.Leo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
close.Leo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
_exit.Leo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
xgetmem.XX_eo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
malloc.XX_eo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
free.XX_eo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
xatexit.XX_elo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
fclose.XX_elo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
xfwprep.XX_eo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
strrchr.XX_eo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
strlen.XX_eo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
fputs.XX_eo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
fflush.XX_eo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
strcpy.XX_elo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
fputc.XX_elo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
errno.XX_elo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
xstrerro.XX_eo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
xfiles.XX_eo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
perror.XX_eo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
memcpy.XX_eo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
exit.XX_eo: Link Error: Could not allocate section .text, size = 0 PC units, attributes = code
......
Can anyone tell me if this has to do with something I'm missing from my code? malloc instructions maybe? Is this just hardware related? Again, I'm new to MPLAB so I would greatly appreciate any detailed answers you guys can provide me. I'm using the XC16 C compiler btw.


text:
Q: Axios @ React : Error: Request failed with status code 400 for PATCH i got this error when trying to Patch with axios on React.
The back-end is working [Node - Mongo] and everything is fine when trying in Postman.
Here is my code :
back-end
front-end
Any help plz ?

A: Your request fails because the allowedUpdates does not contain the id property that should send with the 1selectedUser


text:
Q: How to see all layers of PDF document on iOS, specifically annotations I'm working on an app for my company where we want to view annotations made on PDF documents in iOS (5.0).  The problem is that when the PDF document is viewed on iOS, whether in a UIWebView or QLPreviewer, the annotations do not appear.
I'm assuming that iOS is not picking up on a layer or "subView" of the PDF document. Does anyone know how to get these layers for the annotations to show up?

A: There really isn't a good way to do this with the native iOS API for handling PDF documents. You will need to purchase a third-party solution that is better at properly reading PDF files.  Here is one example


text:
Q: Why is fsck working so inconsistently? Okay, this is hard to describe, so I'll take it point by point.
I got a Linux server, it's running the latest version of Ubuntu. I ran fsck read only to check the hard drive. Here's the output:
blackwidower@Twilight:~$ sudo fsck -fn /dev/sda1
fsck from util-linux 2.26.2
e2fsck 1.42.12 (29-Aug-2014)
Warning!  /dev/sda1 is mounted.
Warning: skipping journal recovery because doing a read-only filesystem check.
Pass 1: Checking inodes, blocks, and sizes
Deleted inode 11667059 has zero dtime.  Fix? no

Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
Free blocks count wrong (98319973, counted=98319938).
Fix? no

Inode bitmap differences:  -11667059
Fix? no

/dev/sda1: ********** WARNING: Filesystem still has errors **********

/dev/sda1: 216607/60932096 files (0.2% non-contiguous), 145383835/243703808 blocks

So I decided to boot from a Live USB, and run the check from there. The result was... well it said everything was clean, with no errors. I then suspected it was something with the Live USB, so I rebooted the server in recovery mode and the result was the same, clean.
And before anyone asks, yes, I did force the check. It ran through all five steps, and found no errors. But it does find errors when I run internally.
I know there are errors here, but why aren't they being picked up? What exactly is going on? Can someone help me with this?

A: fsck are supposed to be run while filesystem is offline.
If file system is online, data are constantly exchanged between disk and memory.
Some data are in buffer (memory), while other are on disk, this lead to inconsitancies.
In your case, /dev/sda1 must be holding / (root) filesystem, so some data are buffered (/var/log/messages, last logs, cron log ...), hence inconsitancies.
If a fsck from an USB running system, after a clean shutdown reveal nothing, thou shalt have no fear, thy data is safe !


text:
Q: Create new variables based on specific factor levels in time series data with dplyr I've got some time series data where both the steps of the sequence (ranging from 1 to 8) as well as its topic (>100) are encoded as character factor levels within a single variable. Here is a minimal example (I omitted timestamps which would be increasing within each id):
id <- c(1,rep(2,5),rep(3,4))
step <- c("call", "call", "agent", "forest", "forward", "resolved", "call", "agent", "beach", "resolved")
(df <- data.frame(id,step))
   id     step
1   1     call
2   2     call
3   2    agent
4   2   forest
5   2  forward
6   2 resolved
7   3     call
8   3    agent
9   3    beach
10  3 resolved

I now want to split this information into two dedicated variables (step and topic), thereby shrinking the dataframe in rows and making it wider, while also repeating the topic for each row of the time series and adding an "NA" when there is no topic. Using base R to split this into two dataframes and merging them back together gets the job done:
step <- subset(df, step %in% c("call", "agent", "forward", "resolved"))
topic <- subset(df, step %in% c("forest", "beach"))
topic$topic <- topic$step
topic$step <- NULL
(newdf <- merge(step,topic, all=TRUE))
  id     step  topic
1  1     call   <NA>
2  2     call forest
3  2    agent forest
4  2  forward forest
5  2 resolved forest
6  3     call  beach
7  3    agent  beach
8  3 resolved  beach

This is somewhat clunky though and I'm looking for a more elegant dplyr/tidyverse approach to this. pivot_wider() doesn't seem to be able to do this. Any ideas?

A: This isn't particularly elegant, but it works:
steps <- c("call", "agent", "forward", "resolved")
df %>%
  mutate(type = ifelse(step %in% steps, "step", "topic"),
         row = cumsum(type == "step")) %>%
  pivot_wider(names_from = type, values_from = step) %>%
  group_by(id) %>%
  fill(topic, .direction = "updown") %>%
  ungroup()

# A tibble: 8 x 4
     id   row step     topic
  <dbl> <int> <chr>    <chr>
1     1     1 call     NA
2     2     2 call     forest
3     2     3 agent    forest
4     2     4 forward  forest
5     2     5 resolved forest
6     3     6 call     beach
7     3     7 agent    beach
8     3     8 resolved beach

A: Thanks for providing a minimal example of your problem
id <- c(1,rep(2,5),rep(3,4))
step <- c("call", "call", "agent", "forest", "forward",
  "resolved", "call", "agent", "beach", "resolved")
df <- data.frame(id,step)
df
#>    id     step
#> 1   1     call
#> 2   2     call
#> 3   2    agent
#> 4   2   forest
#> 5   2  forward
#> 6   2 resolved
#> 7   3     call
#> 8   3    agent
#> 9   3    beach
#> 10  3 resolved

This is a possible solution using tidyverse
library(dplyr)
library(tidyr)

df %>%
  # define in column type_c if step is an step or a topic
  # you need a unique id for each row to use pivot_wider in this case
  mutate(
    type_c = if_else(step %in% c("forest", "beach"), "topic", "step"),
    unique_id = 1:nrow(df)) %>%
  pivot_wider(names_from = type_c, values_from = c(id, step)) %>%
  mutate(id = coalesce(id_step, id_topic)) %>%
  select(id, step = step_step, topic = step_topic) %>%
  # Need group_by to apply the function fill
  group_by(id) %>%
  # fill replaces NA, in each id,  with a value found in any direction "downup"
  fill(topic, .direction = "downup") %>%
  # get rid off the NA in column step that pivot_wider created for each topic
  filter(!is.na(step))
#> # A tibble: 8 x 3
#> # Groups:   id [3]
#>      id step     topic
#>   <dbl> <chr>    <chr>
#> 1     1 call     <NA>
#> 2     2 call     forest
#> 3     2 agent    forest
#> 4     2 forward  forest
#> 5     2 resolved forest
#> 6     3 call     beach
#> 7     3 agent    beach
#> 8     3 resolved beach

Created on 2021-06-08 by the reprex package (v0.3.0)


text:
Q: UIButton Touch Forwarding Not Working In iOS5 (only on iPad) I can't seem to be able to figure out why this code for forwarding a UIButton touch stopped working in iOS5:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self.nextResponder touchesBegan:touches withEvent:event];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesMoved:touches withEvent:event];
    [self.nextResponder touchesMoved:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];
    [self.nextResponder touchesEnded:touches withEvent:event];
}

When I log the next responder's touches methods I can see that touches moved is only forwarded once and touches ended isn't forward at all. This is very unexpected behavior, as all touches are forwarded in iOS4. Any help would be appreciated.

A: While comment posters were able to get this code to work fine in their tests, I was unsuccessful in getting it to reliably work in iOS5. My solution was to use delegation to forward the touches to the interested party. Not elegant or preferred, but so far has worked fine without any gotchas.


text:
Q: Command not found in phonegap I followed a tutorial to use command to build, run, ... in phonegap at http://docs.phonegap.com but I can't use those commands, except the Create command.
The Create command is:
create ./test1 com.test1 test1
the original command is: $ /path/to/cordova-android/bin/create.bat /path/to/my_new_cordova_project com.example.cordova_project_name CordovaProjectName

After created project successfully, I run the command:
cd test1/cordova/build
the original command is: $ /path/to/my_new_cordova_project/cordova/build.bat

but it throws an error:

'build' is not recognized as an internal or external command,
  operable program or batch file.

Then I go to my new project folder, go in folder: cordova to look for build.bat, but I see nothing.
Can you show me how to fix this stuff, i want to use command to build my phonegap project. Thanks!

Additional info:
Using phonegap 2.6, android platform.
Windows 7 64bit.
I'm able to run command: ant, java, javac, and some in the android platform tools,...


text:
Q: ID3D11VideoDevice::CreateVideoDecoderOutputView fails I'm developing an application able to decode H264 stream through DrectX11's ID3D11VideoDecoder interface ( https://msdn.microsoft.com/en-us/library/windows/desktop/hh447766(v=vs.85).aspx ) and I got stuck at ID3D11VideoDevice::CreateVideoDecoderOutputView method, it just fails returning E_INVALIDARG. Yes, I know, there can be millions of reasons,
but are there some exceptionally common maybe? Are there any samples available illustrating decoding through ID3D11VideoDecoder (I haven't found any) ?
The part of my  code that I think is most likely to fail looks as follows:
// texture
D3D11_TEXTURE2D_DESC descT = { 0 };
descT.Width = 1024;
descT.Height = 768;
descT.MipLevels = 1;
descT.ArraySize =  1;
descT.Format = DXGI_FORMAT_NV12;
descT.SampleDesc.Count = 1;
descT.Usage = D3D11_USAGE_DEFAULT;
descT.BindFlags = D3D11_BIND_DECODER;
ID3D11Texture2D *pTex = nullptr;
pDX11VideoDevice->CreateTexture2D(&desc, 0, &pTex);

// decoder
D3D11_VIDEO_DECODER_OUTPUT_VIEW_DESC desc;
desc.DecodeProfile = D3D11_DECODER_PROFILE_H264_VLD_NOFGT; // what is     interesting it fails whatever decoder I choose
desc.Texture2D.ArraySlice = 1;
desc.ViewDimension = D3D11_VDOV_DIMENSION_TEXTURE2D;

HRESULT hr = pDX11VideoDevice->CreateVideoDecoderOutputView(pTex, &desc, &pVideoDecoderOutputView); // and here the fail occurs

Thank you

A: OK, solved the problem, there should be
desc.Texture2D.ArraySlice = 0;

in the snippet in post above. Still lots of work ahead


text:
Q: How to get into terminal on my Dell laptop which interferes with Wi-Fi button? I use 10.04  regularly and I dual-booted my laptop with 10.04 and Windows 7 already.
I  made a mistake in deleting my entire top and bottom panel on 10.04. So I am trying to get it back.
When I search through forums, it asks me to go to terminal and use some commands to get it back. But the problem is, I am not able to access my terminal through Alt+F2.
When I press F2, my Wi-Fi goes off because it is the Wi-Fi button on my Dell laptop and my Internet is off. It doesn't bring me a terminal. How should I get to a terminal to do any further action?

@obsessive foss  Thank you..That helped CTRl+Alt+T. I just pressed some commands  to get back my ubuntu top panel. I used the commands
gconftool-2 --shutdown

rm -rf ~/.gconf/apps/panel

pkill gnome-panel

But the cursory look at commands suggests i am shutting down gconftool and then killing process gnome panel too. How am i able to get back my top panel then..what are these commands actually doing??

A: Please use Fn+Alt+F2 as the function keys may need Fn. However, tris lets you run one command and the better key combination to use is Ctrl+Alt+T.
This actually applies to cases where any function key(F1-F12) acts improperly.