text:
Q: Can we set priority for the middlewares in traefik v2? Using the v1.7.9 in kubernetes I'm facing this issue:
if I set a rate limit (traefik.ingress.kubernetes.io/rate-limit) and custom response headers (traefik.ingress.kubernetes.io/custom-response-headers) then when a request gets rate limited, the custom headers won't be set. I guess it's because of some ordering/priority among these plugins. And I totally agree that reaching the rate-limit should return the response as soon as is possible, but it would be nice, if we could modify the priorities if we need.
The question therefore is: will we be able to set priorities for the middlewares?
I couldn't find any clue of it in the docs nor among the github issues.
Concrete use-case:
I want CORS-policy headers to always be set, even if the rate-limiting kicked in. I want this because my SPA won't get the response object otherwise, because the browser won't allow it:
Access to XMLHttpRequest at 'https://api.example.com/api/v1/resource' from origin 'https://cors.exmaple.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

In this case it would be a fine solution if i could just set the priority of the headers middleware higher than the rate limit middleware.

A: For future reference, a working example that demonstrates such an ordering is here:
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: ratelimit
spec:
  rateLimit:
      average: 100
      burst: 50
---
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: response-header
spec:
  headers:
    customResponseHeaders:
      X-Custom-Response-Header: "value"
---
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: ingressroute
spec:
# more fields...
  routes:
    # more fields...
    middlewares: # the middlewares will be called in this order
    - name: response-header
    - name: ratelimit

I asked the same question on the Containous' community forum: https://community.containo.us/t/can-we-set-priority-for-the-middlewares-in-v2/1326

A: Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
1. Try while testing on you local machine, replaced localhost with your local IP. You had to achieve CORS by the following line of code request.withCredentials = true; where request is the instance of XMLHttpRequest. CORS headers has to be added to the backend server to allow cross origin access.
2. You could just write your own script which will be responsible for executing rate limit middleware after headers middleware.

A: In the v2, the middlewares can ordered in the order you want, you can put the same type of middleware several times with different configurations on the same route.
https://docs.traefik.io/v2.0/middlewares/overview/


text:
Q: AWK - Calling multiple arrays Right so I have and input file which has a multitude of rows but I am only interested in $11 and $12.
these fields look like the following:
$11
 7.4ms
 8.5ms
 11.6ms

$12
TelegramHandlerPackingInfeedHanging
TelegramHandlerPackingOrderBufferHanging

Within $12 there are 10 distinct values.
I have the following Code which is returning these 10 values as well as some out puts that I need.
#!/usr/bin/gawk -f

BEGIN {
        print "Testing glly"
} #End of BEGIN
{ #Start of MID
        MSG_TYPE[substr($12,match($12,":")+1,match($12,")")-15)]++;
        TIME_AR[$11]++;
        SUM[i++] += $11;
} #End of MID
END {
                for (MSG in MSG_TYPE) {
                        print MSG
                        print "Message Count: "MSG_TYPE[MSG]
                        print "MIN: "
                        print "MAX: "
                        print "Total MSG: "MSG_TYPE[MSG]
                        print "AVG: "SUM[sum]/MSG_TYPE[MSG]"ms"
                }
} #End of END

The out put I am getting so far looks like the following:
Testing glly
TelegramHandlerPackingInfeedHanging
Message Count: 65128
MIN:
MAX:
Total MSG: 65128
AVG: 0ms
TelegramHandlerPackingOrderBufferHanging
Message Count: 68473
MIN:
MAX:
Total MSG: 68473
AVG: 0ms

What I am trying to do is you may have noticed that I have 2 more arrays, TIME_AR and SUM. My question is how can I modify my current script to return a single segment for the 10 distinct values but give me a total sum of the values in the array SUM? I have tried to do this but it is returning 10 segments for each of the 10 distinct values.
Thanks in advance.
Reduced while still providing information.
Sorry, sample Input is as follows:
INFO  2016-06-15 00:00:28.273 TelegramDispatcher                                       - --> Complete telegram dispatching took 11189.4ms (canHandle(69:TelegramHandlerTUNotification) took 0.0ms, handleTelegram took 11182.0ms, commit took 5.1ms, doACK took 1.8ms, doNAK took -0.0ms performAfterCommit took 0.3ms, failedCanHandle took 0.1ms)
INFO  2016-06-15 00:00:28.531 TelegramDispatcher                                       - --> Complete telegram dispatching took 58.5ms (canHandle(60:TelegramHandlerPackingInfeedHanging) took 0.0ms, handleTelegram took 43.5ms, commit took 13.0ms, doACK took 1.4ms, doNAK took -0.0ms performAfterCommit took 0.3ms, failedCanHandle took 0.1ms)
INFO  2016-06-15 00:00:28.558 TelegramDispatcher                                       - --> Complete telegram dispatching took 26.8ms (canHandle(61:TelegramHandlerPackingOrderBufferHanging) took 0.0ms, handleTelegram took 10.5ms, commit took 14.5ms, doACK took 1.2ms, doNAK took -0.0ms performAfterCommit took 0.4ms, failedCanHandle took 0.1ms)

A: This looks like more or less what you want.  Your code is using the wrong value as the index to the arrays.
#!/usr/bin/gawk -f

{
    key = substr($12,match($12,":")+1,match($12,")")-15)
    MSG_TYPE[key]++
    TIME_AR[key] += $11
}
END {
    for (MSG in MSG_TYPE)
    {
        print MSG
        print "Message Count: " MSG_TYPE[MSG]
        print "AVG: " TIME_AR[MSG]/MSG_TYPE[MSG] "ms"
    }
}

Extended data
INFO  2016-06-15 00:00:28.273 TelegramDispatcher        - --> Complete telegram dispatching took 11189.4ms (canHandle(69:TelegramHandlerTUNotification) took 0.0ms, handleTelegram took 11182.0ms, commit took 5.1ms, doACK took 1.8ms, doNAK took -0.0ms performAfterCommit took 0.3ms, failedCanHandle took 0.1ms)
INFO  2016-06-15 00:00:28.273 TelegramDispatcher        - --> Complete telegram dispatching took 7189.4ms (canHandle(69:TelegramHandlerTUNotification) took 0.0ms, handleTelegram took 11182.0ms, commit took 5.1ms, doACK took 1.8ms, doNAK took -0.0ms performAfterCommit took 0.3ms, failedCanHandle took 0.1ms)
INFO  2016-06-15 00:00:28.531 TelegramDispatcher        - --> Complete telegram dispatching took 58.5ms (canHandle(60:TelegramHandlerPackingInfeedHanging) took 0.0ms, handleTelegram took 43.5ms, commit took 13.0ms, doACK took 1.4ms, doNAK took -0.0ms performAfterCommit took 0.3ms, failedCanHandle took 0.1ms)
INFO  2016-06-15 00:00:28.531 TelegramDispatcher        - --> Complete telegram dispatching took 48.5ms (canHandle(60:TelegramHandlerPackingInfeedHanging) took 0.0ms, handleTelegram took 43.5ms, commit took 13.0ms, doACK took 1.4ms, doNAK took -0.0ms performAfterCommit took 0.3ms, failedCanHandle took 0.1ms)
INFO  2016-06-15 00:00:28.531 TelegramDispatcher        - --> Complete telegram dispatching took 62.7ms (canHandle(60:TelegramHandlerPackingInfeedHanging) took 0.0ms, handleTelegram took 43.5ms, commit took 13.0ms, doACK took 1.4ms, doNAK took -0.0ms performAfterCommit took 0.3ms, failedCanHandle took 0.1ms)
INFO  2016-06-15 00:00:28.558 TelegramDispatcher        - --> Complete telegram dispatching took 26.8ms (canHandle(61:TelegramHandlerPackingOrderBufferHanging) took 0.0ms, handleTelegram took 10.5ms, commit took 14.5ms, doACK took 1.2ms, doNAK took -0.0ms performAfterCommit took 0.4ms, failedCanHandle took 0.1ms)

Output from extended data
TelegramHandlerPackingInfeedHanging
Message Count: 3
AVG: 56.5667ms
TelegramHandlerTUNotification
Message Count: 2
AVG: 9189.4ms
TelegramHandlerPackingOrderBufferHanging
Message Count: 1
AVG: 26.8ms

redpajama_set_name: RedPajamaStackExchange


text:
Q: Shared library injection: _dl_relocate_object segfaults I was recently experimenting with shared library injection in Linux and decided to write my own program to do it (instead of using say GDB to inject the library).
My program uses pthread to overwrite the first 0x25 bytes of a loaded program program (0x40000-0x400025) with assembly code to allocate space for the filename and call dlopen. Once all of this is done, it restores the program state and detaches from it.
Here's the assembly:
global inject_library
global nullsub

section .data
section .text

inject_library:
; rdi -> Pointer to malloc()
; rsi -> Pointer to free()
; rdx -> Pointer to dlopen()
; rcx -> Size of the path to the .so to load

; Create a new stack frame
push rbp

; Save rbx because we're using it as scratch space
push rbx
; Save addresses of free & dlopen on the stack
push rsi
push rdx

; Move the pointer to malloc into rbx
mov rbx, rdi
; Move the size of the path as the first argument to malloc
mov rdi, rcx
; Call malloc(so_path_size)
call rbx
; Stop so that we can see what's happening from the injector process
int 0x3

; Move the pointer to dlopen into rbx
pop rbx
; Move the malloc'd space (now containing the path) to rdi for the first argument
mov rdi, rax
; Push rax because it'll be overwritten
push rax
; Second argument to dlopen (RTLD_NOW)
mov rsi, 0x2
; Call dlopen(path_to_library, RTLD_NOW)
call rbx
; Pass control to the injector
int 0x3

; Finally, begin free-ing the malloc'd area
pop rdi
; Get the address of free into rbx
pop rbx
; Call free(path_to_library)
call rbx

; Restore rbx
pop rbx

; Destory the stack frame
pop rbp

; We're done
int 0x3
retn

nullsub:
retn

There's also a C program which calls this assembly routine and uses pthread to handle these breakpoints.
This setup works just fine for small, single threaded programs like the following.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char* argv) {
    pid_t my_pid = getpid();
    printf("PID: %ld\n", my_pid);
    getchar();
    return 0;
}

I used a simple shared library that just did puts("Hi"); in its constructor.  As stated above, everything upto here works perfectly.
However, when I try to inject the same library into a much bigger (external, closed-source program), I run into a segfault.
Here's the backtrace:
#0  0x00007f6a7985d64d in _dl_relocate_object (scope=0x21fbc08, reloc_mode=reloc_mode@entry=0, consider_profiling=consider_profiling@entry=0)
    at dl-reloc.c:259
#1  0x00007f6a79865723 in dl_open_worker (a=a@entry=0x7fff82d7cbf8) at dl-open.c:424
#2  0x00007f6a793cf5d4 in __GI__dl_catch_error (objname=objname@entry=0x7fff82d7cbe8, errstring=errstring@entry=0x7fff82d7cbf0,
    mallocedp=mallocedp@entry=0x7fff82d7cbe7, operate=operate@entry=0x7f6a798654c0 <dl_open_worker>, args=args@entry=0x7fff82d7cbf8)
    at dl-error-skeleton.c:198
#3  0x00007f6a79865069 in _dl_open (file=0x21fb830 "/home/umang/code/insertion/test_library.so", mode=-2147483646, caller_dlopen=0x40001a, nsid=-2,
    argc=<optimized out>, argv=<optimized out>, env=0x7fff82d7cfe8) at dl-open.c:649
#4  0x00007f6a7964ef96 in dlopen_doit (a=a@entry=0x7fff82d7ce08) at dlopen.c:66
#5  0x00007f6a793cf5d4 in __GI__dl_catch_error (objname=objname@entry=0x7f6a798510f0 <last_result+16>,
    errstring=errstring@entry=0x7f6a798510f8 <last_result+24>, mallocedp=mallocedp@entry=0x7f6a798510e8 <last_result+8>,
    operate=operate@entry=0x7f6a7964ef40 <dlopen_doit>, args=args@entry=0x7fff82d7ce08) at dl-error-skeleton.c:198
#6  0x00007f6a7964f665 in _dlerror_run (operate=operate@entry=0x7f6a7964ef40 <dlopen_doit>, args=args@entry=0x7fff82d7ce08) at dlerror.c:163
#7  0x00007f6a7964f021 in __dlopen (file=<optimized out>, mode=<optimized out>) at dlopen.c:87
#8  0x000000000040001a in ?? ()
#9  0x00000000021fb830 in ?? ()
#10 0x00007f6a79326a90 in ?? () at malloc.c:3071 from /lib64/libc.so.6
#11 0x00007f6a796488a0 in ?? () from /lib64/libc.so.6
#12 0x0000000000000d68 in ?? ()
#13 0x00007f6a7931e938 in _IO_new_file_underflow (fp=0x7f6a7964efe0 <__dlopen>) at fileops.c:600
#14 0x00007f6a7931fa72 in __GI__IO_default_uflow (fp=0x7f6a796488a0 <_IO_2_1_stdin_>) at genops.c:404
#15 0x00007f6a7931a20d in getchar () at getchar.c:37
#16 0x00000000004005d7 in main ()

This backtrace tells me something went (horribly) wrong in the dlopen call. Specifically, the error lies at glibc dl-reloc.c:259.
Here's the questionable glibc code.
254          l->l_lookup_cache.value = _lr; }))                   \
255      : l)
256
257 #include "dynamic-link.h"
258
259     ELF_DYNAMIC_RELOCATE (l, lazy, consider_profiling, skip_ifunc);
260
261 #ifndef PROF
262     if (__glibc_unlikely (consider_profiling)
263     && l->l_info[DT_PLTRELSZ] != NULL)

ELF_DYNAMIC_RELOCATE is a macro defined in dynamic-link.h as the following -
/* This can't just be an inline function because GCC is too dumb
   to inline functions containing inlines themselves.  */
# define ELF_DYNAMIC_RELOCATE(map, lazy, consider_profile, skip_ifunc) \
  do {                                        \
    int edr_lazy = elf_machine_runtime_setup ((map), (lazy),              \
                          (consider_profile));        \
    ELF_DYNAMIC_DO_REL ((map), edr_lazy, skip_ifunc);                 \
    ELF_DYNAMIC_DO_RELA ((map), edr_lazy, skip_ifunc);                \
  } while (0)

#endif

elf_machine_runtime_setup returns just fine, so I'm assuming that the problem lies with ELF_DYNAMIC_DO_REL. This is the source for the mentioned macro. The problem here is that the called method is inline, so GDB only displays the macro name and not the underlying source.
Using ni in GDB, I see the following after elf_machine_runtime_setup returns:
ELF_DYNAMIC_RELOCATE (l, lazy, consider_profiling, skip_ifunc);
ELF_DYNAMIC_RELOCATE (l, lazy, consider_profiling, skip_ifunc);
ELF_DYNAMIC_RELOCATE (l, lazy, consider_profiling, skip_ifunc);

Stepping through assembly, the segfault happens after the following instruction: movaps %xmm0,-0x70(%rbp).
info local isn't of much help:
(gdb) info local
ranges = {{start = 140072440991568, size = 0, nrelative = 0, lazy = 670467104}, {start = 0, size = 140072438891376, nrelative = 140072441065920,
    lazy = 672664367}}
textrels = 0x0
errstring = 0x0
lazy = <optimized out>
skip_ifunc = 0

Interestingly enough, when I use GDB to inject the shared library (using this code I found somewhere on the net), the library loads perfectly.
sudo gdb -n -q -batch \
  -ex "attach $pid" \
  -ex "set \$dlopen = (void*(*)(char*, int)) dlopen" \
  -ex "call \$dlopen(\"$(pwd)/libexample.so\", 1)" \
  -ex "detach" \
  -ex "quit"
)"

Thanks in advance!

A: After days of scratching my head and ripping off my hair, I decided to Google "MOVAPS segfault".
MOVAPS is a SIMD instruction (and here, it is used to quickly zero out a quadword). Here's some more info about the same.
On taking a closer look, I noticed the following paragraph:

When the source or destination operand is a memory operand, the operand must be aligned on a 16-byte boundary or a general-protection exception (#GP) is generated.

Hmm. So I read the value of the offending address.
(gdb) print $rbp - 0x70
$2 = (void *) 0x7ffecd32e838

There. The address isn't aligned to a 16-byte boundary and thus the segfault occurs.
Fixing this was easy.
; Create a new stack frame
push rbp
sub rsp, 0x8
; Do stuff
; Fix the stack pointer
add rsp, 0x8
; Destroy stack frame, return, etc.

I'm still doubtful if this is the right way to do it, but it works.
Oh, and GDB got it right the whole time - it made sure that the stack was aligned.


text:
Q: Acoustic model path not set right CMU Sphinx The code written below is to convert audio to text using CMU Sphinx in Java 1.6 and Eclipse Helios.
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;

import edu.cmu.sphinx.api.Configuration;
import edu.cmu.sphinx.api.SpeechResult;
import edu.cmu.sphinx.api.StreamSpeechRecognizer;

public class AudioToText {
    public static void main(String [] args) throws FileNotFoundException,IOException{
        Configuration configuration = new Configuration();

        // Set path to acoustic model.
        configuration.setAcousticModelPath("C:/Program Files/eclipse/sphinx4-5prealpha/models/acoustic");
        // Set path to dictionary.
        configuration.setDictionaryPath("C:/Program Files/eclipse/sphinx4-5prealpha/models/acoustic/wsj/dict/cmudict.0.6d");
        // Set language model.
        configuration.setLanguageModelPath("C:/Program Files/eclipse/sphinx4-5prealpha/models/language/en-us.lm.dmp");

        StreamSpeechRecognizer recognizer = new StreamSpeechRecognizer(configuration);
        //recognizer.startRecognition(new File("D:/audio.mp3").toURI().toURL());
        recognizer.startRecognition(new FileInputStream("D:/audio.mp3"));
        SpeechResult result;
        while ((result = recognizer.getResult()) != null) {
            System.out.println(result.getHypothesis());
        }
        recognizer.stopRecognition();
    }
}

Exceptions are arising because of not setting the path of acoustic model correctly as mentioned below:
   Exception in thread "main" Property exception component:'acousticModelLoader' property:'location' - Bad URL C:/Program Files/eclipse/sphinx4-5prealpha/models/acousticunknown protocol: c
edu.cmu.sphinx.util.props.InternalConfigurationException: Bad URL C:/Program Files/eclipse/sphinx4-5prealpha/models/acousticunknown protocol: c
    at edu.cmu.sphinx.util.props.ConfigurationManagerUtils.getResource(ConfigurationManagerUtils.java:479)
    at edu.cmu.sphinx.linguist.acoustic.tiedstate.Sphinx3Loader.newProperties(Sphinx3Loader.java:246)
    at edu.cmu.sphinx.util.props.PropertySheet.getOwner(PropertySheet.java:508)
    at edu.cmu.sphinx.util.props.PropertySheet.getComponent(PropertySheet.java:290)
    at edu.cmu.sphinx.linguist.acoustic.tiedstate.TiedStateAcousticModel.newProperties(TiedStateAcousticModel.java:102)
    at edu.cmu.sphinx.util.props.PropertySheet.getOwner(PropertySheet.java:508)
    at edu.cmu.sphinx.util.props.PropertySheet.getComponent(PropertySheet.java:290)
    at edu.cmu.sphinx.linguist.lextree.LexTreeLinguist.newProperties(LexTreeLinguist.java:301)
    at edu.cmu.sphinx.util.props.PropertySheet.getOwner(PropertySheet.java:508)
    at edu.cmu.sphinx.util.props.PropertySheet.getComponent(PropertySheet.java:290)
    at edu.cmu.sphinx.decoder.search.WordPruningBreadthFirstSearchManager.newProperties(WordPruningBreadthFirstSearchManager.java:199)
    at edu.cmu.sphinx.util.props.PropertySheet.getOwner(PropertySheet.java:508)
    at edu.cmu.sphinx.util.props.PropertySheet.getComponent(PropertySheet.java:290)
    at edu.cmu.sphinx.decoder.AbstractDecoder.newProperties(AbstractDecoder.java:71)
    at edu.cmu.sphinx.decoder.Decoder.newProperties(Decoder.java:37)
    at edu.cmu.sphinx.util.props.PropertySheet.getOwner(PropertySheet.java:508)
    at edu.cmu.sphinx.util.props.PropertySheet.getComponent(PropertySheet.java:290)
    at edu.cmu.sphinx.recognizer.Recognizer.newProperties(Recognizer.java:90)
    at edu.cmu.sphinx.util.props.PropertySheet.getOwner(PropertySheet.java:508)
    at edu.cmu.sphinx.util.props.ConfigurationManager.lookup(ConfigurationManager.java:161)
    at edu.cmu.sphinx.api.Context.<init>(Context.java:77)
    at edu.cmu.sphinx.api.Context.<init>(Context.java:49)
    at edu.cmu.sphinx.api.AbstractSpeechRecognizer.<init>(AbstractSpeechRecognizer.java:37)
    at edu.cmu.sphinx.api.StreamSpeechRecognizer.<init>(StreamSpeechRecognizer.java:33)
    at AudioToText.main(AudioToText.java:21)
Caused by: java.net.MalformedURLException: unknown protocol: c
    at java.net.URL.<init>(URL.java:574)
    at java.net.URL.<init>(URL.java:464)
    at java.net.URL.<init>(URL.java:413)
    at edu.cmu.sphinx.util.props.ConfigurationManagerUtils.resourceToURL(ConfigurationManagerUtils.java:495)
    at edu.cmu.sphinx.util.props.ConfigurationManagerUtils.getResource(ConfigurationManagerUtils.java:472)

I have specified path to acoustic folder. How to specify the correct path?

A:
Change configuration.setAcousticModelPath("C:/Program
  Files/eclipse/sphinx4-5prealpha/models/acoustic");

to

configuration.setAcousticModelPath("file:C:\Program
  Files\eclips\sphinx4-5prealpha\models\\acoustic");

It should work then.

A: private static final String ACOUSTIC_MODEL_PATH =
        TextAligner.class.getResource("/resources/models/acoustic/wsj").toString();
configuration = new Configuration();
configuration.setAcousticModelPath(ACOUSTIC_MODEL_PATH);

I guess you can do it like this if you have added acoustic model to a resources folder in your project folder.

A: private static String ACOUSTIC_MODEL = "file:///C:/zero/zero_ru.cd_cont_4000";
private static String LANGUAGE_MODEL = "file:///C:/zero/ru.lm";
private static String DICTIONARY     = "file:///C:/zero/ru.dic";


text:
Q: Full calendar 3 days agenda custom view is there a way to make a custom view based on agendaDay but restrain to 3 days, and the action on next or previous button, move 3 days on 3 days ?
the first day always reference to moment().day()
thanks for your help

A: This can now be done with something like this:
views: {
  agendaThreeDay: {
    type: 'agenda',
    duration: { days: 3 },
    buttonText: '3 day'
  },
  defaultView: 'agendaThreeDay'
}

You can get more information on this from the document page on Custom Views.


text:
Q: jQuery append is not working on Internet Explorer I have an issue with the append function. It works on chrome and firefox but not IE.
This is my code:
$('a#ajouterTarification').click(function() {
    $("#append_tarification").append($("<div>").load("./server/hotels-ajouter-tarifications.php?i="+i).fadeIn(700));
    $('#nb_lignes_tarification').val(i);
    i++;
});

A: I think the problem may be caused by .load and .fadeIn in .append. I haven't tested it but  try the following:
$('a#ajouterTarification').click(function() {

    var $div = $("<div/>"); // First store the new div in a variable

    $("#append_tarification").append($div); // Then append

    $div.load("./server/hotels-ajouter-tarifications.php?i="+i).fadeIn(700); // Do whatever you want with div

    $('#nb_lignes_tarification').val(i);
    i++;
});

A: Try appendTo instead of append.  That way, the div gets into your DOM before you start operating on it.
$('a#ajouterTarification').click(function() {
    $("<div>").appendTo("#append_tarification").load("./server/hotels-ajouter-tarifications.php?i="+i).fadeIn(700);
    $('#nb_lignes_tarification').val(i);
    i++;
});


text:
Q: Modifying a double list with "move all" button I am working on a GUI (that this community has been extremely helpful with so far) and I have reached another important step I need to achieve.
Currently my GUI consists of a JOptionsPane. Inside this pane is a panel that contains two lists and four buttons. Two of the buttons are arrows who's text is ">" and "<". (The buttons are in between both lists.)
Those buttons work correctly. A user can select one of the objects from the first list and then click the > and it will move to the second list and visa versa.
Next I need to add a feature where there is a ">>" button. This will move all the items in the first list to the second. I really have no idea how to handle this part. I am assuming it is some type of while loop although I'm not entirely sure.
First allow me to post the simple snipplet that shows the > button.
buttonin = new JButton("        >         ");
        buttonin.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                int[] fromindex = outputDetails.getSelectedIndices();
                Object[] from = outputDetails.getSelectedValues();

                for(int i=0; i< from.length; i++){
                    output.addElement(from[i]);
                    System.out.println(output);
                }

                for(int i = (fromindex.length-1); i>=0; i--){
                    input.remove(fromindex[i]);
                }
            }
        });

Next I will post the full code in case that is needed to understand what I am trying to achieve. I hope this is enough information for someone to assist me if not I apologize, the actual program is very long and I couldn't think of an easy way to isolate this test case.
public static void displayGUI(){

        int result = JOptionPane.showOptionDialog(null, getPanel(),"JOptionPane Example : ", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, new String[]{"Confirm","Create Return"}, "default");

        if(result == 1){
            initialScreenDecisions="NONE";
            MainWriter.finishedCounter=true;
            System.out.println(MainWriter.finishedCounter);
            while(MainWriter.entryDetails.size()>0){
                MainWriter.entryDetails.remove(0);
            }
            while(output.size()>0){
                output.remove(0);
            }
        }
    }

    private static JPanel getPanel(){

        JPanel panel = new JPanel();
        JPanel panelTop = new JPanel();
        JPanel topButtons = new JPanel();
        JPanel bottomButtons = new JPanel();

        String text = ""
                +"Batch "+MainWriter.batchHeaderCounter+" of "+BatchCounter.BatchTotal+""
                +"
Batch Header:  "+MainWriter.BatchHeader+""
                +"";
        JLabel topLabel = new JLabel(text);

        panelTop.add(topLabel);

        input = new DefaultListModel();
        output = new DefaultListModel();

        String[] shoppingItems = new String[MainWriter.entryDetails.size()];
        shoppingItems = MainWriter.entryDetails.toArray(shoppingItems);

        for(int i = 0; i < shoppingItems.length; i++){
            input.addElement(shoppingItems[i]);
        }

        outputDetails = new JList(input);
        outputDetails.setVisibleRowCount(10);
        outputDetails.setFixedCellHeight(20);
        outputDetails.setFixedCellWidth(400);
        outputDetails.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        JScrollPane list1 = new JScrollPane(outputDetails);

        inputDetails = new JList(output);
        inputDetails.setVisibleRowCount(10);
        inputDetails.setFixedCellHeight(20);
        inputDetails.setFixedCellWidth(400);
        inputDetails.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        JScrollPane list2 = new JScrollPane(inputDetails);

        JPanel buttonPanel = new JPanel();

        buttonin = new JButton("        >         ");
        buttonin.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                int[] fromindex = outputDetails.getSelectedIndices();
                Object[] from = outputDetails.getSelectedValues();

                for(int i=0; i< from.length; i++){
                    output.addElement(from[i]);
                    System.out.println(output);
                }

                for(int i = (fromindex.length-1); i>=0; i--){
                    input.remove(fromindex[i]);
                }
            }
        });
        buttonPanel.add(buttonin);

        buttonout = new JButton("        <         ");
        buttonout.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                Object[] to = inputDetails.getSelectedValues();
                int[] toindex = inputDetails.getSelectedIndices();

                for(int i = 0; i < to.length; i++){
                    input.addElement(to[i]);
                }

                for(int i = (toindex.length-1); i >=0; i--){
                    output.remove(toindex[i]);
                }
            }
        });

        buttonall = new JButton("        >>        ");
        buttonall.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){

                if(initialScreenDecisions.equals("DEFAULT")){
                    JOptionPane.showMessageDialog(null, "You have selected to add all entry details. Please " +
                                                      "\nclick okay on the next scren to confirm or click " +
                                                      "\n'>>' again to cancel the apply all option.");
                    initialScreenDecisions="ADDALL";
                }else if(initialScreenDecisions.equals("ADDALL")){
                        JOptionPane.showMessageDialog(null, "You have canceled the apply all option.");
                    initialScreenDecisions="DEFAULT";
                }else{
                    JOptionPane.showMessageDialog(null, "You must disable the '<<' option before you can use this.");
                }

            }
        });

        buttonnone = new JButton("        <<        ");
        buttonnone.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                if(initialScreenDecisions.equals("DEFAULT")){

                    JOptionPane.showMessageDialog(null, "You have selected to skip the current batch and" +
                                                    "\nomit all of it's entries. Click okay on the next" +
                                                    "\nscreen to confirm or click '<<' again to" +
                                                    "\ncancel the option.");
                initialScreenDecisions="NONE";

                }else if(initialScreenDecisions.equals("NONE")){

                    JOptionPane.showMessageDialog(null, "You have canceled the omit all option.");
                    initialScreenDecisions="DEFAULT";

                }else{
                    JOptionPane.showMessageDialog(null, "You must disable the '>>' option before you can use this.");
                }

            }
        });

        buttonhelp = new JButton("HELP");
        buttonhelp.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                JOptionPane.showMessageDialog(null, "This screen allows you to determine the entry details from" +
                                                    "\nthe current batch that will be included in the final return." +
                                                    "\nSelect the details you wish to include and click the > arrow to" +
                                                    "\nmove them to the right side. Pressing the >> button will" +
                                                    "\ninclude all entry details for the current batch in the final" +
                                                    "\nreturn. Clicking the < button will move a detail back."+
                                                    "\nClick << to omit the entire batch. Use confirm to continue"+
                                                    "\nto the next step or 'create return' to finish the Nacha return"+
                                                    "\nwith all past additions.");
            }
        });

        buttonPanel.setLayout(new BorderLayout());
        topButtons.add(buttonin);
        topButtons.add(buttonall);
        topButtons.add(buttonnone);
        topButtons.add(buttonout);
        bottomButtons.add(buttonhelp);
        buttonPanel.add(topButtons,BorderLayout.NORTH);
        buttonPanel.add(buttonhelp,BorderLayout.SOUTH);

        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));

        bottomPanel.add(Box.createRigidArea(new Dimension(10,0)));
        bottomPanel.add(list1);
        bottomPanel.add(Box.createRigidArea(new Dimension(5,0)));
        bottomPanel.add(buttonPanel);
        bottomPanel.add(Box.createRigidArea(new Dimension(5,0)));
        bottomPanel.add(list2);
        bottomPanel.add(Box.createRigidArea(new Dimension(10,0)));

        panel.setLayout(new BorderLayout());
        panel.add(panelTop,BorderLayout.NORTH);
        panel.add(bottomPanel,BorderLayout.CENTER);
        panel.setOpaque(true);

        return panel;
    }

You can ignore the above >> button contents. Right now it will allow the user to select all of the items in the list it just doesn't visually show the selection. If I get the >> button to move all the items at once then I won't need the extra steps you can see I have implemented.

A: I'm not too sure what all your variable types are, but I think this should work in your ActionListener for >>.
for (int i = 0; i < input.getSize(); i++) {
    output.addElement(input.get(i));
}
input.clear();


text:
Q: vb.net find line that contain in a string If I can find line that contains word in a file
File.ReadAllLines(html).FirstOrDefault(Function(x) x.Contains("something"))

How can I find all lines that contains in a string
for example I made an webresponse
    Dim rt As String = "http://www.somesaite.com"
    Dim wRequest As WebRequest
    Dim WResponse As WebResponse
    Dim SR As StreamReader
    wRequest = FtpWebRequest.Create(rt)
    WResponse = wRequest.GetResponse
    SR = New StreamReader(WResponse.GetResponseStream)
    rt = SR.ReadToEnd

How to find lines that contains in rt ?

A: You could read all the text that the StreamReader gives you, and then you could split that by the Environment.NewLine character(s). Then you should just be able to use the lambda expression you first mentioned (as the File.ReadAllLines() method returns an array of strings).
Dim FoundLine As String = SR.ReadToEnd().Split(Environment.NewLine).FirstOrDefault(Function(x) x.Contains("something"))


text:
Q: Using cascadeType.Merge duplicates my entity I have an entity "Employee" and a @Embeddable class RecycleBin. Now whenever a user deletes anything in the system the the entity class record is duplicated. I know it is because of the cascadeType.Merge i added in the RecycleBin class but if I remove cascadeType.Merge then the system crashes on delete operation giving a server error of "save transient before flushing". I have been stuck in this since two days and i am new to spring. If someone could please help me.
This is my Employee class.
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Version
private Long version;

private String fullName;

private String fatherName;

private String identityCardNo;

@Temporal(TemporalType.DATE)
private Date dateOfBirth;

private String placeOfBirth;

private String nationality;

private String email;

private String phoneNumber;

@Column(columnDefinition = "TEXT")
private String permanentResAddr;

@Column(columnDefinition = "TEXT")
private String presentResAddr;

@Enumerated(EnumType.STRING)
private MaritalStatus martialStatus;

@Enumerated(EnumType.STRING)
private Gender gender;

private String spouseName;

private String spouseOccupation;

private String spouseOrganization;

private String spouseDesignation;

private String numOfDependents;

private String languagesKnown;

private String salary;
private String bonus;
private String allowance;
private String stipend;

@ElementCollection(fetch = FetchType.EAGER)
@Column(name = "jobrole")
@Enumerated(EnumType.STRING)
private List<JobRole> jobRoles;

@Enumerated(EnumType.STRING)
private JobType jobType;

@ElementCollection(targetClass = Privilege.class, fetch = FetchType.LAZY)
@Column(name = "privilege")
@Enumerated(EnumType.STRING)
private List<Privilege> privileges;

// dep auto del
@OneToMany(mappedBy = "substituteTeacher")
private List<TimetableSubstitute> timetableSubstitutes;

// dep manul del
@OneToMany(mappedBy = "createdBy")
private List<SchemeOfWork> createdSchemeOfWorks;

// dep association del
@OneToMany(mappedBy = "createdBy")
private List<CommentBank> createdComments;

// dep manul del
@OneToMany(mappedBy = "teacher")
private List<BatchSubject> teacherSubjects;

// dep auto del
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "employee_campus", joinColumns = { @JoinColumn(name = "employee", referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "branch", referencedColumnName = "id") })
private List<Campus> schoolCampuses;

// dep auto del
@OneToMany(mappedBy = "employee")
private List<CampusEmployeeAttendance> employeeBranchAttendanceList;

// dep auto del
@OneToMany(mappedBy = "employee")
private List<EmployeeAttendance> employeeDayAttendanceList;

// dep association del
@OneToMany(mappedBy = "createdByTeacher")
private List<ProfileForm> teacherCreateProfileForms;

// dep auto del
@ManyToMany(mappedBy = "employees")
private List<Announcement> announcements;

// dep auto del
@OneToMany(mappedBy = "employee")
private List<Notification> notification;

// dep auto del
@OneToOne
private UserLoginAccount employeeLoginAccount;

// dep manul del
@OneToMany(mappedBy = "batchTeacher")
private List<Batch> teacherBatches;

// dep manul del
@OneToOne(mappedBy = "schoolEmployee")
private Parent parent;

@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "employee_qualifications", joinColumns = @JoinColumn(name = "emp", referencedColumnName = "id"))
private List<Qualification> qualifications;

@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "employee_pre_employment", joinColumns = @JoinColumn(name = "emp", referencedColumnName = "id"))
private List<PreEmployment> preEmployments;

@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "employee_memberships", joinColumns = @JoinColumn(name = "emp", referencedColumnName = "id"))
private List<EmpMembership> memberships;

@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "employee_certificates", joinColumns = @JoinColumn(name = "emp", referencedColumnName = "id"))
private List<EmpCertificate> certificates;

@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "employee_references", joinColumns = @JoinColumn(name = "emp", referencedColumnName = "id"))
private List<EmpReference> references;

// dep auto del
@OneToMany(mappedBy = "employee", fetch = FetchType.LAZY)
private List<FileLibrary> empImages;

@Embedded
private RecycleBin recycleBin;

And this is my RecycleBin class.
@Embeddable
public class RecycleBin {

@Temporal(TemporalType.TIMESTAMP)
private Date deleteDate;

@ManyToOne(cascade= CascadeType.MERGE)
private Employee deletedBy;

@Enumerated(EnumType.STRING)
private RecycleBinStatus recycleBinStatus;


text:
Q: How to make images to go out of the div when width is over the max-width? I have a page with a text and images inside it, with a style float:right.
I'd like to set max-width for the text, but let the images to go outside the text.
Is it possible to do it with a pure css, without javascript?
This is how I would like to see it on a normal screen and wide screen:
+----------------------+    +-------------------+--------------+
|                      |    |                   |              |
|  TEXT         TEXT   |    |                   |              |
|              +-------+    |                   |   +-------+  |
|              |       |    |                   |   |       |  |
|              |  IMG  |    |     TEXT          |   |  IMG  |  |
|              |       |    |                   |   |       |  |
|              +-------+    |                   |   +-------+  |
|                      |    |                   |              |
|  TEXT         TEXT   |    |                   |              |
|                      |    |     TEXT          |  BACKGROUND  |
|                      |    |                   |              |
|              +-------+    |                   |   +-------+  |
|              |       |    |                   |   |       |  |
|              |  IMG  |    |                   |   |  IMG  |  |
|              |       |    |     TEXT          |   |       |  |
|              +-------+    |                   |   +-------+  |
|                      |    |                   |              |
|  TEXT         TEXT   |    |                   |              |
|                      |    |                   |              |
+----------------------+    +-------------------+--------------+

                            <-----MAX-WIDTH----->

A: Use CSS3 media queries:
@media screen and (min-width: 600px) {
     .aClass {}
     .anotherClass {}
     /* properties in here only apply when the viewport is wider than 600px */
}

Using this method you can have the text flow around the images by default, but if the viewport is wide then you override that CSS and position the images outside the container div using negative margins or absolute positioning.
More about responsive web design with CSS.

A: style="position:absolute;right:100px;" may give you what you want. Note that you might not need to specify float:right if you have position:absolute.
You should not have img that are inside a div appear outside of that div. The images should be maybe siblings of the div instead of children.


text:
Q: How to make click button to change label text in other form? How do I make it so when I click a button in Form1 (main form), it will open Form2 while also changing a label's text (Label4) as well.
My current code for the button:
Admin objFrmAdmin = new Admin();
this.Hide();
objFrmAdmin.Show();

I don't want to change the showing code for the form I just want to add it so when I clicked the button to open that form it will also change the text on the label in Form2.

A: Change Admin form constructor, something like this:
//add parameter text
public Admin(string text)
{
    InitializeComponent();
    //change label 4 text
    this.Label4.Text = text;
}

change the way you're initalizing Admin form like this:
Admin objFrmAdmin = new Admin("text to show on label");
this.Hide();
objFrmAdmin.Show();

EDIT: another way to achieve that is to make public method on admin form and call it. So, leave constructor without parameter, like it was and make public method on your Admin form, like this:
public void ChangeText(string text)
{
    this.Label4.Text = text;
    //put other code here if needed, ie. hide buttons or something like that
}

Now, just call that method after you initialized your Admin form.
Admin objFrmAdmin = new Admin();
this.Hide();
objFrmAdmin.ChangeText("text to show");
objFrmAdmin.Show();

A: You use the object heirarchy to change the label directly.
Admin objFrmAdmin = new Admin();
this.Hide();
objFrmAdmin.lblLabelToChange.Text = "Your Test Here";  //<= this line.
objFrmAdmin.Show();

If the label doesn't appear in intellisense, then you probably need to make it public.  An alternative is to use the constructor, and pass the new test:
//Constructor for Admin form
public Admin(string newLabelText)
{
    this.lblLabelToChange.Text = newLabelText;
}

Call it via:
Admin objFrmAdmin = new Admin("The new text");


text:
Q: Django delete without calling signals I use signals for things that should always be done when an object is deleted, saved, updated, etc. However, there are times when I don't want to call my save signals, so I use
Model.objects.filter(id=instance.id).update(field=value)
instead of the instance's save method:
instance.save()
In the case of deleting objects, there are also times when I don't want to call the delete signals, but I haven't found a way to avoid calling them. Is there a way??
UPDATE:
I'm using django 1.6.2 and calling the delete method like this:
Model.objects.filter(id=instance.id).delete()
on the queryset still still calls the delete signal.

A: There is unsafe and undocumented way which probably can change between versions and also can lead to unexpected consequences which will be hard to debug.
This is a hack that probably you don't want to use but.... it's possible.
qs = Model.objects.filter(id=instance.id)
qs.order_by().select_related(None)._raw_delete(qs.db)

If you have any related objects to this one it will probably fail with database error because records will not be deleted automatically by Django

A: In the place where you don't want signals to be called, you have to disconnect them, run you code and then reconnect them again. You can take a look on how mute_signal decorator is implemented in FactoryBoy or just use (but it's basically intended for django tests)

A: You can do this.
Model.objects.filter(id=instance.id).delete()

A: Try using raw SQL and don't resist it. It is always a powerful ultimate weapon you could use.
from django.db import connection

with connection.cursor() as cursor:
    cursor.execute(f'DELETE from tbl_model where id={instance.id}')


text:
Q: When to really focus on performance? We've just finishing up the first release of a database driven web application, which is now in regression testing. The application has an advanced search with many different filtering criteria. When the search is first used with only the 3(of 28) minimum required search criteria it takes like 15-20 secs to calculate and retrieve the data for the page to load.
This happens only the first time the search(uses a stored proc) is run. The search thereafter take 2-6 secs.
The stored procedure has medium complexity around 1500 - 2000 lines. I would like to get it down to run the first time to 6 secs and thereafter like 1-2 secs but I can't seem to find the  time to make it faster.
My question is, is this acceptable for users if it is only slow the first time the search is run? Has anyone else had a similar experience with creating advanced searches? What was your solution?

A: You can do several things:
Create views for performance. A view is a contract of intention that tells the RDBMS "I will be running this query very often". When you do that the RDBMS optimizes the access to this data.
Create views for simplicity and tuning. You create views in order to split the big solution into smaller solutions. This way you can measure exactly where the bottleneck is and try to improve the problematic areas.
Create denormalized tables ( materialized views ). Sometimes it pays back to create summarized tables in order to make certain reports faster, especially of data that is not transactional.
Create a non-transactional database or datawarehouse for queries. Most RDBMS has ways of tuning a special database for queries when this databases is not transactional, ie, it's not being hit continuosly with inserts or updates. The whole set of tuning configurations if different when the database has this purpose. It's more efficient than a general purpose database.
Put most queried tables in faster disks. Move most queried tables in tablespaces located in better, faster disks and better connections (SAN). Move not so important tables to slower, cheaper disks and not so fast connections.
Use structure programming techniques to split your stored procedures into smaller ones, so you can keep complexity at bay. That way you can concentrate better on improving performance once you don't have all the complecity in your face all the time.
Use queries with binding variables avoiding concatenated ones. That way the RDBMS is able to cash them in the query area and they run faster because you save parsing time and planning time.
Remember that your DBA is your friend, and he/she can do a lot to improve database performance. Don't rely solely on your programming skills. You are not alone.

A: "Is it acceptable" is not a technical question; it's a product question.  In some products, 2-6 seconds might be considered hideously slow while in others, 15-20 seconds might be pretty zippy.  How fast are competing products?  How fast are similar products?  What percentage of customers will see the long original query vs. the faster cached query?  If you expect ten million queries, one slow one will be trivial.  If you expect ten, then not so much.  Answers to these questions will tell you if you need to optimize.
One technical solution you might try would be to prewarm these queries.  It isn't clear to me exactly how many possible queries there are, but if you have a low enough number of these "slow" queries, just immediately run them after you deploy so no actual customer sees them.  If there are an extremely large number of possible queries, then maybe run those that you find are most common.


text:
Q: What is the expected payoff in the following matching pennies game So we have the following matching penny game
$\begin{bmatrix}
\ & L & R \\
T & (1,-1) & (-1,1)\\
B & (-1,1) & (1,-1)
\end{bmatrix}$
Let $p_1$ denote the row player, $p_2$ denote the column player.
Now suppose there is an event, $D$, which players assess with distinct subjective
probabilities: $p_1(D) = 2/3; p_2(D) = 1/3$. Suppose players bindingly agree to the
following strategies: $2$ plays $L$ and $1$ plays $T$ if $D$ occurs and they play $(B,R)$ otherwise. What is the expected payoff for both players in this case. I am expecting it to be $1/3$, but I cant figure it out.
Any helps or insight is appreciated.

A: Since $(T,L)$ and $(B,R)$ yield the same payoffs $(1,-1)$, the probabilities are irrelevant – a strategy pair with payoffs $(1,-1)$ is certain to be played, so the payoffs will be $(1,-1)$.


text:
Q: Does a SAML application store the state while creating a request (Okta's document says it doesn't)? Okta's official document states that a SAML Service Provider does not store any state:
https://developer.okta.com/docs/concepts/saml/#planning-for-saml

The Service Provider doesn't know if the Identity Provider will ever complete the entire flow. Because of this, the Service Provider doesn't maintain any state of any authentication requests generated.

However, I also read that the SAML Application will generate a request ID which is unique to that particular request. And the SAML response will contain this same request ID which the application will use to figure out which request it corresponds to.
There is a contradiction between Okta's doc and the SAML concept. The application is storing the state. Is Okta's doc inaccurate or am I missing some concept over here?

A: I think Okta's document is misleading. As you say, one of the checks that a service provider should make is that the InResponseTo field in the SAML response matches the SAML authn request's ID. This is essentially state information the SP must remember so it can perform this check when the SAML response is received. Our SAML implementation certainly maintains state information and I would imagine most, if not all, implementations would.


text:
Q: Change colors in scss depending on row data in React page I have a grid in a react page and each row is styled with properties from a scss file.  I want to be able to change the color of certain things like row background, border, and a few other things based on a color from the row JSON data.  I don't want to maintain 8 scss files (one for each color).  I want to pass in a color and have it change the values in the scss file.  I'm not sure how to pass the value from React to the scss file.
My main .scss file
@import 'variables.scss';

.memberRow{
    width:99%;
    height:55px;
    border:solid 2px $color-member4;
    margin:3px;
    display: flex;
    flex-direction: row;
    background-color: $color-member4-bg;
}

My variables.scss file
$color-member1: #65D3E3;
$color-member2: #ED7425;
$color-member3: #F7BC20;
$color-member4: #34B66B;
$color-member5: #9675CC;
$color-member6: #7B8A97;
$color-member7: #2962FF;
$color-member8: #F48FB1;

$color-member1-bg: #65D3E355;
$color-member2-bg: #ED742555;
$color-member3-bg: #F7BC2055;
$color-member4-bg: #34B66B55;
$color-member5-bg: #9675CC55;
$color-member6-bg: #7B8A9755;
$color-member7-bg: #2962FF55;
$color-member8-bg: #F48FB155;

A: Personally I would do something like:
@import 'variables.scss';

.memberRow{
    width:99%;
    height:55px;
    margin:3px;
    display: flex;
    flex-direction: row;

    &.color1 {
       border: solid 2px $color-member1;
       background-color: $color-member1-bg;
    }
    &.color2 {
       ...
    }
}

Or extending "base class":
.color1 {
   @extend .memberRow;
   border: solid 2px $color-member1;
   background-color: $color-member1-bg;
}


text:
Q: Tabs show too much content only on load, self fixes after click I have a tab set up in a Bootstrap modal that loads with tab 2 content shown directly below tab 1's content, and I can't for the life of me figure out why.  I know it's not a problem with the modal, or a php misstep, as I was able to recreate the problem in this fiddle after taking most of the content out.
Now the strange thing is, once you click on another tab the whole thing works just as it should.  No extra content, even if you go back to tab 1.
This is the shortened version of my code:

$(document).ready(function () {

        $('ul.tabs li').click(function () {
            var tab_id = $(this).attr('data-tab');

            $('ul.tabs li').removeClass('current');
            $('.tab-content').removeClass('current');

            $(this).addClass('current');
            $("#" + tab_id).addClass('current');
        })

    })
ul.tabs {
    margin: 0px;
    padding: 0px;
    list-style: none;
    font-size: 1em;
    font-family: 'Roboto Condensed', sans-serif;
    font-weight: bold;
}

ul.tabs li {
    background: none;
    color: #222;
    display: inline-block;
    padding: 10px 15px;
    cursor: pointer;
}

ul.tabs li.current {
    background: #eaeaea;
    color: #222;
    border-radius: 5px 5px 0 0;
}

.tab-content {
    display: none;
    background: #eaeaea;
    padding: 15px;
    font-size: 1em;
    font-family: 'Roboto Condensed', sans-serif;
    border-radius: 5px 0 5px 5px;
}

.tab-content.current {
    display: block;
    overflow: auto;
    width: 100%;
    margin-bottom: 20px;
    min-height: 300px;
}

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×
    </button>

Job 123

   body is here....Tabs down below-

Outlook

Parts On Order

Labor

Parts

Notes

            Tab 1 Conent

            Tab 2 content

            Tab 3 content

            Tab 4 Content

            Tab 5 content

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <a href="editjob.php?id=<?php echo $id; ?>">
            <button type="button" class="btn btn-warning pull-left">Edit Job</button>

        <a href="printjob.php?id=<?php echo $id; ?>">
            <button type="button" class="btn btn-primary">Print Job</button>

Any ideas on what could be causing this?

A: You've given the "current" class to both tab-1 and tab-2.  Remove it from tab-2 and it will display correctly.
Fiddle

    ...

A: The click handler determines what happens when you click a tab, but it doesn't run right away.
You can fix this by explicitly triggering a click on the first tab after you've defined the click handler:
$(document).ready(function () {
  $('ul.tabs li')
    .click(function () {
      var tab_id = $(this).attr('data-tab');

      $('ul.tabs li').removeClass('current');
      $('.tab-content').removeClass('current');

      $(this).addClass('current');
      $("#" + tab_id).addClass('current');
    })
    .first()
    .click();
});

Working Fiddle


text:
Q: is there a way I can click 2 submit buttons by clicking one of them? ok this sounds weird, but i have two submit buttons.
</input type="submit" name="btn1" id ="btn1"/>

</input type="submit" name="btn2" id ="btn2"/>

is there a way I can bind both to click together when I click one of them?
thanks.

A: You can using javascript
follow http://www.javascript-coder.com/javascript-form/javascript-form-submit.phtml
you simply submit the second form in the function

A: You can write a wrapper for the second method.
onclick = "CallBoth()";

onclick = "CallOne()";

function CallBoth()
{
  ...

  return CallOne();
}

function CallOne()
{
  ...
  return whatever;
}

A: Using jQuery :
$(document).ready(function(){
    $('input[name="btn1"], input[name="btn2"]').click(function(){
        $('#myform').trigger('submit');
    });
});

When you hit either btn1 or btn2, your form ID #myform will submit.
But the best way to do it using jQuery is using this code :
$(document).ready(function(){
    $('.submit_form_1').click(function(){
        $('#myform').trigger('submit');
    });
});

and add to every button you want to use as a "submit form button for your form" the class .submit_form_1. Change it like you want.


text:
Q: Kicad: How to give nets / wires multiple names I'm designing a switching power supply using a BD9G101G step-down regulator. The datasheet is here: http://rohmfs.rohm.com/en/products/databook/datasheet/ic/power/switching_regulator/bd9g101g-e.pdf.
If you look on page 18 there is a simplified board layout (fig. 47).
There are two areas which need special consideration: SGND and POWERGND. Logical they are all on GND level but need some special routing.
It would be very helpfull if I could somehow name the nets in Kicad schematic/pcbnew accordingly.
I tried designing some kind of net-seperator symbol (which works) but I can't find/make a footprint which I can place on the layout without getting trouble.
So what would be a way to do this?
EDIT: Removed screenshot because it was leading to far away from the actual question.
SOLUTION: Francois was first to mention net-ties (and why not to use them). But special thanks to Dennis :)

A: Alright so the figure you are referring to is a bit confusing. Rohm isn't actually requiring 2 separate grounds on your board but pointing out which ground shape is used for switching current return path (POWER GND) and which is intended to be "low-noise" ground for feedback node (SGND). In your design, these 2 shapes should refer to one common ground (GND) and be connected using the vias shown in figure and back-plane (not shown). The reason why they have annotated them differently is that the SGND and PGND shape are actually two separate shapes on the layer shown (top) and that PGND currents shouldn't try to return through SGND as there is no path out.
In most application, it is very highly recommended to use one unique return path (= GND) for all currents, else you end-up creating unnecessary ground return loops which could cause a lot of headaches for other circuits (you do not want to go down this path).
The only times you may consider splitting the ground return paths could be, for instance, in very specific application where you have a highly sensitive/low-noise circuit (example: analog, audio or RF circuit) and a high-risk of exposure to ground noise/bounce. In this case, you can create a return path for your general and higher-current ground return to avoid the low-noise circuit and tie the 2 grounds closer to the source (eg. power connector in most case) using a net tie or jumper resistor. Doing this, you are basically forcing the return currents to follow a defined path, however it takes much more effort to implement as you have to consider all potential signals shared between the low-noise circuit and the rest of the board and be able to keep references when jumping from one ground to the other (which could potentially void the ground separation if not done with ultra-care), this is even more important for high-speed signals (example: SPI / I2S). It's really a big mess to separate ground return paths, only do it if you really have to and know what you are doing.
To come back to your initial question, I am only aware of 2 options to tie 2 nets together which are jumper resistors and net ties. However, do not use them here :)

A: I guess the thing you're looking for is a net tie. Its availible as component and has some footprints. If you want to do your own version with right size, its just a copper line with 2 "pins".
EDIT:
For the case near A7/U2 this could be a solution:

With the shematic symbol "Net-Tie_2", where Pin 1 goes to GND and pin 2 to SGND. Just set the pad width in the footprint editor to your tracewidth. In this example footprint I used 2 SMD pad and one through hole.


text:
Q: Ping doesn't work I want to scan my local network with my application, so I tried to ping all local IP but my code work only for the local IP of my android device.
This is my function :
int timeout=10000;
for (int i = 0; i < 256; i++) {
        String host = "192.168.1." + i;
        try {
            if (InetAddress.getByName(host).isReachable(timeout)) {
                System.out.println(host + " is reachable");
                Log.i("host", host);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output : "host: 192.168.1.10" This is the Local IP of my device.
My manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="...">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

A: Here you are wrong
String host = "192.168.1." + i; /* You missed the dot(.) symbol after 1 */
You should move these three lines above application. It should should like below:
 <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>


text:
Q: play a video file after gnome login I want to see a video clip when I start using computer (and after login into Gnome) automatically. how can I do that in Linux (Manjaro)?
I tried to make this by Systemd service but I was not successful.
this is my Systemd service file:
[Unit]
Description=play video clip

[Service]
Type=oneshot
RemainAfterExit=true
StandardOutput=journal
ExecStart=/usr/bin/mpv /home/username/Videos/video.mp4 --vo=gpu --ao=alsa
User=username
Environment=DISPLAY=:1

[Install]
WantedBy=default.target

A: You can make a .desktop file, which plays the Video (that same command from the system file) and put that in the autostart directory in your home folder.


text:
Q: CSS adjacent disabled selector not working I'm trying to update the background color of button if input[type="file"] is disabled but it is not working.
Any solution?

.btn-file {
  display: inline-block;
  margin: auto 10px;
  vertical-align: top;
  width: auto;
}

.btn-file input[type="file"] {
  display: none;
}

.btn-file input[type="file"]:disabled+.custom-file-upload {
  opacity: 0.5;
}

.btn-file .custom-file-upload {
  background-color: #6692b0;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
  color: #fff;
  display: inline-block;
  padding: 10px 18px;
  cursor: pointer;
  width: auto;
}

       Upload Logo

  <input type="file" id="FileUpload1" class="" disabled="">

https://jsfiddle.net/fnkmmLbs/1/

A: The problem is with css + selector that says the next sibling, but the required element is previous not next. Switch order. <input> for .

  <input type="file" id="FileUpload1" class="" disabled>

     Upload Logo


text:
Q: Convergence in Distribution of a double sequence Suppose I have a sequence of random variables $X_{nm}$ such that I know that $X_{nm} \xrightarrow{D} X_n$ as $m\rightarrow \infty$ at each fixed $n$, and for the sequence $X_n$. I also know that $X_n \xrightarrow{D} X_0$ as $n\rightarrow\infty$.
Is it possible for me to say that there exists a sufficiently slowly increasing sequence $N = n(m)$ such that $X_{Nm} \xrightarrow{D} X_0$ as $m\rightarrow \infty$?


text:
Q: Upload email from nnml to Gmail (or IMAP) I have just found some tens of thousands of old emails in a Linux subdirectory which I would like to upload to GMail.   GMail has an IMAP interface, so if your answer is IMAP-specific, that's perfectly fine.
The emails are stored in nnml format which is sequentially numbered files, one per message.   They are not mbox files (that is, there is no "^From " line at the top of the file and therefore no need to escape that in the body).  I think these emails were originally written there by either Mutt or Gnus (very likely both, at various times).
What programs (or libraries) exist that do this?


text:
Q: Downloading Excel file in Internet Explore through selenium I have to automate a case in which I have to download an excel file using selenium ide.I have done this in firefox by using custom profile feature which automatically download file and save it into a user defined folder. To do the same in Internet explorer, is there any thing in IE like custom profile and preferences? how do I prompt IE to automatically download a file..I am using java for automation..Kindly help..

A: No, you can't do it easily in IE, there's no profile to configure.
That said, you can try:

*

*downloading the file directly using this (or any other similar WebDriver-friendly tool), if you can. That will totally cut IE out of the process.

*see How to download and save a file from Internet using Java? about the same thing, just generic Java and not WebDriver.

*if everything fails, you can try blindly pressing Enter after clicking the download, Robot helps with this. But you can't really specify the folder.


text:
Q: What is the global length variable (window.length)? I have just observed that every page has length global variable.
What does this variable represent? Is it somehow related to how many iframes/frames are loaded on page?
It'd be happy if a doc reference is provided.

For example, on Chrome new tab page its value is 17 and here, on StackOverflow it is 0.

A: window.length

Returns the number of frames (either frame or iframe elements) in the window.

Example
if (window.length) {
  // this is a document with subframes
}

MDN Reference
Note: No part of this answer comes from me. It all comes from the referred source.

A: Yes, it's how many frames (including iframes) are in the current window:
https://developer.mozilla.org/en-US/docs/Web/API/Window.length
W3 specification:
http://www.w3.org/html/wg/drafts/html/master/browsers.html#accessing-other-browsing-contexts


text:
Q: Why does everyone copy the src of app in the php-fpm and nginx containers? I make an app in PHP(Laravel) that runs in an old virtual server. My idea is to move the app to containers.
I read a lot of tutorials, and all create three containers.

*

*nginx(as a dispacher)

*php-fpm

*db

its ok, but I still don't understand this.
If the Nginx is only to pass the request to the php-server, why have the app source?
tkx


text:
Q: ReporteRS not obeying template bullets I was trying to create a presentation using the R package ReporteRS. The unordered lists seems to obey only the limited options set by ReporteRS. Is there anyway to make get ReporteRS to obey the defaults within a template?

A: The solution to this, while not very elegant is to reset the slides using either VBA or VBScript. Below is my solution to reseting all the slides using VBScript. Simple drag and drop a file onto the script saved with a .vbs extension.
Dim inputFile
Dim objPresentation

inputFile = WScript.Arguments(0)
Set objPPT = CreateObject("PowerPoint.Application")
objPPT.Visible = True
objPPT.Presentations.Open inputFile
Set objPresentation = objPPT.ActivePresentation

slideCount = objPresentation.Slides.Count

For i = 1 to slideCount
    objPresentation.Slides(i).Select
    objPresentation.Application.CommandBars.ExecuteMso("SlideReset")
Next

objPresentation.Save
objPPT.Quit


text:
Q: Rails I18n set_locale I want to set the locale by the clients browserlocale request.env['HTTP_ACCEPT_LANGUAGE'] and by the URL.

*

*If a user visits a URL (e.g.: myapp.com) it should check the HTTP_ACCEPT_LANGUAGE and redirect to  the right URL (e.g.: myapp.com/en - if the browserlocale is en)

*If a user then chooses a different language via a language-menu it should change the URL to e.g.: myapp.com/de.
Here is my what I got so far:
class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :set_locale

private

  # set the language
  def set_locale
    if params[:locale].blank?
      I18n.locale = extract_locale_from_accept_language_header
    else
      I18n.locale = params[:locale]
    end
  end

  # pass in language as a default url parameter
  def default_url_options(options = {})
    {locale: I18n.locale}
  end

  # extract the language from the clients browser
  def extract_locale_from_accept_language_header
    browser_locale = request.env['HTTP_ACCEPT_LANGUAGE'].try(:scan, /^[a-z]{2}/).try(:first).try(:to_sym)
    if I18n.available_locales.include? browser_locale
      browser_locale
    else
      I18n.default_locale
    end
  end
end

In my routes file I got:
Myapp::Application.routes.draw do
  # set language path
  scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do

    root :to => "mycontrollers#new"
    ...

  end

  match '*path', to: redirect("/#{I18n.locale}/%{path}"), constraints: lambda { |req| !req.path.starts_with? "/#{I18n.default_locale}/" }

  match '', to: redirect("/#{I18n.locale}")
end

The Problem is that the routesfile gets executed first and the HTTP_ACCEPT_LANGUAGE has no effect, because the url-param already got set when it comes to the controller.
Does anyone has a solution for that? Maybe solve it by a middleware?

A: I'd change a few things in your routes.
First:
scope :path => ":locale" do
  ...
end

Second:
I see what you are trying to do here:
match '', to: redirect("/#{I18n.locale}")

It seems redundant though.
I'd get rid of that line and just modify the set_locale method, like this:
# set the language
def set_locale
  if params[:locale].blank?
    redirect_to "/#{extract_locale_from_accept_language_header}"
  else
    I18n.locale = params[:locale]
  end
end


text:
Q: Google Tag Manager (GTM) - "HTML" tag injection by client We provide an ecommerce checkout on a subsection of our website for example:

example.com/products,
example.com/checkout,
example.com/confirmation

For just those sections of our site we allow our client to add their own Google Tag Manager (GTM) tag.  We've blacklisted the "HTML" tag because it allows arbitrary javascript and can be updated at any point.
var dataLayer = [{ 'gtm.blacklist': ['html'] }];

The business/marketing departments want me to allow it now.  Is any safe way to allow the "HTML" tag that doesn't involve moving everything to a third party domain?

A: There is no safe, or for that matter performant, way to use custom HTML tags or custom Javascript variables (the ones with the anonymous functions). Javascript code therein is run through eval, and can do anything that standard Javascript code can do (and given that the code runs in page context, it can basically do anything).
That is after all the reason Google created custom templates with Sandboxed Javascript that runs dangerous functions through secured APIs.
Do not allow this, and if they make you, keep a paper trail. Even if nobody will exploit this maliciously (which remains to be seen), somebody will sooner or later break the page by incompetence, so it is better to be covered.


text:
Q: Difference between "Cannot insert duplicate key row in object" vs "Violation of UNIQUE KEY constraint" Is it the same sql exception when we get "Violation of UNIQUE KEY constraint 'XXXXXXX'" vs "Cannot insert duplicate key row in object 'dbo.XXXXXX' with unique index 'XXXXXXX'".
In my serverside code we used to handle this with like following:
catch (SqlException sqlEx)
{
  if (sqlEx.Message.Contains("Violation of UNIQUE KEY constraint 'XXXXX'"))
  {
    .....
  }
}

But now the sql server is not prompting the error "Violation of UNIQUE KEY constraint 'XXXXX'", instead it's just saying "Cannot insert duplicate key row in object 'dbo.XXXX' with unique index 'XXXXXX'."
Is there a way in the configuration of MSSQL that I get a descriptive sql exception and get the text "Violation of UNIQUE KEY constraint" back?

A: The first error happens when you attempt to insert a row that violates a unique constraint on a table.
The second error happens when the row violates a unique index.
It's a subtle difference and frankly, I don't really know why there are two different errors for that, especially considering that a unique constraint is implemented in SQL Server using a unique index.
Anyway, I wouldn't use the error message as an indication of what error you've got. Instead, I would check the error number, exposed in the SqlException class as an int property named - surprise surprise - Number.
You can get a list of all error messages and their relevant numbers by querying sys.messages.
I've done this with a like predicate on text to get the relevant errors for your question:
SELECT message_id, [Text]
FROM sys.messages
WHERE [Text] LIKE '%Cannot insert duplicate key%'

Which returned:
message_id  Text
2601        Cannot insert duplicate key row in object '%.*ls' with unique index '%.*ls'. The duplicate key value is %ls.
2627        Violation of %ls constraint '%.*ls'. Cannot insert duplicate key in object '%.*ls'. The duplicate key value is %ls.

(And thanks to Larnu's dupe suggestion, I found the link for Database Engine Errors, but It's faster to query the database than to load that page...)
So, change your c# code in the catch block to
// Cannot insert duplicate key..., Violation of UNIQUE KEY...
if (new int[] {2601, 2627}.Contains(sqlEx.Number))
{
  ....
}


text:
Q: Lost my reference to Microsoft.InteropFormTools in a VB.NET 2008 project I've got an older VB.NET 2008 project, which uses Crystal Reports.  In order to access the .rpt files I used Microsoft.InteropFormTools assembly.  This has worked OK for a number of years.  What this does is allows the user to specify what amounts to parameters to the reports in the Crystal Reports, and then click a button and out prints the report.  (The user is not interested in previewing the report, so it prints directly to the printer, using Crystal.)  The one problem, which I've never been able to figure out, is that sometimes (how, and under what circumstances I don't know, because I can reliably reproduce the error) loading the Crystal Report will cause an error flag to come up.  Next Crystal will insist that the user enter parameters to the report before it previews them.  OF course the users don't know what's going on, so what we've done in the past is just have the user start it over again, and Crystal normally is happy and sends the report to the printer.
However, we've got new users coming on board to do this, and they're not as forgiving. When I wrote this app 4 years ago, I let the CPU be "Any CPU".  I'm wondering if that could be the root of my problems with these Crystal reports not coming out.  So, I've gotten into the project, and changed it from "Any CPU" to "x86", which really is more appropriate, especially since our old version of Crystal is 32-bit.  However, now that I've done that I've got a new error message popping up.  Visual Studio 2008 is telling me that, "The system cannot find the reference specified".  In this case the missing reference is Microsoft.InteropFormTools.  No other changes have happened to this application in 3 years, besides my changing the project configuration from "Any CPU" to "x86".  Could that be what's causing it to not be able to find the path to Microsoft.InteropFormTools?


text:
Q: Linha tracejada apenas css? alguém sabe como fazer esta linha tracejada apenas com css? já tentei com imagens porém não consegui obrigado!

A: Se quer o traço da forma colocada na imagem da pergunta, você pode criar uma classe com os pseudo-elementos ::before e ::after:

/* tirei o underline do "a" apenas para exemplificar no resultado*/
a{
   text-decoration: none;
}

.trasso{
   position: relative;
}

.trasso::before,
.trasso::after{
   content: '';
   border-bottom: 2px solid #090;
   position: absolute;
   top: 100%;
}

.trasso::before{
   width: 5px;
   left: 0;
}

.trasso::after{
   width: 30px;
   left: 10px;
}

Conheça o projeto

   Conheça o projeto

A: Da para fazer com linear-gradient

.linha {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    color: #48958C;
    font-size: 2.5rem;
    position: relative;
}
.linha::after {
   content: '';
   position: absolute;
   width: 6rem;
   height: 0.2rem;
   top: 100%;
   left: 0.25rem;
   background: linear-gradient(to right,#48958C 0%, #48958C 15%, transparent 15%, transparent 30%, #48958C 30%)
}

Conheça o projeto


text:
Q: Saved data to device's local storage is cleared after closing app in production I created React-native app for tourism purpose using Expo. So app checks if device have an internet connection. If so, app downloading all data from cloud and save it to device local storage. If not, then app using old data saved previously to local storage, when device had an internet connection.
The problem is, that when app is closing, local storage is cleared automatically, but it shouldn't. The problem exist only in production and on both iOS and Android devices. Both devices have enough space in memory.
How to prevent device's local storage from clearing automatically?
To handle local storage I'm using @react-native-async-storage/async-storage package.
UPDATE:
app.jsfile. The only place where data is downloaded and added to local storage.
import * as SplashScreen from 'expo-splash-screen'
import { useEffect, useState } from 'react'
import * as Network from 'expo-network'
import { collection, getDocs, query, where } from 'firebase/firestore'
import { db, storage } from './firebase'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { NavigationContainer } from '@react-navigation/native'
import { createNativeStackNavigator } from '@react-navigation/native-stack'
import Languages from './screens/language'
import Home from './screens/home'
import { getDownloadURL, ref } from 'firebase/storage'
import * as FileSystem from 'expo-file-system'
import AllObjectsCategories from './screens/allObjectsCategories'
import ObjectCategory from './screens/objectCategory'
import Object from './screens/object'
import ObjectMap from './screens/objectMap'
import AllRoutes from './screens/allRoutes'
import Route from './screens/route'
import RouteObjects from './screens/routeObjects'
import RouteMap from './screens/routeMap'
import { changeFilename } from './globalFunctions/changeFilename'

const Stack = createNativeStackNavigator()

export default function App() {
  const [loadedData, setLoadedData] = useState(false)
  const [selectedLanguage, setSelectedLanguage] = useState(null)

  useEffect(() => {
    const getData = async () => {
      await SplashScreen.preventAutoHideAsync()
      const notworkStatus = await Network.getNetworkStateAsync()

      const deleteOldFiles = new Promise(async (resolve) => {
        if (notworkStatus) {
          await FileSystem.deleteAsync(
            FileSystem.documentDirectory + 'images',
            {
              idempotent: true
            }
          )
          resolve()
        } else {
          resolve()
        }
      })

      Promise.all([deleteOldFiles])
        .then(async () => {
          const getAllObjects = new Promise((resolve) => {
            if (notworkStatus) {
              getDocs(
                query(
                  collection(db, 'lankytini_objektai'),
                  where('data.published', '==', true)
                )
              )
                .then(async (snap) => {
                  let array = []
                  let filesList = []

                  snap.forEach((element) => {
                    let data = JSON.stringify(element.data())
                    data = JSON.parse(data)

                    array = [...array, data.data]

                    const files = {
                      id: data.data._id,
                      files: [data.data.main_image, ...data.data.gallery_images]
                    }

                    filesList = [...filesList, files]
                  })

                  try {
                    const snapString = JSON.stringify(array)
                    await AsyncStorage.setItem('@tourist_objects', snapString)
                    resolve(filesList)
                  } catch (error) {
                    console.warn(error)
                    resolve(filesList)
                  }
                })
                .catch((error) => {
                  console.warn(error)
                  resolve([])
                })
            } else {
              resolve([])
            }
          })

          const getAllRoutes = new Promise((resolve) => {
            if (notworkStatus) {
              getDocs(
                query(
                  collection(db, 'marsrutai'),
                  where('data.published', '==', true)
                )
              )
                .then(async (snap) => {
                  let array = []
                  let filesList = []

                  snap.forEach((element) => {
                    let data = JSON.stringify(element.data())
                    data = JSON.parse(data)

                    array = [...array, data.data]

                    const files = {
                      id: data.data._id,
                      files: [data.data.main_image, ...data.data.gallery_images]
                    }

                    filesList = [...filesList, files]
                  })

                  try {
                    const snapString = JSON.stringify(array)
                    await AsyncStorage.setItem('@routes', snapString)
                    resolve(filesList)
                  } catch (error) {
                    console.warn(error)
                    resolve(filesList)
                  }
                })
                .catch((error) => {
                  console.warn(error)
                  resolve([])
                })
            } else {
              resolve([])
            }
          })

          await Promise.all([getAllObjects, getAllRoutes])
            .then(async (results) => {
              const touristObjectsFiles = results[0]
              const routesFiles = results[1]

              const downloadTouristObjectsImages = new Promise(
                async (resolve) => {
                  if (touristObjectsFiles.length > 0) {
                    const promises = touristObjectsFiles.map(
                      (touristObject) => {
                        return new Promise((resolve) => {
                          const filesPromises = touristObject.files.map(
                            (file) => {
                              return new Promise(async (resolve) => {
                                if (file !== '') {
                                  await getDownloadURL(
                                    ref(
                                      storage,
                                      `/images/objects/${touristObject.id}/${file}`
                                    )
                                  )
                                    .then(async (url) => {
                                      const fileReference = `${FileSystem.documentDirectory}images/objects/${touristObject.id}`

                                      await FileSystem.makeDirectoryAsync(
                                        fileReference,
                                        {
                                          intermediates: true
                                        }
                                      )

                                      await FileSystem.downloadAsync(
                                        url,
                                        `${fileReference}/${changeFilename(
                                          file
                                        )}`,
                                        {
                                          sessionTyle:
                                            FileSystem.FileSystemSessionType
                                              .BACKGROUND
                                        }
                                      )
                                        .then((uri) => {
                                          resolve()
                                        })
                                        .catch((error) => {
                                          console.warn(error)
                                          resolve()
                                        })
                                    })
                                    .catch((error) => {
                                      console.warn(error)
                                      resolve()
                                    })
                                } else {
                                  resolve()
                                }
                              })
                            }
                          )

                          Promise.all(filesPromises)
                            .then(() => resolve())
                            .catch((error) => {
                              console.warn(error)
                              resolve()
                            })
                        })
                      }
                    )

                    Promise.all(promises)
                      .then(() => resolve())
                      .catch((error) => {
                        console.warn(error)
                        resolve()
                      })
                  } else {
                    resolve()
                  }
                }
              )

              const downloadRoutesImages = new Promise(async (resolve) => {
                if (routesFiles.length > 0) {
                  const promises = routesFiles.map((touristObject) => {
                    return new Promise((resolve) => {
                      const filesPromises = touristObject.files.map((file) => {
                        return new Promise(async (resolve) => {
                          if (file !== '') {
                            await getDownloadURL(
                              ref(
                                storage,
                                `/images/routes/${touristObject.id}/${file}`
                              )
                            )
                              .then(async (url) => {
                                const fileReference = `${FileSystem.documentDirectory}images/routes/${touristObject.id}`

                                await FileSystem.makeDirectoryAsync(
                                  fileReference,
                                  { intermediates: true }
                                )

                                await FileSystem.downloadAsync(
                                  url,
                                  `${fileReference}/${changeFilename(file)}`,
                                  {
                                    sessionTyle:
                                      FileSystem.FileSystemSessionType
                                        .BACKGROUND
                                  }
                                )
                                  .then(() => {
                                    resolve()
                                  })
                                  .catch((error) => {
                                    console.warn(error)
                                    resolve()
                                  })
                              })
                              .catch((error) => {
                                console.warn(error)
                                resolve()
                              })
                          } else {
                            resolve()
                          }
                        })
                      })

                      Promise.all(filesPromises)
                        .then(() => resolve())
                        .catch((error) => {
                          console.warn(error)
                          resolve()
                        })
                    })
                  })

                  Promise.all(promises)
                    .then(() => resolve())
                    .catch((error) => {
                      console.warn(error)
                      resolve()
                    })
                } else {
                  resolve()
                }
              })

              Promise.all([downloadTouristObjectsImages, downloadRoutesImages])
                .then(async () => {
                  try {
                    const language = await AsyncStorage.getItem(
                      '@selected_language'
                    )
                    setSelectedLanguage(language)
                    setLoadedData(true)
                  } catch (error) {
                    console.warn(error)
                    setLoadedData(true)
                  }
                })
                .catch((error) => {
                  console.warn(error)
                  setLoadedData(true)
                })
            })
            .catch((error) => console.warn(error))
        })
        .catch((error) => console.warn(error))
    }

    getData()
  }, [])

  useEffect(() => {
    const hideSplash = async () => {
      await SplashScreen.hideAsync()
    }
    if (loadedData) {
      hideSplash()
    }
  }, [loadedData])

  return (
    ...
  )
}


text:
Q: Error when running NBTree and Random forest through Weka, Java I am implementing the combination of NBTree and Random forest through product rule. My code is working fine as long as I use same dataset for training and testing but I receive error when I use a new dataset for testing. This is the implementation.
RandomForest objRandomForest = new RandomForest();
Classifier[] objClassifiers = {objNBTree,objRandomForest};
objVote.setClassifiers(objClassifiers);

System.out.println("=== Building Model ===");

objVote.buildClassifier(train);

Evaluation eval = new Evaluation(test);
eval.evaluateModel(objVote, test);

System.out.println(eval.toSummaryString("\nResults\n===============\n", true));

The dataset contains many attributes with numeric values therefore I also discretized them too and following is the code
BufferedReader reader = new BufferedReader(
            new FileReader("C:/Users/MUHAMMAD GALA/Documents/CN/Project/NSL_KDD-master/test1000b.arff"));
Instances data = new Instances(reader);

String[] options = new String[2];
options[0] = "-R";
options[1] = "First-last";
Discretize d = new Discretize();
d.setOptions(options);
d.setInputFormat(data);
Instances newData = Filter.useFilter(data, d);

ArffSaver saver = new ArffSaver();
saver.setInstances(newData);
saver.setFile(new File("C:/Users/MUHAMMAD GALA/Documents/CN/Project/NSL_KDD-master/test1000c.arff"));
saver.writeBatch();

The error that I am getting is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12
at weka.classifiers.trees.j48.NBTreeNoSplit.classProb(Unknown Source)
at weka.classifiers.trees.j48.ClassifierTree.getProbs(Unknown Source)
at weka.classifiers.trees.j48.ClassifierTree.getProbs(Unknown Source)
at weka.classifiers.trees.j48.ClassifierTree.distributionForInstance(Unknown Source)
at weka.classifiers.trees.NBTree.distributionForInstance(Unknown Source)
at weka.classifiers.meta.Vote.distributionForInstanceProduct(Unknown Source)
at weka.classifiers.meta.Vote.distributionForInstance(Unknown Source)
at weka.classifiers.Evaluation.evaluateModelOnceAndRecordPrediction(Unknown Source)
at weka.classifiers.Evaluation.evaluateModel(Unknown Source)
at combinationkitesting.CombinationKiTesting.MajorityVotePrediction(CombinationKiTesting.java:88)
at combinationkitesting.CombinationKiTesting.main(CombinationKiTesting.java:54)


text:
Q: How to retrieve tweets from company profile using java or json? In twitter there are many companys which has their own profile like (ex : https://twitter.com/starbucks or https://twitter.com/mcdonalds). i want to get latest tweets from the company profiles. i have the below code using JSON but it returns general search with keyword from latest tweets.
        BufferedReader in = new BufferedReader(
                new InputStreamReader(System.in));
        String urlstr = "http://twitter.com/search.json?q=";
        StringBuffer buff = new StringBuffer();

        System.out.print("Search for : ");
        urlstr += in.readLine();

        URL url = new URL(urlstr);
        BufferedReader br = new BufferedReader(
                                    new InputStreamReader(
                                    url.openConnection().getInputStream()));
        int c;
        while((c=br.read())!=-1)
        {
            buff.append((char)c);
        }
        br.close();

        JSONObject js = new JSONObject(buff.toString());
        JSONArray tweets = js.getJSONArray("results");
        JSONObject tweet;
        for(int i=0;i<tweets.length();i++) {
            tweet = tweets.getJSONObject(i);
            System.out.println((i+1)+") "+tweet.getString("from_user")+" at
                "+tweet.getString("created_at"));
            System.out.println(tweets.getJSONObject(i).getString("text")+"\n");
        }
    }

A: The Correct Url is
 String urlstr="http://search.twitter.com/search.json?q=from%3AMcDonalds";


text:
Q: Need to select closest item on table I need to hide the "lblItemPrice" div when I click the "btnEdit" button.I need to get the closest div which having "lblItemPrice" class.
I have tried like this,But not working.
 $('.btnEdit').die('click').live('click', function () {
     $(this).closest('.lblItemPrice').hide();
 });

HTML

                        $2.00

                    <input type="text" id="editPrice" name="editPrice" placeholder="edit price">

                $2.00

                <button class="btnEdit actionButton secondaryButton short" type="button">
                    Edit</button>

A: Just find your lblItemPrice inside clicked item's parent:
$(this).parents('tr').find('.lblItemPrice').hide();

A: You can use this,
 $(this).closest('tr').find('.lblItemPrice').hide();


text:
Q: Wifi and Ethernet Extremely slow on my computer! I'm running Ubuntu 20 and my internet is extremely slow.I'm getting 20-25 MBS on both Wi-Fi and Ethernet. Wi-Fi being slightly faster. My network says its cable of higher speeds and on my laptop, I get around 320mbs. Any ideas?
I limited the network IP info below. Let me know if I omitted anything too much or not enough. I'm a noob at this stuff.
$ sudo lshw -class network -short && nmcli device status
H/W path         Device      Class       Description
====================================================
/0/100/15/0      wlp2s0      network     RT5390 Wireless 802.11n 1T/1R PCIe
/0/100/15.1/0    enp3s0      network     RTL810xE PCI Express Fast Ethernet cont
DEVICE  TYPE      STATE         CONNECTION
wlp2s0  wifi      connected     Wifi
enp3s0  ethernet  disconnected  --
lo      loopback  unmanaged     --

enp3s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        txqueuelen 1000  (Ethernet)
        RX packets 37902  bytes 52284157 (52.2 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 6503  bytes 616234 (616.2 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536

        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 2195  bytes 207226 (207.2 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 2195  bytes 207226 (207.2 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

wlp2s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500

        inet6  prefixlen 64  scopeid 0x20<link>
        inet6  prefixlen 64  scopeid 0x0<global>
        inet6  prefixlen 64  scopeid 0x0<global>
        ether txqueuelen 1000  (Ethernet)
        RX packets 137909  bytes 154850679 (154.8 MB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 103697  bytes 81099372 (81.0 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

A: Poor IPv6 performance?
Check whether it could be an IPv6 related problem. You can disable IPv6 with
$ sudo sysctl -w net.ipv6.conf.all.disable_ipv6=1
$ sudo sysctl -w net.ipv6.conf.default.disable_ipv6=1

If this helps, you can try to set IPv4 precedence over IPv6 by uncommenting #precedence ::ffff:0:0/96 100 in the file /etc/gai.conf.
Power Management?
Look whether turning off wifi power management could be a least the reason for poor wifi performance:
Edit the file /etc/NetworkManager/conf.d/default-wifi-powersave-on.conf
and set wifi.powersave = 3 to wifi.powersave = 2.
You can check the current power management state with
$ iwconfig 2> /dev/null | grep 'Power Management'

Kernel issue?
Some users experience better network performance by using a newer kernel from the mainline PPA.
But please keep in mind that a newer kernel might have other issues (i.e. in combination with proprietary drivers like NVidia) and you have to keep track of updates etc.
There are also scripts to maintain mainline kernels like ubuntu-mainline-kernel.sh.
If it is fixed with a newer kernel, chances are high, that a bugfix for this issue will be backported for Ubuntu 20.04. So you should find and track this issue. Therefore you could switch to the stable kernel once this issue has been fixed.
PS: You can also add the corresponding Launchpad issue to this thread. This way others can track this issue as well.