text:
Q: Visual Studio 2019 install MFC library? I am inheriting a C++ code base on Windows in Visual Studio 2019 and I'm trying to compile the code, but it seems like VS cannot find the header files in the MFC library, e.g. "afxdialogex.h". I couldn't find any sources on the internet on how to install MFC and it seems like it should come with Visual Studio. Any ideas?
Disclaimer: I have zero Windows experience as I have exclusive used *nix systems until now.

A: As documented:

In Visual Studio 2017 and later, MFC and ATL are optional sub-components under the Desktop development with C++ workload in the Visual Studio Installer program. You can install ATL support without MFC, or combined MFC and ATL support (MFC depends on ATL). For more information about workloads and components, see Install Visual Studio.

You can either select MFC when choosing workloads (on the right-hand side), or choose individual components.


text:
Q: MySQL Statement - Select where like Concat I have a field called "number" in my table modules. I want to show only specific entries, if the correct number is in my "number" field. Right now I am doing this with the following sql statement:
SELECT *
from modules
where number like CONCAT(
                    (SELECT id
                    from account_metadata
                    where hash='00cRTM')
                    )
ORDER BY date DESC

ID = 2385

This query is working fine as long as I have only one number insider the number field. As our system grows we need to save more than just one number insider our number field, therefore the entry could be something like this:
4235, 2385, 2058

More than one number, separated by commas.
Now my above sql query is not working anymore. Can someone help me and let me know how I should change my query to fetch all entries?
I would really appreciate any help.
Thanks in advance,
Chris

A: I found a solution by myself. It is working and all I need for testing purposes. Thanks to everyone who tried to help me.
SELECT *
from modules
where number like CONCAT('%',
                    (SELECT id
                    from account_metadata
                    where hash='00cRTM') ,'%'
                    )
ORDER BY date DESC

redpajama_set_name: RedPajamaStackExchange


text:
Q: Possible causes of java.io.IOException: CreateProcess error=5 What kind of problem(s) could cause Java's ProcessBuilder.start method to return an IOException with a note saying error=5?
Specifically, we've seen a remote customer system running some Java code along the lines of...
ProcessBuilder pb = new ProcessBuilder(cmdArray);
pb.redirectErrorStream(true);
Process p = pb.start();

...throw exceptions like this...
java.io.IOException: CreateProcess: C:\example\example.exe argument1 argument2 error=5
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
at java.lang.ProcessBuilder.start(Unknown Source)
at example_code_above

We have confirmed that the command noted in the exception, "C:\example\example.exe argument1 argument2" can be run successfully by hand via cmd.exe, so we are confident the command itself is not broken.

A: Alexandr is correct, it's Windows security that's not allowing that process to run, but that powershell command didn't work for me.  here's what I did:

*

*Open up Windows explorer, and navigate to example.exe

*Right click on it and choose "Properties"

*Go to the "Security" tab and click the "Edit" button

*Select your username in the top box and in the bottom one give "Full Control" or at least "Read & Execute"

*Click OK to get rid of these boxes

Now your user can execute that program.  Yay!

A: Sometimes this happens because the path you put in code is not correct. For windows put "\\" as a path separator instead of "\" For example change  path to "C:\\example\\example.exe"

A: error=5 means one of:
1) file is not executable
2) file is not accessible
EDIT: wont throw exception
3) the command (example.exe) exits with exit code 5

A: I have the same exception because of Windows UAC.
This can happen even if your account has administrator privileges.
To be able to run such command I had to use powershell to elevate privileges.
powershell start-process 'start.bat' -Verb RunAs


text:
Q: Different stream of pseudorandom numbers I have a homework problem on running a simulation where I generate 100 random numbers and perform a calculation on each outcome. The next question asks me to repeat the previous question but with a different stream of pseudorandom numbers. The side note tells me to to perform two computations within one call  to the program because changing the seed/state arbitrary can lead to overlapping streams.
Can someone explain to me what this means? Why do I have to do it through 1 loop?
Why can't I just call the same code twice using a different seed each time?

A: Pseudo-random number generators (PRNGs) work by iterating through a deterministic set of calculations on some internal information known as the generator's state, and then handing you back a value which is based on the state.  There's a finite amount of state information that determines what the next state, and thus the next outcome, will be.  Since it's finite, eventually the generator will revisit a state that it used before, and from that point forward all values will be exact duplicates of the sequence you've already seen.  The PRNG is said to have cycled.  "Seeding" a random number generator sets the starting point for the state, so it effectively corresponds to choosing an entry point to the cycle.
If a human intervenes by changing the seed arbitrarily, there's a chance that they will prematurely put the state back to where some portion of the output sequence repeat gets repeated.  This is referred to as overlapping streams.  The solution is to seed your PRNG once, and then don't mess with it so it can achieve its full cycle.
In your case it means that the values and ordering of your first set of 100 numbers will be distinct from your the values and ordering of your second set of 100.


text:
Q: Error response from daemon: Unexpected status code 404 I am configuring docker registry on nexus 3 configuration. I Am running nexus behind apache and has https enabled.
On command line, when I do a docker search, I get the below error:

docker search my.nexus.net/ubantu
Error response from daemon: Unexpected status code 404

Here is the daemon log on debug mode:
DEBU[7519] Calling GET /images/search
INFO[7519] GET /v1.19/images/search?term=my.nexus.net%2Fubantu
DEBU[7519] pinging registry endpoint https://my.nexus.net/v0/
DEBU[7519] attempting v2 ping for registry endpoint https://my.nexus.net/v2/
DEBU[7519] hostDir: /etc/docker/certs.d/my.nexus.net
DEBU[7519] attempting v1 ping for registry endpoint https://my.nexus.net/v1/
DEBU[7519] hostDir: /etc/docker/certs.d/my.nexus.net
DEBU[7519] Error unmarshalling the _ping RegistryInfo: invalid character '<' looking for beginning of value
DEBU[7519] RegistryInfo.Version: ""
DEBU[7519] Registry standalone header: ''
DEBU[7519] RegistryInfo.Standalone: true
DEBU[7519] attempting v1 ping for registry endpoint https://my.nexus.net/v1/
DEBU[7519] hostDir: /etc/docker/certs.d/my.nexus.net
DEBU[7519] Error unmarshalling the _ping RegistryInfo: invalid character '<' looking for beginning of value
DEBU[7519] RegistryInfo.Version: ""
DEBU[7519] Registry standalone header: ''
DEBU[7519] RegistryInfo.Standalone: true
DEBU[7519] Endpoint https://my.nexus.net/v1/ is eligible for private registry. Enabling decorator.
DEBU[7519] Index server: https://my.nexus.net/v1/
DEBU[7519] hostDir: /etc/docker/certs.d/my.nexus.net
ERRO[7519] Handler for GET /images/search returned error: Unexpected status code 404
ERRO[7519] HTTP Error                                    err=Unexpected status code 404 statusCode=500

If any one has any idea on it, please let me know.

A: From the logs it seems you try pining different versions of the registry endpoint. Did you use v1Enabled:falseoption on the repository configuration? It seems to get an error during v1 ping but still uses that endpoint. It's rather strange & unexpected behaviour.

A: I had the same problem.
After googling, it looks like 'docker search' uses the V1 API: see Issue https://github.com/docker/distribution/issues/206

So after I have enabled the V1 API on all docker registries of the group corresponding with the port, it works perfectly.

A: The docker search command use a v1 API. You have 2 alternatives :

*

*Enable v1 API before using docker search

*Use a curl like that: curl -X GET localhost:5000/v2/_catalog

A: To do pretty much anything in docker using NXRM3, you need to specify the port you are searching so the repository manager knows what repository you are looking for.  If you just specify the root port (or in your case, looks like no port), NXRM3 has no idea which you are looking at.
So if your group is setup to use HTTPS connector 18075 try "docker search my.nexus.net:18075/ubantu"
Reference: http://books.sonatype.com/nexus-book/reference3/docker.html#docker-search

A: I used a VPN and it worked. Not psiphon.


text:
Q: GridBagLayout adding extra space to column I have a JPanel with GridBagLayout as the layout manager and I'm trying to get this arrangement:

Ignore the extra dark blue space of the border.
I have in total 5 columns and 3 rows and all the components have setPreferredSize() set to the exact value to fit perfectly in the JPanel which also has a preferred size (170 x 115).
The problem is that GridBagLayout appears to be adding 30 pxls to the last column width, because only adding 30 pxls to the width of the JPanel (200 in total) the components are shown properly, like this:

but with the last column separated because of the extra space.
It adds 30 pxls because adding 29 pxls to the JPanel's width gives this result:

which in my experience tells that the space available is too small to show all components and then uses the setMinimumSize().
I don't know where those 30 pxls came from, please can anyone tell me how to make the components fit?
The code is shown below and currently gives this result:

Ignore the extra black space of the JFrame.
You can change the width of the JPanel in line 34.
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;

public class Test{
    public static void main (String[] args){
        JFrame f;
        SizeProperties p;

        f = new JFrame();
        p = new SizeProperties();

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().setPreferredSize(new Dimension(250,200));
        f.getContentPane().setBackground(Color.BLACK);
        f.setLayout(new FlowLayout());

        f.add(p);
        f.pack();
        f.setVisible(true);
    }
}

final class SizeProperties extends JPanel{
    private GridBagConstraints c;
    private PropertiesLabel xL,yL,wL,hL;
    private PropertiesField xF,yF,wF,hF;
    private ProportionToggleButton ptb;

    SizeProperties(){
        setBackground(new Color(18,101,142));
        setPreferredSize(new Dimension(170,115));//Change width here
        setLayout(new GridBagLayout());

        xL = new PropertiesLabel("x:",25,25);
        xF = new PropertiesField();
        yL = new PropertiesLabel("y:",25,25);
        yF = new PropertiesField();
        wL = new PropertiesLabel("Width:",80,25);
        wF = new PropertiesField();
        hL = new PropertiesLabel("Height:",80,25);
        hF = new PropertiesField();
        ptb = new ProportionToggleButton();

        c = new GridBagConstraints(0,0,1,1,0,0,GridBagConstraints.CENTER,GridBagConstraints.NONE,new Insets(10,10,10,0),0,0);
        add(xL,c);

        c = new GridBagConstraints(1,0,1,1,0,0,GridBagConstraints.CENTER,GridBagConstraints.NONE,new Insets(10,0,10,10),0,0);
        add(xF,c);

        c = new GridBagConstraints(2,0,1,1,0,0,GridBagConstraints.CENTER,GridBagConstraints.NONE,new Insets(10,0,10,0),0,0);
        add(yL,c);

        c = new GridBagConstraints(3,0,2,1,0,0,GridBagConstraints.CENTER,GridBagConstraints.NONE,new Insets(10,0,10,10),0,0);
        add(yF,c);

        c = new GridBagConstraints(0,1,2,1,0,0,GridBagConstraints.CENTER,GridBagConstraints.NONE,new Insets(0,10,10,0),0,0);
        add(wL,c);

        c = new GridBagConstraints(2,1,2,1,0,0,GridBagConstraints.CENTER,GridBagConstraints.NONE,new Insets(0,0,10,10),0,0);
        add(wF,c);

        c = new GridBagConstraints(0,2,2,1,0,0,GridBagConstraints.CENTER,GridBagConstraints.NONE,new Insets(0,10,10,0),0,0);
        add(hL,c);

        c = new GridBagConstraints(2,2,2,1,0,0,GridBagConstraints.CENTER,GridBagConstraints.NONE,new Insets(0,0,10,10),0,0);
        add(hF,c);

        c = new GridBagConstraints(4,1,1,2,0,0,GridBagConstraints.CENTER,GridBagConstraints.NONE,new Insets(0,0,10,10),0,0);
        add(ptb,c);

    }
}

final class PropertiesLabel extends JLabel{
    PropertiesLabel(String label,int w,int h){
        setText(label);
        setPreferredSize(new Dimension(w,h));
        setBackground(Color.BLACK);
        setOpaque(true);
        setForeground(Color.WHITE);
        setFont(new Font("SansSerif",Font.PLAIN,14));
        setHorizontalAlignment(SwingConstants.CENTER);
        setVerticalAlignment(SwingConstants.CENTER);
    }
}

final class PropertiesField extends JTextField{
    private int validNumber = 0;

    PropertiesField(){
        setPreferredSize(new Dimension(45,25));
        setBackground(new Color(202,226,255));
        setForeground(Color.BLACK);
        setFont(new Font("SansSerif",Font.PLAIN,14));
        setHorizontalAlignment(JTextField.CENTER);
        setText("999");
    }
}

final class ProportionToggleButton extends JToggleButton{
    ProportionToggleButton(){
        setPreferredSize(new Dimension(15,60));
    }
}

Thanks in advance.

A:
I have in total 5 columns

Not from what I can see. You can't just assign a component to a column. You actually need to have 5 components in a single row to create a grid of 5 columns.
Based on your picture you first row has 4 columns and the last two rows have 3 columns.
So based on your picture you need to rethink your design. What I see is:

*

*you have three columns based on the last two rows.

*now on the first row the x/999 will be a single panel with two components. This panel will be in the 1st column (with the width/height labels).

*Also in the first row the y/999 will be a single panel with two components and will start in the 2nd column and have a gridwidth of 2.

*The 2nd and 3rd row will contain the 999 component in the second column

*the button start in the 2nd row and have a gridheight of 2 and will be contained in the 3rd column

Also, you should not be setting the preferred size of the components. Each component will determine its own preferred size. The GridBagLayout will then determine the size of each cell based on the components in the row/column.


text:
Q: How to detect silence in an audio stream with pydub? I want to monitor an audio streaming for silences. Any idea how I can do this ? it's a stream, not an audio file.

A: Your best bet is to grab chunks from the stream (I'd advise 50 millisecond chunks since one complete wave form at 20Hz is 50ms), and construct an AudioSegment using this data.
Once you've done that you'll be able to use the AudioSegment().dBFS property to get a rough measure of the average loudness of that chunk. Once you get a sense for where the highs and lows are you can set a threshold below which will be considered silence.
You can of course determine the silence threshold automatically as well, but that'll probably require keeping track of loudest and quietest signal level in the last X seconds, and probably using some kind of decay as well.
Note: The method I've described above is definitely not the fastest way to do this, but pydub does not natively handle streaming. That said, it's probably the simplest way to accomplish your goal with pydub.


text:
Q: How to Implement Retry on Transient Actor Failure? I'm in a typical situation where I have a group of worker actors that are being fed jobs from a queue.  Worker failures can be either transient and due to the environment, or permanent and due to an invalid job.
Inside the worker actor I'm handling the permanent failure case, but how can I implement a retry for the transient cases?  With a supervisor I can have the actor restarted, which is desirable to try and reset to a working state, but how then can I retry the message it was working on when it failed?
Thanks!

A: You need to implement the Command pattern.  A Command is an object that encapsulates an operation to be performed, along with its arguments, and exists independent of the Actor.  If the Actor fails in a fashion that is retryable, the supervisor resubmits the Command to the Actor.  If the Actor is fed a stream and processes messages, then the Actor must populate a list of Commands and record completion so it can restart at the right place.  If the stream isn't rewindable, then you have to queue up ALL the commands before starting, and the Actor must record completion status on each Command, so the chain can be resubmitted on transient failure.
The Command pattern can also be used to implement history and undo.

A: If you are working with Akka 1.2 or master, you can override preRestart to obtain the message that was current when the actor crashed.


text:
Q: Spring Prototype bean with constructor argument and injected dependencies I have a bean that has some singleton dependencies but also instance-exclusive parameters. The constructor is something like:
@Autowired
public PrototypeBean(CustomAttribute attribute, Service1 service1, Service2 service2) {
[...some code...]
}

In the example above, service1 and service2 are singleton, Spring, dependencies and must be injected when the bean is created.
On another class, I have a ObjectProvider that should create instances of the prototyped bean above. I am trying something like this:
objectProvider.getObject(attribute);

But Spring returns an error saying it could not find a constructor matching the parameters.
I can easily change my code from Constructor-based injection to attribute-based inject and it will work. But its not a good practice and make tests more harder to be written.
Is there a way to use ObjectProvider with a constructor that have both custom parameters AND dependencies?

A: You can do it like this:
@Configuration
static class PrototypeBeanConfiguration {
   private final Service1 service1;
   private final Service2 service2;

   public PrototypeBeanConfiguration(Service1 service1, Service2 service2) {
      this.service1 = service1;
      this.service2 = service2;
   }

   @Bean
   @Scope(value = BeanDefinition.SCOPE_PROTOTYPE)
   public PrototypeBean(CustomAttribute attribute) {
      return new PrototypeBean(attribute, service1, service2);
   }
}


text:
Q: Existe um modo de não encher o HTML com diretivas? Utilizando a diretiva ng-click para pegar um evento de clique em um link seria algo parecido com:
Home

Mas isto não seria a mesma coisa que o uso de onclick="call('home')"?
Uma boa prática no desenvolvimento web não é separar cada documento com a sua devida funcionalidade? Evitando aquele monte de CSS e JavaScript inline?
É possível, por exemplo, selecionar um elemento de forma semelhante ao conhecido $('foo').on('click', function(){}); i.e conseguir acessar o elemento do arquivo JavaScript e sem encher o HTML de diretivas?
Por exemplo:
Abrir

E no JS:
$scope.abrir.on('click', function(){
   call('foo');
});

A: O ng-click é diferente do onclick. A diretiva do Angular utiliza expressões da própria framework, ou seja, estão no contexto do escopo do Angular (que não é diretamente acessível pelo onclick).
E não, não há método do Angular que se comporte como os handlers do jQuery, mas você pode utilizá-lo paralelamente para executar expressões do escopo global.

A: O Angular vem para estender o HTML, em um primeiro momento você pode achar que está sujando, pra mim ele o torna mais declarativo, no modelo $('item').on('click', faz alguma coisa); lá no arquivo js, pode ser organizado para um programador mas para um designer está escondido porque no html não existe referencia ao código.


text:
Q: Problem definition of struct in Macro I'm working on macros in C, trying to simulate the objet behavior but using C and I'm having a problem with the definition of a variable defined from a struct in another struct in a macro. That's my code... it works:
#include <stdio.h>
#include <stdlib.h>

#define STACK_MAX_CAPACITY 10
#define DECLARE_STACK(Type)                             \
    typedef struct MetaPile_##Type;                     \
                                                        \
    typedef struct Pile_##Type_t{                       \
        Type q[STACK_MAX_CAPACITY];                     \
        int pos;                                        \
    } Pile_##Type;                                      \
                                                        \
    typedef struct MetaPile_##Type_t{                   \
        void (* push) ( Pile_##Type* p, Type val );     \
        void (*init) (Pile_##Type* p);                  \
    } MetaPile_##Type;                                  \
                                                        \
    void init_##Type( Pile_##Type* p ){                 \
        p->pos = 0;                                     \
        int i;                                          \
        for(i=0; i<STACK_MAX_CAPACITY; i++){            \
            p->q[i]=0;                                  \
        }                                               \
    }                                                   \
                                                        \
    void push_##Type( Pile_##Type* p, Type val ) {      \
        if(p->pos < STACK_MAX_CAPACITY){                \
            p->q[p->pos]=val;                           \
            p->pos++;                                   \
        }                                               \
    }                                                   \
    MetaPile_##Type TheMetaPile_##Type;                 \
    void initTheMetaPile_##Type(){                      \
        TheMetaPile_##Type.init = &init_##Type;         \
        TheMetaPile_##Type.push = &push_##Type;         \
    }                                                   \
                                                        \

DECLARE_STACK(int)

int main(){

    int i;

    initTheMetaPile_int();
    Pile_int pi;

    TheMetaPile_int.init(&pi);

    push_int(&pi, 2);
    push_int(&pi, 3);
    push_int(&pi, 4);
    push_int(&pi, 5);
    push_int(&pi, 6);

    for(i=0; i<STACK_MAX_CAPACITY; i++){
        printf("%d",pi.q[i]);
    }

    return 0;
}

The first structure define an array of a dinamic type thanks to the macro (Pile_##Type) that represents the attributs side of an objet, and another structure (MetaPile_##Type) that will manage the "methods" of the objet, via fonction pointers. The fonction init works as a constructor and initialises my "objet" pi.
Now what I want is to have a reference in Pile_##Type of a variable of type MetaPile_##Type (called for exemple myClass) in order to be able to make pi->myClass->push and call the fonction push_int. But when I make:
typedef struct Pile_##Type_t{                       \
    Type q[STACK_MAX_CAPACITY];                     \
    int pos;                                        \
    MetaPile_##Type myClass;                        \
} Pile_##Type;                                      \

I have a misunderstandable mistake...
D:\main.c|40|warning: useless keyword or type name in empty declaration|
D:\main.c|40|error: syntax error before "MetaPile_int"|
D:\main.c|40|warning: no semicolon at end of struct or union|
D:\main.c|40|warning: type defaults to `int' in declaration of `Pile_int'|
D:\main.c|40|warning: data definition has no type or storage class|
D:\main.c|40|error: syntax error before '*' token|
D:\main.c|40|error: syntax error before '*' token|
D:\main.c|40|error: syntax error before '*' token|
D:\main.c||In function `init_int':|
D:\main.c|40|error: `p' undeclared (first use in this function)|
D:\main.c|40|error: (Each undeclared identifier is reported only once|
D:\main.c|40|error: for each function it appears in.)|
D:\main.c|40|error: syntax error before '*' token|
D:\main.c||In function `push_int':|
D:\main.c|40|error: `p' undeclared (first use in this function)|
D:\main.c|40|error: `val' undeclared (first use in this function)|
D:\main.c||In function `main':|
D:\main.c|47|error: syntax error before "pi"|
D:\main.c|49|error: `pi' undeclared (first use in this function)|
||=== Build finished: 12 errors, 4 warnings ===|

I don't know what's worong with the defintion of myClass, I've used * also but the error persits. Thanks if somebody can help.

A: Your problem is not the usage of macros, this only distracts you.
typedef struct MetaPile_int;

is just syntactically incorrect. A simple forward declaration of a struct looks like this:
struct MetaPile_int;

But if you just want to make your life easier do it like this:
typedef struct MetaPile_int MetaPile_int;

This is a forward declaration of the struct and a definition of the identifier MetaPile_int at the same time.
To get it working try it without putting it in a macro, first. Or use a compiler that helps you trace errors in macros such as clang.

A: Remove the typedef struct MetaPile_##Type; line - what's that supposed to do (besides causing your errors, that is)?

A: You try to insert a full struct (MetaPile_##Type) before declaring it, change the order of them like that [ in MetaPile_##Type you only use pointers to Pile_##Type_t, and the size of pointers is known]:
Edit:
This declaration works for me fine:
#define DECLARE_STACK(Type)                             \
    struct Pile_##Type_t;                     \
                                                        \
    typedef struct MetaPile_##Type_t{                   \
        void (* push) ( Pile_##Type_t* p, Type val );     \
        void (*init) (Pile_##Type_t* p);                  \
    } MetaPile_##Type;                                  \
                                                        \
    typedef struct Pile_##Type_t{                       \
        Type q[STACK_MAX_CAPACITY];                     \
        int pos;                                        \
    MetaPile_##Type myClass;                        \
    } Pile_##Type;                                      \
                                                        \
    void init_##Type( Pile_##Type* p ){                 \
        p->pos = 0;                                     \
        int i;                                          \
        for(i=0; i<STACK_MAX_CAPACITY; i++){            \
            p->q[i]=0;                                  \
        }                                               \
    }                                                   \
                                                        \
    void push_##Type( Pile_##Type* p, Type val ) {      \
        if(p->pos < STACK_MAX_CAPACITY){                \
            p->q[p->pos]=val;                           \
            p->pos++;                                   \
        }                                               \
    }                                                   \
    MetaPile_##Type TheMetaPile_##Type;                 \
    void initTheMetaPile_##Type(){                      \
        TheMetaPile_##Type.init = &init_##Type;         \
        TheMetaPile_##Type.push = &push_##Type;         \
    }                                                   \
                                                        \

and it should do the work.


text:
Q: How do I get at the text inside this anchor tag with jQuery? If I have a link like this:

    Sign In

How do I retrieve the text Sign In with jQuery?

A: Use the text method. Example:
var txt = $('#main li a').text();

A: This is useful for grabbing the text based on the hyperlink URI:
  var linkText = $('a[href="/login"]').text();

http://api.jquery.com/attribute-equals-selector/

A: If that's actually the only text, you can get it direclty from the #main element. No need to drill down to the  element.
$('#main').text();

Though you may want to trim it.
$.trim( $('#main').text() );

Working Example: http://jsfiddle.net/GqKaN/

A: You can use this approach, which selects the anchor by its href attribute:
$("#main a[href=/login]").text()

http://api.jquery.com/attribute-equals-selector/

A: var text = $('#main li:first-child a:first-child').text();

Or without :first-child depending on your overall structure.
Reference: .text


text:
Q: Return status code 404 with JSON data for ASP WebMethod I'm trying to return status code 404 with a JSON response, like such:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static dynamic Save(int Id)
{
    HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.NotFound;
    return new
    {
        message = $"Couldn't find object with Id: {id}"
    };
}

But I keep getting HTML error page for 404 error instead of the JSON response. I've tried various of manipulating the Response with Flush, Clear, Write, SuppressContent, CompleteRequest (Not in order), but whenever I return 404 it still picks up the html error page.
Any ideas on how I can return a status code other than 200 OK (Since it's not ok, it's an error) and a JSON response?
I know I can throw an exception, but I'd prefer not to since it doesn't work with customErrors mode="On"
This is an older Website project in ASP.Net, and it seems most solutions in ASP MVC doesn't work.

A: Usually when you get he HTML error page that is IIS taking over the handling of the not found error.
You can usually bypass/disable this by telling the response to skip IIS custom errors.
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static dynamic Save(int id) {
    //...

    //if we get this far return not found.
    return NotFound($"Couldn't find object with Id: {id}");
}

private static object NotFound(string message) {
    var statusCode = (int)System.Net.HttpStatusCode.NotFound;
    var response = HttpContext.Current.Response;
    response.StatusCode = statusCode;
    response.TrySkipIisCustomErrors = true; //<--
    return new {
        message = message
    };
}


text:
Q: Get value from variable created on run time from another variable in Oracle PLSQL I have this thing in unix for example below
filename1_temp=3
var1=filename1
var2=${var1}_temp
var3=\$${var2}

so basically var3 contains the value stored in variable filename1_temp which is 3. I need this implementation in oracle PL/SQL. For example
filename1_temp:=3
var1:="filename1";
var2:=var1||"_temp";
var3:=???

How will I do it in PL/SQL??
Please suggest.

A: You'd like to evaluate a string as a PL/SQL code. Essentially the following code should do what you're asking but unfortunately it doesn't work:
declare
  filename1_temp constant varchar2(32767) := 'magic';
  var1 constant varchar2(32767) := 'filename1';
  var2 constant varchar2(32767) := var1 || '_temp';
  var3 varchar2(32767);
  function eval(p_var in varchar2) return varchar2 is
    v_ret varchar2(32767);
  begin
    execute immediate 'begin :ret := ' || p_var || '; end;'
      using out v_ret;
    return v_ret;
  end;
begin
  dbms_output.put_line('var3 = ' || var3);
  var3 := eval(var2); -- expecting magic
  dbms_output.put_line('var3 = ' || var3);
end;
/

It fails with:
ORA-06550: line 1, column 15:
PLS-00201: identifier 'FILENAME1_TEMP' must be declared

because execute immediate runs in SQL context and it doesn't know the details of the anonymous PL/SQL block. So you have to make the variable accessible from SQL too. Here is an example where I have used public package variable:
create or replace package so49 is
  filename1_temp varchar2(32767);
end;
/
show errors

declare
  var1 constant varchar2(32767) := 'so49.filename1';
  var2 constant varchar2(32767) := var1 || '_temp';
  var3 varchar2(32767);
  function eval(p_var in varchar2) return varchar2 is
    v_ret varchar2(32767);
  begin
    execute immediate 'begin :ret := ' || p_var || '; end;'
      using out v_ret;
    return v_ret;
  end;
begin
  so49.filename1_temp := 'magic';
  dbms_output.put_line('var3 = ' || var3);
  var3 := eval(var2); -- expecting magic
  dbms_output.put_line('var3 = ' || var3);
end;
/

The magic happens:
SQL> @so49

var3 =
var3 = magic

PL/SQL procedure successfully completed.

SQL>

Hope this helps.

A: I am not sure what you are looking for but do you want this kind of stuff..
declare
  filename1_temp number(4);
  var1           number(4);
  var2           varchar2(100);
  var3           varchar2(100);
begin
  filename1_temp := 3 ;
  var1 := filename1_temp;
  var2           := to_char(var1) || '_temp';
  var3           := var2;
  dbms_output.put_line(var3);
end;


text:
Q: Get image and save in storage I have an web page which is a profile viewing page. Here I have an blank image. On click of this image I am able to prompt browse image option. But I don't know how to save the image into storage. Here is my code:

            .Hii

            <input type="file" id="my_file" style="display: none;" />

$(document).ready(function(){
    $("#fileupload").on("click", function() {
        $("#my_file").click();
    }

I tried this below jQuery to save image but is was of no use.
$(document).ready(function(){
    $("#fileupload").on("click",function(){
        $("#my_file").click();
        userImage = document.getElementById('fileupload');
        imgData = getBase64Image(userImage);
        localStorage.setItem("imgData", imgData);
    });
});

My requirement is I should be able to save the image from clicking add image i.e img.png in my code. I am using beego as web framework, but i will be happy if this get solved in jQuery or javascript.

A: jsBin demo
// https://stackoverflow.com/a/17711190/383904
function readImage() {
  if ( this.files && this.files[0] ) {
    var FR= new FileReader();
    FR.onload = function(e) {
      localStorage.setItem("imgData", event.target.result); // Send to Localstorage
    };
    FR.readAsDataURL( this.files[0] );
  }
}

$(document).ready(function(){
  $("#fileupload").on("click",function(){
    $("#my_file").click().change( readImage );
  });
});

To save that image on server you'll need to send that data to PHP.
PHP can than convert your base64 string to an image.
Otherwise, why not simply send that image using AJAX to a PHP script that will put it inside a server folder?
Send Image to server using File input type
https://stackoverflow.com/a/17711190/383904


text:
Q: Django prefetch related returns null The requirement is to have subtopics prefetched at the Campaigns queryset as the attribute
prefetched_subtopics

but it currently returns null
Models
class SubTopic(Base):
    name = models.CharField(max_length=100, unique=True)

class CampaignSubTopicAssn(HistoryMixin, Base):
    campaign = models.ForeignKey(Campaign, related_name='subtopic_assn', on_delete=models.CASCADE)
    subtopic = models.ForeignKey(SubTopic, related_name='campaign_assn', on_delete=models.PROTECT)

View
def get_queryset(self):
        return super(CampaignViewSet, self).get_queryset().prefetch_related(Prefetch('subtopic_assn__subtopic', queryset=SubTopic.objects.all(), to_attr='prefetched_subtopics'))


text:
Q: Entity Framework Migration cascade delete is always true even WillCascadeOnDelete(false) in configuration Why relations with  WillCascadeOnDelete(false) defined in configuration,  are always true in generated migration?
Here is the configuration code
 public class PartySuppliesConfiguration:EntityTypeConfiguration<PartySupplies>
{
    public PartySuppliesConfiguration()
    {
        HasKey(x => x.Id);
        HasRequired(x=>x.Supplier).WithMany().HasForeignKey(x=>x.SupplierId).WillCascadeOnDelete(false);
        HasRequired(x => x.Product).WithMany().HasForeignKey(x => x.ProductId).WillCascadeOnDelete(false);
        HasRequired(x => x.Currency).WithMany().HasForeignKey(x => x.CurrencyId).WillCascadeOnDelete(false);
        HasRequired(x => x.CreatedUser).WithMany().HasForeignKey(x => x.CreatedUserId).WillCascadeOnDelete(false);
        Property(x => x.UnitPrice).HasColumnType("Money");
    }
}

and here is the generated migration
 public override void Up()
    {
        CreateTable(
            "PartySupplies",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    SupplierId = c.Int(nullable: false),
                    ProductId = c.Int(nullable: false),
                    UnitPrice = c.Decimal(nullable: false, precision: 18, scale: 2),
                    CurrencyId = c.Int(nullable: false),
                    FromDate = c.DateTime(nullable: false),
                    ThruDate = c.DateTime(),
                    CreatedUserId = c.Int(nullable: false),
                })
            .PrimaryKey(t => t.Id)
            .ForeignKey("Parties", t => t.SupplierId, cascadeDelete: true)
            .ForeignKey("Products", t => t.ProductId, cascadeDelete: true)
            .ForeignKey("Curencies", t => t.CurrencyId, cascadeDelete: true)
            .ForeignKey("Users", t => t.CreatedUserId, cascadeDelete: true)
            .Index(t => t.SupplierId)
            .Index(t => t.ProductId)
            .Index(t => t.CurrencyId)
            .Index(t => t.CreatedUserId);

    }

A: It might be a silly question but have you overriden the OnModelBuilding method in DbContext and added modelBuilder.Configurations.Add( new PartySuppliesConfiguration( ) );? Does PartySuppliers have any DataAnnotations that might be overriding your entity config class? Or maybe it's derived from another class where cascadeondelete is set to true?


text:
Q: how to fix object is not an instance of declaring class in android? Please help me fix this problem

All of my projects are like this
I already done a gradle sync, rebuild, clean project. I even did reinstall the android studio. But I can't fix it.
Even creating a new project is not working.
here is the stack trace:
java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at android.animation.PropertyValuesHolder_Delegate.callMethod(PropertyValuesHolder_Delegate.java:108)
at android.animation.PropertyValuesHolder_Delegate.nCallFloatMethod(PropertyValuesHolder_Delegate.java:143)
at android.animation.PropertyValuesHolder.nCallFloatMethod(PropertyValuesHolder.java)
at android.animation.PropertyValuesHolder.access$400(PropertyValuesHolder.java:38)
at android.animation.PropertyValuesHolder$FloatPropertyValuesHolder.setAnimatedValue(PropertyValuesHolder.java:1387)
at android.animation.ObjectAnimator.animateValue(ObjectAnimator.java:990)
at android.animation.ValueAnimator.setCurrentFraction(ValueAnimator.java:674)
at android.animation.ValueAnimator.setCurrentPlayTime(ValueAnimator.java:637)
at android.animation.ValueAnimator.start(ValueAnimator.java:1069)
at android.animation.ValueAnimator.start(ValueAnimator.java:1088)
at android.animation.ObjectAnimator.start(ObjectAnimator.java:852)
at android.animation.StateListAnimator.start(StateListAnimator.java:188)
at android.animation.StateListAnimator.setState(StateListAnimator.java:181)
at android.view.View.drawableStateChanged(View.java:21105)
at android.view.ViewGroup.drawableStateChanged(ViewGroup.java:7101)
at android.view.View.refreshDrawableState(View.java:21160)
at android.view.View.dispatchAttachedToWindow(View.java:18379)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3397)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3404)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3404)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3404)
at android.view.AttachInfo_Accessor.setAttachInfo(AttachInfo_Accessor.java:42)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:335)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:391)
at com.android.tools.idea.layoutlib.LayoutLibrary.createSession(LayoutLibrary.java:195)
at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:540)
at com.android.tools.idea.rendering.RenderTask.lambda$inflate$5(RenderTask.java:666)
at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)


text:
Q: If I date Liara in ME1, what will affect me if I want to date Tali in ME2 and 3? Well, everythings's in the title.
I was wanting to date Tali (I just love the character) and I'm doing all the Mass Effect games. I'm currently Male Sheppard and in the original Mass Effect.
Tali isn't available in ME1, so I guess I'll date Liara instead.
I know about the picture in ME2, but is there any other effect? Knowing that I will keep Tali as my date in ME3?
Am I better not dating anyone since I don't care much about trophies?

A: You can choose not to romance anyone. That keeps things super-simple.
If, however, you'd like your Shep to get some play, you can totally romance Liara in 1 and then Tali in 2 and 3. Liara might be a little sad about it, but she's not going to hate you or anything as a result. I'm not sure if Tali says anything about Liara in 2, since I've never gone down that road, but given how other romances go about it I'd say Tali will ask you about Liara, and you are given the option of backing out or saying "nope, it's all you".
Basically, you won't be penalized if you start with Liara in 1 and go with Tali in 2 and 3. Liara's not going to be a pain and keep info from you or whatever over it. At most, there might be a snarky comment or two, but that'd be about it.


text:
Q: How to satisfy flow with union type of date or object I have the following type:
export type dateParts = { day?: string, month?: string, year?: string };

export type dateOrObject = Date | dateParts;

Then I have a DatePicker component:
export class DatePicker extends Component {
  props: {
    value?: dateOrObject,
  };

But when I try and deconstruct value when it is an object:
if (!isDate(value)) {
  const { day, month, year } = value;

  this.state = {
    day,
    month,
    year
  };

  return;
}

I get this error:
const { day, month, year } = value;
                               ^^^^ property `year`. Property not found in
const { day, month, year } = value;
                                        ^^^^^ Date

A:
Disjoint unions require you to use a single property to distinguish
  each object type. You cannot distinguish two different objects by
  different properties.

Flow doesn't know in your case what isDate function is about. So it's better to use simple property checking.
if (value.year) {
  const { day, month, year } = value;

  this.state = {
    day,
    month,
    year
 };

 return;
}

Update, above doesn't work, though it follows the official docs.
Try this one instead :
! (value instanceof Date)


text:
Q: Equations for Mandelbrot bifurcation diagram The Mandelbrot set is the set of all complex numbers $c$ that cause the function $z_{n+1} = z_n^2 + c$ to remain bounded within a circle of radius 2 when iterated from $z_0 = 0$. Looking at only the real numbers, all values between positive $\frac{1}{4}$ and negative 2 are part of the set. If we plot the attractive fixed point value on the vertical axis against the input $c$ value on the horizontal axis we get a classic bifurcation diagram. Going from right to left, the diagram starts with the function $\frac{1 - \sqrt{-4c + 1}}{2}$ where $\frac{1}{4} ≥ c ≥ -\frac{3}{4}$. It then splits into two branches as $\frac{-1 ± \sqrt{-4c + 3}}{2}$ where $-\frac{3}{4} ≥ c ≥ -\frac{5}{4}$. Both branches divide again and again, over increasingly narrow intervals, until the plot dissolves into chaos around $-\frac{7}{5}$.

Are there closed-form equations for any of the divisions beyond the first two I've listed? For example, the period-4 region or the period-8 region? They don't seem to line up with quadratic expressions or any other expressions I've tried. I also can't find closed-form expressions for the end-points of the intervals for each division, that is, the $c$ value for each bifurcation point.
The closest I've been able to get so far for the topmost period-four section is $\frac{(-4c - 5)^{\frac{1}{2.05}}} {2.5} - \frac{1 - \sqrt{2}} {2}$, which is pretty darn close, but it's not exact.
I do know that the sweeping curves visible in the chaotic portion of the bifurcation diagram, the critical curves, are of the form $(c² + c)² + c$, $((c² + c)² + c)² + c$, $(((c² + c)² + c)² + c)² + c$, and so on, but these curves don't line up with the bifurcating parts either.

A: If we let
$$f_c(z)=z^2+c$$
then the lines on that diagram (in the column corresponding to $c$) are exactly at attractive cycles of $f_c$ - which is to say that they are certain solutions of
$$f_c^n(z)=z$$
where $f_c^n$ is the $n$-fold composition of $f_c$ with itself - and where $n$ will be the number of lines seen on the plot. More specifically, they are the solutions for which the derivative $|(f_c^n)'(z)| \leq 1$.
So, the curves are described as some of the roots of the following degree $2^n$ polynomial in $z$ (but note that cycles of every length appear in that plot - so certain pieces will require arbitrarily large $n$ to describe):
$$f_c^n(z)-z.$$
You can slightly reduce this by noting that if $m$ divides $n$ then $f_c^m(z)-z$ divides $f_c^n(z)-z$, which at least lets us factor the polynomial a little bit. As far as I know, the only $n$ for which the solutions of this have a form with radicals is $n=1$ (the fixed point) and $n=2$ (the two-cycle).
You can certainly, however, solve these equations using numerical methods for solving polynomials - and even something simple such as Newton's method is going to converge a lot faster than finding the cycles just by iterating a single point (as is how bifurcations diagrams are usually made) under $f_c$ itself.


text:
Q: Is there any more subtle convention for GPIO pin labelling between overlines, asterisks, and/or inverter symbols? As a firmware developer, I've been given an old schematic that seems to have an inconsistency between pin naming conventions. Some of the signal lines from the microcontroller are labeled with an overbar e.g. \$\text{ENCABULATOR}\,\overline{\text{POWER}}\$ while others are labelled with an asterisk like \$\text{Warp Core On*}\$.
In both cases, inspecting the circuit downstream, it is often apparent that the "sense" of the pin is inverted whenever either notation is used. That is, I would need to drive both the "Encabulator" and the "Warp Core" pin low to turn the respective device on.
My suspicion is that this schematic was edited by multiple people, and some of them knew how to add overbars to labels in whatever app they were using, while others simply typed in an asterisk instead — perhaps alluding to the pin plus inverter symbol "dot" convention?
Regardless, is it most likely that this is a simple inconsistency within the schematic? Or might there be a more subtle meaning, like declaring different intents regarding pull-ups or drive levels or other pin sourcing/sinking behaviors?
Of course only the original team could answer for sure but before I pester them about it I'm curious if there's any convention here that would already be recognizable to someone less on the software and more on the hardware side.

A: No, it's just people using different low-true conventions based on what they're used to. I'll show examples below.
Overbars in schematics are problematic these days as they aren't normal ASCII characters that one can deal with using a text editor. With the popularity of text-based hardware description languages like Verilog and VHDL, this becomes a major issue.
Noting this, a few text-based approaches have emerged to indicate low-true signals:

*

*backslash after each letter (e.g., R\A\S\) - used in OrCAD, which translates this to overbar. While this works, it's a royal pain to use. Regardless, you'd rightly also add a bubble to such a pin to indicate low-true.

*asterisk at the end (e.g., DTACK*) - 68000 and NuBus. Also gets a bubble.

*pound sign at the end (e.g., RESET#) - Intel. Yep, bubble again.

*'n' preceding (nRESET) - ARM. Bubble, too.

*'n' at the end (RESETn) - AXI / AMBA, also from ARM. Bubble here as well.

There are some others, but the trailing-n convention seems to be the most used now. This applies even for names that indicate both polarities, for example:

*

*RD/WRn or RD_WRn, for high = read and low = write.

Diff pairs use a few conventions:

*

*DP/DM: USB2

*HSOp/HSOn: PCIe

*A+/A-: SATA

There was an attempt some time ago to introduce a standard symbology for this and other issues in schematics: IEEE-STD-315. It wasn't widely adopted, and in retrospect, seems downright silly when working with large ICs and hardware description languages. More about that standard here: https://resources.pcb.cadence.com/blog/2020-working-with-standardized-ieee-315-1975-e-cad-symbols.
Instead, pin attributes on CAD symbols and hardware description languages made this graphic standard largely irrelevant.


text:
Q: What's the easiest way to add Java servlets to a WAMP configured machine? I have WAMP installed on my local machine and am looking to serve up charts using jFree's Eastwood charting, which requires me to use servlets. So basically I will insert images with src tags that have URLs pointing to my servlet on the same machine.
What's the easiest way to enable servlets on the same machine? Do I need to install a servlet server on a different port? Or is there a way to integrate it into WAMP?

A: You have a couple of choices.
The easiest is to get a Web container such as Tomcat or Jetty and run it on a different port (by default it's usually 8080).
A Web container can be integrated into Apache and this tends to be what happens in production sites. See Tomcat-Apache HOWTO or Apache 2 with Tomcat 6: How to Configure. It's probably overkill for a local install.


text:
Q: How to prove an isometry is injective? So I was given the following statement:
$f:\mathbb E^{2}\longrightarrow \mathbb E^{2}$ is an isometry if and only if $\forall X,Y\in  \mathbb E^{2}, d(X,Y)=d(f(X),f(Y))$.
How would I prove that $f$ is an injective?

A: $f(x)=f(y)$ implies that $d(f(x),f(y))=0=d(x,y)$ and $x=y$ since $d$ is a metric


text:
Q: Red-Black Tree Deletion Partially Working I implemented a red black tree in c++ with find, insert and delete. The delete only works for right side nodes and for the root node. I can't figure out why it isn't working for any of the left side nodes. Here is my code:
Node* searchNode(Node* root, int value){
    Node* temp = root;
    while (temp != NULL){
        if (temp->val == value){
            return temp;
        }
        else if (temp->val < value){
            temp = temp->right;
        }
        else if (temp->val > value){
            temp = temp->left;
        }
    }
}

Node* sibling(Node* node){
    if ((node == NULL) || (node->parent == NULL)){
        return NULL;
    }
    if (node == node->parent->left){
        return node->parent->right;
    }
    else{
        return node->parent->left;
    }
}
Node* maxNode(Node* node){
    while (node->right != NULL){
        node = node->left;
    }
    return node;
}
void replaceNode(Node* old, Node* new_node){
    if (old->parent == NULL){
        old = new_node;
    }
    else{
        if (old == old->parent->left){
            old->parent->left = new_node;
        }
        else{
            old->parent->right = new_node;
        }
    }
    if (new_node != NULL){
        new_node->parent = old->parent;
    }
}
void deleteNode(Node* root, int value){

    Node* child;
    Node* temp = searchNode(root, value);
    if (temp == NULL){
        return;
    }
    if (temp->left != NULL&&temp->right != NULL){
        Node* pred = maxNode(temp->right);
        temp->val = pred->val;
        temp = pred;
    }
    if (temp->left == NULL || temp->right == NULL){
        if (temp->right == NULL && temp->left == NULL){
            child = temp;
        }
        else if (temp->right == NULL){
            child = temp->left;
        }
        else{
            child = temp->right;
        }
    }
        if (temp->color == 1){
            temp->color = child->color;
            delete_case1(root, child);
        }

        replaceNode(temp, child);
        delete temp;

}
void delete_case6(Node* root, Node* n)
{
    Node *s = sibling(n);

    s->color = n->parent->color;
    n->parent->color = 1;

    if (n == n->parent->left) {
        s->right->color = 1;
        rotate_left(root, n->parent);
    }
    else {
        s->left->color = 1;
        rotate_right(root, n->parent);
    }
}
void delete_case5(Node* root, Node* n)
{
    Node *s = sibling(n);

    if (s->color == 1) {
        if ((n == n->parent->left) &&(s->right->color == 1) &&(s->left->color == 0)) {
            s->color = 0;
            s->left->color = 1;
            rotate_right(root, s);
        }else if ((n == n->parent->right) &&(s->left->color == 1) &&(s->right->color == 0)) {
            s->color = 0;
            s->right->color = 1;
            rotate_left(root, s);
        }
    }
    delete_case6(root, n);
}
void delete_case4(Node* root, Node* n)
{
    Node *s = sibling(n);

        if ((n->parent->color == 0) && (s->color == 1) && (s->left->color == 1) && (s->right->color == 1)) {
            s->color = 0;
            n->parent->color = 1;
        }
        else{
            delete_case5(root, n);
        }

    }
void delete_case3(Node* root, Node* n){
    Node* s = sibling(n);
    if ((n->parent->color == 1) &&(s->color == 1) &&(s->left->color == 1) &&(s->right->color == 1)) {
        s->color = 0;
        delete_case1(root, n->parent);
    }
    else
        delete_case4(root, n);
}
void delete_case2(Node* root, Node* n){
    Node *s = sibling(n);
    if (s->color == 0){
        n->parent->color = 0;
        s->color = 1;
        if (n == n->parent->left){
            rotate_left(root, n->parent);
        }
        else if (n == n->parent->right){
            rotate_right(root, n->parent);
        }
    }
    delete_case3(root, n);
}
void delete_case1(Node* root,Node* n){
    if (n->parent != NULL){
        delete_case2(root,n);
    }
}

void main(){
    ABTree* ABtree=new ABTree;
    ABtree->root = NULL;
    insertTree(ABtree->root, 15);
    insertTree(ABtree->root, 8);
    insertTree(ABtree->root, 2);
    insertTree(ABtree->root, 9);
    insertTree(ABtree->root, 10);
    insertTree(ABtree->root, 12);
    insertTree(ABtree->root, 18);
    insertTree(ABtree->root, 25);
    insertTree(ABtree->root, 20);
    printTree(ABtree->root);
    Node* search=searchNode(ABtree->root, 18);
    cout << endl;
    cout << search->val<<endl;
    deleteNode(ABtree->root, 8);
    printTree(ABtree->root);
}

For example if i want to delete either 8/9/2 the program crashes at delete_case4 at the if statement.
Thanks in advance!


text:
Q: How to decrease the opacity of only background in HTML, CSS? `
<!DOCTYPE html>

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

Change only background opacity not text. When I am run this code it has shown  me both opacity decrease background and text.<y /h1>

        Here I have taken h1 and give id

`

I want to decraese opacity only upper side of image but i am not getting solution.


text:
Q: not being able to persist entity in JPA in spring 3 I am not being able to persist entity in JPA, although findAll works
here.
Here is the JpaDAO

package aop.web.teacher.dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public abstract class JpaDAO extends JpaDaoSupport {
 protected Class entityClass;

 private static Logger log = Logger.getLogger(JpaDAO.class);

 @SuppressWarnings("unchecked")
 public JpaDAO() {
  ParameterizedType genericSuperclass = (ParameterizedType) getClass()
    .getGenericSuperclass();
  this.entityClass = (Class) genericSuperclass
    .getActualTypeArguments()[1];
 }

 @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
 public void persist(E entity) {
  getJpaTemplate().persist(entity);
 }

 @Transactional
 public void remove(E entity) {
  getJpaTemplate().remove(entity);
 }

 @Transactional
 public E merge(E entity) {
  return getJpaTemplate().merge(entity);
 }

 @Transactional
 public void refresh(E entity) {
  getJpaTemplate().refresh(entity);
 }

 @Transactional
 public E findById(K id) {
  return getJpaTemplate().find(entityClass, id);
 }

 @Transactional
 public E flush(E entity) {
  getJpaTemplate().flush();
  return entity;
 }

 @SuppressWarnings("unchecked")
 @Transactional
 public List findAll() {
  Object res = getJpaTemplate().execute(new JpaCallback() {

   public Object doInJpa(EntityManager em) throws PersistenceException {
    Query q = em.createQuery("SELECT h FROM "
      + entityClass.getName() + " h");
    return q.getResultList();
   }

  });

  return (List) res;
 }

 @SuppressWarnings("unchecked")
 @Transactional
 public Integer removeAll() {
  return (Integer) getJpaTemplate().execute(new JpaCallback() {

   public Object doInJpa(EntityManager em) throws PersistenceException {
    Query q = em.createQuery("DELETE FROM " + entityClass.getName()
      + " h");
    return q.executeUpdate();
   }

  });
 }

}

Here is the TestDao class

package aop.web.teacher.dao;

import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import aop.web.teacher.rmodels.Teachermaster;

@Service
@Repository
public class TestDaoImpl extends JpaDAO implements TestDao {

 @Autowired
 EntityManagerFactory entityManagerFactory;

 @PersistenceContext
 private EntityManager em;

 @PostConstruct
 public void init() {
  super.setEntityManagerFactory(entityManagerFactory);
 }

 public int saveTeacher() {
  List teacherList = findAll();
  Teachermaster m1 = teacherList.get(0);
  logger.info("Found " + m1.getId() + " and " + m1.getRace());
  m1.setRace(m1.getRace() + "::" + System.currentTimeMillis());
  logger.info("New " + m1.getId() + " and " + m1.getRace());
  persist(m1);
  return 0;
 }

}

Here is the spring context xml
http://pastebin.com/pKqzW9h1
Here the findAll works
but when we make a change to the attribute of the Teachermaster
then persist or merge does not seem to save the entity...
If we flush it we get exception
javax.persistence.TransactionRequiredException: no transaction is in progress

Please advise

A: Spring uses proxy-based AOP, therefore aspects (including transactional aspect) are not applied when methods are called from the same class.
Generally speaking

*

*@Transactional annotations should be usually placed on service methods rather than on DAO methods

*Your saveTeacher() looks like a service method, it would be better to place it in the separate service class and annotate as @Transactional

*You don't need persist() in saveTeacher() - changes made to persistent objects should be saved automatically

*Beware of dynamic proxy vs target class proxy distinction (regarding to TestDao) - see the links below

See also:

*

*7.6.1 Understanding AOP proxies

*10.5.1 Understanding the Spring Framework's declarative transaction implementation

A: You are calling a local method when invoking persist() from your test class. This way the proxy that would create transactions is not invoked so your call to persist() has no transaction.
The way to do this properly is to have the test class not extend the object under test but have it injected. This way the proxy will be triggered and the transaction will be created.
By the way, I must add that I find your class design a little bit beculiar. May I suggest creating a structure like the following?
DAO interface:
public interface FooDao {
    void persist(Foo foo);
    // ...
}

DAO implementation:
public class FooDaoImpl implements FooDao {
    @PersistenceContext
    private EntityManager entityManager;

    @Transactional
    public void persist(Foo foo) {
        entityManager.persist(foo);
    }
}

Test class:
@RunWith(SpringJunit4ClassRunner.class)
@ContextConfiguration(...)
public class FooDaoTest {
    @Autowired
    private FooDao fooDao;

    @Test
    public void testPersist() {
        // do some testing
    }
}

You can, if you wish, extract most of the logic in the DAO implementations into a generic superclass.


text:
Q: How to make my Asp.net webforms Application as Progressive web application with dynamic file to cache i have tried to make my Asp.net Application as a progressive web application and i successfully made one. but the thing is there any way to cache my pages without being shown in serviceworker. because there might be security issue if someone knows my actual page name for example.
./Checkout.aspx.. etc

A: you can make an Asp.net Web app as PWA but dynamic files are not yet supported.
Sure you can , but the dynamic pages for cache will be a geniue
on your pre-cache files you must have to provide an array of items (Files/Images) to be cached

*

*pages

*images

*js files
etc
you need to provide files to cache and your service worker will be public too.


text:
Q: clickhouse: Invalid use of collate in window functions Question
- clickhouse: Invalid  use of collate in window functions

Version
- 22.8.5.1

Recurrence
    create table test_window_collate(c1 String, c2 String) engine=MergeTree order by c1;
    insert into test_window_collate values('1', '上海');
    insert into test_window_collate values('1', '北京');
    insert into test_window_collate values('1', '西安');

    select c2, groupArray(c2) over (partition by c1 order by c2  asc collate 'zh_Hans_CN') as res  from test_window_collate order by c2  asc collate 'zh_Hans_CN';

Actual result
| c2       |    res              |
| -------- |--------------       |
|北京      |   [上海,北京]       |
|上海      |   [上海]             |
|西安      |   [上海, 北京, 西安]|

Expected result
| c2       |      res          |
| -------- |--------------     |
|北京      |   [北京]           |
|上海      |   [北京,上海]     |
|西安      |   [北京,上海,西安]|

Guess the cause
It's not the expected result because invalid  use of collate in window functions.
Code analysis
- File ParserSelectQuery.cpp
- Line 164
- Code         `if (!exp_list_for_select_clause.parse(pos, select_expression_list, expected))`

The code here does not give s_order_by(Line 262) a chance to get the collate
- File ExpressionAnalyzer.cpp
- Line 1951
- Code `&& !query_analyzer.hasWindow()`

This code causes collator not to be created
How to make window function support collate?


text:
Q: Python Model Callbacks I'm trying to implement a simple model class that executes callbacks whenever an attribute is set in the class, however I am getting an AttributeError when trying to use this in my application. It seems the instance doesn't have the attributes I setup in my initializer and I'm a bit confused as to why. I haven't used magic methods much, so some elaboration might be helpful:
class ReportModel(object):

    def __init__(self):
        self.current_date = None
        self.prior_date = None
        self._callbacks = defaultdict([])

    def __setattr__(self, attr, value):
        object.__setattr__(self, attr, value)
        for func in self._callbacks[attr]:
            func(value)

    def set_callback(self, attr, function):
        self._callbacks[attr].append(function)

Traceback:
AttributeError: 'ReportModel' object has no attribute '_callbacks'

A: Your __setattr__ method is called during the class instantiation when __init__ is running and setting self.current_date and self.prior_date.
To fix this you have to use try, except block around callback calling to prevent the error.
    try:
        for func in self._callbacks[attr]:
            func(value)
    except:
        pass

A: Since you have overridden __setattr__(), when you do self.current_date = None in __init__() it will call your __setattr__() implementation which will try to access self._callbacks.  This is what causes the AttributeError.
Here is one option to fix this:
class ReportModel(object):

     def __init__(self):
         object.__setattr__(self, '_callbacks', defaultdict(list))
         self.current_date = None
         self.prior_date = None

     def __setattr__(self, attr, value):
         object.__setattr__(self, attr, value)
         for func in self._callbacks[attr]:
             func(value)

     def set_callback(self, attr, function):
         self._callbacks[attr].append(function)

This adds the _callbacks attribute using object.__setattr__() before any other attributes are added, so that future calls to __setattr__() for your ReportModel instance will not choke on accessing self._callbacks.
Alternatively, you could modify __setattr__() to check for the existence of the _callbacks attribute:
class ReportModel(object):

     def __init__(self):
         object.__setattr__(self, '_callbacks', defaultdict(list))
         self.current_date = None
         self.prior_date = None

     def __setattr__(self, attr, value):
         object.__setattr__(self, attr, value)
         if hasattr(self, '_callbacks'):
             for func in self._callbacks[attr]:
                 func(value)

     def set_callback(self, attr, function):
         self._callbacks[attr].append(function)


text:
Q: Pass through 302 respond and save the html for the redirect page I have write a code to get the html code from security website. I get the 302 respond but i am not sure how to save the html for the webpage. Below is my code.
#!/usr/bin/perl -w

use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Request;
use HTTP::Request::Common qw(POST);
use HTTP::Cookies;

my $URL="http://www.example.com";
my $UA = LWP::UserAgent->new();
$UA->ssl_opts( verify_hostnames => 0 );

my $req =HTTP::Request::Common::POST("$URL",
   Content_type=>'form-data',
   Content =>[
     'username'=>'user',
     'password'=>'password',
   ]
);
$req->header('Cookie' =>q(TIN=287000; LastMRH_Session=439960f5; MRHSession=78c9c47291c1fcedae166121439960f5));

my $resp=$UA->request($req);

if ($resp->is_success) {

    my $res2 = $UA->post($resp->base, []);
    print $res2->decoded_content;
}

Below is the 302 respond i get
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

    <title>302 Found</title>

Found

The document has moved here.

    <address>Apache/2.2.3 (CentOS) Server at www Port 80</address>

I want to get the html information from the website www.XXX.com but i only can get the 302 respond. I think i stuck in the redirect loop but not sure how to pass trough it.

A: The problem with this is LWP::UserAgent does not allow for the "post" method by default.  You need the following code to allow for the POST method:
push @{ $UA->requests_redirectable }, 'POST';

so, like so:
my $UA = LWP::UserAgent->new();
push @{ $UA->requests_redirectable }, 'POST';
$UA->ssl_opts( verify_hostnames => 0 );


text:
Q: mysql stored procedure parameters don't seem to work with "@" (At sign) I'm changing a MS SQL database over to MySQL.
I've rewritten one of the stored procedures which takes a parameter called @Account_Number.  When I run the stored procedure in MySQL I get the following Message:  Error Code: 1048 Column 'Account_Number' cannot be null.
Using the workbench I finally tinkered around and figured out that when I removed the "@" from my stored procedures and renamed them like parmAccount_Number the stored procedure would execute.
I really want to keep the stored procedure input parameters named the same, and I don't want to go back and rename my MS SQL parameters... just in case I want to flip flop Databases.
I can't find any info on what MySQL does with the "@"....
Is there a way to make it work with "@"  ?
EDIT
Declaring the stored procedure
CREATE PROCEDURE `My_sp`(
 `@Account_Number` varchar(8),....)

insert portion of sp
insert into
My_Table
(
    Account_Number, ...
)
values
(
    @Account_Number,...
)

A: No, you can't name MySQL procedure variables starting with the @ sign.
The @ sign character signifies a MySQL User-Defined Variable, which is quite different than a procedure variable.
The big differences is that user defined variable aren't declared (they don't have a datatype), and they have scope within a session (database connection), not just a procedure. It persists for the entire session. (This also means it's subject to modification anywhere in the session, any SQL statement, trigger, function or procedure can modify it, which makes it very useful, and also makes it a potential pitfall.
It's possible to use user defined variables as the actual values passed to a procedure or function. But you can't name MySQL procedure variables or parameters starting with an @ sign.
I believe this is compliant with the SQL 2003 standards.
Documentation here:
http://dev.mysql.com/doc/refman/5.5/en/user-variables.html
UPDATE
Interesting.
Given that you are able to get a procedure compiled by enclosing the parameter name in backticks (as shown in the example statement you added)...
You might try enclosing the parameter name reference in the INSERT statement in backticks as well. (I've never tested that; I've never tried "back ticking" variable names before; I've never seen that done before.)  But if the procedure is actually compiling, then maybe that would work.


text:
Q: How can I hide a modal element in Dittofi? How do I use a "modal" element in #Dittofi. When I add the element it covers the entire page and I cannot access elements underneed.

A: When you add the modal box, you need to select the box marked "Modal" in the breadcrumb trial at the bottom of the page.

Then you can select the modal settings box to either show or hide the modal box.

Let me know if that works for you?


text:
Q: Replace only domain part with awk in the second column when this lines are given in a file:
docker://docker.io/some-repo/my-image:v1.1.2 docker://docker.io/some-repo/my-image:v1.1.2
docker://ghcr.io/some-repo/my-image:v1.1.2 docker://ghcr.io/some-repo/my-image:v1.1.2
docker://ecr.aws/some-repo/my-image:v1.1.2 docker://ecr.aws/some-repo/my-image:v1.1.2

if i execute
awk -F: -v var2="example.local/" 'BEGIN{FS=OFS=" "} {gsub(/(\/\/.*\.[a-z{2,6}]*\/)/, var2, $2)} 1'

results in
docker://docker.io/some-repo/my-image:v1.1.2 docker:example.local/some-repo/my-image:v1.1.2
docker://ghcr.io/some-repo/my-image:v1.1.2 docker:example.local/some-repo/my-image:v1.1.2
docker://ecr.aws/some-repo/my-image:v1.1.2 docker:example.local/some-repo/my-image:v1.1.2

How can i only replace the domain part in the 2nd column? In this case "docker.io|ghcr.io|ecr.aws" in a generic way.

A: With your shown samples please try following GNU awk solution. In case // in output before new value is needed then change regex to ^(.*docker:\/\/)[^/]*\/(.*) in both the solutions.
awk -v var="example.local/" '
match($0,/^(.*docker:)\/\/[^/]*\/(.*)/,arr){
  print arr[1] var arr[2]
}
'  Input_file

Explanation: Adding detailed explanation for above awk code. Using GNU awk's match function here. Where I am using regex ^(.*docker:)\/\/[^/]*\/(.*) to do the matches. This expression is creating 2 capturing groups(1st value from starting of line to till docker:// AND 2nd after 1st occurrence of / which comes after docker.io|ghcr.io|ecr.aws values to till end of the line). As per GNU awk's match function it creates an array(named arr here) which stores values of capturing groups in to it. Once match condition is TRUE then simply printing arr's 1st value followed by var(new value) followed by arr's 2nd value.

Bonus solution: In case you are ok with perl one-liner solution then you may try following, using lazy matching concept in its regex to get the exact match, creating 2 capturing groups and then substituting it with only required parts only.
perl -pe 's/^(.*?\s+docker:)\/\/.*?\/(.*)$/$1\/example.local\/$2/' Input_file

A: you might try:
awk -v domain2=example.com '{sub("://[^/]*", "://" domain2, $2)} 1'

A: For the example data, perhaps a pattern without matching // would be acceptable.
As you replace only 1 occurrence, you might use sub to match the first occurrence of the pattern.
For example
awk -v var2="example.local/" '{sub(/[^./]+\.[a-z]{2,6}\//, var2, $2)}1' file

The pattern matches:

*

*[^./]+ Match 1+ chars other than / or .

*\.[a-z]{2,6} Match a dot and 2-6 times a char a-z

*\/ Match /
Output
docker://docker.io/some-repo/my-image:v1.1.2 docker://example.local/some-repo/my-image:v1.1.2
docker://ghcr.io/some-repo/my-image:v1.1.2 docker://example.local/some-repo/my-image:v1.1.2
docker://ecr.aws/some-repo/my-image:v1.1.2 docker://example.local/some-repo/my-image:v1.1.2

Else you can match the leading docker:// at the start of the string,  and use that in the replacement:
awk -v var2="example.local/" '{sub(/^docker:\/\/[^./]+\.[a-z]{2,6}\//, "docker://" var2, $2)}1' file


text:
Q: Как на javascript создать своё событие? Интересует, возможно ли на javaScript создать свое событие, чтоб на него можно было поставить слушатель события.
Например есть два блока, как создать событие если кто-то кликнул на первый блок, это событие click_1, а если на второй блок, событие click_2.
Нужно, чтоб была возможность повесить на эти события обработчик, как на обычный клик:
$( "#target" ).click_1(function() {
  alert( "click_1" );
});

Пример разметки:

.block_1{
  width:300px;
  height:300px;
  background-color: aqua;
}

.block_2{
  width:300px;
  height:300px;
  background-color: chartreuse;
}

 1

 2

Как такое реализовать на js?

A: Благодаря методам trigger и triggerHandler (triggerHandler можно условно назвать урезанной версией trigger) вы можете генерировать стандартные и кастомные события
http://api.jquery.com/trigger/
http://api.jquery.com/triggerHandler/
Вы также можете группировать общие события (события одного компонента например), используя namespace https://api.jquery.com/event.namespace/
$element.on('event.namespace', function (e) {
  ...
});
...
$element.trigger('event.namespace');

Однако в вашем примере на самом деле лучше подписываться на события конкретного элемента:

$('.block_1').on('click', function () {
  alert('Block 1');
});
$('.block_2').on('click', function () {
  alert('Block 2');
});
.block_1 {
  width:300px;
  height:300px;
  background-color: aqua;
}

.block_2 {
  width:300px;
  height:300px;
  background-color: chartreuse;
}

1

2

Можно даже воспользоваться единым обработчиком:

$('.js-block').on('click', function () {
  alert('Block ' + $(this).data('blockNum'));
});
.block_1 {
  width:300px;
  height:300px;
  background-color: aqua;
}

.block_2 {
  width:300px;
  height:300px;
  background-color: chartreuse;
}

1

2

А делегирование позволит отлавливать события динамически создаваемых элементов:

var $body = $('body'),
    addBlock = (function  () {
  var $lastBlock = $('.js-block').last(),
      className = ['block_2', 'block_1'],
      counter = 0 || $lastBlock.data('blockNum');

  return function () {
    var $block = $('
');
    counter++;
    $block.data('blockNum', counter);
    $block.addClass(className[counter % 2]).addClass('js-block').text(counter);
    $body.append($block);
  };
})();

$body.on('click', '.js-block', function () {
  alert('Block ' + $(this).data('blockNum'));
  addBlock();
});
.block_1 {
  width:300px;
  height:300px;
  background-color: aqua;
}

.block_2 {
  width:300px;
  height:300px;
  background-color: chartreuse;
}

1

2

Но если вам все же нужно ловить глобально генерируемые события (только не делайте этого в условиях данного примера - это будет не очень хорошим тоном), воспользуйтесь паттерном "Медиатор". Его простую реализацию для jquery можно найти здесь https://github.com/cowboy/jquery-tiny-pubsub

/*! Tiny Pub/Sub - v0.7.0 - 2013-01-29
* https://github.com/cowboy/jquery-tiny-pubsub
* Copyright (c) 2013 "Cowboy" Ben Alman; Licensed MIT */
(function($) {

  var o = $({});

  $.subscribe = function() {
    o.on.apply(o, arguments);
  };

  $.unsubscribe = function() {
    o.off.apply(o, arguments);
  };

  $.publish = function() {
    o.trigger.apply(o, arguments);
  };

}(jQuery));

$('.js-block').on('click', function() {
  $.publish('click_' + $(this).data('blockNum'));
});

$.subscribe('click_1', function() {
  alert('Block 1');
});

$.subscribe('click_2', function() {
  alert('Block 2');
});
.block_1 {
  width: 300px;
  height: 300px;
  background-color: aqua;
}
.block_2 {
  width: 300px;
  height: 300px;
  background-color: chartreuse;
}

1

2

Советую подробнее прочитать про паттерны проектирования http://largescalejs.ru/

A: На чистом JS смотрите Создание и вызов событий:

var click1 = new Event('click_1')
  ,click2 = new Event('click_2')
  ,b1 = document.getElementById('block_1')
  ,b2 = document.getElementById('block_2')
;

// слушать события
b1.addEventListener('click_1', function (e) { console.log("Clicked 1"); }, false);
b2.addEventListener('click_2', function (e) { console.log("Clicked 2"); }, false);

// вызвать события
b2.dispatchEvent(click2);
#block_1,#block_2{width: 50px;height: 50px;margin: 10px;text-align: center;float: left;cursor: pointer;}#block_1{background-color: aqua}#block_2{background-color: chartreuse}

1

2

При этом стандартное событие клика остаётся, и если хотите вызывать созданные события по клику, надо ловить клик, и из его обработчика делать dispatchEvent(ваше нестандартное событие)


text:
Q: How do I make a clickable UIButton with animated alpha? I'd like to create an UIButton that "breathes", changes its alpha from 1.0 to 0.7 and back again, repeating. The code is quite simple, but when the animation runs, the button is not clickable. Which is a pity, for a button. I can understand why the button might not be clickable when the animation changes its position, but changing alpha seems quite harmless to me. Is there a way to make the button clickable, keeping the animation and not animating by hand?

A: Use opacity.
UIButton *btnTest = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnTest.frame = CGRectMake(0, 0, 100, 100);
[btnTest setTitle:@"Breathe" forState:UIControlStateNormal];
[btnTest addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnTest];

CABasicAnimation *fadeAnimation=[CABasicAnimation animationWithKeyPath:@"opacity"];
fadeAnimation.fromValue=[NSNumber numberWithFloat:0.7];
fadeAnimation.toValue=[NSNumber numberWithFloat:1.0];
fadeAnimation.duration=1.0;
fadeAnimation.repeatCount=INFINITY;
fadeAnimation.autoreverses=YES;

[btnTest.layer addAnimation:fadeAnimation forKey:@"fadeInOut"];


text:
Q: Enumerate with tabular-like characteristics I want the text to display more like the first example, but automatically enumerate like the second one and be indented a tab away.
\begin{tabular}{lll}
(a)& $A\cup B=\{x:x\in A$ oder $x\in B\}$& Vereinigung von $A$ und $B$\\
(b)& $A\cap B=\{x:x\in A$ und $x\in B\}$& Schnitt von $A$ und $B$\\
(c)& $A\backslash B=\{x:x\in A$ und $x\notin B\}$& Differenz, sprich "A ohne B"\\
(d)& $A\times B=\{(x,y):x\in A$ und $y\in B\}$& Kartesisches Produkt\\
& Für $A=B$ schreibe kurz $A^2$
\end{tabular}

\begin{enumerate}[label=(\alph*)]
    \item $A\cup B=\{x:x\in A$ oder $x\in B\}$ \hfill Vereinigung von $A$ und $B$
    \item $A\cap B=\{x:x\in A$ und $x\in B\}$ \hfill Schnitt von $A$ und $B$
    \item $A\backslash B=\{x:x\in A$ und $x\notin B\}$ \hfill Differenz, sprich "A ohne B"
    \item $A\times B=\{(x,y):x\in A$ und $y\in B\}$ \hfill Kartesisches Produkt \\
    Für $A=B$ schreibe kurz $A^2$ %Stand zumindest so ohne weitere Aufzählung an der Tafel... ja, echt komisch, müssen wir später in erfahrung bringen
\end{enumerate}

A: Similar to Zarko's solution, but a little bit more 'condensed', using \newcolumntype.
\documentclass{article}
\usepackage{amsmath}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[ngerman]{babel}
\usepackage[babel,style=german]{csquotes}
\usepackage{array}

\newcounter{rowcntr}  % new counter for enumerating table rows
\renewcommand\therowcntr{(\alph{rowcntr})}

\newcolumntype{N}[1]{>{\raggedleft\refstepcounter{rowcntr}\therowcntr\arraybackslash}p{#1}}
\newcolumntype{L}[1]{>{\raggedright}p{#1}}

\begin{document}
\begin{tabular*}{\linewidth}{N{2cm}*{2}{L{0.45\linewidth}}}
  \label{foo} & $A\cup B=\{x:x\in A$ oder $x\in B\}$          &  Vereinigung von $A$ und $B$  \tabularnewline
  & $A\cap B=\{x:x\in A$  oder $x\in B\}$           & Schnitt von $A$ und $B$\tabularnewline
  & $A\setminus B=\{x:x\in A$ und $x\notin B\}$  & Differenz, sprich \enquote{A ohne B} \tabularnewline
  & $A\times B=\{(x,y):x\in A$ und $y\in B\}$   Für $A=B$ schreibe kurz $A^2$               & Kartesisches Produkt\tabularnewline
\end{tabular*}

See \ref{foo}
\end{document}

A: like this?

\documentclass{article}
\usepackage{amsmath}
\usepackage{array}
\newcounter{tabitem}  % new counter for enumerating table rows
\renewcommand\thetabitem{(\alph{tabitem})}
\newcommand{\getTabItem}{\refstepcounter{tabitem}\thetabitem}% rows can be labeled and referenced

    \begin{document}
\begin{tabular*}{\linewidth}{@{}
                             >{\getTabItem}l
                        *{2}{>{\raggedright\arraybackslash}p{0.45\linewidth}}
                             @{}}
    & $A\cup B=\{x:x\in A$ oder $x\in B\}$          & Vereinigung von $A$ und $B$\\
    & $A\cap B=\{x:x\in A$ und $x\in B\}$           & Schnitt von $A$ und $B$\\
    & $A\setminus B=\{x:x\in A$ und $x\notin B\}$  & Differenz, sprich "A ohne B``\\
    & $A\times B=\{(x,y):x\in A$ und $y\in B\}$
        Für $A=B$ schreibe kurz $A^2$               & Kartesisches Produkt\\
\end{tabular*}
\end{document}

A: Here is a code which relies on listliketab and tabularx. The rows can be cross-referenced:
\documentclass[11pt, a4paper, german]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{babel}
\usepackage{geometry}
\usepackage{amsmath}
\usepackage{tabularx, listliketab}

    \begin{document}

\storestyleof{enumerate}
\begin{listliketab}
\newcounter{tabenum}\setcounter{tabenum}{0}\renewcommand\thetabenum{(\alph{tabenum})}
\newcommand{\tabitem}{\refstepcounter{tabenum}\thetabenum}
\begin{tabularx}{\linewidth}{@{}L >{\hsize=1.2\hsize}X>{\hsize=0.8\hsize\raggedleft\arraybackslash}X @{}}
  \tabitem & $A\cup B=\{x:x\in A$ oder $x\in B\}$ & Vereinigung von $A$ und $B$\\
   \tabitem\label{row-2} & $A\cap B=\{x:x\in A$ und $x\in B\}$ & Schnitt von $A$ und $B$\\
   \tabitem & $A\setminus B=\{x:x\in A$ und $x\notin B\}$ & Differenz, sprich "A ohne B``\\
   \tabitem & $A\times B=\{(x,y):x\in A$ und $y\in B\}$
        Für $A=B$ schreibe kurz $A^2$ & Kartesisches Produkt\\
\end{tabularx}
\end{listliketab}

We read in row \ref{row-2}

\end{document}


text:
Q: seaborn or matplotlib bar plot multiple dataframes side by side Using matplotlib I was trying to put bar plots next to each other. This is pretty common and I've gone through a bunch of stackoverflow pages but something still isn't right.
df1
    Net Count   date
0   AA  242624806   2018-03-01 00:00:00.000
1   AA  213729127   2018-03-01 00:01:00.000
2   AA  4482234727  2018-03-01 00:02:00.000
3   AA  26042386    2018-03-01 00:03:00.000
4   AA  13444400    2018-03-01 00:04:00.000

df2
    Net Count   date
0   BB  242806      2018-03-01 00:00:00.000
1   BB  729127      2018-03-01 00:01:00.000
2   BB  85872722    2018-03-01 00:02:00.000
3   BB  26006231    2018-03-01 00:03:00.000
4   BB  123115400   2018-03-01 00:04:00.000

df3
    Net Count   date
0   CC  452806      2018-03-01 00:00:00.000
1   CC  129127      2018-03-01 00:01:00.000
2   CC  858722      2018-03-01 00:02:00.000
3   CC  26216231    2018-03-01 00:03:00.000
4   CC  33115400    2018-03-01 00:04:00.000

Code:
x=df['date']  #since the date are the same in both tables I only have 1 x
y=df['count']
y2=d2['count']
y3=d2['count']

plt.figure(figsize=(15,8))
plt.bar(x,y,label="AA")
plt.bar(x,y2,label="BB")
plt.bar(x,y3,label="CC")

plt.title("Count by Networks")
plt.legend(title="Network")
plt.show()

Here is how it looks :
But I've tried align=edge, align=center and playing around with the widths but it is always overlapping.
How would I make this work so that the bars are not stacked so they are side by side?
Like this:

**** Updated with Answer *****
Y.Luo this worked for me the best in pandas like this:
dateindex=df1['date']

aa=dict(zip(x,df1['count']))
bb=dict(zip(x,df2['count']))
cc=dict(zip(x,df3['count']))
dd=dict(zip(x,df4['count']))
ee=dict(zip(x,df5['count']))

dfbar = pd.DataFrame({'AA': aa, 'BB': bb, 'CC': cc,'DD': dd, 'EE': ee}, index=dateindex)

# Non-stacked bar plot
dfbar.plot.bar(figsize=(16, 6))

plt.title("Count by Networks")
plt.legend(title="Network")
plt.show()

A: If you want a non-stacked bar plot with matplotlib, you would need to adjust the position for each dataframe yourself like this:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Example data
n=24
dateindex = pd.date_range(pd.datetime(2018, 1, 1), periods=n)
np.random.seed(1)
aa = pd.DataFrame(np.random.randn(n), columns=['count'], index=dateindex)
np.random.seed(2)
bb = pd.DataFrame(np.random.randn(n), columns=['count'], index=dateindex)
np.random.seed(3)
cc = pd.DataFrame(np.random.randn(n), columns=['count'], index=dateindex)

# Non-stacked bar plot
plt.figure(figsize=(16, 6))
width = 0.25
plt.bar(np.arange(len(aa))-width, aa.values, width, label="AA")
plt.bar(np.arange(len(aa)), bb.values, width, label="BB")
plt.bar(np.arange(len(aa))+width, cc.values, width, label="CC")
plt.xticks(np.arange(len(aa)), dateindex, rotation='vertical')

plt.title("Count by Networks")
plt.legend(title="Network")
plt.show()

ImportanceOfBeingErnest is correct. Pandas is the easiest since it does the adjustment for you:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Example data
n=24
dateindex = pd.date_range(pd.datetime(2018, 1, 1), periods=n)
np.random.seed(1)
aa = np.random.randn(n)
np.random.seed(2)
bb = np.random.randn(n)
np.random.seed(3)
cc = np.random.randn(n)
df = pd.DataFrame({'AA': aa, 'BB': bb, 'CC': cc}, index=dateindex)

# Non-stacked bar plot
df.plot.bar(figsize=(16, 6))

plt.title("Count by Networks")
plt.legend(title="Network")
plt.show()


text:
Q: How do I set up Debugging? In my wp-config.php, I have:
// Enable WP_DEBUG mode
define('WP_DEBUG', true);

// Enable Debug logging to the /wp-content/debug.log file
define('WP_DEBUG_LOG', true);

// Disable display of errors and warnings
define('WP_DEBUG_DISPLAY', false);
@ini_set('display_errors',0);

However, the debug.log file is empty. It wasn't being created so I created it and then set its permissions to 666, yet it remains empty. Can anyone help me?

A: I use a plugin for this issue. Even if debug is set to false, it still prints error to the screen in red.
It is easy and fast to create the plugin.

*

*In your plugins folder in your wordpress install, create a new file and call it anything you like, for instance, debugger-plugin.php.

*Open up your newly created file, and paste the following code in there and save it. (this code comes from this post on code.tutsplus.com/
<?php
/*
Plugin Name: Debugger Plugin
*/
function admin_alert_errors($errno, $errstr, $errfile, $errline){

    $errorType = array (
         E_ERROR                            => 'ERROR',
         E_CORE_ERROR           => 'CORE ERROR',
         E_COMPILE_ERROR        => 'COMPILE ERROR',
         E_USER_ERROR           => 'USER ERROR',
         E_RECOVERABLE_ERROR  => 'RECOVERABLE ERROR',
         E_WARNING              => 'WARNING',
         E_CORE_WARNING         => 'CORE WARNING',
         E_COMPILE_WARNING      => 'COMPILE WARNING',
         E_USER_WARNING         => 'USER WARNING',
         E_NOTICE               => 'NOTICE',
         E_USER_NOTICE          => 'USER NOTICE',
         E_DEPRECATED                   => 'DEPRECATED',
         E_USER_DEPRECATED      => 'USER_DEPRECATED',
         E_PARSE                => 'PARSING ERROR'
    );

    if (array_key_exists($errno, $errorType)) {
        $errname = $errorType[$errno];
    } else {
        $errname = 'UNKNOWN ERROR';
    }
ob_start();?>

    <?php echo $errname; ?> Error: [<?php echo $errno; ?>] <?php echo $errstr; ?> <?php echo $errfile; ?> on line <?php echo $errline; ?>

<?php
echo ob_get_clean();
}

set_error_handler("admin_alert_errors", E_ERROR ^ E_CORE_ERROR ^ E_COMPILE_ERROR ^ E_USER_ERROR ^ E_RECOVERABLE_ERROR ^  E_WARNING ^  E_CORE_WARNING ^ E_COMPILE_WARNING ^ E_USER_WARNING ^ E_NOTICE ^  E_USER_NOTICE ^ E_DEPRECATED    ^  E_USER_DEPRECATED    ^  E_PARSE );

*You can now activate your debugger plugin from the back-end whenever you want. No need to make changes to wp-config.php :-)


text:
Q: Does the COPY command create an intermediate container? Does the COPY command create an intermediate container to copy the files just like RUN command? I did not find any reference to this in the docs.

A: It does not actually create a container.
In the classic builder, Builder.performCopy() goes through the steps of assembling an augmented image: get the base image, create a new layer, actually copy files into the new layer, and then construct a new image.  While there is a variable named runConfigWithCommentCmd this just sets the per-layer description that's visible in docker history.
Contrast this with dispatchRun() which actually goes through the mechanics of creating and launching a container.  Remember that a container fundamentally wraps a single command, and in the case of COPY there's not an obvious command that could be run (nor, for that matter, is there guaranteed to be any runnable command in the container at all; consider a FROM scratch image).


text:
Q: Jquery issue with changing classes I'm creating a small box on one of my pages which will toggle between 3 different outputs based on the active tab. I set the left-most tab to be active upon loading and when the others are clicked this active tab becomes ordinary and the clicked tab becomes active. I created two classes, one called activeBoxTab and boxTab which are toggled between as you can see in the jsfiddle below. My issue is that whichever tab is set as the default active, becomes useless once another tab is clicked yet the other two can be clicked back and forth.
http://jsfiddle.net/rxYB7/2/
HTML:

Tab 1

Tab 2

Tab 3

JS:
$(document).ready(function () {
    $(".boxTab").click(function () {
        $(this).siblings(".activeBoxTab").attr('class', 'boxTab');
        $(this).attr('class', 'activeBoxTab');
        return false;
    });
});

A: You only bind the event handler to elements with class boxTab. But in your HTML, the "selected" element only has the class activeBoxTab. The event handler is never bound to that element and thus nothing happens when you click on it!
Just give it the boxTab class as well:

Tab 2

and change your event handler to:
$(this).siblings('.activeBoxTab').removeClass('activeBoxTab');
$(this).addClass('activeBoxTab');

A: You're only binding the click handler to the boxTab tabs and the originally active tab isn't a boxTab. You need to bind the click handler to both:
$(document).ready(function () {
    $(".boxTab, .activeBoxTab").click(function () {
        $(this).siblings(".activeBoxTab").attr('class', 'boxTab');
        $(this).attr('class', 'activeBoxTab');
        return false;
    });
});

Fixed fiddle: http://jsfiddle.net/rxYB7/4/
The does however mean that the click handler will fire when you re-click the currently active tab. If you want to avoid that you can check and abort in the click handler or use a live event check using '.on' to dynamically set the click handlers based on current class for all elements within the containing div.

A: Your first activeBoxTab has no click event. Thats why it's not working. You have to add both classes boxTab activeBoxTab to handle the event in that tab. Then you must remove or add activeBoxTab class.

Tab 1

Tab 2

Tab 3

$(document).ready(function () {
    $(".boxTab").click(function () {
        $('.activeBoxTab').each(function(index, value) {
            $(value).removeClass('activeBoxTab');
        });
        $(this).addClass('activeBoxTab');

        return false;
    });
});

Working demo


text:
Q: Create a share of USB drive with USBDLM In Windows XP this worked (from usbdlm.ini):
[OnArrival]
Letter=H
open=net share H$=H:\

On Windows 7 I get Access Denied errors. How can I add users other than Administrato
to the group of users allowed to run the net share command?
The version is the latest (V4.6.9.2,) and it's installed to C:\Program Files\usbdlm.


text:
Q: Writing Perl libraries I have been learning Perl for the past few weeks and I have made decent progress in learning the language. After reading various forums I came to know that it's better to write libraries than writing stand alone programs. I have absolutely no clue about writing libraries but I'd like to learn it. Can some body help me with this?
My understanding is we have the main script in .pm and call it from .pl. Correct me if im wrong.
If the below code is in time.pm,

*

*How do I call it from .pl?

*How do I pass the value of $t from .pl?

time.pm:
while(1)
{
       $Time = join ':', (localtime(time))[2, 1, 0];
       if ($Time eq  my $t)
        {
           //code
           print ($time);
        }
}

A: You need to have your main code in a .pl file that you would run. The library or module that you are building would go into a .pm file.
Inside of your main perl file (.pl) you need to include the module (.pm) file you wrote with something like:
use newmodule;
If you run into issues with it not finding the module you need to make sure that it is in perl's library path.
Once the module is included in your perl script you will be able to invoke it's functions.


text:
Q: Cherry pick only commits that touch a particular file What is a concise way to request "cherry pick from another branch only the commits that touch a particular file"?  i.e. the command git log ..other-branch afile gives a list of unmerged commits in other-branch that touch "afile"; how can I request that this same set of commits be replayed on the current branch?

A: git cherry-pick $(git log --reverse --pretty=format:"%H" filename)
Should do the trick. git log --reverse --pretty=format:"%H" filename basically gives you a newline separated list of SHA's of all commits that modified filename in reverse order so the commits merge in the correct order. We then feed the list to git cherry-pick.
git cherry-pick $(git rev-list --reverse HEAD -- filename)is another version of the above command provided by Magnus Bäck.


text:
Q: React Native import json file & read the content I tried to load an .json file and read the content. But all I get is an output like this:

this is my Code:
 import movies from './movies.json';

  /*
  ...
  */

  function componentWillMount() {
    return (
      fetch(movies).then((res) => res.json()).then((data) =>
      {this.setState({hugeText: data.something});
      })
    );
  }
  function searchForName(){
     var content = componentWillMount();
     alert(content);
  }

It would like to get the real content as a String.

A: I don't think you can use componentWillMount like that...
componentWillMount() {
  fetch(movies).then((res) => res.json()).then((data) => {
    this.setState({hugeText: data.something});
  });
}

searchForName() {
  alert(this.state.hugeText);
}

A: First of all, don't use ComponentWillMount:
From the docs:

UNSAFE_componentWillMount() is invoked just before mounting occurs. It
  is called before render(), therefore calling setState() synchronously
  in this method will not trigger an extra rendering. Generally, we
  recommend using the constructor() instead for initializing state.
Avoid introducing any side-effects or subscriptions in this method.
  For those use cases, use componentDidMount() instead.

Now, set a state variable in your component, to save the value that you will receive from that API call:
constructor(props){
  super(props);
  this.state = { hugeText: '' }
}

If you just want to render what the object is as a string, use:
JSON.stringify(your_object_here)

Use it like this:
function componentDidMount() {
  fetch(movies).then((res) => res.json())
    .then((data) => {
      this.setState({hugeText: JSON.stringify( data.something ) } , () => {
        alert(this.state.hugeText); // This will happen AFTER the state has been set
      });
    })
}

You can use this.state.hugeText afterwards in your render function for example.
Have a read at the setState API as well.