text:
Q: Compiling across different directories with GNU make I have a project structure like such:
mcts/
    src/
        node_queue.c
        node_queue.h
    tests/
        munit.c    # testing frame work
        munit.h
        list_test.c # includes node_queue.h and munit.h
        Makefile    # Makefile in question

So my objective here is to compile the test mcts/test/list_test.c .  I have read a couple different strategies to doing this. After reading a bit I adapted some things I took from Makefiles into this:
CC= gcc
SOURCE= $(wildcard ../src/*.c ./*.c)
OBJECTS= $(patsubst %.c, %.o, $(SOURCE))
INCLUDE= -I. -I../src/
CFLAGS= -std=c11 -g $(INCLUDE) -Werror -Wall

list_test: list_test.o munit.o ../src/node_queue.o
    $(CC) $(CFLAGS) $(INCLUDE) -o $@ list_test.o munit.o    ../src/node_queue.o

.c.o:
    $(CC) $(CFLAGS) -c $< -o $@

Which is the closest I've gotten in about 2 hours to working, when calling make in mcts/tests I receive the error:
list_test.o: In function `construct_test':
/home/----/mcts/tests/list_test.c:9: undefined reference to `construct'
collect2: error: ld returned 1 exit status
make: *** [Makefile:8: list_test] Error 1

Where construct is defined in mcts/src/node_queue.h.
Shouldn't $(INCLUDE) ensure that the header is being included?
And how can I get this to function?
Much thanks!

A: For your actual error, you're reporting a linking error to an undefined symbol. If the object or function of that name were defined in node_queue.h, you would instead get a multiple definition error for construct.
What you probably are missing is that you have a declaration in that header, but no definition in node_queue.c.


text:
Q: Instanceof for generic with > or without > I have a question about generics in Java and instanceof operator.
It's immposible to make such instanceof check:
if (arg instanceof List<Integer>)  // immposible due to
                                   // loosing parameter at runtime

but it's possible to run this one:
if (arg instanceof List<?>)

Now comes my question - is there any difference between arg instanceof List and arg instanceof List<?> ?

A: Java Generics are implemented by erasure, that is, the additional type information (<...>) will not be available at runtime, but erased by the compiler. It helps with static type checking, but not at runtime.
Since instanceof will perform a check at runtime, not at compile time, you can not check for Type<GenericParameter> in an instanceof ... expression.
As to your question (you probably seem to know already that the generic parameter is not available at runtime) there is no difference between List and List<?>. The latter is a wildcard which basically expresses the same thing as the type without parameters. It's a way of telling the compiler "I know that I don't know the exact type in here".
instanceof List<?> boils down to instanceof List - which are exactly the same.

A: List and List < ? > are not same but in this case when you using with instanceof operator they mean the same thing.
instanceof cann't be used with Generics as Generics doesn't store any type information at run time (due to erasure implementation).
This point gets cleared by below main method. I have declared two list (one of Integer type and other of String type). And instanceof behave same for List and List < ? >
public static void main(String[] args){
    List<Integer> l = new ArrayList<Integer>();
    List<String> ls = new ArrayList<String>();

    if(l instanceof List<?>){
        System.out.print("<?> ");
    }

    if(l instanceof List){
        System.out.print("l ");
    }

    if(ls instanceof List<?>){
        System.out.print("<?> ");
    }

    if(ls instanceof List){
        System.out.print("ls ");
    }
     }

output is :
<?> l <?> ls
In above main method all if statements are true. So it clear that in this case List and List<?> are same.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Oozie shell action failed to exec java in Linux We have submit below Oozie workflow job. It executed in windows cluster but in Linux it is failed.
<workflow-app xmlns='uri:oozie:workflow:0.3' name='shell-wf'>
    <start to='shell1' />
    <action name='shell1'>
        <shell xmlns="uri:oozie:shell-action:0.1">
            <job-tracker>${jobTracker}</job-tracker>
            <name-node>${nameNode}</name-node>
            <configuration>
                <property>
                  <name>mapred.job.queue.name</name>
                  <value>${queueName}</value>
                </property>
            </configuration>
            <exec>Java</exec>
            <argument>A</argument>
            <argument>B</argument>
            <file>${EXEC}#${EXEC}</file> <!--Copy the executable to compute node's current working directory -->
        </shell>
        <ok to="end" />
        <error to="fail" />
    </action>
    <kill name="fail">
        <message>Script failed, error message[${wf:errorMessage(wf:lastErrorNode())}]</message>
    </kill>
    <end name='end' />
</workflow-app>

But when i execute the above workflow file, it throw's exception can not run java program. No such file or directory.

A: If there is a shell action for a shell script, and any of the commands have failed in the shell script, you have to add the line #!/bin/bash -e in your shell script to capture the failure code for the transition. Then it will be captured in the output, and only your workflow will be killed.  Otherwise it will exit as successful even though the shell action might have had a failure.


text:
Q: How to obtain a single word from a string in C? In order to complete a program I am working on, I have to be able to put pieces of a string into a stack for later use. For example, say I had this string:
"22 15 - 2 +"
Ideally, I first want to extract 22 from the string, place it in a separate, temporary string, and then manipulate it as I would like. Here is the code that I'm using which I think would work, but it is very over-complicated.
void evaluatePostfix(char *exp){
    stack *s = initStack();
    char *temp_str;
    char temp;
    int temp_len, val, a, b, i=0, j;
    int len = strlen(exp);

    while(len > 0){
        temp_str = malloc(sizeof(char)); //holds the string i am extracting
        j=0;                             //first index in temp_str
        temp = exp[i];                   //current value in exp, incremented later on the function
        temp_len = 1;                    //for reallocation purposes
        while(!isspace(temp)){           //if a white space is hit, the full value is already scanned
            if(ispunct(temp))            //punctuation will always be by itself
                break;                   //break if it is encountered
            temp_str = (char*)realloc(temp_str, temp_len+1); //or else reallocate the string to hold the new character
            temp_str[j] = temp;          //copy the character to the string
            temp_len++;                  //increment for the length of temp_str
            i++;                         //advance one value in exp
            j++;                         //advance one value in temp_str
            len--;                       //the number of characters left to scan is one less
            temp = exp[i];               //prepare for the next loop
        }                                //and so on, and so on...
    }                                    //more actions follow this, but are excluded
}

Like I said, overcomplicated. Is there a simpler way for me to extract this code? I can reliably depend upon there being white space between the values and characters I need to extract.

A: If you are good to use library function, then strtok is for this
#include <string.h>
#include <stdio.h>

int main()
{
   char str[80] = "22 15 - 2 +";
   const char s[2] = " ";
   char *token;

   /* get the first token */
   token = strtok(str, s);

   /* walk through other tokens */
   while( token != NULL )
   {
      printf( " %s\n", token );

      token = strtok(NULL, s);
   }

   return(0);
}

Reference

The limitation of strtok(char *str, const char *delim) is that it can't work on multiple strings simultaneously as it maintains a static pointer to store the index till it has parsed (hence sufficient if playing with only one string at a time). The better and safer method is to use strtok_r(char *str, const char *delim, char **saveptr) which explicitly takes a third pointer to save the parsed index.
#include <string.h>
#include <stdio.h>

int main()
{
   char str[80] = "22 15 - 2 +";
   const char s[2] = " ";
   char *token, *saveptr;

   /* get the first token */
   token = strtok_r(str, s, &saveptr);

   /* walk through other tokens */
   while( token != NULL )
   {
      printf( " %s\n", token );

      token = strtok_r(NULL, s, &saveptr);
   }

   return(0);
}

A: Take a look at the strotk function, i think it's what you'r looking for.


text:
Q: Plotting Cross section in a phase diagram α2 = 1/2 (κ2 + 2 η2) + I (δ0 - β2 I2);
α1 = 1/2 (κ1 - 2 η1) + I (δ0 - β1 I1);

I would like to plot a cross-section for different values of δ2 but could get the output, any comments would be greatly appreciated.
I2 = x*10^12;
I1 = y*10^12;

P = (h ν2a)/(2 κ2a) I2 Abs[α2]^2;

ListPlot[{Table[{(P /. δ2 -> 4 π)*10^12, I2/10^10}, {x, 0,
    0.1, 0.0001}],
  Table[{(P /. δ2 -> 0)*10^12, I2/10^10}, {x, 0, 0.1, 0.0001}],
   Table[{(P /. δ2 -> 6 π)*10^12, I2/10^10}, {x, 0, 0.1,
    0.0001}]}, PlotRange -> {{0, 0.042}, {0, 1.8}}, Frame -> True,
 FrameLabel -> {"P(pW)",
   "\!\(\*SubscriptBox[\(I\), \
\(2\)]\)\[Cross]\!\(\*SuperscriptBox[\(10\), \(12\)]\)"},
 FrameStyle -> Directive[19, Black], Joined -> True,
 AspectRatio -> 1.3, ImageSize -> 250,
 PlotStyle -> {{Black, Thick, DotDashed}, {Blue, Thick, Dashed}, {Red,
     Thick}}, ImageSize -> 300]

A: If you look at  P you will see it is a list instead of a scalar.  At some point in its definition something has returned as a list and this has made its way through P.
You could First P, First@P /. δ2 -> 4 π , wherever it is used. This will get you the ListPlot; you could just Plot it instead of all the Table bits.  However, you should probably work through its definition to find out how it became a list as there could be other issues as a result.
Hope this helps.

A: Other way to fix that is:
 ListPlot[{
 Map[Flatten, Table[{(P /. \[Delta]2 -> 4 \[Pi])*10^12, I2/10^10}, {x, 0, 0.1, 0.0001}]],
 Map[Flatten, Table[{(P /. \[Delta]2 -> 0)*10^12, I2/10^10}, {x, 0, 0.1, 0.0001}]],
 Map[Flatten, Table[{(P /. \[Delta]2 -> 6 \[Pi])*10^12, I2/10^10}, {x, 0, 0.1, 0.0001}]]},
 PlotRange -> {{0, 0.042}, {0, 1.8}},
 Frame -> True, FrameLabel -> {"P(pW)", "\!\(\*SubscriptBox[\(I\), \
\(2\)]\)\[Cross]\!\(\*SuperscriptBox[\(10\), \(12\)]\)"},
 FrameStyle -> Directive[19, Black], Joined -> True, AspectRatio -> 1.3, ImageSize -> 250,
 PlotStyle -> {{Black, Thick, DotDashed}, {Blue, Thick, Dashed}, {Red, Thick}}, ImageSize -> 300]


text:
Q: How to use tabs as horizontal indentation and spaces as vertical indentation in Vim? Is there a way to configure Vim so it combines tabs to use as horizontal indentation character, and spaces as vertical indentation character (for instance, when continuing long lines, giving out arguments to methods)? Basically, something like this (i have marked tabs with > and spaces with dot):
class xyz {
>   function abc()
>   {
>   >   $var1 = "this is a multi-"
>   >   ......+ "line string which spans "
>   >   ......+ "several lines";
>   }
}

Ideas or suggestions?
Edit: I'm not looking how to use spaces instead of tabs, I'd like to combine them in a way I described above.

A: There is a "Smart Tabs" script that may be what you're looking for. It describes itself as using tabs for indentation and spaces for alignment.

A: Add the below lines to $HOME/.vimrc
set tabstop=4
set shiftwidth=4
set expandtab

This should set a tab to 4 spaces.
Here is the VIM Wiki on this: http://vim.wikia.com/wiki/Converting_tabs_to_spaces


text:
Q: Why unbind Service onDestroy? I've seen it mentioned in multiple sources, that if an Activity binds a Service, it should unbind it onDestroy. Why? Since the Activity is destroyed, it seems like the service will be unbound anyway. If it was "started" - it doesn't matter anyway. And if it was auto-started by the activity - it will close anyway if no others bound it.
So why unbind it?

A: Activities need to handle configuration changes, such as when the screen is rotated, or the user changes locales, or the device enters night mode.
The default behavior of the foreground activity, when a configuration change occurs, is for it to be destroyed and recreated.
As a result, calling bindService() on an Activity is not a good idea. We want the binding to remain intact across the configuration change. Otherwise, our service will get destroyed and recreated, along with the activity (assuming that the activity has the one-and-only binding and nothing else started the service).
So, the recommended pattern is to call bindService() on the Application singleton. Then, you can pass your ServiceConnection from the old activity instance to the new activity instance. Retained fragments work great for this, as you can then call unbindService() in onDestroy() of the fragment, so that when the activity is "permanently" destroyed (e.g., user presses BACK, you call finish()), your binding can be released.

With all that as background, on to your specific concern.
First, you assume that a destroyed activity automatically unbinds from any services that it bound to via bindService() called on that Activity. It's possible that this happens, though I do not recall that being documented behavior, and it's the sort of thing that developers should not rely upon.
More importantly, in most cases, calling bindService() on the Activity is not the right approach. Otherwise, you get into the problems that I outlined above.
But, following the call-bindService()-on-the-Application pattern, I would not expect there ever to be some sort of automatic unbinding, because the Application singleton is never destroyed. So, if you fail to call unbindService() somewhere (e.g., in onDestroy() of the retained fragment), you will leak your service.


text:
Q: Bot framework v4: error moving into next step I want my bot to ask the user for a location. And when the user answer "Near me" the bot should continue to the next step and when the user answer "Somewhere else" the bot should ask the user for the specific location before moving to the next step. How ever I'm having an error in the bot emulator. When the user chooses "Near me" or "Somewhere else" it would not send.
namespace FinancialPlannerBot.Dialogs.RealEstate
{
public class MainRealEstateDialog : WaterfallDialog
{
    public MainRealEstateDialog(string dialogId, IEnumerable<WaterfallStep> steps = null) : base(dialogId, steps)
    {
        AddStep(async (stepContext, cancellationToken) =>
        {
            return await stepContext.PromptAsync("choicePrompt",
               new PromptOptions
               {
                   Prompt = stepContext.Context.Activity.CreateReply("Would you like to buy or rent?"),
                   Choices = new[] {new Choice {Value = "Buy"},
                                    new Choice {Value = "Rent"}
                   }.ToList()
               });
        });

        AddStep(async (stepContext, cancellationToken) =>
        {

            var buyOrRent = stepContext.Result as FoundChoice;
            var state = await (stepContext.Context.TurnState["FPBotAccessors"] as FPBotAccessors).FPBotStateAccessor.GetAsync(stepContext.Context);
            state.BuyOrRent = buyOrRent.Value;

            return await stepContext.PromptAsync("choicePrompt",
               new PromptOptions
               {
                   Prompt = stepContext.Context.Activity.CreateReply("What kind of real estate do you want?"),
                   Choices = new[] {new Choice {Value = "Type 1"},
                                    new Choice {Value = "Type 2"},
                                    new Choice {Value = "Type 3"}
                   }.ToList()
               });

        });

        AddStep(async (stepContext, cancellationToken) =>
        {
            var realEstateType = stepContext.Result as FoundChoice;
            var state = await (stepContext.Context.TurnState["FPBotAccessors"] as FPBotAccessors).FPBotStateAccessor.GetAsync(stepContext.Context);
            state.RealEstateType = realEstateType.Value;

            return await stepContext.PromptAsync("choicePrompt",
               new PromptOptions
               {
                   Prompt = stepContext.Context.Activity.CreateReply("Which location are you considering?"),
                   Choices = new[] {new Choice {Value = "Near me"},
                                    new Choice {Value = "Somewhere else"}
                   }.ToList()
               });
        });

        AddStep(async (stepContext, cancellationToken) => //ERROR
        {
            var nearOrSomewhereElse = stepContext.Result as FoundChoice;
            var state = await (stepContext.Context.TurnState["FPBotAccessors"] as FPBotAccessors).FPBotStateAccessor.GetAsync(stepContext.Context);
            state.NearOrSomewhereElse = nearOrSomewhereElse.Value;

            if (state.NearOrSomewhereElse == "Somewhere else")
            {
                await stepContext.PromptAsync("textPrompt",
                new PromptOptions
                {
                    Prompt = stepContext.Context.Activity.CreateReply("Which location are you considering?")
                });
            }

            return await stepContext.ContinueDialogAsync();
        });

        AddStep(async (stepContext, cancellationToken) =>
        {
            var nearOrSomewhereElse = stepContext.Result as FoundChoice;
            var state = await (stepContext.Context.TurnState["FPBotAccessors"] as FPBotAccessors).FPBotStateAccessor.GetAsync(stepContext.Context);
            state.NearOrSomewhereElse = nearOrSomewhereElse.Value;

            return await stepContext.PromptAsync("choicePrompt",
             new PromptOptions
                 {
                   Prompt = stepContext.Context.Activity.CreateReply($"Please indicate the size of {state.RealEstateType}"),
                   Choices = new[] {new Choice {Value = "Size 1"},
                                    new Choice {Value = "Size 2"},
                                    new Choice {Value = "Size 3"}
                   }.ToList()
             });

        });

    }

    public static string Id = "MainRealEstateDialog";
    public static MainRealEstateDialog Instance { get; }= new MainRealEstateDialog(Id);
}

}

A: Well, there's a couple problems here...
First, you'd need an if/else in the step that is dealing with the "Near me" vs "Somewhere else" because you only want to prompt in the case of the "Somewhere else", right?
Second, because that step is now going to return different results depending on the path taken, that next step needs to be ready to process to different incoming results. Right now that last step is bugged because it currently assumes it's going to receive a FoundChoice, but it won't. It would either be receiving the text from the textPrompt in the case of the "Somewhere else" path or it would receive nothing because of the manual ContinueDialog call. I'm actually not even sure that works, but, even if it does, it would be more "correct" to use the WaterfallStepContext::NextAsync() API to advance the waterfall instead. Take a look at the following changes to the third step for starters:
    AddStep(async (stepContext, cancellationToken) => //ERROR
    {
        var nearOrSomewhereElse = stepContext.Result as FoundChoice;
        var state = await (stepContext.Context.TurnState["FPBotAccessors"] as FPBotAccessors).FPBotStateAccessor.GetAsync(stepContext.Context);
        state.NearOrSomewhereElse = nearOrSomewhereElse.Value;

        if (state.NearOrSomewhereElse == "Somewhere else")
        {
            await stepContext.PromptAsync("textPrompt",
            new PromptOptions
            {
                Prompt = stepContext.Context.Activity.CreateReply("Which location are you considering?")
            });
        }
        else
        {
          await stepContext.NextAsync();
        }
    });

Ok, now here would be the changes you'd need to make to the following step:
        AddStep(async (stepContext, cancellationToken) =>
        {
            var nearOrSomewhereElse = await (stepContext.Context.TurnState["FPBotAccessors"] as FPBotAccessors).FPBotStateAccessor.GetAsync(stepContext.Context).NearOrSomewhereElse;

            // If it's somewhere else, then this step need to get the text value the person was prompted for in the previous step
            if(nearOrSomewhereElse.Value == "Somewhere else")
            {
               // Get the result of the text prompt from the previous step
               var whereExactly = stepContext.Result as string;

               // TODO: store the value in your state so you can reference it later in the final search
            }

            return await stepContext.PromptAsync("choicePrompt",
             new PromptOptions
                 {
                   Prompt = stepContext.Context.Activity.CreateReply($"Please indicate the size of {state.RealEstateType}"),
                   Choices = new[] {new Choice {Value = "Size 1"},
                                    new Choice {Value = "Size 2"},
                                    new Choice {Value = "Size 3"}
                   }.ToList()
             });

        });

I should also point out that there are MUCH cleaner/simpler ways to do this without using the state accessors at all. You should really be storing intermediate values that you collect during the flow of your waterfall into the WaterfallStepContext::Values property instead.


text:
Q: Remover ultimo caractere de uma string, quando o caractere for um espaço em branco Boa tarde.
Estou programando em java e quero pegar as inicias de um nome, no caso:
"Jonas Barros Santos"
Tem que aparecer : JS
O código que uso, faz isso, porém se a pessoa colocar o nome com espaço no final, meu código não funciona, dando uma exception.
"Jonas Barros Santos "
Queria uma ajuda para resolver esse problema.
 public static void main(String[] args) {
        // TODO code application logic here
        String nome = "Jonas Barros Santos ";
        String nomeAbrev = null;
        int posicaoUltimoEspaco = nome.lastIndexOf(" ");
        String primeiraLetraUltimoNome = "";
        if (posicaoUltimoEspaco > 0) {
            primeiraLetraUltimoNome = nome.substring(posicaoUltimoEspaco + 1, posicaoUltimoEspaco + 2);
        }
        String primeiraLetra = nome.substring(0, 1);
        nomeAbrev = primeiraLetra + primeiraLetraUltimoNome;
        System.out.println(nomeAbrev);
    }

A: Usa a função trim(), por exemplo, nome.trim() tira o espaço de inicio e final. https://www.tutorialspoint.com/java/java_string_trim.htm

A: Pode utilizar método o trim() que tira espaço apenas do início e fim da string.

A: É simples Amanda, como o @Marconi comentou, aplicando um trim na parte da direita da tua string, é eliminado o espaço em branco independente de quantos tiver, logo tu pode utilizar o teu código que não irá acusar error por acessar um índice inexistente na string. Fica assim:
String nome = "Jonas Barros Santos     ";
String nomeAbrev = "";
nomeAbrev = nome.replaceAll("\\s+$","");
int posicaoUltimoEspaco = nomeAbrev.lastIndexOf(" ");
String primeiraLetraUltimoNome = "";
if (posicaoUltimoEspaco > 0) {
      primeiraLetraUltimoNome = nomeAbrev.substring(posicaoUltimoEspaco + 1, posicaoUltimoEspaco + 2);
}
String primeiraLetra = nomeAbrev.substring(0, 1);
nomeAbrev = primeiraLetra + primeiraLetraUltimoNome;
System.out.println(nomeAbrev);


text:
Q: Python: changing shape of list of lists Using python, I'd like to convert this list of lists:
list_3_5 = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]

To a different shape -- a list of 6 lists, where the first 3 new lists have the first three values from the each of the 3 main lists in list_3_5, and then the last 3 new lists have the remaining values from list_3_5:
[[1,2,3],[6,7,8],[11,12,13],[4,5],[9,10],[14,15]]

Any help appreciated.
Updates:
For longer lists, this:
list2 = [list(range(1, 34)), list(range(34, 67)), list(range(67, 100))]

list2b = [list2[i][:5] for i in range(0, len(list2))] + [
    list2[i][5:] for i in range(0, len(list2))
]

or this
list2 = [list(range(1, 34)), list(range(34, 67)), list(range(67, 100))]
list2b = list(range(2 * len(list2)))

for key, element in enumerate(list2):
    list2b[key] = element[:5]
    list2b[key + len(list2)] = element[5:]

Gives this (modifies my original list of 3 lists each with 33 elements, into a list of 6 lists, the first three lists each having 5 elements, and the last three each having 28) :
[[1, 2, 3, 4, 5],
 [34, 35, 36, 37, 38],
 [67, 68, 69, 70, 71],
 [6, 7, 8, ..., 33],
 [39, 40, 41, ..., 66],
 [72, 73, 74, ... 99]]

But what I would like is this (for this example, a list of 19 lists with 5 elements each, and 1 list at the end with remaining 4 elements):
[[1, 2, 3, 4, 5],
 [6, 7, 8, 9, 10],
 [11, 12, 13, 14, 15],
 [16, 17, 18, 19, 20],
 ....
 ....
 [91, 92, 93, 94, 95],
 [96, 97, 98, 99]]

seems like this, but I can't quite see how to modify for my case: reshape an irregular list in python

A: Here is a solution with double for loops that will work for an arbitrary length list:
list_3_5 = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]
newlist = []

for element in list_3_5:
    newlist.append(element[:3])

for element in list_3_5:
    newlist.append(element[3:])

newlist

Out: [[1, 2, 3], [6, 7, 8], [11, 12, 13], [4, 5], [9, 10], [14, 15]]

But wait! There is more:
list_3_5 = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]
newlist = list(range(2*len(list_3_5)))

for key, element in enumerate(list_3_5):
    newlist[key] = element[:3]
    newlist[key+len(list_3_5)] = element[3:]

newlist
[[1, 2, 3], [6, 7, 8], [11, 12, 13], [4, 5], [9, 10], [14, 15]]

Below part answers the updated section of the question:
biglist = []
for i in list2:
    biglist = biglist + i
#Here we put all small lists in the given list into a big list
print(biglist)

#construct an empty list to save the result as we go:
newlist = []

#add sections of 5 to newlist
while len(biglist) >= 5:
    newlist.append(biglist[:5])
    biglist = biglist[5:]

#add the remaining part of biglist to the newlist:
newlist.append(biglist)
print(newlist)

Output is:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25], [26, 27, 28, 29, 30], [31, 32, 33, 34, 35], [36, 37, 38, 39, 40], [41, 42, 43, 44, 45], [46, 47, 48, 49, 50], [51, 52, 53, 54, 55], [56, 57, 58, 59, 60], [61, 62, 63, 64, 65], [66, 67, 68, 69, 70], [71, 72, 73, 74, 75], [76, 77, 78, 79, 80], [81, 82, 83, 84, 85], [86, 87, 88, 89, 90], [91, 92, 93, 94, 95], [96, 97, 98, 99]]

A: If you want to have a general code to separate first three elements, try this:
new_list=[list_3_5[i][:3] for i in range(0,len(list_3_5))]+[ list_3_5[i][3:] for i in range(0,len(list_3_5))]

A: Try this:
[list_3_5[0][:3],list_3_5[1][:3], list_3_5[2][:3], list_3_5[0][3:],list_3_5[1][3:], list_3_5[2][3:]]

Output:
[[1, 2, 3], [6, 7, 8], [11, 12, 13], [4, 5], [9, 10], [14, 15]]


text:
Q: How can remove next cell in table using JavaScript? I have the code below:

   function colspan(){
     var x = document.getElementById("Cell2");
     x.setAttribute("colspan", 2);
     x.next().remove();
     }

     Cell 1
     Cell 2
     Cell 3

     Cell 4
     Cell 5
     Cell 6

     Cell 7
     Cell 8
     Cell 9

     <input type="button" onclick="colspan();" value="Change"/>

I would like to delete the next cell of the current cell I have called. When the Cell 2 is colspan, the Cell 3 should be removed, but I use .next().remove() is not working. Anyone can help?

A: This is something you could do.

function colspan() {
  var ele = document.getElementById("Cell2");
  ele.setAttribute("colspan", 2);
  if (ele.nextElementSibling) {
    ele.nextElementSibling.remove();
  }
}

    Cell 1
    Cell 2
    Cell 3

    Cell 4
    Cell 5
    Cell 6

    Cell 7
    Cell 8
    Cell 9

<input type="button" onclick="colspan();" value="Change" />

A: I think you are mixing jQuery and pure JS..
You should use nextSibling() & removeChild(element) on parent.
have a look here: Remove element by id

A: The last remove() function  was on jquery function. so use jquery library link and call the id with jquery type.

function colspan(){
     var x = document.getElementById("Cell2");
     x.setAttribute("colspan", 2);
     $('#Cell2').next().remove();
     }

     Cell 1
     Cell 2
     Cell 3

     Cell 4
     Cell 5
     Cell 6

     Cell 7
     Cell 8
     Cell 9

     <input type="button" onclick="colspan();" value="Change"/>


text:
Q: Hadoop services turn off on one or more data nodes when running a Hive query All the sudden, and after being working fine, now when I run a simple hive query like:
select MAX(temp) from weather where USAF=400010;

The Hadoop job information shows:
Hadoop job information for Stage-1: number of mappers: 11; number of reducers: 0
2016-12-10 04:10:09,211 Stage-1 map = 0%,  reduce = 0%
2016-12-10 04:10:31,983 Stage-1 map = 14%,  reduce = 0%, Cumulative CPU 37.03 sec
2016-12-10 04:10:33,049 Stage-1 map = 24%,  reduce = 0%, Cumulative CPU 41.24 sec
2016-12-10 04:20:44,396 Stage-1 map = 0%,  reduce = 0%
2016-12-10 04:21:44,883 Stage-1 map = 0%,  reduce = 0%
2016-12-10 04:22:45,197 Stage-1 map = 0%,  reduce = 0%
2016-12-10 04:23:45,488 Stage-1 map = 0%,  reduce = 0%
2016-12-10 04:24:45,844 Stage-1 map = 0%,  reduce = 0%
.
.
.

And it keeps on map = 0%.
More complex queries were finishing successfully.
I have noticed that, for no reason to me, Hadoop services on one (or more) node out of the three data nodes I have, stops running when "map = 0%" starts to appear. So if I jps on those data nodes I get nothing.
What could be the reason? or at least, where can I find the log for that?

A: Can you check in the application logs. By default it can be found in http://your _name_node_url:8088/cluster. Click on the specific application and get the logs.
There might be the case that particular node is failing . can be due to various reasons like (memory , network, timestamp etc etc ).


text:
Q: Oauth token exchange returning a 400 error in Cognito My auth model is set up so that the callback hits an endpoint on my site and then it parses out the code param and does the token exchange. This is what I have so far
   class TokenExchange extends React.Component <any, any> {
    constructor(props: any) {
        super(props);
    }

    componentDidMount() {
        const parsed = queryString.parse(location.hash);
        const code = parsed["code"]
        console.log(code);
        const postData = {
            "grant_type": 'authorization_code',
            "code": code,
            "client_id": OAUTH_CLIENT_ID,
            "redirect_uri": OAUTH_REDIRECT_URI
        }
        console.log(postData)
        const credential = btoa(`${OAUTH_CLIENT_ID}:${OAUTH_CLIENT_SECRET}`)
        const headers = {
            "Accept": "application/json",
            "Content-Type": "application/x-www-form-urlencoded",
            "authorizationMethod": "body",
            "Authorization": `Basic ${credential}`
        }
        console.log(headers)

        const requestOptions = {
            method: 'POST',
            headers: headers,
            body: JSON.stringify(postData)
        };
        fetch(OAUTH_TOKEN_EXCHANGE_URL, requestOptions)
            .then(response => response.json())
            .then((result) => {
              console.log(result)
            })
    }
}

The problem I'm running into is that my code's running into an HTTP 400 error and it's not giving me much information to go by other than invalid request.
This is what the copied curl request looks like
curl 'https://MYAPP.us-west-2.amazoncognito.com/oauth2/token' \
  -H 'authority: MYAPP.us-west-2.amazoncognito.com' \
  -H 'pragma: no-cache' \
  -H 'cache-control: no-cache' \
  -H 'sec-ch-ua: " Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"' \
  -H 'accept: application/json' \
  -H 'authorizationmethod: body' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'authorization: Basic BASE64ENCODEDSTUFFHERE' \
  -H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36' \
  -H 'content-type: application/x-www-form-urlencoded' \
  -H 'origin: http://localhost:5000' \
  -H 'sec-fetch-site: cross-site' \
  -H 'sec-fetch-mode: cors' \
  -H 'sec-fetch-dest: empty' \
  -H 'referer: http://localhost:5000/' \
  -H 'accept-language: en-GB,en;q=0.9' \
  --data-raw '{"grant_type":"authorization_code","code":"SOMECODE","client_id":"SOMEID","redirect_uri":"https://SOMEURI"}' \
  --compressed

Could anyone spot what I may be doing wrong?

A: The data should be sent form URL encoded and not as JSON so update your code / script:
STEP 1
Use this type of syntax to send the data and get a working solution:
fetch('https://example.com/login', {
    method: 'POST',
    body: new URLSearchParams({
        'field1': 'value1',
        'field2': 'value2'
    })
});

Or in curl you can do this:
--data-urlencode "field1=value1" \
--data-urlencode "field2=value2"

STEP 2
An SPA should not use a client secret since it cannot store it securely. Aim to update your requests to use Proof Key for Code Exchange (PKCE) as recommended for SPAs. Steps 4 and 8 in my blog post show what this should look like, and a sample of mine runs in Cognito like this.


text:
Q: Context menu shows up completely black I followed the instructions and examples on Android website to create a context menu but mine shows up completely black and i cannot change any options in it ; anyone out there had the same experience and can help me solve this issue.
FWIW, here are my class .java and the menu .xml files
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item android:id="@+id/red"
              android:title="@string/red"
              android:checked="true" />
        <item android:id="@+id/blue"
              android:title="@string/blue" />
        <item android:id="@+id/green"
              android:title="@string/green" />
        <item android:id="@+id/yellow"
              android:title="@string/yellow" />
        <item android:id="@+id/black"
              android:title="@string/black" />
        <item android:id="@+id/white"
              android:title="@string/white" />
        <item android:id="@+id/orange"
              android:title="@string/orange" />
    </group>
</menu>

package com.MyProject;

import android.view.MenuInflater;
import android.view.MenuItem;
import android.app.Activity;
import android.view.ContextMenu;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;

public class ColorsActivity extends Activity {

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
          super.onCreateContextMenu(menu, v, menuInfo);
          MenuInflater inflater = getMenuInflater();
          inflater.inflate(R.menu.context_menu, menu);
          registerForContextMenu(v);

    }
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.red:
                if (item.isChecked()) item.setChecked(false);
                else item.setChecked(true);
                return true;
            case R.id.blue:
                if (item.isChecked()) item.setChecked(false);
                else item.setChecked(true);
                return true;
            case R.id.green:
                if (item.isChecked()) item.setChecked(false);
                else item.setChecked(true);
                return true;
            case R.id.yellow:
                if (item.isChecked()) item.setChecked(false);
                else item.setChecked(true);
                return true;
            case R.id.black:
                if (item.isChecked()) item.setChecked(false);
                else item.setChecked(true);
                return true;
            case R.id.white:
                if (item.isChecked()) item.setChecked(false);
                else item.setChecked(true);
                return true;
            case R.id.orange:
                if (item.isChecked()) item.setChecked(false);
                else item.setChecked(true);
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }
}

A: Activity.registerForContextMenu (View) registers the context menu with the OS so that when the menu button is pressed and the given view is in the foreground, the callback to onCreateContextMenu is made. What you have done is register the view within the callback, making it fundamentally unreachable in your code because the view would have to be already registered in order to reach the registration you have here. registerForContextMenu should be called in one of your lifecycle startup methods, probably onResume.


text:
Q: How to write two case statements with in the single case in sql I have tried a lot. But its showing the error. Any 1 please help me.
My Query (Please see in Image)
enter image description here

A: You cannot nest case statements, each one needs to stand alone. And you cannot give them different names.
You can try to trick with Coalesce, like
SELECT COALESCE
  (
    CASE WHEN condition1 THEN calculation1 ELSE calcelse1 END,
    CASE WHEN condition2 THEN calculation2 ELSE calcelse2 END,
    etc...
  )

but I think it wont solve your problem directly.
IMHO you need to enhanced each of your case statements. Or you are going to implement this with a pivot statement. And on first sight, you need to think about redesigning your data model ...


text:
Q: Error while building unity project(having firebase) for android I am using firebase database(for android) for unity. However, while building for android platform, I am getting this error:

IOException: Failed to Move File / Directory from 'Temp/StagingArea\android-libraries\firebase-analytics-impl-license-11.8.0\classes.jar' to 'Temp/StagingArea\android-libraries\firebase-analytics-impl-license-11.8.0\libs\classes.jar'.

I am using Unity's default build system. I looked up online for a solution - It said to add classpath 'com.google.gms:google-services:3.1.0' to project's build.gradle and apply plugin: 'com.google.gms.google-services' to app-level build.gradle.
But I don't have any gradle files in my project directory.
Please suggest ways how I can solve it.

A: I had the same problem, the only solution I found is :

*

*delete all the firebase plugins

*import all the modules again, starting with analytics (this plugin has some problems)

And then... Tada, it works. It's kind of magical, but can't say why it worked...

A: I ran into the same issue. My solution was:

*

*Exit Unity

*Navigate to Assets\Plugins\Android in your Unity project folder.

*Delete every folder, every .jar and every .aar that starts with com.google or com.android

*Delete all .meta files

Voilá


text:
Q: How can a superclass in Dart access its own methods if they have been overridden? Here is a simplified version of a problem I have.
class A {
  void a1() => xxx();
  void xxx() => print('A xxx');
}

class B extends A {
  void b1() => super.xxx();
  void b2() => xxx();
  void xxx() => print('B xxx');
}

void main() {
  B().a1();
  B().b1();
  B().b2();
}

Here is the output.
B xxx
A xxx
B xxx
I need class A to be able to access xxx in class A even if xxx has been overridden. How do I achieve this? Class B can access it using super but I can't find a way for class A to access its own method.


text:
Q: How do I find the left of the smallest number in a column So the cell will say bamboo because the lowest amount in the column is 662
https://i.stack.imgur.com/ELbpE.jpg
I know how to find the lowest amount with =SMALL(B2:B17, 2)
and how to find the left of the cell with =INDIRECT("RC[-1]",FALSE)
But I can't use them together

A: try:
=FILTER(A:A; B:B=MIN(B:B))


text:
Q: Python: Create Dictionary using list of list, list of tuples and list I have a list l1 as shown below:
l1 = [[(1,"INC1"), (1, "INC2")],[(3, "INC4"),(4, "INC6")]]

I have a list names as shown below:
names = ['John', 'Marcia']

I have another list label_issue_list as shown below:
label_issue_list = [["Problem1","Problem1"],["Problem3","Problem4"]]

The indices of all the three lists are connected as shown in the below output.
I'm trying to use all these three lists and get a dictionary output which would like the below:
{
"John" : {
            "Problem1" : 2,
          "tick_info" : {"1": ["INC1", "INC2"]}

            },
"Marcia" : {
            "Problem3" : 1,
            "Problem4" : 1,
            "tick_info" : {"3":["INC4"], "4":["INC6"]}
           }
}

I have tried the below code but this doesn't seem to work:
clust_stack = {}
for i in range(len(l1)):
      fq= defaultdict( list )
      for n,v in l1[i]:
           fq[str(n)].append(v)
      for name_, data in zip(names, label_issue_list)[i]:
           clust_stack[name_] = Counter(map(str,data))
           clust_stack[name_]["tick_info"] = {}
           clust_stack[name_]["tick_info"] = dict(fq)

I get the below error in the for name_, data in zip(names, label_issue_list)[i]: line:
ValueError: too many values to unpack

What do I need to do to get my desired output?

A: Start with zipping all 3 lists:
clust_stack = {}
for name, data, fq in zip(names, label_issue_list, l1):
    clust_stack[name] = dict(Counter(data))  # turn back into regular dictionary
    tick_info = clust_stack[name]['tick_info'] = {}
    for num, tick in fq:
        tick_info.setdefault(num, []).append(tick)

Using a Counter to count the information in each l1 element is excellent, but you do need to turn that result back to a regular dictionary so you can add other keys to it.
You can then add the tick_info key to that, collecting the information in those lists in list values per key.
Demo:
>>> from collections import Counter
>>> from pprint import pprint
>>> l1 = [[(1,"INC1"), (1, "INC2")],[(3, "INC4"),(4, "INC6")]]
>>> names = ['John', 'Marcia']
>>> label_issue_list = [["Problem1","Problem1"],["Problem3","Problem4"]]
>>> clust_stack = {}
>>> for name, data, fq in zip(names, label_issue_list, l1):
...     clust_stack[name] = dict(Counter(data))  # turn back into regular dictionary
...     tick_info = clust_stack[name]['tick_info'] = {}
...     for num, tick in fq:
...         tick_info.setdefault(num, []).append(tick)
...
>>> pprint(clust_stack)
{'John': {'Problem1': 2, 'tick_info': {1: ['INC1', 'INC2']}},
 'Marcia': {'Problem3': 1,
            'Problem4': 1,
            'tick_info': {3: ['INC4'], 4: ['INC6']}}}


text:
Q: how to display encrypted image as an image without decrypting it #encrypting an image using AES
import binascii
from Crypto.Cipher import AES

def pad(s):
  return s + b"\0" * (AES.block_size - len(s) % AES.block_size)

filename = 'path to input_image.jpg'
with open(filename, 'rb') as f:
  content = f.read()

#converting the jpg to hex, trimming whitespaces and padding.
content = binascii.hexlify(content)
binascii.a2b_hex(content.replace(' ', ''))
content = pad(content)

#16 byte key and IV
#thank you stackoverflow.com
obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
ciphertext = obj.encrypt(content)

#is it right to try and convert the garbled text to hex?
ciphertext = binascii.hexlify(ciphertext)
print ciphertext

#decryption

obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
plaintext = obj2.decrypt(ciphertext)
#content =  content.encode('utf-8')
print plaintext
#the plaintext here matches the original hex input file as it should

with open('path to - AESimageDecrypted.txt', 'wb') as g:
   g.write(plaintext)

My question is two fold,
1) how would i go about converting the encrypted file (which is garbled before hexlify) which is basically a text file of hex strings, back into an image?
i'd like the output to be viewable as a jpg on any viewer.
I've tried a few things out , came across Pillow, except i can't seem to grasp if it can do what i want.
Any help would be appreciated thanks.
PS: i want to try this with other ciphers too. so i think it'd be helpful if anyone can help clear out if this understanding is right:
jpg -> convert to binary/hex -> encrypt -> garbled output -> convert to bin/hex -> convert to jpg
2) is the above possible? and should they be converted to hex or bin?

A: The question here is how to display encrypted image as an image without decrypting it.
The encrypted contents are not an image and cannot be unambiguously represented as an image. The best that can be done is to treat it as a bitmap, i.e. each binary value represents the intensity of some color at some coordinate.
It seems logical to treat the data as 3 bytes per pixel: RGB RGB RGB...
Images are 2D and encrypted data is just a list of bytes. Again, several options are valid. Let's say it is a square image (NxN pixels).
To create the image, I would use PIL / Pillow:
from PIL import Image

# calculate sizes
num_bytes = len(cyphertext)
num_pixels = int((num_bytes+2)/3)                     # 3 bytes per pixel
W = H = int(math.ceil(num_pixels ** 0.5))             # W=H, such that everything fits in

# fill the image with zeros, because probably len(imagedata) < needed W*H*3
imagedata = cyphertext + '\0' * (W*H*3 - len(cyphertext))

image = Image.fromstring('RGB', (W, H), imagedata)         # create image
image.save('C:\\Temp\\image.bmp')                          # save to a file

BTW, this can be done with absolutely any string of bytes, not just encrypted images.


text:
Q: Existence of Killing field Definition of Killing field as picutre below, and acoording to 2.2.20, the existence of Killing field is equal to the solvability of
$$
g_{ij,k}X^k+g_{kj}\frac{\partial X^k}{\partial x^j}+ g_{ik}\frac{\partial X^k}{\partial x^j} =0
$$
I don't know PDE, so I don't know whether the 1-order PDEs has solution for any given smooth Riemannian manifold $(M,g)$. Whether it must has solution ?

A: Not all Riemannian manifolds $(M,g)$ admit Killing fields.  For example:
Lemma: Let $(M,g)$ be a Riemannian manifold, let $X$ be a Killing field on $(M,g)$, and let $f_X = \frac{1}{2}|X|^2$.  Then
$$\Delta f_X = |\nabla X|^2 - \text{Ric}(X,X).$$
Here, $\Delta$ is the Laplacian and $\nabla$ is the Levi-Civita connection of $g$.
Theorem (Bochner, 1946): Let $(M, g)$ be a compact, oriented Riemannian manifold without boundary.  If $\text{Ric} < 0$, then there are no (non-trivial) Killing fields on $M$.
Proof: Let $X$ be a Killing field on $(M,g)$, and let $f_X = \frac{1}{2}|X|^2$ as above.  Let $\text{vol}_g$ be the volume form on $(M,g)$.  Observe that
$$\Delta f_X \,\text{vol}_g = \text{div}(\text{grad } f_X)\,\text{vol}_g = d( (\text{grad}\,f_X) \,\lrcorner\,\text{vol}_g)$$
is an exact form.  By Stokes' Theorem and the Lemma above:
$$0 = \int_M \Delta f_X\,\text{vol}_g = \int_M (|\nabla X|^2 - \text{Ric}(X,X))\,\text{vol}_g,$$
so
$$\int_M \text{Ric}(X,X)\,\text{vol}_g = \int_M |\nabla X|^2\,\text{vol}_g \geq 0.$$
Since $\text{Ric}(X,X) \leq 0$, this implies $\text{Ric}(X,X) = 0$, so $X = 0$. $\lozenge$


text:
Q: Android Button in Gridlayout don't have same margin top I got a GridLayout, and there will be two or more buttons in the layout, and all the buttons must with same width.
My problem is that when the buttons having different line number of text, the marginTop of button will different too.
How can I fix this?
Thanks.
<GridLayout
    android:id="@+id/grid_buddies"
    android:columnCount="4"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <Button
        android:layout_width="60dp"
        android:layout_height="match_parent"
        android:text="TEST"/>
    <Button
        android:layout_width="60dp"
        android:layout_height="wrap_content"
        android:text="TESTDDFF"/>
</GridLayout>

Here is the picture:

A: Use android:layout_gravity="fill_vertical" attribute in your Button with text TEST
<GridLayout
    android:id="@+id/grid_buddies"
    android:columnCount="4"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <Button
       android:layout_width="60dp"
       android:layout_height="match_parent"
       android:text="TEST"
       android:layout_gravity="fill_vertical"/>
    <Button
       android:layout_width="60dp"
       android:layout_height="wrap_content"
       android:text="TESTDDFF"/>
</GridLayout>


text:
Q: How to add a drop down list in Excel I need to add a drop down list of Profit margin figures (namely 8.5%, 10% and 12.5%) against each inventory item as shown below but I can't find out how to do it
Code    Product            Cost         Margin        GST     Customer Price

2345td  Bicycle Boy       $125.50   <drop down here>

Thanks

A: If I understood you correctly, you need a drop-down list with 3 options
If so, the functionality you're looking for is data validation
Directions for implementation in the following link are much better than anything I'd type here.
https://support.office.com/en-us/article/create-a-dropdown-list-7693307a-59ef-400a-b769-c5402dce407b


text:
Q: Python: how to act on re's matched string The following
>>> re.sub(r'(\d+)', r'\1' * 2, 'test line 123')

gives
'test line 123123'

is there a way to make it give
'test line 246'

?
float() coercion doesn't work:
>>> re.sub(r'(\d+)', float(r'\1') * 2, 'test line 123')
could not convert string to float: \1

nor do eval or exec.

A: The second argument to re.sub() can also be a callable, which lets you do:
re.sub(r'(\d+)', lambda match:'%d' % (int(match.group(1))*2), 'test line 123')

BTW, there really is no reason to use float over int, as your regex does not include periods and will always be a non-negative integer

A: The trick is to supply a function as the repl argument to re.sub():
In [7]: re.sub(r'(\d+)', lambda m:'%.0f'%(float(m.group(1))*2), 'test line 123')
Out[7]: 'test line 246'

Each match is converted to float, doubled, and then converted to string using the appropriate format.
This can be simplified a little bit if the number is integer, but your question specifically mentions float, so that's what I've used.


text:
Q: JFileChooser hangs sometimes I am running into the problem of the "hanging JFileChooser" as described in the following threads:
http://forums.sun.com/thread.jspa?threadID=5309960
http://forums.sun.com/thread.jspa?threadID=724817
http://x86.sun.com/thread.jspa?threadID=5275999&messageID=10156541
I am using JVM 1.6.0_07-b06. It happens on Windows XP as well as on Windows Vista.
Has anybody found a workaround for this yet?

A: There's a bug where if you a networked drive mapped on the desktop, it can sometimes hang on the JFileChooser. That or it might be a shortcut to a networked drive. Something along those lines...

A: I've run into this myself and the updates didn't help. Strangely enough, removing all zip files (particularly large ones) from my desktop (JFileChooser's default location) solved the issue.

A: The .10 update is supposed to fix the zipfile related one.

A: Yes, it was a bug, but I believe recent versions of Java no longer have it.
There are a few workarounds(although they are all dirty hacks):

*

*Use a thread to wait until it was initialized

*Reuse the same JFileChooser(store it in a variable) instead of creating new ones. If possible, lazily initialize them:

public static JFileChooser chooser = null;

public static void doSomething(){
    if(chooser==null)
         chooser = new JFileChooser();
    //use JFileChooser
}

This way your users have to wait less... but they still will need to wait. The only way to really fix this is to update your JRE.


text:
Q: How to select item from drop down menu using Selenium with Python? I have a drop down menu and need to select an item based on its value.
let's say I want to select value "50.0"

full HTML of the table is at the end of the post:
below code can work based on the ID (but the problem is that everytime I reload the page the ID changes so I have to update it in my code).
                width = browser.find_element_by_css_selector("#linemodechannelwidth > tbody > tr > td.dijitReset.dijitStretch.dijitButtonContents > div.dijitReset.dijitInputField.dijitButtonText > span")
                actions3 = ActionChains(browser)
                actions3.click(width).perform()
                time.sleep(4)
                spacing50 = browser.find_element_by_css_selector('#dijit_MenuItem_27_text')
                spacing50.click()

what should be the code to use to select the value 50.0 from the dropdown box based on its value and not the ID ?
Below is the HTML of this dropdown menu:

          50.0

                                       +

              37.5

                                           +

              62.5

                                           +

              75.0

                                           +

              87.5

                                           +

A: for example: let's assume the dropdown has an id "12345"
and there is :
< option value="x"> A < /option>
< option value="y"> B < /option>
< option value="z"> C < /option>

first capture the options in selenium:
=> options_list = new Select(driver.findElement(By.id("1234")));
if you want to select by visible dropdown item : (lets say "A" )
=> options_list.selectByVisibleText("A")
if you want to select the item by dropdown number  (lets say second item)
=> options_list.selectByIndex(1)

A: from selenium.webdriver.remote.webelement import WebElement

### Find the table first

table = browser.find_element_by_css_selector(
'table.dijit.dijitReset.dijitMenuTable.dijitSelectMenu.dijitValidationTextBoxMenu.dijitMenu.dijitMenuPassive'
)

### Loop through all td in the table
for td in table.find_elements_by_tag_name('td'):
    assert isinstance(td, WebElement)
    ### If the text value cast to int is 50 click and break.
    if int(td.text) == 50:
        td.click()
        break


text:
Q: Collapse all tabs in an accordion (not jQuery UI) I made a little accordion which works fine, but I'd like to add the functionality that you also can close all boxes.
In this DEMO you can see, that there is never more than one box open.
See the jQuery code below:
$(function() {
  $('.job_content .job_description_box').hide();
  $('.job_box:first').addClass('active').next().slideDown('slow');
  $('.job_box').click(function() {
    if($(this).next().is(':hidden')) {
        $('.job_box').removeClass('active').next().slideUp('slow');
        $(this).toggleClass('active').next().slideDown('slow');
        $(".downarrow", this).toggleClass( ".uparrow" );
    }
  });
});

Now if you click on the opened box it should collapse. This was my try, which unfortunately doesn't work:
if($(this).find('.job_description_box').is(':visible')) {
  $(this).slideUp('slow');
}

–––
For those who looked at the demo: I'm talking about the blue job boxes at the bottom.

A:     if($(this).next().is(':hidden')) {
        $('.job_box').removeClass('active').next().slideUp('slow');
        $(this).toggleClass('active').next().slideDown('slow');
        $(".downarrow", this).toggleClass( ".uparrow" );
 }
  else
  {
    $(this).toggleClass('active').next().slideUp('slow');
  }

I have added an 'else' statement to your current 'if' statement to hide the content upon clicking the box again.
EDIT:
Add this to your CSS file.  This will rotate your arrow rather than using another image.
.arrow_rotate {
-webkit-transform: rotate(180deg);
-moz-transform: rotate(180deg);
  -ms-transform: rotate(180deg);
    -o-transform: rotate(180deg;
     transform: rotate(180deg);

}
Update your JQuery:
 $('.job_box').click(function() {
    if($(this).next().is(':hidden')) {
        $('.job_box').removeClass('active').next().slideUp('slow');
        $(this).toggleClass('active').next().slideDown('slow');
        $(".downarrow", this).addClass('arrow_rotate');
 }
 else
  {
    $(this).toggleClass('active').next().slideUp('slow');
                $(".downarrow", this).removeClass('arrow_rotate');
  }

This should now do as you require.


text:
Q: Assign `call system()` result to a Fortran variable I am using this piece of code to review the number of files of  a folder
call system ('dir c:\data /B /A-d|find /v /c "*"')

I need to assign it to a variable. I have tried everything.


text:
Q: Javascript GPS math I need a javascript function that updates current position based on speed, heading, and time elapsed.
function getUpdatedPosition(oldLat, oldLon, speedInMetersPerSec, headingInDegrees, durationInSeconds)
Where "headingInDegrees"  is Direction of travel, specified in degrees counting clockwise relative to the true north. (Number)
Which would return a geoPosition object like this:
{lat: 43.34532, lon: -84.23421}  accurate and precise to 5 decimal places.
With regards to accuracy, I am calculating over short distances with frequent updates and therefore a linear approximation is sufficient.

A: See "Problem 1c" in http://www.codeguru.com/Cpp/Cpp/algorithms/article.php/c5115.
"distance" would be speedInMetersPerSec * durationInSeconds for you, obviously.


text:
Q: HTML/CSS trouble aligning content center I just started learning HTML and CSS none of the fixes google has suggested have managed to align my contact box to the center of the page. I have tried justify-content, align-items, align-content, and display flex in combination with the stuff above. My page either stays the same or the box aligns itself to the upper left.
I have had a lot of trouble with the things I have built in html so far never aligning center. I would just like to understand why this is happening.
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Contact Us</title>
    <link rel="stylesheet" href="./CSS/Style.CSS" />

      <form>

        <input
          type="text"
          class="input-field"
          placeholder="Full Name"
          required
        />
        <input
          type="text"
          class="input-field"
          placeholder="Your Email"
          required
        />

        <select id="Priority">
          <option value="Priority">Message Priority</option>
          <option value="High">High Priority</option>
          <option value="Medium">Medium Priority</option>
          <option value="Low">Low Priority/ non-urgent</option>
        </select>

        <textarea
          type="text"
          class="input-field textarea-field"
          placeholder="Your Message"
        >
        </textarea>

        <button type="button" class="btn">Send Message</button>
      </form>

*{
    margin: 0;
    padding: 0;
}

body{
    background-color: lightpink;
    font-family: sans-serif;
}

/*styles contact box*/
.contact-box{
    width: 500px;
    background-color: antiquewhite;
    box-shadow: 0 0 20px 0 #999;
   /*below here I comment everything out within contact box styling and tried all the center alignment things I could find*/
    top: 50%;
    left: 50%;
    transform: translate(-50%.-50%);
    position: absolute;
}

form{
    margin: 35px;
}

/*styles inputs name, email,etc*/
.input-field{
    width: 400px;
    height: 40px;
    margin-top: 20px;
    padding-left: 10px;
    padding-right: 10px;
    border: 1px solid #777;
    border-radius: 14px;
    outline: none;
}

/*Makes message box bigger*/
.textarea-field{
    height: 150px;
    padding-top: 10px;
}

/*styles send message button*/
.btn{
    border-radius: 20px;
    color: #fff;
    margin-top: 18px;
    padding: 10px;
    background-color: #47c35a;
    font-size: 12px;
    border: none;
    cursor: pointer;
}

/*styles dropdown menu*/
input [type=text], select{
    width: 400px;
    height: 40px;
    margin-top: 20px;
    padding-left: 10px;
    padding-right: 10px;
    border: 1px solid #777;
    border-radius: 14px;
    outline: none;
}

A: I guess you just have a typo here:
transform: translate(-50%.-50%);

It should look like this:
transform: translate(-50%,-50%);

A: You should try to put the code below in your CSS file. When you start writing, upper left is the starting point, that's where your content is going.
html {
  text-align: center;
}

A: please replace "margin : 35px" with "padding : 35px" in form class and use below 4 lines in contact-box class to center your form:
top: 50%;
left: 50%;
position: fixed;
transform: translate(-50%, -50%);
attaching the corrected code for your reference, hope it helps!

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Contact Us</title>

      <form>

        <input
          type="text"
          class="input-field"
          placeholder="Full Name"
          required
        />
        <input
          type="text"
          class="input-field"
          placeholder="Your Email"
          required
        />

        <select id="Priority">
          <option value="Priority">Message Priority</option>
          <option value="High">High Priority</option>
          <option value="Medium">Medium Priority</option>
          <option value="Low">Low Priority/ non-urgent</option>
        </select>

        <textarea
          type="text"
          class="input-field textarea-field"
          placeholder="Your Message"
        >
        </textarea>

        <button type="button" class="btn">Send Message</button>
      </form>


text:
Q: Angular Popup not showing after navigation to new route This issue is very critical in Angular from my view
Iam working with Angular 4 in my application
I want to show a popup it should be displayed
when i get the API Response. it may be success/failure/warning/info
My Idea: Create component and open it when we get response from API
and My Application requirement is popup should not close until the
user perform some action on displayed popup.(this action will provide by giving buttons on popup)
Requirement 1: After getting API Response i am navigating to other route, Popup should show on top of new route and it should   not be close until user perform some action.
[https://plnkr.co/edit/GmOUPtXYpzaY81qJjbHp?p=preview][1]

if the above plunkr is userfull consider.
if not usefull please provide me another example

A: The issue isn't critical, you just do it wrong.
Of course, if you display a pop-up on the routed component, it will disappear. That's not a critical Angular issue, that's poor thinking (no offense though).
The correct way of displaying a pop-up in single page applications is to append the pop-up to the body, in an absolute position. If you do it in the routed component, then on route change, the component gets destroyed, and so is the pop-up.


text:
Q: ERR! code building for production in Vue with npm run build Couldn't find any solution that worked online so asking here, I am a bit of a noob in web development and using npm and such.
Log:
0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'build'
1 verbose cli ]
2 info using npm@6.14.13
3 info using node@v14.17.0
4 verbose run-script [ 'prebuild', 'build', 'postbuild' ]
5 info lifecycle vue-crash@0.1.0~prebuild: vue-crash@0.1.0
6 info lifecycle vue-crash@0.1.0~build: vue-crash@0.1.0
7 verbose lifecycle vue-crash@0.1.0~build: unsafe-perm in lifecycle true
8 verbose lifecycle vue-crash@0.1.0~build: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;D:\D_Documents\Web_dev\vue-crash\node_modules\.bin;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;D:\D_Programs\Git\cmd;C:\Program Files (x86)\dotnet\;C:\ffmpeg\bin;C:\Program Files\Tesseract-OCR;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\nodejs\;C:\Users\peter\AppData\Local\Programs\Python\Python38-32\Scripts\;C:\Users\peter\AppData\Local\Programs\Python\Python38-32\;C:\Users\peter\AppData\Local\Microsoft\WindowsApps;D:\D_Programs\MikTeX\miktex\bin\x64\;C:\Users\peter\AppData\Local\Programs\Microsoft VS Code\bin;C:\ffmpeg\bin;C:\Users\peter\AppData\Roaming\Amazon;C:\Program Files\Unity\Hub\Editor\2019.3.4f1\Editor\Data\PlaybackEngines\AndroidPlayer\OpenJDK\bin;C:\Users\peter\AppData\Roaming\npm
9 verbose lifecycle vue-crash@0.1.0~build: CWD: D:\D_Documents\Web_dev\vue-crash
10 silly lifecycle vue-crash@0.1.0~build: Args: [ '/d /s /c', 'vue-cli-service build' ]
11 silly lifecycle vue-crash@0.1.0~build: Returned: code: 1  signal: null
12 info lifecycle vue-crash@0.1.0~build: Failed to exec build script
13 verbose stack Error: vue-crash@0.1.0 build: `vue-cli-service build`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:376:20)
13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:376:20)
13 verbose stack     at maybeClose (internal/child_process.js:1055:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5)
14 verbose pkgid vue-crash@0.1.0
15 verbose cwd D:\D_Documents\Web_dev\vue-crash
16 verbose Windows_NT 10.0.19042
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "build"
18 verbose node v14.17.0
19 verbose npm  v6.14.13
20 error code ELIFECYCLE
21 error errno 1
22 error vue-crash@0.1.0 build: `vue-cli-service build`
22 error Exit status 1
23 error Failed at the vue-crash@0.1.0 build script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

npm --versions :
  npm: '6.14.13',
  ares: '1.17.1',
  brotli: '1.0.9',
  cldr: '38.1',
  icu: '68.2',
  llhttp: '2.1.3',
  modules: '83',
  napi: '8',
  nghttp2: '1.42.0',
  node: '14.17.0',
  openssl: '1.1.1k',
  tz: '2020d',
  unicode: '13.0',
  uv: '1.41.0',
  v8: '8.4.371.23-node.63',
  zlib: '1.2.11'

Already tried deleting node_modules and package-lock.json and running npm install. If you have any idea it would be greatly appreciated since I have no idea where to start.


text:
Q: Can't encrypt SanDisk 8GB I've formatted my SanDisk flash drive to a OSX Extended format with the GUID Partition Map.
But when I go to encrypt the drive I continually get this error:
"A partition, not a whole disk, is required for this operation."
The partition option in Disk Utility is not available for this drive. I'm using Disk Utility to format it.
I'm using OS X version 10.11.


text:
Q: Java - convert unix time in miliseconds with time zone to timestamp I have a string for example:
1517439600000+0100

and I want to convert it to unix time in miliseconds with no timezone.
how can I do it?
p.s.
1) I cant use substring(0,5) and add 3.6m miliseconds to the string because I have a lot of time zone once is +0100 and then is +0200 and etc...
2) if it more easier to convert to regular timestamp like YYYY-mm-dd hh:mm:ss
it should be fine.

A: You can do something like:
    String sign = "+";
    String [] parts = time.split(sign);

    Long millis = Long.parseLong(parts[0]);
    String zoneOffset = sign + parts[1];

    LocalDate date = Instant.ofEpochMilli(millis).atZone(ZoneOffset.of(zoneOffset)).toLocalDate();

A:     String exampleString = "1517439600000+0100";
    // Split string before + or-
    String[] parts = exampleString.split("(?=[+-])");
    if (parts.length != 2) {
        throw new IllegalArgumentException("Unexpected/unsupported format: " + exampleString);
    }
    // Parse the milliseconds into an Instant
    Instant timeStamp = Instant.ofEpochMilli(Long.parseLong(parts[0]));
    // Parse the offset into a ZoneOffset
    DateTimeFormatter offsetFormatter = DateTimeFormatter.ofPattern("xx");
    ZoneOffset offset = ZoneOffset.from(offsetFormatter.parse(parts[1]));
    // Combine
    OffsetDateTime dateTime = timeStamp.atOffset(offset);
    System.out.println(dateTime);

Output:

2018-02-01T00:00+01:00

The number of milliseconds since the epoch (1 517 439 600 000) denotes a point in time independently of time zone or offset. So for getting a timestamp it's enough to parse this number. If you're happy with the Instant (2018-01-31T23:00:00Z in the example), you can of course drop the last half of the code. My style would be to harvest all the information from the string also when I don't need all of it right away.
The regular expression I use for splitting, (?=[+-]), is a positive look-ahead: it matches the empty string before a + or -. Matching the empty string is important so no part of the string gets lost in the splitting (we need to preserve the sign).
A simpler way to parse the offset is ZoneOffset.of(parts[1]) (as NiVeR does in another answer). The only difference is that the DateTimeFormatter I use also validates that the format is indeed either like +0100 (no colon) or Z.


text:
Q: What is the max. database size allowed for Azure Managed Instance database? From the documentation, it is not very clear what is the exact limit for database size (in TBs) using Managed Instnace option in case of Azure?

A: Its 8 TeraBytes allowed for sql database managed instance resource


text:
Q: Problems trying to define and configure my custom provider I am pretty certain I'm following all the rules:

*

*$get() is defined.

*injecting properly into the controller

*configuring in the initial app def before it's instantiated

Here is a fiddle
angular.module('app', function($httpProvider, $locationProvider, MockServiceProvider) {
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
    $locationProvider.html5Mode(false);
    MockServiceProvider.enableMocks(true);
})
.provider('MockService',['$http', '$q', function ($http, $q) {
    this.mocksEnabled = false;
    this.enableMocks = function(val) {
            mocksEnabled = val;
    };
    this.$get = function() {
        var _mock_getNext = function() {
            return {
                'status' : {
                    'type': 'OK',
                    'msg': null
                },
                'data': {
                    'id': 123456789
                }
            };
        };
        return {
            getData : function() {
                if(mocksEnabled) {
                    return _mock_getNext;
                } else {
                    return "Real Data";
                }
            }
        };
    };
}])
.controller('Main', function(MockService) {
    $scope.maybe_mock_data = MockService.getData();
});

A: The $http and $q injections for the provider should be on the $get method of the provider, not on the constructor of the provider.
Fiddle: http://jsfiddle.net/pvtpenguin/UAP29/1/
.provider('MockService',function () {
    this.mocksEnabled = false;
    this.enableMocks = function(val) {
            mocksEnabled = val;
    };
    this.$get = ['$http', '$q', function($http, $q) {
        var _mock_getNext = function() {
            return {
                'status' : {
                    'type': 'OK',
                    'msg': null
                },
                'data': {
                    'id': 123456789
                }
            };
        };
        return {
            getData : function() {
                if(this.mocksEnabled) {
                    return _mock_getNext;
                } else {
                    return "Real Data";
                }
            }
        };
    }];
})

Other minor problems:

*

*$scope was not injected into the controller

*In the getData function of the service, mocksEnabled needed to be this.mocksEnabled


text:
Q: Xamarin.forms iOS Install failed due to distribution provisioning issue I can compile my Xamarin.forms (iOS) app using manual provisioning.
Machine:
Windows
Visual Studio 16.5.5
Certificates
1- Apple Distribution
Provisioning Profile
1- App Store Distribution Profile
Entitlements.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.developer.associated-domains</key>
    <array>
        <string>applinks:example.com</string>
        <string>applinks:my.example.com</string>
        <string>applinks:hbalphaweb.example.com</string>
        <string>applinks:staging.example.com</string>
        <string>applinks:hblivemy.example.com</string>
        <string>applinks:app.example.com</string>
        <string>webcredentials:devweb1.example.com</string>
        <string>webcredentials:my.example.com</string>
        <string>webcredentials:hbalphaweb.example.com</string>
        <string>webcredentials:staging.example.com</string>
        <string>webcredentials:hblivemy.example.com</string>
        <string>webcredentials:app.example.com</string>
    </array>
  <key>aps-environment</key>
    <string>production</string>
</dict>
</plist>

I can compile successfully and push it to Test Flight. The problem is that my testers can't install the App because it says that The App was not provisioned properly.
I have tried deleting temp files, cleaning and restarting VS and rebuilding but all in vain.
Can any one help me to figure it out what could be possible issue?


text:
Q: Setup Magento 2.4.1 project on Github I have created the Magento 2.4.1 project in my local system.
Now I have to set up this project on Github. I have created an account on Github.
Can someone tell me the steps to set up this on Github? Which files and directories should be upload on Github? What should be in the gitignore file?

A: Check this article for a quick ramp-up for managing your project with git and github.
As for the .gitignore file, here the Magento official reference file. However, I find this relevant when you keep your whole project there, as in the whole magento installation files, not only your customizations. If this is what you need, then use it like this.
If you only work on an individual module that you need versioned (and not keep the whole Magento project on the repo), then I would consider adding only the module to the github repo. Afterwards, you could install it by composer, here is an example. If you use this approach, you will need a simpler .gitignore, so I would delete the lines containing Magento installation specific folders (like app, lib, pub, media, var, etc).


text:
Q: Is there another way of returning a value from this SQL without the use of a promise? Here is the code I have tried, when I try to return soc it says it is undefined, I know this is because it is defined within a nested promise. My question is how can I return the result of my sql query without the use of a .then promise as I do not fully understand them and they're just causing me pain.
async function get_charge_level() {
    var config = {
            <config_settings>
        };
        sql.setDefaultConfig(config);
        await sql.execute( {
            query: "some query"
        } ).then(async function( id ) {

            await sql.execute( {
                query: "some other query"
            } ).then(async function( soc ) {
            })
        })

    return soc
}

A: You're already using the async-await syntax, so just change as follows:

async function get_charge_level() {
  var config = {
    //<config_settings>
  }
  sql.setDefaultConfig(config);
  let id = await sql.execute({
    query: "some query"
  })
  let soc = await sql.execute({
    query: "some other query"
  })
  return soc
}


text:
Q: File Upload for asp.net in c# I have been working on an image/file uploader that stores an image to a virtual directory with MapPath or to a database. I have been using if statements for the button click event to check the file and attempt to save but I have not been successful.
protected void Button1_Click(object sender, EventArgs e)
{

    if (FileUpload1.HasFile)
    {

        string extension = Path.GetExtension(FileUpload1.FileName);

        if (extension == ".jpg" || extension == ".gif" || extension == ".png" || extension == ".bmp")
        {

            FileUpload1.SaveAs(Server.MapPath("../photos/" + FileUpload1.FileName));

            string imagePath = "/photos/" + FileUpload1.FileName;

A: please try this
FileUpload1.SaveAs(Server.MapPath(@"~\photos\" + FileUpload1.FileName));


text:
Q: How to simulate a micrologix allen bradley PLC? Currently I'm working on writing data to a test machine that simulates reads from an Allen Bradley PLC in python. This machine is supposed to replicate another that we have live that simply reads the PLC tags, and I don't have any spare PLC's just lying around. Is there any program or code out there I could use to simulate a PLC for reading and writing?
This is for reading and writing tags to a simulated PLC for our test machine. I have tried using cpppo's sample code for a server, however the tag names in the live PLC has "[]" in the name (so for example, "tag[1] tag[2] etc..), and cpppo fragments these whenever I try to instantiate them in the terminal.
I expect there to be some simulator that exists that should solve this problem, however I have been searching for more than a week now with no hope/leads besides cpppo, any kind of insight or suggestions would be appreciated.

A: Logix 500 Emulate is what you want, and it's free.
Go to the RA downloads site, and then search for "Emulate".
Rockwell Automation - Downloads


text:
Q: Image not resizing in the command prompt I want to resize my image 200x200px but below command not working. I have successfully installed imagemagick in my computer.
convert current_image.png -resize 200 new_image.png

I have tried above command but not working. I am getting error message Invalid Parameter - -resize
Please let me know how to fix that?

A: You are running the Windows built-in command called CONVERT.EXE which converts filesystems to NTFS and not the ImageMagick convert program.
You have two options... the first is best if you plan on using ImageMagick only one or two times, the second one is best if you plan on using ImageMagick often.
Option 1
Use the full path to ImageMagick's convert program every time you want to process images, e.g.:
C:\ImageMagick-6.9.2\convert image.png ...

Your installation path may differ from the one I guessed above.
Option 2
Edit your PATH so that the directory where you installed ImageMagick is near the start of the PATH so that Windows finds that one first. So, you need to click:
Start->Control Panel->System->Advanced->Environment Variables

Then edit the PATH so it looks like:
C:\ImageMagick-6.9-3;C:\other stuff

Specifically, the directory containing ImageMagick must come before C:\Windows\System32 where the Windows file conversion tool lives.
After you do that, you will just be able to type convert and it will run ImageMagick convert.

A: *

*At first, check whether your path is set. (How? Mentioned above)

*If you are using latest ImageMagick, try changing from convert to magick
There is another way to do this (I didn't try it)--

*

*Replace convert with the path. For example "C:\Program Files\ImageMagick\convert.exe" (In the latest ImageMagick, replace convert with magick)

*For reference: See here
It works for me. Let me know if it works for you too. If you find any error in my answer, let me know also.


text:
Q: How to link to Google Directions public transit page for specific arrival time I'd like to be able to link to a google directions map from a departure location to an arrival location for a specific future arrival time. So I want to link to a page like this:
https://goo.gl/maps/2n6FC
It's easy to get the directions using the Google Directions API, which is well documented and would return me the stepped directions in a format like json... but the thing is, in my case, linking to Google would be fine, so why try to re-create it, and why would Google want me to do that instead of link?! But the parameters for the links are pretty much undocumented, as far as I can tell, with people fishing around for parameters as I did at this page:
http://asnsblues.blogspot.co.uk/2011/11/google-maps-query-string-parameters.html
This gets me halfway with &dirflg=r which defaults the directions to public transit, but I can't find a parameter reported anywhere for arrival time, probably because it's quite specific to public transit.


text:
Q: Custom draw navigation not rendering - React Native I'm trying to replace default drawer navigator with customDrawerNavigator. I have used ScrollView, DrawerNavigatorItems and passed props inside the custom drawer component. I have an AppNavigator component which renders the drawer navigator.
Here is what I have tried so far,
import React from 'react';
import { createDrawerNavigator, ScrollView,DrawerNavigatorItems } from 'react-navigation-drawer';
import {Icon, Body, Button, Container, Header, Content, Left} from 'native-base';
import {Image, View} from 'react-native';
import Admin from '../screens/Admin.js';
import Manager from '../screens/Manager.js';
import Login from '../screens/Login.js'

const DrawerNavigator = createDrawerNavigator({

    Admin: {
        screen: Admin
    },
    Manager: {
        screen: Manager
    },
    Login: {
        screen: Login
    }
},
{
    initialRouteName: 'Admin',
    drawerPosition: 'left',
    contentComponent: CustomDrawerContentComponent,
    drawerOpenRoute: 'DrawerOpen',
    drawerCloseRoute: 'DrawerClose',
    drawerToggleRoute: 'DrawerToggle'
}
);

const CustomDrawerContentComponent = (props) => (

    <Container>
      <Header style={{height: 200, backgroundColor: 'white', paddingTop: 50}}>
        <Body>
          <Image style={{width: 30, height: 30}} source={require("../assets/logo.png")}/>
          <ScrollView>
            <DrawerNavigatorItems {...props} />
            <Text>Your Own Footer Area After</Text>
            </ScrollView>
        </Body>
     </Header>
   </Container>
  );

export default DrawerNavigator;

I have an AppNavigator content to wrap this DrawerNavigator and rendered inside the App.js file.
export default createAppContainer(
    createSwitchNavigator({
        // Auth: Login,
        Main:DrawerNavigator,
    })
);

But I'm getting an empty drawer.

A: Navigators need to be wrapped inside createAppContainer provided by react-navigation :
import { createAppContainer } from 'react-navigation';
const DrawerNavigator = createDrawerNavigator({

    Admin: {
        screen: Admin
    },
    Manager: {
        screen: Manager
    },
    Login: {
        screen: Login
    }
},
{
    initialRouteName: 'Admin',
    drawerPosition: 'left',
    contentComponent: CustomDrawerContentComponent,
    drawerOpenRoute: 'DrawerOpen',
    drawerCloseRoute: 'DrawerClose',
    drawerToggleRoute: 'DrawerToggle'
}
);

const Container = createAppContainer(DrawerNavigator);
export default Container;

Hope, this will help.


text:
Q: Use some row values as column SQL I would like to have columns that look like this:
KILL, DEATH, WIN, playerName

this is the resultset that it should be applied on

and this is the query that i use to get that resultset:
SELECT SUM(amount) as amount, type.name as type, gamemode_statistics.Name as playerName
FROM gamemode_statistics INNER JOIN type ON gamemode_statistics.type_id = type.id
GROUP BY gamemode_statistics.type_id, playerName

i really have no clue on how to do this, i tried various ways but none of them solve my problem. Maybe i just configured my tables incorrectly?

A: You're looking for a pivot query, and MySQL doesn't support them directly. For a simple 3-column result, it's not too bad, but this cannot be made to work as a general solution for n-way arbitrary columns:
SELECT
    SUM(IF type='KILL', amount, 0) AS KILL,
    SUM(IF type='DEATH', amount, 0) AS DEATH
    etc..
FROM ...

A: If these are the only three values you want to show as column you can do so,this will give you the count of types
SELECT SUM(amount) as amount,
SUM(`type`='KILL') AS `KILL`,
SUM(`type`='DEATH') AS `DEATH`,
SUM(`type`='WIN') AS `WIN`,
 gamemode_statistics.Name as playerName
FROM gamemode_statistics
INNER JOIN type ON gamemode_statistics.type_id = type.id
GROUP BY gamemode_statistics.type_id, playerName

A: SELECT
    ISNULL(SUM(CASE WHEN type='KILL'THEN amount ELSE 0 END),0) AS KILL,
    ISNULL(SUM(CASE WHEN type='DEATH'THEN amount ELSE 0 END) AS DEATH
    etc..
FROM ...

A: Consider putting your database into 3rd normal form.  http://www.andrewrollins.com/2009/08/11/database-normalization-first-second-and-third-normal-forms/
CREATE TABLE players (
  id int not null primary key auto_increment,
  name text not null,
... other player data
);

Create TABLE player_stats(
  player_id int not null primary key, -- this is a foreign key to the players table
  kills int not null default 0
  deaths not null default 0,
  wins not null default 0,
  ... other stats
);

then the query becomes something like
SELECT name, wins
  FROM players join player_stats on player_id = players.id
  WHERE name = 'fred';


text:
Q: Declare "LANGUAGE plpgsql" before or after the function body? Is there any difference between:
CREATE FUNCTION func() RETURNS integer
    LANGUAGE plpgsql AS $$
    declare
    begin
      -- do something
    end
$$;

and
CREATE FUNCTION func() RETURNS INTEGER AS $$
    declare
    begin
      -- do something
    end
$$ LANGUAGE plpgsql;

Does LANGUAGE plpgsql basically just have to be outside the scope of the $$ usage?

A: No difference whatsoever.
The function body is a string literal. The $$ are just dollar-quotes and could be single quotes, too (but better use dollar quotes!):

*

*What are '$$' used for in PL/pgSQL

*Insert text with single quotes in PostgreSQL
CREATE FUNCTION is a declarative SQL-DDL command, and the order of keywords is pretty free, as per definition in the manual. (Key words within the curly braces in the command definition can be arranged freely, but not the rest).
I eventually settled on always putting the language declaration on top with the rest of the function header, before the function body. Makes more sense.


text:
Q: Create portable pgaudit extension for windows How shall i create and manage portable pgaudit extension for windows? I couldn't install with makefile.
This is the error below:
D:\pgxs.mk:85: D:/Windows/: Permission denied
D:\pgxs.mk:85: Files/PostgreSQL/12/lib/pgxs/src/makefiles/../../src/Makefile.global: No such file or directory
D:\pgxs.mk:224: /src/Makefile.shlib: No such file or directory
make: *** No rule to make target `/src/Makefile.shlib'.  Stop.

A: I have not tried this but on Windows it is recommended to build this extension the following way according to https://github.com/pgaudit/pgaudit/issues/66

I have found that Postgres extensions on Windows are very sensitive to
  exactly how they are built. I would try to build the extension by
  dropping the pgaudit source code directory into a full Postgres source
  code tree under "contrib", and then build the entire thing following
  the docs for a Windows source build. Then take the resulting
  pgaudit.dll and use that.


text:
Q: Unix extract lines in between 2 lines and store them in respective files I have a file like below in file allreport.txt:
11:22:33:456        Script started                  Running: first_script
11:22:34:456        GetData - Read                  Read 12 Bytes
11:22:34:456        SetData - Write                 Write 12 Bytes
11:32:33:456        Script started                  Running: second_script
11:32:34:456        GetData - Read                  Read 12 Bytes
11:32:34:456        SetData - Write                 Write 12 Bytes
11:42:33:456        Script started                  Running: third_script
11:42:34:456        GetData - Read                  Read 12 Bytes
11:42:34:456        SetData - Write                 Write 12 Bytes
11:52:33:456        Script started                  Running: fourth_script

My requirement is that I need to extract the '....' lines which are in between '*scripts'. I tried something like below:
grep 'Running:' allreport.txt | sed 's/[^ ]* //' | cut -d":" -f2 | tr '\n' ' ' | awk -v col=1 '/$col/,/$($col+1)/ allreport.txt  > $col'

But after execution of the command I see no output and no result files also created?
How can I achieve the same - the expected output is to have files like first_script, second_script and so on and each of the files contains logs of its run - example first_script should have below lines only:
11:22:34:456        GetData - Read                  Read 12 Bytes
11:22:34:456        SetData - Write                 Write 12 Bytes

Similarly second_script should have below lines and so on:
11:32:34:456        GetData - Read                  Read 12 Bytes
11:32:34:456        SetData - Write                 Write 12 Bytes

A: With your shown samples only, please try following. As an output it will create 3 files named first_script, second_script and third_script with shown samples.
awk -F': ' '/Running/{close(outFile);outFile=$2;next} {print > (outFile)}' Input_file

Explanation: Simple explanation would be, making field separator as : then checking if line has Running in it then set output file name as 2nd field. If line is NOT having Running then print that line into output file. Also making sure to close the output file in backend to avoid "too many opened files error" here.

A: You may try this awk also:
awk '$(NF-1) == "Running:" {close(fn); fn = $NF; next} {print > fn}' file

A: The immediate problem seems to be that you have some shell script code inside the quotes of your Awk script ... but also more fundamentally, your script is much too complex and weird.
awk '/Running:/ { close(c); c++; next }
    { print >c }' allreport.txt

A: $ awk 'sub(/.*Running: /,""){ close(out); out=$0; next } { print > out }' allreport.txt

$ head *script
==> first_script <==
11:22:34:456        GetData - Read                  Read 12 Bytes
11:22:34:456        SetData - Write                 Write 12 Bytes

==> second_script <==
11:32:34:456        GetData - Read                  Read 12 Bytes
11:32:34:456        SetData - Write                 Write 12 Bytes

==> third_script <==
11:42:34:456        GetData - Read                  Read 12 Bytes
11:42:34:456        SetData - Write                 Write 12 Bytes

A: You can use the csplit utility to split a file based on content:
csplit allrep.txt /[[:space:]]Running:[[:space:]]/ '{*}'
# produces xx00 - xxNN files based on that match

Some versions do not support '{*}'. If that is the case, you need to supply the number of splits in the {}. You could do:
csplit allrep.txt /[[:space:]]Running:[[:space:]]/ "{$(awk '/\sRunning:\s/{cnt++} END{print cnt-1}' allrep.txt)}"

If you want the file names, I would do something like this in awk:
awk 'BEGIN{fn="0000 - Header"}
{sub(/\r$/,"")}   # the file you uploaded has \r\n endings
$(NF-1)=="Running:" {close(fn); fn=sprintf("%04d - %s.txt", ++fc, $NF)}
{print >fn}
' allrep.txt

By adding a numeral in front, 1) that takes care of any dups and 2) allows you to see the order.


text:
Q: MODIFY TABLE of type ANY TABLE from field-symbol of type ANY I have a generic table of type "any table" and I'm trying to modify some entries in there, in this way:
  LOOP AT ct_data INTO <fs_data>.
    ASSIGN COMPONENT 'KEY' OF STRUCTURE <fs_data> TO <fs_feld_fu_key>.
    IF <fs_feld_fu_key> IS ASSIGNED.
      IF <fs_feld_fu_key> = <fs_mci_items>-parent_key.
        ASSIGN COMPONENT 'ZZ_CHANGED_FIELD' OF STRUCTURE <fs_data>  TO <fs_feld_walzzyk>.
        IF <fs_feld_walzzyk> IS ASSIGNED.
          <fs_feld_walzzyk> = <fs_mci_items>-zz_changed_field.
          MODIFY TABLE ct_data FROM <fs_data>.
        ENDIF.
      ENDIF.
    ENDIF.
  ENDLOOP.

Field-Symbols are all having the type "any".
Everything in this code woks just fine, BUT after this line:
MODIFY TABLE ct_data FROM <fs_data>.

I get SY_SUBRC = 4 and the table will not be modified. Does anybody have some ideas or tips? What am I doing wrong in this case?
Full code:
    DATA: rt_data TYPE REF TO data,
      ls_key  TYPE /bobf/s_frw_key,
      lt_key  TYPE /bobf/t_frw_key.
FIELD-SYMBOLS: <fs_data>         TYPE any,
               <fs_feld_fu_key>  TYPE any,
               <fs_feld_walzzyk> TYPE any.

CREATE DATA rt_data LIKE LINE OF ct_data.
ASSIGN rt_data->* TO <fs_data>.

IF <fs_data> IS ASSIGNED.
  LOOP AT ct_data INTO <fs_data>.
    ASSIGN COMPONENT 'fu_key' OF STRUCTURE <fs_data> TO <fs_feld_fu_key>.
    IF <fs_feld_fu_key> IS ASSIGNED.
      ls_key-key = <fs_feld_fu_key>.
      APPEND ls_key TO lt_key.
    ENDIF.
  ENDLOOP.
ENDIF.

/scmtms/cl_tor_helper_read=>get_tor_data(
  EXPORTING
    it_root_key          = lt_key
  IMPORTING
    et_mci_items         = DATA(lt_mci_items)
).

LOOP AT lt_mci_items ASSIGNING FIELD-SYMBOL(<fs_mci_items>).
  LOOP AT ct_data INTO <fs_data>.
    ASSIGN COMPONENT 'FU_KEY' OF STRUCTURE <fs_data> TO <fs_feld_fu_key>.
    IF <fs_feld_fu_key> IS ASSIGNED.
      IF <fs_feld_fu_key> = <fs_mci_items>-parent_key.
        ASSIGN COMPONENT 'ZZ_CHANGED_FIELD' OF STRUCTURE <fs_data>  TO <fs_feld_walzzyk>.
        IF <fs_feld_walzzyk> IS ASSIGNED.
          <fs_feld_walzzyk> = <fs_mci_items>-zz_walzzyklus.
          MODIFY TABLE ct_data FROM <fs_data>.
        ENDIF.
      ENDIF.
    ENDIF.
  ENDLOOP.
ENDLOOP.

A: <fs_data> doesn't point to ct_data. It points to a new memory area that you create in the very beginning. Remove this and declare the field symbol inline to get a pointer to the actual output:
DATA: rt_data TYPE REF TO data,
      ls_key  TYPE /bobf/s_frw_key,
      lt_key  TYPE /bobf/t_frw_key.
FIELD-SYMBOLS: <fs_feld_fu_key>  TYPE any,
               <fs_feld_walzzyk> TYPE any.

IF <fs_data> IS ASSIGNED.
  LOOP AT ct_data ASSIGNING FIELD-SYMBOL(<fs_data>).
    ASSIGN COMPONENT 'fu_key' OF STRUCTURE <fs_data> TO <fs_feld_fu_key>.
    IF <fs_feld_fu_key> IS ASSIGNED.
      ls_key-key = <fs_feld_fu_key>.
      APPEND ls_key TO lt_key.
    ENDIF.
  ENDLOOP.
ENDIF.

/scmtms/cl_tor_helper_read=>get_tor_data(
  EXPORTING
    it_root_key          = lt_key
  IMPORTING
    et_mci_items         = DATA(lt_mci_items)
).

LOOP AT lt_mci_items ASSIGNING FIELD-SYMBOL(<fs_mci_items>).
  LOOP AT ct_data ASSIGNING <fs_data>.
    ASSIGN COMPONENT 'FU_KEY' OF STRUCTURE <fs_data> TO <fs_feld_fu_key>.
    IF <fs_feld_fu_key> IS ASSIGNED.
      IF <fs_feld_fu_key> = <fs_mci_items>-parent_key.
        ASSIGN COMPONENT 'ZZ_CHANGED_FIELD' OF STRUCTURE <fs_data>  TO <fs_feld_walzzyk>.
        IF <fs_feld_walzzyk> IS ASSIGNED.
          <fs_feld_walzzyk> = <fs_mci_items>-zz_walzzyklus.
        ENDIF.
      ENDIF.
    ENDIF.
  ENDLOOP.
ENDLOOP.

A: <fs_data> is a pointer to a row in ct_data. You are trying to modify the table from itself. The sy-subrc = 4 simply states that there is nothing to change.
As JozsefSzikszai points out in his comment, you don't need the MODIFY TABLE at all. Simply change the values in <fs_data> directly.


text:
Q: git reset all branches to origin? I want to reset multiple branches to their origin version. So,
git fetch --all
for b in master work; do
  git switch $b; git reset --hard origin/$b
done

But simpler? I've thought about deleting all branches so they get recreated, but one has to be checked out and will error out.
Edit: the scenario is that origin often rewrites multiple branches with impunity. The answer below also gave me the idea of saving various states to backup refs -- which is a nice bonus.

A: You don't need to switch to the branches. You can simply re-create a branch and have it point to any arbitrary ref:
git branch -f branchname "$target"

(As an added bonus, unstaged changes in your working tree won't be affected, as compared to git reset --hard which will wipe any local changes.)
When being used in scripts git branch should be avoided and it is better to use for-each-ref:
git for-each-ref 'refs/remotes/origin' --format='%(refname:strip=3)' \
| while read ref; do
    git branch -f "$ref" "origin/$ref";
done

If you are only interested in creating a "backup" of the current state of the remote tracking branches, git push or git fetch can help by using the current clone as remote.
Either command will replicate all branches of the origin remote into a new (local) branch hierarchy with prefix backup/, i.e. origin/dev becomes backup/dev:
git fetch . 'refs/remotes/origin/*:refs/heads/backup/*'
# or:
git push . 'refs/remotes/origin/*:refs/heads/backup/*'

Or to fetch directly from the remote into a separate set of local refs:
git fetch origin 'refs/heads/*:refs/heads/backup/*'


text:
Q: Spring gateway and spring mvc in an application I have a spring boot application.
I know that spring mvc is incompatible with spring cloud gateway and it is needed to use spring-boot-starter-webflux instead of spring-boot-starter-web.
But the problem is that I have to add a gateway functionality to an existing app.
And so I have some questions that I hope will help with the problem:

*

*May I create another spring context for separate beans of this libraries? I. e., I mean the old app will work with old context and gateway only with the new. And here are another question: How can I load spring starter in another spring context?

*May I configure another port for gateway? So that the old app receives messages on port 8080, and the gateway receives messages for itself on port 8081.


text:
Q: Anchor tag having newline because of code-mirror Using code mirror to convert my html to formatted html.
To doing this Code mirror is moving all the end HTML tags to the next line.This is creating an issue with the anchor tags as it is moving the end anchor tag to the next line.So while it is being displayed the next line char is also displayed as a white space so we can see a white space next to the content of the anchor tag
Tried to change it via styling but did not have any luck as HTML is rendering the next line as a white space in display
Consider this same HTML

content

linkname

Code mirror converts this to

     content

              linkname

Is there any way to avoid the white space next to the anchor tag that is being rendered because of the new line char via HTML or by code-mirror


text:
Q: Numpy NaN returning as 'nan' This is a part of my code:
df['ColZ'] = np.where(
            (df['ColA'] == 'AA') & (df['ColB'] == 'BB'),
            'GOOD!',
            np.where((df['ColA'] == 'BB') & (df['ColB'] == 'AA'),
            'BAD...',
            np.nan))

But the 'nan's are populated as 'nan' (string) instead of NaN.
Naturally, df.isnull().any() returns False, because the 'nan's are registered as strings.
Where did I go wrong?

A: Maybe try replace nan to NaN:
df = df.replace('nan', np.nan)