text:
Q: Is it possible to shift to run off Focus in C# for a Windows Form? I am currently working on a calculator application that looks similar to what the Windows 10 standard calculator looks like. I am practically done with it but sort of ran into an issue I thought I could fix but can't seem to figure out.
I envisioned the calculator being able to have input pressed from on the screen like pressing the "1" button "+" button etc, while also having input from the keyboard. I figured out how to have it sort of work but I have to click the button so the focus shifts to that button every time.
Is there a way to bypass the focus and just look for which button is pressed? I have looked on other posts from this website but haven't found one that seems to match my needs.
Here is my code so far,
private void oneBtn_KeyPress(object sender, KeyPressEventArgs e)
{
     if (e.KeyChar == (char)Keys.D1 || e.KeyChar == (char)Keys.NumPad1)
     {
         textBox1.Text = textBox1.Text + "1";
     }
}

Would I have to set the focus to the whole page in order to achieve what I want my application to do? Is there even a way to do this? I found an question on reddit that seemed pretty similar to what I am asking and it mentions setting the "KeyPreview" property to true. I have done this here,
public CalculatorPage()
{
    InitializeComponent();
    this.KeyPreview = true;
}

but I am still not getting the button click from other buttons to work because the focus is still on the "1" key from loading the program up.

A: you should handle the key binding in the Form Key press event, something like this
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
     // NUM PAD 1
     if (e.KeyChar == (char)Keys.D1 || e.KeyChar == (char)Keys.NumPad1)
     {
         textBox1.Text = textBox1.Text + "1";
     }
     // CHAR NUM PAD 2
     ...

     // CHAR NUM PAD 3
     ...

}

A: The way I understand it, you want to make the button which you pressed in the previous "round" of calculating lose the focus the next time the calculator is opened.
You could do that just by either coding it, e.g. Btn_example.CanFocus = false or you could click every button you want no focus in the Designer and under Properties (bottom left corner) set the CanFocus property to false


text:
Q: Функция возвращающая объект Добрый день, друзья!
Имеется следующий код:
class FileInfo
{
 public static String NameFile;
 public static String TypeFile;
 public static int SizeFile;
 public static String DateCreate;
 public static String DateEdit;
}

И другой класс:
public class View_files_folders
{
  public ??? getItem(int number)
  {

   }
}

*

*Вопрос первый как сделать, чтобы
   функция getItem возвращала класс
   FileInfo?

*Второй вопрос, есть ли специальные в Java типы данных даты и времени, если да, то какой модуль надо подключать? Чтобы поля DateCreate и DateEdit по возможности не делать типом String.

*Как сделать чтобы getItem возвращала объект?

A: public FileInfo getItem(){}

A: 2) Date, GregorianCalendar
Сторонняя: JodaTime
A: В Java 8 появилась замечательная библиотека для работы со временем:
Статья на Хабре

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Remote error from mongot :: caused by :: \"path\" is required (from \"wildcard\")" - Error in mongodb Atlas Search (Java Driver) I'm getting the following when trying to do a MongoDB Atlas Search query using mongodb Java driver, I'm using the java driver 4.1.
exception in thread "main" com.mongodb.MongoCommandException: Command failed with error 8 (UnknownError): 'Remote error from mongot :: caused by :: "path" is required (from "wildcard")' on server ***. The full response is {"operationTime": {"$timestamp": {"t": 1603099324, "i": 1}}, "ok": 0.0, "errmsg": "Remote error from mongot :: caused by :: \"path\" is required (from \"wildcard\")", "code": 8, "codeName": "UnknownError", "$clusterTime": {"clusterTime": {"$timestamp": {"t": 1603099324, "i": 1}}, "signature": ***}, "keyId": ***}}}
at com.mongodb.internal.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:175)
at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:359)
at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:280)
at com.mongodb.internal.connection.UsageTrackingInternalConnection.sendAndReceive(UsageTrackingInternalConnection.java:100)
at com.mongodb.internal.connection.DefaultConnectionPool$PooledConnection.sendAndReceive(DefaultConnectionPool.java:490)
at com.mongodb.internal.connection.CommandProtocolImpl.execute(CommandProtocolImpl.java:71)

following the code snippet, it was generated from mogodb atlas console itself.
testingCollection.aggregate(Arrays.asList(
    eq("$search",
            eq("wildcard",
                    and(
                            eq("path", "name"),
                            eq("query", "dushan*"),
                            eq("allowAnalyzedField", true)
                       )
              )
      ))).first();

Any idea what would be the cause?


text:
Q: Woocommerce coupon apply automatically on cart and checkout page I need a coupon to be applied automatically when a product selects a custom field in it ( a checkbox as custom field) .If that checkbox is ticked in that product then woo commerce coupon should be applied automatically on cart and checkout page also well..I have written a custom code for it and its working fine .But if the checkbox is not selected and customer comes to checkout page - there is a default apply coupon code input box , if the customer puts the same coupon and apply's the coupon gets applied .But it shouldn't. The coupon was created on the back-end .
The code is :
add_action( 'woocommerce_before_checkout_form', 'apply_matched_coupons');
function apply_matched_coupons() {
    $coupon_code = 'promo25';
    if (WC()->cart->has_discount($coupon_code))
        return;
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        // this is your product ID
        $autocoupon = array(968);
        if (in_array($cart_item['product_id'], $autocoupon)) {
            if (isset($cart_item[WCPA_CART_ITEM_KEY])) {
                foreach ($cart_item[WCPA_CART_ITEM_KEY] as $field) {
                    if ($field['name'] == 'carpet-steam1') {
                        WC()->cart->add_discount($coupon_code);
                        wc_print_notices();
                    }
                }
            }
        }
    }
}

When promo25 is applied on checkout page, the coupon should not be applied.


text:
Q: \hfill in math mode for multiple alignments I would like to reproduce something like the screenshot attached here, with two separate equations in each line, each set of equations aligned amongst themselves.
On my end, LaTeX always pushes everything left of the second alignment symbol to the farthest left it can be, as if it is all part of the first equation, while I would like the left hand side of the second equation in the same line be immediately next to its own equal sign.
Specifically for the case attached here, I would like to align the two equations respectively with $\to$ and $=$ separately.

Also, if possible, ideally I would like to implement this with just the align environment.
Minimum not-working code:
\documentclass[11pt, oneside]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[english]{babel}
\usepackage{amsmath}
\begin{document}
\begin{align}
\left(\begin{array}{c}{A_{\mu}} \\ {\rho_{\mu}^{*}}\end{array}\right) &\rightarrow\left(\begin{array}{cc}{\cos \theta} & {-\sin \theta} \\ {\sin \theta} & {\cos \theta}\end{array}\right)\left(\begin{array}{c}{A_{\mu}} \\ {\rho_{\mu}^{*}}\end{array}\right), \qquad\qquad\qquad\qquad\tan \theta&=\frac{g_{e l}}{g_{*}}\\
\left(\begin{array}{c}{\psi_{L}} \\ {\chi_{L}}\end{array}\right) &\rightarrow\left(\begin{array}{cc}{\cos \varphi_{\psi_{L}}} & {-\sin \varphi_{\psi_{L}}} \\ {\sin \varphi_{\psi_{L}}} & {\cos \varphi_{\psi_{L}}}\end{array}\right)\left(\begin{array}{c}{\psi_{L}} \\ {\chi_{L}}\end{array}\right), \hfill \tan \varphi_{\psi_{L}}&=\frac{\Delta}{m}\\
\left(\begin{array}{c}{\tilde{\psi}_{R}} \\ {\tilde{\chi}_{R}}\end{array}\right) &\rightarrow\left(\begin{array}{cc}{\cos \varphi_{\tilde{\psi}_{R}}} & {-\sin \varphi_{\tilde{\psi}_{R}}} \\ {\sin \varphi_{\tilde{\psi}_{R}}} & {\cos \varphi_{\tilde{\psi}_{R}}}\end{array}\right)\left(\begin{array}{c}{\tilde{\psi}_{R}} \\ {\tilde{\chi}_{R}}\end{array}\right), \quad \tan \varphi_{\tilde{\psi}_{R}}&=\frac{\tilde{\Delta}}{\tilde{m}}
\end{align}
\end{document}

A: I'd propose alignat, that gives more control of spacing between the column pairs.
The second parts of each row should not, in my opinion, be aligned at the equals sign, because the prominence should be to "tan".
\documentclass[11pt, oneside]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[english]{babel}
\usepackage{amsmath}
\begin{document}
\begin{alignat}{2}
\begin{pmatrix} A_{\mu} \\ \rho_{\mu}^{*} \end{pmatrix}
  & \rightarrow
    \begin{pmatrix} \cos \theta & -\sin \theta \\ \sin \theta & \cos \theta \end{pmatrix}
    \begin{pmatrix} A_{\mu} \\ \rho_{\mu}^{*} \end{pmatrix},
  &\quad& \tan \theta = \frac{g_{e l}}{g_{*}}
\\
\begin{pmatrix} \psi_{L} \\ \chi_{L} \end{pmatrix}
  & \rightarrow
    \begin{pmatrix}
      \cos \varphi_{\psi_{L}} & -\sin \varphi_{\psi_{L}} \\
      \sin \varphi_{\psi_{L}} & \cos \varphi_{\psi_{L}}
    \end{pmatrix}
    \begin{pmatrix} \psi_{L} \\ \chi_{L} \end{pmatrix},
  && \tan \varphi_{\psi_{L}} = \frac{\Delta}{m}
\\
\begin{pmatrix} \tilde{\psi}_{R} \\ \tilde{\chi}_{R} \end{pmatrix}
   & \rightarrow
     \begin{pmatrix}
       \cos \varphi_{\tilde{\psi}_{R}} & -\sin \varphi_{\tilde{\psi}_{R}} \\
       \sin \varphi_{\tilde{\psi}_{R}} & \cos \varphi_{\tilde{\psi}_{R}}
     \end{pmatrix}
     \begin{pmatrix} \tilde{\psi}_{R} \\ \tilde{\chi}_{R} \end{pmatrix},
   && \tan \varphi_{\tilde{\psi}_{R}} = \frac{\tilde{\Delta}}{\tilde{m}}
\end{alignat}

\end{document}

Your opinion may differ. In any case, avoid overusing braces.

A: like this?

with use of pmatrix from asmath and extend align environment with one more ampersand:
\documentclass{article}
\usepackage{amsmath,amssymb,amsthm}

\begin{document}
\begin{align}
\begin{pmatrix}
    A_{\mu}\\ \rho_{\mu}^{*}
\end{pmatrix}
    & \rightarrow   \begin{pmatrix}
                    \cos \theta & -\sin \theta \\
                    \sin \theta &  \cos \theta
                    \end{pmatrix}\begin{pmatrix}
                                    A_{\mu} \\ \rho_{\mu}^{*}
                                 \end{pmatrix},
    &   \tan \theta & = \frac{g_{e l}}{g_{*}}         \\
\begin{pmatrix}\psi_{L} \\ \chi_{L} \end{pmatrix}
    & \rightarrow   \begin{pmatrix}
                    \cos \varphi_{\psi_{L}} & -\sin \varphi_{\psi_{L}} \\
                    \sin \varphi_{\psi_{L}} &  \cos \varphi_{\psi_{L}}
                    \end{pmatrix}\begin{pmatrix}
                                    \psi_{L} \\ \chi_{L}
                                 \end{pmatrix},
    &   \tan \varphi_{\psi_{L}}
            & = \frac{\Delta}{m}    \\
\begin{pmatrix}
    \tilde{\psi}_{R} \\  \tilde{\chi}_{R}
\end{pmatrix}
    & \rightarrow   \begin{pmatrix}
                    \cos \varphi_{\tilde{\psi}_{R}} & -\sin \varphi_{\tilde{\psi}_{R}}  \\
                    \sin \varphi_{\tilde{\psi}_{R}} &  \cos \varphi_{\tilde{\psi}_{R}}
                    \end{pmatrix}\begin{pmatrix}
                                    \tilde{\psi}_{R} \\\tilde{\chi}_{R}
                                 \end{pmatrix},
    &   \tan \varphi_{\tilde{\psi}_{R}}
            & =\frac{\tilde{\Delta}}{\tilde{m}}
\end{align}
\end{document}


text:
Q: Vimeo iframe as background I going to make a website that has a video as a background.
I want to load the video from vimeo but I havent found the best way to put it fullscreen.
i´m trying to add a css to the iframe but it doesn´t work at all:
iframe{
     width: 100%;
     height: 100%;
}

Do any of you know the best way to embed it as a background without using plugins or html5 to avoid problems with IE.
thank you!

A: Here you go: Demo
Wrap it in a div and set that also to 100%, 100%
iframe, div {
     width: 100%;
     height: 100%;
}

A: HTML:

CSS:
body {
    overflow: hidden;
}
iframe {
     position: absolute;
     z-index: 1;
     top: 0;
     left: 0;
     width: 100%;
     height: 100%;
}
#container {
     position: absolute;
     z-index: 2;
     top: 0;
     left: 0;
     width: 100%;
     height: 100%;
     overflow: auto;
}

DEMO:
http://jsbin.com/utezov/4/embed?live

A:
Jape 'Scorpio' from Fergal Brennan on Vimeo.

Now i just took a video from vimeo.
maybe set a class to the iframe like

and set the css like:
iframe.fullvideo {
width: 100%;
height: 100%;
}

A: Try to use an ID to identify this bg iframe:
...

and redefine this iframe in this way:
html, body, p, div, span, table, td
/* Add other elements... These are explicit defined since ie6/7 doesn't support * selector */
{
   z-index: inherit;
   background: transparent; /* this is important to see-through normal elements */
}

#bgiframe {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    padding 0;
    margin: 0;
    border: 0;
    width: 100%; height: 100%;
    z-index: -1;
}

z-index: -1; is for take this element under every other elements.
background: transparent; for every other elements is to see through and see video as background.
This can be an example:
http://jsfiddle.net/4KHET/2/


text:
Q: Java: Getting coordinates of a character, read out of a file Good evening,
for hours I've been searching for a solution for this problem without success so I figured I'd ask a question here!
I have a question regarding reading characters / lines out of a textfile. I have been able to implement a function, which reads lines out of a file.
I am using Greenfoot (Java) to create a game which uses 32x32 blocks. I'd like to generate a world out of that textfile by getting the x- / y-coordinate of each "block" / "character" and placing it in the world. Would it be easier to use an array? My current code looks like this but I cannot figure out, how to get the coordinates. Could it work by using the hashcode it returns?
    public void readFile(String filename) throws IOException
{
    String s;
    int x = 0;
    int y = 0;

    // Create BufferedReader and FileReader
    BufferedReader r = new BufferedReader(new FileReader(filename));

    // Try-catch block as exception handler
    try {
        while((s = r.readLine()) != null) {

            // Create the blocks
            GrassBlock A = new GrassBlock();

            // Place them in the world
            addObject(A, x, y);

            // Test to see, if the blocks get recognised
            System.out.println(A);

            DirtBlock B = new DirtBlock();
            System.out.println(B);
            addObject(B, x, y);
        }
    } catch (IOException e) {
        System.out.println("Fehler beim Öffnen der Datei");
    } finally {

    }
}

My file looks somewhat like this:
0000000000
0000000000
AAAAAA00AA
BBBBBB00BB

I see that I have assigned the value "0" to both x and y so of course it can't work like this but how can I get that position? Right now the function is able to read the lines, generate the blocks at (0, 0) and showing the blocks in the console with a hashcode.
P.S Sorry if I have used the wrong term for some things, I am relatively new to programming!
Thank you,
Julian

A: Just the very basic, without changing question code too much, not complete

*

*determining the line number y:
int y = 0;
while ((s = ...) != null) {
    // do something with s
    y += 1;  // or y++
}

*similar for character position x inside the line and using charAt to retrieve the character:
while ((s = ...) != null)  {
    int x = 0;
    while (x < s.length()) {
        char ch = s.charAt(x);
        // do something with ch, x, y - test for 0, A or B and add block
        x += 1;  // or x++
    }
    y += 1;  // or y++
}

Notes: x is declared inside the outer (first) loop since it is not needed elsewhere; x is set to zero before the inner loop since it is the start of a new line; a for loop could be used instead of while - mostly better when using counters (like x)


text:
Q: Does SCNetworkReachability respect HTTP proxy settings? I'm afraid the answer to this is No, but I'm hoping someone can provide a definitive answer as it is not documented in the current iOS SDK documentation.
We're seeing a case where NSURLConnection is able to connect to https://mysite.com via an HTTP proxy but, because of the way the local DNS is setup in this case, DNS lookups for mysite.com will fail.   In this case, it appears that SCNetworkReachability is trying to perform a DNS lookup for mysite.com and failing.  Meanwhile, NSURLConnection is able to connect.
We have incorporated the Apple Reachability sample code into our app and are calling SCNetworkReachabilityCreateWithName with mysite.com.

A: I can't provide a definitive answer, but I can provide more empirical evidence, and some justification, that the answer is NO. I have an app that uses SCNetworkReachabilityGetFlags to check whether a particular host is reachable (e.g.: www.mysite.com). Depending on that reachability check, it then uses [NSMutableData dataWithContentsOfURL:] to download the data.
The app has always worked fine, but recently I've been doing some coding at work where network access is via the corporate HTTP proxy. When running the app in the iOS Simulator (which uses the proxy settings configured on my Mac) the reachability check fails. At first I thought that perhaps the iOS Simulator wasn't using the Mac's proxy settings, but Mobile Safari in the simulator worked fine. So I removed the reachability check in my app and the call to [NSMutableData dataWithContentsOfURL:] worked fine. This would appear to indicate that SCNetworkReachability does not respect the proxy settings.
Having thought about it, this is probably the correct behaviour if you view SCNetworkReachability as running at the TCP/IP level, not at the HTTP level, in the same way that ping google.com on a Mac/PC behind a corporate firewall doesn't work either. The HTTP proxy (as the name implies) is for the HTTP protocol, not the whole TCP/IP stack.
Having read the answers to this question on Reachability I'm inclined to bin my reachability check altogether. Even though it's only been a problem in the simulator until now, it could be problematic in other situations (e.g. public WiFi hotspot that requires authentication).


text:
Q: Make EventHandler work for clicks and keys in a Dynamic display I am trying to write a way that will do certain events depending on what screen is showing.
What happens so far is that the screen will change in accordance to a click, but when you try to do the key presses associated with that screen, they won't respond. I think the events are being passed to the old screen that is being shown. Is there an option or way to fix this?
My code thus sees if you click within certain coordinates (works, but not shown in simplified code below), then changes what it is showing. The arrow key pressing that corresponds to the new screen does not happen, unless I reevaluate the EventHandler block of code.
Code is below:
displaying = True;

 start[] :=
 If[displaying,
  Show[firstScreen],
  Show[secondScreen]
  ]

EventHandler[
 Dynamic[start[]], {"UpArrowKeyDown" :> (If[!displaying, Print["up press"]]),
  "DownArrowKeyDown" :> (If[!displaying, Print["down press"]]),
  "MouseClicked" :> (If[displaying,
     displaying = False])
  }]

A: Try using NotebookEventActions
displaying = True;

SetOptions[EvaluationNotebook[],
 NotebookEventActions :> {"UpArrowKeyDown" :> (If[! displaying,
      Print["up press"]]),
   "DownArrowKeyDown" :> (If[! displaying, Print["down press"]]),
   "MouseClicked" :> (If[displaying, displaying = False])}]


text:
Q: Windows service TCP communication in local network I've been trying to set up a service that runs in the background and communicates with a Server via TCP. I'm using the .NET Core to set up a TCPListener and, on another device, try to remotely connect via a TCPClient. If i use this outside of a service, in a user executed programm, it works just fine. However, if i start my service, the port im listening to only receives messages from 127.0.0.1, not from the local network.
I suspect there's some permission the service needs to accept network communication, but this is not really my field of expertise. Any advice?
There's no error message. Using Wireshark i confirmed that theres an incoming TCP request on the host, but no connection gets established with my Service.
Thanks in advance o/)
Edit:
I found out that it works if i disable the public firewall on the host PC. But im not really proficient with reading and interpreting the logs. the relevant sections read as follows:
Firewall Log output
Fields: date time action protocol src-ip dst-ip src-port dst-port size tcpflags tcpsyn tcpack tcpwin icmptype icmpcode info path
                                                                                2019-08-29 15:43:58 DROP UDP 192.168.7.98 192.168.7.255 34638 15600 63 - - - - - - - RECEIVE
2019-08-29 15:44:01 ALLOW UDP 192.168.7.117 192.168.7.70 137 137 0 - - - - - - - SEND
2019-08-29 15:44:02 DROP TCP 192.168.7.46 192.168.7.117 49958 13000 52 S 1580866692 0 64240 - - - RECEIVE
2019-08-29 15:44:03 DROP UDP 192.168.7.62 192.168.7.255 57621 57621 72 - - - - - - - RECEIVE
2019-08-29 15:44:04 DROP UDP 192.168.7.98 192.168.7.255 54123 15600 63 - - - - - - - RECEIVE
2019-08-29 15:44:05 DROP TCP 192.168.7.46 192.168.7.117 49958 13000 52 S 1580866692 0 64240 - - - RECEIVE
2019-08-29 15:44:10 DROP UDP 192.168.7.98 192.168.7.255 58249 15600 63 - - - - - - - RECEIVE
2019-08-29 15:44:11 DROP TCP 192.168.7.46 192.168.7.117 49958 13000 52 S 1580866692 0 64240 - - - RECEIVE

(Important are the dropped packages with destination 192.168.7.117:13000.) Does anyone have an idea of how to read those and find out why it's blocking it, and how to stop it from doing so?

A: Update:
The problem was the public firewall blocking service communication for that port. Easiely fixed by adding a two rules that allowed my  windows service to communicate with the assigned port number.


text:
Q: Getting Envoy Access Logs with Istio on GKE I'd like Envoy's Istio access logs (i.e. logs that record every HTTP request) to show up somewhere inside Stackdriver logging. I've tried following the steps in https://istio.io/docs/tasks/telemetry/logs/access-log/. However, the default accessLogFile setting for Istio on GKE seems to be empty, and if I try to change it with kubectl edit configmap -n istio-system istio, it gets reset by the system after a few minute.
Is there a way to push Istio on GKE's access logs into Stackdriver?

A: For the Google managed version of Istio (enabled by checking the box on your GKE cluster) then versions 1.13 and above have the access logs disabled by default, having the configmap accessLogFile: "". On 1.12 or older versions, the access logs are enabled by default so the configmap has accessLogFile: "/dev/stdout".
As you have noted, you are unable to change it as the reconciliation will wipe the change.
I logged a support case with Google to find out the best approach and they suggested using the Mixer logs instead. To access these, you need Stackdriver enabled on your GKE cluster (either legacy or the newer Kubernetes Engine monitoring). You can then use the filter logName="projects/[PROJECT-NAME]/logs/server-accesslog-stackdriver.logentry.istio-system".
To see the requests between two services you would use this Stackdriver query:
logName="projects/[PROJECT-NAME]/logs/server-accesslog-stackdriver.logentry.istio-system"
labels.destination_app="[YOUR-SERVICE]"
labels.source_app="[YOUR-OTHER-SERVICE]"

To see the requests originating from outside GKE and flowing through the Istio Ingress Gateway:
logName="projects/[YOUR-PROJECT]/logs/server-accesslog-stackdriver.logentry.istio-system"
labels.destination_app="[YOUR-SERVICE]"
labels.source_app="istio-ingressgateway"

These logs aren't 100% equivalent to the proxy access logs however, and may not help troubleshooting all scenarios. There is a feature request open with Google to support customization of the Istio config-map including the accessLogFile setting: https://issuetracker.google.com/issues/126527530
I'd suggest anyone interested in this feature should vote for it by adding a star.
Hope that helps!

A: In GKE, all stdout and stderr gets collected and sent to the node's log-rotate for later parsing and exporting into Stackdriver, via Fluentd.
The Access Logs are available using kubectl logs command, meaning that they're in the node and they're being parsed and exported using the Fluentd agent.
I replicated this and was able to find the Access Logs using the following Stackdriver advaced filter (change it according to your own resources):
resource.type="container"
resource.labels.cluster_name="gke-cluster"
resource.labels.namespace_id="application-namespace"
resource.labels.project_id="project-id"
resource.labels.zone:"gcp-zone1-a"
resource.labels.container_name="istio-proxy"
resource.labels.pod_id:"sleep-"

The important lines are the resource.labels.container_name="istio-proxy" to query the istio-proxy container and looking into each replica of the interested pod with resource.labels.pod_id:"sleep-".
Regarding the configMap, since GKE is a managed Kubernetes implementation, you're not supposed to change many configurations, including Fluentd. A reconciliation loop will automatically reset any changes attempted to these resources.
If you really need it, you can deploy your own unmanaged version of Fluentd when using GKE.


text:
Q: service/products for audio and video embedding What is the easiest solution that will allow me to embed audio and video on a webpage so that it will be supported by all recent browser versions (Firefox, Safari, IE) and devices (iOS, Android)? I've read a few things on stackoverflow and at other sources. Holy crap what a pain in the ass. Is there a service that will handle all the issues? I would just like to post the media files on my site or elsewhere then paste some code into a webpage. I'm willing to pay for a service (

Ideally I would like to post one file and have the service/product do whatever encoding is necessary to support compatibility.
Perhaps I am living in a fantasy world that is 5+ years in the future.

A: For video, your best bet is YouTube.  Here is a video about how to embed with it http://www.youtube.com/watch?v=ZnehCBoYLbc
For audio, try SoundCloud (soundcloud.com).  Here is how to post player links with it: http://en.support.wordpress.com/audio/soundcloud-audio-player/
Both use Flash, have specialized clients for devices, and are either currently or in the near future going to support HTML5.

A: The solution we settled on is using http://vimeo.com for video which has a cheap yearly plan that allows for private videos and has a richly customizable player that we embed.
For audio we just use html5 and allow the user to download the mp3 file if they don't have html 5


text:
Q: Unpivot multiple columns into two distinct ones without VBA I've got a dataset that has thousands of rows and multiple columns for questions and answers that expand horizontally. I would like to unpivot all the "Questions" columns into one and do the same for the corresponding "Answers" columns.
My dataset looks like this:
Header1 Header2 Q1 A1  Q2  A2
 560-19  Bill   A   A'  B   B'
 560-33  Jay    A   A'  B   B'
 560-34  Nick   A   A'  B   B'
 490-31  Julia  A   A'  B   B'
 490-32  Anna   A   A'  B   B'
 490-33  Reed   A   A'  B   B'
 900-87  Mick   A   A'  B   B'
and I want to transform it into this:
Header1 Header2 Q  A
560-19   Bill    A  A'
560-19   Bill    B  B'
560-33   Jay     A  A'
560-33   Jay     B  B'
560-34   Nick    A  A'
560-34   Nick    B  B'
490-31   Julia   A  A'
490-31   Julia   B  B'
490-32   Anna    A  A'
490-32   Anna    B  B'
490-33   Reed    A  A'
490-33   Reed    B  B'
900-87   Mick    A  A'
900-87   Mick    B  B'
I am using Excel 365.

A: To do this in Power Query (most but not all steps can be done in the UI), with your setup (and could be with multiple q/a pairs of columns) try:

*

*Select the two Header columns and then Unpivot other columns

*Add index column

*Remove Attribute column

*Transform the Index column into an Integer-Divided column (div by 2) to create a series of {0,0,1,1,2,2,...}

*Group rows by the transformed Index column into a Record this cannot be done from the UI

*Remove the Index column

*Expand the values in the grouped column and rename the new columns A and Q
Original Data

M-Code
let
    Source = Excel.CurrentWorkbook(){[Name="Table2"]}[Content],
    #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(Source, {"Header1", "Header2"}, "Attribute", "Value"),
    #"Added Index" = Table.AddIndexColumn(#"Unpivoted Other Columns", "Index", 0, 1),
    #"Removed Columns" = Table.RemoveColumns(#"Added Index",{"Attribute"}),
    #"Integer-Divided Column" = Table.TransformColumns(#"Removed Columns", {{"Index", each Number.IntegerDivide(_, 2), Int64.Type}}),
    #"Grouped Rows" = Table.Group(#"Integer-Divided Column", {"Index", "Header1","Header2"},{{"Values", each Record.FromList([Value], {"Header1","Header2"}), type record}}),
    RemIndex = Table.RemoveColumns(#"Grouped Rows",{"Index"}),
    ExpandValues = Table.ExpandRecordColumn(RemIndex,"Values",{"Header1","Header2"},{"Q","A"}),
    #"Changed Type" = Table.TransformColumnTypes(ExpandValues,{{"Header1", type text}, {"Header2", type text}, {"Q", type text}, {"A", type text}})
in
    #"Changed Type"

Results


text:
Q: turn on 12v from 2n2222a 5v source

simulate this circuit – Schematic created using CircuitLab
I am trying to be able to switch off the motor, then energize or de-energize the relay coil for a motor direction change.  I can't get this to work.  I am just a very beginner and am trying to learn.

simulate this circuit
But if I delete the two lines and put a "GND" it works.  Is GND not the negative terminal of the 12V battery?  How can I get this to work?  I would like to understand and also know what kind of diode or protection for my gpio pin would be suitable for this circuit.
Thanks

A: wire up something like this
RLY1   RLY2  MOTOR
off    off   stopped
off    on    spins one way
on     off   spins other way
on     on    stopped

simulate this circuit – Schematic created using CircuitLab


text:
Q: Finding minimum value in index(match) array [EXCEL] This is my simple table
A                           B               C
tasmania                   hobart            21
queensland                 brisbane          22
new south wales            sydney            23
northern territory         darwin            24
south australia            adelaide          25
western australia          perth             26
tasmania                   hobart            17
queensland                 brisbane          18
new south wales            sydney            19
northern territory        darwin             11
south australia           adelaide           12
western australia         perth              13

index match array formula:
=INDEX(A2:C9,MATCH(1,(H4=$A:$A)*(I4=$B:$B),0),3)

Basically A and B are my lookup criteria while C is the value I want to get. I want C to be the minimum value among the matched C value.
Ex.
If I have tasmania and hobart as my criteria, I would want to get 17 because it is the minimum value and not 21.
I tried nesting MIN inside the index match array (H4=$A:$A)*(I4=$B:$B)*(MIN($C:$C)) but it only results in errors

A: This is rather a MIN(IF... than a INDEX. Before SUMIF or COUNTIF was implemented in Excel even SUM(IF... or COUNT(IF... had to be used this way.
Since there is not a MINIFS until now, for this we must further use:
{=MIN(IF($A$1:$A$1000=H4,IF($B$1:$B$1000=I4,$C$1:$C$1000,NA())))}

This is an array formula. Input it into the cell without the curly brackets and press [Ctrl]+[Shift]+[Enter] to confirm. The curly brackets should then appear automatically.

A: With the AGGREGATE function as a standard formula,
=AGGREGATE(15, 6, C2:INDEX(C:C, MATCH(1E+99,C:C ))/((A2:INDEX(A:A, MATCH(1E+99,C:C ))=F2)*(B2:INDEX(B:B, MATCH(1E+99,C:C ))=G2)), 1)

As an older style standard formula, your original would look like,
=MIN(INDEX(C2:C13+((H4<>A2:A13)+(I4<>B2:B13))*1E+99, , ))


text:
Q: divide file into equal counts I have one .txt file which has more than 1 million record inside. (rownum from 1 to 1 million) I need to divide this file into two 500k files in linux. (file1 = rownum from 1 to 500k and file2 = rownum from 500k to 1 million).
How can I do it?

A: You are looking for the program split.
split -l 500000 file prefix


text:
Q: I want Disable Drag. When drop image to target and insert to database $(document).ready(function() {

    $(".Shops").draggable({ revert: 'invalid'});
    $('#inventory').droppable();
    $('#slot2').droppable({ accept: '.Shops'});
    $('#slot1').droppable({ accept: '.Shops'});
    $('#slot2,#slot1,#inventory').bind('drop', function(ev,ui) { itemInSpot(ui.draggable,this); });

});

I want Disable Drag. When drop image to target and insert to database


text:
Q: Is there a Ruby framework similar to the Flash Player capabilities? Is there an open source Ruby framework that allows working with multimedia (video, sound, etc) similar to Flash, including Display Object hierarchy, that is not targeted for video games?
I'm looking for something between Ruby/Processing with a more object oriented API.

A: You could take a look at Ruby-Processing that runs on jruby.


text:
Q: How to optimize OpenCL code for neighbors accessing? Edit: Proposed solutions results are added at the end of the question.
I'm starting to program with OpenCL, and I have created a naive implementation of my problem.
The theory is: I have a 3D grid of elements, where each elements has a bunch of information (around 200 bytes). Every step, every element access its neighbors information and accumulates this information to prepare to update itself. After that there is a step where each element updates itself with the information gathered before. This process is executed iteratively.
My OpenCL implementation is: I create an OpenCL buffer of 1 dimension, fill it with structs representing the elements, which have an "int neighbors 6  " where I store the index of the neighbors in the Buffer. I launch a kernel that consults the neighbors and accumulate their information into element variables not consulted in this step, and then I launch another kernel that uses this variables to update the elements. These kernels use __global variables only.
Sample code:
typedef struct{
  float4 var1;
  float4 var2;
  float4 nextStepVar1;
  int neighbors[8];
  int var3;
  int nextStepVar2;
  bool var4;
} Element;

__kernel void step1(__global Element *elements, int nelements){
  int id = get_global_id(0);
  if (id >= nelements){
    return;
  }
  Element elem = elements[id];

  for (int i=0; i < 6; ++i){
    if (elem.neighbors[i] != -1){
      //Gather information of the neighbor and accumulate it in elem.nextStepVars
    }
  }
  elements[id] = elem;
}

__kernel void step2(__global Element *elements, int nelements){
  int id = get_global_id(0);
  if (id >= nelements){
    return;
  }
  Element elem = elements[id];

  //update elem variables by using elem.nextStepVariables
  //restart elem.nextStepVariables
}

Right now, my OpenCL implementation takes basically the same time than my C++ implementation.
So, the question is: How would you (the experts :P) address this problem?
I have read about 3D images, to store the information and change the neighborhood accessing pattern by changing the NDRange to a 3D one. Also, I have read about __local memory, to first load all the neighborhood in a workgroup, synchronize with a barrier and then use them, so that accesses to memory are reduced.
Could you give me some tips to optimize a process like the one I described, and if possible, give me some snippets?
Edit: Third and fifth optimizations proposed by Huseyin Tugrul were already in the code. As mentioned here, to make structs behave properly, they need to satisfy some restrictions, so it is worth understanding that to avoid headaches.
Edit 1: Applying the seventh optimization proposed by Huseyin Tugrul performance increased from 7 fps to 60 fps. In a more general experimentation, the performance gain was about x8.
Edit 2: Applying the first optimization proposed by Huseyin Tugrul performance increased about x1.2 . I think that the real gain is higher, but hides because of another bottleneck not yet solved.
Edit 3: Applying the 8th and 9th optimizations proposed by Huseyin Tugrul didn't change performance, because of the lack of significant code taking advantage of these optimizations, worth trying in other kernels though.
Edit 4: Passing invariant arguments (such as n_elements or workgroupsize) to the kernels as #DEFINEs instead of kernel args, as mentioned here, increased performance around x1.33. As explained in the document, this is because of the aggressive optimizations that the compiler can do when knowing the variables at compile-time.
Edit 5: Applying the second optimization proposed by Huseyin Tugrul, but using 1 bit per neighbor and using bitwise operations to check if neighbor is present (so, if neighbors & 1 != 0, top neighbor is present, if neighbors & 2 != 0, bot neighbor is present, if neighbors & 4 != 0, right neighbor is present, etc), increased performance by a factor of x1.11. I think this was mostly because of the data transfer reduction, because the data movement was, and keeps being my bottleneck. Soon I will try to get rid of the dummy variables used to add padding to my structs.
Edit 6: By eliminating the structs that I was using, and creating separated buffers for each property, I eliminated the padding variables, saving space, and was able to optimize the global memory access and local memory allocation. Performance increased by a factor of x1.25, which is very good. Worth doing this, despite the programmatic complexity and unreadability.

A: According to your step1 and step2, you are not making your gpu core work hard. What is your kernel's complexity? What is your gpu usage? Did you check with monitoring programs like afterburner? Mid-range desktop gaming cards can get 10k threads each doing 10k iterations.
Since you are working with only neighbours, data size/calculation size is too big and your kernels may be bottlenecked by vram bandiwdth. Your main system ram could be as fast as your pci-e bandwidth and this could be the issue.
1) Use of Dedicated Cache could be getting you thread's actual grid cell into private registers that is fastest. Then neighbours into __local array so the comparisons/calc only done in chip.
Load current cell into __private
Load neighbours into __local
start looping for local array
get next neighbour into __private from __local
compute
end loop
(if it has many neighbours, lines after "Load neighbours into __local" can be in another loop that gets from main memory by patches)
What is your gpu? Nice it is GTX660. You should have 64kB controllable cache per compute unit. CPUs have only registers of 1kB and not addressable for array operations.
2) Shorter Indexing could be using a single byte as index of neighbour stored instead of int.  Saving precious L1 cache space from "id" fetches is important so that other threads can hit L1 cache more!
Example:
 0=neighbour from left
 1=neighbour from right
 2=neighbour from up
 3=neighbour from down
 4=neighbour from front
 5=neighbour from back
 6=neighbour from upper left
 ...
 ...

so you can just derive neighbour index from a single byte instead of 4-byte int which decreases main memory accessing for at least neighbour accessing. Your kernel will derive neighbour index from upper table using its compute power, not memory power because you would make this from core registers(__privates). If your total grid size is constant, this is very easy such as just adding 1 actual cell id, adding 256 to id or adding 256*256 to id  or so.
3) Optimum Object Size could be making your struct/cell-object size a multiple of 4 bytes. If your total object size is around 200-bytes, you can pad it or augment it with some empty bytes to make exactly 200 bytes, 220Bytes or 256 bytes.
4) Branchless Code (Edit: depends!) using less if-statements. Using if-statement makes computation much slower. Rather than checking for -1 as end of neightbour index , you can use another way . Becuase lightweight core are not as capable of heavyweight. You can use surface-buffer-cells to wrap the surface so computed-cells will have always have 6-neighbours so you get rid of  if (elem.neighbors[i] != -1) . Worth a try especially for GPU.
Just computing all neighbours are faster rather than doing if-statement. Just multiply the result change with zero when it is not a valid neighbour. How can we know that it is not a valid neighbour? By using a byte array of 6-elements per cell(parallel to neighbour id array)(invalid=0, valid=1 -->multiply the result with this)
The if-statement is inside a loop which counting for six times. Loop unrolling gives similar speed-up if the workload in the loop is relatively easy.
But, if all threads within same warp goes into same if-or-else branch, they don't lose performance. So this depends wheter your code diverges or not.
5) Data Elements Reordering you can move the int[8] element to uppermost side of struct so memory accessing may become more yielding so smaller sized elements to lower side can be read in a single read-operation.
6) Size of Workgroup trying different local workgroup size can give 2-3x performance. Starting from 16 until 512 gives different results. For example, AMD GPUs like integer multiple of 64 while NVIDIA GPUs like integer multiple of 32. INTEL does fine at 8 to anything since it can meld multiple compute units together to work on same workgroup.
7) Separation of Variables(only if you cant get rid of if-statements) Separation of comparison elements from struct. This way you dont need to load a whole struct from main memory just to compare an int or a boolean. When comparison needs, then loads the struct from main memory(if you have local mem optimization already, then you should put this operation before it so loading into local mem is only done for selected neighbours)
This optimisation makes best case(no neighbour or only one eighbour) considerably faster. Does not affect worst case(maximum neighbours case).
8a) Magic Using shifting instead of dividing by power of 2. Doing similar for modulo. Putting "f" at the end of floating literals(1.0f instead of 1.0) to avoid automatic conversion from double to float.
8b) Magic-2 -cl-mad-enable Compiler option can increase multiply+add operation speed.
9) Latency Hiding Execution configuration optimization. You need to hide memory access latency and take care of occupancy.
 Get maximum cycles of latency for instructions and global memory access.
 Then divide memory latency by instruction latency.
 Now you have the ratio of: arithmetic instruction number per memory access to hide latency.
 If you have to use N instructions to hide mem latency and you have only M  instructions in your code, then you will need N/M warps(wavefronts?) to hide latency because a thread in gpu can do arithmetics while other thread getting things from mem.

10) Mixed Type Computing After memory access is optimized, swap or move some instructions where applicable to get better occupancy, use half-type to help floating point operations where precision is not important.
11) Latency Hiding again Try your kernel code with only arithmetics(comment out all mem accesses and initiate them with 0 or sometihng you like) then try your kernel code with only memory access instructions(comment out calculations/ ifs)
Compare kernel times with original kernel time. Which is affeecting the originatl time more? Concentrate on that..
12) Lane & Bank Conflicts Correct any LDS-lane conflicts and global memory bank conflicts because same address accessings can be done in a serialed way slowing process(newer cards have broadcast ability to reduce this)
13) Using registers Try to replace any independent locals with privates since your GPU can give nearly 10TB/s throughput using registers.
14) Not Using Registers Dont use too many registers or they will spill to global memory and slow the process.
15) Minimalistic Approach for Occupation Look at local/private usage to get an idea of occupation. If you use much more local and privates then less threads can be utilized in same compute unit and leading lesser occupation. Less resource usage leads higher chance of occupation(if you have enough total threads)
16) Gather Scatter When neighbours are different particles(like an nbody NNS) from random addresses of memory, its maybe hard to apply but, gather read optimization can give 2x-3x speed on top of before optimizations (needs local memory optimization to work) so it reads in an order from memory instead of randomly and reorders as needed in the local memory to share between (scatter) to threads.
17) Divide and Conquer Just in case when buffer is too big and copied between host and device so makes gpu wait idle, then divide it in two, send them separately, start computing as soon as one arrives, send results back concurrently in the end. Even a process-level parallelism could push a gpu to its limits this way. Also L2 cache of GPU may not be enough for whole of data. Cache-tiled computing but implicitly done instead of direct usage of local memory.
18) Bandwidth from memory qualifiers. When kernel needs some extra 'read' bandwidth, you can use '__constant'(instead of __global) keyword on some parameters which are less in size and only for reading. If those parameters are too large then you can still have good streaming from '__read_only' qualifier(after the '__global' qualifier). Similary '__write_only' increases throughput but these give mostly hardware-specific performance. If it is Amd's HD5000 series, constant is good. Maybe GTX660 is faster with its cache so __read_only may become more usable(or Nvidia using cache for __constant?).
Have three parts of same buffer with one as __global __read_only, one as __constant and one as just __global (if building them doesn't penalty more than reads' benefits).
Just tested my card using AMD APP SDK examples, LDS bandwidth shows 2TB/s while constant is 5TB/s(same indexing instead of linear/random) and main memory is 120 GB/s.
Also don't forget to add restrict to kernel parameters where possible. This lets compiler do more optimizations on them(if you are not aliasing them).
19) Modern hardware transcendental functions are faster than old bit hack (like Quake-3 fast inverse square root) versions
20) Now there is Opencl 2.0 which enables spawning kernels inside kernels so you can further increase resolution in a 2d grid point and offload it to workgroup when needed (something like increasing vorticity detail on edges of a fluid dynamically)
A profiler can help for all those, but any FPS indicator can do if only single optimization is done per step.
Even if benchmarking is not for architecture-dependent code paths, you could try having a multiple of 192 number of dots per row in your compute space since your gpu has multiple of that number of cores and benchmark that if it makes gpu more occupied and have more gigafloatingpoint operations per second.
There must be still some room for optimization after all these options, but idk if it damages your card or feasible for production time of your projects. For example:
21) Lookup tables When there is 10% more memory bandwidth headroom but no compute power headroom, offload 10% of those workitems to a LUT version such that it gets precomputed values from a table. I didn't try but something like this should work:

*

*8 compute groups

*2 LUT groups

*8 compute groups

*2 LUT groups

so they are evenly distributed into "threads in-flight" and get advantage of latency hiding stuff. I'm not sure if this is a preferable way of doing science.
21) Z-order pattern For traveling neighbors increases cache hit rate. Cache hit rate saves some global memory bandwidth for other jobs so that overall performance increases. But this depends on size of cache, data layout and some other things I don't remember.
22) Asynchronous Neighbor Traversal

*

*iteration-1: Load neighbor 2 + compute neighbor 1 + store neighbor 0

*iteration-2: Load neighbor 3 + compute neighbor 2 + store neighbor 1

*iteration-3: Load neighbor 4 + compute neighbor 3 + store neighbor 2

so each body of loop doesn't have any chain of dependency and fully pipelined on GPU processing elements and OpenCL has special instructions for asynchronously loading/storing global variables using all cores of a workgroup. Check this:
https://www.khronos.org/registry/OpenCL/sdk/1.0/docs/man/xhtml/async_work_group_copy.html
Maybe you can even divide computing part into two and have one part use transcandental functions and other part use add/multiply so that add/multiply operations don't wait for a slow sqrt. If there are at least several neighbors to traveerse, this should hide some latency behind other iterations.


text:
Q: changing the format of decimal in a csv file I have a CSV file that has this format :
ffsdfff llkkfk fdflmk,000,1254489632,-1256.56,,0
jlfgdgf gfgfkl kiefnf,000,2548562325,2141.6,,262.54
dfgjklf kklfgk llfsmf,000,8654344845,25.3,8654344845,-25.25
sdfsklf dfsdfg gfdggs,000,2256352124,20,2256352124,-19

I am struggling to get this result :
ffsdfff llkkfk fdflmk,000,1254489632,-,000000000001256560,          ,+,000000000000000000
jlfgdgf gfgfkl kiefnf,000,2548562325,+,000000000002141600,          ,+,000000000000262540
dfgjklf kklfgk llfsmf,000,8654344845,+,000000000000025300,8654344845,-,000000000000025250
sdfsklf dfsdfg gfdggs,000,2256352124,+,000000000000020000,2256352124,-,000000000000019000

I am looking to separate the sign(+/-) from the decimal numbers. then changing the actual length of each decimal to 18.(The decimal part of the number has a max lenght of 3).
If the Fourth field is empty , I have to add 10 blank space to it.

A: you can try with awk
awk '
    BEGIN{OFS=FS=","}
    function abs(v) {return v < 0 ? -v : v}
    {
        $8=abs($6*1000)
        $7=($6<0 ? "-" : "+")
        $6=$5
        $5=abs($4*1000)
        $4=($4<0 ? "-" : "+")
        $8=sprintf("%018d", $8)
        $6=sprintf("%10s", $6)
        $5=sprintf("%018d", $5)
        print
    }' input.txt

you get,
ffsdfff llkkfk fdflmk,000,1254489632,-,000000000001256560,          ,+,000000000000000000
jlfgdgf gfgfkl kiefnf,000,2548562325,+,000000000002141600,          ,+,000000000000262540
dfgjklf kklfgk llfsmf,000,8654344845,+,000000000000025300,8654344845,-,000000000000025250
sdfsklf dfsdfg gfdggs,000,2256352124,+,000000000000020000,2256352124,-,000000000000019000


text:
Q: Java - Parsing Method Calls to other Class I want to outsource my Menu-Creater, so i create the Class Menuhelper.
There i have a Method named "addActionListener" who adds a Action to the MenuItems
  public static void addActionListener(JMenuItem menuItem ) //Need parsed Method
  {

    menuItem.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        //MethodeCall
      }
    });
  }

How can i parse the Method who i need ? As String ?

A: You can use callback method or java 8 lambda expression.
public static void addActionListener(JMenuItem menuItem, Callback callback) //Need parsed Method   {
   menuItem.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            callback.doAction();
        }
    });
}


text:
Q: Highlight Delphi TwwDBGrid Cell I have a program that a call center uses to guide phone agents through a script and gather information.  Column 1 ("Question") is a text block that identifies what data is to be gathered ("Name", "Phone", "Address", etc.), Column 2 ("Response") is a free form text field for entering the information.
Each row in this grid is associated with a script the agents are to read, "Thank you for calling, can I have your name please?", and the response to this would go into the "Response" column.  There are anywhere between 10-25 rows depending on who is calling and occasionally the agent will have to jump around from row to row based on how the call proceeds (i.e., the caller may not want to give all their info until they know the price of a service).
What I would like to do is highlight each cell in the "Response" column to indicate that the agent has NOT yet visited that field (and not read the script associated with that row).  Once the agent clicks on the "response" cell I want the highlighting to disappear and just have the standard background color.
Does anyone know how I would accomplish this?  I don't see a OnCellClick event that I can call to change the color of the cell.
EDIT:
I am using Delphi 2005 and I was mistaken on what I am using for the grid.  I am actually using Infopower's TwwDBGrid and there is no OnCellClick event.

A: Edit: This answer was written when the question states a TDBGrid and not a TwwDBGrid as it states now, clearly the answer is wrong for that class.

You can have a set of boolean flags to track if a particular row was visited.  On the call begining, initialize the flag set.
To track the "visited" fields, you can rely on the OnColEnter event and set the flag for that particular part of the script.
Then, rely on the OnDrawColumnCell to paint the background of each cell in the response column according to the associated VisitedFlag, highlighting the not yet visited ones.

A: TwwDBGrid supports the OnColEnter and OnCelExit events. It also has an OnRowChanged event to detect scrolling to a another record. So jachguate's answer is still valid.


text:
Q: Coming from Computer Vision (CV), what is camera.matrixWorldInverse and camera.projectionMatrix in THREE.JS? In computer vision the projection matrix contains the camera pose in camera space and the intrinsics of the camera. This will allow you to project 3D points on an image (x,y).
In THREE.js that is the projection matrix exactly ? When I print it, it is mostly a diagonal matrix.
I read that to get the projection matrix in THREE.js you have to do:
const matrix = new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse)

Is the camera.matrixWorldInverse the equivalent of a camera pose in CV and camera.projectionMatrix the equivalent of an intrinsics matrix ?
PS: in COLMAP for example the camera pose in camera space transforms a world point to camera space.


text:
Q: Java Program Output (Stacks) This is my first question here on SO.
It might be a stupid question, but so far I haven't been able to figure it out.
Consider the program Reader.java below:
   public class Reader {

      public static void main(String [ ] args) {

      Stack<String> stack = new Stack <String>();

         while (!StdIn.isEmpty ()) {

            stack.push(StdIn.readString());
         }

         while (!stack.isEmpty()) {

            StdOut.print(stack.pop() + " ");
         }
         StdOut.println();
     }
   }

Then it is given that a text file (words.txt) has the following contents:
read
cannot
I

Given that the program has compiled successfully using the files StdIn.java, StdOut.java and
Stack.java as used in the course, what output is produced by the following command line instruction?
java Reader < words.txt

The solution says that the output should be:
"I can read"

and not
"I cannot read"

Why is this?
Thanks :)

A: The correct output is what you got "I cannot read".  That should be a typo in that book.
What ever input is pushed in to the stack, will come out in reverse order during pop opertions (Not any new words)


text:
Q: Change the text size of Bokeh label annotations I'm adding label annotations to Bokeh bar chart :
labels = LabelSet(x='roomsavailable', y='area', text='roomsavailable', level='glyph',
        x_offset=-15, y_offset=-13.5, source=source, render_mode='canvas')

p.add_layout(labels)

Does anyone know if it's possible to adjust the size of the text?

A: text_font_size takes in a string value like
YOUR_FONT_SIZE = '10pt'

A: In the docs it describes the text_font_size attribute:

The text font size values for the text.

So try something like
YOUR_FONT_SIZE = 10
labels = LabelSet(x='stock',
                  y='area',
                  text='roomsavailable',
                  text_font_size=YOUR_FONT_SIZE,
                  level='glyph',
                  x_offset=-15,
                  y_offset=-13.5,
                  source=source,
                  render_mode='canvas')

A: You can also add the following code:
p.xaxis.axis_label_text_font_size = '15pt'
p.yaxis.axis_label_text_font_size = '15pt'

A: This is an extantion to the already existing answer by @MarkWeston.
Let's take a look to this minimal example below:
from bokeh.io import show
from bokeh.models import ColumnDataSource, LabelSet
from bokeh.plotting import figure

p = figure()

source = ColumnDataSource(dict(x=[x for x in range(1,8)],
                               y=[1]*7,
                               names=[str(x) for x in range(1,8)]
                              )
                         )

p = figure(x_range=(0, 8), y_range=(0, 2), plot_height=100, tools='' )

labels = LabelSet(x='x', y='y', text='names', level='overlay', text_align='center',
              x_offset=0, y_offset=-8, source=source, render_mode='canvas')
p.add_layout(labels)

p.circle(x='x', y='y', radius=0.3, alpha=0.3, source=source)

p.xgrid.visible = False
p.ygrid.visible = False
p.xaxis.visible = False
p.yaxis.visible = False

show(p)

This is the output of the example.
Now we can follow the answer by @MarkWeston and set the parameter we want beforehand.
If you create a LabelSet you can pass all parameters explained in the documentation of LabelSet.
But there is also a second way, if you want to change your settings after calling p.add_layout().
The function p.add_layout(labels) comes with a parameter called place. Valid values are left, right, above, below and the default value center. For more see also the documentation to add_layout.
For simplification let's assume that you call the add_layout() function with the default value center. Now we need to now, at which index of the list contained in p.center our LabelSet is placed.
We can get this information by running
[i for i, item in enumerate(p.center) if isinstance(item, LabelSet)]
>>> [2]

which will return "2". Note that at 0 and 1 there are the invisible grids.
Now we can change our parameter settings of this LabelSet calling lines like
p.center[2].text_color = {'value':'#0000ff'}
p.center[2].text_size = {'value':'11pt'}
p.center[2].text_size = 'TimesNewRoman'

and many more.
If you plot the figure again with show(p) you can see the changes and it looks like
this.


text:
Q: phpinfo() not updating to terminal version? My phpinfo() shows the version to be 7.1.23. But when I execute php -v on terminal, it shows the version to be 7.3.10. How do I get the phpinfo version to be the same as the CLI/terminal? I followed the steps by user corretge on this question:
different result between phpinfo.php and php-v
which I assumed would resolve the issue, but it didn't. I also added these lines to my httpd.conf file:
LoadModule php7_module /usr/local/opt/php71/libexec/apache2/libphp7.so
<FilesMatch .php$>
    SetHandler application/x-httpd-php
</FilesMatch>

I added all the above code right below the last LoadModule (etc etc etc) text. The location of my httpd.conf is:
/etc/apache2/httpd.conf

So doing all that for whatever reason did not work. I installed via Curl at first, it didn't update the phpinfo version, and did the same just now via Homebrew, and same - no updated result.
I am using macOS High Sierra 10.13.6
When I run this command:
/usr/local/bin/php -v

the result is:
PHP 7.3.10

When I run this command:
/usr/bin/php -v

the result is:
PHP 7.1.23

A: Try to see what program your /usr/bin/php and /usr/local/bin/php are actually calling:
ll /usr/bin/php
ll /usr/local/bin/php

Very likely, just like @Always Sunny said, you will find out that you have two versions of the PHP installed on your machine. In other words, these links are calling different executables.

A:
LoadModule php7_module /usr/local/opt/php71/libexec/apache2/libphp7.so
<FilesMatch .php$>
    SetHandler application/x-httpd-php
</FilesMatch>

Your LoadModule directive in httpd.conf file points to php71 path. You may want to change that to php73 path. Also, set the handler properly:
SetHandler application/x-httpd-php73

If you just had one php version, then x-httpd-php would work.
Restart apache to ensure new configurations are loaded.
You may also need to do additional setup mentioned below. I am not sure if that's necessary, but you may give it a try.
If you want to force web request to specific PHP version, you have 2 options:
1. php.ini modifications
In your php_info() output, you would see loaded configuration file - php.ini path. Go to that path and add the
AddHandler application/x-httpd-php73 .php

2. Add the following directives in the .htaccess file of your website.
To switch to PHP 7.3
AddHandler application/x-httpd-php73 .php

To switch to PHP 7.1
AddHandler application/x-httpd-php71 .php

Details
PHP lets you load multiple php.ini files with a provision to override them in particular folder.
When you run the PHP script with phpinfo(), it would load the nearest php.ini to that file. It may be the root level or any other php.ini that is present in the folder hierarchy above.
Whereas when you run from terminal, it would run PHP from the path that is registered in your environment variable. When you run from terminal, I doubt apache configuration would come into the picture, so changing anything in apache configuration won't have an effect on terminal execution. The Apache PHP module and the PHP command line binary are two different things that don't interfere with each other.

If you want to force your terminal to use the version that you want, there are two options
1. Change the environment variable to run PHP in a specific version
printenv PATH

This would have a path to your PHP. Remove that and put new one by
export PATH=/usr/local/php73/bin:$PATH

2. Change the PHP alias
You can also use an alias instead. Add the following to your .bash_profile file.
alias php='/usr/local/php73/bin/php'

This works the same as the export PATH when added to your .bash_profile.


text:
Q: Content Item with users and items in Orchard CMS I'm considering using Orchard CMS (1.5) as a backbone of my next application. What I will try to achieve is to create an Content Item called 'Account' that will represent a business account.
The challenge is that each account - content item will need to:

*

*manage their own users

*users can have parents - managers

*have content items which are accessible only by users associated with that account

I couldn't find any projects out there that would implement such structure so I wondered if anyone here knows about anything like that or maybe articles that would help me get started. I understand that in 1.5 content item permissions are available but I have no idea how to start with points (1) and (2)

A: I don't think an Account fits under the notion of a Content Item. What I would suggest is to develop your own module. Perhaps you can have a look at http://gallery.orchardproject.net/List/Modules/Orchard.Module.Contrib.Profile. This modules was developed on top of the Orchard.Users module that ships with Orchard. You can see how it makes use of Orchard.Users to provide more features. :)

A: If you're building application with this level of complexity, you should definitely look at skywalker's web shop series. It currently has 11 parts, starting from here.
I presume that the most interesting parts for you would be parts 8 (Registering new Customer to the site), 9 (Creating Orders and Communicating with the PSP) and 10 (Managing the Customers and Orders from the backend) where there are plenty examples of using Orchard architecture against your own, creating complex parent-child relationships (for example a Customer can have many Orders, while every Order can have multiple Order Items, and each Order Item consists of a Product or Bundles of Products) and handling them through administration by building your own admin menus with multiple tabs.
This series helped me a lot when I was building some of my own complex applications and I believe it would help you too if you're still considering Orchard for application development..


text:
Q: При вызове функции fsync() из библиотеки aiofile возникает ошибка SystemError(22, "invalid argument") Открыл файл с помощью aiofile, записал данные, но при вызове fsync() скрипт падает. Версия интерпретатора последняя, собирал сам, так как нужна была новая версия, а ее нету в старых реаозиториях убунту в 16 версии.
async def load_file(self):
    response = await self.session.get(url=self.url)
    ret = False
    file = await aiofile.AIOFile(self.file_name, mode='wb')
    if response.status == 200:
        data = await response.read()
        ret = True
        await file.write(data)
        try:
            await file.close()
        except SystemError:
            pass
    return ret

Сессия создана, в функции close вызывается fsync при записи

A: from aiofile import AIOFile

async def load_file(self):
    response = await self.session.get(url=self.url)
    ret = False
    if response.status == 200:
        data = await response.read()
        ret = True
        async with AIOFile("/tmp/hello.txt", 'wb') as afp:
            await afp.write(data)
            await afp.fsync()

    return ret


text:
Q: Does TRUNCATE TABLE grows up transaction log? I have read that one of the differences between DELETE and TRUNCATE TABLE in Sql is the TRUNCATE operation cannot be rolled back and no triggers will be fired  (as written in this site for example) :
QUESTION:
Does this mean that when I TRUNcATE TABLE that is containing millions of records, I should not be effecting the transaction log file -that is transaction log file should not grow up in the time of truncating-, am I correct?

A: In MS SQL Server (Books Online)

Compared to the DELETE statement, TRUNCATE TABLE has the following advantages:

*

*Less transaction log space is used.
The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction log.

*Fewer locks are typically used.
When the DELETE statement is executed using a row lock, each row in the table is locked for deletion. TRUNCATE TABLE always locks the table (including a schema (SCH-M) lock) and page but not each row.

*Without exception, zero pages are left in the table.
After a DELETE statement is executed, the table can still contain empty pages. For example, empty pages in a heap cannot be deallocated without at least an exclusive (LCK_M_X) table lock. If the delete operation does not use a table lock, the table (heap) will contain many empty pages. For indexes, the delete operation can leave empty pages behind, although these pages will be deallocated quickly by a background cleanup process.
TRUNCATE TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes, and so on remain. To remove the table definition in addition to its data, use the DROP TABLE statement.
If the table contains an identity column, the counter for that column is reset to the seed value defined for the column. If no seed was defined, the default value 1 is used. To retain the identity counter, use DELETE instead.

From: http://msdn.microsoft.com/en-us/library/ms177570.aspx
To the original question:
Technically TRUNCATE is deallocating the data pages from the table, effectively removing all records from it. This action in theory can be rolled back until none of the data pages are being re-used. The information on the deallocated pages are not removed, they are still available in the data file. These deallocated pages in the data file can be re-used (allocated to another table for example) and the data on them can be overwritten.
The transaction log contains the list of pages (in SQL Server) being deallocated from the table during TRUNCATE, but this list is much shorter than the list of all records, therefore the transaction log will not grow to the same extent.
Depending on the implementation of transactions and TRUNCATE on different RDBMS it can be possible to do a rollback within a transaction. Sometimes it is possible to do a 'rollback' (restore the table) after the transaction is committed, if the data on the pages are still intact and all information is available, but that is some black magic and usually not supported directly by the RDBMS.

A:
Does this mean that when I TRUNcATE TABLE that is containing millions of records, I should not be effecting the transaction log file -that is transaction log file should not grow up in the time of truncating-, am I correct?

Well you don't specify that actual server software but in all cases that I'm aware of that's correct.
DELETE effectively works row-by-row, deleting the record, firing any appropriate triggers, and adding a transaction to the log.
TRUNCATE just removes all of the data in one swoop, not significantly affecting the transaction log (certainly not enough to allow a rollback) and not executing triggers.


text:
Q: Net surgery: How to reshape a convolution layer of a caffemodel file in caffe? I'm trying to reshape the size of a convolution layer of a caffemodel (This is a follow-up question to this question). Although there is a tutorial on how to do net surgery, it only shows how to copy weight parameters from one caffemodel to another of the same size.
Instead I need to add a new channel (all 0) to my convolution filter such that it changes its size from currently (64x3x3x3) to (64x4x3x3).
Say the convolution layer is called 'conv1'. This is what I tried so far:
# Load the original network and extract the fully connected layers' parameters.
net = caffe.Net('../models/train.prototxt',
                '../models/train.caffemodel',
                caffe.TRAIN)

Now I can perform this:
net.blobs['conv1'].reshape(64,4,3,3);
net.save('myNewTrainModel.caffemodel');

But the saved model seems not to have changed. I've read that the actual weights of the convolution are stored rather in net.params['conv1'][0].data than in net.blobs but I can't figure out how to reshape the net.params object. Does anyone have an idea?

A: As you well noted, net.blobs does not store the learned parameters/weights, but rather stores the result of applying the filters/activations on the net's input. The learned weights are stored in net.params. (see this for more details).
AFAIK, you cannot directly reshape net.params and add a channel.
What you can do, is have two nets deploy_trained_net_with_3ch.prototxt and deploy_empty_net_with_4ch.prototxt. The two files can be almost identical apart from the input shape definition and the first layer's name.
Then you can load both nets to python and copy the relevant part:
net3ch = caffe.Net('deploy_trained_net_with_3ch.prototxt', 'train.caffemodel', caffe.TEST)
net4ch = caffe.Net('deploy_empty_net_with_4ch.prototxt', 'train.caffemodel', caffe.TEST)

since all layer names are identical (apart from conv1) net4ch.params will have the weights of train.caffemodel. As for the first layer, you can now manually copy the relevant part:
net4ch.params['conv1_4ch'][0].data[:,:3,:,:] = net3ch.params['conv1'][0].data[...]

and finally:
net4ch.save('myNewTrainModel.caffemodel')


text:
Q: How to add dynamic texfield while clicking a checkbox? I need to create textfield dynamically when I click checkbox in table. In table I have around 500 data. Each data has check box and user can search and select parameters. As below image, If user click Testing 1 checkbox from table, Same Testing1 value should present in Parameter name text field.
If the user selects Testing 2 checkbox, dynamically Textfield needs be added and Testing 2 value should be present in created textfield. If user uncheck checkbox, textfield has to be removed from table. I have attached snapshot for reference.

Below code for TextField which resides in table.

            Parameter Name
            Data Type
            Expected Set Value

              <input type="text" id="parameterName" class="parameterName" name="parameter_name">

              <input type="text" class="parameterDscription" name="parameter_description">

              <input type="text" class="expectedValue" name="expected_value">

A: You can do it like this:

$("#paramTable input[type='checkbox']").on("click", function() {
  if ($(this).is(":checked")) {
    let name = $(this).parent("td").next("td").text();
    let newname = name.replace(" ", "_");
    let newrow = $("
");
    let newcell = $("");
    let newinput = $("<input type='text' class='parameterName' name='" + newname + "' id='" + newname + "' value='" + name + "'/>");
    newcell.append(newinput);
    newrow.append(newcell);
    let newcells = $("<input type='text' class='parameterDscription' name='parameter_description'>	<input type='text' class='expectedValue' name='expected_value'>	")
    newrow.append(newcells);
    $("tbody.parameter_table").append(newrow);
  } else {
    let name = $(this).parent("td").next("td").text();
    let newname = name.replace(" ", "_");
    $("#addParamTable").find("#" + newname).closest("tr").remove();
  }
})

  <input type="checkbox"/>
  Testing 1
  1, 4, 6, 5, 9

  <input type="checkbox"/>
  Testing 2
  1, 4, 3, 5

            Parameter Name
            Data Type
            Expected Set Value

              <input type="text" id="parameterName" class="parameterName" name="parameter_name">

              <input type="text" class="parameterDscription" name="parameter_description">

              <input type="text" class="expectedValue" name="expected_value">


text:
Q: How to prove the disease rate in conditional probability recently I am confused by a question.
Suppose screening test A has been used to detect disease D. Based on historical performance, it's known that 21% of patients who are A positive will have disease D, while 99% of patients who are A negative will NOT have disease D. It is known that 20% of the population are detected to be A positive.
I would like to show that the rate of disease D in the population is 5.00%.
P(Disease D | A positive) = 21%
P(No Disease D | A negative) = 99%
P(A positive) = 20%
P(Disease D | A positive) = P(A positive | Disease D) * P( Disease D) / P( A positive)
However, P(A positive | Disease D) is unknown, how can I prove this question?
Thank you very much

A: We have that by LOTP
$$P(D)=P(D|A^+)P(A^+)+P(D|A^-)P(A^-)=0.21\cdot 0.20+0.01\cdot 0.80=0.05$$


text:
Q: Odoo - How to find menu "action" name I would like to add "Products" directly to the top menu (without having to click on Inventory -> Products)
I have tried this:
<menuitem name= "Articles" id="product.menu_products_top_menu" action="product.product_normal_action_sell" sequence="4"/>

But "product.product_normal_action_sell" send me to "Products Variants" page which is not exactly what I want..
Where to find out the action name ?

A: We can find the action name of a specific page by going to this page. On the Debug Mode -> Edit Action.
On the top we have "External ID" (which is corresponding to the action name) In my case: "product.product_template_action_product"


text:
Q: Can I use /free without an /end-free in rpgleref source? I am writing a set of programs that create, write and compile a set of SQLRPGLE programs. A lot of the code at the beginning of my program is repeated in every program I have, so it makes sense for me to put this into a reference source ... it is roughly of the form
    H some h specs
    D a load of d specs

    /free
       my nice free formatted code that I use everywhere

Then my metaprogram comes along and adds lots of code. At this point my program looks like this
    /copy *libl/qrpgleref,myRefPgm

      lots of nice rpg and sql

    /end-free

When I compile this it doesn't work - I think this is because the program can't match up the /free and /end-free properly ... is that right? Or am I missing something more subtle here?
Cheers

A: I think the reason your program isn't compiling, based only on the samples provided in your question, is because you have H and D specs mixed in with your free format calc specs.  Order is important with RPG and you can't mess with that.  If your copied code requires D and H specs, then you have two options:

*

*Create a separate /copy source member for the H, D, and C (free format) specs.  Then /copy them into your RPG program in the right places.

*Create a *MODULE or *SRVPGM and then copy only the D specs for the prototype into your RPG program.  Based only on what you posed in your question, I think the best solution is to create a service program.  To make it easier to bind a service program to an RPG program, I like to create a binding directory and then place an H spec in my RPG program: H BNDDIR(library/bnddir).  That way, I can still compile with a normal 14 in PDM.

A: I think you can, but why not add the /free and /end-free anyway just in case there is confusion or problems in the future?

A: Per the IBM ILE RPGLE Language Reference (SC09-2508-08)

Any statements that are included by a /COPY or /INCLUDE directive are
  considered fixed syntax calculations. Any free-form statements in a /COPY
  member must be delimited by the /FREE and /END-FREE directives.

Also note:

The free-form calculation block ends when you specify
  /END-FREE.

My recommendation is avoid /copybooks as much as possible.


text:
Q: How to assign different row's value to new column I'm trying to add a column, 'C_End', to a DataFrame in Pandas that looks something like this:
df = pd.DataFrame({'ID':[123,123,123,456,456,789],
                   'C_ID':[8,10,35,36,40,7],
                   'C_Type':['New','Renew','Renew','New','Term','New'],
                   'Rank':[1,2,3,1,2,1]})

The new column needs to be the next 'C_Type' for each ID based on 'Rank', resulting in a DataFrame that looks like this:
    ID  C_ID C_Type Rank  C_End
0  123     8    New    1  Renew
1  123    10  Renew    2  Renew
2  123    35  Renew    3   None
3  456    36    New    1   Term
4  456    40   Term    2   None
5  789     7    New    1   None

Essentially, I want to find the row where ID = ID and Rank = Rank+1 and assign C_Type to new column C_End. I've tried creating a function and using Apply (below), but that took forever and eventually gave me an error. I'm still new to Pandas and Python in general, but I feel like there has to be an easy solution that I'm not seeing.
def get_next_c_type(row):
    return df.loc[(df['id'] == row['id']) & (df['rank'] == row['rank'] + 1),'c_type']

df['c_end'] = df.apply(get_next_c_type, axis = 1)

A: Try:
df['C_End'] = df.sort_values('Rank').groupby('ID')['C_Type'].transform('shift',-1)

Or as @W-B suggest:
df['C_End'] = df.sort_values('Rank').groupby('ID')['C_Type'].shift(-1)

Output:
    ID  C_ID C_Type  Rank  C_End
0  123     8    New     1  Renew
1  123    10  Renew     2  Renew
2  123    35  Renew     3    NaN
3  456    36    New     1   Term
4  456    40   Term     2    NaN
5  789     7    New     1    NaN

A: Here's one way using np.where:
dfs = df.shift(-1)
m1 = df.ID == dfs.ID
m2 = df.Rank + 1 == dfs.Rank
df.loc[:, 'C_End'] = np.where(m1 & m2, dfs.C_Type, None)

   ID    C_ID C_Type  Rank C_End
0  123     8    New     1  Renew
1  123    10  Renew     2  Renew
2  123    35  Renew     3   None
3  456    36    New     1   Term
4  456    40   Term     2   None
5  789     7    New     1   None


text:
Q: PyQt5 tray program closes after QDialog executing from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QGridLayout, QWidget, QCheckBox, QSystemTrayIcon, \
    QSpacerItem, QSizePolicy, QMenu, QAction, QStyle, qApp, QPushButton
from PyQt5.QtCore import QSize
from PyQt5 import QtWidgets

class MainWindow(QMainWindow):
    check_box = None
    tray_icon = None

    def __init__(self):

        QMainWindow.__init__(self)

        self.setMinimumSize(QSize(480, 80))
        self.setWindowTitle("System Tray Application")
        central_widget = QWidget(self)
        self.setCentralWidget(central_widget)

        grid_layout = QGridLayout(self)
        central_widget.setLayout(grid_layout)
        grid_layout.addWidget(QLabel("Application, which can minimize to Tray", self), 0, 0)

        self.check_box = QCheckBox('Minimize to Tray')
        grid_layout.addWidget(self.check_box, 1, 0)
        grid_layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding), 2, 0)

        self.btn = QPushButton('Dialog', self)
        grid_layout.addWidget(self.btn, 1, 1)
        self.btn.clicked.connect(self.dial_func)

        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setIcon(self.style().standardIcon(QStyle.SP_ComputerIcon))

        show_action = QAction("Show", self)
        quit_action = QAction("Exit", self)
        hide_action = QAction("Hide", self)
        dial = QAction('Dial', self)
        dial.triggered.connect(self.dial_func)
        show_action.triggered.connect(self.show)
        hide_action.triggered.connect(self.hide)
        quit_action.triggered.connect(qApp.quit)

        tray_menu = QMenu()
        tray_menu.addAction(show_action)
        tray_menu.addAction(hide_action)
        tray_menu.addAction(dial)
        tray_menu.addAction(quit_action)
        self.tray_icon.setContextMenu(tray_menu)
        self.tray_icon.show()

    def closeEvent(self, event):
        if self.check_box.isChecked():
            event.ignore()
            self.hide()
            self.tray_icon.showMessage(
                "Tray Program",
                "Application was minimized to Tray",
                QSystemTrayIcon.Information,
                2000
            )

    def dial_func(self):
        text, ok = QtWidgets.QInputDialog.getText(self, 'Input dialog', 'Enter your name')

        if ok:
            print('simple text', text)

if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    mw = MainWindow()
    mw.show()
    sys.exit(app.exec())

I am trying to write little application for diagnostic. Application should work in tray and have options to change settings from QDialog.
With this code, I can run dialog from btn (in main window) and from Dial (from QMenu). And if program not in tray, everything works fine, but if it's in tray, program finishes. What's way to solve this problem?

A: I think you need to call the show function when calling the dialog window.
def dial_func(self):
    self.show()
    text, ok = QtWidgets.QInputDialog.getText(
        self, 'Input dialog', 'Enter your name')

    if ok:
        print('simple text', text)

This solution will solve your issue.


text:
Q: More info on Array click, show option 1 on array by default I have a method which shows a div with 3 locations. When I click a location (for e.g, Scotland) in the other div, it shows information for Scotland, then when I click Europe, it switches to Europe e.t.c.
On the Div which displays more info, can I make a location appear by default on page load? I want Europe to display by default.

Visit {{location.name}}

{{location.desc}}

const app = new Vue({
    el: '#test',
    data: {
        moreinfo: false,
        locations: [
            {
                name: "Europe",
                desc: "Phasellus non pulvinar elit. Etiam id fringilla eros. Mauris mi odio, fringilla eget tempus eu, vehicula nec neque.",
                img: "img/europe.jpg",

                moreinfo: [
                    {
                        desc: "Euro desc",
                    header: "Welcome to Europe"
                    }
                ]
            },
            {
                name: "America",
                desc: "Curabitur vel lacus ipsum. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris ex ante, scelerisque vitae semper ut",
                img: "https://images.fineartamerica.com/images-medium-large-5/14-american-flag-les-cunliffe.jpg",
               moreinfo: [
                    {desc: "America desc",
                    header: "Welcome to America"}
                ]
            },
            {
                name: "Scotland",
                desc: "Phasellus non pulvinar elit. Etiam id fringilla eros. Mauris mi odio, fringilla eget tempus eu, vehicula nec neque.",
                img: "https://images-na.ssl-images-amazon.com/images/I/41VvuLQ7UhL.jpg",
                moreinfo: [
                    {desc: "Scotland desc",
                    header: "Welcome to Scotland"}
                ]
            },

        ],
        selected: location[1],
    },
    methods:{
        moreinfo2(location) {
        this.selected = location;
        },
    }
})


text:
Q: Working with 2 tables PHP & MySQL I am working on a webpage that displays list of shops. I have 2 tables, shops and shops_sched.
+-shops-+
| id | title |

+-------------shops_sched-------------+
| id | shops_id | start_date | end_date |

Basically, the program displays the list of shops from the shops table, but if a value from shops.id is found @ shops_sched.shops_id the page must output shops.title + 'coming soon'.
I understand this will be easy if I just place the date fields inside the table shops but due to programming restrictions I can't. I'm working on an existing project and I'm trying to minimize changes to existing functions. I can create new PHP functions if necessary though.
In addition, I need to get all the entries from the shops table. The Program needs to return all shops.title but for those shops whose id is found @ shops_sched.shops_id, the program will have to return shops.title + "Coming Soon".

A: Join the two tables :
SELECT shops.title
FROM shops INNER JOIN shops_sched ON shops.id = shops_sched.shops_id

The query should return only the the shops inside shops_sched
EDIT :
If I understood your question, try this :
SELECT shops.title, shops_sched.id
FROM shops LEFT JOIN shops_sched ON shops.id = shops_sched.shops_id

This will return all the titles, and the shops_sched.shops_id if shops.id = shops_sched.shops_id. In the other case, the hops_sched.shops_id will be null
Then you fetch the rows and if the second row is not null, print title + coming soon
Sample code : (Something like this)
$query = "SELECT `title`, 'shops_id' FROM `shops` LEFT JOIN `shops_sched` ON `shops`.`id`     = `shops_sched`.`shops_id` WHERE `shops_sched`.`shop_id`";

$result = mysql_query($query);

while($row = mysql_fetch_array($result) {
    if($row['shops_id'] != "")
    {
         echo $row['title'] . ' coming soon';
    }
    else
    {
         echo $row['title'];
    }
}

A:
must output shops.title + 'coming soon'.

So do it like this:
$shops.title = "Donut-John";
echo $shops.title." coming soon";

A: To join the shops and shops_sched table
$query = SELECT `title` FROM `shops` JOIN `shops_sched` ON `shops`.`id` = `shops_sched`.`shops_id` WHERE `shops_sched`.`shop_id` = 5;

$result = mysql_query($query);

while($row = mysql_fetch_array($result) {
    echo $row['title'] . 'coming soon';
}

For more about join you also can refer the following link
https://dev.mysql.com/doc/refman/5.0/en/join.html
http://www.tutorialspoint.com/mysql/mysql-using-joins.htm


text:
Q: Magento 2 on login getting message This website is excluded from customer's group I have created one group from admin then assign that group to the specific customer. Now whenever I am trying to log in with that customer getting message "This website is excluded from customer's group.".
I have found this exception is throwing from the observer vendor/magento/module-customer/Observer/CustomerGroupAuthenticate.php. And my group entry is in the database table customer_group_excluded_website
Can you please tell me is there any configuration in magento admin from where we can add specific groups into this table customer_group_excluded_website ?
Thank You!
Abbas

A: If you go to

Admin Panel -> Customers -> Customer Groups -> [ Select your customer
related group ] -> Excluded Website(s)

Make sure the website from where you are trying to login with this customer group should not be selected in Excluded Website(s)
I hope if will helpful for anyone else. :)


text:
Q: Nest could not find GraphQLModule element I'm trying to write the e2e test for my backend app (nestjs, grpahql, mongodb).
This is my test:
import { INestApplication } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { Test, TestingModule } from '@nestjs/testing';
import {
    ApolloServerTestClient,
    createTestClient,
} from 'apollo-server-testing';
import gql from 'graphql-tag';
import { UserModule } from '../src/user/user.module';
import { MongooseModule } from '@nestjs/mongoose';
import config from '../src/environments/environment';

describe('User', () => {
    let app: INestApplication;
    let apolloClient: ApolloServerTestClient;

    beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
        imports: [UserModule, MongooseModule.forRoot(config.mongoURI)],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();

    const module: GraphQLModule = moduleFixture.get<GraphQLModule>(
        GraphQLModule,
    );
    apolloClient = createTestClient((module as any).apolloServer);
    });

    it('should get users', async () => {
    const { query } = apolloClient;
    const result: any = await query({
        query: gql`
        query {
            getUsers {
            _id
            name
            }
        }
        `,
        variables: {},
    });
    console.log(result);
    });
});

I face this error:

Nest could not find GraphQLModule element (this provider does not exist in the current context)

Could someone share a working example or point me what is wrong?

A: It looks like GraphQLModule is not imported in the scope of your TestModule. If so, the context will never be able to provide it using get().
Also, this might not help you but this is what we do in our projects:
  beforeAll(async () => {
    const TCP_PORT = 4242;
    const testingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    gqlClient = new ApolloClient({
      uri: `http://localhost:${TCP_PORT}/graphql`,
      fetch: fetch as any,
      cache: new InMemoryCache({
        addTypename: false,
      }),
    });

    app = testingModule.createNestApplication();
    await app.listen(TCP_PORT);
  });

I did not add all the imports but here are the most relevant:
import ApolloClient, { gql, InMemoryCache } from 'apollo-boost';
import fetch from 'node-fetch';

I assume you know the other ones and/or don't need them


text:
Q: Extract description from EXIF data and exclude duplicate text I'm working on an image gallery with portraits where I extract text from Exif data. When I edit the images I am writing the names of the people which I later show in my image gallery as captions.
I would like to make a list, but can't figure out how to make it into an array from which I can exclude duplicates with array_unique().
My code is:
$imgdir = 'images/'; //pick your folder ie.: 'images/'
$current_folder = basename(dirname(__FILE__));
$allowed_types = array('png','jpg','jpeg','gif');

$dimg = opendir($imgdir);
while($imgfile = readdir($dimg)){
    if(in_array(strtolower(substr($imgfile,-3)),$allowed_types)){
        $a_img[] = $imgfile;
        sort($a_img);
        reset ($a_img);
    }
}
$totimg = count($a_img);

?><!DOCTYPE html>
<html>
<head>
    <title>Names listing</title>
</head>
<body>
<?php
for ($x=0; $x < $totimg; $x++){
    if ($x == ($totimg-1))
        $_content = (exif_read_data('images/'.$a_img[$x])[ImageDescription]).'';
    else
        $_content = (exif_read_data('images/'.$a_img[$x])[ImageDescription]).', ';
    $_unique = $_content;
    echo $_unique;
}
?>
</body>
</html>

If I have multiple images with the same person I get a list like:
John, John, Jane, Jane, Jane, ... etc.

What I would like is:
John, Jane, ... etc.

Thanks in advance.

A: You should store all of the ImageDescription values in a temporary array (e.g. $descriptions), then after the loop finishes call array_unique() on the temporary array to remove duplicates, then you can optionally alphabetize the values, and finally convert the remaining values to a string using implode() with [comma and space] delimiting the values.
for($x=0; $x<$totimg; ++$x){
    $descriptions[]=exif_read_data('images/'.$a_img[$x])[ImageDescription];
}
$descriptions=array_unique($descriptions);       // remove duplicates before sorting
sort($descriptions);                             // sort alphabetically
echo implode(', ',$descriptions);                // display csv


text:
Q: MariaDB create user using hostname I created the following user, within the mariaDB USER table.
MariaDB [(none)]> CREATE USER 'dbadmin'@'example.ddns.net' IDENTIFIED BY 'Password_Here';
MariaDB [(none)]> GRANT ALL ON databaseName.* TO 'dbadmin'@'example.ddns.net';
MariaDB [(none)]> FLUSH PRIVILEGES;

I then performed a host lookup on the server (running the mariaDB).
$ host engelsen.ddns.net
example.ddns.net has address 12.34.56.78

However, when I attempt to connect to the mySQL database (from the remote client), I get the following error message:
ERROR 1130 (HY000): Host '12.34.56.78' is not allowed to connect to this MariaDB server.

Is there a reason why mariaDB (appears to be) incapable of performing a hostname lookup? Or is there a different reason why the access request is being rejected? Thanks!


text:
Q: String turned to Object when passed from client to nodeJS I'm using yeoman angular-fullstack to generate my project.
So the client is angularJs (typeScript) and the backend is nodeJs.
The problem is I got a variable and when I print it to the console, I get a very long string, (if u need to know its a photo_reference from googleplacesapi).
And when I pass it to the with a http.get to the nodeJS api, and print it to the log I get the response Object object.
MainController
    for (var photo of response.data.result.photos) {
      this.getImages(photo);
      console.log(photo.photo_reference);
    }
  getImages(photo_reference: string): void{
    this.$http.get('/api/image/' + photo_reference).then((response) => {

    });
  }

NodeJs
export function show(req, res) {

    console.log("photoreference:" + req.params.photoreference);

A: console.log will invoke .toString() in any objects you pass to it. The default implementation of toString(), for plain Objects, is to return "[Object object]", which is stupid but also happily generic.
If you want to see the full structure of the object, stringify it:
console.log(JSON.stringify(req.params.photoreference));

You can ask JSON.stringify to render a human-readable version, using 2 spaces for indentation:
console.log(JSON.stringify(req.params.photoreference, null, 2))

A: You are passing the wrong value to the getImages function.
since the argument passed to getImages has a photo_reference property it is an object so the logging is correct
pass the photo.photo_reference to the function
for (var photo of response.data.result.photos) {
    this.getImages(photo.photo_reference);
}


text:
Q: Games from gamejolt.com aren't permitted to run Whenever I run a game from http://gamejolt.com, Java prevents me from playing it.
It tells me Java doesn't allow applets without an approved certificate.  From what I understand, GameJolt's games are self-signed, meaning the creators signed their own games.
Downloading the game seems to fix it sometimes. Adding GameJolt to Java's security exceptions didn't work either.
Why won't Java let the applet run? What can I do to fix this?
I'm using Chrome on Windows 7.

A: Chrome has dropped support for NPAPI plugins (Unity, Java, Silverlight self signed certs effected).
You can re-enable NPAPI (but as of Sept 15 this will no longer work) :
Enabling NPAPI in Chrome Version 42 and later
As of Chrome Version 42, an additional configuration step is required to continue using NPAPI plugins.
In your URL bar, enter:

*

*chrome://flags/#enable-npapi

*Click the Enable link for the Enable NPAPI configuration option.

*Click the Relaunch button that now appears at the bottom of the configuration page.

This is only effecting Chrome so another way around it is to just logon to the site with Firefox, iExplorer etc.
More info here


text:
Q: convert an eclipse project to Makefile based project I have an existing eclipse project, currently with no nature. I have written a Makefile for it, and want to use it. I have tried to do project/configure, and expected to see a "convert to Makefile project" there, but there is not suchthing. I also tried to add a builder in project/properties/builder, but there is no Makefile builder there.
I suspect I have to install some plugin what is missing, but cannot figure out which. I have tried to add several c/c++ related ones (the project is actually xslt based, not c or c++), but it seems I could not find the right one.
What should I install and/or do to convert my project to Makefile based?
update:
I have the following c++ related packages installed:
C/C++ Autotools support 8.8.0.201509131935  org.eclipse.cdt.autotools.feature.group Eclipse CDT
C/C++ Development Tools 8.8.0.201509131935  org.eclipse.cdt.feature.group   Eclipse CDT
  C/C++ Common GDB Support  8.8.0.201509131935  org.eclipse.cdt.gdb.feature.group   Eclipse CDT
  C/C++ Development Platform    8.8.0.201509131935  org.eclipse.cdt.platform.feature.group  Eclipse CDT
  C/C++ DSF GDB Debugger Integration    8.8.0.201509131935  org.eclipse.cdt.gnu.dsf.feature.group   Eclipse CDT
  C/C++ GNU Toolchain Build Support 8.8.0.201509131935  org.eclipse.cdt.gnu.build.feature.group Eclipse CDT
  C/C++ GNU Toolchain Debug Support 8.8.0.201509131935  org.eclipse.cdt.gnu.debug.feature.group Eclipse CDT

A workaround would be to run make as an external tool. But I am looking for the correct solution.


text:
Q: Why is zero-point energy idolized as a good source of energy? I've really only seen it in like liquid helium and I don't understand how it can hold the potential portrayed in the incredible movie by the main villian

A: It can't.  The Incredibles, being an animated film about a family of superhumans, is not the best place to look for actual physics.