text:
Q: CSS Style Individual I have a ccs sheet with the usual tags
    a. {}
    a.hover {}

I also have a div=id "footer" that I want to change the font style but the global a. and a.hover are overriding it even when I add a
#footer{
    color: #333333
}

Can I override using this or do I need to try? a.#footer or a.hover:#footer
Basically the #footer as is wont work because of the a. mentioned above even though the other elements are working in the #footer div such as margin...just the font color and hover??
Can someone tell me how to style this and not let the global a. interfere with it?
Many thanks

A: It's all about the hierarchy of code:
HTML:

    Sample link

        Footer link

CSS:
a {
    color: #ebebeb;
}

a:hover {
    color: #000;
}

#footer a {
    color: #3e3e3e;
}

#footer a:hover {
    color: #609;
}

A: Try this piece of code
#footer a,
#footer a:hover{
 color:#333;
}

A: what is dot after a ?
the correct form is a {} , a:hover {} , a#footer and a:hover #footer

A: If you are nesting a inside div element you need to use
#footer a {
    color: #333333;
}

If you only use #footer {} it will apply the styles to div and a won't inherit the color, so you can also write
#footer {
   color: #f00;
}

#footer a {
   color: inherit;
}

A: This is a matter of specificity. Styling the  elements directly is more specific then just applying some CSS to the
 element and all of its children. You can target any links within your footer by using
#footer a {
    color: #333;
}

Due to the descendant selector this rule itself is more specific than the one you're using for all the other  elements outside of the footer.


text:
Q: Rows to columns in oracle sql for multiple rows I have raw data as below in source table. i need this transformed as shown below.

user_id
domain_id
id_value
id_status

48085640
ID1
21885688845
5

48085640
ID1
20544518912
5

48085640
ID2
176652329
5

48085640
ID2
121702229
5

48085640
ID3
111844976
5

48085640
ID3
111347117
5

48085640
ID4
1234567
5

And i am trying to achieve the output as below. There are two values for ID1, ID2, ID3. if i use pivot i must use an aggregate function like max() or min() i am losing one of the rows.also i need to fetch the ID1, ID2 and ID3 only and filter rest of the IDs. Please help me achieve this in oracle sql and also in impala if possible

user_id
ID1
ID2
ID3
id_status

48085640
218856888
1766523293
111844976
5

48085640
205445189
1217022297
111347117
5

A: You can always manualy pivot this data and then join it to itsefl for each IDs.
Let's try:
 CREATE TABLE ABC_123 (
user_id NUMBER,     domain_id varchar2(3),  id_value NUMBER,    id_status number );

begin
INSERT INTO ABC_123 values (48085640, 'ID1', 21885688845, 5);
INSERT INTO ABC_123 values (48085640, 'ID1', 20544518912 ,5);
INSERT INTO ABC_123 values (48085640, 'ID2', 176652329 ,5);
INSERT INTO ABC_123 values (48085640, 'ID2', 121702229 ,5);
INSERT INTO ABC_123 values (48085640, 'ID3', 111844976 ,5);
INSERT INTO ABC_123 values (48085640, 'ID3', 111347117 ,5);
INSERT INTO ABC_123 values (48085640, 'ID4', 1234567 ,5);
END;

COMMIT;

WITH pivot_data as
( SELECT user_id
, CASE WHEN domain_id = 'ID1' THEN id_value ELSE NULL END AS ID1
, CASE WHEN domain_id = 'ID2' THEN id_value ELSE NULL END AS ID2
, CASE WHEN domain_id = 'ID3' THEN id_value ELSE NULL END AS ID3
, row_number() over(PARTITION BY  domain_id ORDER BY 1 /* order by is not important, but is mandatory*/ ) AS rownum_for_domain_id
, id_status
FROM ABC_123 )
SELECT d1.user_id, d1.ID1, d2.ID2, d3.ID3, d1.id_status
FROM pivot_data d1  /* inner for domain_id = 'ID1' - it determines number of rows */
LEFT JOIN pivot_data d2
 ON d1.user_id = d2.user_id
 AND d2.ID2 IS NOT NULL
 AND d2.rownum_for_domain_id = d1.rownum_for_domain_id
LEFT JOIN pivot_data d3
 ON d1.user_id = d3.user_id
 AND d3.ID3 IS NOT NULL
 AND d3.rownum_for_domain_id = d1.rownum_for_domain_id
WHERE d1.ID1 IS NOT null ;

USER_ID
ID1
ID2
ID3
ID_STATUS

48085640
21885688845
176652329
111844976
5

48085640
20544518912
121702229
111347117
5

A: Use the ROW_NUMBER analytic function to give each row a number based on the order within each user_id/domain_id partition and then use PIVOT:
SELECT user_id,
       id1,
       id2,
       id3,
       id_status
FROM   (
  SELECT t.*,
         ROW_NUMBER() OVER (PARTITION BY user_id, domain_id ORDER BY ROWNUM)
           AS rn
  FROM   table_name t
)
PIVOT (
  MAX(id_value)
  FOR domain_id IN ('ID1' AS id1, 'ID2' AS id2, 'ID3' AS id3)
)

Which, for the sample data:
CREATE TABLE table_name (user_id, domain_id, id_value, id_status) AS
SELECT 48085640, 'ID1', 21885688845, 5 FROM DUAL UNION ALL
SELECT 48085640, 'ID1', 20544518912, 5 FROM DUAL UNION ALL
SELECT 48085640, 'ID2',   176652329, 5 FROM DUAL UNION ALL
SELECT 48085640, 'ID2',   121702229, 5 FROM DUAL UNION ALL
SELECT 48085640, 'ID3',   111844976, 5 FROM DUAL UNION ALL
SELECT 48085640, 'ID3',   111347117, 5 FROM DUAL UNION ALL
SELECT 48085640, 'ID4',     1234567, 5 FROM DUAL;

Outputs:

USER_ID
ID1
ID2
ID3
ID_STATUS

48085640
21885688845
176652329
111844976
5

48085640
20544518912
121702229
111347117
5

db<>fiddle here

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python 3: Specific user input check Just to clarify, I know next to nothing in python 3 so searching gave me answers that were still difficult for me to understand
I am following a tutorial, a memory game in python 3
I have this piece of code written so far:
board_invisible = list("ABCD") * 2
board_visible = list("________")
revealed = []

while True:

    print(" ".join(board_visible))
    print("0 1 2 3 4 5 6 7")

    user_input = input()

    if user_input == "q":
        break

    if len(revealed) == 2:
        for i in revealed:
            board_visible[i] = '_'

            revealed = []

    board_index = int(user_input)
    board_visible[board_index] = board_invisible[board_index]

    revealed.append(board_index)

My assignment was to find a way to catch any user input that is not a number from 0 to 7 and print wrong  input if that was the case.
Now, I have seen a few solutions for doing this, but beforehand, I had came up with my own solution, which did not work. It was as follow :
if user_input == "0" or "1" or "2" or "3" or "4" or "5" or "6" or "7":
        continue
    else:
        print("wrong input")

I had integrated it like this :
board_invisible = list("ABCD") * 2
board_visible = list("________")
revealed = []

while True:

    print(" ".join(board_visible))
    print("0 1 2 3 4 5 6 7")

    user_input = input()

    if user_input == "q":
        break

    if user_input == "0" or "1" or "2" or "3" or "4" or "5" or "6" or "7":
        continue

    else:
        print("wrong input")

    if len(revealed) == 2:
        for i in revealed:
            board_visible[i] = '_'

            revealed = []

    board_index = int(user_input)
    board_visible[board_index] = board_invisible[board_index]

    revealed.append(board_index)

The result was that python would completely ignore my "if condition" that I hoped would prevent the user from entering anything else than a number from 0 to 7.
I would like to know why this piece of code did not work for that purpose:
if user_input == "0" or "1" or "2" or "3" or "4" or "5" or "6" or "7":
    continue

else:
    print("wrong input")

I should also mention the suggested solution I had seen, which only half worked for me: (changed some variable names for simplicity's sake)
board_visible = list("________")
board = ['A', 'B', 'C', 'D'] * 2
flipped = []

while True:

    print(" ".join(board_visible))
    print("0 1 2 3 4 5 6 7")

    if len(flipped) == 2:
        for i in flipped:
            board_visible[i] = '_'
        flipped = []

    user_input = input()

    if user_input == "q":
        break

    if user_input.isdigit():

        idx = int(user_input)

        if idx < len(board):

            board_visible[idx] = board_invisible[idx]

            flipped.append(idx)

            continue

        print("wrong input")

but for some reason it only wrote "wrong input" when I entered an "out of range number". Entering a character (anything else than an int) simply continued to run my program as if I did not entered anything.
the last line "print("wrong input") has a wrong indentation. now it works, but I still am glad that I could learn that there is more than one way to do this, thanks to the answers given in this thread.

A: That condition returns True if user_input == "0" and returns "1" if user_input != "0" because == has more precedence than or. And because that how or works, it returns the first operand if it is "truthy" (non empty lists, non empty strings, True, etc...) else it returns the second operand.
Example:
 In [8]: 1 == 1 or "1" or "2" or "3" or "4" or "5" or "6" or "7"
 Out[8]: True

 In [9]: 1 == 0  or "1" or "2" or "3" or "4" or "5" or "6" or "7"
 Out[9]: '1'

You have different ways to check if the input is what you want:
 if user_input in "01234567": # ...
 if user_input in [ "0", "1", "2", "3", "4", "5", "6", "7" ]: # ...

 import re
 #...
 if re.match(r'^[0-7]$', user_input): # ...

Also note the body of your if is incorrect, continue skips the rest of the current while iteration, so if the user inputs a value between 0 and 7 the program just returns to the beginning of the while.
You should write something like:
 if user_input not in "01234567": # Notice the `not in` operator
     print("wrong input")
     continue # To skip the rest of the while and ask the user to input a number again

You may understand the semantics of continue with the following example:
 # Lets print even numbers
 for i in range(20):
     if i % 2 != 0: # if it is odd
         continue   # skip the rest of this for
     print(i)       # prints i (only even numbers reach this point)


text:
Q: sscanf and multiple %ms When sscanf() gets two "%ms" in the format string.
Is it safe to call free() for both target pointers, when the sscanf() returns 0 or 1? Like in the next function:
void foo(const char* text)
{
    char* key = NULL;
    char* value = NULL;

    int count = sscanf(text, "%ms %ms", &key, &value);

    if (count == 2)
    {
        ...
    }

    free(key);
    free(value);
}

Or can the later target pointer (value) have some garbage value?
And the following cleanup is needed:
void bar(const char* text)
{
    char* key = NULL;
    char* value = NULL;

    int count = sscanf(text, "%ms %ms", &key, &value);

    if (count == 2)
    {
        ...
        free(key);
        free(value);
    }
    else if (count == 1)
    {
        free(key);
    }
}

A: First, you should be aware that m in a conversion specification is non-standard, so you should think about using it twice: Your code will be non-portable.
But then, if your implementation supports m, this usage is safe as long as you initialize your pointers to 0/NULL. scanf() never touches anything when there's no conversion possible and free(0) is specified to be a no op (it's always safe).


text:
Q: two-sample KS test: data becomes significantly different after normalization I'm currently working on a data set with two sets of samples. The csv file of the data could be found here. I would like to use KS test to see if these two sets of samples are from different distributions.
I ran the following R script:
# read data from the file
> data = read.csv('data.csv')
> ks.test(data[[1]], data[[2]])
    Two-sample Kolmogorov-Smirnov test

data:  data[[1]] and data[[2]]
D = 0.025, p-value = 0.9132
alternative hypothesis: two-sided

The KS test shows that these two samples are very similar. (In fact, they should come from same distribution.)
However, due to some reasons, instead of the raw values, the actual data that I will get will be normalized (zero mean, unit variance). So I tried to normalize the raw data I have and run the KS test again:
> ks.test(scale(data[[1]]), scale(data[[2]]))
    Two-sample Kolmogorov-Smirnov test

data:  scale(data[[1]]) and scale(data[[2]])
D = 0.3273, p-value < 2.2e-16
alternative hypothesis: two-sided

The p-value becomes almost zero after normalization indicating these two samples are significantly different (from different distributions).
My question is: How the normalization could make two similar samples becomes different from each other? I can see that if two samples are different, then normalization could make them similar. However, if two sets of data are similar, then intuitively, applying same operation onto them should make them still similar, at least not different from each other too much.
I did some further analysis about the data. I also tried to normalize the data into [0,1] range (using the formula (x-min(x))/(max(x)-min(x))), but same thing happened. At first, I thought it might be outliers caused this problem (I can see that an outlier may cause this problem if I normalize the data into [0,1] range.) I deleted all data whose abs value is larger than 4 standard deviation. But it still didn't help. Plus, I even plotted the eCDFs, they look the same even after normalization. Anything wrong with my usage of the R function?
Since the data contains ties, I also tried ks.boot, but I got the same result.
Could anyone help me to explain why it happened? Also, any suggestion about the hypothesis testing on normalized data? (The data I have right now is simulated data. In real world, I cannot get raw data, but only normalized one.)

A: I hope to replace this with a full answer once we have sorted out what's going on.
In trying to show you what's going on with the dependence in large vs small values, I see another problem:

The y-values have been monotonically transformed (log(y-2.e6)) for clarity.
The green box shows how the large values always occur together.
But they're also astonishingly regular. It looks like the large ones are every 20th value.
The red ovals show another problem. Notice patches of almost pure-black followed by almost pure-blue in the red ovals? There's something weird going on. Why would the middling-size values alternate, with a patch from column 1 then a patch from column 2?
You have neither independence within columns nor within pairs, but I am not sure what is causing that particular alternation in the red ovals.


text:
Q: Use env variable to represent SSH options These two ssh options:
 ssh -o StrictHostKeyChecking=no -o NumberOfPasswordPrompts=0

I am interested in setting those using env variables, is there a way to do that?
export StrictHostKeyChecking=no
export NumberOfPasswordPrompts=0

but that's of course not quite right

A: The "proper" way to do this is within your ~/.ssh/config file, where you can make those global for all connections or you can restrict it by host (or a few more advanced things). I'm going to assume you can't do that but that you do still have the ability to alter your ~/.bashrc or whatever.
You can solve this by putting this in your ~/.bashrc or ~/.zshrc (or by running these lines before ssh):
SSH_ARGS=( -o StrictHostKeyChecking=no -o NumberOfPasswordPrompts=0 )
alias ssh='ssh "${SSH_ARGS[@]}"'

If you want explicit environment variables like what you're proposing in your question (e.g. $StrictHostKeyChecking) then you'll have to make a really ugly alias or function to convert them all to the final ssh call. Here's a solution that should work in bash but won't work in POSIX shell:
ssh() {
  local SSH_VAR SSH_VAR_VALUE
  for SSH_VAR in StrictHostKeyChecking NumberOfPasswordPrompts; do # expand this
    SSH_VAR_VALUE="${!SSH_VAR}" # bash indirect expansion
    if [ -n "$SSH_VAR_VALUE" ]; then
      set -- -o "$SSH_VAR=$SSH_VAR_VALUE" "$@"
    fi
  done
  command ssh "$@"
}

The above example only supports the two SSH variables named in the question. That line will likely have to get really long as it must explicitly name every option before the semicolon on the line with the # expand this comment.
This loops over every supported SSH variable and uses bash's indirect expansion to check whether it is in the environment (and not an empty value). If it is, a -o and the option name and its value are prepended to the start of the argument list ($@).
If you use zsh, you'll need zsh's parameter expansion flag P, replacing bash's ${!SSH_VAR} with zsh's ${(P)SSH_VAR}. Other shells may need to replace that whole "bash indirect expansion" line with eval "SSH_VAR_VALUE=\"\${$SSH_VAR}\"" (watch your quoting there, or that line can be dangerous).
Invoking command ssh prevents the recursion we'd get from calling ssh from within a function of the same name. command ssh ignores the function and actually runs the true ssh command.


text:
Q: Get posts of a custom post type from another wordpress on another server? I got this two wordpress installations on two different servers.

*

*external site; on this I got a custom post type (faq), I use this to store all my faq posts, both for external and internal use.

*internal site; on this I want to load in the custom post type from site no. 1 so I don't have to double post the content.

I've used <?php require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');    ?> before but this time they dont share the same $_SERVER.


text:
Q: How to check If my PC was exploited after apt exploit? I used
sudo apt-get update
sudo apt-get upgrade

before I read https://www.debian.org/security/2019/dsa-4371
Is there a way to check if my PC got exploited/hacked/virused ?


text:
Q: Is there an Ifilter for Nuance PDFs to be used in junction with SharePoint2010? I know that there are ifilters for Adobe PDF files and hence make these files searchable inside Sharepoint.  Have not tried them but is there an ifilter for nuance created PDF documents? Please let me know.
Thanks,

A: The Adobe IFilter allows to index all searchable PDF files (i.e. not the ones created by scanning a document or a book), regardless of  software that was used to generate them.


text:
Q: Terminating app due to uncaught exception 'NSInvalidArgumentException', i hav this error. can anyone help me...
Call stack at first throw:
(
    0   CoreFoundation                      0x00dc25a9 __exceptionPreprocess + 185
    1   libobjc.A.dylib                     0x00f16313 objc_exception_throw + 44
    2   CoreFoundation                      0x00dc40bb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
    3   CoreFoundation                      0x00d33966 ___forwarding___ + 966
    4   CoreFoundation                      0x00d33522 _CF_forwarding_prep_0 + 50
    5   UIKit                               0x002b24fd -[UIApplication sendAction:to:from:forEvent:] + 119
    6   UIKit                               0x00342799 -[UIControl sendAction:to:forEvent:] + 67
    7   UIKit                               0x00344c2b -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527
    8   UIKit                               0x003437d8 -[UIControl touchesEnded:withEvent:] + 458
    9   UIKit                               0x002d6ded -[UIWindow _sendTouchesForEvent:] + 567
    10  UIKit                               0x002b7c37 -[UIApplication sendEvent:] + 447
    11  UIKit                               0x002bcf2e _UIApplicationHandleEvent + 7576
    12  GraphicsServices                    0x0171a992 PurpleEventCallback + 1550
    13  CoreFoundation                      0x00da3944 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
    14  CoreFoundation                      0x00d03cf7 __CFRunLoopDoSource1 + 215
    15  CoreFoundation                      0x00d00f83 __CFRunLoopRun + 979
    16  CoreFoundation                      0x00d00840 CFRunLoopRunSpecific + 208
    17  CoreFoundation                      0x00d00761 CFRunLoopRunInMode + 97
    18  GraphicsServices                    0x017191c4 GSEventRunModal + 217
    19  GraphicsServices                    0x01719289 GSEventRun + 115
    20  UIKit                               0x002c0c93 UIApplicationMain + 1160
    21  BasicNavigation                     0x00001ea0 main + 102
    22  BasicNavigation                     0x00001e31 start + 53
)
terminate called after throwing an instance of 'NSException'
Program received signal:  "SIGABRT".
(gdb)

A: When you are getting this error?

NSInvalidArgumentException
Name of an exception that occurs when you pass an invalid argument
  to a method, such as a nil pointer where a non-nil object is required.

A: -[NSObject(NSObject) doesNotRecognizeSelector:]

indicates that one of your objects does not recognize the selector method. You are probably calling a method using an object which does not perform the particular method. Please post your code so that you can get the exact reason.


text:
Q: How to trim const wchar_t*? I have const wchar_t* looks like "\n\t\t\t\tsomething\n\t\t\t\t" and I want to get "something". What is the most efficient way to do it?
[EDIT]
I've worked out something like this:
typedef wchar_t XMLCh

const XMLCh* trimTabs(const XMLCh* text)
{
string dest = XMLString::transcode(text);
dest.erase(remove(dest.begin(),dest.end(),'\t'), dest.end());
dest.erase(remove(dest.begin(),dest.end(),'\n'), dest.end());
return XMLStr(dest.c_str()).getXMLStr();
}

XMLStr class which is existing already in my project helped mi a lot. I hope it's good answer. XMLString is a class from Xercesc library.

A: Copy your const wchar_t* to std::wstring, and then trim it using one of the methods from What's the best way to trim std::string?. You cant trim const wchar_t*, it must be copied.
[edit]
additional comment to your updated question. With below function signature it is not possible to accomplish what you want.
const XMLCh* trimTabs(const XMLCh* text)

I dont know how the rest of your code looks like, but here the best you can do is to change to:
string trimTabs(const XMLCh* text)
{
string dest = XMLString::transcode(text);
dest.erase(remove(dest.begin(),dest.end(),'\t'), dest.end());
dest.erase(remove(dest.begin(),dest.end(),'\n'), dest.end());
return string(XMLStr(dest.c_str()).getXMLStr());
}

otherwise you are returning const wchar_t* to some temporary buffer which is undefined behaviur. I assume here your XMLStr is not managing memory in some global allocator.

A: You will need new variable to store the characters, so first of all just iterate over your string and find the first and the last occurrance of non-whitespace character. You can use two pointers and iterate from the beginning and the end of a string. Then you can use this function to copy the string:
wchar_t* wcscpy (wchar_t* destination, const wchar_t* source);

You can find the description here:  C++ Reference - wcscpy


text:
Q: EJS include pass data to Partial (not working?) So i am working on an application where i need to pass multiple data sources to different partials it works for the table partials but when i do the exact! same thing for another Partial/include it won't work i'm starting to get crazy but their should be a solution for this right? Is their someone so kind to help me?
// THIS WORKS!
 //index.ejs

    Drop of the week

  <%- include('partials/table', {data: dropOfTheWeek}); %>

//table.ejs (partial)

<% if(data.length > 0){ %>

    #
    Name
    Profile
    Mint
    Supply
    Socials
    date (CET)
    Information

  <% for(var i=0; i < data.length; i++) { %>

    <%= data[i].id %>
    <a href="/drop/<%= data[i].id %>"><%= data[i].name %>

// DOESN'T WORK
// index.ejs

      <%- include ('partials/displayCard' , {data: dropOfTheWeek}); %>

      <%- include ('partials/displayCard' , {data: dropOfTheWeek}); %>

// displayCard.ejs (partial)

 <% if(data.length > 0){ %>

hello world!

 <% } else{ %>

Nothing

 <% } %>


text:
Q: 'DefaultValue' property was already registered by 'Xceed_Wpf_Toolkit_NumericUpDown`1_12_151463089' Error Description
I've searched for this error but every other topic was involving C# code and metadata/dependency overridings.
But my problem actually involves only and just XAML declarations (of course, it has "MyControl.xaml" and "MyControl.xaml.cs", but nothing that even mention any control that gives those errors).
Also, it does compile, the program runs OK, everything is fine, but it gives a build error (tracked in blue) is annoying to see every line envolving xctk underlined in blue as if it had something wrong.
If I do:
<xctk:IntegerUpDown />

I get this:

'DefaultValue' property was already registered by 'Xceed_Wpf_Toolkit_NumericUpDown'1_12_151463089'

How to reproduce
Just do anything envolving Xceed WPF Toolkit:
<xctk:DecimalUpDown />
<xctk:IntegerUpDown x:Name="something" />
<xctk:IntegerUpDown Name="something" />
<xctk:IntegerUpDown DefaultValue="0" />
<xctk:IntegerUpDown x:Name="something" DefaultValue="0" />

No aditional C# code involved, still all of above gives the same error.
Aditional Information
"xctk" is defined this way in my UserControl XAML:
<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    ...other definitions...
    xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"

What could it be related with and what should I check first?
(EDIT)
More Aditional Information
Just found that DoubleUpDown doesn't raise the error:
<xctk:DoubleUpDown />


text:
Q: Background programming in C I'm trying to create a background program that has main config file which contains another config file locations and execute each of them. For example:
if main_config.conf:
/home/conf1
/home/conf2

i want to execute ./background_pro /home/conf1 and ./background_pro /home/conf2 in background. How do i do that ? I'm using below structure.Thank you
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>

int main(void) {

        /* Our process ID and Session ID */
        pid_t pid, sid;

        /* Fork off the parent process */
        pid = fork();
        if (pid < 0) {
                exit(EXIT_FAILURE);
        }
        /* If we got a good PID, then
           we can exit the parent process. */
        if (pid > 0) {
                exit(EXIT_SUCCESS);
        }

        /* Change the file mode mask */
        umask(0);

        /* Open any logs here */

        /* Create a new SID for the child process */
        sid = setsid();
        if (sid < 0) {
                /* Log the failure */
                exit(EXIT_FAILURE);
        }

        /* Change the current working directory */
        if ((chdir("/")) < 0) {
                /* Log the failure */
                exit(EXIT_FAILURE);
        }

        /* Close out the standard file descriptors */
        close(STDIN_FILENO);
        close(STDOUT_FILENO);
        close(STDERR_FILENO);

        /* Daemon-specific initialization goes here */

        /* The Big Loop */
        while (1) {
           /* Do some task here ... */

           sleep(30); /* wait 30 seconds */
        }
   exit(EXIT_SUCCESS);
}

A: Just append an '&' at the rear of shell command, then the command will run in background.
I think, this may be what you want: daemon.bash
#!bash

# to stop a sub process
if [ "x$1" = "x-stop" ]; then
    if [ "x$2" = "xsub1" ]; then
        kill `cat sub1.pid`
    elif [ "x$2" = "xsub2" ]; then
        kill `cat sub2.pid`
    fi
    exit
fi

# to start sub processes
conf1=`head -1 main_config.conf`
conf2=`head -2 main_config.conf | tail -1`
nohup ./background_pro $conf1 &
pid1=$!
echo "$pid1" > sub1.pid
nohup ./background_pro $conf2 &
pid2=$!
echo "$pid2" > sub2.pid

Run the demon:
nohup ./daemon.bash &

The nohup will keep the program running even you turn off the terminal.
Stop sub process 1:
./daemon.bash -stop sub1

A: A background program might be what linux users call a "Daemon" program. Please look here on Creating a daemon in Linux where you can find a plethora of information on how to begin writing your own Daemon. For parsing command line arguments, i recommend reading the GNU c library manual for getopt().


text:
Q: Fixing function from swift 1.0 to 1.2 I just upgraded to the new swift and can't figure out how to fix this function. Any ideas? I get the error below and my first and return lines:

'(@Ivalue String!) -> _' is not identical to 'NSInteger'

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        var countx = count(textView.text) + (count(text) - count(range))
        var t = String(countx) + "/500"
        countText.text = t
        return count(textView.text) + (count(text) - count(range)) <= 500
    }

A: Try this code ->
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        let countx = count(textView.text) + (count(text) - range.length)
        countText.text = "\(countx)/500"
        return countx <= 500
    }

A: Convert Swift 1.0 to Swift 1.2
First you select a target and then it's very similar to how refactoring works – Xcode will churn away and then come back with a preview. You'll see the old code and new code side-by-side with the changes highlighted.
Go Edit\Convert\To Swift 1.2
I hope its work....

A: Thanks for the answers, was very helpful. Turns out I had a variable named count. Since the function was countElements before there was no conflict.


text:
Q: Python for loop in Django template syntax, iterate by 5 I know this is an incredibly noob question but I can't seem to find an example of what I need (there's some for loop examples here but not what i need..
I can get this working using a simple script but the template syntax really throws me.
I need to simply add 10 to each iteration and just have a select list of multiples of ten.  However, I can't get even the following simple example to work:
<select id="multiples">
{% for num in range(5,100) %}
<option value="{{ num }}">{{ num }}</option>
{% endfor %}

Could anyone offer a hand please, thanks.

A: Templates don't work with arbitrary code. Django's built-in for loops don't support this sort of thing.
Here is a previous discussion with some good options on how to get the sort of behavior you want.

A: Use Python's range third argument (offset or increment). You can set it to skip certain elements:
 >>> range(0, 10, 3)
 [0, 3, 6, 9]

Edit-----
As you know, Django templates don't understand ranges. So, the option would be to pass either the range or the list itself from the backend. Passing the range would be something like:
render_to_response('template.html', {..., 'range': range(0, 10, 3), ...}, ...)


text:
Q: A2019: how to get a context menu in a form for an unbound date control like for bound date controls I'm not sure how it is possible to get the same contextmenu for an unbound form's control like for bound controls, both with a date value.
There are two unbound controls which get their control value via:
txtErsteSpende:
=Wenn([spSurrKey]>0;DomMin("[zaZahlDatum]";"[tblZahlungen]";"[zaSP_FKEY] = " & [Formulare]![frm110_Spender]![spSurrKey]);Null)

and
txtLetzteSpende:
=Wenn([spSurrKey]>0;DomMax("[zaZahlDatum]";"[tblZahlungen]";"[zaSP_FKEY] = " & [Formulare]![frm110_Spender]![spSurrKey]);Null)

Sorry for these are examples in german: "wenn" means "iif". It seems the bound control allows the context menu but not available for unbound controls.
Or is there a technique without writing vba-code to allow same context menu for both kind of controls?
Any suggestions appreciated
thx
Contextmenu filter a date - bound control
Contextmenu filter a date - unbound control

A: the goal was:

*

*make the form updatable

*display the date contextmenu for the two textboxes

After trying around with subforms which wasn't practable because the form is displayed in data sheet view I found this solution:
qry110:
SELECT tblSpender.spID, tblSpender.spNachname, tblSpender.spVorname, tblSpender.spOrt, tblSpender.spGebdat, DMin("[zaZahlungsdatum]","[tblZahlungen]","[zaSPFKEY] = " & Nz([tblSpender].[spID],0)) AS datErsteSpende, DMax("[zaZahlungsdatum]","[tblZahlungen]","[zaSPFKEY] = " & Nz([tblSpender].[spID],0)) AS datLetzteSpende
FROM tblSpender;

=> works fine but shows #Error in the form's textbox when in table tblZahlungen there is no entry (no ForeignKey) for the PrimaryKey in tblSpender
So I created a second query as recordsource for frm110 based on the first qry110 which checks the NULLvalue:
qry111:
SELECT qry110_Spender.spID, qry110_Spender.spNachname, qry110_Spender.spVorname, qry110_Spender.spOrt, qry110_Spender.spGebdat, IIf(Nz([datErsteSpende],0)>0,DateValue([datErsteSpende]),Null) AS datumErsteSpende, IIf(Nz([datLetzteSpende],0)>0,DateValue([datLetzteSpende]),Null) AS datumLetzteSpende
FROM qry110_Spender;

It works and now the form's recordset IS updatable.
Maybe the form isn't very performant for big data but it's acceptable for my users
thx for your hints
contextmenu for date textboxes


text:
Q: yii, ajax, javascript not calling action I am trying to post data to an action with ajax in yii.  Currently I am hard coding true and false in the action to see if I am even posting data, and it's not getting there.
I can't seem to figure out where I am going wrong.  Any Information would help, Thank you
JS/AJAX below:
    function printObject(o) {  // alerts an object
        var out = '';
        for (var p in o) {
            out += p + ': ' + o[p] + '\n';
        }
        alert(out);
    }

    $(function() {
        var dialog, form,
            //select ticket_code, I don't know if this is working properly
            ticket_code = $( "#ticket_code"),
            allFields = $( [] ).add( ticket_code ),
                tips = $( ".validateTips" );

        function addTicket() {
            var valid = false;
            //alert ticket_code (however, it only alerts a long error message)
            //saying that the length is 1, but not sure if that is correct
            //see link at the end for error message.
            printObject(ticket_code);
            $.ajax({
                type: "POST",
                url: '<?php echo Yii::app()->createUrl('ticket/addTicket'); ?>',
                data: {ticket_code : ticket_code},
                success: function(){
                    alert('got here');
                    valid = true;
                }
            });
            alert("after ajax");
            if ( valid ) {
                dialog.dialog( "close" );
                alert('yay');
            }
        }

actionAddTicket below:
public function actionAddTicket(){
    if(isset($_POST['ticket_code'])){
        return true;
    }
    return false;
}

form view below:

Please Enter Ticket Number

<form>
    <fieldset>
        Ticket Code #
        <input type="text" name="ticket_code" id="ticket_code" placeholder="000-0000" class="text ui-widget-content ui-corner-all" title="You can find this on the bottom right hand side of your ticket">

        <input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
    </fieldset>
</form>

A: The problem appears to be caused by two things:

*

*AJAX requests are Asynchronous, which means the line of JavaScript immediately following the call to $.ajax gets executed before the AJAX request comes back in, or most likely will. It becomes a race condition.

*The line ticket_code = $( "#ticket_code") is a jQuery object. You then pass it as the ticket_code property in the request data which jQuery is trying to serialize as a string. jQuery thinks ticket_code is an HTMLInputElement (e.g. <input type="text">) when it actually is a jQuery object, so there is no way for it to be serialized as a string.
Anything you want to do after the AJAX request comes back to the browser should be done in the success callback. Secondly, you need to use ticket_code.val() when creating your data to pass along in the request:
function addTicket() {
    var valid = false;

    $.ajax({
        type: "POST",
        url: '<?php echo Yii::app()->createUrl('ticket/addTicket'); ?>',
        data: {ticket_code : ticket_code.val()},
        success: function(){
            // ticket_code is valid
            dialog.dialog( "close" );
        }
    });
}


text:
Q: Postgres query taking too long I've looked at many of the primary mistakes people make when executing queries and I'm not sure why it takes so long to execute.
I removed all of the fields I am not using, this query fetches about 10,000 records.
What can I do to optimize my query.
SELECT ord.id              AS ord_id,
       oli.id              AS oli_id,
       ord.dealer_code__c  AS ord_dealer_code__c,
       ord.recordtypeid    AS ord_recordtypeid,
       ord.order_number__c AS ord_order_number__c,
       ord.status          AS ord_status,
       ord.opportunityid   AS ord_opportunityid,
       ord.sfid            AS ord_sfid,
       ord.pricebook2id    AS ord_pricebook2id,
       cont.opportunity__c AS cont_opportunity__c,
       cont.sfid           AS cont_sfid,
       opp.sfid            AS opp_sfid,
       opp.recordtypeid    AS opp_recordtypeid,
       opp.pricebook2id    AS opp_pricebook2id,
       accban.sfid         AS accban_sfid,
       accban.ban__c       AS accban_ban__c,
       usr.sfid            AS usr_sfid
FROM   fullsbxsalesforce.order ord
       LEFT JOIN fullsbxsalesforce.contract cont
              ON ord.contractid = cont.sfid
       LEFT JOIN fullsbxsalesforce.opportunity opp
              ON cont.opportunity__c = opp.sfid
       LEFT JOIN fullsbxsalesforce.user usr
              ON ( ord.dealer_code__c = usr.dealer_code_bd__c
                    OR ord.dealer_code__c = usr.dealer_code_co_sell__c
                    OR ord.dealer_code__c = usr.rep_dealer_code__c
                    OR ord.dealer_code__c = usr.dealer_code_secondary__c )
       LEFT JOIN fullsbxsalesforce.account_ban_tax_id__c accban
              ON ord.ban_number__c = accban.ban__c
       LEFT JOIN fullsbxsalesforce.orderitem oli
              ON oli.sfid = (SELECT sfid
                             FROM   fullsbxsalesforce.orderitem oli
                             WHERE  ord.sfid = oli.orderid
                             LIMIT  1)
WHERE  ord.recordtypeid = 'specificid'
       AND ( ord.status IN ( 'Submitted', 'Pending EIP eSignature',
                             'Partially Shipped',
                                                 'In-Fulfilment Queue',
                             'Locked', 'Pending Approval', 'Resubmitted',
                             'Pending Order',
                             'Pending Customer Completion', 'Backorder', 'Draft'
                             ,
                                   'Credit Card Declined',
                             'External System', 'Shipped/Pending Activation',
                                   'Shipped/Partially Activated'
                                                 , 'SAP Order Does not exist',
                             'Approved', 'Submit Failed for an Easy Order',
                                   'Pending e-Signature',
                                                 'e-Signature Complete',
                             'Credit Card Decline (Hold)', 'Pre-Order',
                             'In Shipping Queue'
                               )
              OR ( ord.status = 'Shipped'
                   AND ord.hasmsisdn__c = false
                   AND ord.last_status_change__c >= CURRENT_DATE -
                                                    INTERVAL '7' day ) );

Thanks
-Tim
EDIT:
thankyou for all of your help so far, the query has finished at 25 minutes returning 9.5k records.
I have changed it from java to postgres and added sql to the tags.
Thanks everyone so far
EDIT 2: I have performed an "EXPLAIN" on my query
 Nested Loop Left Join  (cost=4283.25..5032.80 rows=2 width=256)
   Join Filter: (((ord.dealer_code__c)::text = (usr.dealer_code_bd__c)::text) OR ((ord.dealer_code__c)::text = (usr.dealer_code_co_sell__c)::text) OR ((ord.dealer_code__c)::text = (usr.rep_dealer_code__c)::text) OR ((ord.dealer_code__c)::text = (usr.dealer_code_secondary__c)::text))
   ->  Nested Loop Left Join  (cost=4283.25..4298.93 rows=1 width=237)
         ->  Nested Loop Left Join  (cost=0.34..12.01 rows=1 width=233)
               ->  Nested Loop Left Join  (cost=0.25..7.92 rows=1 width=215)
                     ->  Nested Loop Left Join  (cost=0.17..6.99 rows=1 width=158)
                           ->  Index Scan using hc_idx_order_recordtypeid on "order" ord  (cost=0.08..2.90 rows=1 width=139)
                                 Index Cond: ((recordtypeid)::text = 'specificid'::text)
                                 Filter: (((status)::text = ANY ('{Submitted,"Pending EIP eSignature","Partially Shipped","In-Fulfilment Queue",Locked,"Pending Approval",Resubmitted,"Pending Order","Pending Customer Completion",Backorder,Draft,"Credit Card Declined","External System","Shipped/Pending Activation","Shipped/Partially Activated","SAP Order Does not exist",Approved,"Submit Failed for an Easy Order","Pending e-Signature","e-Signature Complete","Credit Card Decline (Hold)",Pre-Order,"In Shipping Queue"}'::text[])) OR (((status)::text = 'Shipped'::text) AND (NOT hasmsisdn__c) AND (last_status_change__c >= (('now'::cstring)::date - '7 days'::interval day))))
                           ->  Index Scan using hcu_idx_contract_sfid on contract cont  (cost=0.08..4.09 rows=1 width=38)
                                 Index Cond: ((ord.contractid)::text = (sfid)::text)
                     ->  Index Scan using hcu_idx_opportunity_sfid on opportunity opp  (cost=0.08..0.93 rows=1 width=57)
                           Index Cond: ((cont.opportunity__c)::text = (sfid)::text)
               ->  Index Scan using hcu_idx_account_ban_tax_id__c_ban__c on account_ban_tax_id__c accban  (cost=0.08..4.09 rows=1 width=28)
                     Index Cond: ((ord.ban_number__c)::text = (ban__c)::text)
         ->  Index Scan using hcu_idx_orderitem_sfid on orderitem oli  (cost=4282.91..4286.92 rows=1 width=23)
               Index Cond: ((sfid)::text = ((SubPlan 1))::text)
               SubPlan 1
                 ->  Limit  (cost=0.00..4282.83 rows=1 width=19)
                       ->  Seq Scan on orderitem oli_1  (cost=0.00..25696.96 rows=6 width=19)
                             Filter: ((ord.sfid)::text = (orderid)::text)
   ->  Seq Scan on "user" usr  (cost=0.00..555.20 rows=35733 width=74)
(22 rows)


text:
Q: Cypher query to match one perticular path of a graph I have a graph as below. The purple color nodes(11376 & 11394) are my root nodes i.e., my graph starts from there.
Now I wanted to write a cypher query such a way that i should get complete path for node 11376 i.e., from start node to end node (purple to yellow) . Also when i say node 11376  I should not get other node 11394.  How can i do it.
I tried the below query but did not get the desired output:
 match (hh{id:'11376'})-[*0..2]-(n) return n;

It is giving other node as well i.e., 11394
Below is the neo4j grapg:

So if i write cypher match query for node 11376, i should get the complete below path , as below.
How can i do it ?
Thanks

A: By using your the label types of your yellow nodes, write the query as:
match path = (hh{id:'11376'})-[*0..3]-(n:YELLOW_NODE_LABEL_TYPE_HERE)
return path;

That will return all paths that traverse 3 hops or less from (node {id:'11376'}) to any nodes who have the label type you've assigned to your yellow nodes. The paths through the second purple node will not be included in your result because it will take greater than three hops to get to another yellow node through both purple nodes.

A: Well you know that there will be minimum 3 hops so you can specify it in your query :
MATCH p=(hh {id:11376})-[r*3]-(n)) RETURN p

By the way without having a label for the yellow nodes you can not restrict that the path must end with a yellow node so with the above query you might have some extra paths


text:
Q: Why java.lang.NoSuchMethodError when dynamically load a dex jar? There is a interface IA class in APK file.  I create a jar containing IA's implementation MA.  The jar has a Global class and B class. The jar is loaded dynamically with Dexclassloader from data directory.
interface IA {
  test();
}

class Global {
   IA instance;  //refer to  MA instance.
}

class B {
  ....
  instance.test() ; // throw NoSuchMethodError
....
}

But it's OK to call instance's test method through reflection.
Why?  Surely I am not familiar with some principals of Classloader or DexClassloader. Could someone give explanation for me? Thanks

A: I too got a NoSuchMethod error, after doing some testing I found out that the problem was that the DEX file inside the JAR wasn't named classes.dex as it's supposed to be.
The fact that the app was able to create a new instance of your class doesn't necessarily mean that the DEX was loaded properly, I tested it with an empty JAR (i. e. removed all internal files via 7-ZIP) and was still able to instantiate my class (although I guess it would work only with a default constructor that gets zero parameters).


text:
Q: Cambiar index bucle python Mi problema es modificar el valor de k. Es decir cuando llamo a la función funmeta, esta me devuelve una posición que quiero que adquiera k y vuelva a empezar el bucle de arriba por esa posición. Conforme está en el código, no se modifica.
for k,i in enumerate(lista):
        print(k)
        print(i.m)
        valor = input("Introduce el valor de m" + i.m)
        index = funmeta(lista, i.m, valor)
        if(index!=0):
            k = index
        k = index
        print(k)
        print(i.m)

A: En estos casos lo más sencillo es cambiar el ciclo for por un while, de forma que la variable de control del while es el indice en si y puede ser modificada sin problemas desde dentro del propio ciclo.
Dado que no se que hace tu función funmeta() o qué es i.m, te dejo una implementación con la misma idea, cambiar el índice de iteración dentro del propio ciclo a voluntad al recorrer una lista.
En este ejemplo puedes cambiar el índice mediante el retorno de la función getIndx que usa un input, si introduces un índice válido la función retorna este indice y el bucle se 'reinicia' por esa posición de la lista, si se introduce otra cosa la función retorna -1 y el ciclo continua normalmente:
lista = [1,2,3,4,5,6,7,8,9,10]

def getIndx(lista):
    try:
        index = int(input("Introduce el nuevo indice, entre 0 y {0} o otra si desea continuar el ciclo: ".format(len(lista)-1)))
        if index in range(0, len(lista)):
            return index
    except:
        return -1

#A partir de aquí el código es el sustituto de tu for

k = 0
while k < len(lista):
    v = lista[k]
    print('Indice:', k, 'Valor:', lista[k])
    k+=1

    index = getIndx(lista)

    if index >= 0:
        k = index

Si tienes problemas para adaptarlo a tu código edita la pregunta añadiendo el código mínimo para poder reproducir tu programa.


text:
Q: Dialogflow Knowledge (beta feature) I am trying to create FAQ using Dialogflow Knowledge. Ideally, either the conversation intent or FAQ must trigger. When I type in the FAQ, it does fetch the response from knowledge base but at the same time it also triggers a intent for slot filling.
How can I resolve this to trigger either FAQ (if found in knowledge base) or intent  (if no FAQ exists in knowledge base, for the given threshold).
Regards.

A: For my bot, I preferred knowledge base answers for response. for that I set the preference more towards Knowledge base like this:

Also, I didn't created any separate intent to capture slots. Only using the default that is generated while creating the knowledge base. There is also no webhook enabled for my agent.


text:
Q: Apache HTTP/2 Issues on Virtual Hosts I have third-party domains pointed to my IP address using A records, and these are configured on the server using a Virtual Host configuration. Here's an example:
Protocols h2 h2c http/1.1

<VirtualHost *:443>
    ServerName clientwebsite.com
    ServerAlias www.clientwebsite.com username.mywebsite.com
    DocumentRoot "/home/username/html"
    SSLEngine on
    Include /etc/letsencrypt/options-ssl-apache.conf
    SSLCertificateFile /etc/letsencrypt/live/username.mywebsite.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/username.mywebsite.com/privkey.pem
</VirtualHost>

The content will serve over HTTP/2 only if I use the alias username.mywebsite.com and not if I use the client's domain clientwebsite.com.
The primary domain for my web server mywebsite.com has its NS records with Cloudflare and any URL containing mywebsite.com seems to deliver over HTTP/2 just fine - it's any other domain that I'm having a problem with.


text:
Q: Cert-Manager and Nginx under one umbrella helm chart in AKS fails to issue my certificates My experience with Kubernetes is relatively small about a month since I have started learning and experimenting.
I am migrating my setup from azure app services to AKS and I have encountered some issues with nginx ingress controller and cert-manager working together. Maybe it is the timing of the dns record change or my aproach of installing the packages that causes me the issue
My general approach is that I have a networking chart and an application chart meaning that I have to install one instance/release of the networking chart and I can install several instaces/release of my application chart(being staging,qa,production environments).
My networking chart looks like this:
Chart.yaml:
apiVersion: v2
name: networking
description: A Helm chart for Kubernetes
type: application
version: 0.0.1
appVersion: "1.1.0"
icon: <<I have iconurl here>>

dependencies:
  - name: nginx-ingress
    version: 0.14.0
    repository: https://helm.nginx.com/stable
    alias: nginx-ingress
  - name: cert-manager
    version: 1.8.2
    repository: https://charts.jetstack.io

values.yaml:
replicaCount: 1

cert-manager:
  installCRDs: true

nginx-ingress:
  controller:
    service:
      annotations:
        "service.beta.kubernetes.io/azure-load-balancer-health-probe-request-path": /healthz

I have no templates in this chart
The application chart has an issuer and ingress resource for the given environment as follows:
ingress.yaml:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress
  {{ if eq .Values.environment "Release" }}
  namespace: release
  {{ else if eq .Values.environment "ReleaseQA" }}
  namespace: release-qa
  {{ else if eq .Values.environment "ReleaseProd" }}
  namespace: release-prod
  {{ else }}
  {{ required "value for .Values.environment is not as expected" .Values.environment }}
  {{ end }}
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
    nginx.ingress.kubernetes.io/ssl-redirect: "false"
    # ingress.kubernetes.io/ssl-redirect: "false" # I tried these various options
    cert-manager.io/issuer: letsencrypt-nginx
    # acme.cert-manager.io/http01-ingress-class: "nginx-cert-controller" # I tried these various options
spec:
  tls:
    {{ if eq .Values.environment "Release" }}
    - hosts:
        - core.staging.foo.com
      secretName: core-cert-nginx
    - hosts:
        - portal.staging.foo.com
      secretName: portal-cert-nginx
    - hosts:
#more tsl definitions here for other environments
#and the rules later in the file:
  ingressClassName: nginx
  rules:
    {{ if eq .Values.environment "Release" }}
    - host: core.staging.foo.com
      http:
        paths:
          - pathType: Prefix
            path: "/"
            backend:
              service:
                name: core-service
                port:
                  number: 80
    - host: portal.staging.foo.com
      http:
        paths:
          - pathType: Prefix
            path: "/"
            backend:
              service:
                name: portal-service
                port:
                  number: 80

issuer.yaml
apiVersion: cert-manager.io/v1
kind: Issuer
metadata:
  name: letsencrypt-nginx
  {{ if eq .Values.environment "Release" }}
  namespace: release
  {{ else if eq .Values.environment "ReleaseQA" }}
  namespace: release-qa
  {{ else if eq .Values.environment "ReleaseProd" }}
  namespace: release-prod
  {{ else }}
  {{ required "value for .Values.environment is not as expected" .Values.environment }}
  {{ end }}
spec:
  acme:
    email: <<my-valid-acme-email>>
    server: https://acme-v02.api.letsencrypt.org/directory
    privateKeySecretRef:
      name: letsencrypt-nginx-private-key
    solvers:
      # Use the HTTP-01 challenge provider
      - http01:
          ingress:
            class: nginx

All internal services and application pods are also created and healty.
So the question would be why is my http01 challenges keep failing? I also used in container terminal and descibed challenges with kubectl but I get the same result that the challenges created by cert-manager cannot be reached, in other words I get 302,404,502 codes or just routes to my application instead while switching between configurations.
I am also experiencing a weird behaviour that I cannot diagnose properly, that if the challenge does not fail at the first try it can pass and I am able to renew it with the cet-manager kubectl extention. Here I should mention that I am using external domain provider and I have to reroute traffic with the least down time so before the challenges can be completed they probably fail plenty of time before the domain address is set to the new IP.
I should probably mention the kubernetes environment details I am using:
Platform: Azure AKS
Kubernetes version: 1.23.5
nginx-ingress chart version: 0.14.0
cert-manager chart version: 1.8.2
applicaions running in the pods are:

*

*2*static react websites

*4*.NET Core backend apis and other type of services.

Please let me know in the comments/answers if you need addictional onformation to help.

A: I solved it by adding acme.cert-manager.io/http01-edit-in-place: "true" annotation on my ingress. For some reason the two different ingress resources made my ingress controller confused. But since then I moved on to dns01 challenges because they provide better versatility.


text:
Q: node.js , mysql too many connections on multiple clicks Okay i have implemented a like button in my website using node.js/socket.io . Whenever the user clicks the like button the following stuff happens -
1) using jquery i check the data-islike attribute (which is true if the current user has liked the content and false otherwise ) of the button .
2) Depending on whether it is true/false i do a socket.emit with unlike/like .
Now the problem that i am having is , if a user clicks on the like button repeatedly , then instead of like-unlike-like-unlike sequence i have multiple likes and ultimately my server crashes with mysql giving an error stating that there are too many connections . what should i do ?


text:
Q: Best practice for declaring an empty variable I know Python is a dynamic language and declaring variables before-hand is generally not necessary, but in the case where I need to create a variable and then give it a value later, both of the following methods work:
some_variable = ''
some_variable = str()

Is there a difference between both of these and which is considered best practice?
Example:
some_variable = str()

for number in range(10):
    some_variable += str(number)
print(some_variable)

Works for both some_variable = '' and some_variable = str()

By best practice I do not mean "which is best coding style/most readable" but rather factors such as memory consumption, speed and which on the whole is more reliable for general use.

A: If you want to initialize a variable to an empty value, using an empty value literal will be slightly faster, since it avoids having to do a name lookup.
That is, if you write:
some_variable = str()

Python first needs to make sure you haven't written something silly like
str = int

in some visible scope first, so it has to do a recursive name lookup.
But if you write:
some_variable = ''

Then there's no way that '' will ever be anything but a str. (Similar principles apply for list and tuple literals: prefer [] and () over list() and tuple().)
More generally, though: initializing a variable to an empty value is generally considered a code smell in Python. For things like an empty list, consider using a generator expression (... for ... in ...) or a generator function (using yield) instead -- in most cases you can avoid setting up empty values at all, and that's generally considered a more Pythonic style.

A:
I know Python is a dynamic language and declaring variables before-hand is generally not necessary

What? First of all how is declaring a variable before hand related to being dynamic or not? Secondly how can you even imagine any language that forbits declaring a variable "before-hand" (whatever that means) to work? You need to declare some variable directly at some point.

Is there a difference between both of these and which is considered best practice?

Yes, there are differences. Consider this:
def str():
   return 1

x = str()

Python does not protect you from variable shadowing. But the literal empty string '' cannot be shadowed. That's a difference on the functional level.
There is also a difference on the performance level: x = '' is slightly faster then x = str() due to being translated to a different bytecode. After all x = '' does not require a function call (which cannot be optimized again due to variable shadowing).
And finally esthethics: x = '' is probably more readable then x = str(). Again since you need to be sure what str() actually is in the context.
So all in all: go with x = ''.


text:
Q: pre tag with h:outputtext is it possible to have a pre tag surrounding an h:outputtext as given below?

  <h:outputText value="#{maintainBusinessProcessBean.featureCodeAssistContent}">
  </h:outputText>

I need to display the content of a java method in my html page. I tried giving some sample java method directly in my pre tag as given below it works fine.

  public int getResult(int a, int b){
      return a+b;
  }

whereas if i give the same method as a string to an h:outputtext and surround it with a pre tag, no formatting or syntax highlighting is happening. The java method content is just displayed as a text.

A: Surely it's possible. Escaping is even not necessary in this particular case as the output in the example doesn't contain any HTML special characters such as <, >, etc. Even more, it would definitely cause trouble (XSS attack holes and so on) when the output contains them. Your problem is caused elsewhere. Most likely you're simply executing the syntax highlighting script at the wrong moment. E.g. before the
 tag is declared in the HTML DOM tree:
<h:outputScript>prettyPrint();</h:outputScript>

#{maintainBusinessProcessBean.featureCodeAssistContent}

You should be executing it during window load
<h:outputScript>window.onload = prettyPrint;</h:outputScript>

#{maintainBusinessProcessBean.featureCodeAssistContent}

or at least in the end of the body as

#{maintainBusinessProcessBean.featureCodeAssistContent}

<h:outputScript>prettyPrint();</h:outputScript>

or
<h:outputScript target="body">prettyPrint();</h:outputScript>

#{maintainBusinessProcessBean.featureCodeAssistContent}


text:
Q: Pyspark: count on pyspark.sql.dataframe.DataFrame takes long time I have a pyspark.sql.dataframe.DataFrame like the following
df.show()
+--------------------+----+----+---------+----------+---------+----------+---------+
|                  ID|Code|bool|      lat|       lon|       v1|        v2|       v3|
+--------------------+----+----+---------+----------+---------+----------+---------+
|5ac52674ffff34c98...|IDFA|   1|42.377167| -71.06994|17.422535|1525319638|36.853622|
|5ac52674ffff34c98...|IDFA|   1| 42.37747|-71.069824|17.683573|1525319639|36.853622|
|5ac52674ffff34c98...|IDFA|   1| 42.37757| -71.06942|22.287935|1525319640|36.853622|
|5ac52674ffff34c98...|IDFA|   1| 42.37761| -71.06943|19.110023|1525319641|36.853622|
|5ac52674ffff34c98...|IDFA|   1|42.377243| -71.06952|18.904774|1525319642|36.853622|
|5ac52674ffff34c98...|IDFA|   1|42.378254| -71.06948|20.772903|1525319643|36.853622|
|5ac52674ffff34c98...|IDFA|   1| 42.37801| -71.06983|18.084948|1525319644|36.853622|
|5ac52674ffff34c98...|IDFA|   1|42.378693| -71.07033| 15.64326|1525319645|36.853622|
|5ac52674ffff34c98...|IDFA|   1|42.378723|-71.070335|21.093477|1525319646|36.853622|
|5ac52674ffff34c98...|IDFA|   1| 42.37868| -71.07034|21.851894|1525319647|36.853622|
|5ac52674ffff34c98...|IDFA|   1|42.378716| -71.07029|20.583202|1525319648|36.853622|
|5ac52674ffff34c98...|IDFA|   1| 42.37872| -71.07067|19.738768|1525319649|36.853622|
|5ac52674ffff34c98...|IDFA|   1|42.379112| -71.07097|20.480911|1525319650|36.853622|
|5ac52674ffff34c98...|IDFA|   1| 42.37952|  -71.0708|20.526752|1525319651| 44.93808|
|5ac52674ffff34c98...|IDFA|   1| 42.37902| -71.07056|20.534052|1525319652| 44.93808|
|5ac52674ffff34c98...|IDFA|   1|42.380203|  -71.0709|19.921381|1525319653| 44.93808|
|5ac52674ffff34c98...|IDFA|   1| 42.37968|-71.071144| 20.12599|1525319654| 44.93808|
|5ac52674ffff34c98...|IDFA|   1|42.379696| -71.07114|18.760069|1525319655| 36.77853|
|5ac52674ffff34c98...|IDFA|   1| 42.38011| -71.07123|19.155525|1525319656| 36.77853|
|5ac52674ffff34c98...|IDFA|   1| 42.38022|  -71.0712|16.978994|1525319657| 36.77853|
+--------------------+----+----+---------+----------+---------+----------+---------+
only showing top 20 rows

If try to count
%%time
df.count()

CPU times: user 4 ms, sys: 0 ns, total: 4 ms
Wall time: 28.1 s

30241272

now if I take a subset of df the time to count is even longer.
id0 = df.first().ID  ## First ID
tmp = df.filter( (df['ID'] == id0) )

%%time
tmp.count()

CPU times: user 12 ms, sys: 0 ns, total: 12 ms
Wall time: 1min 33s
Out[6]:
3299

A: Your question is very ingesting and tricky..
I tested with a large dataset in order to reproduce your behavior.
Problem Description
I tested the following two cases in a large dataset:
# Case 1
df.count() # Execution time: 37secs

# Case 2
df.filter((df['ID'] == id0)).count() #Execution time: 1.39 min

Explaination
Lets see the Physical Plan with only .count():
== Physical Plan ==
*(2) HashAggregate(keys=[], functions=[count(1)], output=[count#38L])
+- Exchange SinglePartition
   +- *(1) HashAggregate(keys=[], functions=[partial_count(1)], output=[count#41L])
      +- *(1) FileScan csv [] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:...], PartitionFilters: [], PushedFilters: [], ReadSchema: struct<>

Lets see the physical plan with .filter() and then .count():
== Physical Plan ==
*(2) HashAggregate(keys=[], functions=[count(1)], output=[count#61L])
+- Exchange SinglePartition
   +- *(1) HashAggregate(keys=[], functions=[partial_count(1)], output=[count#64L])
      +- *(1) Project
         +- *(1) Filter (isnotnull(ID#11) && (ID#11 = Muhammed MacIntyre))
            +- *(1) FileScan csv [ID#11] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:...], PartitionFilters: [], PushedFilters: [IsNotNull(ID), EqualTo(ID,Muhammed MacIntyre)], ReadSchema: struct<_c1:string>

Generally, Spark when counts the number of rows maps the rows with count=1 and the reduce all the mappers to create the final number of rows.
In the Case 2 Spark has first to filter and then create the partial counts for every partition and then having another stage to sum those up together. So, for the same rows, in the second case the Spark doing also the filtering, something that affects the computation time in large datasets. Spark is a framework for distributed processing and doesn't have indexes like Pandas, which could do the filtering extremely fast without passing all the rows.
Summary
In that simple case you can't do a lot of things to improve the execution time.
You can try your application with different configuration settings (e.g # spark.sql.shuffle.partitions, # spark.default.parallelism, # of executors, # executor memory etc)

A: This is because spark is lazily evaluated. When you call tmp.count(), that is an action step. In other words, your timing of tmp.count also includes the filter time. If you want to truly compare the two counts, try the following:
%%time
df.count()

id0 = df.first().ID  ## First ID
tmp = df.filter( (df['ID'] == id0) )
tmp.persist().show()

%%time
tmp.count()

The important component here is the tmp.persist().show() BEFORE performing the count. This performs the filter and caches the result. That way, the tmp.count() only includes the actual count time.


text:
Q: How to draw many gradient lines quickly I'm developing an app that has to draw 320 vertical gradient lines on a portrait iPhone screen where each gradient line is either 1px or 2px wide (non-retina vs retina). Each gradient line has 1000 positions, with each position able to have a unique color. These 1000 colors (floats) sit in a C-style 2D array (an array of arrays, 320 arrays of 1000 colors)
Currently, the gradient lines are drawn in a For Loop inside the drawRect method of a custom UIView. The problem I'm having is that it takes longer than ONE second to cycle through the For Loop and draw all 320 lines. Within that ONE second, I have another thread that's updating the color arrays and but since it takes longer than ONE second to draw, I don't see every update. I see every second or third update.
I'm using the exact same procedure in my Android code, which has no problems drawing 640 gradient lines (double the amount) multiple times in a second using a SurfaceView. My Android app never misses an update.
If you look at the Android code, it actually draws gradient lines to TWO separate canvases. The array size is dynamic and can be up to half the landscape resolution width of an Android phone (ex 1280 width = 1280/2 = 640 lines). Since the Android app is fast enough, I allow landscape mode. Even with the double the data as an iPhone and drawing to two separate canvases, the Android code runs multiple times a second. The iPhone code with half the number of lines and only drawing to a single context can not draw in under a second.
Is there a faster way to draw 320 vertical gradient lines (each with 1000 positions) on an iPhone?
Is there a hardware accelerated SurfaceView equivalent for iOS that can draw many gradients really fast?
//IPHONE - drawRect method
int totalNumberOfColors = 1000;
int i;
CGFloat *locations = malloc(totalNumberOfColors * sizeof locations[0]);
for (i = 0; i < totalNumberOfColors; i++) {
    float division = (float)1 / (float)(totalNumberOfColors - 1);
    locations[i] = i * division;
}
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGColorSpaceRef colorSpace  = CGColorSpaceCreateDeviceRGB();
for (int k = 0; k < 320; k++) {
    CGFloat * colorComponents = arrayOfFloatArrays[k];

    CGGradientRef gradient = CGGradientCreateWithColorComponents(
                                                                 colorSpace,
                                                                 colorComponents,
                                                                 locations,
                                                                 (size_t)(totalNumberOfColors));
    CGRect newRect;
    if (currentPositionOffset >=320) {
        newRect = CGRectMake(0, 0, 1, CGRectGetMaxY(rect));
    } else {
        newRect = CGRectMake(319 - (k * 1), 0, 1, CGRectGetMaxY(rect));
    }
    CGContextSaveGState(ctx);
    //NO CLIPPING STATE
    CGContextAddRect(ctx, newRect);
    CGContextClip(ctx);
    //CLIPPING STATE
    CGContextDrawLinearGradient(
                                ctx,
                                gradient,
                                CGPointMake(0, 0),
                                CGPointMake(0, CGRectGetMaxY(rect)),
                                (CGGradientDrawingOptions)NULL);

    CGContextRestoreGState(ctx);
    //RESTORE TO NO CLIPPING STATE
    CGGradientRelease(gradient);
}

//ANDROID - public void run() method on SurfaceView
for (i = 0; i < sonarData.arrayOfColorIntColumns.size() - currentPositionOffset; i++) {
    Paint paint = new Paint();
    int[] currentColors = sonarData.arrayOfColorIntColumns.get(currentPositionOffset + i);
    //Log.d("currentColors.toString()",currentColors.toString());
    LinearGradient linearGradient;
    if (currentScaleFactor > 1.0) {
        int numberOfColorsToUse = (int)(1000.0/currentScaleFactor);

        int tmpTopOffset = currentTopOffset;
        if (currentTopOffset + numberOfColorsToUse > 1000) {
            //shift tmpTopOffset
            tmpTopOffset = 1000 - numberOfColorsToUse - 1;
        }
        int[] subsetOfCurrentColors = new int[numberOfColorsToUse];
        System.arraycopy(currentColors, tmpTopOffset, subsetOfCurrentColors, 0, numberOfColorsToUse);
        linearGradient = new LinearGradient(0, tmpTopOffset, 0, getHeight(), subsetOfCurrentColors, null, Shader.TileMode.MIRROR);
        //Log.d("getHeight()","" + getHeight());
        //Log.d("subsetOfCurrentColors.length","" + subsetOfCurrentColors.length);
    } else {
        //use all colors
        linearGradient = new LinearGradient(0, 0, 0, getHeight(), currentColors, null, Shader.TileMode.MIRROR);
        //Log.d("getHeight()","" + getHeight());
        //Log.d("currentColors.length","" + currentColors.length);
    }
    paint.setShader(linearGradient);
    sonarData.checkAndAddPaint(paint);

    numberOfColumnsToDraw = i + 1;
}
//Log.d(TAG,"numberOfColumnsToDraw " + numberOfColumnsToDraw);
currentPositionOffset = currentPositionOffset + i;

if (currentPositionOffset >= sonarData.getMaxNumberOfColumns()) {
    currentPositionOffset = sonarData.getMaxNumberOfColumns() - 1;
}

if (numberOfColumnsToDraw > 0) {
    Canvas canvas = surfaceHolder.lockCanvas();
    if (AppInstanceData.sonarBackgroundImage != null && canvas != null) {
        canvas.drawBitmap(AppInstanceData.sonarBackgroundImage, 0, getHeight()- AppInstanceData.sonarBackgroundImage.getHeight(), null);
        if (cacheCanvas != null) {
            cacheCanvas.drawBitmap(AppInstanceData.sonarBackgroundImage, 0, getHeight()- AppInstanceData.sonarBackgroundImage.getHeight(), null);
        }

    }
    for (i = drawOffset; i < sizeToDraw + drawOffset; i++) {
        Paint p = sonarData.paintArray.get(i - dataStartOffset);
        p.setStrokeWidth(2);
        //Log.d("drawGradientLines", "canvas.getHeight() " + canvas.getHeight());
        canvas.drawLine(getWidth() - (i - drawOffset) * 2, 0, getWidth() - (i - drawOffset) * 2, canvas.getHeight(), p);

        if (cacheCanvas != null) {
            cacheCanvas.drawLine(getWidth() - (i - drawOffset) * 2, 0, getWidth() - (i - drawOffset) * 2, canvas.getHeight(), p);
        }

    }
    surfaceHolder.unlockCanvasAndPost(canvas);
}

A: No comment on the CG code — it's been a while since I've drawn any gradients — but a couple of notes:

*

*You shouldn't be doing that in drawRect because it's called a lot. Draw into an image and display it.

*There's no matching free for the malloc, so you're leaking memory like crazy.

A: It'll have a learning curve, but implement this using OpenGL ES 2.0. I previously took something that was drawing a large number of gradients as well, and reimplemented it using OpenGL ES 2.0 and custom vertex and fragment shaders. It is way faster than the equivalent drawing done using Core Graphics, so you will probably see a big speed boost as well.
If you don't know any OpenGL yet, I would suggest finding some tutorials for working with OpenGL ES 2.0 (has to be 2.0 because that's what offers the ability to write custom shaders) on iOS, to learn the basics. Once you do that, you should be able to significantly increase the performance of your drawing, way above that of the Android version, and maybe would be incentive to make the Android version use OpenGL as well.


text:
Q: Exit status code 1 Unable to send email I'm attempting to send an email out to the person(s) who register for my site using the Email Class provided with Codeigniter for my project. I am receiving the following error message.
Exit status code: 1
Unable to open a socket to Sendmail. Please check settings.
Unable to send email using PHP Sendmail. Your server might not be configured to sendmail using this method.

$this->email->message('Welcome to '.$this->config->item('company_name').', "\r\n" Thank you for joining the '.$this->config->item('company_name').' team. We have listed your registration details below. Make sure you save this email. To verify this account please click the following link. "\r\n" '.anchor('register/verify/'.$registration_key, 'Click Here To Activate Your Account', '').' "\r\n" Please verfiy your account within 2 hours, otherwise your registration will become invalid and you will have to register again. "\r\n" Your email address: '.$post_email_address.' "\r\n" Your Password: '.$post_password.' "\r\n" Enjoy your stay here at '.$this->config->item('company_name').' "\r\n" The '.$this->config->item('company_name').' Team');

UPDATE :
I am updating my code because for some reason I am still receiving an the same error and I can't figure out what it is that is giving me the error.
../application/configs/site_configs.php
<?php

$config['company_name'] = 'My Test Site';
$config['comapny_email'] = 'owner@testingsite.com';

I would also like to mention here that I am autoloading my site configs file.
$autoload['config'] = array('site_configs');

Register Controller
// User was successfully created and the user needs to verify their account.
// Send registered an email informing them how to validate their account.
$this->load->library('email');
$this->email->from($this->config->item('company_email'), $this->config->item('company_name'));
$this->email->to($post_email_address);
$this->email->subject($this->config->item('company_name').' Registration');
//$message = 'Welcome to '. $this->config->item('company_name') ."\r\n";
//$message .= 'Thank you for joining the ' . $this->config->item('company_name') . ' team.';
//$message .= 'We have listed your registration details below. Make sure you save this email.';
//$message .= 'To verify this account please click the following link.'."\r\n";
//$message .= anchor('register/verify/'.$registration_key, 'Click Here To Activate Your Account', '')."\r\n";
//$message .= 'Please verfiy your account within 2 hours, otherwise your registration will become invalid and you will have to register again.'."\r\n";
//$message .= 'Your email address: '.$post_email_address."\r\n";
//$message .= 'Your Password: '.$post_password."\r\n";
//$message .= 'Enjoy your stay here at '.$this->config->item('company_name')."\r\n";
//$message .= 'The '.$this->config->item('company_name').' Team';
$this->email->message('Great registration.' /*$message */);
$this->email->send();
echo $this->email->print_debugger();

A: Also try to have your code be a little more readable.. I notice, your gigantic string for the message is riddled with continuations going in and out of dynamic variables. Chaining the string together as it goes along.
Why not try
$message = 'Welcome to '. $this->config->item('company_name') ."\r\n";
$message .= 'Thank you for joining the ' . $this->config->item('company_name') . ' team.';
$message .= 'We have listed your registration details below. Make sure you save this email.';
$message .= 'To verify this account please click the following link.'."\r\n";
$message .= .anchor('register/verify/'.$registration_key, 'Click Here To Activate Your Account', '')."\r\n";
$message .= 'Please verfiy your account within 2 hours, otherwise your registration will become invalid and you will have to register again.'."\r\n";
$message .= 'Your email address: '.$post_email_address."\r\n";
$message .= 'Your Password: '.$post_password."\r\n";
$message .= 'Enjoy your stay here at '.$this->config->item('company_name')."\r\n";
$message .= 'The '.$this->config->item('company_name').' Team';

$this->email->message($message);

Where its a bit more manageable and readable. So you can see where your missing a single or double quote or where you might be missing a period that would chain string to variable, etc..
The only thing Im not sure about is one line had .anchor() not sure if thats a function or something else but didn't look complete.

A: Make sure your server has sendmail and it is correctly set up or install sendmail package in your server
yum install sendmail

OR
sudo apt-get install sendmail

Make your, user email id is valid, will not send e-mail if sender does not exist
send a testmail,   echo "test sendmail" | sendmail xxx@yy.com

A:     $this->load->library('email');

    $config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'smtp.googlemail.com',
        'smtp_port' => 587,
        'smtp_user' => 'example@gmail.com',
        'smtp_pass' => 'password',
        'mailtype'  => 'html',
        'charset'   => 'iso-8859-1'
    );
    $this->email->set_newline("\r\n");

    $this->email->from('example@gmail.com', 'easyfact');
    $this->email->to('example@gmail.com');
    $this->email->cc('example@gmail.com');
    $this->email->bcc('example@gmail.com');

    $this->email->subject('Email Test');
    $this->email->message('Testing the email class.');

    $this->email->send();

    echo $this->email->print_debugger();


text:
Q: Golang build all downloaded packages I'm trying to build a docker image for my go application and I'd like to build all of the package dependencies separately from compiling the source code of my application.
Here's an example that might be helpful:
FROM ubuntu:focal

# ... a bunch of run commands that install go and other binaries I need

ENV GOPATH=/root/go
WORKDIR gadic

COPY go.mod .
RUN go mod download
RUN go build /root/go/pkg/... # this fails!!

COPY src src
RUN go build path/to/main.go # I'd like to speed this step up by pre-compiling the packages main.go depends on

When I try to build this dockerfile I get the following output:
 > [ 8/19] RUN go build /root/go/pkg/...:
#12 0.955 pattern /root/go/pkg/...: directory prefix /root/go/pkg outside available modules

Is there a way to build the packages/modules that my application depends on prior to building the main.go of my application?

A: What you really need is a build cache, see this.
There are two folders needed to be mounted into build container:

*

*GOPATH
Here we set as /root/go, used to store downloaded dependency

*GOCACHE
Default is /root/.cache/go-build, used for build cache
A minimal example as next.
Dockerfile:
# syntax = docker/dockerfile:1.2
FROM golang
ENV GOPATH=/root/go
WORKDIR /root
COPY main.go .
COPY go.mod .
COPY go.sum .

RUN --mount=type=cache,mode=0755,target=/root/.cache/go-build --mount=type=cache,mode=0755,target=/root/go go build -v main.go

main.go:
package main

import (
     _ "github.com/phachon/go-logger"
)

func main() {
}

go.mod:
module trial

go 1.14

require github.com/phachon/go-logger v0.0.0-20191215032019-86e4227f71ea

go.sum:
github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/mailru/easyjson v0.7.0 h1:aizVhC/NAAcKWb+5QsU1iNOZb4Yws5UO2I+aIprQITM=
github.com/mailru/easyjson v0.7.0/go.mod h1:KAzv3t3aY1NaHWoQz1+4F1ccyAH66Jk7yos7ldAVICs=
github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA=
github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM=
github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
github.com/phachon/go-logger v0.0.0-20191215032019-86e4227f71ea h1:IkOONr/u7Wy+j2R4r1eMV8PEuN4kmOhZZNaYxDOF+KQ=
github.com/phachon/go-logger v0.0.0-20191215032019-86e4227f71ea/go.mod h1:WBIWFH/iYYvuApCvPU+/R6hfX6v0Ogu4apwf0UgzVF0=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=

Execution:

*

*1st time, you could see it downloads the dependency package, and then build different packages.

$ export DOCKER_BUILDKIT=1
$ docker build --progress=plain -t abc:1 . --no-cache
...
#14 [stage-0 6/6] RUN --mount=type=cache,mode=0755,target=/root/.cache/go-bu...
#14 3.100 go: downloading github.com/phachon/go-logger v0.0.0-20191215032019-86e4227f71ea
#14 3.330 go: downloading github.com/fatih/color v1.7.0
#14 3.331 go: downloading github.com/mailru/easyjson v0.7.0
#14 3.523 go: downloading github.com/mattn/go-colorable v0.1.4
#14 3.561 go: downloading github.com/mattn/go-isatty v0.0.11
#14 3.731 go: downloading golang.org/x/sys v0.0.0-20191026070338-33540a1f6037
#14 5.058 github.com/mailru/easyjson/buffer
#14 5.063 golang.org/x/sys/unix
#14 5.070 github.com/mailru/easyjson/jlexer
#14 5.077 github.com/mailru/easyjson/jwriter
#14 5.087 github.com/phachon/go-logger/utils
#14 5.174 github.com/mailru/easyjson
#14 5.346 github.com/mattn/go-isatty
#14 5.355 github.com/mattn/go-colorable
#14 5.368 github.com/fatih/color
#14 5.396 github.com/phachon/go-logger
#14 5.451 command-line-arguments
#14 DONE 7.4s
...

*

*2nd time, I changed the main.go as next:

main.go:
package main

import (
     _ "github.com/phachon/go-logger"
     "fmt"
)

func main() {
    fmt.Println("helloworld")
}

Then, execute build again:
$ export DOCKER_BUILDKIT=1
$ docker build --progress=plain -t abc:1 . --no-cache
...
#14 [stage-0 6/6] RUN --mount=type=cache,mode=0755,target=/root/.cache/go-bu...
#14 1.469 command-line-arguments
#14 DONE 3.2s
...

You could see from above, it no longer downloads package (because /root/go was reused during different times build). And, it just build command-line-arguments, corresponding to the change of main.go, no packages related to github.com/phachon/go-logger been rebuilt (because /root/.cache/go-build as build cache be reused).

A: I think you should take the advantage of the multi-stage builds. In the first stage, you use the docker image with Go installed. You can use one of those available here https://hub.docker.com/_/golang. At this point, you have to copy your source code into the container and run go build there.
In the next step, you (for example) use an alpine image and copy the executable (and other required fields) to the target container.
This is an example how it can be done.
FROM golang:alpine AS build-env
RUN apk --no-cache add build-base git bzr mercurial gcc
ADD . /src
RUN cd /src && go build -o goapp

# final stage
FROM alpine
WORKDIR /app
COPY --from=build-env /src/goapp /app/
ENTRYPOINT ./goapp

This has several benefits and the size of the final image is one of them.


text:
Q: DATEDIFF in HH:MM:SS format I need to calculate the total length in terms of Hours, Minutes, Seconds, and the average length, given some data with start time and end time.
For example the result must be something like 45:15:10 which means 45 hours 15 min 10 sec, or 30:07 for 30 min 07 sec.
We're using SQL Server 2008 R2 and the conversion failed when time is more than 24:59:59. Any idea of how I could do this?
For information, the columns in the table are Id, StartDateTime, EndDateTime, etc. I need to make a monthly report which contains the recordings count of the month, the total length of these records, and the average length. I'd like to know if there is an easy way to perform all of this.

A: I slightly modified Avinash's answer as it may end with error if difference is too big. If you need only HH:mm:ss it is sufficient to distinguish at seconds level ony like this:
SELECT CONVERT(time,
  DATEADD(s,
    DATEDIFF(s,
      '2018-01-07 09:53:00',
      '2018-01-07 11:53:01'),
     CAST('1900-01-01 00:00:00.0000000' as datetime2)
   )
)

A: SELECT CONVERT(time,
               DATEADD(mcs,
                       DATEDIFF(mcs,
                                '2007-05-07 09:53:00.0273335',
                                '2007-05-07 09:53:01.0376635'),
                       CAST('1900-01-01 00:00:00.0000000' as datetime2)
                      )
              )

A: If you want to do averages, then the best approach is to convert to seconds or fractions of a day.  Day fractions are convenient in SQL Server, because you can do things like:
select avg(cast(endtime - starttime) as float)
from t

You can convert it back to a datetime using the reverse cast:
select cast(avg(cast(endtime - starttime as float) as datetime)
from t

The arithmetic to get the times in the format you want . . . that is a pain.  You might consider including days in the final format, and using:
select right(convert(varchar(255), <val>, 120), 10)

To get the hours exceeding 24, here is another approach:
select cast(floor(cast(<val> as float)*24) as varchar(255))+right(convert(varchar(255), <val>, 120), 6)

It uses convert for minutes and seconds, which should be padded with 0s on the left.  It then appends the hours as a separate value.

A: You shouldn't be converting to time - it is meant to store a point in time on a single 24h clock, not a duration or interval (even one that is constrained on its own to < 24 hours, which clearly your data is not). Instead you can take the datediff in the smallest interval required (in your case, seconds), and then perform some math and string manipulation to present it in the output format you need (it might also be preferable to return the seconds to the application or report tool and have it do this work).
DECLARE @d TABLE
(
  id INT IDENTITY(1,1),
  StartDateTime DATETIME,
  EndDateTime DATETIME
);

INSERT @d(StartDateTime, EndDateTime) VALUES
(DATEADD(DAY, -2, GETDATE()), DATEADD(MINUTE, 15, GETDATE())),
(GETDATE()                  , DATEADD(MINUTE, 22, GETDATE())),
(DATEADD(DAY, -1, GETDATE()), DATEADD(MINUTE,  5, GETDATE())),
(DATEADD(DAY, -4, GETDATE()), DATEADD(SECOND, 14, GETDATE()));

;WITH x AS (SELECT id, StartDateTime, EndDateTime,
  d = DATEDIFF(SECOND, StartDateTime, EndDateTime),
  a = AVG(DATEDIFF(SECOND, StartDateTime, EndDateTime)) OVER()
  FROM @d
)
SELECT id, StartDateTime, EndDateTime,
  [delta_HH:MM:SS] = CONVERT(VARCHAR(5), d/60/60)
  + ':' + RIGHT('0' + CONVERT(VARCHAR(2), d/60%60), 2)
  + ':' + RIGHT('0' + CONVERT(VARCHAR(2), d % 60), 2),
  [avg_HH:MM:SS] = CONVERT(VARCHAR(5), a/60/60)
  + ':' + RIGHT('0' + CONVERT(VARCHAR(2), a/60%60), 2)
  + ':' + RIGHT('0' + CONVERT(VARCHAR(2), a % 60), 2)
FROM x;

Results:
id  StartDateTime        EndDateTime          delta_HH:MM:SS  avg_HH:MM:SS
--  -------------------  -------------------  --------------  ------------
1   2013-01-19 14:24:46  2013-01-21 14:39:46  48:15:00        42:10:33
2   2013-01-21 14:24:46  2013-01-21 14:46:46   0:22:00        42:10:33
3   2013-01-20 14:24:46  2013-01-21 14:29:46  24:05:00        42:10:33
4   2013-01-17 14:24:46  2013-01-21 14:25:00  96:00:14        42:10:33

This isn't precisely what you asked for, as it won't show just MM:SS for deltas < 1 hour. You can adjust that with a simple CASE expression:
;WITH x AS (SELECT id, StartDateTime, EndDateTime,
  d = DATEDIFF(SECOND, StartDateTime, EndDateTime),
  a = AVG(DATEDIFF(SECOND, StartDateTime, EndDateTime)) OVER()
  FROM @d
)
SELECT id, StartDateTime, EndDateTime,
  [delta_HH:MM:SS] = CASE WHEN d >= 3600 THEN
    CONVERT(VARCHAR(5), d/60/60) + ':' ELSE '' END
  + RIGHT('0' + CONVERT(VARCHAR(2), d/60%60), 2)
  + ':' + RIGHT('0' + CONVERT(VARCHAR(2), d % 60), 2),
  [avg_HH:MM:SS] = CASE WHEN a >= 3600 THEN
    CONVERT(VARCHAR(5), a/60/60) + ':' ELSE '' END
  + RIGHT('0' + CONVERT(VARCHAR(2), a/60%60), 2)
  + ':' + RIGHT('0' + CONVERT(VARCHAR(2), a % 60), 2)
FROM x;

This query changes the delta column in the 2nd row in the above result from 0:22:00 to 22:00.

A: Starting in SQL SERVER 2012, you don't need to use DATEDIFF function. You can use FORMAT function to achieve what you want:
SELECT
    FORMAT(CONVERT(TIME, [appoitment].[Start] - [appointment].[End]), N'hh\:mm') AS 'Duration'
FROM
    [tblAppointment] (NOLOCK)

A: A way that avoids overflows and can include days and go all the way to milliseconds in the output:
DECLARE @startDate AS DATETIME = '2018-06-01 14:20:02.100'
DECLARE @endDate AS DATETIME = '2018-06-02 15:23:09.000'
SELECT CAST(DATEDIFF(day,'1900-01-01', @endDate - @startDate) AS VARCHAR) +  'd ' + CONVERT(varchar(22), @endDate - @startDate, 114)

The above will return

1d 01:03:06:900

And, off course, you can use the formatting of your choice
SQL Supports datetime substraction which outputs a new datetime relative to the MIN date (for instance 1900-01-01, you can probably get this value from some system variable) This works better than DATEDIFF, because DATEDIFF will count ONE for each "datepart boundaries crossed", even if the elapsed time is less than a whole datapart. Another nice thing about this method is that it allows you to use the date formatting conversions.

A: If days is the (positive) number of days, like 0.5 for 12 hours, use this expression to format it as a proper duration:
CONVERT(varchar(9), FLOOR(days * 24)) + RIGHT(CONVERT(char(19), CAST(days AS datetime), 120), 6)

Excel will understands values up to 9999:59:59 when pasted. There apply a custom format: [h]:mm:ss in the English version ([u]:mm:ss for Dutch).


text:
Q: Can't clone private Github repositories over HTTPS I have problems cloning private GitHub Repositories over HTTPS. If i try to clone my repository using:
git clone https://github.com/{username}/{repository}

i get the error:
fatal: remote error: Repository not found

when i try to enter my credentials in the request like this:
git clone https://{username}@github.com/{username}/{repository}

I get the error:
fatal: Unable to look up {username}@github.com (port 9418)

Cloning over ssh works without. Cloning public repositories also works over https. Does anybody know what i could do?
I'm using windows 10 and git for windows version 2.14.13

A: You can clone your repository with:
git clone https://username@github.com/username/repo_name

It can also help to check your git configuration with:
git config -l

A: Recent changes in GitHub security do not allow anymore to use your Password to authenticate when cloning a repo.
To overcome this issue you have to generate a Personal access token and use it in place of your password.
To generate a token:

*

*open the menu on top right with your avatar and click  settings

*from your profile settings page click  Developer Settings that is the last option in the left menu

*from the developer setting page click Personal access token

*click on the generate new token button

*select the duration and the access scope you want to give to this token and click on the Generate token button

You will be able to see the token only at this time, so use / save it before closing the page.
Now that you have the PAT you can use it in place of the password when cloning or logging in with git clients.
BTW it is better to have a different token for each client.


text:
Q: Google Apps Script onFormSubmit(e) "e is undefined"? I am trying to get a form submit to push a new issue to github. Here is the code, which I got from a gist which commenters seem to have been able to get working :
var ghToken = "MY_TOKEN";

function onFormSubmit(e) {
  Logger.log(e)
var result = e.response.getItemResponses();

var testResult = result[1].getResponse();
var describeIssues = result[2].getResponse();
var issueScreenshot = result[3].getResponse();
var iosMail = result[4].getResponse();
var iosGmail = result[5].getResponse();
var iosOutlook = result[6].getResponse();
var androidGmail = result[7].getResponse();
var androidOutlook = result[8].getResponse();
var androidYahoo = result[9].getResponse();

var body = "## Status \n" +
"![warning]" + testResult +"\n" +
describeIssues +"\n" +
"______________________________________________________________________________________________________\n" +
issueScreenshot +"\n" +
"______________________________________________________________________________________________________\n" +
"## Test Results\n" +
"#### iOS\n" +
"| Mail | Outlook | Gmail\n" +
"| ------------- |:-------------:| :--------------:|\n" +
"| ![ios mail]"+iosMail+" | "+iosOutlook+" | "+iosGmail+"\n" +
"| **Interactive** | **Static** | **Static**\n"+
"| Interactive module off-center | Working - 2-column | Working 1-column\n"+
"#### Android = Samsung s8+\n" +
"| Gmail | Outlook | Yahoo! Mail\n" +
"| ------------- |:-------------:| :--------------:|\n" +
"| ![ios mail]"+iandroidGmail+" | "+androidOutlook+" | "+androidYahoo+"\n" +
"| **Interactive** | **Static** | **Static**\n"+
"| Interactive module off-center | Working - 2-column | Working 1-column\n";

  var payload = {
    "title": "Jon testing",
    "body": body
  };

  var options = {
    "method": "POST",
    "contentType": "application/json",
    "payload": JSON.stringify(payload)
  };

  var response = UrlFetchApp.fetch("https://api.github.com/repos/me/myRepo/issues?access_token="+ghToken, options);
}

This doesn't work however, when I run the script in the script editor or when I submit the form response I get TypeError: Cannot call method "getItemResponses" of undefined. (line 7, file "Code") (by the way the triggers are set correctly to run on form submit using data stored in spreadheet, which I verified is being populated).
What am I doing wrong? Why is e undefined?

A: If you run it in the script editor, of course e is undefined; where would its value come from? What would it contain? Event objects are populated by a trigger.
A Spreadsheet trigger FormSubmit does not have a response field, so e.response is undefined.
It's the Form trigger FormSubmit that has response field. To create it, go to the Script Editor of the form, not of the spreadsheet. (Or, if you want to use the Spreadsheet trigger you already have, just make sure you access the properties that it has, such as values.)


text:
Q: Missing Alias settings when calling bash withing a subprocess in python I placed a script in /etc/profile.d/
# default_dba.sh
if  groups | grep -qw "dba" ;
 then
if [ $USER != "oracle" ]; then
. /u00/scripts/oracle_alias
fi
fi

The scipt sets aliases if the LDAP user is a member of the dba group.
This works.
The LDAP user starts a python script.
As a last step the python script calls a new bash shell
subprocess.call(['/bin/bash', '-i'], shell=True)

In that shell session there are the special aliases (created by the /u00/scripts/oracle_alias script) missing, just the default os aliases are there.
Can I fix this without creating home directories for LDAP users?

A: The startup files (under /etc/profile etc..) are read only when the shell is invoked as 'login' shell. eg:- bash -l
See 'INVOCATION' section under man bash for more details.
snippet (from man page)
When  bash  is  invoked  as  an  interactive  login  shell, or as a non-interactive shell with the --login option,
it first reads and executes commands from the file /etc/profile, if that file exists.
After reading that file, it looks for ~/.bash_profile,  ~/.bash_login, and ~/.profile, in that order,
and reads and executes commands from the first one that exists and is readable.
The --noprofile option may be used when the shell is started to inhibit this behavior.


text:
Q: Add different colors to each bar in D3 I am using d3 library to display bar charts with each bar having a different color.
Here is my code -
<!DOCTYPE html>
<meta charset="utf-8">

I am unable to get different color for each bar.
Can anyone please help me fix it.

A: You are modifying fill styling, but you have div elements, so you need background-color property.
Also, you should use your color scale range as a function to get a correct result.

var data = [{
  "label": "Recommended",
  "value": 60
}, {
  "label": " You",
  "value": 60
}, {
  "label": "Peers",
  "value": 40
}];
var color = d3.scale.ordinal().range(["#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);

var x = d3.scale.linear()
  .domain([0, d3.max(data)])
  .range([0, 420]);

d3.select(".chart")
  .selectAll("div")
  .data(data)
  .enter().append("div")
  // .attr("width",400)
  // .attr("depth",400)
  .style("width", function(d) {
    return d.value + "px";
  })
  .style("background-color", function(d, i) {
    return color(i);
  })
  .text(function(d, i) {
    return data[i].label;
  });
.chart div {
  font: 10px sans-serif;
  text-align: right;
  padding: 3px;
  margin: 1px;
  color: white;
}

A: // Took from http://stackoverflow.com/questions/1484506/random-color-generator-in-javascript
function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
         color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

d3.select(".chart")
    .selectAll("div")
    .data(data)
    .enter().append("div")
    .style("background", function (d) { return getRandomColor(); })
    .style("color", function (d) { return '#FFFFFF'; })
    .style("width", function(d) { return d.value + "px"; })
    .text(function(d,i) { return data[i].label; });

A: @jprivillaso
good answer but i used the D3 index itself and pulled color codes from json object
buildlegendvalues =
[{
  "1.0": "#79abbd",
  "2.0": "#6784b4",
  "3.0": "#9b799b",
  "4.0": "#a07b70"
}]

  bl = 0;
  function getByIndex(buildlegendvalues, index) {
    bl++
    return buildlegendvalues[Object.keys(buildlegendvalues)[index]];
  }

and then:
 .attr("fill", function() { return getByIndex(buildlegendvalues,bl); })


text:
Q: use vector and push_back function with my template class with dummy business validation in vector.push_back(...) -- Can it be done with stl? I have a template class so idea of this template class is that I want to create vector object of type same as my template class abc. Can I pass int or char as T and use something like following
vector<abc<int>> g1;// <<-------how to do this correctly?
        g1.push_back({               //<-----  looks wrong
           {{1,1,1},{2,2,2},{3,3,3}} //<----- this is obvious wrong

        })

this is my template class
template <typename T>
class abc: /*drived from what???*/{
private:
    T *px=x;
    T *py=y;
    T *pz=z;
public:
    //these members must be included
    T x[10];
    T y[10];
    T z[10];

abc(const T _px[],T _py[],T _pz[]):x{{10}},y{{10}},z{{10}}
{

}

int writeto_HW()
{
    //member write to ...x,y,z to...  and other work
}
};

int main()
{
    vector<abc<int>> g1;// <<-------how to do this correctly?
    g1.push_back({               //<-----  looks wrong
       {{1,1,1},{2,2,2},{3,3,3}} //<----- this is obvious wrong

    })
    g1.push_back({{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},// <----wrong
                  {1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
                  {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    });

}

is it possible? if yes then how to achieve this
I don't  need any fancy push_back function from vector I just like to have access to inside of push_back code I will do some business validation on class abc members x[],y[],z[] to stl vector's push_back. so I need just structure what if its possible.
thanks for help