text:
Q: Java incompatible type error The following code is a part of a java program for making predictions with inception v3 model using Tensorflow library.
private static float[] executeInceptionGraph(byte[] graphDef, Tensor image) {
    try (Graph g = new Graph()) {
        g.importGraphDef(graphDef);
        try (Session s = new Session(g);
                Tensor result = s.runner().feed("DecodeJpeg/contents", image).fetch("softmax").run().get(0)) {
            final long[] rshape = result.shape();
            if (result.numDimensions() != 2 || rshape[0] != 1)
            {
                throw new RuntimeException(
                        String.format(
                                "Expected model to produce a [1 N] shaped tensor where N is the number of labels, instead it produced one with shape %s",
                                Arrays.toString(rshape)));
            }
            int nlabels = (int) rshape[1];

            return result.copyTo(new float[1][nlabels])[0];
        }
    }
}

The return statement however shows the error:
incompatable types, required:float,found:Object.

I tried type casting to float[] but that gave me a run time error "Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [[F cannot be cast to [F".
I downloaded the program from https://github.com/emara-geek/object-recognition-tensorflow
Im using IntelliJ IDE. What should I change?

A: The code that you've provided does not match the code that you said you copied.  The source code is:
return result.copyTo(new float[1][nlabels])[0];

which removes one level of the arrays... which explains the errors you are seeing.

A: Okay I figured it out.Replace the following
result.copyTo(new float[1][nlabels])[0];

to the following:
            float[][] res = new float[1][nlabels];

            result.copyTo(res);

            return res[0];

Perhaps the first line of code works with the version being used by the code author but I cant be certain. The second set of code worked on java vesion 7.


text:
Q: Pipes are not closing properly inside one of the child processes #include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int funcone(){
    int i;
    char *arr[5] = {"One", "Two", "Three", "Four", "Five"};
    for(i = 0; i <= 5; i++){
        printf("%s\t%d\n", arr[i], i);
    }
    printf("\n~");
    return 1;
}

#define NCHAR 1024
#define DELIMIT "\t\n"
int functwo(){
    //prints only numbers from input received from funcone
    int c;
    int position = 0, nchar = NCHAR, i;
    char *arr = malloc(sizeof *arr * nchar);

    if (!arr)
    {
        fprintf(stderr, "Memory Exhausted.");
    }

    //reads input from stdin stream, supposedly piped from func1
    while ((c = fgetc(stdin)) != 126)
    {
        arr[position++] = c;

        if (position >= nchar) // reallocate space if needed
        {
            nchar += NCHAR;
            arr = realloc(arr, nchar + NCHAR);

            if (!arr)
            {
                fprintf(stderr, "Memory Exhausted.\n");
                break;
            }
        }
    }
    arr[position] = 0;

    char *token;
    //splits string by \t\n, and converts string into numbers
    token = strtok(arr, DELIMIT);
    while (token != NULL)
    {
        char *endptr;
        int x = strtol(token, &endptr, 10);
        if (x > 0)
        {
            printf("%d\n", x);
        }
        token = strtok(NULL, DELIMIT);
    }
    printf("\n~");

    free(arr);

    return 1;
}

int main(){
    printf("piping begins\n");
    int fd[2];
    int childstatus = 0;

    if (pipe(fd) == -1)
    {
        perror("Pipe1 error");
        return 1;
    }

    int pid1 = fork();
    if (pid1 < 0)
    {
        perror("Pid1 error");
        return 1;
    }

    if (pid1 == 0)
    {
        //child 1 process
        dup2(fd[1], STDOUT_FILENO);
        close(fd[1]);
        close(fd[0]);
        int f1 = funcone();
        // int f1 = (*builtin_functions[aone])(argone);
        /*In the main program, this line runs a function
         *with a corresponding index number, and takes in the
         *command keywords as arguments. Returns 1 to continue Shell loop, 0 to exit.*/
    }

    int pid2 = fork();
    if (pid2 < 0)
    {
        perror("Pid2 error");
        return 1;
    }

    if (pid2 == 0)
    {
        // child 2 process
        dup2(fd[0], STDIN_FILENO);
        dup2(fd[1], STDOUT_FILENO);
        close(fd[0]);
        close(fd[1]);
        int f2 = functwo();
        // int f1 = (*builtin_functions[aone])(argone);
    }

    // parent process

    waitpid(pid1, &childstatus, WNOHANG);
    waitpid(pid2, &childstatus, WNOHANG);

    dup2(fd[0], STDIN_FILENO);
    close(fd[0]);
    close(fd[1]);

    int f3 = functwo();
    //supposed to be functhree, but something similar to functwo so i reused it.
    // int f3 = (*builtin_functions[aone])(argone);
    printf("Piping process complete.\n");
}

I'm working on a mini shell in C and I've been trying to figure out for a while now as to why some pipes are stuck inside the child process and do not execute. The only way I get both child processes to stop is is I use waitpid( , ,WNOHANG), which kind of shows that something is stuck in there. This causes the duplicated STDOUT and STDIN streams to not close properly, causing  the program to constantly loop my shell prompt into the input stream and ultimately making my program crash due to segmentation fault.
Is there any way to overcome this problem or identify exactly where in the child processes are the pipes stuck?
EDIT 1
So I tried creating two different pipes in the main function namely int fd1[2], fd2[2];, making sure to close all ends as shown below. I've also made all funcone() and functwo() void to not return anything. However, my program now runs infinitely while printing ���� on the terminal until I use CTRL + C. Could there be any other possible reasons as to why this is happening? Or could there be any alternative methods to simulating an Interprocess Communication (IPC)?
int main(){
printf("piping begins\n");
int fd1[2], fd2[2];
int childstatus = 0;

if (pipe(fd1) == -1)
{
    perror("Pipe1 error");
    return 1;
}

if (pipe(fd2) == -1)
{
    perror("Pipe2 error");
    return 1;
}

int pid1 = fork();
if (pid1 < 0)
{
    perror("Pid1 error");
    return 1;
}

if (pid1 == 0)
{
    //child 1 process
    dup2(fd1[1], STDOUT_FILENO);
    close(fd1[1]);
    close(fd1[0]);
    close(fd2[0]);
    close(fd2[1]);
    funcone();
    // int f1 = (*builtin_functions[aone])(argone);
}

int pid2 = fork();
if (pid2 < 0)
{
    perror("Pid2 error");
    return 1;
}

if (pid2 == 0)
{
    // child 2 process
    dup2(fd1[0], STDIN_FILENO);
    dup2(fd2[1], STDOUT_FILENO);
    close(fd1[0]);
    close(fd1[1]);
    close(fd2[0]);
    close(fd2[1]);
    functwo();
}

// parent process

waitpid(pid1, &childstatus, WNOHANG);
waitpid(pid2, &childstatus, WNOHANG);

dup2(fd2[0], STDIN_FILENO);
close(fd1[0]);
close(fd1[1]);
close(fd2[0]);
close(fd2[1]);

functwo();
printf("Piping process complete.\n");
return 0;

}

A: Your first child process is writing to the pipe.  Your parent process and second child process are both reading from that same pipe.  Each byte written to the pipe will be consumed by one of those latter two processes, but you have no direct control over which one.  This is not inherently wrong, but it is rarely what you want, and it will not work reliably for you in the example program.
What likely is happening is that the parent process consumes the data written by the first process, or at least the end-of-message character, which you intend for the second child instead.  The second child then waits forever to read data that will never arrive.  It does not even detect end-of-file on the pipe when the first child terminates, because the second child itself holds the write end of the pipe open.  The parent, in turn, waits forever for the second child to terminate.
Supposing that the intention is for the second child to consume all the data written by the first child, and for the parent to in turn consume all the data written by the second child, you should create a separate pipe for the child2 --> parent link.  That's usually the pattern you want: a separate pipe for each distinct ordered pair of endpoints.  That includes a separate pipe for each direction if you want bidirectional communication between the same two processes.
Update:
Additionally, funcone() overruns the bounds of its local arr array.  The valid indices are 0 through 4, but the for loop in that function runs from 0 through 5.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to prove that $\mathbb{Z}[\exp(\frac{2\pi i}{3})]$ is a Euclidean domain? To give the context I am currently studying Gaussian Integers, and I have of course studied rings. The full question is:
Given $\rho = \exp(\frac{2\pi i}{3})$, show that the ring $R = \mathbb{Z}[\rho]$ together with $N(z) = |z|^2$, for $z \in R$, is a Euclidean domain.
My bigest problem so far is that I am confused about $\mathbb{Z}[\rho]$: I believe it refers to the polynomial ring of variable $\rho$ where $i$ is the imaginary number. However it doesn't really make sens since $\rho$ is not a variable but a constant. Therefore I thought it might refer to the ring of integers modulo $\rho$, but if it is so I can't see clearly what it represents.
Furthermore, I know there is no general way to prove something is a Euclidean domain, so if we are to do it case by case I would like to be positive how to begin. The only thing that comes to my mind so far is to prove that $\forall \rho_1,\rho_2 \in R$, $\exists q,r \in R$ such that $\rho_1 = q\rho_2 + r$ where either $r = 0$ or $N(r) < N(\rho_2)$.
I've already looked up for something similar or just a general case on the internet and on Mathstack but all I could I could find was How do I prove whether something is a Euclidean domain? which is not relevant in this situation.
I hope you can help me with the basics of this problem so I can move on a little! I only hope for hints.


text:
Q: xml multi level to csv using xslt I have an XML like this:
 <PROGRAM>
    <date>10/07/2014</date>
    <name>Name</name>
    <LOTS>
        <LOT>
            <ID>1</ID>
            <type>A</type>
        </LOT>
        <LOT>
            <ID>2</ID>
            <type>B</type>
        </LOT>
</PROGRAM>

And I'd like to get this from the transformation (XSLT) result:
10/07/2014,Name,1,A
10/07/2014,Name,2,B
here is my xslt :
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="text"/>
    <xsl:variable name='newline'>
        <xsl:text></xsl:text>
    </xsl:variable>

<xsl:template match="/">
        <xsl:for-each select="//LOT">
            <xsl:for-each select="//PROGRAM">
                <xsl:value-of select="concat(date,',',name)"/>
            </xsl:for-each>
            <xsl:value-of select="concat(',',ID,',',type,$newline)"/>
        </xsl:for-each>
</xsl:template>

Does anyone know the XSLT to achieve this?
Thanks!

A: How about something simpler:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>

<xsl:template match="/">
        <xsl:for-each select="PROGRAM/LOTS/LOT">
            <xsl:value-of select="concat(../../date, ',', ../../name, ',', ID, ',', type)"/>
            <xsl:if test="position()!=last()">
                <xsl:text>
</xsl:text>
            </xsl:if>
        </xsl:for-each>
</xsl:template>

</xsl:stylesheet>


text:
Q: How to influence keyboard focus traversal policy in WPF? Let's say there are two WPF lists.
I'd like to be able to iterate seamlessly through items it both lists using just keyboard arrow keys.
By default focus scope is limited to iteration within a single container.
Is there any way to help it cross container borders?

A: So say there are two ListViews:
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <ListView x:Name="list1" KeyDown="list1_KeyDown">
        <ListViewItem Content="item 1"/>
        <ListViewItem Content="item 2"/>
        <ListViewItem Content="item 3"/>
    </ListView>
    <ListView x:Name="list2" Grid.Row="1" KeyDown="list2_KeyDown">
        <ListViewItem Content="item 1"/>
        <ListViewItem Content="item 2"/>
        <ListViewItem Content="item 3"/>
    </ListView>
</Grid>

Add two handlers for the KeyDown events:
private void list1_KeyDown(object sender, KeyEventArgs e) {
    switch (e.Key) {
        // check for down key
        case Key.Down:
            // if the bottom item is selected
            if (list1.SelectedIndex == list1.Items.Count - 1) {
                // select the next item
                list2.SelectedIndex = 0;
                (list2.Items[0] as UIElement).Focus();
                // make sure nothing else happens
                e.Handled = true;
            }
            break;
    }
}

private void list2_KeyDown(object sender, KeyEventArgs e) {
    switch (e.Key) {
        // check for up key
        case Key.Up:
            // if the top item is selected
            if (list2.SelectedIndex == 0) {
                // select the previous item
                int i = list1.Items.Count - 1;
                list1.SelectedIndex = i;
                (list1.Items[i] as UIElement).Focus();
                // make sure nothing else happens
                e.Handled = true;
            }
            break;
    }
}

This will allow seamless vertical transition between the two ListViews using up/down keys. You can add more case blocks to add additional left/right transition or whatever.
I'm sure you can work out how to adapt this to your specific scenario.

A: Just figured this out.
KeyboardNavigation.DirectionalNavigation attached property does the trick. (possible values listed here)
The sample can be simplified to:
<StackPanel KeyboardNavigation.DirectionalNavigation="Contained">
  <ListBox KeyboardNavigation.DirectionalNavigation="Continue">
    <ListBoxItem Content="Item 1" />
    <ListBoxItem Content="Item 2" />
    <ListBoxItem Content="Item 3" />
  </ListBox>
  <ListBox KeyboardNavigation.DirectionalNavigation="Continue">
    <ListBoxItem Content="Item A" />
    <ListBoxItem Content="Item B" />
    <ListBoxItem Content="Item C" />
  </ListBox>
</StackPanel>


text:
Q: resizing a MDI Tabbed Group Using C++, MFC, I have an application with MDI Tabbed Groups.   I have written code to
1
vote
0answers
21 views
programmatically create new tab groups and move tabs around.  That all works fine.
But I am having trouble setting the size of the tab groups I make.  By default, the groups are given a size that is half of the available space.   I couldn't find an official size method on the tab control class.  So I tried SetWindowPos() and MoveWindow() on the group controls instead.  That seems to have an impact, but not a full impact.
For example, lets say I want group A to be 10% of the frame window's area, while group B takes 90%.  When I issue calls to SetWindowPos() or MoveWindow(), I get about 30%:70% instead of 10%:90% I asked for.  It seems like it wants to do what I said, but it is fighting it.
I also tried calling the tab control's AutoSizeWindow(FALSE) method beforehand.
But that didn't help.
Any ideas?
Any ideas?

A: Ok, my mistake.  MoveWindow() works fine.
I just didn't notice that each tabgroup needed a rect with it's own origin.  (every left would be 0)
I tried to setup rectangles that were in frame window coordinates.


text:
Q: Angularjs: ng-show not showing after set to true <button type="button" class="btn btn-default" ng-click="callMe()"
    ng-show="isVisible">Call</button>

In my controller.js I tried to:
$scope.isVisible = false;
myService.callMe().success(function (response) {
    $scope.isVisible = true;
    alert("enabled");
}

But button "Call" is not showing (alert was shown). What went wrong? Thanks in advance.

A: You need to embed the service call inside the function,
$scope.callMe = function(){
myService.callMe().success(function (response) {
    $scope.isVisible = true;
    alert("enabled");
}
}

I am not sure why you are using a service here, you can do without service as,
$scope.callMe = function(){
    $scope.isVisible = true;
    alert("enabled");
}

WORKING DEMO


text:
Q: Converting year-month format to year-quarter [excel] I'd like to convert year-month (2022-Sep) to year-quarter (2022-Q3). I've found a way to do it, I was just wondering if there was an easier method just for my learning in the future.
=CONCAT(LEFT(L2;4);"-";IF(OR(RIGHT(L2;3)="Jan";RIGHT(L2;3)="Feb";RIGHT(L2;3)="Mar");"Q1";IF(OR(RIGHT(L2;3)="Apr";RIGHT(L2;3)="May";RIGHT(L2;3)="Jun");"Q2";IF(OR(RIGHT(L2;3)="Jul";RIGHT(L2;3)="Aug";RIGHT(L2;3)="Sep");"Q3";"Q4"))))

My year-month data was in L2.
I'd appreciate any advices how to make it easier.
Thank you!


text:
Q: Repaint() relocating buttons I'm writing a Java program that will draw a circle or rectangle depending on the button pressed. While it does draw the given shape, upon drawing it creates new buttons at the top left((0,0) most likely) of the window. Am I breaking some rule of paint()/repaint()?
Here's my class:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPanel;
public class Components extends JPanel implements ActionListener
{
  String em="Nothing";
  public Components()
{
    JButton c=new JButton("Rectangle");
    JButton b=new JButton("Circle");
    b.addActionListener(this);
    c.addActionListener(this);
    add(c, 0);
    add(b, 1);
    setBackground(Color.WHITE);
    setVisible(true);
}

public void actionPerformed(ActionEvent e)
{
    if(e.getActionCommand().equals("Rectangle"))
    {
        em="Rectangle";
        repaint();
    }
    else
    {
        em="Circle";
        repaint();
    }
}

public void paint(Graphics g)
{
    if(em.equals("Rectangle"))
    {
        g.drawRect(50, 50, 50, 50);
    }
    else if(em.equals("Circle"))
    {
        g.drawOval(50, 50, 50, 50);
    }

}

}

As well as the less-important JFrame class:
import java.awt.Graphics;

import javax.swing.JFrame;
public class Wndw extends JFrame
{
    public Wndw()
    {
        setTitle("Hello");
        setSize(400, 400);
        setResizable(false);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        add(new Components());
    }

public static void main (String [] args)
{
    new Wndw();
}
}

A: It's got (very little) to do with repaint and everything to do with your violation of the painting routines
Start by having a look at Performing Custom Painting and Painting in AWT and Swing for more details into how painting works.
paint delegates it's responsibilities, by calling paintComponent, paintBorder and paintChildren.  When you override paint and fail to call it's super method, you are breaking this responsibility and you end up with issues like you have now.
The Graphics context is a shared resource among Swing components.  Every component which is painted during a paint cycle gets the same Graphics. This means, one of the first things that should be done, is the Graphics context should be prepared for the component to paint on it.  This is typically done by the paintComponent method, which you are no longer calling
The first thing to do to is, stop overriding paint and instead, which is generally recommended, override paintComponent, it limits your overall responsibility and reduces the risk of introducing further issues.
Next, call super.paintComponent before you do any custom painting...
public class Components extends JPanel implements ActionListener
{
    //....
    @Overrride
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        if(em.equals("Rectangle"))
        {
            g.drawRect(50, 50, 50, 50);
        }
        else if(em.equals("Circle"))
        {
            g.drawOval(50, 50, 50, 50);
        }
    }

But when I do this, what was previously paint is erased

Yes, that's how painting works.  It's destructive.  When ever a paint pass is executed, you are expected to repaint the entire state of the component as it is at that point in time.
If you wish to preserve what was previously painted, you have two basic choices.

*

*Draw everything to a backing buffer (image) and paint that

*Store the "commands" you need to redraw the context from scratch in some kind of List
There are plenty of examples of both


text:
Q: Ubuntu OpenVPN GUI setting incorrect default routing gateway I'm currently playing with setting up an OpenVPN Access Server in AWS. For the most part I've got everything working, except when I try to add the VPN connection to Ubuntu using the networks GUI.
This is my routes -n output when I'm not connected to the VPN,
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.0.1     0.0.0.0         UG    0      0        0 wlan0
192.168.0.0     0.0.0.0         255.255.255.0   U     9      0        0 wlan0

The VPN is configured to not route internet traffic. So when I connect via the command line using sudo openvpn client.ovpn everything works as expected and my routes -n looks like the following,
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.0.1     0.0.0.0         UG    0      0        0 wlan0
54.173.232.46   192.168.0.1     255.255.255.255 UGH   0      0        0 wlan0
172.16.0.0      172.16.224.129  255.255.254.0   UG    101    0        0 tun0
172.16.224.0    172.16.224.129  255.255.255.0   UG    101    0        0 tun0
172.16.224.128  0.0.0.0         255.255.255.128 U     0      0        0 tun0
192.168.0.0     0.0.0.0         255.255.255.0   U     9      0        0 wlan0

Take note of the default route 0.0.0.0 hitting my router 192.168.0.1. If I try and hit Google, all works as expected.
I don't want to have to connect to the VPN via command line everytime so I installed network-manager-openvpn-gnome and imported the client.ovpn when creating the VPN.
Now when I connect via the network dropdown in the tool bar, the VPN connects fine, but I can't access Google or any other website. I can access servers in my AWS VPC, but that's it.
Interestingly my routes -n now looks like the following,
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         172.16.224.129  0.0.0.0         UG    0      0        0 tun0
54.173.232.46   192.168.0.1     255.255.255.255 UGH   0      0        0 wlan0
172.16.0.0      172.16.224.129  255.255.254.0   UG    101    0        0 tun0
172.16.224.0    172.16.224.129  255.255.255.0   UG    101    0        0 tun0
172.16.224.128  0.0.0.0         255.255.255.128 U     0      0        0 tun0
192.168.0.0     0.0.0.0         255.255.255.0   U     9      0        0 wlan0

Note the default route is no longer pointing at my router.
Unless I'm being blind I can't find an option in the networks GUI where I can fix this.
Any ideas?
Thanks

A: The accepted answer did not work for me on Fedora 31 and NetworkManager.  I was able to resolve by modifying /etc/NetworkManager/system-connections/vpn_name
[vpn]
...
never-default=true
...

Then restart NetworkManager with
sudo systemctl restart NetworkManager

A: Turns out I was being blind.
Edit the VPN connection -> IPv4 Settings -> Click "Routes", and finally check "Use this connection only for resources on its network".


text:
Q: cannnot boot to text mode with r/w fileystem I installed Ubuntu 12.10 server to a laptop, and the grub file is along the lines of:
setparams 'Ubuntu'
recordfail
    gfxmod $linux -gfxmod
    set root ='hd0,msdos/'

    if[[x%feature_platform_search_hint=xy];then
        search --nofloppy ...
        ...

        else
            search -- noflopppy ...
    fi

linux /vmliuz -3.5.0-17 ??? root = /dev/map/dur2\-root ro
initrd /initrd...

(pardon, that was written by pencil and not complete, obviously).
How can I put something like GRUB_CMDLINE_LINUX_DEFAULT="text" in there to boot to text mode?
Or, is there another way to boot to text mode with a live, editable file system using GRUB?

A: You seem to have answered your own question.  You set GRUB_CMDLINE_LINUX_DEFAULT="text" in /etc/default/grub, then run sudo update-grub.


text:
Q: WCF tracing in code does not follow MessageLogging settings I need to use WCF tracing in my application but it needs to be controlled from code as much as possible.
IT was suggested that I install the following sections in my app.config file:
<configuration>
  <system.serviceModel>
    <diagnostics>
      <messageLogging
        maxMessagesToLog="100"
        logEntireMessage="true"
        logMessagesAtServiceLevel="true"
        logMalformedMessages="true"
        logMessagesAtTransportLevel="true">
      </messageLogging>
    </diagnostics>
  </system.serviceModel>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel" >
        <listeners>
          <add type="System.Diagnostics.DefaultTraceListener" name="dummy"/>
        </listeners>
      </source>
    </sources>
  </system.diagnostics>
</configuration>

Then the following code could be used to get the trace running as needed:
BindingFlags privateMember = BindingFlags.NonPublic | BindingFlags.Instance;
BindingFlags privateStaticMember = privateMember | BindingFlags.Static;

Type type = Type.GetType("System.ServiceModel.DiagnosticUtility, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
MethodInfo[] mi = type.GetMethods(privateStaticMember);

// invoke InitializeTracing
object diagnosticTrace = mi.FirstOrDefault(e => e.Name == "InitializeTracing").Invoke(null, null);
if (diagnosticTrace != null)
{
    // get TraceSource
    Type type2 = Type.GetType("System.ServiceModel.Diagnostics.DiagnosticTrace, SMDiagnostics, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
    PropertyInfo pi = type2.GetProperty("TraceSource", privateMember);
    TraceSource traceSource = pi.GetValue(diagnosticTrace, null) as TraceSource;

    // clear all listeners in the trace source
    traceSource.Listeners.Clear();

    // add listener to trace source
    XmlWriterTraceListener listener = new XmlWriterTraceListener("mylogfile".svclog");
    listener.TraceOutputOptions = TraceOptions.Timestamp | TraceOptions.Callstack;
    traceSource.Attributes["propagateActivity"] = "true";
    traceSource.Switch.ShouldTrace(TraceEventType.Verbose | TraceEventType.Start);
    traceSource.Listeners.Add(listener);

    // enable tracing
    type.GetProperty("Level", privateStaticMember).SetValue(null, SourceLevels.All, null);

    Trace.AutoFlush = true;

This works fine up to a point, the main problem being that the messagelogging settings in the system.servicemodel section of the app.config file are being ignored.
Is there anything that can be done to solve this problem?

A: I can't comment on all of your code because I have not used System.Diagnostics in this way before (programmatically configuring the WCF communication tracing), but if your intent on this line:
traceSource.Switch.ShouldTrace(TraceEventType.Verbose | TraceEventType.Start);
Is to set the level of tracing that you want, I think that you should be using the Switch.Level property instead.  ShouldTrace is for asking if a given TraceSource would trace, given the input flags.
traceSource.Switch.Level = SourceLevels.Verbose | SourceLevels.ActivityTracing;

Note that according to this link, it is possible to configure apparently reasonable settings and yet the activity id might not be propogated correctly.  Read it carefully.  It may or not apply to your situation.

A: *

*You need to enable MessageLogging by defining a trace source as indicated in this MSDN Library page.  So, you need this extra bit in your app.config in the sources section:
<source name="System.ServiceModel.MessageLogging">
   <listeners>
     <add type="System.Diagnostics.DefaultTraceListener" name="dummy"/>
  <remove name="Default" />
</listeners>      </source>

The message logging settings don't apply to the System.ServiceModel trace source.


text:
Q: What's a better workflow for database migration? When asked to work on an existing WordPress Site, I generally take a copy of the whole site and work on it locally. For quite a few years I have used a script such as the following after importing the database locally.
UPDATE wp_options SET option_value = replace(option_value, 'http://clientsite.co.uk', 'http://local.wordpressdev') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE wp_posts SET guid = REPLACE (guid, 'http://clientsite.co.uk', 'http://local.wordpressdev');
UPDATE wp_postmeta SET meta_value = REPLACE (meta_value, 'http://clientsite.co.uk', 'http://local.wordpressdev');
UPDATE wp_posts SET post_content = REPLACE (post_content, 'http://clientsite.co.uk', 'http://local.wordpressdev');

I've seen advice to never mess with post guids but the above has always worked for me and has, to my knowledge, never caused any problems.
My question is, is this still a valid migration method with Wordpress 4? Also do plugins like 'Search & Replace' or tools such as WP-CLI do this better?

A: I use this for search and replace on databases - https://interconnectit.com/products/search-and-replace-for-wordpress-databases/
Simply move files with FTP, export and import database and then run the script searching for old URL and replacing with the new URL. Then I resave permalinks and I'm done. I've moved WP thousands of times using this.
I've got the old script which is just a single file, I'm not so keen on the new version, it's a bit slower and more idiot proof which I actually don't like.

A: wp-cli has this built in. If you have wp-cli installed, from the command line you can run:
wp search-replace 'http://oldurl.com' 'http://newurl.localhost'

or whatever URLs you use in your local environment and this will update the local site database, taking serialised arrays into account (which the OP doesn't do).
You can create aliases in your .bash_profile to run a series of wp-cli commands to create a database, reset a database, import a database, search-replace on a database etc. So in the end you could have one alias you run on the command line that does all the work of importing a new database to a site for you.


text:
Q: Using @Valid in Spring MVC to validate a list of String My Pojo looks like this -
public class Employee {

   @Pattern(regexp="some regex")

   private String Address;

   **// How do I validate each element in list for the a regex pattern**

   private List<String> names;
}

My goal is to validate each String in the list 'names' for a regex. How can I achieve that use @Valid in spring mvc validation support ?


text:
Q: Branching tree with tight continuous relaxation Suppose you are solving an integer, linear math problem. The continuous relaxation is denoted by $z$, and the optimal solution is denoted by $z^*$.
In a branch-and-bound algorithm, is it possible to have more than one node in the branching tree if the continuous relaxation is tight, i.e., if $z^*=z$ ?

A: The answer is yes. If you solve $\max_{x \in \{0,1\}^2}\{ x_1+x_2 : x_1+x_2\leq 1 \}$ with an interior point solver, the root node will have $x=(0.5, 0.5)$ and you need to branch.


text:
Q: How to add bootstrap menu,sub menu with custom css? I am developing a wordpress theme using bootsatrap my html structure is something like :

BRUSHES

BODY

          BLADES

Men

Woman

BEAUTY

BABY

PET

To integrate it in wordpress menu I used the code :
wp_nav_menu(array('theme_location' => 'navi', 'container' => 'false','menu_class' => 'nav navbar-nav inner', 'menu_id' => 'nav', 'echo' => 'true', 'fallback_cb' => 'themezee_default_menu', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'depth' => 0));

My problem is I want to add submenu and submenu related class like :

   BLADES

Men

Woman

My code is generating the code below :

Brushes

Body

Blades

Men

Women

Beauty

Baby

Pet

Any idea?

A: You can do it in two ways.
1) Simply go for the third party developed code here (its free too)
2) If you want to make your own without any plugin, then u have to code something like below,
    Step 1:  Add an extra CSS class (dropdown) in the parent pages CSS class
     U can add that extra CSS class here Appearance-> menus: there u find CSS Classes (optional)
     If u didn't find it then, click screen option in the top right-hand corner (near help), there u can enable CSS classes, description, etc.,
Step 2: the real code is here

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">

        </button>

    <?php
    $menu_args = array(
      'menu'            => 'Main Menu',
      'container'       => 'container',
      'container_class' => 'container_class',
      'container_id'    => 'container_id',
      'menu_class'      => 'nav navbar-nav',
      'menu_id'         => 'menu_id',
      'echo'            => true);
    ?>
    <?php wp_nav_menu($menu_args);?>

Step 3: in footer inclde the following

And finally, don't forget to include the necessary bootstrap CSS and js and jquery
PS: I hope u will go for the first method


text:
Q: NodeJS Redis client initialization best practices Hi I have a question related to using a redis client in NodeJS.
I am currently using redis package in my node backend and what I do is that at application startup I connect to my redis url and use the same for all my requests.
I'm having some issues when the client disconnects and server receives requests.
Those requests have to wait for redis to reconnect and sometimes take several seconds which results in a timeout.
A colleague of mine suggested to initialize a redis connection for each requests. What do you guys think about that ?


text:
Q: innerHTML Not Updating Text I've been stumped on this bug where I am unable to update the innerHTML of my li classes named "currMonth" and "currYear". They are supposed to get updated by the OnStart() function. I tried using console.log and it showed that the values were changing behind the scenes. It would be great if someone can show me what I'm doing wrong. Thanks!
HTML:
<!DOCTYPE html>

  <title title = "O(n)Time"></title>
  <meta charset="UTF-8">

  <link rel="stylesheet" type="text/css" href="../css/styles.css">

❮

❯

Sunday

Monday

Tuesday

Wednesday

Thursday

Friday

Saturday

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

29

30

31

CSS:
ul {
  list-style-type: none;
}

body{
  font-family: Verdana, sans-serif;
}

/* Month header */
.month{
  padding: 70px 25px;
  width: auto;
  background: #1abc9c;
  text-align: center;
}

/* Month list */
.month ul {
  margin: 0;
  padding: 0;
}

.month ul li{
  color: white;
  font-size: 20px;
  text-transform: uppercase;
  letter-spacing: 3px;
}

/* Previous button inside month header */
.month .prev {
  float: left;
  padding-top: 10px;
}

/* Next button */
.month .next {
  float: right;
  padding-top: 10px;
}

/* Weekdays (Sun-Sat) */
.weekdays {
  margin: 0;
  padding: 10px 0;
  background-color: #ddd;
}

.weekdays li {
  display: inline-block;
  width: 13.6%;
  color: #666;
  text-align: center;
}

/* Days (1-31) */
.days {
  padding: 10px 0;
  background: #eee;
  margin: 0;
}

.days li {
  list-style-type: none;
  display: inline-block;
  width: 13.6%;
  text-align: center;
  margin-bottom: 5px;
  font-size: 12px;
  color: #777;
}

/* Highlight of the "current" day */
.days li .active {
  padding: 5px;
  background: #1abc9c;
  color: white !important
}

JS:
//Constants
MONTHS = ["January", "February", "March", "April", "May", "June", "July",
          "August", "September", "October", "November", "December"];

//Variables
  var prevArrow = document.getElementsByClassName('prev');
  var nextArrow = document.getElementsByClassName('next');

OnStart(MONTHS);

//Functions
function OnStart(MONTHS){
  var d = new Date();
  var month = d.getMonth();
  var year = d.getFullYear();

  document.getElementById('currMonth').innerHTML = MONTHS[month];
  document.getElementById('currYear').innerHTML = year;

}

A: getElementsByClassName() returns collection. You have to use proper index with that.
Change:
document.getElementsByClassName('currMonth').innerHTML = MONTHS[month];
document.getElementsByClassName('currYear').innerHTML = year;

To:
document.getElementsByClassName('currMonth')[0].innerHTML = MONTHS[month];
document.getElementsByClassName('currYear')[0].innerHTML = year;

A: You get an array back even though there may be only one result hence you need to reference the 0'th element like so.
document.getElementsByClassName('currMonth')[0].innerHTML = MONTHS[month];

document.getElementsByClassName('currYear')[0].innerHTML = year;

A: replace .getElementsbyClassName to querySelector
?
That works?

A: document.getElementsByClassName('currMonth') returns a nodelist. you'll need to iterate through each node and then assign the innerHTML. That's why you cannot assign it like the way you are doing. You can alternatively use document.querySelectorAll
let list = document.getElementsByClassName('currMonth');
// list = document.querySelectorAll('.currMonth'); either or
let foo = [].slice.call(list); // convert to array of values from node list

foo.forEach(function(objNode) {
    objNode.innerHTML = "value"
}


text:
Q: mvn command not found in OSX Mavericks Before marking this as duplicate, I went through these posts, but nothing helped.

*

*'mvn' is not recognized as an internal or external command,

*Getting -bash: mvn: command not found,

*Can't access mvn command from command line?
Some are specific to windows and did not help. A couple of them on Mac OS X gave suggestions, that I tried but did not help.
What I tried (this is exactly what Maven suggests):

Extract the distribution archive, i.e. apache-maven-3.1.1-bin.tar.gz
to the directory you wish to install Maven 3.1.1. These instructions
assume you chose /usr/local/apache-maven. The subdirectory
apache-maven-3.1.1 will be created from the archive. In a command
terminal, add the M2_HOME environment variable, e.g. export
M2_HOME=/usr/local/apache-maven/apache-maven-3.1.1. Add the M2
environment variable, e.g. export M2=$M2_HOME/bin. Optional: Add the
MAVEN_OPTS environment variable to specify JVM properties, e.g. export
MAVEN_OPTS="-Xms256m -Xmx512m". This environment variable can be used
to supply extra options to Maven. Add M2 environment variable to your
path, e.g. export PATH=$M2:$PATH. Make sure that JAVA_HOME is set to
the location of your JDK, e.g. export JAVA_HOME=/usr/java/jdk1.5.0_02
and that $JAVA_HOME/bin is in your PATH environment variable. Run mvn
--version to verify that it is correctly installed.

I see that on the terminal that I used for installation, it works fine. I do not have this issue. but when I tried on a new terminal, I get command not found.
I also added export PATH=$M2 to my .bashrc, I did source and then restarted the terminal, still it did not help.
can someone suggest how to make it available in all sessions of terminal?
Thanks

A: Try following these if these might help:
Since your installation works on the terminal you installed, all the exports you did, work on the current bash and its child process. but is not spawned to new terminals.
env variables are lost if the session is closed; using .bash_profile, you can make it available in all sessions, since when a bash session starts, it 'runs' its .bashrc and .bash_profile
Now follow these steps and see if it helps:

*

*type env | grep M2_HOME on the terminal that is working. This should give something like
M2_HOME=/usr/local/apache-maven/apache-maven-3.1.1

*typing env | grep JAVA_HOME should give like this:
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home
Now you have the PATH for M2_HOME and JAVA_HOME.
If you just do ls /usr/local/apache-maven/apache-maven-3.1.1/bin, you will see mvn binary there.
All you have to do now is to point to this location everytime using PATH. since bash searches in all the directory path mentioned in PATH, it will find mvn.

*

*now open .bash_profile, if you dont have one just create one
vi ~/.bash_profile
Add the following:
#set JAVA_HOME
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home
export JAVA_HOME

M2_HOME=/usr/local/apache-maven/apache-maven-3.1.1
export M2_HOME

PATH=$PATH:$JAVA_HOME/bin:$M2_HOME/bin
export PATH

*

*save the file and type source ~/.bash_profile. This steps executes the commands in the .bash_profile file and you are good to go now.

*open a new terminal and type mvn that should work.

A: Solutions above are good but they require ~/.bash_profile. /usr/local/bin is already in the $PATH and it can be confirmed by doing echo $PATH. Download maven and run the following commands -
$ cd ~/Downloads
$ tar xvf apache-maven-3.5.3-bin.tar.gz
$ mv apache-maven-3.5.3 /usr/local/
$ cd /usr/local/bin
$ sudo ln -s ../apache-maven-3.5.3/bin/mvn mvn
$ mvn -version
$ which mvn

Note: The version of apache maven would be the one you will download.

A: steps to install maven :

*

*download the maven file from http://maven.apache.org/download.cgi

*$tar xvf apache-maven-3.5.4-bin.tar.gz

*copy the apache folder to desired place $cp -R apache-maven-3.5.4 /Users/locals

*go to apache directory $cd /Users/locals/apache-maven-3.5.4/

*create .bash_profile $vim ~/.bash_profile

*write these two command :
 export M2_HOME=/Users/manisha/apache-maven-3.5.4
 export PATH=$PATH:$M2_HOME/bin
7 save and quit the vim  :wq!

*restart the terminal and type mvn -version

A: Here is what worked for me.
First of all I checked if M2_HOME variable is set env | grep M2_HOME. I've got nothing.
I knew I had Maven installed in the folder "/usr/local/apache-maven-3.2.2", so executing the following 3 steps solved the problem for me:

*

*Set M2_HOME env variable

M2_HOME=/usr/local/apache-maven-3.2.2

*Set M2 env variable

M2=$M2_HOME/bin

*Update the PATH

export PATH=$M2:$PATH
As mentioned above you can save that sequence in the .bash_profile file if you want it to be executed automatically.

A: I got same problem, I tried all above, nothing solved my problem. Luckily, I solved the problem this way:
echo $SHELL

Output

/bin/zsh
OR
/bin/bash

If it showing "bash" in output. You have to add env properties in .bashrc file (.bash_profile i did not tried, you can try) or else
It is showing 'zsh' in output. You have to add env properties in .zshrc file, if not exist already you create one no issue.

A: The possible solution can be that maven is not installed in your mac system.
Use this command to install maven:
brew install maven

And, to verify, that it is successfully installed, run this command:
mvn -v

If it returns you maven version, then maven is successfully installed in your system.

A: I followed brain storm's instructions and still wasn't getting different results - any new terminal windows would not recognize the mvn command. I don't know why, but breaking out the declarations in smaller chunks .bash_profile worked. As far as I can tell, I'm essentially doing the same thing he did. Here's what looks different in my .bash_profile:
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_221.jdk/Contents/Home
export PATH JAVA_HOME
J2=$JAVA_HOME/bin
export PATH J2
M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1
export PATH M2_HOME
M2=$M2_HOME/bin
export PATH M2

A: You probably have 2 types of shell instances.
sh vs zsh.
Both can have different path defined.
Check your PATH environment variable by typing the below line in terminal
echo $PATH
To test you can change shell mode -
sh to zsh -> type zsh and press enter in terminal (notice $ changes to %)
zsh to sh -> type sh/bash and press enter in terminal (notice % changes to $)
In Both shell modes check for PATH env.
Make both same, or append path from other as needed.
Commands running in 1 shell and not in other would be sorted.

A: For some of you the cause might be using of other variables in the path to the maven directory. More details in the answer.


text:
Q: Angular, change class variable/property with function Can't believe I am asking this, but I did not find an answer to this problem.
As you can guess I am fairly new to Angular.
How can I change public slideNumber = 1 dynamically within a class?
    export class TestimonialComponent {
  public slideNumber = 1;

  Carousel() {
    setInterval(function () {
      this.slideNumber = 9;
    }, 1000);
  }

  ngOnInit(): void {
    this.Carousel();
    this.slideNumber = 3;
  }
}

from my understanding ngOnInit shares slideNumber with the class, but the Carousel function declares its own slideNumber.
My question is why does this happen and how can I dynamically change the first declared variable in the class? (public slideNumber = 1)
Clarification

*

*ngOnInit changes the public slideNumber = 1 to 3

*Carousel function creates it's own property this.slideNumber = 9
This means that public slideNumber = 1 is now 3 and Carousel is not able to interact with public slideNumber = 1

A: change Carousel to
Carousel() {
    setInterval(() =>{
      this.slideNumber = 9;
    }, 1000);
  }

When using function(){} , it makes a new this that depends on how it being called. when using arrow syntax () => {}, this is same as parent's.
For more info, check out https://itnext.io/the-this-keyword-in-javascript-demystified-c389c92de26d

A: make slideNumber an @Input variable. or add a method
setSlideNumber(num:number) {
  this.slideNumber = num;
}

and then use a ViewChild to set it. there's no reason to have hard coded numbers in your code.


text:
Q: Combining enums and using getter to return a specified enum Let's say I have 2 different sets of enums: fruits and vegetables.
public static enum Fruits{
    APPLE ("Apple"),
    PEAR ("Pear");

    //constructor
    //getName()
    ...
}
public static enum Vegetables{
    CARROT ("Carrot"),
    LETTUCE ("Lettuce");

    //constructor
    //getName()
    ...
}

I display all this in a JComboBox. After someone selects something, I want to use a getter method to get back the Enum.
For a single enum, I would do something like:
public static Fruits getEnum(String name) {
  for(Fruits fruit: Fruits.values()) {
    if(name.equals(fruit.getName())) {
      return fruit;
    }
  }
  return null;
}

Any ideas what the return type is? I tried using Enum instead of Fruits. When I do that, I don't seem to have access to the getName() methods.

A: Option 1.
Create one method that returns Enum
public static Enum getEnum(String name) {
    Enum selectedEnum = null;
    for (Fruits fruit : Fruits.values()) {
        if (name.equals(fruit.getName())) {
            selectedEnum = fruit;
        }
    }

    for (Vegetables vegetables : Vegetables.values()) {
        if (name.equals(vegetables.getName())) {
            selectedEnum = vegetables;
        }
    }
    return selectedEnum;
}

and to get the name of enum you can use this method
public static String getName(final Enum value) {
    String name = null;
    if (value instanceof Fruits) {
        name = ((Fruits) value).getName();
    } else if (value instanceof Vegetables) {
        name = ((Vegetables) value).getName();
    }
    return name;
}

Option 2.
You can combine 2 enum as
public static enum FruitsAndVegitables{
    APPLE ("Apple" , true),
    PEAR ("Pear", true),
    CARROT ("Carrot", false),
    LETTUCE ("Lettuce", false);

    private String name;
    private boolean isFurit;
    //constructor
    //getName()
    ...
}

A: Here is another demonstration of what you're looking for. The difference between this and previous solutions is that this one is more generic and reusable pattern. This in fact goes beyond the original problem, to show some other benefits of this approach. So you might just comment the bits you don't need. I also attach a unit test to demonstrate the behaviour.
So basically to look for name Apple or APPLE in one of these enums just write:
FruitVeg<?> fvg = getEnum("APPLE", Fruits.class, Vegetables.class);
FruitVeg<> is an interface, which allows to also tap inside of Enum, this interface allows to do some very interesting things with enums below. Here are just some of the things you could do with that:

*

*Enum.valueOf(fvg.getDeclaringClass(), fvg.name()):  returns enum Value e.g. APPLE

*fvg.getRaw():  returns enum Value e.g. APPLE

*fvg.name() :   returns enum's String Name e.g. APPLE

*fvg.getFriendlyName() : e.g. Apple

*fvg.getDeclaringClass() :     returns Class<Enum<?>> e.g. class ox.dummy.dummyTest$Fruits

*fvg.getClass() : class ox.dummy.dummyTest$Fruits returns Class<?>

*EnumSet.allOf(fvg.getDeclaringClass())) : e.g. [APPLE, PEAR]
Here is code
   @Test
public void doSimpleTest() throws Exception {

    FruitVeg<?> fvg = getEnum("APPLE", Fruits.class, Vegetables.class);
    log.info("{} : {} : {} : {} : {}", fvg.name(), fvg.getFriendlyName(), fvg.getClass(), fvg.getDeclaringClass(), EnumSet.allOf(fvg.getDeclaringClass()));
    log.info("get enum: {} ", Enum.valueOf(fvg.getDeclaringClass(), fvg.name()));

}

public interface FruitVeg<T extends Enum<T>> {
    String name();

    String getFriendlyName();

    Class<T> getDeclaringClass();

    T getRaw();

}

enum Fruits implements FruitVeg<Fruits> {
    APPLE("Apple"),
    PEAR("Pear");

    Fruits(String friendlyName) {
        this.friendlyName = friendlyName;
    }

    private final String friendlyName;

    @Override
    public String getFriendlyName() {
        return friendlyName;
    }
    @Override
    public Fruits getRaw() {
        return this;
    }
}

enum Vegetables implements FruitVeg<Vegetables> {
    CARROT("Carrot"),
    LETTUCE("Lettuce");

    Vegetables(String friendlyName) {
        this.friendlyName = friendlyName;
    }

    private final String friendlyName;

    @Override
    public String getFriendlyName() {
        return friendlyName;
    }

    @Override
    public Vegetables getRaw() {
        return this;
    }
}

public static FruitVeg<?> getEnum(String name, Class<? extends FruitVeg<?>>... fvgClasses) {
    for (Class<? extends FruitVeg<?>> fruitVegCLass : Arrays.asList(fvgClasses)) {
        for (FruitVeg<?> fvg : fruitVegCLass.getEnumConstants()) {
            if (name.equals(fvg.name()) || name.equals(fvg.getFriendlyName())) {
                return fvg;
            }
        }
    }
    return null;
}

A: Pass in the Enums themselves as values.  Then use getSelectedItem to retrieve the selected object, and do a test to see what type the object is.
Make the return type of your method an Object, not an enum of a specific type. This would fix your problem.
However, I think your approach is wrong.  If I wanted fruits and vegetables displayed in a list and broken into categories, I'd create an object to do so, and an enum to represent type of food like so:
public enum FoodType{FRUIT, VEGETABLE}
public class Food{
    FoodType type;
    String name;
    public Food(FoodType type, String name){
        this.type = type;
        this.name = name;
    }
    public String toString(){return this.name;}
}

//and then when you want to use it...
Food lettuce = new Food(FoodType.VEGETABLE, "Lettuce");
Food berry = new Food(FoodType.FRUIT, "Berry");
comboBox.add(lettuces);
comboBox.add(berry);

And only add Food items to your JComboBox.  Return Food items when a selection is made, and test for food type using the FoodType enum.

A: It sounds like what you're looking for is the ability to apply inheritance to enums, but this is not possible in java, as enums implicity extend java.lang.Enum and java does not support multiple inheritance.
Nonetheless, I think that using "nested enums" could solve your problem.  By nested, I mean implementing an interface to get around the multiple inheritance issue.  There are a few different approaches in the answers in the link, I assume one of them will suffice.

A: You could use Object instead of explicitly using Fruit or Vegetables
public static Object getEnum(String name)
{
    for(Fruits fruit: Fruits.values())
    {
        if(name.equals(fruit.getName()))
        {
              return fruit;
        }
    }
    for(Vegetables vege: Vegetables.values())
    {
        if(name.equals(Vegetables.getName()))
        {
              return vege;
        }
    }
  return null;
}

Downside of this however is that you will then have to compare and cast the result to what you want
Object o = getEnum("Carrot")
if(o instanceof Vegetable)
{
     Vegetable v = (Vegetable)o;
     v.getName();
}
//.. and again for fruit


text:
Q: Search through an array with another array I'm pulling in a text file as a multidimensional array and giving the user a choice to pick one of the items and it is stored in another array. I'm trying to figure out how to find the index of the first array with the elements in the second.
Code:
with open("books.txt") as b:
    books = b.readlines()[7:]

books = [x.strip() for x in books]
books = [x.split(",") for x in books]

def welcome():
    print("Welcome to the Bookstore")
    global name
    name = input("What is your name? ")
    print("Our current list of books are: ")
    inventory()

def choice():
    select = input("Which books would you like? (ID):\n")
    global chosen
    chosen = []
    flag = "y"

    while flag == "y":
        chosen.append(select)

        flag = input("Would you like to add more books to your cart? (y/n): ")
    print(chosen)

    for chosen in books:
        books.index(chosen[0])

def inventory():
    length = len(books)
    for i in range(length):
        print(books[i][0], books[i][1].strip(), ("$" + books[i][2]).replace(" ", ""))
    choice()

def receipt():
    print("Thank you", name)

welcome()

Text File:

To add books to your store please have a new book on each line,
and use the format ItemNumber,BookName,BookPrice an example would be as follows:
B142, Prelude to Programing, 5.25
Please start entering books under the heading Books Available.
Thank You

Books Available:
B12, Prelude to Programing, 5.25
B13, Lazy Python, 10.25
B14, Coding for Dummys, 19.25

I have tried
for chosen in books:
    books.index(chosen[0])

If i select B12, I want the result to be 0 0 for the index numbers.

A: Issues:

*

*You are overwriting chosen in the line for chosen in books:.

*Loop prompting for more books just appends last selected book id when y is entered for more.

*The word select colors in my editor as a module select exists. You may want to change the name.

Replace choice() with this change.
def choice():
    global chosen
    chosen = []

    while True:
        select = input("Which books would you like? (ID):\n")
        chosen.append(select)

        flag = input("Would you like to add more books to your cart? (y/n): ")
        if flag != 'y':
            break
    print(chosen)

    index = []
    for item in chosen:
        for idx, book in enumerate(books):
            if item == book[0]:
                index.append([idx, 0])

    print('index:', index)

The index list contains i.e. [[2, 0], ...]
The 2 being the index to find the book in books.
The 0 being the index of the book id.
If the result not exactly what you want, you can make the any changes needed.

Storing the book ID means searching later. You could store the index of the book instead.
i.e.
def choice():
    global chosen
    chosen = []

    while True:
        select = input("Which books would you like? (ID):\n")
        # Get the index of the selected book in books.
        for idx, book in enumerate(books):
            if select == book[0]:
                chosen.append(idx)
                break

        flag = input("Would you like to add more books to your cart? (y/n): ")
        if flag != 'y':
            break
    print(chosen)

    # [[0, 0], ...]
    result = [[idx, 0] for idx in chosen]
    print(result)

This function is storing the index of the book chosen rather than the ID of the book ID as it is more convenient to use the index later as the use of list comprehension shows at the end.


text:
Q: Holy Grail of Layouts and its change Question 1:I learnt Holy Grail of Layouts today, after coding,the browsers show me strange format like this(not a complete black border):
[
my code is following:

 #container {
   border: 10px solid black;
   /*this code cause the umcomplete black border*/
   padding: 0 220px 0 200px;
 }
 .main1 {
   float: left;
   position: relative;
   width: 100%;
   background-color: grey;
   min-height: 100px;
 }
 .left1 {
   float: left;
   position: relative;
   width: 200px;
   margin-left: -100%;
   left: -200px;
   background-color: red;
   min-height: 100px;
 }
 .right1 {
   float: left;
   position: relative;
   width: 220px;
   margin-left: -220px;
   right: -220px;
   background-color: green;
   min-height: 100px;
 }

this is paragraph 1

this is paragraph 2

this is paragraph 3

Question 2:In my opion,if I make some changes, same layout will show but position:relative is not included.The format is still strange(content in midddle area is covered by both side areas):

.main2 {
  background-color: grey;
  float: left;
  width: 100%;
  min-height: 100px;
}
/*this is the only new code*/

#main2Inner {
  margin: 0 220px 0 600px;
}
.left2 {
  float: left;
  width: 200px;
  margin-left: -100%;
  background-color: red;
  min-height: 100px;
}
.right2 {
  float: left;
  width: 220px;
  margin-left: -220px;
  background-color: green;
  min-height: 100px;
}

this is paragraph 4 I dont know why some content cannot be displayed

this is paragraph 5

this is paragraph 6

A: You are dealing with floating elements overflowing their container. You may use overflow:hidden (or position/float, display) to modify the block formating context (BFC).

#container {
  border: 10px solid black;
  overflow: hidden;
  /*keyword : Block Formating Context */
  padding: 0 220px 0 200px;
  min-width: 500px;
  ;
}
.main1 {
  float: left;
  position: relative;
  width: 100%;
  background-color: grey;
  min-height: 100px;
}
.left1 {
  float: left;
  position: relative;
  width: 200px;
  margin-left: -100%;
  left: -200px;
  background-color: red;
  min-height: 100px;
}
.right1 {
  float: left;
  position: relative;
  width: 220px;
  margin-left: -220px;
  right: -220px;
  background-color: green;
  min-height: 100px;
}

this is paragraph 1

this is paragraph 2

this is paragraph 3

http://www.sitepoint.com/understanding-block-formatting-contexts-in-css/

Flex or table display would be more reliable in my own opinion

#container {
  border: 10px solid black;
  display: flex;
  min-height: 50px;
  box-sizing: border-box;
}
.main1 {
  background-color: grey;
  flex: 1;
}
.left1 {
  order: -1;
  width: 200px;
  background-color: red;
}
.right1 {
  width: 220px;
  background-color: green;
}
#container2 {
  border: 10px solid black;
  height: 50px;
  /* will grow taller if needed */
  display: table;
  width: 100%;
  box-sizing: border-box;
  table-layout: fixed;
}
#container2 > div {
  display: table-cell;
}

display:flex

this is paragraph 1

this is paragraph 2

this is paragraph 3

display:table

this is paragraph 1

this is paragraph 2

this is paragraph 3


text:
Q: SQL Server database tries to restore itself automatically (and gets stuck) I currently run into an issue, that a SQL Server Database has the state 'recovery pending' every morning.
No one has started a database recovery, the server itself decides to do it.
The recovery process gets stuck and the SQL Server stops working, as its memory limit is reached.
Temporarily, I can resolve it by restarting the MSSQLSERVER process and then taking the database offline and back online. However, as this seems to be happening every day now, this is an unacceptable workaround.
I am eager to know:

*

*What are the possible reasons, that a SQL Server automatically starts such an automated restore process

*Are there any Logs / Events I can look for, to find the reason.

*How can I solve it :)

Any help or hint will be highly appreciated.

Update: Database was in recovery pending, not in restore pending . The SSMS is installed in german language and didn't show me the english status.

A: I have a feeling that what you really  have is "recovery pending" and not "restore pending". If you look at the documentation for sys.databases, the state column, you will see that there isn't a state called "restore pending". So, I will assume it is indeed "recovery pending" below. If it is anything else, please let us know, show is what it look like in SSMS Object Explorer as well as the state column from sys.databases.
Recovery pending means that SQL server couldn't do recovery at startup of the database. Note that start of the database can happen outside startup of SQL Server. Having the autoclose database option set to true is one such case.
Anyhow, whenever recovery isn't doable, the database goes into recovery pending. But SQL server will document why, in the errorlog file. So your task is to hunt down these error messages and act on them. My guess is that any of the database files are used by some other process (anti-virus, snapshot thingie, etc). But at a later time, the files are accessible to SQL Server.


text:
Q: node redis - id generation race condition Multiple processes have access to my redis store. When adding a new user hash, I do the following steps:

*

*incr userId

*set user:[the incremented userId] ...

How can I bundle these steps into a transaction?
const client = require('redis').createClient();

client.on("connect", () => {
    const multi = client.multi();
    multi.incr("userId", (userId) => {
        console.log("new userId is %s", userId);    // TODO userId should not be null
        multi.set("user:"+userId, {name:"UserName"} );
    });
    multi.exec();    // TODO after the execution I expect to see the key user:null using redis-cli, but it does not exist
});

A: You can't use a the reply from an operation on a transaction inside the same transaction, but there's also no need for that in your case - the INCR operation is atomic and guaranteed to return a race-free unique value.


text:
Q: Handle Chain Expressions (Antlr) I am making an interpreter in Antlr and I am having trouble with the following:
One of my rules states:
expression
    : { .. }
    | {... }
    | identifier
    | expression DOT expressioon
    | get_index
    | invoke_method
    | { ... }
    ;

I thought this way I'd evaluate expressions such as "a.b[2].Run()" or whatever... the idea is being able to use both variables, indexing, and methods. All 3 syntaxes are in place... How do I chain them tho? Is my approach correct? or is there a better way? (The example I provided just randomly throws those in with no specification for the sake of clearance, it's not the actual grammar but I can assure you all other 3 grammar rules(identifier, get_index and invoke_method) are defined and are proper, identifier is a single one, not chained)


text:
Q: Primary Keys and Normalization I have to normalize my database up to BCNF but I'm a little bit confused about 1NF.
My main table is about video games and it looks like this:
game_id(PK, AI)    title    developer_id(FK)    publisher_id(FK)    genre                   modes                               release_date
    1              XYZ          3                   5               FPS, Battle Royale      Single-player, multiplayer          2019-02-04

My confusion is about the "modes" and "genre" columns because sometimes I have more than one value so it's not atomic, right? This comment says the same Explain Like I am Five -> How a Primary Key Satisfies First Normal Form BUT the comment right below him says the opposite...
I've read about normalization and I found this example of a table in 1NF. Looking back at my table, I realized I can't do the same because I have an 'id' which is a PK so it can't have duplicate values. Other sources say that once you have a PK it means that the table is in 1NF because all rows are different.
I'm thinking about creating another two tables where I store only the 'modes' which are (Single-player/Multiplayer/Single-player, multiplayer) and the 'genres'. But, how would I insert the 'mode_id' as an FK in the 'game' table if, again, a game has only one 'id' which is also a PK?
Then I guess it also satisfies NF2? And for NF3 I should create two more tables where I store the n-m relationships between games-modes and games-genres...
I'd be glad if anyone wants to look at my whole database (it's small and simple) and tell me where I should apply normalization. Thank you!

A: The comment you linked is correct, the comment below that is wrong.
1NF says that each attribute needs to be atomic (which is usually meant semantically, not technically. Technically, the string "FPS, Battle Royale" is as atomic as any other, because technically any string is as atomic as any other.
But 1NF is meant semantically: you should not store multiple values in a single column of a single row.
The easiest way to make your table 1NF is just to transform it into
game_id(PK, AI)    title    developer_id(FK)    publisher_id(FK)    genre          modes                               release_date
1                  xyz      3                   5                   FPS            Single-player          2019-02-04
1                  xyz      3                   5                   FPS            multiplayer          2019-02-04
1                  xyz      3                   5                   Battle Royale  Single-player          2019-02-04
1                  xyz      3                   5                   Battle Royale  multiplayer          2019-02-04

Of course, this is only 1NF. Fully normalized, it should be something along:
table GAMES
game_id(PK, AI)    title    developer_id(FK)    publisher_id(FK)    release_date
1                  xyz      3                   5                   2019-02-04

table GENRES
genre_id(PK)       name
1                  FPS
2                  Battle Royale

table MODES
mode_id(PK)        name
1                  Single-player
2                  multiplayer

table GAME_GENRE
id      game_id      genre_id
1       1            1
2       1            2

table GAME_MODE
id      game_id      mode_id
1       1            1
2       1            2

``


text:
Q: extremely short power interruption causes PC reset I am trying to evaluate the following sentence from a customer:
"a 30 milliseconds power interruption has caused a reset of a personal computer".
This specific PC has a 600W power supply.
Is it  possible that a 30 milliseconds power interruption can have caused this issue?

A: A few facts to start with:

*

*In a 50Hz grid, a complete cycle is 20ms

*In a 60Hz grid, a complete cycle is ca. 17ms.

*Consumer PC power suplies are typically designed to survive a single cycle power loss (i.e.: The combination of amount of energy stored in the PSU's LC elements and the fill- and empty-rate of these allow to recover the amount of energy used in a single cycle)

*Server power supplies are typically designed to survive 2-3 cycles, but only if all (in a redundant PSU setting) are present and operative. They should survive a single cycle even in emergency mode (no more redundancy)

*UPSes are designed to switch over within 8ms (60Hz) resp. 10ms (50Hz), which is half a cycle.

Now: A 30ms interruption is close to a 2-cycle energy loss on a 60Hz grid, this would imply, that if a standard consumer PC PSU were to supply a load of a bit over 50% and designed to the usual standard, it would indeed drop out of the voltage window and signal this via the PWRGOOD signal to the mainboard. If this were to immediately assert a power failure (and not delay for a few ms), the chipset would shut down hard.
On return of power (ca. 50ms later: 30ms brownout plus PSU restart) it would do a cold boot.


text:
Q: Borel equivalence relations on Ellentuck cubes Is there a Borel equivalence relation $E$ on $[\omega]^\omega$ such that $E \not \leq_B E_0$ and for any $a \in [\omega]^\omega$ we have that $E \upharpoonright [a]^\omega$ is Borel bireducible with $E$?
I have a feeling I have seen this question (possibly with an answer) somewhere, but I cannot find it now. In case this really can be found somewhere, I would appreciate the reference.
In case the answer is yes, is it still yes if we replace $E_0$ by something more complex?
Note that by Theorem 8.17 (Mathias) from Canonical Ramsey theory on Polish spaces by Kanovei, Sabok and Zapletal, we have that for a countable Borel equivalence relation $E$, there will be some $a \in [\omega]^\omega$ with $E \upharpoonright [a]^\omega \leq_B E_0$, so we can exclude countable $E$.


text:
Q: How can I make my bash script wait 30 minutes to run? I have a bash script to lock my computer. I want to set it to lock in 30 minutes from right now.
This is my bash script for my mac computer to lock my screen
/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend

I can execute it with this code
sh ~/Documents/Misc/lock_computer

A: You can use the sleep 30m command.
More details here: https://www.cyberciti.biz/faq/linux-unix-sleep-bash-scripting/

A: echo 'sh ~/Documents/Misc/lock_computer' | at 'now + 30 minutes'


text:
Q: display nested elements withing a group using xslt I have edi doc in xml that looks like this (this is a snippet only, the actual EDI is at the end of this post)
<ediroot>
<interchange><sender><address Id="7817942742" Qual="12" /></sender>
<group>
    <transaction Control="0001">
            <segment Id="B3">
                <element Id="B302">12345678</element>
                <element Id="B303">NS</element>
                <element Id="B304">CC</element>
                <element Id="B305">L</element>
            </segment>
            <segment Id="G62">
                <element Id="G6201">12</element>
                <element Id="G6202">20160928</element>
            </segment>
            <segment Id="R3">
                <element Id="R301">ABCD</element>
                <element Id="R302">B</element>
            </segment>
        </transaction>
        <transaction Control="0002">
            <segment Id="B3">
                <element Id="B302">999999</element>
                <element Id="B303">NS</element>
                <element Id="B304">CC</element>
            </segment>
            <segment Id="G62">
                <element Id="G6201">13</element>
                <element Id="G6202">20150928</element>
            </segment>
            <segment Id="R3">
                <element Id="R301">ABCD</element>
                <element Id="R302">B</element>
            </segment>
        </transaction>
    </group>
</interchange>
</ediroot>

I need to set element Id as a new element and element value as value, like this
<ediroot>
<interchange>
<group>
    <transaction Control="0001">
            <B3>
                <B302>12345678</B302>
                <B303>NS</B303>
.....

I am strugling with iterating thru the group, I am using this xslt
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" indent="yes" />
<xsl:template match="ediroot">
<ediroot>
    <xsl:apply-templates select="interchange"/>
</ediroot>
</xsl:template>
    <xsl:template match="group">
        <transaction>
            <xsl:apply-templates select="transaction"/>
        </transaction>
    </xsl:template>
            <xsl:template match="transaction">
            <txn>
                <xsl:for-each-group select="segment" group-by="@Id">
                    <group name="{current-grouping-key()}">
                        <Id><xsl:value-of select="element/@Id"/></Id>
                        <Value><xsl:value-of select="element"/></Value>
                    </group>
                </xsl:for-each-group>
            </txn>
            </xsl:template>

</xsl:stylesheet>

and it produces xml like this
<?xml version="1.0" encoding="UTF-8"?>
<ediroot>
   <transaction>
      <txn>
        <group name="B3">
            <Id>B302 B303 B304 B305</Id>
            <Value>12345678 NS CC L</Value>
        </group>

        <group name="G62">
            <Id>G6201 G6202</Id>
            <Value>86 20160928</Value>
        </group>
        <group name="R3">
            <Id>R301 R302</Id>
            <Value>ABCD B</Value>
        </group>
      </txn>
      <txn>
         <!-- second txn group -->
      </txn>
   </transaction>
</ediroot>

How do I get group/transaction/segment/element as separate xml elements rather than in one node? i.e. instead of this
<group name="B3">
            <Id>B302 B303 B304 B305</Id>
            <Value>12345678 NS CC L</Value>
        </group>

I need this

            <B3>
                <B302>12345678</B302>
                <B303>NS</B303>
                <B304>CC</B304>
                <B305>L</B305>

For those who are interested to see the actual xml, its an edi-to-xml transform using http://edireader.sourceforge.net/
<?xml version="1.0" encoding="UTF-8"?>
<ediroot>
    <interchange Standard="ANSI X.12" Date="110813" Time="1410" StandardsId="U" Version="00300"
        Control="000000001">
        <sender>
            <address Id="ABCCOM         " Qual="01"/>
        </sender>
        <receiver>
            <address Id="999999999" Qual="01"/>
        </receiver>
        <group GroupType="IM" ApplSender="006998397" ApplReceiver="123456789" Date="20110813"
            Time="1410" Control="000000001" StandardCode="X" StandardVersion="004010">
            <transaction DocType="210" Name="Motor Carrier Freight Details and Invoice"
                Control="000000001">
                <segment Id="B3">
                    <element Id="B302">2509121213</element>
                    <element Id="B303">8000281336</element>
                    <element Id="B304">PP</element>
                    <element Id="B306">20110813</element>
                    <element Id="B307">18304</element>
                    <element Id="B309">20110801</element>
                    <element Id="B310">017</element>
                    <element Id="B311">XXXX</element>
                </segment>
                <segment Id="N9">
                    <element Id="N901">PO</element>
                    <element Id="N902">SM12003301</element>
                </segment>
                <segment Id="G62">
                    <element Id="G6201">86</element>
                    <element Id="G6202">20110801</element>
                </segment>
                <loop Id="N1">
                    <segment Id="N1">
                        <element Id="N101">CN</element>
                        <element Id="N102">AAA HARDWARE</element>
                    </segment>
                    <segment Id="N3">
                        <element Id="N301">9805 POPLAR ST</element>
                    </segment>
                    <segment Id="N4">
                        <element Id="N401">LEADVILLE</element>
                        <element Id="N402">CO</element>
                        <element Id="N403">80461</element>
                    </segment>
                </loop>
                <loop Id="N1">
                    <segment Id="N1">
                        <element Id="N101">SH</element>
                        <element Id="N102">BBB OIL COMPANY</element>
                    </segment>
                    <segment Id="N3">
                        <element Id="N301">2361 S DIXIE HWY</element>
                    </segment>
                    <segment Id="N4">
                        <element Id="N401">LIMA</element>
                        <element Id="N402">OH</element>
                        <element Id="N403">45802</element>
                    </segment>
                </loop>
                <loop Id="N1">
                    <segment Id="N1">
                        <element Id="N101">BT</element>
                        <element Id="N102">ANY PAY AGENT</element>
                    </segment>
                    <segment Id="N3">
                        <element Id="N301">ATTN: DONNA SMITH</element>
                        <element Id="N302">PO BOX 16789</element>
                    </segment>
                    <segment Id="N4">
                        <element Id="N401">ANYTOWN</element>
                        <element Id="N402">MO</element>
                        <element Id="N403">12345-6789</element>
                    </segment>
                </loop>
                <loop Id="LX">
                    <segment Id="LX">
                        <element Id="LX01">1</element>
                    </segment>
                    <segment Id="L5">
                        <element Id="L501">1</element>
                        <element Id="L502">PETROLEUM OILS,</element>
                        <element Id="L503">15525002</element>
                        <element Id="L504">N</element>
                    </segment>
                    <segment Id="L0">
                        <element Id="L001">1</element>
                        <element Id="L004">138</element>
                        <element Id="L005">N</element>
                        <element Id="L008">1</element>
                        <element Id="L009">PLT</element>
                        <element Id="L011">L</element>
                    </segment>
                    <segment Id="L1">
                        <element Id="L101">1</element>
                        <element Id="L102">120</element>
                        <element Id="L103">PH</element>
                        <element Id="L104">18304</element>
                    </segment>
                    <segment Id="L7">
                        <element Id="L701">1</element>
                        <element Id="L707">0E60</element>
                    </segment>
                </loop>
                <loop Id="LX">
                    <segment Id="LX">
                        <element Id="LX01">2</element>
                    </segment>
                </loop>
                <segment Id="L3">
                    <element Id="L301">138</element>
                    <element Id="L302">G</element>
                    <element Id="L305">18304</element>
                    <element Id="L311">1</element>
                </segment>
            </transaction>
        </group>
    </interchange>
</ediroot>

A: The XML you presented contains a syntax error: it contains a second <group> start tag where an end tag is needed.
Although XSLT supports iteration, there are often simpler approaches.  Yours appears to be such a case.  You want to transform each element with an Id attribute into another element, which seems to call for a simple template with an appropriate selector, nothing more.  For example:
<xsl:stylesheet version="1.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <!-- identity transform for otherwise-unmatched nodes and attributes -->
   <xsl:template match="@*|node()">
     <xsl:copy>
       <xsl:apply-templates select="@*|node()" />
     </xsl:copy>
   </xsl:template>

   <!-- Special handling for elements bearing an Id attribute -->
   <xsl:template match="segment[@Id]|element[@Id]">
     <!-- transform as an element whose name is drawn from the Id attribute -->
     <xsl:element name="{@Id}">
       <!-- transform child nodes (including text nodes), but not attributes -->
       <xsl:apply-templates select="node()" />
     </xsl:element>
   </xsl:template>

</xsl:stylesheet>

A: I don't understand your example. In general, you would use either
<xsl:for-each select="current-group()">

or:
<xsl:apply-templates select="current-group()"/>

to process the members of the current group.

Working example: http://xsltransform.net/jz1PuP9


text:
Q: ios security image files in document directory I need to secure files in document directory on iOS especially images. I don't want user can download images in document directory by Xcode or iExplorer app.
I research on iOS 6, Apple support security by passcode of device. But it's not as i expected.
Are you have any ideas?

A: The easiest way is to use the NSData method writeToFile:options:error:
with one of the options NSDataWritingOptions which will write the file encrypted:
NSDataWritingFileProtectionComplete,
NSDataWritingFileProtectionCompleteUnlessOpen or
NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication
Otherwise you can use the CommonCrypto functions to encrypt/decrypt yourself. That is not really hard except for securing and handling the key and securing the key is the most important part and the hardest to get right.

A: I think the easiest way to encrypt your file is Exclusive-OR.
The Basic principle is A xor B xor B = A.
More from Link


text:
Q: decoding unicode? im not sure wtf it is Im trying to decode some characters that Im getting from a curl call. The strange thing is that on the output it looks ok, but on the source code not, and I cant work with that.
For example:
3.200 a. C.

3.200 a. C.

I have tried everything and I cant find the solution. Please help, thanks!

A: Those are XML/SGML/HTML character references. html_entity_decode should decode them

A: You can use multibyte string functions.

A: &#xA0 is the character representation of a non-breaking space, i. e. a space where you're not allowed to do a line break. Sort of like   in HTML.
Where exactly are you running into problems with this?

A: The   is an XML-escaped non-breaking space (U+00A0 (160)). As such, this has nothing to do with Unicode, but ASCII. (My bad, see comments!)
If you want to "get rid" of it, you should look for a way to decode it, i.e., resolve the XML entities to regular characters.


text:
Q: MySqlCommand.ExecuteReader() is throwing a System.Format exception on Initialization So I'm trying to use a MySqlDataReader to acquire data from my database. I know that the database does in fact respond (insert, delete, and update all work fine from my program).
using (MySqlConnection conn = new MySqlConnection(connectionString))
        {
            // Open a connection
            conn.Open();
            MySqlCommand command = conn.CreateCommand();
            command.CommandText = "select * from cs3500_u0848199.PairedGames";

            // Execute the command and cycle through the DataReader object

            using (MySqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                { /*do something here*/}
            }
        }

The problem does not appear to be with the command itself, as the command works in the MySQL workbench. Anyways, upon executing this line of code
using (MySqlConnection conn = new MySqlConnection(connectionString))

the VS debugger notes that the following exception was thrown

System.FormatException was unhandled by user code
  HResult=-2146233033   Message=Guid should contain 32 digits with 4
  dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).   Source=mscorlib
  StackTrace:
         at System.Guid.TryParseGuidWithNoStyle(String guidString, GuidResult& result)
         at System.Guid.TryParseGuid(String g, GuidStyles flags, GuidResult& result)
         at System.Guid..ctor(String g)
         at MySql.Data.Types.MySqlGuid.MySql.Data.Types.IMySqlValue.ReadValue(MySqlPacket
  packet, Int64 length, Boolean nullVal)
         at MySql.Data.MySqlClient.NativeDriver.ReadColumnValue(Int32 index, MySqlField field, IMySqlValue valObject)
         at MySql.Data.MySqlClient.Driver.ReadColumnValue(Int32 index, MySqlField field, IMySqlValue value)
         at MySql.Data.MySqlClient.ResultSet.ReadColumnData(Boolean outputParms)
         at MySql.Data.MySqlClient.ResultSet.NextRow(CommandBehavior behavior)
         at MySql.Data.MySqlClient.MySqlDataReader.Read()
         at ToDoList.BoggleService.GetBriefStatus(String gameToken) in d:\repositories\x0848199\PS11\ToDoService\BoggleService.svc.cs:line
  443
         at SyncInvokeGetBriefStatus(Object , Object[] , Object[] )
         at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object
  instance, Object[] inputs, Object[]& outputs)
         at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&
  rpc)   InnerException:

Really unsure as to why it's telling me about the guid format since i'm not using Guids in this code.
Any help will be greatly appreciated.

A: it appears that appending ;old guids=true; to the connection string resolved the issue.


text:
Q: Is there a way to display notification badge on Google's official BottomNavigationView menu items introduced in API 25? I have been trying BottomNavigationView released in API 25. I want to display a notification badge (say a small blue circle with or without a count in it) on one of the menu items in bottom navigation bar.
I have a selector drawable where I have added checked true and checked false states with greyed out drawable which has a BLUE dot on it. When user navigates to other navigation item the whole menu button turns grey and the badge as well. I know this is because itemIconTint is applied to the drawable which is the reason having a different colour badge as part of the icon won't work. Is there any alternate way to achieve this?
<android.support.design.widget.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/white"
    app:itemIconTint="@color/selector_bottom_nav"
    app:itemTextColor="@color/selector_bottom_nav"
    android:layout_gravity="bottom"
    app:menu="@menu/menu_bottom_nav">
</android.support.design.widget.BottomNavigationView>

That is how I am using it. Removing itemIconTint and changing icon drawable programmatically does not help.
On Android Developers I have found nothing and it being pretty new nothing is available on the web as well.
There are custom libraries for bottom navigation bar but I am looking for its support in the official one.
Any ideas, anyone?

A: Answering my own question:
I ended up putting 2 ImageViews with badge drawable and visiblity GONE in my layout. I calculate positioning of the badges like this:
private void calculateBadgesPosition() {
int totalNavItems = 3;
        for(int i = 0 ; i < bottomNavigation.getChildCount() ; i++) {
            View view =  bottomNavigation.getChildAt(i);

// Since Y remains same for all badges at least in my case.
// 1.3 is a factor that fits my placement of badge.
            double y = getResources().getDisplayMetrics().heightPixels - (view.getMeasuredHeight() * 1.3);
            if(image2ndItemBadge != null) {
                float x = getResources().getDisplayMetrics().widthPixels/2 + imageClassroomBadge.getMeasuredWidth()/2;

                image2ndItemBadge.setX(x);
                image2ndItemBadge.setY((float)y);
                image2ndItemBadge.requestLayout();
            }
// Since BottomNavigationView items are equally distributed you can find
// the right position for 3rd item (in my case last item) by dividing
// BottomNavigationView width by 3 and then by 2 to get the middle of that
// item, which was needed in my case.
            if(image3rdItemBadge != null) {
                float x = getResources().getDisplayMetrics().widthPixels - ((view.getMeasuredWidth()/totalNavItems)/2);

                image3rdItemBadge.setX(x);
                image3rdItemBadge.setY((float)y);
                image3rdItemBadge.requestLayout();
            }
            // BottomNavigationView count should always be 1
            // but I observed the count was 2 in API 19. So I break after first iteration.
            break;
        }
    }

You can remove the for loop and just check if child count greater than 0 and get that child. I call the above method at the end of onCreate like this:
ViewTreeObserver viewTreeObserver = getWindow().getDecorView().getViewTreeObserver();
            viewTreeObservier.addOnGlobalLayoutListener (new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    calculateBadgesPosition();
                    getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            });

Badge ImageView not being part of the BottomNavigationView Items drawable will not be effected by tint that BottomNavigationView applies on selection/un selection of item. Also if you see your badge not appearing try giving it a higher elevation 8 or 16 or whatever. In my case my badge stayed behind BottomNavigationView probably because it has higher elevation or Z index.
I tested this with 3 different screen sizes and the positioning was same on all.
I hope this helps anyone facing similar issue with official BottomNavigationView.
Also if you have a better approach please share it.

A: One way of achieving this is using two icons for each item - one with the badge and the other without and replace them programmatically. Alternatively, instead of two icons, you can use a single icon and draw the badge programmatically. So the code can look something like this (assuming you know the index of each item and can get the Drawable for each):
public static void updateItem(BottomNavigationView bottomNavigationView, int index, Drawable icon) {
    Menu menu = bottomNavigationView.getMenu();
    MenuItem item = menu.getItem(index);

    if (item != null) {
        item.setIcon(icon);
    }
}

A: Create a layout with a Textview.
Inflate the view by adding the BottomNavigationMenuView as child for BottomNavigationView. Add the count to required menu.
See the below link.
https://stackoverflow.com/a/48269868/4675067


text:
Q: How to measure QoS parameters in the ns-3 simulation I would like to simulate voip in a wimax network. What I would like to measure are the QoS parameters such as IPTD, IPDV and IPLR. I am new to the ns-3 simulator and I can't find anything about QoS measurment. I've already searched in google and it seems that there is nothing like QoS library? If I am correct, how to measure these parameters in this simulation tool? If not, could please someone give me some advice where I can find such library?

A: From my short experience,
Generally you need to use the flowMonitor helper class to get the statistics.
Refer below.
http://www.nsnam.org/doxygen/classns3_1_1_flow_monitor_helper.html
If it is just the basic statistics like bytes received, sent etc, you have already functions in the packet class that can be used to get the values. Else you need to define them and write methods to do the calculations.
I am not an expert in wireless world, but you can find an example here
http://personal.ee.surrey.ac.uk/Personal/K.Katsaros/media/ns3lab-sol/lab-5-solved.cc


text:
Q: Simple (but not for me) - Translate ActionScript 3 to C# code recently I have discovered C#, which is really what I want. Before C# I was coding with AS3. I've recoded all my old program using C# but I am blocked with this :
public function Envoie_Serveur(param1:String) : void
{
    var _loc_2:* = String(this.CMDTEC % 9000 + 1000).split("");
    this.Serveur.send(this.MDT[_loc_2[0]] + this.MDT[_loc_2[1]] + this.MDT[_loc_2[2]] + this.MDT[_loc_2[3]] + param1);
    var _loc_3:* = this;
    var _loc_4:* = this.CMDTEC + 1;
    _loc_3.CMDTEC = _loc_4;
    return;
}

CMDTEC and MDT are 2 byteArray (byte[] in C# I guess)
That is what I have tried but which is not working ;c
byte[] _loc_1 = Encode((Int64.Parse(this.CMDTEC[0].ToString("X", System.Globalization.NumberStyles.HexNumber)) % 9000 + 1000) + "");
var fingerprint = new byte[4];

fingerprint[0] = byte.Parse(this.MDT[_loc_1[0]].ToString("X"), System.Globalization.NumberStyles.HexNumber);
fingerprint[1] = byte.Parse(this.MDT[_loc_1[1]].ToString("X"), System.Globalization.NumberStyles.HexNumber);
fingerprint[2] = byte.Parse(this.MDT[_loc_1[2]].ToString("X"), System.Globalization.NumberStyles.HexNumber);
fingerprint[3] = byte.Parse(this.MDT[_loc_1[3]].ToString("X"), System.Globalization.NumberStyles.HexNumber);
this.CMDTEC++;

And for exemple, that is what CMDTEC and MDT contains :
this.MDT = "1400175151406"; (just for exemple, I get this by socket)
this.CMDTEC = "8306"; (idem as ^)

How can I convert properly that to C# please ? Thanks in advance for answers.


text:
Q: Seeking world sea routes for ships Where I can find world sea routes for ships?
I need it as a GeoJSON or shapefile format.

A: Check out these two sources to find datasets for sea routes for ships worldwide
Shipping Routes (with labels) - One Year
Global Shipping Routes, Using 250 Million Data Points


text:
Q: XP in VMware with Host SSD My host computer, running Windows 8.1, has an SSD drive.
I want to install Windows XP in a VMware machine, is it safe to place the machine files on the SSD? I have the fear that XP might not handle the underlying SSD correctly and does too many writes or other "abuses".
If yes, should I use special options when creating the VM to prevent this (connection type, reserve full size for the HDD (no dynamic expansion of the disk), etc.)?
I've heard XP does not have direct access to the HDD; more over a VMware driver which then handles the SSD correctly, but my source was not very trustworthy.
Does the same apply for a virtual Windows Vista machine since Vista also doesn't support TRIM out of the box?

A: I'm now using XP since a longer time on my host with an SSD. As said in the comments above, VMware wraps the HDD access and lets it run over the hosts drivers as it seems, so the typical bookkeeping and optimization routines of your SSD are run.


text:
Q: Groupby selected rows by a condition on a column value and then transform another column This seems to be easy but couldn't find a working solution for it:
I have a dataframe with 3 columns:
df = pd.DataFrame({'A': [0,0,2,2,2],
                'B': [1,1,2,2,3],
                'C': [1,1,2,3,4]})

   A  B  C
0  0  1  1
1  0  1  1
2  2  2  2
3  2  2  3
4  2  3  4

I want to select rows based on values of column A, then groupby based on values of column B, and finally transform values of column C into sum. something along the line of this (obviously not working) code:
df[df['A'].isin(['2']), 'C'] = df[df['A'].isin(['2']), 'C'].groupby('B').transform('sum')

desired output for above example is:
   A  B  C
0  0  1  1
1  0  1  1
2  2  2  5
3  2  3  4

I also know how to split dataframe and do it. I am looking more for a solution that does it without the need of split+concat/merge. Thank you.

A: Is it just
s = df['A'].isin([2])

pd.concat((df[s].groupby(['A','B'])['C'].sum().reset_index(),
           df[~s])
         )

Output:
   A  B  C
0  2  2  5
1  2  3  4
0  0  1  1

Update: Without splitting, you can assign a new column indicating special values of A:
(df.sort_values('A')
   .assign(D=(~df['A'].isin([2])).cumsum())
   .groupby(['D','A','B'])['C'].sum()
   .reset_index('D',drop=True)
   .reset_index()
)

Output:
   A  B  C
0  0  1  1
1  0  1  1
2  2  2  5
3  2  3  4


text:
Q: How to use Waves Transactions library in testnet? I'm using Waves transactions library, I need to do some transaction testing using javascript and I would like to know how can I use it in testnet?

A: You will need two things:
First, Some transactions have chainId as param. You need to pass 'T'. E.g:
const burnTx = burn({assetId:'someId', amount:1000, chainId:'T'})

Second, You send tx to testnet node. E.g:
await broadcast(burnTx, ' https://testnodes.wavesnodes.com')


text:
Q: How to fix the issue with very small screen size with Selenium webdriver We just ran into a problem in our test automation infrastructure. The problem is that Windows defaults to a very small screen size (I assume 800x600) while running from Jenkins. Then if the website under test doesn't support such a small resolution without overlapping UI elements, the browser will fail some tests for items that are no longer visible. How can we solve this?

A: It would be best maximize your window as soon as you instantiate your web driver instance.
I don't know the setup of your code but please try adding the following line after you've created an instance of the web driver you wish to use:
Java
driver.manage().window().maximize();

C#
_driver.Manage().Window.Maximize();

Python
driver.maximize_window()

Ruby
@driver.manage.window.maximize

The above may not work in Chrome - if this is the case, please use:
ChromeOptions options = new ChromeOptions();
options.addArgument("--start-maximized");
driver = new ChromeDriver(options);

As per @Ardesco & @Fenio comments - you can also set a specific dimension using:
driver.manage().window().setSize(new Dimension(1920,1080));

A: driver.manage().window().fullscreen()

A: Within your driver setup you can change the browser window size using the following in C#
driver.Manage().Window.Size = new System.Drawing.Size(width: 1600, height: 1200);


text:
Q: How do i get an item with a bold / italic colored name I know how to get a colored item but i cant find out how to get a bold and colored item at the same time.

A: you mean like that?
/give @p minecraft:egg{display:{Lore:['{"text":"Egg","color":"red","bold":true}']}} 1