text:
Q: Cant run shell in Ubuntu server 18.04.2 LTS but it does run in Ubuntu Desktop 18.04 LTS I have been working in a shell at Ubuntu desktop, I also did a detailed spell check to it, after that I kept testing it and made sure every single line was working as intended, besides a couple directory mistakes (that will need to be changed in the server), everything seems OK
And now I'm trying to run it in a clean virtual machine with ubuntu server, so I mounted a shared folder to get access to my shell, gave permissions to execute to all users, and tried running it and surprise, it doesn't run at all
To get the interpreter to run the script i need to remove the first line #!/bin/bash and use source instead of ./ to run the shell (named master.sh)
And now that i can get it to run I keep getting this error

A common error for wrong syntax on if statements, that I know its been fixed by me and tested it using spellcheck
After that I tried to purge any other non Unix character using

I know for a fact that both OS are using BASH as an interpreter (I checked)
Here's an minimum example of the code of the 2 "IF conditions" that I can identify stopping the script, if anyone wants to look at it
#!/bin/bash
if [ -e DB_conf ]
    then
            read -p "Use DB_conf settings? [y/n]: " -n 1 -r
                if [[ $REPLY =~ ^[Yy]$ ]]
                then
                    STUFF
                else           #This is line 39
                    STUFF2
                fi
    else
        MORE STUFF
    fi

Why is ubuntu server showing this error but not the desktop one (where it actually works)?

A: It looks to me like the sed command has too many or too few /, see the comment by @steeldriver for a better sed command.
Alternatively, you can open the script in vim and view non-printable characters with [esc] :set list to see if you have any carriage returns. If that isn't the issue we'll need more context in order to solve the bash error.


text:
Q: Analogues of properties (DN) and (Ω) for more general locally convex spaces In the structure theory of Fréchet spaces, especially results around splitting short exact sequences, the properties (DN) and (Ω) play a major rôle. There are many variants, but they are phrased in terms of an increasing sequence $\left(||\cdot||_k\right)_{k=1,2,\ldots}$ of seminorms. In particular, no mention is made of completeness.
It is conceivable that these properties may have been studied for more general locally convex spaces. One might even imagine that variants could be defined where one has a larger system of seminorms. Has this ever been addressed in the literature? Or perhaps variants that take into account the weakening of the assumptions on the tvs?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I calculate total numbers of days, hours, and minutes using python pandas? This is my dataframe. I want to find total time taken from particular product.
product,query,time1,time2
A,a1,25-06-15 08:42:43.830000000 PM,25-06-15 08:42:43.830000000 PM
A,a2,03-07-15 11:57:10.557000000 AM,03-07-15 11:57:10.557000000 AM
A,a3,02-07-15 02:32:33.090000000 PM,02-07-15 02:32:33.090000000 PM
A,a4,04-07-15 11:51:59.090000000 AM,04-07-15 11:51:59.090000000 AM
A,a5,27-06-15 07:12:30.250000000 PM,27-06-15 07:47:40.270000000 PM
B,b1,30-06-15 07:48:22.090000000 PM,30-06-15 07:48:22.090000000 PM
B,b1,01-07-15 02:59:36.290000000 PM,02-07-15 05:37:40.700000000 PM
B,b1,29-06-15 01:28:07.250000000 PM,20-07-15 12:57:06.343000000 PM
B,b1,03-07-15 05:58:52.737000000 PM,03-07-15 06:06:23.977000000 PM
B,b1,26-06-15 12:56:36.210000000 AM,26-06-15 12:56:36.210000000 AM
B,b1,22-06-15 08:16:10.743000000 PM,22-06-15 08:16:10.743000000 PM
B,b1,29-06-15 11:35:36.807000000 AM,29-06-15 11:55:01.690000000 AM

I need output like
Product,query_count,total_time_taken
A,5,total time taken
B,7,total time taken

A: I think you can use groupby with apply custom function f:
df[['time1', 'time2']] = df['time1'].str.split('\t').apply(pd.Series)

#you can first convert columns to datetime
df['time1'] = pd.to_datetime(df['time1'] )
df['time2'] = pd.to_datetime(df['time2'] )

def f(x):
    return pd.Series([(x.time2 - x.time1).sum(),
                      len(x)],
                     index=['total_time_taken', 'query_count'])

print df.groupby('product').apply(f)

                total_time_taken  query_count
product
A         0 days 00:35:10.020000            5
B        52 days 02:33:59.626000            7

A: df['time'] = df.time2 - df.time1
>>> (df.groupby('product')
       .agg({'query': 'count', 'time': sum})
       .rename(columns={'query': 'query_count', 'time': 'total_time_taken'}))
         query_count        total_time_taken
product
A                  5  0 days 00:35:10.020000
B                  7 52 days 02:33:59.626000

To recreate your original dataframe:
from pandas import Timestamp

df = pd.DataFrame(
    {'product': ['A'] * 6 +  ['B'] * 6,
     'query': ['a1', 'a2', 'a3', 'a4', 'a5'] + ['b1'] * 7,
     'time1': [
         Timestamp('2015-06-25 20:42:43.830000'),
         Timestamp('2015-03-07 11:57:10.557000'),
         Timestamp('2015-02-07 14:32:33.090000'),
         Timestamp('2015-04-07 11:51:59.090000'),
         Timestamp('2015-06-27 19:12:30.250000'),
         Timestamp('2015-06-30 19:48:22.090000'),
         Timestamp('2015-01-07 14:59:36.290000'),
         Timestamp('2015-06-29 13:28:07.250000'),
         Timestamp('2015-03-07 17:58:52.737000'),
         Timestamp('2015-06-26 00:56:36.210000'),
         Timestamp('2015-06-22 20:16:10.743000'),
         Timestamp('2015-06-29 11:35:36.807000')],
    'time2': [
         Timestamp('2015-06-25 20:42:43.830000'),
         Timestamp('2015-03-07 11:57:10.557000'),
         Timestamp('2015-02-07 14:32:33.090000'),
         Timestamp('2015-04-07 11:51:59.090000'),
         Timestamp('2015-06-27 19:47:40.270000'),
         Timestamp('2015-06-30 19:48:22.090000'),
         Timestamp('2015-02-07 17:37:40.700000'),
         Timestamp('2015-07-20 12:57:06.343000'),
         Timestamp('2015-03-07 18:06:23.977000'),
         Timestamp('2015-06-26 00:56:36.210000'),
         Timestamp('2015-06-22 20:16:10.743000'),
         Timestamp('2015-06-29 11:55:01.690000')]})


text:
Q: Create custom parameters (options) for already existing commands? Recently I 've been wanting to create a custom parameter for pacman.
To elaborate, I have tweaked pacman.conf so that specific packages (linux, linux-firmware, and a couple more) are ignored when I use # pacman -Syu to upgrade all packages - unless they are explicitly mentioned (eg. # pacman -Syu linux linux-firmware).
So what I want now is a parameter to use instead of mentioning each package that is normally ignored.
Summing it up, I want to create a parameter (say --param) so that # pacman -Syu --param be equivalent to # pacman -Syu linux linux-firmware linux-headers ....

*

*Trying to implement this using aliases seems to be impossible (unless I've missed something).

*A parameter to allow upgrading all ignored packages would be welcome, albeit not ideal. It also seems to me that it would be far more difficult to construct.

*I'm currently using bash (and sometimes zsh) - I'm open to suggestions though.

A: First, this is a terrible idea. IgnorePkg is meant to be a temporary measure as it is essentially forcing partial upgrades, not something that is your de facto approach to package management for a rolling release.
Having said that, it would be relatively straightforward to create a function to achieve your goal.
fullupgrade() { pacman -Syu $(awk -F= '/^IgnorePkg/ {print $NF}' /etc/pacman.conf) ; }


text:
Q: Is there an a website to calculate the Gauss-Jordan Elimination in Finite fields GF(p)? Is there  an a website   to  calculate the   Gauss-Jordan Elimination  in Finite fields GF(p) ?

A: Yes, Wolfram Alpha will do it: an example.


text:
Q: c assign function pointer to variable I have two functions,
//virDomain is some struct
int virDomainCreate(virDomain*);
int virDomainDestroy(virDomain*);

How do I assign these two functions to a variable?
I tried,
int (*func)(virDomain*) = NULL;
func = virDomainCreate(virDomain*); // not working
func = &virDomainDestroy(virDomain*); //not working

Thanks for all your help!
Waka.

A: You can just assign the pointer to the function like:
func = &virDomainCreate;

Or you can just use the short format:
func = virDomainCreate;

A: The return type is int so
int func;
func = virDomainCreate(virDomain*);
func = virDomainDestroy(virDomain*);

will work.


text:
Q: XGboost and XGb.DMatrix am getting this error when using XGBoost in R
Error in xgb.DMatrix(data, label = label, missing = missing) :
  'data' has class 'character' and length 1791.
  'data' accepts either a numeric matrix or a single filename.

Below is the code am running
#importing the dataset
XGBoostDataSet_Hr_Admin <- read.csv("CompletedDataImputed_HR_Admin.csv")

#Use factor function to convert categorical data to numerical data
XGBoostDataSet_Hr_Admin$Salary = factor(XGBoostDataSet_Hr_Admin$Salary, levels =c('L','M', 'H', 'V'), labels =c(1,2,3,4))

#split the data in train dataset and test dataset

#fitting XGBoost to the Training Test
library(xgboost)
classifier = xgboost(data = as.matrix(training_set[-10]), label = training_set$Employee_Turnover, nrounds = 10)

A: I have been able to resolve the issue, i needed to added the as.numeric when converting categorical values to numerical values


text:
Q: вопрос про lastIndexOf кто-нибудь может мне объяснить как это работает? какая здесь логика? почему равенство с position выдает уникальные элементы? спасибо

const a = [1, 9, 2, 2, 3, 4, 1, 7, 8, 0, 9, 0, 1, 5, 3];

const b = a.filter(function(item, position, array) {
  return a.lastIndexOf(item) === position;
});
console.log(a); // [1, 9, 2, 2, 3, 4, 1, 7, 8, 0, 9, 0, 1, 5, 3]
console.log(b); // [2, 4, 7, 8, 9, 0, 1, 5, 3]

A: Метод filter() создаёт новый массив со всеми элементами, прошедшими проверку, задаваемую в передаваемой функции. Это значит, что если внутри функции какое-то условие вернёт true, то элемент попадёт в результирующий массив. Пример.

let array = [1,2,3,4,5];
let result = array.filter((el, index) => index === 0 || index === array.length - 1);
console.log(result);

В результат попали элементы, которые стоЯт на по индексу 0 или на последнем месте. Их, очевидно, всего два.
lastIndexOf возвращает последний индекс, по которому данный элемент может быть найден в массиве. Очевидно, что такой индекс может быть только один (вариант, когда ничего не найдено - не рассматриваем). Всегда один.
Допустим есть массив [0, 0, 0, 0, 0, 0]. lastIndexOf в этом массиве всегда будет возвращать нам 5. А filter нам вернёт только тот элемент у которого 5 === position (index). Получается, что у нас 6 итераций такого вида:
return 5 === 0
return 5 === 1
return 5 === 2
return 5 === 3
return 5 === 4
return 5 === 5

Из всех условий подойдёт только последнее и вернётся только тот ноль, что стоИт на позиции 5. Другие - не пройдут.
Тоже самое можно рассматривать с любыми числами в любом массиве

A: Просто доказательство от обратного:
Пусть утверждение "равенство с position выдает уникальные элементы" - неверное. Тогда у нас в результирующем массиве есть 2 элемента с одинаковым значением x. Это значит, что в исходном массиве были хотябы 2 x, но очевидно на разных позициях
Т.к. мы ищем наибольшую позицию, где находится x, то очевидно такая позиция единственная, следовательно может быть всего 1 x, который находится на данной позиции, следовательно 2 x не могли пройти проверку, следовательно в результирующий массив попадёт только 1 из них, следовательно в результирующем массиве 1 x
А это противоречит этому Тогда у нас в результирующем массиве есть 2 элемента с одинаковым значением x, значит исходное утверждение "равенство с position выдает уникальные элементы" - неверное - неверное, значит утверждение равенство с position выдает уникальные элементы - верное


text:
Q: TRIRIGA Installation error - the installer cannot determine the status of WebSphere During Tririga installation over WebSphere, in the step of WebSphere configuration, then next, it will try to connect to WebSphere using serverStatus.bat but the result is:
" WebSphere Server Status
The installer cannot determine the status of WebSphere, or WebSphere is not in the STARTED state.
WebSphere should be started at this point, please click back and try again once WebSphere has started.
If WebSphere is started, please make sure the username and password are correct.
The command that was run to determine was:
[-WebSphere path-\serverStatus.bat, SERVERNAME, -username, admin, -password, password, -profileName, TRIRIGA]  "

*

*WebSphere is started, I am able to login and browse the UI.

*User name and password are correct, as I am copying and pasting them on the Tririga installation Wizard.

*If a run this command from cmd, I get no output nor error message.

Please advise :)

A: I found that, I was copying the password from Excel (copying the entire cell instead of the cell content), and my theory is that clipboard had a carriage return and the installer took that character and thus password validation was failing.


text:
Q: JQUERY Mobile: Dynamic append list not working Im new to Jquery Mobile and I have some issues with the following.
What I try to build is:
- Have a button. When I click on the button a popup will be showned
- In the popup you can enter some input and submit by pressing the button.
- After that, what has been entered should be added to the list.

What happens is the following:
- When you press the button, the popup is shown
- You can enter a value in the input and submit. This works as expected.
- After that I see that the value is added twice to the list and then the page refresh and the items disappear from the list.
- After I used the button to show the popupbox, the button is not working again.

So I have the following questions:
- Why is the input added twice to the list?
- Why is my page refreshing and removes the list item that just is added?
- Why is my button not working when I used it 1 time?

I have read many hours on the internet and tried a lot, but I don't know what I am doing wrong.

Hereby the code:
    <!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1">
    <title>Test App</title>
    <link rel="stylesheet" href="themes/Bootstrap.css">
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.0/jquery.mobile.structure-1.4.0.min.css" />
    <link rel="stylesheet" href="themes/jquery.mobile.icons.min.css" />

    <link rel="apple-touch-icon-precomposed" href="apple-touch-icon.png">

    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="apple-touch-icon.png">

    <link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

    <link rel="shortcut icon" href="apple-touch-icon.png">

Test App

Personenlijst

            Persoon Toevoegen

                    <form>

Voer persoonsnaam in

                    Persoon:
                    <input id="persoon" name="persoon" value="" type="text" data-theme="a" placeholder="persoon">
                    <button type="submit" id="submit" data-theme="b" data-icon="check">Persoon Toevoegen</button>

                    </form>

Many thanks for your help!
regards,
Victor

A: You are using submit button hence form getting submitted and page reloading. This is causing your page to refresh.
Change button type to type="button"
<button type="button" id="submit" data-theme="b" data-icon="check">
  Persoon Toevoegen
</button>

Keep your script inside document.ready, this will ensure that all DOM structure is ready before assigning any event handler


text:
Q: Is it possible to make Paypal payment after 29 days of of capturing buyer credentials My requirement is Buyer will authorize payment through credit card or express checkout via Paypal. Initially balance will not get deducted. after 29 days balance automatically deducted if he not canceled the transaction.
I have Two payment option one is Paypal express checkout and another is Paypal pro credit card processing.
Currently Instant payment using both payment options is working fine in my system. I just want to delay the payment for 30 days. Please someone help me if it is possible.

A: You need to use this - Billing plans


text:
Q: I am new to virtual environments and successfully installed virtualenv-win through CMD....aslo created an environment named ( Samim ) After creating the environment I accidently closed cmd.
now I want to reopen the ( Samim ) environment but cant find the command to reopen it , please help me.
I tried to check if that envionment existed or nor by typing "lsvirtualenv"
it returned
dir /b /ad "C:\Users\User\Envs"
================================================
Samim

So it is present in the system , how can I activate this env ?

A: You can activate the virtual environment in a Windows command prompt with:
workon envname
So you can change the directory with:
cd "C\Users\User\Envs"
and then write:
workon Samim

A: For activating a virtualenv in windows direct you cmd to the folder containing the environment and type the following command
environment_name\Scripts\activate

Remember to cd to the folder containing the Env one


text:
Q: MIPS: "lw" instruction path From lecture notes:

from what I understand, doesn't the black dots indicate the binary bits is being copied to both paths moving forward?
For example, instruction bits I[20-16] should be going into the Read register 2 and Write register. It's just that in the end, the Read data 2 is not being used due to the MUX selecting 1.
Did my prof choose not to draw the red lines going to the Read register 2 path just to emphasize on the most significant path? Or does the black dot before Read register 2 have the ability to close off irrelevant data path?

A: Your professor is only highlighting the paths that affect the result. This is normal -- if every path that contained data were highlighted, everything would be red.


text:
Q: HTTP2 PING frames over AWS ALB (gRPC keepalive ping) I'm using AWS Application Load Balancer (ALB) to expose the ASP.NET Core gRPC services. The services are running in Fargate containers and expose unsecured HTTP ports. ALB terminates the outer TLS connection and forwards the unencrypted traffic to a target group based on the route. The gRPC application has several client streaming endpoints and the client can pause the streaming for several minutes. I know that there are HTTP2 PING frames, which can be used in such cases, to keep alive the connection that has no data transmission for some amount of time.
The gRPC server is configured to send HTTP2 pings every 20 seconds for keeping the connection alive. I tested this approach and it works, the ping frames went from the server and were acknowledged by the client.
But this approach fails when it comes to ALB. During the transmission pauses, I don't see any packages from the server behind the load balancer (I use Wireshark). Then after the timeout of 1 minute, the ALB resets the connection.
I tried to use client-sent HTTP2 pings as well. But the connection also resets in 1 minute and I have no evidence whether these ping packages actually reached the server behind the ALB.
I have an assumption that AWS ALB doesn't allow such packets to pass over it, but I didn't find any documentation that proves it.

A: ALB forwards requests based on HTTP protocol semantics, and not raw HTTP/2 frames. Therefore something like ping frames will only apply for one of the hops.
If you want an end to end ping, you could define a gRPC API which is performing the ping. For server to client you would be required to use a server side streaming APIs. But it might actually be preferrable to let the clients start the pings, to reduce the worker the server has to perform.

A: The AWS support team responded to my ticket and the short answer is ALB does not support the HTTP2 ping frames. They suggested increasing the value of idle timeout on the load balancer, but this solution may be not applicable in some cases.
As Matthias247 already mentioned, the possible workaround is to define a gRPC API for the purpose of doing a ping.

A: Since ALB does not support the HTTP2 ping frames. A straightforward way to solve it is to use a custom PING message.
I think you can get another new stream to send messages when the current stream is closed by ALB due to idle timeout (without messages within idle time)
When idle timeout of ALB, the RST_STREAM message with ErrCode=PROTOCOL_ERROR will be sent from ALB to client-side. The client could handle this error in sender and receiver and then get another new stream to send new messages to reuse the http2 connection.
Here are the sample codes with gRPC-go
    conn, errD := grpc.Dial(ServerAddress,
        grpc.WithTransportCredentials(cred),
        grpc.WithConnectParams(grpc.ConnectParams{MinConnectTimeout: time.Duration(63) * time.Second}),
        grpc.WithKeepaliveParams(keepalive.ClientParameters{
            Time:                time.Second * 20,
            Timeout:             time.Second * 3,
            PermitWithoutStream: true,
        }))

    if errD != nil {
        log.Fatalf("net.Connect err: %v", errD)
    }
    defer conn.Close()

    grpcClient := protocol.NewChatClient(conn)
    ctx := context.Background()
    stream, errS := grpcClient.Stream(ctx, grpc.WaitForReady(true))
    if errS != nil {
        log.Fatalf("get BidirectionalHello stream err: %v", errS)
    }

    for i := 0; i < 200; i++ {
        err := stream.Send(
            // some message
        })
        if err != nil {
            if err == io.EOF {
                // get anothe stream to send new message on sender
                stream, errS = grpcClient.Stream(ctx, grpc.WaitForReady(true))
                if errS != nil {
                    log.Fatalf("get  stream err: %v", errS)
                }
            } else if s, ok := status.FromError(err); ok {
                switch s.Code() {
                case codes.OK:
                    // noop
                case codes.Unavailable, codes.Canceled, codes.DeadlineExceeded:
                    return
                default:
                    return
                }
            }
        }

        go func() {
            for {
                res, errR := stream.Recv()
                if errR != nil {
                    if errR == io.EOF {
                        log.Printf("stream recv err %+v \n", errR)
                    }

                    // get anothe stream to send new message on receiver
                    stream, errS = grpcClient.Stream(ctx, grpc.WaitForReady(true))
                    if errS != nil {
                        log.Fatalf("in recv to get stream err: %v", errS)
                    }
                    return
                }

                log.Printf("recv resp %+v", res)
            }
        }()

        // over the idle timeout of alb (60 seconds)
        time.Sleep(time.Duration(61) * time.Second)
    }

To view the details of gRPC message, you could run it through GODEBUG=http2debug=2  go run main.go


text:
Q: Error proyecto/solucion de Visual Studio "No se pueden cargar 2 o mas puntos de interrupción" En cualquier versión Visual Studio (tengo 17 y 19) cuando cierro y abro de nuevo se pierden los archivos "abiertos" que he estado trabajando (el contenido si lo guarda), los puntos de interrupción también se pierden y el proyecto que arranca de inicio vuelve hacer el default (el primer proyecto en la solución que cree), que aunque no es un problema grave es molesto y tardado cuando trabajo para realizar otras actividades, ¡ayuda!.

A: revisa los siguiente en el menú (lo pongo en inglés ya que así tengo mi Visual studio) : Tools/Options/Environment/Startup en la parte At Startup verifica que no tengas establecido Empty environment


text:
Q: How to pass onComplete a variable containing a function name for Ajax class Mootools Ajax class has a onComplete parameter whereby you can pass a function name to it and it would call that function when it completes (obvious).
http://docs111.mootools.net/Remote/Ajax.js
I want to be able to pass a variable containing the said function instead. How do I go about doing that? My attempt can be seen below.
/*
 * This way works
 */
var TestClass = new Class({

    myRequest: function()
    {

        $aj = new Ajax(urle, {

          method: 'get',
          update: $('update_div'),
          onComplete: this.testFunctionA

        }).request();

    },

    testFunctionA: function()
    {
        alert('Yo');
    }

});

/*
 * This way doesn't
 */
var TestClass = new Class({

    myRequest: function()
    {

        var updateFunction = 'this.testFunctionA';

        $aj = new Ajax(urle, {

          method: 'get',
          update: $('update_div'),
          onComplete: updateFunction

        }).request();

    },

    testFunctionA: function()
    {
        alert('Yo');
    }

});

A: Your updateFunction variable holds a string.
You need it to hold the function itself, like this:
var updateFunction = this.testFunctionA;


text:
Q: how can i avoid having to get data very time i change view in angularjs i am new to angular and a bit of a novice generally. any examples i have looked at seem to use a service to request a collection in a controller for a view and attach it to the scope for that controller. when you change view and hence controller the controller is destroyed and therefore when you go back into the view you have to request the data for the view again. this seems like a lot of uneccessary fetching of the same data.
also say there were many records in my collection it could take a while to make this request and slow the loading of the data. say for example you had a a calander app with a week view and an average of 30 events a week, the collection for a year would have 1500 events would you fetch the events for the week in view and then fetch the rest of the events after that and how would you go about doing this. or would you just fetch the events for each week as you incremented the week. apologies for the lack of code but i havent written it yet as i am trying to figure out how i should write it.


text:
Q: Numbering references in the order they appear in dcu-style natbib I am using the natbib package with the dcu style and my bibliography is displayed in alphabetical order. I was wondering if it is possible to change that and to number my references in the order where they appear in the text instead without changing the style? This style matches exactly the requirements I have and I don't really want to rewrite my whole bibliography to get kind of the same result using the unsrtnat style...
\usepackage[square,numbers,sort&compress]{natbib}
\bibliographystyle{dcu}

A: I suggest you proceed as follows:

*

*Find the file dcu.bst in your TeX distribution. Make a copy of this file and call the copy, say, dcu-nosort.bst.

*Open the file dcu-nosort.bst in a text editor.

*Comment out all three instances of SORT. In my copy of the bst file, they occur on lines 1239, 1311, and 1344.

*Save the file dcu-nosort.bst either in the directory where your main tex file is located or in a directory that's searched by BibTeX. If you choose the latter method, be sure to update the filename database of your TeX distribution suitably.

*In your main tex file, change the instruction \bibliographystyle{dcu} to \bibliographystyle{dcu-nosort} and perform a full recompile cycle (LaTeX, BibTeX, and LaTeX twice more) to fully propagate all changes.
Happy BibTeXing!


text:
Q: Why does EnumerateMetafile only work with Aero enabled My code enumerates a metafile:
private void Parse()
{
    Graphics graphics = Graphics.FromHwnd(IntPtr.Zero);
    PointF pointf = new PointF();
    graphics.EnumerateMetafile(_metafile, pointf, ParseCallback);
}

private bool ParseCallback(EmfPlusRecordType recordType,
    int flags, int dataSize, IntPtr data, PlayRecordCallback callbackData)
{
    // do stuff
}

My development machine is Windows 7 VirtualBox guest on Ubuntu host.
The code used to work fine. However, when I turned off Aero, the code stopped working: The ParseCallback would never be called.
Only when I turned Aero back on, ParseCallback was executed again.
Why and how can I make this code work on non-Aero-enabled machines?

A: I don't have a full answer to the "why?" question, but it does not work because you're getting the Graphics GDI+ object from the Window handle. Instead, you want to get it from a GDI DC, like this:
private void Parse()
{
    IntPtr hdc = GetDC(IntPtr.Zero); // get entire screen dc
    Graphics graphics = Graphics.FromHdc(hdc));
    PointF pointf = new PointF();
    graphics.EnumerateMetafile(_metafile, pointf, ParseCallback);
    ReleaseDC(IntPtr.Zero, hdc);
}

[DllImport("user32.dll")]
static extern IntPtr GetDC(IntPtr hWnd);

[DllImport("user32.dll")]
static extern IntPtr ReleaseDC(IntPtr hwnd, IntPtr hdc);

Note you could also use the Graphics object from the Form OnPaint(PaintEventArgs e) method, it should also work, just like in the official sample code for EnumerateMetafile method here: Graphics.EnumerateMetafile Method


text:
Q: Parsing parameters from command line with RegEx and PHP I have this as an input to my command line interface as parameters to the executable:
-Parameter1=1234 -Parameter2=38518 -param3 "Test \"escaped\"" -param4 10 -param5 0 -param6 "TT" -param7 "Seven" -param8 "secret" "-SuperParam9=4857?--SuperParam10=123"

What I want to is to get all of the parameters in a key-value / associative array with PHP like this:
$result = [
    'Parameter1' => '1234',
    'Parameter2' => '1234',
    'param3' => 'Test \"escaped\"',
    'param4' => '10',
    'param5' => '0',
    'param6' => 'TT',
    'param7' => 'Seven',
    'param8' => 'secret',
    'SuperParam9' => '4857',
    'SuperParam10' => '123',
];

The problem here lies at the following:

*

*parameter's prefix can be - or --

*parameter's glue (value assignment operator) can be either an = sign or a whitespace ' '

*some parameters may be inside a quote block and can also have different, both separators and glues and prefixes, ie. a ? mark for the separator.

So far, since I'm really bad with RegEx, and still learning it, is this:
/(-[a-zA-Z]+)/gui

With which I can get all the parameters starting with an -...
I can go to manually explode the entire thing and parse it manually, but there are way too many contingencies to think about.

A: You can try this that uses the branch reset feature (?|...|...) to deal with the different possible formats of the values:
$str = '-Parameter1=1234 -Parameter2=38518 -param3 "Test \"escaped\"" -param4 10 -param5 0 -param6 "TT" -param7 "Seven" -param8 "secret" "-SuperParam9=4857?--SuperParam10=123"';

$pattern = '~ --?(?<key> [^= ]+ ) [ =]
(?|
    " (?<value> [^\\\\"]*+ (?s:\\\\.[^\\\\"]*)*+ ) "
  |
    ([^ ?"]*)
)~x';

preg_match_all ($pattern, $str, $matches);
$result = array_combine($matches['key'], $matches['value']);
print_r($result);

demo
In a branch reset group, the capture groups have the same number or the same name in each branch of the alternation.
This means that (?<value> [^\\\\"]*+ (?s:\\\\.[^\\\\"]*)*+ ) is (obviously) the value named capture, but that ([^ ?"]*) is also the value named capture.

A: You could use
--?
(?P<key>\w+)
(?|
    =(?P<value>[^-\s?"]+)
    |
    \h+"(?P<value>.*?)(?<!\\)"
    |
    \h+(?P<value>\H+)
)

See a demo on regex101.com.

Which in PHP would be:

<?php

$data = <<<DATA
-Parameter1=1234 -Parameter2=38518 -param3 "Test \"escaped\"" -param4 10 -param5 0 -param6 "TT" -param7 "Seven" -param8 "secret" "-SuperParam9=4857?--SuperParam10=123"
DATA;

$regex = '~
            --?
            (?P<key>\w+)
            (?|
                =(?P<value>[^-\s?"]+)
                |
                \h+"(?P<value>.*?)(?<!\\\\)"
                |
                \h+(?P<value>\H+)
            )~x';

if (preg_match_all($regex, $data, $matches)) {
    $result = array_combine($matches['key'], $matches['value']);
    print_r($result);
}
?>

This yields

Array
(
    [Parameter1] => 1234
    [Parameter2] => 38518
    [param3] => Test \"escaped\"
    [param4] => 10
    [param5] => 0
    [param6] => TT
    [param7] => Seven
    [param8] => secret
    [SuperParam9] => 4857
    [SuperParam10] => 123
)


text:
Q: Why is the base64 string not showing completely? So this is my code
_image1 = File(pickedImage.path);
List<int> imageBytes = _image1.readAsBytesSync();
String base64Image = base64.encode(imageBytes);
_shcpImg = base64Image;

But when I print the string _shcpImg, it just prints a part of the string, because when I copy and paste that base64 into an online converter, it only shows a really tiny piece of the image. So the thing is that the string is not showing completely or somehow the base64 encoder is not working well.
Any suggestions?

A: From the comments, since you are using VsCode and you can't print the full string (long string)
You can use log from dart: developer,
if the string is REALLY LONG, There is a workaround to fix this, the idea is to divide your long string into small pieces (in the example, 800 length for each piece) using RegExp and then iterate into the result and print each piece.
void printWrapped(String text) {
  final pattern = new RegExp('.{1,800}'); // 800 is the size of each chunk
  pattern.allMatches(text).forEach((match) => print(match.group(0)));
}


text:
Q: Using wait() inside a synchronized block I stumbled upon a piece of code in an Android Service class that has a synchronized block with a wait statement.
The code is as follows:
    public class MyService extends IntentService{

     protected void onHandleIntent(Intent intent){
     synchronized(this){
        try{
           wait(10000);
           }catch(InterruptedException e){
           e.printStackTrack();
         }
        String message = intent.getStringExtra("Message");
        showMessage(message);
       }
      }
    }

Does the above code means that any number of threads can enter the synchronized block? I know that sleep puts the Thread in a Blocked state. Is this the same with a Thread calling wait()?
Basically when I pass a text to the Service, I want the Service to wait for 10 seconds then display the message in the LogCat.
I have never used wait() anytime so could anybody explain to me what the above code is doing?

A: Part of your question deals with multithreading, which is a pretty complicated topic. I recommend starting out with a tutorial like this one to get those answers.
The above code will serve to delay log entries by 10 seconds. However, IntentService only has 1 worker thread, so successive requests will get backlogged if they occur more often than once every 10 seconds.
Because only 1 worker thread is involved, using synchronization is really the wrong answer. Why not ditch the IntentService, and just do all this on the UI thread, using a CountDownTimer?
final String msg = intent.getStringExtra("Message");

new CountDownTimer(10000, 10000) {
    @Override
    public void onTick(long millisUntilFinished) {}

    @Override
    public void onFinish()  {
        showMessage(msg);
    }
}.start();

That way, you can create the appearance of parallel execution, without the complexity of multithreading, by taking advantage of Android's built-in message queueing system.

A: Your statement "any number of threads can enter the synchronized block" is false.
Theoretically, if one thread is inside the synchronized block, this prevents other threads from entering. Which is not possible in the case of IntentService because IntentService uses a single worker thread to handle the workload.
Calling wait() is a thread synchronization method, not a delay method. This is different from calling sleep() which just blocks the thread for a specific amount of time.  When you call wait() this blocks the thread until another thread calls notify(), which is used to coordinate activities among multiple threads. wait(10000) blocks the thread until either notify() is called from another thread OR until the timeout expires (in this case 10 seconds). So this looks like there should be another thread somewhere which is calling notify() on the IntentService object to wake it up.
There is an additional complexity here associated with the use of notify() and wait(). In order to call either of these methods, a lock on the object's monitor must first be obtained (by the use of synchronized). This means that calls to wait() and notify() must be within synchronized blocks or within synchronized methods that are synchronized on the object.
The thread that calls wait() actually releases the lock on the object. This means that the thread is blocked inside a synchronized block/method but it does not have a lock on the object while waiting. Once notify() is called (or the timeout has expired), the thread will regain the lock on the object and continue executing.
For more information about using notify() and wait() in Java, search for these terms and read about it.

This code is pretty convoluted if all it is supposed to do is delay 10 seconds and then write a something to logcat. You could just call sleep() instead of wait() which would not require the synchronized statement. However, as another poster noted, if this Service is called very often, this will create a backlog as each and every call to onHandleIntent() will be delayed by 10 seconds and since there is only 1 worker thread, all calls are serialized. Example: a call to startService() is made at 10:00:00, the entry in the logcat will appear at 10:00:10. If another call to startService() is made at 10:00:01, that entry will not appear in the logcat until 10:00:20, because the second call to onHandleIntent() will not happen until 10:00:10.


text:
Q: How common are probability distributions with a finite variance? It's always very surprising to learn that some of the entities one has been assiduously studying actually represent negligibly tiny minorities (e.g. continuous functions vis-à-vis all functions)...

Now, the Central Limit Theorem, for one, holds only for probability distributions with a finite variance.
How common are such distributions in the space of all probability distributions?

More formally, let $U$ be the set of all probability distributions on $\mathbb{R}$ (say), and $F \subset U$ be the subset of those probability distributions that have a finite variance.  I expect that, of the cardinalities $|F|$ and $|U\setminus F|$, one will be a strictly larger infinity than the other, but I have no intuition as to which.

(I guess this is a "meta-measure theory" question.)

A: I presume that you speak about distributions on the Borel $\sigma$-algebra $\mathcal B(\mathbb R)$. In terms of cardinality, there are quite few of them, namely, $\mathfrak{c} = |\mathbb{R}|$.
Indeed, each probability distribution $\mathcal B(\mathbb R)$ is uniquely determined by its values on the intervals $(-\infty,q)$ with $q\in\mathbb{Q}$. Therefore, the number of probability measures does not exceed the number of sequences of real numbers, which is $\mathfrak{c}$.
Since, obviously, there are both $\mathfrak{c}$ distributions with finite and infinite variance, so your guess is wrong.
There are other ways to compare sets, e.g. in terms of the Baire categories. If we consider the weak convergence topology, then both finite variance and infinite variance sets are easily shown to be second category, so another draw here.
Overall, I see no reason to believe that there are fewer finite variance (or finite expectation or finite exponential moment) distributions than others.


text:
Q: R - Keras Churn Tutorial - Error in py_call_impl(callable, dots$args, dots$keywords) : ValueError: No data provided for "dense_1_input" I have been working through the Keras (Tensorflow) example for Churn Prediction and came across an error with the below line.
Error in py_call_impl(callable, dots$args, dots$keywords) :
  ValueError: No data provided for "dense_1_input". Need data for each key in: ['dense_1_input']

The error I got was
Error in py_call_impl(callable, dots$args, dots$keywords) :
  ValueError: No data provided for "dense_1_input". Need data for each key in: ['dense_1_input']

A: In case anyone else has the problem it can be solved by changing newdata into as.matrix(newdata)
# Setup lime::predict_model() function for keras
predict_model.keras.models.Sequential <- function(x, newdata, type, ...) {
  pred <- predict_proba(object = x, x = as.matrix(newdata))
  data.frame(Yes = pred, No = 1 - pred)
}


text:
Q: Why Unix.tm_hour is the real hour minus one? The current time here is 11:05, If I do Unix.gmtime (Unix.time()), I get
{Unix.tm_sec = 53; Unix.tm_min = 4; Unix.tm_hour = 10; Unix.tm_mday = 19;
 Unix.tm_mon = 5; Unix.tm_year = 113; Unix.tm_wday = 3; Unix.tm_yday = 169;
 Unix.tm_isdst = false}

The Unix.tm_hour=10, but it should be 11, right?
Why it is the real hour minus one?

A: That's because it's summer and UNIX is still using GMT (so will be one hour out once the clocks go forward).

A: You should use Unix.localtime () to get the local time, the time returned by Unix.gmtime will be different from your local time depending on which timezone you are in.


text:
Q: onesignal does not register the playerid on onesignal sever after clicking on the subscribe button I'm using the following code and it generates a player-id but does not create id as a subscriber on the onesignal sever. How can I fix it?
I'm attaching the code and the error.
Error:
PUT https://onesignal.com/api/v1/players/123232-33-44345-1234c-712312 400 ()
index.html:89 Uncaught (in promise) ReferenceError: OneSignalUserSubscription is not defined
    at index.html:89
    at <anonymous>

Code:
<!DOCTYPE html>

<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">

    <link rel="manifest" href="/manifest.json">

OneSingle Testing

    <button id="subscribe" class="button" onclick="subscribeOneSignal()">Subscribe </button>
    <button id="unsubscribe" class="button" onclick="unSubscribeOneSignal()">Unsubscribe </button>

A: You should use the browser console to see what the response body is in the 400 error response. This should have an explanation for what's causing the 400 error.
Separately, you are calling a function named OneSignalUserSubscription but this function is not defined in your code, which is why you're getting the ReferenceError.


text:
Q: Required css rule to obtain the required result I am working on a layout which required the result in the fiddle below:
http://jsfiddle.net/Kosenshi/a8n52Lkk/

Foo

Bar
Hello World

CSS:
.c1, .c2, .c3 {}

But the problem is neither I can include additional class nor I can treat three classes separately is there any way to obtain the result.
Thanks

A: I don't know if this is exactly what you wanted  try display

div{
    display:inline-block;
}
span{
    display:block;
}

Foo

Bar
Hello World


text:
Q: How to make an agent/turtle not see through multiple walls? (Netlogo) I am new to posting in stackoverflow.
Before I had a problem with agents/turtles seeing through the walls I make, but I have found the solution here:
Not see through the walls
The problem now is when there is another wall within the vision-cone, the valid line of sight (green patches) are incorrect. I'm currently still tinkering on how to fix this.
Here is my current code that I have been working on,
breed [walls wall]
walls-own [first-end second-end]

to setup
  ca
  reset-ticks
  set-default-shape walls "line"
  crt 1 [setxy 4 0]
  ask turtles [facexy 0 0]

  ;color all cones in radius blue by default
  let dist 10
  let angle 80
  ask turtles [ask patches in-cone dist angle [set pcolor blue]]

  ;; place a wall down.... the line of sight is blocked (keyword: line)
  create-walls 1 [setxy 0 0]

  ;;This is an interpretation of a wall. Two points that define the edges.
  ask wall 1 [set size 10]

  ;;my wall is vertical. you can do trig above and below to adjust for not vert lines.
  ask wall 1 [set heading 45]
  ask wall 1 [set color hsb 216 50 100]

  ;; I made it so that it could consider not vertical lines
  ask wall 1 [ set first-end (list (round (sin heading * (size / 2))) (round (cos heading * (size / 2))))]
  ask wall 1 [ set second-end (list (round((-1 * (size / 2) * sin heading))) (round ((-1 * (size / 2) * cos heading))))]

  ;;Test wall. UN-COMMENT THE SET BELOW TO SEE THE PROBLEM
;  create-walls 1 [setxy 4 4]
;  ask wall 2 [set size 10]
;  ask wall 2 [set heading 90]
;  ask wall 2 [ set first-end (list (round (sin heading * (size / 2))) (round (cos heading * (size / 2))))]
;  ask wall 2 [ set second-end (list (round((-1 * (size / 2) * sin heading))) (round ((-1 * (size / 2) * cos heading))))]
;  ask wall 2 [set color hsb 216 50 100]

  ask turtle 0 [ask in-sight dist angle [set pcolor green]]
end

;;a turtle can see a patch if the line from the patch to the trutle isnt intersected by a wall.
to-report in-sight [dist angle]
  let turtle-x xcor
  let turtle-y ycor

  report patches in-cone dist angle with
  [
    not any? walls with [intersects [pxcor] of myself [pycor] of myself turtle-x turtle-y ;; line 1
      (first first-end)(last first-end)(first second-end)(last second-end)] ;; line 2
  ]
end

to-report counter-clockwise [x1 y1 x2 y2 x3 y3]
  ;; returns true if triplet creates counter clockwise angle (uses slopes)
  ;; (C.y-A.y) * (B.x-A.x) > (B.y-A.y*(C.x-A.x)
  report (y3 - y1)*(x2 - x1)>(y2 - y1)*(x3 - x1)
end

to-report intersects [x1 y1 x2 y2 x3 y3 x4 y4]
  ;; line 1: x1 y1 x2 y2
  ;; line 2: x3 y3 x4 y4
  ;;DANGER: Doesnt work for colinear segments
  report (counter-clockwise x1 y1 x3 y3 x4 y4) != (counter-clockwise x2 y2 x3 y3 x4 y4)
  and (counter-clockwise x1 y1 x2 y2 x3 y3) != (counter-clockwise x1 y1 x2 y2 x4 y4)
end

This is what it looks like if you would uncomment the set of code for the test wall.
Problem
Any suggestions or tips would be very helpful!
Thank you in advance.


text:
Q: installing comicsans to TeX Live, Windows I need help to install the comicsans package and the fonts. My system is TeX Live 2011, and Windows 7. Below is what I did:

*

*Copied comic.ttf and comicbd.ttf in
C:\texlive\texmf-local\fonts\ttf. (I created the ttf directory.)

*Copied dvips, tfm, and vf directories from the comicsans.zip to C:\texlive\texmf-local\fonts.

*Ran mktexlsr to update the file name database.

*Copied comicsans.dtx and comicsans.ins in C:\texlive\texmf-local\tex\latex\comicsans. (I created the comicsans directory.)

*Ran tex comicsans.ins in C:\texlive\texmf-local\tex\latex\comicsans.

*Ran mktexlsr to update the file name database.

*Ran updmap-sys --enable Map=comicsans.map.

*Ran mktexlsr to update the file name database.
Using TeXworks, I tested it with:
\documentclass{article}
\usepackage{comicsans}
\renewcommand{\sfdefault}{comic}

\begin{document}
This is a text.
\end{document}

and it did not work. No font change, no error message.
Did I make any mistake, or miss any step? I believe some of the above steps are unnecessary, which one?

A: Your steps for installing the font appear to be correct. You get no font change in your sample document because you're defining ComicSans as the default "sans serif" font, but you aren't choosing that font family.
\begin{document}
Somebody would say that this \textsf{Hello world} printed
with a fancy font is awful.
\end{document}

If you want the font to be used throughout the document, redefine \rmdefault or say
\usepackage{comicsans}

This regards the technical part. Now a comment.
Don't use ComicSans other than for strips or particular short text. It's not a font designed for continuous reading and it will probably annoy your audience during a presentation or, in the worst case, make them laugh.


text:
Q: How do I integrate tabs into android preference I want to have a List Preference with 3 tabs (3 lists) inside it. I think none of android default preference (ListPreference, CheckBoxPreference, RingtonePreference etc.) supports tabs. I think I will need to write a custom preference for this.
I know for writing tabs you need to extend TabActivity but I am not getting how to do it for custom preference. Please help?
I need something like a CustomListPreference which contains 3 tabs each containing a list of options. User can select one item out of these 3 lists. How to achieve this?

A: You could build a Tabbed view (extending TabActivity) in which each of your tab activity is a PreferenceActivity.


text:
Q: Different languages in headings I am using babel with Greek and English languages. I don't use XeLaTeX. I have the following configuration for the header:
\usepackage{fancyhdr}
\renewcommand{\chaptermark}[1]{\markboth{#1}{}}
\renewcommand{\sectionmark}[1]{\markright{#1}}
\pagestyle{fancy}
\fancyhf{}
\fancyhead[LE,RO]{\thepage}
\fancyhead[LO]{\itshape\nouppercase{\rightmark}}
\fancyhead[RE]{\itshape\nouppercase{\leftmark}}
\renewcommand{\headrulewidth}{0.5pt}
\renewcommand{\footrulewidth}{0pt}
\setlength{\headsep}{10pt}

The problem is that I have some title text with both languages and it is not expanding correct in the headers.
Example: \section{\texorpdfstring{Η Συσκευή \eng{Kinect}}{}} and the result is H Συσκευή Κινεςτ
\documentclass[12pt, a4paper]{book}

\usepackage[T1]{fontenc}
\usepackage{ucs}
\usepackage[utf8x]{inputenc}
\usepackage[english, greek]{babel}

%Fonts
\usepackage[version=3]{mhchem}

%Hyper reference
\usepackage[unicode]{hyperref}

%headings
\usepackage{fancyhdr}
\renewcommand{\chaptermark}[1]{\markboth{#1}{}}
\renewcommand{\sectionmark}[1]{\markright{#1}}
\pagestyle{fancy}
\fancyhf{}
\fancyhead[LE,RO]{\thepage}
\fancyhead[LO]{\itshape\nouppercase{\rightmark}}
\fancyhead[RE]{\itshape\nouppercase{\leftmark}}
\renewcommand{\headrulewidth}{0.5pt}
\renewcommand{\footrulewidth}{0pt}
\setlength{\headsep}{10pt}

%Commands
\newcommand{\eng}[1]{\selectlanguage{english}#1\selectlanguage{greek}}
\newcommand{\gre}[1]{\selectlanguage{greek}#1\selectlanguage{english}}

\newcommand{\en}{\selectlanguage{english}}
\newcommand{\gr}{\selectlanguage{greek}}

\begin{document}

\section{\texorpdfstring{Η Συσκευή \eng{Kinect}}{}}
Δοκιμή

\end{document}


text:
Q: Bourbon Neat @include row(table) function Please help.
I'm using Bourbon Neat 1.7 and trying to add and display a second row.
All the info currently displayed shows on one line, should be 2 lines.
My plan is to attach a record set and display the records, line by line.
My scss code
.third {
    @include outer-container;
    background-color: #afa;

    .alpha3 {
        @include fill-parent();
        @include row(table);
        margin-bottom: 0;
        padding: 0;
        background-color: #aaf;

        .aside3 {
            @include span-columns(4);
            @include pad();
            border: 1px solid black;
            background-color: #faa;
        }

        .article3 {
            @include span-columns(8);
            @include pad();
            @include reset-display;
            background-color: #faa;
        }
    }
}

HTML code

div class third

1st Col 1st row

2nd Col 1st row

1st Col 2nd row

2nd Col 2nd row

A: In table display, the row element becomes a table (in this case .alpha3), effectively trying to fit all its children without wrapping (tables don't wrap).
You should create an additional .alpha3 element to host the second row.

div class third

1st Col 1st row

2nd Col 1st row

1st Col 2nd row

2nd Col 2nd row


text:
Q: Trying to save value from ajax/jquery submit form in database I have CSS Pie chart which when I click on one of the pies, it opens a simple submit form.
The problem is that when I click submit button nothing goes into the database. Just shows thank you message and this is it. Nothing in the console.
I have put the pie chart front part here: https://jsfiddle.net/096hgmqd/. When you click on Button 1 it opens the form below.
Here is the jquery/ajax part

And the PHP part - submit.php
$connect = new PDO("mysql:host=localhost;dbname=MYDBNAME", "DBUSERNAME", "DBPASSWORD");
$message = '';
if(isset($_POST["saveAnswers"])) {
    $query = "INSERT INTO clarity (name) VALUES (:name)";

    $user_data = array( ':name'  => $_POST["name"] );

    $statement = $connect->prepare($query);

    if($statement->execute($user_data)) {
        $message = '
 Registration Completed Successfully
';
    } else {
        $message = '
 There is an error in Registration
';
    }
}

Can anyone help here?
UPDATE: current code:
$( document ).ready(function() {
    $('form').on('submit',function(e){
    e.preventDefault();
        $.ajax({
                url: "submit.php",
                type: "POST",
                data: formData,
                contentType: false,
                cache: false,
                processData:false,
                success: function(data) {
                    if(data.result == 'success') {
                         $("#loadingmessage").hide();
                         $("#sucessmsg").show();
                    } else if(data.result == 'error') {
                         $("#loadingmessage").hide();
                         $("#errormsg").show();
                    }
                },
                error: function(){}
        });
    });
});

And PHP
if(isset($_POST["saveAnswers"]))
{
    sleep(5);
    $query = "INSERT INTO clarity (name) VALUES (:name)";

    $user_data = array(
      ':name'  => $_POST["name"]
    );
    $statement = $connect->prepare($query);
    $response = 'error';
       if($statement->execute($user_data)) {
         $response = 'success';
       }
       echo json_encode(array('result' => $response));
    }

HTML form
  <form class="form-wrapper" action="" method="post" id="submitForm1">
    <fieldset class="section is-active">

What is your name?

      <input type="text" name="name" id="name" placeholder="Your Name">
      <button type="submit" class="button" name="saveAnswers" id="saveAnswers">Submit</button>
    </fieldset>
  </form>

A: you need to submit your form.Your ajax request will fire as soon as the page loads not on form submit.
$('form').on('submit',function(e){
e.preventDefault();
$.ajax({
        url: "submit.php",
        type: "POST",
        data: formData,
        contentType: false,
        cache: false,
        processData:false,
        success: function(data) {
            if(data == 'success') {
                $("#loadingmessage").hide();
                $("#sucessmsg").show();
            }
            if(data == 'error') {
                $("#loadingmessage").hide();
                $("#errormsg").show();
            }
        },
        error: function(){}
});
});

A: For the DB problem, you first need to fix the communication between PHP and JS. Also, you can debug the data with console.log(form) in JS. You can also debug at the server-side, you can return the debugging data, especially the $_POST like this:
$debug = var_export($_POST, true);
echo json_encode(array('debug' => $debug);

And you can view the response in the Developer Console of your browser, to see whether the information is received by the PHP or not.

Your PHP does not return anything. You just saved the output to a variable named $message. In your jQuery AJAX call, you expect there are some data returned, either success or error, but your PHP script does not provide these.
Try to change the PHP if-else clause to:
$response = 'error';
if($statement->execute($user_data)) {
    $response = 'success';
}
echo json_encode(array('result' => $response));

and add the following line to the very first line of PHP:
header('Content-Type: application/json');

Last, in your jQuery call, change the if-else clause in the success handler to:
if(data.result == 'success') {
     $("#loadingmessage").hide();
     $("#sucessmsg").show();
} else if(data.result == 'error') {
     $("#loadingmessage").hide();
     $("#errormsg").show();
}

A: You have mentioned that you don't see anything on the Network tab. This means that there is "no connection" between your Ajax/jQuery and PHP parts and I believe that the actual problem is in your Ajax part. You can try like this. (I have tested it and it works just fine).
HTML part

Form data sent.

<form class="form-wrapper" action="" method="post" id="submitForm1">
   <fieldset class="section is-active">

What is your name?

      <input type="text" name="name" id="name" placeholder="Your Name">
      <button type="submit" class="button" name="saveAnswers" id="saveAnswers">Submit</button>
   </fieldset>
</form>

Ajax part


text:
Q: How to sort posts with the first 2 or 3 by latest, and the rest is random? I'm trying to sort my posts in the way I stated in the title.
What's the simplest way to do this?
I know how to change the order by object using the pre_get_post hook. But how can I use it to get what I need?
EDIT:
here's my code so far
add_action('pre_get_posts', 'filter_category_orderby');

function filter_category_orderby($query){
if($query->is_category()){

    $query2 = $query;
    $query->set('orderby','rand');

    $wp_query = new WP_Query();
    $wp_query->posts = array_merge( $query2->posts, $query->posts );

    $wp_query->post_count = $query1->post_count + $query2->post_count;
    $query = $wp_query;
 }
}

This is the idea, but i can't seem to make it work like i want it to.
got the idea from here

A: EDIT: Here is the correct answer...
<!-- RECENT BLOG POSTS -->
<?php
$recentargs = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'category_name' => 'social-grid',
    'posts_per_page' => $number_of_recent_posts,
    'orderby' => 'post_date',
    'order' => 'DESC'
);
$rec_arr_posts = new WP_Query( $recentargs );

if ( $rec_arr_posts->have_posts() ) :

    while ( $rec_arr_posts->have_posts() ) :
        $rec_arr_posts->the_post();
    ?>

        <?php get_the_post_thumbnail_url(); ?>
        <?php the_permalink(); ?>
        <?php the_title(); ?>
        <?php echo get_the_excerpt(); ?>

    <?php endwhile; ?>

<?php endif; ?>
<?php wp_reset_postdata(); ?>
<!-- END RECENT BLOG POSTS -->

<!-- RECENT EXCLUDED POSTS -->
<?php
$recenttoexcludeargs = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'category_name' => 'social-grid',
    'posts_per_page' => $number_of_recent_posts,
    'orderby' => 'post_date',
    'order' => 'DESC'
);
$recent_to_exclude_arr_posts = new WP_Query( $recenttoexcludeargs );

if ( $recent_to_exclude_arr_posts->have_posts() ) {
    $posts_ids = wp_list_pluck( $recent_to_exclude_arr_posts->posts, 'ID' );
} ?>
<!-- END RECENT EXCLUDED POSTS -->
<!-- RANDOM BLOG POSTS -->
<?php
$randomargs = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'category_name' => 'social-grid',
    'posts_per_page' => $number_of_random_posts,
    'post__not_in' => $posts_ids,
    'orderby' => 'rand',
    'order' => 'DESC'
);
$rand_arr_posts = new WP_Query( $randomargs );

if ( $rand_arr_posts->have_posts() ) :

    while ( $rand_arr_posts->have_posts() ) :
        $rand_arr_posts->the_post();
    ?>

        <?php get_the_post_thumbnail_url(); ?>
        <?php the_permalink(); ?>
        <?php the_title(); ?>
        <?php echo get_the_excerpt(); ?>

    <?php endwhile; ?>

<?php endif; ?>
<?php wp_reset_postdata(); ?>

You need to set the variables $number_of_recent_posts & $number_of_random_posts.
P.S - where do you work? - I am coming for your job c:


text:
Q: ¿Por qué entra dos veces al form_valid de mi FormView? Al presionar el boton que envia el formulario me está entrando dos veces al form_valid del FormView, este error me esta pasando solo con los formularios que utilizan modales(Estoy usando django-bootstrap-modal-forms). Al ser valido el formulario estoy enviando un correo que también se envía doble.
Este es el botón que llama al modal


text:
Q: How to get a response in HAL-Format with Spring-Hateoas Basically i have the same issue like the member who posted this question
When i request a single user in my Application, i get the response in the HAL-format, like i wish
http://localhost:8080/api/v1/users/25 with GET:
{
"userId": "25",
"firstname": "Beytullah",
"lastname": "Güneyli",
"username": "gueneylb",
"_links": {
"self": {
  "href": "http://localhost:8080/api/v1/users/25"
 },
"roles": [
  {
    "href": "http://localhost:8080/api/v1/roles/33"
  },
  {
    "href": "http://localhost:8080/api/v1/roles/34"
  }
 ]
 }
 }

But, when i request all users , i get the response in non-HAL-Format, like this:
http://localhost:8080/api/v1/users with GET:
[...

{
"userId": "25",
"firstname": "Beytullah",
"lastname": "Güneyli",
"username": "gueneylb",
"links": [
  {
    "rel": "self",
    "href": "http://localhost:8080/api/v1/users/25"
  },
  {
    "rel": "roles",
    "href": "http://localhost:8080/api/v1/roles/33"
  },
  {
    "rel": "roles",
    "href": "http://localhost:8080/api/v1/roles/34"
  }
]
},

...]

Here are my methods:
@RequestMapping(value = "users", method = RequestMethod.GET, produces = MediaTypes.HAL_JSON_VALUE)
public List<UserResource> list() throws MyException, NotFoundException {
    List<User> userList= userRepository.findAll();
    List<UserResource> resources = new ArrayList<UserResource>();
    for (User user : userList) {
        resources.add(getUserResource(user));
    }
    if(userList == null)
        throw new MyException("List is empty");
    else
        return resources;
}

@RequestMapping(value = "users/{id}", method = RequestMethod.GET)
public UserResource get(@PathVariable Long id) throws NotFoundException {

    User findOne = userRepository.findOne(id);
    if (findOne == null){
        log.error("Unexpected error, User with ID " + id + " not found");
        throw new NotFoundException("User with ID " + id + " not found");
    }
    return getUserResource(findOne);
}

private UserResource getUserResource(User user) throws NotFoundException {
    resource.add(linkTo(UserController.class).slash("users").slash(user.getId()).withSelfRel());
    for(Role role : user.getRoles()){
          resource.add(linkTo(RoleController.class).slash("roles").slash(role.getId()).withRel("roles"));
    }
    return resource;

}

You can see that both methods invoke thegetUserResource(User user) method.
But when i get all users in my database, the format of the _linksis not like i want. I think it must be something about the List of resources i return. Maybe because of that it has no HAL-Format. I also tried a Set instead of List but it gave me the same response

A: You should return Resources<UserResource> in your list() method.
return new Resources(resources);

You could also add a self-link to the resources itself to point to the list resource.
Furthermore, I would suggest using a RessourceAssembler to create the resource instance - see http://docs.spring.io/spring-hateoas/docs/0.23.0.RELEASE/reference/html/#fundamentals.resource-assembler.
Additionally, you could add paging to your list resource.
For this you need to:

*

*use the findAll method in your repository that returns a Page<User>.

*autowire PagedResourcesAssembler<User> in your controller

*return PagedResources<UserResource> in your list method

*use the PagedResourcesAssembler to convert the Page into PagedResources
This would result in something like this:
    private final PagedResourcesAssembler<User> pagedResourcesAssembler;

    @RequestMapping(value = "users", method = RequestMethod.GET)
    public ResponseEntity<PagedResources<UserResource>> list(Pageable pageable) {
        final Page<User> page = repository.findAll(pageable);
        final Link link = ControllerLinkBuilder.linkTo(ControllerLinkBuilder.methodOn(this.getClass()).list(null)).withSelfRel();

        PagedResources<UserResource> resources = page.getContent().isEmpty() ?
                (PagedResources<UserResource>) pagedResourcesAssembler.toEmptyResource(page, ShippingZoneResource.class, link)
                : pagedResourcesAssembler.toResource(page, resourceAssembler, link);

        return ResponseEntity.ok(resources);
    }


text:
Q: How to change the margin of an "included" layout programatically I have a LinearLayout inside which I am including a different layout. Something like this
<LinearLayout
                    android:id="@+id/linear_layout"
                    android:layout_width="match_parent"
                    android:layout_height="20dp"
                    android:visibility="gone"
                    tools:visibility="visible">

                    <include
                        layout="@layout/new_layout"
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_marginBottom="4dp"
                        android:layout_marginLeft="4dp"
                        android:layout_marginStart="4dp"
                        android:layout_weight="1"/>

</LinearLayout>

Now what I would like to do is, to programmatically change the "marginBottom" of the included layout (new_layout). How can I do that?
I tried calling various LayoutParams and tried changing the margin, but not sure if it is the right approach. Any help greatly appreciated.
Thanks

A: Try this.. Make the Linear layout using your id
    LinearLayout ll =(LinearLayout) findViewById(R.id.linear_layout);

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, 20);

    layoutParams.setMargins(left,top,right,bottom);

where you can pass the value in setMargins
and if you want to input value in dp.. Try this
public void setMargin(Context con,ViewGroup.LayoutParams params,int dp) {

    final float scale = con.getResources().getDisplayMetrics().density;
    // convert the DP into pixel
    int pixel =  (int)(dp * scale + 0.5f);

    ViewGroup.MarginLayoutParams s =(ViewGroup.MarginLayoutParams)params;
    s.setMargins(pixel,pixel,pixel,pixel);

    yourView.setLayoutParams(params);
}

where you can pass your layout params

A: include.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:id="@+id/include_layout">

<ImageView android:layout_width="90dp"
    android:layout_height="90dp"
    android:src="@drawable/cross" />

</LinearLayout>

activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">

<include layout="@layout/include"/>

<TextView android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Hello"
    android:padding="10dp" />

</LinearLayout>

MainActivity.class
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);

    LinearLayout included=(LinearLayout)findViewById(R.id.include_layout);
    LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
    params.setMargins(Math.round(10), Math.round(10), Math.round(10), Math.round(10));

    //set margin...
    included.setLayoutParams(params);
}
}

A: You should not directly change or modify margins in the <include> tag. This tag is just adding the layout resource in the current view hierarchy without adding an extra parent view container.
So essentially what you want to do is set margins on the root view container of the "included layout". That is you should directly call findViewById() for the root view and set all of your margins on it pro grammatically and as the included view's parent is a Linear-layout you should use
   LinerLayout.LayoutParams params = (LinerLayout.LayoutParams) includedRootView.getLayoutParams();
   params.setMargins();
   includedViewRoot.setLayoutParams(params);`

A: You can change it by dimensions also
res/values/dimens.xml
res/values-small/dimens.xml
res/values-normal/dimens.xml
res/values-xlarge/dimens.xml

A: I think this code helpful...
include.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 android:gravity="center">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_launcher" >
</ImageView>

</LinearLayout>

activity_main.xml
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<include
    android:id="@+id/include_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="4dp"
    android:layout_marginStart="4dp"
     layout="@layout/include" />

 </LinearLayout>

MainActivity
package com.example.stackdemo;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;

 public class MainActivity extends Activity {

 LinearLayout include_layout;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    include_layout = (LinearLayout) findViewById(R.id.include_layout);

    @SuppressWarnings("deprecation")
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.FILL_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);

    layoutParams.setMargins(0, 0, 0, 100);
    include_layout.setLayoutParams(layoutParams);
 }

  }


text:
Q: Problems using socket.io, socket.io.js not found I receive this error in console GET http://localhost/socket.io/socket.io.js 404 (Not Found). I used npm install to install express and socket.io. Everytime I try to access localhost:3000 it downloads a file instead of displaying chat.php
This is my javascript code

var express = require('express')
var app = express()
  , http = require('http')
  , server = http.createServer(app)
  , io = require('socket.io').listen(server);

server.listen(3000);

users = [];
connnection = [];

console.log('Server running!');

app.get('/',function(req, res){
    res.sendFile(__dirname + '/game.php');
});

io.sockets.on('connection', function(socket){
  connections.push(socket);
  console.log('Connected: %s sockets connected', connections.length);

  //Disconnect
  socket.on('disconnect', function(data){
  connections.splice(connections.indexOf(socket),1);
  console.log('Disconnected: %s sockets connected', connections.length);
});
});

And this is what I added into php file

<script src="/socket.io/socket.io.js"></script>
<script>
$(function(){
    var socket=io.connect();
});
</script>

A: res.sendFile(__dirname + '/game.php'); just sends a raw PHP file to the browser client.  Instead, what you need to send to the browser is HTML.  So, you either have to change your app to run in node.js and not PHP or you have to exec that PHP file and grab its output and send that to the browser.
Normally, if you wanted your page to be generated via PHP, you wouldn't be using node.js at all - you'd just be using PHP.  If the only reason you brought node.js into the equation is because of socket.io, then maybe you should be using socket.io directly with PHP which you can read about in this question.  You could use a hybrid of node.js and PHP, but it's unlikely to be all that efficient if you're using node.js to run your PHP.  For that case, you would probably be better off running socket.io in node.js on a different port number, enabling cross origin access and just leaving your PHP to be PHP.

A: I found the working solution with PHP here https://github.com/jdutheil/nodePHP. I tested it and it is working just great.


text:
Q: What does filtration contains (Stochastic calculus for finance) I am reading the book Stochastic Calculus for Finance II. I have a problem about Filtration.
The author said that: 'A filtration tells us the information we will have at future times. More precisely, when we get to time t, we will know for each set in $\mathcal{F}(t)$ whether the true $\omega$ lies in that set'.
If $X(t)$ is the price at time $t$, so what are contained in $\mathcal{F}(t)$?
It is very helpful if there is an real example.


text:
Q: WIX check if VS2015 C++ redistributable is installed Does anybody know how to check in a WIX project, if the actuall C++ redistributable package is installed or not? This link describes the serveral product IDs, but there is a problem with them. They change with every update of a C++ redist package. Based on that I've to apapt my checks in the WIX project every time a new VC redist package update is released, which is not a useable solution.
I want to use the RegistrySearch WIX element to solve this problem. Therefore I need to know a registry key that doesn't change if a newer version of a C++ redist package is installed. I've also checked the registry key described in this link, but no one seems to be reliable.

A: Visual Studio 2013/2015 will add additional registry keys:
Hive: HKEY_LOCAL_MACHINE\SOFTWARE\classes\installer\Dependencies

Name                           Property
----                           --------
Microsoft.VS.VC_RuntimeAdditio Version     : 12.0.21005
nalVSU_amd64,v12               (default)   : {929FBD26-9020-399B-9A7A-751D61F0B942}
                               DisplayName : Microsoft Visual C++ 2013 x64 Additional Runtime - 12.0.21005
Microsoft.VS.VC_RuntimeAdditio Version     : 14.0.23026
nalVSU_amd64,v14               (default)   : {BC958BD2-5DAC-3862-BB1A-C1BE0790438D}
                               DisplayName : Microsoft Visual C++ 2015 x64 Additional Runtime - 14.0.23026

They also include keys like Microsoft.VS.VC_RuntimeMinimumVSU_amd64,v12. These keys will point to the currently installed redist packages, and will be removed/added when you install a redist package.


text:
Q: gdb stops at breakpoint, but no code is shown I've recently changed compilers from the Oracle Studio compiler on RHEL7 to Clang on RHEL8 due to no support of the oracle compiler.  I'm trying to debug our application using GDB, but running into some issues I am yet to find a solution for.
I can set a breakpoing with:
b class::function or
b file.cc:linenumber
It does break when it hits that breakpoint, but no code is shown at that location.  Funnily enough, some stuff does, and in this case, it shows line numbers in the base class.
this is the stack on break:
Thread 41 "dms" hit Breakpoint 2, 0x0000000000880f44 in
User_Registrar::login(Address const*, int, char const*, Boolean,
RWCString) ()
(gdb) where
#0  0x0000000000880f44 in User_Registrar::login(Address const*, int,
char const*, Boolean, RWCString) ()
#1  0x0000000000878dfb in
User_Registrar::userLoginRequest(UserLoginRequest*) ()
#2  0x0000000000871597 in User_Registrar::processMessage(Message*) ()
#3  0x00000000009cd530 in MessageHandlerObject::processMessageQueue
(this=0x7fffe8068010) at BaseObjects.cc:488
#4  0x00000000009cd40e in
MessageHandlerObject::processMessageQueueStartup
(thisInstance=0x7fffe8068010) at BaseObjects.cc:447
#5  0x00007ffff69d887c in stl_thread_start_rtn () from
/opt1/dms/lib/libthread.so
#6  0x00007ffff643318a in start_thread () from /lib64/libpthread.so.0
#7  0x00007fffee095dd3 in clone () from /lib64/libc.so.6
(gdb) up
#1  0x0000000000878dfb in
User_Registrar::userLoginRequest(UserLoginRequest*) ()
(gdb) down
#0  0x0000000000880f44 in User_Registrar::login(Address const*, int,
char const*, Boolean, RWCString) ()
(gdb)

Am I missing something like a limit or something similar?
Things I have checked:
Yes, it is being compiled with -g
objdump does show the debug_info for the source file
gdb does show it has loaded the source file

A:
(gdb) where
#0  0x0000000000880f44 in User_Registrar::login(Address const*, int, char const*, Boolean, RWCString) ()

Note that there is no file / line info for this level -- that is the reason GDB doesn't show source.
Why did this happen? Clang omits file/line info under certain conditions when optimization is in effect (as far as I understand, when code is inlined and re-ordered, it is sometimes hard to keep code to file/line association).
If you can disable optimizations, or add __attribute__((noinline)) to the login() function, you'll have a better debugging experience.
If you must debug this particular function with optimizations, you'll have to disassemble it and reconstruct the code to file/line association "by hand".

A: If gdb doesn't know where to look for the source file, you can use the directory command to add a path: gdb directory command


text:
Q: Shell script that filters command output and saves it in Json formated list never worked with shell scripts before,but i need to in my current task.
So i have to run a command that returns output like this:
    awd54a7w6ds54awd47awd refs/heads/SomeInfo1
    awdafawe23413f13a3r3r refs/heads/SomeInfo2
    a8wd5a8w5da78d6asawd7 refs/heads/SomeInfo3
    g9reh9wrg69egs7ef987e refs/heads/SomeInfo4

And i need to loop over every line of output get only the "SomeInfo" part and write it to a file in a format like this:
    ["SomeInfo1","SomeInfo2","SomeInfo3"]

I've tried things like this:
    for i in $(some command); do
      echo $i | cut -f2 -d"heads/" >> text.txt
    done

But i don't know how to format it into an array without using a temporary file.
Sorry if the question is dumb and probably too easy and im sure i can figure it out on my own,but i just don't have the time for it because its just an extra conveniance feature that i personally want to implement.

A: Try this
# json_encoder.sh
arr=()
while read line; do
  arr+=(\"$(basename "$line")\")
done
printf "[%s]" $(IFS=,; echo "${arr[*]}")

And then invoke
./your_command | json_encoder.sh

PS. I personally do this kind of data massaging with Vim.

A: While you should rarely ever use a script to format json, in your case you are simply parsing output into a comma-separated line with added end-caps of [...]. You can use bash parameter expansion to avoid spawning any additional subshells to obtain the last field of information in each line as follows:
#!/bin/bash

[ -z "$1" -o ! -r "$1" ] && {   ## validate file given as argument
    printf "error: file doesn't exist or not readable.\n" >&2
    exit 1
}

c=0     ## simple flag variable

while read -r line; do                  ## read each line
    if [ "$c" -eq '0' ]; then           ## is flag 0?
        printf "[\"%s\"" "${line##*/}"  ## output ["last"
    else                                ## otherwise
        printf ",\"%s\"" "${line##*/}"  ## output ,"last"
    fi
    c=1         ## set flag 1
done < file     ## redirect file to loop
echo "]"        ## append closing ]

Example Use/Output
Using your given data as the input file, you would get the following:
$ bash script.sh file
["SomeInfo1","SomeInfo2","SomeInfo3","SomeInfo4"]

Look things over and let me know if you have any questions.

A: You can also use awk without any loops I guess:
cat prev_output | awk -v ORS=',' -F'/' '{print "\042"$3"\042"}' | \
sed 's/^/[/g ; s/,$/]\n/g' > new_output

cat new_output
["SomeInfo1","SomeInfo2","SomeInfo3","SomeInfo4"]

A: Using Perl one-liner
$ cat petar.txt
    awd54a7w6ds54awd47awd refs/heads/SomeInfo1
    awdafawe23413f13a3r3r refs/heads/SomeInfo2
    a8wd5a8w5da78d6asawd7 refs/heads/SomeInfo3
    g9reh9wrg69egs7ef987e refs/heads/SomeInfo4

$ perl -ne ' { /.*\/(.*)/ and push(@res,"\"$1\"") } END { print "[".join(",",@res)."]\n" }' petar.txt
["SomeInfo1","SomeInfo2","SomeInfo3","SomeInfo4"]


text:
Q: Rails can't find my route but it exists! Ok I have events that I want to publish/unpublish with an extra action (nonRESTful) I watched Ryan Bates' railscast on this: http://railscasts.com/episodes/35-custom-rest-actions and it got me most of the way. I think the problem is that my route is nested in an /admin section so even though when I run rake routes and get:
publish_admin_event PUT /admin/events/:id/publish(.:format) {:controller=>"event_services", :action=>"publish"}

This won't work in my /views/admin/index.html.erb file:
<%= link_to 'Publish', publish_admin_event(event), :method => :put %>

because it claims that path doesn't exist! And neither will this:
<%= link_to 'Publish', {:controller => :event_services, :action => :publish}, {:method => :put, :id => event} %>

and says that "No route matches {:controller=>"event_services", :action=>"publish"}"
so what gives? (And I've tried restarting my server so that isn't it.)
EDIT:
This DOES work:
<%= link_to 'Publish', "/admin/events/" + event.id.to_s + "/publish", :method => :put %>

But I'd rather NOT do this.
EDIT #2:
My route entry:
map.resource :admin do |admin|
  admin.admin '', :controller => :admin, :only => :index
  admin.resources :events, :controller => :event_services, :member => {:publish => :put } do |service_event|
    # ...
  end
end

A:
This won't work in my /views/admin/index.html.erb file:
<%= link_to 'Publish', publish_admin_event(event), :method => :put %>

because it claims that path doesn't exist!

I'd rather expect it not to work because of a NoMethodError. I think you meant to write publish_admin_event_path instead of just publish_admin_event there. Then it should work.

And neither will this:
<%= link_to 'Publish', {:controller => :event_services, :action => :publish}, {:method => :put, :id => event} %>

This will work if you do :controller => "/admin/event_services" (though that isn't necessary if you're already in the admin namespace) and, as you figured out in your comment, move :id => event into the first hash.


text:
Q: How do I do a set timer within each react component? I am making a quiz and I want each question to have a 60-second timer. I am using react-router so that users can navigate between questions.
Here is the reusable question Component.
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
class Questions extends Component {
    constructor(props){
        super(props);
    }

    render(){
        let {
            questionCover,
            answerSelection,
            answer1,
            answer2,
            answer3,
            answer4,
            answer5,
            answer6,
            nextQuestion,
            title1,
            title2,
            back,
            questionNumber,
            selected,
        } = this.props;

        return(

{title1.toUpperCase()}

        { true &&
{title2}
 }

                        <div
                            id={answer1}
                            className={`answers ${selected === 1 ? 'selected' : ''}`}
                            onClick={()=>
                                this.props.selectedScore(1, questionNumber)
                            }
                            >

                        <div
                            id={answer2}
                            className={`answers ${selected === 2 ? 'selected' : ''}`}
                            onClick={()=>
                                this.props.selectedScore(2, questionNumber)
                            }
                            >

                        <div
                              id={answer3}
                              className={`answers ${selected === 3 ? 'selected' : ''}`}
                              onClick={()=>
                                  this.props.selectedScore(3, questionNumber)
                              }
                              >

                    <div
                            id={answer4}
                            className={`answers ${selected === 4 ? 'selected' : ''}`}
                            onClick={()=>
                                this.props.selectedScore(4, questionNumber)
                            }
                            >

                        <div
                            id={answer5}
                            className={`answers ${selected === 5 ? 'selected' : ''}`}
                            onClick={()=>
                                this.props.selectedScore(5, questionNumber)
                            }
                            >

                        <Link to={nextQuestion} activeClassName="active">

this.props.calculateScore()}
                            >

                        </Link>

            <Link to={`/`} activeClassName="active">

</Link>

                        <Link to={`/question1`} >

</Link>
                        <Link to={`/question2`} >

</Link>
                        <Link to={`/question3`} >

</Link>
                        <Link to={`/question4`} >

</Link>
                        <Link to={`/question5`} >

</Link>

            <Link to={back} activeClassName="active">

</Link>

        )
    }
}

export default Questions;

If a user decides to navigate back to question 4 or go to question 5 for example, the timer should reset to 60 seconds and should begin counting down again. If the timer expires, I want to kick them back to the / route and reset state.

A: use setTimeout(function, timeout duration) inside the componentDidMount (although remember setTimeout durations can get blocked by the call stack if 60seconds expires and the call stack is still occupied.

A: In your componentDidMount function set a timer like this:
componentDidMount = () => {
  this.timer = setTimeout(functionWhenDone, 60000)
}

This will set the timer and assign a pointer to it to a member variable of your React class.
Then in your componentWillUnmount() function clear the timeout so if a timer is running, and the user navigates away before it's done, you won't get a memory leak.
componentWillUnmount = () => {
  clearTimeout(this.timer)
}


text:
Q: Replace content by class with JavaScript How can I modify the content with Javascript selecting the elements by class?
Actually I tried using this:
document.getElementsByClassName("myClass").innerHTML = "new content"

But does nothing.
If I select the element by ID it's work
document.getElementById("myID").innerHTML = "new content"

But I need can select by class.
I only need to change the content inside a  tag. Replacing a text to an img element for a woocommerce buttons.
Thanks!

A: getElementsByClassName returns an array so you have to loop that array to change the content having your given class. You can try following to code. I hope it will help you.
var arr = document.getElementsByClassName("myClass");
for (var i = 0; i < arr.length; i++) {
   arr[i].innerHTML = "new content";
}

A: As others pointed out getElementsByClass returns an array.
If you are willing to use jquery it could simplify as
$(".myClass").html("new content")

A: getElementsByClassName will return array. So loop that array and do your logic:

var myClasses = document.getElementsByClassName("myClass");

for (var i = 0; i < myClasses.length; i++) {
  myClasses[i].innerHTML = "new content";
  }

old content

old content

A: document.getElementsByClassName returns an array, as classes are not unique, whereas document.getElementById returns just an object (it should be unique).
Long story short, try document.getElementsByClassName("myClass")[i].innerHTML = "new content" where i can take values from 0 to n-1, where n is the number of elements with the .myclass class.

A: Your class name is not unique. i.e The same class name is used by many other elements. So document.getElementsByClassName("myClass") this will retrun an array containing all the classes. So, either you need to select the porper class by document.getElementsByClassName("myClass")[0] or assign some id to that particular element.

A: ECMAScript 2015 (ES6) also provides the spread operator, which can be used to transform the HTMLCollection returned by getElementsBYClassName into a regular array and then combine it with forEach(), to change all array elements with the new content, with the line:
[...document.getElementsByClassName('myClass')].forEach(element => {
    element.innerHTML = '
New Content
' }

A: Classes are returned in an array, so you need to iterate the array.

A: Use something like this:
var elems = document.getElementsByClassName('myClass'), i;
for (i in elems) {
    elems[i].innerHTML = "new content";
}


text:
Q: Reorderable parent/children hierarchy in a relational database I'm struggling on a design question for my Ruby on Rails website. I'm working on an estimation tool for construction companies for renovation projects.
It orders items this way by default:

*

*Room (ex: Kitchen)

*

*Section (ex: Painting)

*

*Item (ex: Painting the ceiling)

But sometimes companies prefer to order items this way

*

*Section

*

*Room

*

*Item

In our database, these items are in the same table with children containing their parent_id.
I give the option to quickly switch between 1st and 2nd display modes, but the way I do doesn't seem really clean to me. It is always stored like in the first example, and I have a bunch of "ifs" changing the way it's displayed.
I can't find a way to do this better, and didn't find any discussion on the subject (maybe I didn't know where to look)
Is there any best practices for this situation ?

A: Rather than the entities, let's look at the relationships here:

*

*An Item is for exactly one Room; a Room has many Items

*An Item is for exactly one Section; a Section has many Items

*A Room has many Sections; a Section applies to many Rooms (even in the original hierarchy, your example Section was "Painting", not "Painting the Kitchen")

So we have two one-to-many relationships, and one many-to-many relationship. A hierarchy is a one-to-many structure, so can't correctly model the relationship between Rooms and Sections.
Instead, you can model the relationships explicitly:

*

*Every Item has a Room ID and a Section ID

*To list all Sections for a Room, look in Items for the distinct set of Section IDs with that Room ID

*To list all Rooms for a Section, look in Items for the distinct set of Room IDs with that Section ID

If there is information that needs to be stored against the combination of Room and Section, you would need to create a new entity to represent that combination:

*

*Every Item has a RoomSection ID

*Every RoomSection has a unique combination of Room ID and a Section ID

*To list all Sections for a Room, look in RoomSections for all the Section IDs with that Room ID

*To list all Room for a Sections, look in RoomSections for all the Room IDs with that Section ID

Or, you might go the other way, and make this into a generic "facet" system, with "Room" and "Section" as run-time defined attributes which can be extended or replaced according to need. This flexibility brings a lot of complexity - you need to re-implement things like constraints, for instance - so don't take this option unless you're sure it will bring value.


text:
Q: Smart html page break I make html reports and print them (or PDF) and want to make smart page breaks. I want to avoid that the heading is on one page and the paragraph on the next page. In that case the next page should start with the heading.
I have tried page-break-after:avoid but with no success. And I don't understand why. If I try page-break-after:always it works. So I guess the avoid functions is not that good. I always use IE8.
Is their any script way to calculate where the page break should be? If their is I can just make a page-break-after:always at that place.
Thanks!
/Georg

A: This class is only a hint. A page break is only avoided if it can be avoided. If it would mean the result would have to be clipped, a page break will be inserted after all.
I don't think it's possible to calculate where the page breaks would be, because it depends on numerous variables, including printer margins and paper size, which are not accessable in CSS nor JavaScript.

A: I used TCPDF (http://www.tcpdf.org/) to do something similar. It was easy to get the page breaks in the right place though as it was printing tabular data so I could do a row count.
You could try it with a character count but it wouldn't be as accurate.


text:
Q: Using minimal LXC containers as an advanced and secure chroot to isolate services First of all I'm not a security expert, and I never used LXC before.
I'm trying to harden as much as possible a Gentoo hardened server. To do so, I'm thinking to use LXC, maybe combined with KVM, to isolate as much as possible network services.
I read the LXC unix manual page, but it's still pretty obscure to me how Linux containers are setup. Looking on the internet for more information, I've only found documentation about running an entire system inside a Linux container which isn't what I'd like to do.
What I want to use LXC for, is running just one application inside a container including only the strict minimal files / resources required by the application. I do not want to run an entire system inside a container, avoiding even having busybox.
For example, I'd like to isolate the ntpd service, as far as I know to be able to synchronize the system clock, I can't run it inside a VM. But I could run it inside a chroot, or I suppose I could run it inside a Linux container for a better isolation and security.
To do so I would have to:

*

*Identify what files ntpd requires like when setting up a chroot jail.

*This where I don't know what to do and how: LXC configuration, template, where to put my files to set up the container, etc.

*Run it with lxc-execute
Is it something possible? What would be the various steps to build, run and manage such a container?

A: Historically, LXC has had many showstopping security issues that prevent it from being truly isolated, but infrastructure enhancements in the mainline Linux kernel have alleviated most (if not all) of these concerns.
See here for an overview of the security problems / enhancements that have been observed in successive Ubuntu releases bundling LXC.
I found this Oracle Unbreakable Enterprise Kernel documentation to be particularly useful for explaining how to do application-level containers.
From the docs:

Application containers are not created by using template scripts. Instead, an application container mounts all or part of the host's root file system to provide access to the binaries and libraries that the application requires. You use the lxc-execute command to invoke lxc-init (a cut-down version of /sbin/init) in the container. lxc-init mounts any required directories such as /proc, /dev/shm, and /dev/mqueue, executes the specified application program, and then waits for it to finish executing. When the application exits, the container instance ceases to exist.


text:
Q: Как перевести URL (slug) в Wordpress с русского на английский? В WordPress по умолчанию генерируется URL (в WP это называется slug) на основе заголовка поста. К примеру, Из заголовка "Привет мой мир" мы получим адрес "привет-мой-мир".
Возможно ли автоматически создавать ссылки постов в Wordpress на английском языке? Чтобы из "Привет мой мир" в адресе был "hello-my-world"?
Вариант с транслитерацией не подходит – нужен именно перевод. Есть ли какой-то плагин для этого?

A:
Вариант с транслитерацией не подходит, нужен именно перевод.

Ну если так - использовать API сервисов-переводчиков в своём плагине.

A: Для этой цели я разработал плагин MobiDevices Translate URL, который работает на основе Яндекс Переводчика, что обеспечивает отличное качество перевода.
Плагин удаляет из полученных URL английские предлоги и артикли, которые не влияют на продвижение, однако увеличивает длину ссылок.
MobiDevices Translate URL правильно форматирует переведенный URL и очень легкий в установке и работе.