text:
Q: Regex to match datetime between a word and end of line? I am trying to write a regex pattern matcher to extract the date from the last-modified and date in a raw http header response.
I am reading the header in with a buffered reader and then going through it line by line to find the required information.
The two I am having trouble with are
Date: Mon, 27 Jul 2009 12:28:53 GMT
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT

I wish to extract the datetime from the string representing the line, but I cant seem to find a regular expression that works :/
The expected output should look like
27 Jul 2009 12:28:53 GMT

I was trying this, but it is not working
(?<=Date:\s).*(?=\n)

Cheers
Corey

A: You could try this out:
(?<=(Last\\-Modified|Date):\\s(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\\s)(.+)

In your sample input-output, you have not matched the day, and I've assumed that's intentional, and not a typo.
Trial at this link.
Regex -
(?<=(Last\\-Modified|Date):\\s(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\\s) is a positive look-behind to ensure that the match is preceded by Date: or Last-Modified: and a day
(Last\\-Modified|Date): checks for the presence of Date: or Last-Modified:
\\s is a single space
(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\\s is a non-capturing group for any day, followed by a comma and a space. Do note that I have added this only because according to the question, days must be excluded, and if you do want to obtain them, just remove this part of the regex as shown here.
(.+) matches one or more characters, which is the actual date desired in the question.
Here's a cheat sheet for regex conventions, should you need it.
Implemented as follows:
String regex = "(?<=(Last\\-Modified|Date):\\s(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\\s)(.+)";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(YourString);
while(m.find())
{
    String date = m.group();
}

A: I would write it as:
Pattern pattern = Pattern.compile("(?:Date|Last-Modified)\\s*:[^,]+,\\s*(.*)");

String input =
            "Date: Mon, 27 Jul 2009 12:28:53 GMT\n" +
            "Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT";

Matcher matcher = pattern.matcher(input);
while(matcher.find()) {
    System.out.println(matcher.group(1));
}

Basically you want the find a line with:

*

*Date or Last-Modified: (?:Date|Last-Modified)

*Optionally followed by spaces: \\s*

*The literal :

*Followed by the day name and a comma: [^,]+,

*Followed by any spaces and your group of interest: \\s*(.*)

A: Do you have to use regex? What about something like this:
String input = "Date: Mon, 27 Jul 2009 12:28:53 GMT";
String output = input.split(", ")[1];


text:
Q: SQL LIKE with % query for text in Perl I have the following piece of code:
$query = "SELECT tac FROM lte_modems WHERE tac = ?";
$check_name = $dbh->prepare($query);
$my_name = "Jo"
$check_name->execute($my_name);
my @result = $check_name->fetchrow_array();

which works perfectly fine.
I would like to change the SQL query to get back names starting with "Jo":
ie my SQL query should be
   $query = "SELECT tac FROM lte_modems WHERE tac LIKE '?%'";

but this is not working out. any help pls? maybe I need to escape some characters?
thanks in advance

A: You need to include the % in your parameter. Otherwise you'll get additional quoting as DBI handles that for you.
my $sth = $dbh->prepare( "SELECT tac FROM lte_modems WHERE tac LIKE ?" );
$sth->execute( $my_name . '%' );

The trick is really to always let DBI do all the quoting and do none of it yourself. DBI doesn't care if the placeholder ? is after an equals =, a LIKE or a REGEXP or something else. It escapes quotes properly and adds quotes if necessary. You don't want to interfere with that at all.

A: You quoted the ?, turning it from a placeholder into a string. Use
my $sth = $dbh->prepare("SELECT tac FROM lte_modems WHERE tac LIKE ?");
$sth->execute($my_name . '%');

or
my $sth = $dbh->prepare("SELECT tac FROM lte_modems WHERE tac LIKE CONCAT(?, '%')");

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to debug winforms designer My question is not how to debug during design time. I actually want to debug through the events available in designer. I know that the form has load and other type of events. Is there any events in windows forms designer like init, load, etc ?
I have done a similar debugging in ASP through user controls. It allows us to view the output HTML of a user control before adding it to the designer.
I know windows forms and ASP are different but there should be some event to check values of Controls before actually rendering it.

My Form takes a long time to open in the VS designer. So I attached a
  debugger to VisualStudio (devenv.exe), set a breakpoint in my Form's
  InitializeComponent to step through it to see what the problem is.
  However, the breakpoint is not getting hit.

A: To debug design-time of your windows forms project:

*

*Right click on your project in solution explorer and open Properties.

*In the property page select the Debug tab.

*In the Start Action section, select Start external programand then click on button to browse for the Visual Studio executable file devenv.exe which is located in a path like "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe"

*Save project and then run using F5. A new instance of visual studio will be opened.

*Open the project using new instance. Which enables you to debug the previous instance of visual studio containing your project.

*Put breakpoints in the files which you want to debug in instance.

When may I find this approach useful?

*

*When you have an exception in design-time.

*When you want to debug the behavior of a Designer or a TypeConverter or a UiTypeEditor at design time.

For more information:

*

*Walkthrough: Debugging Custom Windows Forms Controls at Design Time

A: To debug in designer you need to put a breakpoint on top of designer code.
Then start your application and it will stop at the breakpoint.
Press F11 to move one line at the time.

A:
Go to Tools → Options → Expand Debugging from left pane window → Enable Just my Code [Just Check off this checkbox] → OK.

A: You can debug Visual Studio using another instance of Visual Studio: https://stackoverflow.com/a/7757140/343309
If you run into design time error and cannot recover the design view, you can open another visual studio and attached the current visual studio process for debugging.

A: Found a really old(almost 12 years) blog post through the following stack overflow question How does the Winforms Designer instantiate my form?
Blog: https://blogs.msdn.microsoft.com/rprabhu/2004/12/12/how-does-the-windows-forms-designer-in-visual-studio-load-a-form/
A quote from above blog that points me in the right direction

Well, the designer is not really instantiating Form1 at all. It is
  creating an instance of the base class of Form1

As per the above quote, follow the below steps and find the code that makes the designer slow
1) Create a class that extends Form and add it to your winforms project
public class DebuggableForm : Form
{
    public DebuggableForm()
    {
        //Put your code in InitializeComponent method here.
        //Through line-by-line debugging you can find
        //which line is making the designer slow
    }
}

2) Extend the above class instead of directly extending Form in Form1.cs. Here Form1 is the name of a form, check the appropriate form name in your project
public class Form1: DebuggableForm
{
//Your actual form code
}

3) Place a breakpoint in the constructor of class created in step-1 (DebuggableForm)
4) Attach your project to another instance of VS and open a project in new VS
5) Open form1.cs in newly opened project and perform step-2 again.
6) Open the designer or double click on Form1 in solution explorer. Your debugger in DebuggableForm will be hit
Note: Form1.cs in above steps refer to a form in windows forms project. The name may vary in your project


text:
Q: "kernel package linux-headers-5.0.0-2173611831 is not supported" when building modules I download linux kernel-5.0.0 and try to compile and install it on my Ubuntu-18.04.3
the commands i used in /usr/src/linux-5.0:
sudo make mrproper

sudo make menuconfig

sudo make -j4

sudo make modules_install

sudo make install

but at the result of last command, there is a error:
 * dkms: running auto installation service for kernel 5.0.0-2173611831

Kernel preparation unnecessary for this kernel.  Skipping...

Building module:

cleaning build area...(bad exit status: 2)

unset ARCH; env NV_VERBOSE=1 'make' -j4 NV_EXCLUDE_BUILD_MODULES='' KERNEL_UNAME=5.0.0-2173611831 IGNORE_XEN_PRESENCE=1 IGNORE_CC_MISMATCH=1 SYSSRC=/lib/modules/5.0.0-2173611831/build LD=/usr/bin/ld.bfd modules...(bad exit status: 2)

ERROR (dkms apport): kernel package linux-headers-5.0.0-2173611831 is not supported

Error! Bad return status for module build on kernel: 5.0.0-2173611831 (x86_64)

Consult /var/lib/dkms/nvidia/430.50/build/make.log for more information.
                                                                         [ OK ]

I vim the /var/lib/dkms/nvidia/430.50/build/make.log as it suggests and I get this:
DKMS make.log for nvidia-430.50 for kernel 5.0.0-2173611831 (x86_64)
Wed Oct 16 13:07:33 CST 2019
Makefile:19: /Kbuild: No such file or directory
make[2]: *** No rule to make target '/Kbuild'.  Stop

It seems something needed is gone. Did I miss something?
.

A: I skip these errors and just reboot. Then I change NVIDIA version from 430 to 390 and sudo make install again. It just works(in other words, no errors) even though I don't know how.


text:
Q: How do I prompt the user to enter in either a character or a number? Lets say I'm making a math program simple arithmetic quizing program. It gives a random number and asks the user to enter in the answer as an integer or q to quit. Is this possible?

A: Get the answer as a string, then check if it is == "q", exit, else, convert it to an integer.
#include <iostream>
#include <cstdlib>

int main() {
    std::string got;
    std::cin >> got;
    if(got == "q")
            return 0;
    else {
            int i = std::atoi(got.c_str());
            std::cout << i;
    }
    return 0;
}


text:
Q: Get Processed Email Template How do I get the processed Template in Magento 2 ? In version Magento 1 it worked like this:
$email_template = Mage::getModel('core/email_template')->load($templateId);
$email_template_variables = array();
$processedTemplate = $email_template->getProcessedTemplate($email_template_variables);

A: the same method exists in m2 and i suggest you take a look on how it's used in the vendor/magento/module-newsletter/Model/Queue/TransportBuilder.php class, inside the prepareMessage() method.
Basically, the implementation resides in the abstract class vendor/magento/module-email/Model/AbstractTemplate.php which does pretty much what the m1 implementation did, but i suggest you take a look and understand what is processed additionally.


text:
Q: Eclipse Luna with JBoss Tools does not export libraries I'm attempting to upgrade our environment to Eclipse Luna w/ JBoss Tools from our current Indigo instance. Most things are sorted well enough, but I'm running into a wall when deploying our application to a JBoss server within Eclipse.
As far as I can see, the lib/ directory of the .ear file generated contains none of the transitive dependencies from maven that we would normally expect to see, and as a result the application does not deploy or run correctly on the server. For clarity, we use the 'use workspace metadata' deployment option on the JBoss server within Eclipse.
By contrast, if I right click on the relevant project within Eclipse and say Export... .ear file, the resulting .ear contains all the .jars that I'd expect inside the lib/ folder (there's over 50 of these things, so it's pretty easy to spot the difference). Subsequently dropping the .ear into the deploy directory of JBoss and starting a server manually has the application working fine.
Has anyone ever encountered this sort of issue within JBoss Tools / Luna, and if so what steps were taken to try and remediate it?
Cheers for any help.
Dave.
EDIT: For what it's worth, this is a JBoss Enterprise Application Platform 5.x server instance, and we're using JBoss EAP 5.2


text:
Q: Reveal hidden form elements by modifying their display attribute How can I make a bookmarklet for Firefox that shows form elements hidden by display: none;?

A: If I understand correctly, you want to set all form and related elements to be visible by altering the display attribute if necessary. You can do this with JavaScript and jQuery.

Greasemonkey userscript:
// ==UserScript==
// @name        Show Form Elements
// @namespace   http://igalvez.net
// @description Modifies form elements' display attributes to reveal them.
// @version     1.0
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// ==/UserScript==

var elements = ['form', 'input', 'textarea', 'label', 'fieldset', 'legend',
                'select', 'optgroup', 'option', 'button'];
for (var i = 0; i < elements.length; i++)
{
    $(elements[i]).each(
        function()
        {
            $(this).show();
        }
    );
}

Bookmarklet URL:
javascript:(function(e,a,g,h,f,c,b,d){if(!(f=e.jQuery)||g>f.fn.jquery||h(f)){c=a.createElement("script");c.type="text/javascript";c.src="http://ajax.googleapis.com/ajax/libs/jquery/"+g+"/jquery.min.js";c.onload=c.onreadystatechange=function(){if(!b&&(!(d=this.readyState)||d=="loaded"||d=="complete")){h((f=e.jQuery).noConflict(1),b=1);f(c).remove()}};a.documentElement.childNodes[0].appendChild(c)}})(window,document,"1.3.2",function($,L){var%20elements=["form","input","textarea","label","fieldset","legend","select","optgroup","option","button"];for(var%20i=0;i<elements.length;i++){$(elements[i]).each(function(){$(this).show()})};});

(Generated using Ben Alman's jQuery Bookmarklet tool)


text:
Q: Using a single regex to search for 2 criteria in python I have a function
def extract_pid(log_line):
    regex = PROBLEM
    result = re.search(regex, log_line)
    if result is None:
        return None
    return "{} ({})".format(result[1], result[2])

My intended outcome of this function is to be able to return the pid numbers between [ ] and the corresponding uppercase text, for example;
logline = "July 31 07:51:48 mycomputer bad_process[12345]: ERROR Performing package upgrade"

From the above string I'd expect the outcome of my function to return 12345 (ERROR)
I have 2 criteria to meet in this function \[\d+\] and [A-Z]{2,} If i test each regex individually I get the expected outcome.
My question is, how do I specify both regex in the same line and output them as displayed in the function above, I cannot find anywhere in the documentation a simple "use this for AND" I found "| for or" but I need it to process both regex criteria.
I understand this could be done in 2 functions and joined together but i've been tasked with doing this from a single function.

A: Use two capturing groups:
regex = r'(\[\d+\]).*?([A-Z]{2,})'

The .*? means "put any characters in between, as few as possible". If you can, replace that with : (colon space) assuming that's what's always there.


text:
Q: Socks4 proxy support in QNetworkProxy I am working on an application that make use of QNetworkProxy.
I want to know is, how can I include support for Socks4 type proxy in my application, as Qt only supports NoProxy, DefaultProxy, Socks5Proxy, HttpProxy, HttpCachingProxy and FtpCachingProxy.
I have already added support for NoProxy, DefaultProxy, Socks5Proxy and HttpProxy using Qt but don't know how to include Socks4proxy support. So can anyone help me in adding Socks4proxy support in my application using only Qt.
Thanks in advance.

A: I was in a similar situation a while ago and had no luck finding anything. There is a project implementing a Socks4 Server, but that wasn't helpful in my case.
While looking at the Qt source I decided that implementing a Socks4 proxy is far from being trivial. In the end, I decided to install an internal Socks5 Proxy which itself makes use of another proxy.


text:
Q: Is using an approximation technique to estimate the parameter under a known posterior distribution necessary? Let $X_i \sim \text{IID Poisson}(\theta)$ for $i=1,2,...,n.$ The MLE of $\theta$ is written as
$$\hat{\theta}_\text{MLE}=\bar{x}.$$
Suppose $\theta$ has a probability density function (pdf) $p(\theta) \propto \theta^{-1/2}$, which is Jeffrey's prior. The resulting posterior distribution is $\theta|\mathbf{x} \sim \text{Gamma}(\sum_{i=1}^{n} x_i +\frac{1}{2},\frac{1}{n})$.  Under quadratic loss, it can be shown that the (minimum risk) Bayes estimator is
$$\hat{\theta}_\text{Bayes} = \bar{x}+\frac{1}{2n}.$$

Now, knowing the Bayes estimator in this scenario, if I were to compare the performances of the MLE and the Bayes estimator in terms of bias, can I simply simulate data from Poisson with parameter $\theta_0$ and estimate using $\hat{\theta}_\text{MLE}$ and $\hat{\theta}_\text{Bayes}$ directly? Then, repeat for say, $1000$ iterations and check the means of the estimated values of $\hat{\theta}$?  Alternatively, should I use some sort of approximation techniques such as MCMC?

A: You can certainly use simulation to examine the performance of estimators, but the difficulty is that you would need to choose one or more values of $\theta_0$, and the performance of the estimators might (in principle) depend on this choice.  In the present case you can get explicit distributional results for the estimators without simulation, so that is preferable.    Specifically, you have the distributions:
$$\hat{\theta}_\text{MLE} \sim \frac{1}{n} \text{Pois}(n \theta)
\quad \quad \quad \quad \quad
\hat{\theta}_\text{Bayes} \sim \frac{1}{n} \bigg[ \text{Pois}(n \theta) + \frac{1}{2} \bigg].$$
Consequently, the biases of the two estimators are:
$$\text{Bias}(\hat{\theta}_\text{MLE}, \theta) = 0
\quad \quad \quad \quad \quad
\text{Bias}(\hat{\theta}_\text{Bayes}, \theta) = \frac{1}{2n}.$$


text:
Q: ExactTarget Query Data Extension for NUMBER of emails NOT OPENED I am trying to build a Data Extension with subscribers that have NOT OPENED a NUMBER of emails. For example: "RETRIEVE SUBSCRIBERS WHO HAVE NOT OPENED THE LAST 100 EMAILS SENT".
I hope someone can help me build this query.
Thanks!

A: What you are trying to do, is not possible, as you are, in a way, querying for data that does not exist. There are three tables that are of interest to you here:

*

*_Subscriber (stores all you have ever sent to)

*_Sent (stores the individual logs of the emails sent)

*_Open (stores the opens related to the individual sends)

Now, unless you are always sending all email, to all subscribers, sometimes you will have a subscriber that has not been sent a particular email. That means - his "last 100 emails", isn't the same as my "last 100 emails".
The one route you could pursue is manually typing in the email id's for the last 100 emails sent, but that is extremely tedious.
What is typically done here, is a query for those who have been sent an email within the last X period, but haven't opened or clicked the email (remember, due to the way tracking works, sometimes you can click an email without it registering as an open). A query to achieve this, can look like this:
SELECT
s.SubscriberKey AS SubscriberKey,
sub.EmailAddress AS EmailAddress

FROM _Sent s

LEFT JOIN _Subscribers sub
ON s.SubscriberKey = sub.SubscriberKey

WHERE
s.EventDate > DateAdd(Day,-100,GetDate())

AND NOT EXISTS (
  Select 1
  FROM _Open o
  WHERE s.JobId = o.JobId
  AND s.SubscriberKey = o.SubscriberKey
  )

AND NOT EXISTS (
  Select 1
  FROM _Click c
  WHERE s.JobId = c.JobId
  AND s.SubscriberKey = c.SubscriberKey
  )

This will see if a subscriber has opened any of the email it was sent within the last 100 days. NOW - THIS IS A LOT OF DATA - and sometimes this can time out, meaning that you might need to pull the sent data, open data and click data into separate data extensions first - and then instead of querying and comparing system views, you are querying and comparing data extensions which will typically perform better.

A: This will work and speed up processing time:
select

SubscriberKey as 'SubscriberKey'

From [Data_Extension]

WHERE SubscriberKey

NOT IN (
SELECT

SubscriberKey
FROM _Open

WHERE EventDate > dateadd(Day,-100,getdate()))


text:
Q: interaction contrast with glmer I am running a model with a similar structure:
model <- glmer(protest ~ factora*factorb*numeric+factora+factorb+numeric+1 + (1 + factor1|level1) + (1|level2), data=data, family=binomial(link='logit'))

where factora and factorb are factor variables, numeric is a numerical variable.
I am curious of the statistical significance of the contrast in the interaction while holding factora constant at 3, between two values of factorb (1-5) across the range of the numerical value.
I have tried the following options with no luck:
library(psycho)
get_contrasts(model, formula="factora:factorb:numeric", adjust="tukey")
View(contrasts$contrasts)

this works, but unfortunately the results hold numeric constant and only vary factora and factorb. Therefore, it does not answer my question.
I have also tried:
library(multcomp)
test = glht(model,linfct=mcp("factora:factorb:numeric"="Tukey"))

this yields the error of
Error in mcp2matrix(model, linfct = linfct) :
  Variable(s) 'factora:factorb:numeric' have been specified in 'linfct' but cannot be found in 'model'!

without regard of the way I specify the interaction and despite other functions like get_contrasts finding the interaction specified the same way.
I have also tried:
library(emmeans)
contrast(m.3[[2]], interaction = c("factora", "factorb", "numeric"))

this however does not support glmer.
Any ideas?

A: There are a couple of issues here that are tripping you up.
One is that we don't really apply contrasts to numeric predictors. Numeric predictors have slopes, not contrasts; and if you have a model where a numeric predictor interacts with a factor, that means that the slope for the numeric predictor is different for each level of the factor. The function emtrends() in the emmeans package can help you estimate those different slopes.
The second is that the interaction argument in emmeans::contrast() needs a specification for the type of contrasts to use, e.g., "pairwise". The factors to apply them to are those in the emmGrid object in the first argument.
So... I think maybe you want to try something like this:
emt <- emtrends(model, ~ factora*factorb, var = "numeric")
emt    # list the estimated slopes

contrast(emt, interaction = "consec")
    # obtain interaction contrasts comparing consecutive levels of the two factors


text:
Q: How to watch a server's HDD activity (opened files and simple hddled) in SSH? I'd like to see if a hard disk is being actively used right now (a hddled-like indicator) and what particular files are being accessed. How can I achieve this in command line with SSH?

A: You can see the usage by using a tool like iotop.  You can see a list of open files by using the command lsof.

A: In addition to iotop/lsof that was already mentioned, some other options include nmon, iostat, or atop.  See this post on StackOverflow or this other question here on ServerFault.

A: Assuming you wanted to run the command through ssh and not just ssh directly to the machine. The command from ssh will look some thing like this:
ssh <hostname> lsof <options>
If you need this to run as root from a script, slightly fancy use of sudo and ssh keys should get you no requirement for a password. But be careful slightly to fancy use of sudo and ssh keys can just up and give anybody root access to your box.


text:
Q: MySQL IF... SELECT statement whilst retaining column headers Fumbling in the dark with MySql but it isn't too bad. (I am a coding novice)
I have a massive database that I need to join to another database (in Arc GIS). I originally did some code to get the joining database with headers (necessary for the join) as that surprisingly didn't come as standard when generating sub data sets with MySQL.
As it is still 3 million records I need to wittle the data down. I am originally did this by querying whether it contained part of a grid square reference (but no titles!). So now I'm trying to see if it contains an image number (grid_image) whilst retaining the column headers. So IF it a field contains a certain number SELECT ... INTO OUTFILE.
I'm struggling with the IF though, any help would be greatly appreciated :).
Laura
Code thus far:
WHERE geograph_db.image_numbers.column1 = geograph_db.gridimage_geo.gridimage_id
SELECT 'gridimage_id','nateastings','natnorthings', 'view_direction'
UNION
SELECT gridimage_geo.gridimage_id, gridimage_geo.nateastings,  gridimage_geo.natnorthings, gridimage_geo.view_direction
INTO OUTFILE 'geo.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
FROM geograph_db.gridimage_geo
;

Sorry its awful.

A: Here is what the syntax should be, I think.
SELECT 'gridimage_id','nateastings','natnorthings', 'view_direction'
  UNION
SELECT gridimage_geo.gridimage_id, gridimage_geo.nateastings,
  gridimage_geo.natnorthings, gridimage_geo.view_direction
INTO OUTFILE 'geo.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
FROM geograph_db.gridimage_geo, geograph_db.image_numbers
WHERE image_numbers.column1 = gridimage_geo.gridimage_id;


text:
Q: Align Equations in Subequations I would like to align these equations as shown in the picture by eq. 3.1.

I tried to use the command \begin{align*} unsuccessfully. My equations are automatically set to the centre, I've also tried to itemise the equations but I do get an error.
% --------------
%\begin{align*}
\begin{subequations} \label{eq:optimalsteuerungsprob_zeitkont}
    \begin{equation} \label{eq:optProb_J_Phi_l}
        \min_{\textbf{u} \in \mathcal{A}} \quad J[\textbf{u}(\cdot)] = \varphi\big(t_f, \textbf{x}(t_f)\big) + \int_{t_s}^{t_f} l\big(t,\textbf{x}(t),\textbf{u}(t)\big)\,\mathrm{d}t
    \end{equation}
    \begin{equation}
        \text{u.B.v.} \quad \dot{\textbf{x}}(t) = \textbf{f}(t,\textbf{x}(t), \textbf{u}(t)) \qquad , \qquad \textbf{x}(0)=\textbf{x}_{0}
    \end{equation}
    \begin{equation} \label{eq:optProb_endbedin_PSI}
        \psi\big(\,t_f,\textbf{x}(t_f)\big) = \textbf{0}
    \end{equation}
    \begin{equation}
        \textbf{h}\big(t,\textbf{x}(t),\textbf{u}()t\big) \le \textbf{0} \quad , \quad \forall t \in [t_{s},t_{f}]
    \end{equation}
\end{subequations}
%\end{align*}
%-----------------

Could You please help me in this task for my final thesis?
Many thanks

A: I would use alignat inside subequations without any additional space between columns. The code:
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{subequations} \label{eq:optimalsteuerungsprob_zeitkont}
\begin{alignat}{2}
  \min_{\textbf{u} \in \mathcal{A}} \quad &J[\textbf{u}(\cdot)] = \varphi\big(t_f, \textbf{x}(t_f)\big)+{}&&\int_{t_s}^{t_f}
        l\big(t,\textbf{x}(t),\textbf{u}(t)\big)\,\mathrm{d}t\label{eq:optProb_J_Phi_l}\\
        \text{u.B.v.} \quad &\dot{\textbf{x}}(t) = \textbf{f}(t,\textbf{x}(t), \textbf{u}(t)),
  &&\textbf{x}(0)=\textbf{x}_{0}\\
  &\psi\big(\,t_f,\textbf{x}(t_f)\big) = \textbf{0}\label{eq:optProb_endbedin_PSI}\\
  &\textbf{h}\big(t,\textbf{x}(t),\textbf{u}()t\big) \le \textbf{0}, &&\forall t \in [t_{s},t_{f}]
\end{alignat}
\end{subequations}
\end{document}

The result (see that the second columns in rows 2 and 4 are aligned to the integral sign):

A: The layout and numbering seems a little unusual, I ended up having to have align immediately following another display, then correcting for the bad space that causes.

Because you are numbering each line of the conditions in the same sequence as the equation you can't use aligned as a sub-term, which is what I'd normally use here.
\documentclass{article}

\usepackage{amsmath}

\begin{document}

% --------------

\begin{subequations} \label{eq:optimalsteuerungsprob_zeitkont}
\begin{equation}
    \label{eq:optProb_J_Phi_l}
        \min_{\textbf{u} \in \mathcal{A}} \quad J[\textbf{u}(\cdot)] = \varphi\bigl(t_f, \textbf{x}(t_f)\bigr) + \int_{t_s}^{t_f} l\bigl(t,\textbf{x}(t),\textbf{u}(t)\bigr)\,\mathrm{d}t
\end{equation}
\vspace{-\baselineskip}% sigh
\begin{align}
        \text{u.B.v.} \quad&\dot{\textbf{x}}(t) = \textbf{f}(t,\textbf{x}(t), \textbf{u}(t)), && \textbf{x}(0)=\textbf{x}_{0}
\\ & \label{eq:optProb_endbedin_PSI}
        \psi\bigl(\,t_f,\textbf{x}(t_f)\bigr) = \textbf{0}
\\&
        \textbf{h}\bigl(t,\textbf{x}(t),\textbf{u}()t\bigr) \le \textbf{0},&& \forall t \in [t_{s},t_{f}]
    \end{align}
\end{subequations}
%\end{align*}
%-----------------
\end{document}

A: Here is how  to do that with alignat. I systematically replaced \textbf with \mathbf. Note there also exists a package for optimisation problems formatting, optidef.
\documentclass{article}
\usepackage{mathtools}

\begin{document}

\begin{subequations} \label{eq:optimalsteuerungsprob_zeitkont}
    \begin{alignat}{3} \label{eq:optProb_J_Phi_l}
         & \min_{\mathbf{u} \in \mathcal{A}} & & J[\mathbf{u}(\cdot)] = \varphi\big(t_f, \mathbf{x}(t_f)\big)+ {}& & \int_{t_s}^{t_f} l\big(t,\mathbf{x}(t),\mathbf{u}(t)\big)\,\mathrm{d}t \\[2ex]
         & \text{u.B.v.} & \quad & \dot{\mathbf{x}}(t) = \mathbf{f}(t,\mathbf{x}(t), \mathbf{u}(t)),%
         & & \mathbf{x}(0)=\mathbf{x}_{0} \\ \label{eq:optProb_endbedin_PSI}
         & & & \psi\big(\,t_f,\mathbf{x}(t_f)\big) = \mathbf{0} \\
         & & & \mathbf{h}\big(t,\mathbf{x}(t),\mathbf{u}()t\big) \le \mathbf{0}, %
         & & \forall t \in [t_{s},t_{f}]
    \end{alignat}
\end{subequations}

 \end{document}


text:
Q: Inserting into mysql table with archive engine "duplicate key" error I am trying to archive some files using mysql archive engine. I am using this query to insert file contents:
insert into test_table (id,arch) values (123,'FILE_CONTENT')

After inserting 2 records, I get "duplicate key" error from mysql for a key that doesn't exist in the table. I checked it like 5 times but the record is not there. I selected count(*) for the duplicate id and the result is 0.
I checked the same code with an innodb engine and it works fine. Can anyone tell me what the problem is with the archive engine?
EDIT:
My table info is
CREATE TABLE `test_table` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `arch` mediumtext,
  PRIMARY KEY (`id`)
) ENGINE=ARCHIVE AUTO_INCREMENT=100175977 DEFAULT CHARSET=utf8mb4;

A: It looks like you have discovered a bug in the ARCHIVE engine. The insertion seems to be failing as soon as you try to insert a record with a value for an AUTO_INCREMENT column smaller than the AUTO_INCREMENT property of the table.
This works fine:
CREATE TABLE test_table1 (
  id INT NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (id)
) ENGINE=ARCHIVE AUTO_INCREMENT=123; -- notice the AUTO_INCREMENT value

INSERT INTO test_table1 (id) value (123); -- ok

But this fails with "Duplicate key":
CREATE TABLE test_table2 (
  id INT NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (id)
) ENGINE=ARCHIVE AUTO_INCREMENT=124; -- notice the AUTO_INCREMENT value

INSERT INTO test_table2 (id) value (123); -- duplicate key

MyISAM and InnoDB do not exhibit this behaviour, and I can find no reference to this in the docs. I would file a bug at MySQL if I were you (verified under v5.5.6 and v5.5.32).


text:
Q: Spring Cloud Contract: Access hostname and port in contract response for URL generation we are trying to provide a contract with the following characteristics:
import org.springframework.cloud.contract.spec.Contract

Contract.make {
    request {
        method(GET())
        url("/v2/entity")
        headers {
            accept(applicationJson())
        }
    }
    response {
        status 200
        body( """
         {
            "saveLink": "http://<requestedHost>:<requestedPort>/v2/entity/save"
          }
        )
    }
}

If our client uses the stubrunner and chooses a different port, e.q. 9876, the "saveLink" should reflect this port in the response URL.
We couldn'd find a simple API way to get the host and port information. fromRequest() or url() only return the relative part of the request URL. Is there an API method or a simple solution to this requirement? Any other suggestions?

A: To begin with I think that you're misuing the concept of contract testing. I wonder why is it crucial for you to have those concrete values there? In contract tests you would be only interested that the link contains some value of a URL and port. You wouldn't even make a call to that URL. So most likely you should change your approach before going any further.
If however you decide that this is the only way to go I present my opinion on how you could solve this (I haven't tested it though but it looks like it should work ;) ).
Currently making this all work is not easy. It will be easier in the upcoming Edgware release once this https://github.com/spring-cloud/spring-cloud-contract/pull/429 gets merged.
I'll try to think of a workaround though. What we will do is to add an transformation mechanism that will modify the response payload before sending it back from WireMock. We will need the transformation class and we'll need to extend the existing stub serving mechanism too.
First, let's create a custom WireMock extension that will analyze each mapping that is consumed by WireMock. We will want to modify only the one that has the saveLink in it.
class CustomExtension extends ResponseTransformer {

    @Override
    String getName() {
        return "url-transformer";
    }

    /**
     * Transformer that converts the save the way we want it to look like
     */
    @Override
    Response transform(Request request, Response response, FileSource files, Parameters parameters) {
    if (requestRelatedToMyParticularCase(response)) {
      String body = "\"{\"saveLink\" : \"http://"+ url.host + ":" + url.port + "/v2/entity/save\"}\"";
      return new Response(response.getStatus(), response.getStatusMessage(),
                body, response.getHeaders(), response.wasConfigured(), response.getFault(), response.isFromProxy());
    }
    // if it's not related continue as usual
        return response;
    }

  private boolean requestRelatedToMyParticularCase(Response response) {
    // is it related to your particular scenario ?
    return response.bodyAsString.contains("saveLink");
  }

    /**
     * We want to apply this transformation for all mappings
     */
    @Override
    boolean applyGlobally() {
        return true
    }
}

Now, you can create a class that implements the HttpServerStub and register it as presented here - http://cloud.spring.io/spring-cloud-static/Dalston.SR3/#_custom_stub_runner . It's basically a copy of WireMockHttpServerStub with a change where we add the transformer manually
public class MyCustomWireMockHttpServerStub implements HttpServerStub {

    private static final Logger log = LoggerFactory.getLogger(MyCustomWireMockHttpServerStub.class);
    private static final int INVALID_PORT = -1;

    private WireMockServer wireMockServer;

  @Override
    public HttpServerStub start(int port) {
        this.wireMockServer = new WireMockServer(myConfig().port(port)
                .notifier(new Slf4jNotifier(true)));
        this.wireMockServer.start();
        return this;
    }

    private WireMockConfiguration myConfig() {
        if (ClassUtils.isPresent("org.springframework.cloud.contract.wiremock.WireMockSpring", null)) {
            return WireMockSpring.options()
                    .extensions(responseTransformers());
        }
        return new WireMockConfiguration().extensions(responseTransformers());
    }

    private Extension[] responseTransformers() {
      List<Extension> extensions = new ArrayList<>();
      extensions.add(defaultResponseTemplateTransformer());
      extensions.add(new CustomExtension());
      return extensions.toArray(new Extension[extensions.size()]);
    }

    private ResponseTemplateTransformer defaultResponseTemplateTransformer() {
        return new ResponseTemplateTransformer(false, helpers());
    }

    @Override
    public int port() {
        return isRunning() ? this.wireMockServer.port() : INVALID_PORT;
    }

    @Override
    public boolean isRunning() {
        return this.wireMockServer != null && this.wireMockServer.isRunning();
    }

    @Override
    public HttpServerStub start() {
        if (isRunning()) {
            if (log.isDebugEnabled()) {
                log.debug("The server is already running at port [" + port() + "]");
            }
            return this;
        }
        return start(SocketUtils.findAvailableTcpPort());
    }

    @Override
    public HttpServerStub stop() {
        if (!isRunning()) {
            if (log.isDebugEnabled()) {
                log.debug("Trying to stop a non started server!");
            }
            return this;
        }
        this.wireMockServer.stop();
        return this;
    }

    @Override
    public HttpServerStub registerMappings(Collection<File> stubFiles) {
        if (!isRunning()) {
            throw new IllegalStateException("Server not started!");
        }
        registerStubMappings(stubFiles);
        return this;
    }

    @Override public String registeredMappings() {
        Collection<String> mappings = new ArrayList<>();
        for (StubMapping stubMapping : this.wireMockServer.getStubMappings()) {
            mappings.add(stubMapping.toString());
        }
        return jsonArrayOfMappings(mappings);
    }

    private String jsonArrayOfMappings(Collection<String> mappings) {
        return "[" + StringUtils.collectionToDelimitedString(mappings, ",\n") + "]";
    }

    @Override
    public boolean isAccepted(File file) {
        return file.getName().endsWith(".json");
    }

    StubMapping getMapping(File file) {
        try (InputStream stream = Files.newInputStream(file.toPath())) {
            return StubMapping.buildFrom(
                    StreamUtils.copyToString(stream, Charset.forName("UTF-8")));
        }
        catch (IOException e) {
            throw new IllegalStateException("Cannot read file", e);
        }
    }

    private void registerStubMappings(Collection<File> stubFiles) {
        WireMock wireMock = new WireMock("localhost", port(), "");
        registerDefaultHealthChecks(wireMock);
        registerStubs(stubFiles, wireMock);
    }

    private void registerDefaultHealthChecks(WireMock wireMock) {
        registerHealthCheck(wireMock, "/ping");
        registerHealthCheck(wireMock, "/health");
    }

    private void registerStubs(Collection<File> sortedMappings, WireMock wireMock) {
        for (File mappingDescriptor : sortedMappings) {
            try {
                wireMock.register(getMapping(mappingDescriptor));
                if (log.isDebugEnabled()) {
                    log.debug("Registered stub mappings from [" + mappingDescriptor + "]");
                }
            }
            catch (Exception e) {
                if (log.isDebugEnabled()) {
                    log.debug("Failed to register the stub mapping [" + mappingDescriptor + "]", e);
                }
            }
        }
    }

    private void registerHealthCheck(WireMock wireMock, String url) {
        registerHealthCheck(wireMock, url, "OK");
    }

    private void registerHealthCheck(WireMock wireMock, String url, String body) {
        wireMock.register(
                WireMock.get(WireMock.urlEqualTo(url)).willReturn(WireMock.aResponse().withBody(body).withStatus(200)));
    }
}


text:
Q: Is it possible to embed conditional actions into barcode I would like to know if it possible to create a barcode that contains conditional logic.
if (x == true)
   do this
else
   do that

The context would be someone using the camera on their mobile device to scan a barcode.
Taking the pseudo-code from above and applying it to my particular use case the scenario becomes:
if (mobile device has particular mobile app installed and active session is detected)
    open mobile app to particular module and update something

else if (mobile device has particular mobile app installed and no active session is detected)
    prompt user to authenticate, followed by opening module and updating something

else
   prompt user to download and install mobile app

A)  Is this possible?
B)  If yes, is there a particular set of barcode types (e.g. 1D and/or 2D barcodes) that would need to be used in order to achieve this?
C)  Is there a limitation to any particular mobile device that could do this (e.g. platform dependence)?


text:
Q: Is there some thing in python language which is similar to interface in Java or C++ as well? I've used to program use Java or C++, both has the 'interface' mechanism. And in some books of Object Oriented Programming and Design Pattern, interface is often mentioned.
Is there anything similar to interface in Python?


text:
Q: Parse error: syntax error, unexpected end of file in /var/www/html/system/expressionengine/third_party/account/mcp.account.php on line 165 I'm receiving the error ' Parse error: syntax error, unexpected end of file in /var/www/html/system/expressionengine/third_party/account/mcp.account.php on line 165'
It appears to be a error around the content of 'get_header_html' class.
Can anyone help with why this is happening?
The output of mcp.account.php is a follows:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Account_mcp {

    /**
     * Constructor
     *
     * @access  public
     */

    var $data = array();

    function Account_mcp()
    {

        // no notices thank you
        error_reporting(E_ALL ^ E_NOTICE);

        // Make a local reference to the ExpressionEngine super object
        $this->EE =& get_instance();
        $head_html = $this->get_header_html();
        $this->EE->cp->add_to_head($head_html);
        $this->EE->cp->set_variable('cp_page_title', $this->EE->lang->line('account_module_name'));

        $this->data['module_root'] = BASE.AMP.'C=addons_modules'.AMP.'M=show_module_cp'.AMP.'module=account'.AMP;
        $this->data['module_root_unencoded'] = str_replace("amp;",'&',BASE.'&'.'C=addons_modules'.'&'.'M=show_module_cp'.'&'.'module=account'.'&');

        $this->EE->load->helper('form');

        # load property housename / number helper as it's often needed
        $this->EE->load->helper('format_house_name_number_helper');

    }

    // --------------------------------------------------------------------

    /**
     * Main Page
     *
     * @access  public
     */
    function index()
    {
        return $this->EE->load->view('admin/admin_home', $this->data, TRUE);
    }

    /**
     * create_agent_profile()
     * method for adding/editing agent profiles
     * @access  public
     */
    function create_agent_profile() {

        $this->EE->load->library('admin/agent_profile_lib');
        return $this->EE->agent_profile_lib->process($this->data);

    }

    /**
     * view_agent_list()
     * method for adding/editing agent profiles
     * @access  public
     */
    function view_agent_list() {

        $this->EE->load->library('admin/agent_profile_lib');
        return $this->EE->agent_profile_lib->list_agents($this->data);

    }

    /**
     * delete_profile()
     * deletes an agent profile and all associated content
     * @access  public
     */
    function delete_profile() {

        $this->EE->load->model('agent_profile');
        $this->EE->agent_profile->delete_profile();
        $this->EE->session->set_flashdata('status_msg', 'Agent successfully deleted.');
        header("location: ".$this->data['module_root_unencoded']."method=view_agent_list");
        exit();
    }

    /**
     * ajax_list_agents()
     * returns html list of agents for ajax request
     * @access  public
     */
    function ajax_list_agents() {

        $this->EE->load->library('admin/agent_profile_lib');
        $this->EE->agent_profile_lib->ajax_list_agents($this->data);

    }

    /**
     * instructions()
     * method for viewing list of pending instructions etc.
     * @access  public
     */
    function instructions() {

        $this->EE->load->library('admin/admin_instructions_lib');
        return $this->EE->admin_instructions_lib->process($this->data);

    }

    /**
     * invoices()
     * method for managing and viewing invoices
     * @access  public
     */
    function invoices() {

        $this->EE->load->library('admin/admin_invoices_lib');
        return $this->EE->admin_invoices_lib->process($this->data);

    }

    /**
     * get_header_html()
     * returns output buffer of header for control panel i.e. CSS
     * @access  public
     */
    function get_header_html() {

        // get HTML for header
        ob_start();
        ?>

        <script type="text/javascript" src="<?=NSM_SITE_URL?>js/json2.js"></script>
        <script type="text/javascript" src="<?=NSM_SITE_URL?>js/admin.js"></script>

        <link href="<?=site_url()?>css/admin.css" media="screen" rel="stylesheet" type="text/css" />

        <!--[if IE]>
        <link rel="stylesheet" type="text/css" href="<?=site_url()?>css/admin_ie.css" />
        <![endif]-->

        <!--[if IE 6]>
        <link rel="stylesheet" type="text/css" href="<?=site_url()?>css/admin_ie6.css" />
        <![endif]-->

        <?
        $return = ob_get_contents();
        ob_end_clean();
        return $return;

    }

}
// END CLASS

/* End of file mcp.account.php */
/* Location: ./system/expressionengine/third_party/account/mcp.account.php */
?>


text:
Q: oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1350) . Exception while update I am updating records using JDBC PreparedStatement, and I'm not understanding where I went wrong. I think exception is occurring on excuteUpdate() or is there anything wrong in my code?
My code for updating looks like below code
try {
         cn.setAutoCommit(false);
         ps=cn.prepareStatement("update ISEVAENQUIRY set DATED=?,SOURCE1 =?,SOURCE2=?,CALLON=?,CALLBY =?,NAMEN=?,SBIC=?,SBISMSSENTDATE=?"
                + ",NUMBER1=?,FORMFILLEDUPC =?,FORMFILLEDUPDATE=?,NUMBER2=?,FORMCOURIREDC=?,FORMCOURIREDDATE=?,EMAIL1 =?,FORMRECIC=?,FORMRECIDATE=?,EMAIL2 =?"
                + ",PAYEMNTRCC=?,PAYDATE=?,PAN=?,REMARKS=? where NUMBER1=?");
        ps.setString(1,val[0] );
        ps.setString(2,val[1] );
        ps.setString(3,val[2] );
        ps.setString(4,val[3] );
        ps.setString(5,val[4] );
        ps.setString(6,val[5] );
        ps.setString(7,val[6] );
        ps.setString(8,val[7] );
        ps.setString(9,val[8] );
        ps.setString(10,val[9] );
        ps.setString(11,val[10] );
        ps.setString(12,val[11] );
        ps.setString(13,val[12] );
        ps.setString(14,val[13] );
        ps.setString(15,val[14] );
        ps.setString(16,val[15] );
        ps.setString(17,val[16] );
        ps.setString(18,val[17] );
        ps.setString(19,val[18] );
        ps.setString(20,val[19] );
        ps.setString(21,val[20] );
        ps.setString(22,val[21] );
        ps.setString(23,val[8] );
        int c=ps.executeUpdate();
         cn.commit();
        if(c !=0)
        {
            result="updated";
            System.out.println(result);
        }
        ps.close();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

when executeUpdate() following exceptions are coming
 java.net.SocketInputStream.socketRead0(Native Method)
 java.net.SocketInputStream.socketRead(Unknown Source)
 java.net.SocketInputStream.read(Unknown Source)
 java.net.SocketInputStream.read(Unknown Source)
 oracle.net.ns.Packet.receive(Packet.java:283)
 oracle.net.ns.DataPacket.receive(DataPacket.java:103)
 oracle.net.ns.NetInputStream.getNextPacket(NetInputStream.java:230)
 oracle.net.ns.NetInputStream.read(NetInputStream.java:175)
 oracle.net.ns.NetInputStream.read(NetInputStream.java:100)
 oracle.net.ns.NetInputStream.read(NetInputStream.java:85)
 oracle.jdbc.driver.T4CSocketInputStreamWrapper.readNextPacket(T4CSocketInputStreamWrapper.java:123)
 oracle.jdbc.driver.T4CSocketInputStreamWrapper.read(T4CSocketInputStreamWrapper.java:79)
 oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1122)
 oracle.jdbc.driver.T4CMAREngine.unmarshalSB1(T4CMAREngine.java:1099)
 oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:288)
 oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:191)
 oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:523)
 oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207)
 oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1010)
 oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1315)
 oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3576)
 oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3657)
 oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1350)
 com.iseva.Servlet.UpdateIsevaEnquery.doGet(UpdateIsevaEnquery.java:65)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
 org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
 org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
 org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
 org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
 org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
 org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
 org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
 org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
 org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
 org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
 org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
 org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
 org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
 org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1104)
 org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
 org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1519)
 org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1475)
 java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
 java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
 org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
 java.lang.Thread.run(Unknown Source)

I don't understand why this happens, can any one help me?


text:
Q: What will be xpath query to read the value of tag element whose name attribute value is 'manufacturer' This is the sample XML file and I have to query the tag with the name attribute value 'manufacturer'.
<Car>
  <tag name="Engine">v12</tag>
  <tag name="Gear">6</tag>
  <tag name="SelfDrive">true</tag>
  <tag name="manufacturer">tesla</tag>
</Car>

A: You can try the following:
/Car/tag[@name='manufacturer']

Explanation:

*

*/Car will select the tag Car from the root node

*/tag will select from the previous node, Car in this case

*[@name='manufacturer'] will select only the elements that have an attribute name with a value of manufacturer


text:
Q: GridEngine on single machine: How can I limit cores for each job? I have a single machine with 32 cores (2 processors), and 32G RAM. I installed gridengine to submit jobs to those queues I created. But it seems jobs are running on all cores.
I wonder if there is way to limit cores and RAMs for each job. For example I have two queues: parallel.q and serial.q, so that I allocate 20G RAMS and 20 cores to serial.q but I want each job only use one core and maximum 1G RAMs, and 8G RAMs + 8 cores to a single parallel job. All 4 cores and 4G rams left for other usage.
How can I config my queue or gridengine to get the setting right? I tried to read the manual, but don't have a clue.
Thanks!

I don't have problem with parallel jobs. I have some serial jobs will call several different programs somehow the system will assign them all cores available. But I don't want all cores be used for jobs rather for example only two cores available for each job.(Each job has several programs run sequentially, in which case systems allocate each program a core). BTW, I would like have some idle cores all the time to process other jobs, like processing data. Is it possible or necessary?

A: In fact, if I understand well, you want to partition a single machine with several sub-queues, is that right?
This may be problematic with SGE because the host configuration allows you to set the number of CPU available on a given node. Than you create your queues and assign different hosts to different queues.
In your case, you shoud assign the same host to one master queue, and then add subordinate queues that can use only a given MAX_SLOTS slots.
But if I may ask one question: why should you partition it? If you set up only one queue and configure some parallel environment then you can just submit your jobs using qsub -pe <parallelEnvironment> <NSLOTS> and the grid engine takes care of everything. I suggest you setup at least an OpenMP parallel environment, because you won't probably need MPI on a shared memory machine like yours (it seems a great machine BTW).
Another thing is that you must be able to configure your model run so that the code that you are using can be used with a limited number of CPU; this is very important. In practice you must assign the same number of CPUs to the simulation code than to the SGE. This information is contained in the $NSLOTS variable of your qsub-script.


text:
Q: How to determine required max_allowed_packet size when used with PDO and prepared statements? Or through example, what does max_allowed_packet need to be to perform the following query?  Please do not just give me the value, but explain how you determined it.  Thank you
$stmt=$pdo->prepare('INSERT INTO t(c1,c2,c3) VALUES(?,?,?)');
$stmt->execute([9876543210,9876543210,9876543210]);

EDIT.  Or what about this one:
$sql='INSERT INTO t(pk,c1,c2) VALUES(?,?,?), (?,?,?), (?,?,?)
ON DUPLICATE KEY UPDATE c1=VALUES(c1),c2=VALUES(c2)';
$stmt=$pdo->prepare($sql);
$stmt->execute([1,111,111,2,222,222,3,333,333]);

A: To calculate the max_allowed_packet size, take the byte length of your largest blob column and multiply times 11. For more details, see this post.
In your example, though you have a lengthy query not a large quantity of blob data. Based on my experience the multiply by 11 guideline will still work, but it's not an optimal way to tune the value.
As commented above, evidence is the optimal means to tune this value. I would set the max_allowed_packet to an arbitrarily huge value, like 1G. (The maximum MySQL supports, I believe.) Then, run your software in normal operation. If you don't get a PACKET_TOO_LARGE error, then cut the value in half and try again. Repeat until you do overflow the limit then double. That will then represent a reasonable upper-bound for your particular needs, with plenty of head room for growth.


text:
Q: Matriz de estructura c++ Buenas, primero para ponerlos en contextos la funcion del codigo es agregar X productos de una tienda y luego si el cliente asi lo quiere agregar otra tienda con Y productos el problema ocurre cuando se va a imprimir pues las filas pueden tener diferente cantidad de columnas.
#include <iostream>
#include <vector>

using namespace std;

struct comida{
  int cant;
  string name;
  float price;
}f;

vector <comida> food1; //Vector que guarda la estructura de productos de una tenda
vector <vector<comida>> food;//Vector hecho a base del vector anterior para añadir las diferentes tiendas

int main ()
{
  string ans,ans2;//Vectores de verificacion
  do
  {
    do
    {
      cout << "\nIngrese nombre: ";
      cin >> f.name;
      cout << "\nIngrese cantidad: ";
      cin >> f.cant;
      cout << "\nIngrese precio: ";
      cin >> f.price;
      food1.push_back(f);//Al vector de los productos se le van agregando gracias al do while
      cout << "\nDesea seguir 0<-no otro numero si: ";
      cin >> ans;//Pidiedo variable verificadora
    }while(ans!="0");//Verificador, en caso de que el cliente quiera seguir o no

    food.push_back(food1);//Se guarda el vector de productos en el vector de tiendas
    food1.clear();//Limpiamos en vector de productos

    cout << "\nAgregar otra tienda? 0<-no otro numero si: ";
    cin >> ans2;//Verificamos si quiere agregar otra tienda

  }while(ans2!="0");

  cout << "\nNombre\tCantidad   Precio" << endl;
  //Aqui surge el problema
  for (int i=0;i<food.size();i++)
  {
    int j=0,r=1;
    do
    {
      if(food[i][j].name!="\0"){
        cout << food[i][j].name << "\t" << food[i][j].cant << "\t   "  << food[i][j].price << "\t" << endl;}
      else
      {
        cout << "\t";
        r=0;
      }
      j++;
    }while(r!=0);
  }
}

Los datos que puse en entrada son:
cafe 120 10 1 tinto 200 20 1 tren 100 2000 0 1 ponque 20 200 1 pastel 50 400
0 0

A: Te estás expresando mal y eso hace que aún no hayas obtenido respuestas:

el problema ocurre cuando se va a imprimir pues las filas pueden tener diferente cantidad de columnas.

Eso que dices es totalmente erróneo. El número de columnas es fijo y su valor es siempre 3 (nombre, cantidad y precio).
El problema que tienes realmente es que cada tienda puede tener un número de artículos diferente... así que lo que realmente es variable es el número de filas (filas => eje Y, columnas => eje X).
Veamos:
for (int i=0;i<food.size();i++)
{
  int j=0,r=1;
  do
  {
    if(food[i][j].name!="\0"){
      cout << food[i][j].name << "\t" << food[i][j].cant << "\t   "  << food[i][j].price << "\t" << endl;}
    else
    {
      cout << "\t";
      r=0;
    }
    j++;
  }while(r!=0);
}

Bien, en esta porción de código intentas volcar el listado de cada tienda en la consola... tienes food.size() tiendas, así que parece lógico realizar una iteración desde 0 hasta food.size()... ahora bien, si resulta que para cada tienda (food[i]) tienes un vector con la lista de artículos... ¿Por qué no creas un segundo bucle que itere dicha lista?
for (int i=0;i<food.size();i++)
{
  for( int j=0;<food[i].size();j++)
  {
    cout << food[i][j].name << '\t' << food[i][j].cant << '\t'  << food[i][j].price << '\n';
  }
}

Aunque puestos a evitar redundancia...
for (int i=0;i<food.size();i++)
{
  vector<comida> & lista = food[i];
  for( int j=0;<lista.size();j++)
  {
    cout << lista[j].name << '\t' << lista[j].cant << '\t'  << lista[j].price << '\n';
  }
}

Los contenedores de la STL se diferencian de los arrays crudos (int* lista), en que son capaces de decirte cuántos elementos contienen. Aprovecha esta característica y déjate de insertar elementos vacíos al final de la lista... es un engorro innecesario lidiar con ese último elemento.


text:
Q: apt-add-repository raises an error I'm trying to install JDE (Java Development Environment), but apt-get fails with the following error:
me@ubuntu:~/$ sudo add-apt-repository ppa:webupd8team/java
You are about to add the following PPA to your system:
  Oracle Java (JDK) Installer (automatically downloads and installs Oracle JDK6 /    JDK7 / JDK8). There are no actual Java files in this PPA. More info: http://www.webupd8.org/2012/01/install-oracle-java-jdk-7-in-ubuntu-via.html

Debian installation instructions: http://www.webupd8.org/2012/06/how-to-install-oracle-java-7-in-debian.html
 More info: https://launchpad.net/~webupd8team/+archive/java
 Press [ENTER] to continue or ctrl-c to cancel adding it

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/dist-packages/softwareproperties/ppa.py", line 99, in run
    self.add_ppa_signing_key(self.ppa_path)
  File "/usr/lib/python2.7/dist-packages/softwareproperties/ppa.py", line 132, in add_ppa_signing_key
    tmp_keyring_dir = tempfile.mkdtemp()
  File "/usr/lib/python2.7/tempfile.py", line 322, in mkdtemp
    name = names.next()
  File "/usr/lib/python2.7/tempfile.py", line 141, in next
    letters = [choose(c) for dummy in "123456"]
  File "/usr/lib/python2.7/random.py", line 274, in choice
    return seq[int(self.random() * len(seq))]  # raises IndexError if seq is empty
ValueError: cannot convert float NaN to integer

So, please can someone tell me, what can I do?
(Sorry for my bad English, I hope you understand)

A: actually the problem which is bothering you is a Ubuntu BUG. Look at the BUG link . In the bug link Comment #4 and comment #11 have some good information for you.
comment #11 have patch too & apply that patch and its approved.


text:
Q: how to stop braintree to store payment_methode without asking for server side nonce? I have installed Braintree on our system for users subscriptions and everything works well, except for one strange behave of Braintree which is storing payment method without my server-side nonce.
My goal is to let the user have a maximum of 3 payment methods stored on his customer account.
Here is what I expect each time user add a payment method:

*

*server generates and sends the SDK to client-side

*client sends me nonce

*server sends a nonce and customer id to Braintree

*Brain tree store payment method of customer

Here is what I get after storing first payment method:

*

*server generates and sends the SDK to client-side

*client sends me nonce

*Brain tree already stored the payment method of the customer!

As you see Braintree stores payment_method without asking me for step 3. which is not good because then I can not limit the number of payment_methods which stored in the customer profile.

A: Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.
It sounds like you are passing a customer ID into the client token generation. As a result, the Drop-in UI displays a customer's stored payment methods and automatically stores any new payment methods added by the customer in your Braintree Vault upon tokenization.
If you are using Drop-in version 1.18.0 or later, you can pass vaultCard as false in the dropin.create option. You could then Vault the card server-side using the store_in_vault_on_success parameter or follow your desired workflow from here.


text:
Q: Is there a closed expression for $\sum_{n=0}^\infty \frac{n^2a^n}{n!}$, where $a \in (0,\infty)$? Is there a closed expression for $\sum_{n=0}^\infty \frac{n^2a^n}{n!}$, where $a \in (0,\infty)$?
I have concluded that the sum converges using the ratio test: $\frac{(n+1)^2a^{n+1} n!}{n^2a^n(n+1)!}=\frac{(n+1)a}{n^2} \rightarrow 0$ as $n\rightarrow \infty$. Also, by comparison the following "similar expression" has a closed form:  $\sum_{n=0}^\infty \frac{na^n}{n!} = a\sum_{n=0}^\infty \frac{na^{n-1}}{n!}=ae^a$

A: Hint. Note that for $n\geq 2$,
$$\frac{n^2}{n!}=\frac{n(n-1)+n}{n!}=\frac{1}{(n-2)!}+\frac{1}{(n-1)!}.$$

A: Start with
$$e^x=\sum_{n=0}^\infty\frac{x^n}{n!}$$
Differentiate both sides:
$$e^x=\sum_{n=0}^\infty\frac{nx^{n-1}}{n!}$$
Multiply by $x$:
$$xe^x=\sum_{n=0}^\infty\frac{nx^n}{n!}$$
Differentiate both sides:
$$(x+1)e^x=\sum_{n=0}^\infty\frac{n^2x^{n-1}}{n!}$$
Multiply by $x$:
$$x(x+1)e^x=\sum_{n=0}^\infty\frac{n^2x^n}{n!}$$


text:
Q: Allow Googlebot to crawl dynamically generated product pages I have been doing some reading into how Googlebot crawls javascript generated webpages but am still a little confused on it.
Say I have a web page for company XYZ Inc that has 5 general products like bath towels and Pencils.
How do I allow Googlebot to index www.xyzinc.com/products/bath-towels so that it shows up in the google search results such as:

XYZ Inc. - Bath Towels
www.xyzinc.com/products/bath-towels
some description here

My one idea was to created a Site Map that has a generated list of all the products on the page in nested links with links that I can feed to the Google Search Console, but I do not know if that is the right way to go about doing it.

A: I had this issue before with dynamic pages. What helped me is:

*

*Add all those links to sitemap.

*Make links accessible via custom url. (let's say each search on my site will generate new page if it doesn't exist with its unique url).

*Make each page unique.

A: I use 2 things to Allow Googlebot to crawl dynamically generated page

*

*routing (create a smart URL)

*I create statics Pages recaping my dynamicals pages with links to
them


text:
Q: Call fake not happening in unit testing of service method   function logOutUser() {
            var url = "User/Logout";
            httpWrapperService.post(url, {}, {}).then(function (success) {

            },
            function error(error) {

            });
            localStorageService.clearLocalStorage();
            httpWrapperService.setAuthenticationToken(null);
        }

Here is the code of testing
'use strict';

describe('Testing registration-service\n\n', function () {

var httpBackend = null;

var baseURL = null;
var services = {
    registration: null,
    settings: null,
    httpservice:null
};

// Initialization before tests
 beforeEach(function () {
        module("app");

        // Inject needed services
        inject(function ($httpBackend, _registrationService_, _settingsService_, _httpWrapperService_) {
            services.registration = _registrationService_;
            services.settings = _settingsService_;
            httpBackend = $httpBackend;
            httpservice=_httpWrapperService_;
            //modal=$modal
            // Get baseurl
            baseURL = services.settings.getServicesURL();

            // Default answer
            httpBackend.whenGET("languages/en.json").respond("OK");
        });
    });

  describe('Checking logOutUser() function for different test cases!!!\n', function () {

    jasmine.createSpy('setAuthenticationToken').and.CallFake(function() {
      //a fake implementation
    });

    console.log("setAuthenticationToken===", setAuthenticationToken);

        it("1. When user is logged in \n", function (done) {
           localStorage.SA_User='{"tokenId":"TICKET_1","rememberMe":true}';
           var url = baseURL + "User/Logout";
           httpBackend.whenPOST(url, {}).respond({});
           expect(localStorage.SA_User).toEqual(undefined);
           ///expect(1).toEqual(1);
           done();
        });

    });

});

I have a function defined in registration service (logoutuser). I want to unit test this function . I dont want to call httpWrapperService.setAuthentication function.
how can I do this , I tried using jasmine and spy using callfake but not able to do it in karma .
Any help is appreciated !!!!
Thanks

A: Try: spyOn(services.httpservice, 'setAuthenticationToken').and.callFake(function(){}) instead of the jasmine.createSpy. This should add the spy to the service.


text:
Q: Use a loop for slicing I'm trying to make a program where if you write in a word, let's say "Hello". And then you press the print button the outcome would be this:
"H"
"He"
"Hel"
"Hell"
"Hello".
Should i use a loop for this? My code so far is this:
function printit()
{
var temptext = document.getElementById("mytext").value;
temptext = temptext.slice(1,2);

document.getElementById("translated").innerHTML=temptext;
}

Anyone got any suggestions on how to solve this?

A: try this:

let word = 'Good';

for (let i = 1; i <= word.length; i++) {
  console.log(word.substring(0, i));
}

A: Here's how this would work with a loop.

*

*Loop over the characters

*Use the loop counter (i) to progressively slice the required chunk off your text.

*Make sure you slice(0, i + 1), so you don't slice(0, 0) on the 1st iteration

function print() {
  var text = document.querySelector("#text").value

  for(var i = 0; i < text.length; i++) {
    console.log(text.slice(0, i + 1))
  }
}
<input id="text" value="Hello"/>
<button onclick="print()">Print</button>

A: You can use .map() with a scoped variable, to return an array of the words you need

function toSplicedWordArray(what) {
   var before='';
   return what.split('').map(function(item) {before+=item;return before;});
}
console.log(toSplicedWordArray('hello'));

A:
function printinit() {
  var tempText = document.getElementById("mytext").value;
  var slicedText = "";
  for (var i = 0; i < tempText.length; i++) {
    slicedText = tempText.slice(0, i) + " ";
  }
  document.getElementById("translated").innerHTML = temptext;
}


text:
Q: Why array does not print list? #include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    int i;
    char s[10] = {'a' , 'b' ,'c' 'd' ,'e', 'f', 'g', 'g','h','i'};

    cout << "element" << setw(7) << "value " << endl;
    for (i=0 ; i <10 ; i++)
    cout << i << setw(7) << s[i] << endl;

    return 0;
}

I Wanted tp get list like
element       value
0              a
1              b
2              c
3              d
4              e
5              f
6              g
7              g
8              h
9              i

but compiler gives error....
Is there anyone who can point out my error?

A: There is a typo in the initializer list. You forgot to place a comma
char s[10] = {'a' , 'b' ,'c' 'd' ,'e', 'f', 'g', 'g','h','i'};
                          ^^^^


text:
Q: Multiple flex items next to eachother, fill out container I have a container with 3 items in a row. The items are less wide than the container it sits in. I want the three items to fill out the container.
This is because when I downscale my browser width I'd like the items to jump to 2 or 1 whenever the container can't fit them anymore.
So in short:
3 items of 200px next to eachother in a 660px container. The middle div should mimic margin: 0 30px;. But I don't want to put a margin on every 2nd item, because when the browser width becomes smaller there will be 2 or even 1 items in a row.
Here's my fiddle to make it a little less clear

A: This seems to be what you want

.container {
  display: flex;
  flex-flow: row wrap;
  width: 660px;
  justify-content: space-between;
  border: 1px solid grey;
}
.container .item {
  width: 200px;
  background: hotpink;
}

Item1

Item2

Item3

Item4

Item5

Item6


text:
Q: AVMutableVideoComposition sometimes won't play video I'm using this short snippet to set up my video. For some unknown reason - sometimes the video simply won't show up, while for other video it'll work perfectly.
let videoTrack: AVAssetTrack = asset.tracksWithMediaType(AVMediaTypeVideo)[0]
        let composition: AVMutableComposition = AVMutableComposition()

        let videoComposition: AVMutableVideoComposition = AVMutableVideoComposition()
        var videoSize: CGSize = videoTrack.naturalSize
        let isPortrait_: Bool = self.isVideoPortrait(asset)
        if isPortrait_ {
            NSLog("video is portrait ")
            videoSize = CGSizeMake(videoSize.height, videoSize.width)
        }
        composition.naturalSize = videoSize
        videoComposition.renderSize = videoSize
        // videoComposition.renderSize = videoTrack.naturalSize; //
        videoComposition.frameDuration = CMTimeMake(1, 30)

        let compositionVideoTrack = composition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: 1)
        let timeRange = videoTrack.timeRange
        do {
            try compositionVideoTrack.insertTimeRange(timeRange, ofTrack: videoTrack, atTime: kCMTimeZero)
        } catch {
            print("error")

        }
        let layerInst = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack)

        layerInst.setTransform(videoTrack.preferredTransform, atTime: kCMTimeZero)
        let inst: AVMutableVideoCompositionInstruction = AVMutableVideoCompositionInstruction()
        inst.timeRange = timeRange

        inst.layerInstructions = [layerInst]
        videoComposition.instructions = [inst]

        let playerItem = AVPlayerItem(asset: composition)
        playerItem.videoComposition = videoComposition

Tho for some videos, it simply wont show them up.
Any suggestions? Thanks!!

A: Hello i had a relative similar code hope this helps you figure out your problem
class func MergeVideosSequentially(URLS : [NSURL], callback : (error : ErrorType? , outURL : NSURL?) -> Void){
    let composition = AVMutableComposition()

    //videoTrack
    let videoTrack = composition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid)
    let audioTrack = composition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: kCMPersistentTrackID_Invalid)

    var cursorTime = kCMTimeZero
    for URL in URLS {
        let asset = AVAsset(URL: URL)
        let assetVideoTrack = asset.tracksWithMediaType(AVMediaTypeVideo).first! as AVAssetTrack
        let assetAudioTrack = asset.tracksWithMediaType(AVMediaTypeAudio).first! as AVAssetTrack

        var duration : CMTimeRange? = nil
        duration = CMTimeRangeMake(kCMTimeZero, asset.duration)

        do {
            try videoTrack.insertTimeRange(duration!, ofTrack: assetVideoTrack, atTime: cursorTime)
            try audioTrack.insertTimeRange(duration!, ofTrack: assetAudioTrack, atTime: cursorTime)
        }catch {
            print(error)
        }
        cursorTime = CMTimeAdd(cursorTime, asset.duration)
    }

    let directory = NSTemporaryDirectory()
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateStyle = .LongStyle
    dateFormatter.timeStyle = .ShortStyle
    let date = dateFormatter.stringFromDate(NSDate())
    let savePath = "\(directory)/mergedVideo-\(date).mp4"
    let url = NSURL(fileURLWithPath: savePath)

    let exporter = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetHighestQuality)
    exporter!.outputURL = url
    exporter!.shouldOptimizeForNetworkUse = true
    exporter!.outputFileType = AVFileTypeMPEG4

    exporter!.exportAsynchronouslyWithCompletionHandler({ () -> Void in
        let outputURL = exporter!.outputURL

        switch exporter!.status {
        case .Completed :
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                callback(error: nil, outURL: outputURL)
            })
        default:
            callback(error: CCMovieWriterError.CannotMergeClips, outURL: nil)
        }

    })
}


text:
Q: Spring ApplicationContextShutdownBean entries in log My SpringSource dm Server log is full of lines like the following:
com.springsource.server.kernel.dm.ApplicationContextShutdownBean < void com.springsource.server.kernel.dm.ApplicationContextShutdownBean.onApplicationEvent(ApplicationEvent)

making it hard to spot interesting log events.
How can I turn these log entries off?

A: why don't you suppress it via config/server.config?
"serviceability": {
            "trace": {
                "directory": "serviceability/trace",
                "levels": {
                   "com.springsource.server.kernel.dm.ApplicationContextShutdownBean" : "warn",
                    "*" : "info"


text:
Q: JCOP Shell does not output prompts I was working on an Applet of JCOP on Eclipse. But all of a sudden, no matter how I clean and try to create new projects, the JCOP Shell (JCShell) will selectively omit some outputs for commands sent in. I don't know what is wrong. And there does not seem to be any manual related to how I can set up JCShell.
Is there any commands or preference settings to make JCOP Shell reverse to the standard settings?

A: In order to receive full information, you should enable Trace APDUs and Comm details options:


text:
Q: How do I change user interface language in Firefox to avoid so-called localization? Since yesterday my Firefox thinks that everyone in Belgium speaks Flemish. This is a typically American problem: Americans NEVER seem to know where languages are spoken (I think they just guess), but for some reason believe that language localization software is cool.
It is NOT; it is a curse. So suddenly I no longer have my user interface in English (which was fine), but now in Flemish, which looks and reads like a tongue disease and is not even the second language of the area I live in (the first language here is German and second is French). How can I change back to English?

A: You should install an English language pack. A language pack is a Firefox add-on.
You can download it from here. Then you must install it like any other add-on ("install add-on from file" in the add-on interface).
Then you should change the language preference. You can do this by typing about:config in the Location bar (address bar) and then searching for

general.useragent.locale

And change that to:

en-US

(the same name as the downloaded .xpi)
Then you must restart the browser.
More details at:
http://kb.mozillazine.org/Language_packs

A: Install en-US https://addons.mozilla.org/en-US/firefox/addon/english-us-language-pack/ and have key intl.locale.requested set to en-US in about:config.
https://support.mozilla.org/en-US/kb/use-firefox-interface-other-languages-language-pack


text:
Q: HIbernate Mapping Exception: PropertyNotFoundException: Could not find a setter I have two POJO's ,STOCK and STOCK_DETAILS (one to many relationship).
Also I have one interface IAUDITLOG (having two methods). I need to implement this interface with BOTH POJO's and want to write some implementation within those methods. But when I implement IAUDITLOG interface with child class "STOCKDETAILS" then it gives exception "that you should have setter property"
STOCK CLASS:
@Entity
@Table(name = "stock")
public class Stock implements java.io.Serializable, IAuditLog
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer stockId;

    @Column(name = "STOCK_CODE")
    private String stockCode;

    @Column(name = "STOCK_NAME")
    private String stockName;

    @OneToMany( fetch = FetchType.LAZY, mappedBy = "stock")
    public Set<StockDetail> stockDetails = new HashSet<StockDetail>(0);

    public Set<StockDetail> getStockDetails() {
        return stockDetails;
    }

    public void setStockDetails(Set<StockDetail> stockDetails) {
        this.stockDetails = stockDetails;
    }

    public Integer getStockId() {
        return stockId;
    }

    public void setStockId(Integer stockId) {
        this.stockId = stockId;
    }

    public String getStockCode() {
        return stockCode;
    }

    public void setStockCode(String stockCode) {
        this.stockCode = stockCode;
    }

    public String getStockName() {
        return stockName;
    }

    public void setStockName(String stockName) {
        this.stockName = stockName;
    }

// overridded methods of IAUDITLOG interface
    public int getLogId() {

        return stockId;
    }
    public String getLogDetail() {
        return "some implementaion";
    }
}

STOCK DETAILS CLASS
@Entity
@Table(name = "StockDetail")
public class StockDetail implements Serializable, IAuditLog {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private Integer recordId;
    private Stock stock;
    private Float priceOpen;

    @Id
    @GeneratedValue
    @Column(name = "RECORD_ID", unique = true, nullable = false)
    public Integer getRecordId() {
        return this.recordId;
    }

    public void setRecordId(Integer recordId) {
        this.recordId = recordId;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "STOCK_ID", nullable = false)
    public Stock getStock() {
        return this.stock;
    }

    public void setStock(Stock stock) {
        this.stock = stock;
    }

    @Column(name = "PRICE_OPEN", precision = 6)
    public Float getPriceOpen() {
        return this.priceOpen;
    }

    public void setPriceOpen(Float priceOpen) {
        this.priceOpen = priceOpen;
    }

    //overriddded methods of IADUTILOG inteface
    public int getLogId() {
        // TODO Auto-generated method stub
        return 0;
    }

    public String getLogDetail() {
        // TODO Auto-generated method stub
        return "some implementation";
    }
}

IAUDITLOg interface:
public interface IAuditLog {
    public int getLogId();
    public String getLogDetail();
}

STACK TRACE:
Caused by: org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
    at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:185)
    at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:135)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:385)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1760)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1798)
    at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:247)
    at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:373)
    at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:358)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1571)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1509)
    ... 46 more
Caused by: org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
    at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:138)
    at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:188)
    at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:341)
    at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:507)
    at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:146)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:163)
    ... 55 more
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:135)
    ... 64 more
Caused by: org.hibernate.PropertyNotFoundException: Could not find a setter for property logDetail in class com.auditLog.common.StockDetail
    at org.hibernate.property.BasicPropertyAccessor.createSetter(BasicPropertyAccessor.java:252)
    at org.hibernate.property.BasicPropertyAccessor.getSetter(BasicPropertyAccessor.java:245)
    at org.hibernate.mapping.Property.getSetter(Property.java:326)
    at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertySetter(PojoEntityTuplizer.java:444)
    at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:201)
    at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:82)
    ... 69 more

Feb 26, 2014 10:17:08 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet dispatcher
org.hibernate.PropertyNotFoundException: Could not find a setter for property logDetail in class com.auditLog.common.StockDetail
    at org.hibernate.property.BasicPropertyAccessor.createSetter(BasicPropertyAccessor.java:252)
    at org.hibernate.property.BasicPropertyAccessor.getSetter(BasicPropertyAccessor.java:245)
    at org.hibernate.mapping.Property.getSetter(Property.java:326)
    at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertySetter(PojoEntityTuplizer.java:444)
    at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:201)
    at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:82)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:135)
    at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:188)
    at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:341)
    at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:507)
    at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:146)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

CAN ANYONE PLEASE LET ME KNOW,what could be the problem??? Why should I create getter and setter for those properties which is not ACTUALLY belongs to that class, but implemented from some other interface.
FYI... this works fine when I implement this interface with Parent class "STOCK"

A: For others who come across this and the above solution does not work, my error was that the name for my setter was not correct; it did not match the property it was setting. That's all

A: You should annotate the overridden methods with @Transient.
http://docs.oracle.com/javaee/5/api/javax/persistence/Transient.html

This annotation specifies that the property or field is not persistent. It is used to annotate a property or field of an entity class, mapped superclass, or embeddable class.

P.s. As of Hibernate 3 collections are lazy by default so there is no need to explicitly mark it as lazy.


text:
Q: Is it possible to have if/case in select Is it possible to write a sql query that returns a set of columns based on a condition? below is a sample query:
Select
    id
    ,name
    ,col3

From
Table A
,left outer join (If (select col6 from table D =='A')
 {
     Select col3,col4,col5 as id
      From Table A
      ,left join table C
      ,left join
  }
 Else If (select col6 from table D =='D')
 {
   Select Col1, Col3 as id
    From Table A
  } ) as temp_tab on temp_tab.id = table A.id

,left outer join Table R on table R.name = table A.name

where id = 129

A: You can do this with dynamic SQL or ref cursors, which means a procedural approach. So you need to be clear about what it is you are trying to do and what benefits you hope to gain. This particularly affects how your code is called.
If you need a pure SQL approach you can try something like this. The projection of the inline view (temp_tab) is static but its actual values vary according to the content of d.col6.
select
    x.id
    ,x.name
    ,temp_tab.col3
    ,temp_tab.col4
    ,temp_tab.id
from x
left outer join
 (
     select case
                when d.col6 = 'A' then a.col3
                when d.col6 = 'D' then a.col1
                else null
            end as col3
            ,case
                when d.col6 = 'A' then c.col4
                else null
             end as col4
            ,case
                when d.col6 = 'A' then a.col5
                when d.col6 = 'D' then a.col3
                else null
             end as id
      from d
           cross join a
           left outer join c on a.whatever = c.whatever
      where (d.col6 = 'D' or c.whatever is not null)
 ) as temp_tab on temp_tab.id = x.id
where x.id = 129

Depending on your precise requirements this may suffice for you, but obviously it is quite a clunky solution. Dynamically changing the tables in the FROM clause or the conditions in WHERE clause is tricky to impossible: if you need to do that you're looking at using dynamic SQL.


text:
Q: Daemon app to fetch list of events from personal microsoft account I have created a web app in past to access calendar events from ADD user's calendars. It worked fine, Now I want to create a daemon app that can fetch the calendar events of my personal outlook account or from account of people from my organization.
I followed this section of microsoft graph api docs :
https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-daemon-overview
I could only get all user details present in my Azure active directory but I am unable to fetch calendar events.
In my parameters.json file. I mentioned my endpoint as : https://graph.microsoft.com/v1.0/users/{user id}/events
The official docs(link given above) told that we cannot access the web API which require 'incremental consent'. I want to know can I access calendar events from daemon apps as a background service using MS graph api. If yes, please provide my any links or resource
to do so. I tried searching on stackoverflow also but couldn't find any resource or doc which I can use.
Your help would be really appreciated. Thankyou.

A: To use client credential flow, you need to add application permissions in your registered application in Azure portal, and this permission need admin consent.

Reference:
Get access without a user.


text:
Q: Unit-length vector x maximizing $||Mx+b||^2$ I am looking for the unit-length vector x which maximizes the expression
$||\mathbf{M}\,\mathbf{x}\,+\mathbf{b}||^2$ (euclidean norm), given a 2x2 (invertible) matrix M and a 2-vector b. For $||\mathbf{M}\,\mathbf{x}||^2$ I can simply use the eigen-decomposition of M -- is there an equivalent solution for this problem?

A: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\fermi}{\,{\rm f}}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\half}{{1 \over 2}}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\ol}[1]{\overline{#1}}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
$$
{\cal F}\pars{{\bf x}^{\sf T}}
\equiv \pars{{\bf x}^{\sf T}M^{\sf T} + {\bf b}^{\sf T}}\pars{M{\bf x} + {\bf b}}
- \mu\pars{{\bf x}^{\sf T}{\bf x} - 1}
$$
$$
\delta{\cal F}\pars{{\bf x}^{\sf T}}
= \delta{\bf x}^{\sf T}\pars{M^{\sf T}M{\bf x} + M^{\sf T}{\bf b} - \mu{\bf x}}
$$
Solve $M^{\sf T}M{\bf x} + M^{\sf T}{\bf b} - \mu{\bf x}
=\pars{M^{\sf T}M - \mu}{\bf x} + M^{\sf T}{\bf b} = 0$. It yields:
${\bf x} = -\pars{M^{\sf T}M - \mu}^{-1}M^{\sf T}{\bf b}$. $\mu$ is determided by the condition:
$$
1 = {\bf x}^{\sf T}{\bf x} = {\bf b}^{\sf T}M\bracks{\pars{M^{\sf T}M - \mu}^{-1}}^{\sf T}\pars{M^{\sf T}M - \mu}^{-1}M^{\sf T}{\bf b}
$$


text:
Q: Google AI Platform training - wait for the job to finish I've built an AI Platform pipeline with a lot of parallel processes. Each process launches a training job on the AI Platform, like this:
gcloud ai-platform jobs submit training ...

Then it has to wait for the job to finish to pass to the next step. For doing this, I've tried to add the parameter --stream-logs to the above command. In this way, it streams all the logs until the job is done.
The problem is, with so many parallel processes, I run out of requests for getting logs:
Quota exceeded for quota metric 'Read requests' and limit 'Read requests per minute'
of service 'logging.googleapis.com'

But I do not need to actually stream the logs, I just need a way to tell the process to "wait" until the training job is done. Is there a smarter and simpler way of doing this?

A: I've just found that I can use the Python API to launch and monitor the job:
training_inputs = {
    'scaleTier': 'CUSTOM',
    'masterType': 'n1-standard-8',
    ...
}

job_spec = {'jobId': 'your_job_name', 'trainingInput': training_inputs}

project_name = 'your-project'
project_id = 'projects/{}'.format(project_name)

cloudml = discovery.build('ml', 'v1')

request = cloudml.projects().jobs().create(
    body=job_spec,
    parent=project_id
)
response = request.execute()

Now I can set up a loop that checks the job state every 60 seconds
state = 'RUNNING'
while state == 'RUNNING':

    time.sleep(60)
    status_req = cloudml.projects().jobs().get(name=f'{project_id}/jobs/{job_name}')

    state = status_req.execute()['state']

    print(state)

A: Regarding the error message you are experiencing, indeed you are hitting a quota exceeded for Cloud Logging, what you can do is to request a quota increase.
On the other hand, about an smarter way to check the status of a job without streaming logs, what you can do is to check the status once in a while by running gcloud ai-platform jobs describe <job_name> or create a Python script to check the status, this is explained in the following documentation.


text:
Q: how can i give a target blank on the specific href tag in my navigation jQuery i will to give a specific outside link in my navigation with target blank. How can i solve this with jQuery ?
Here my Site:
http://devel.hoevermann-gruppe.de/
If you click `auf "Kontakt" in the head navigation you see the mega sub menuand if you click on Facebook, so the outside started in the same window tab but i will use the target blank tag.

A: Is this what you want?
$('a[href*="www.facebook.com"]').attr('target', '_blank');


text:
Q: Segmentation fault when trying to copy elements of a string (C) I am trying to work on a problem for school which requires me to reverse a string in place (among other things..). I have been struggling with this for awhile and am out of ideas.. here is my code:
void strRev(char*s)
{
    int i = 0;
    int length = strlen(s);
    char*rev = (char*)malloc((length+1)*sizeof(char));

    strcpy(rev,s);

    for(i;i<length;i++)
        s[i] = rev[length - 1 - i];

    printf("%s    %s",rev,s);
}

int main()
{
    char * test = "hello";
    strRev(test);
}

when I step through in Visual Studio, it hangs when it reaches the line inside the for loop. Unix gives me a segmentation fault. I know this must be something simple I'm missing, but I'm out of ideas and none of the answers online are helping.. And I'm running out of time.. Someone please enlighten me, what am I doing wrong?

A: Well, your code doesn't do it in place (else you wouldn't use malloc, also why are you using sizeof(char)?).
Try this:
void strRev(char*s)
{
    int i, len;
    char tmp;
    len = strlen(s);
    for(i = 0; i < (len >> 1); ++i)
    {
       tmp = s[len - 1 - i];
       s[len - 1 - i] = s[i];
       s[i] = tmp;
    }
}

And then modify you main() as the comments suggest.

A: test points to statically allocated buffer which must not be modified. And you do modify it by assigning s[i]=rev[...]. This causes segfault.
I think you wanted to write rev[i]=s[...].
If you need to do it in place then allocate memory for "hello" dynamically (strdup) or on stack.


text:
Q: Find out if cubic equation has real solution or complex ones? Without knowing any solution to that equation, is there a way to quickly tell if it has 3 real solution or 1 real and 2 conjugated ones?

A: A cubic may have two extrema or none. Three roots are possible when it has extrema and they have opposite signs.
For convenience, let us consider the depressed form,
$$x^3+px+q.$$
The maxima occur at the roots of
$$3x^2+p,$$ hence they require $p$ to be negative and $$x=\pm\sqrt{-\frac p3}.$$
Then the values at these extrema are
$$\mp\frac p3\sqrt{-\frac p3}\pm p\sqrt{-\frac p3}+q=\pm\frac23p\sqrt{-\frac p3}+q$$ and their product is
$$q^2+\frac{4p^3}{27},$$ which must be negative.

To depress the cubic
$$ax^3+bx^2+cx+d,$$ divide by $a$ and translate the argument by $\dfrac b{3a}$.


text:
Q: tmux cuts symbols in status bar For some reason, I can't use tmux battery plugin, so I've written a small script to get battery status:
percentage=$(cat /sys/class/power_supply/BAT1/capacity)
status=$(cat /sys/class/power_supply/BAT1/status)
str=""
[ "$status" == "Charging" ] && str="^"
str="$str$percentage%"
echo $str

This script works fine in bash, printing something like '^78%'. Then I've included it in a statusbar:
set -g status-fg colour6
set -g status-attr bold
set -g status-left ''
set -g status-right "%d/%m %H:%M:%S | #(~/.status/battery.sh) "

However, only '78%' is shown in statusbar, without '^' symbol indicating charging. I tried to print something like '78% (CHRG)', but again, only '78%' is displayed in statusbar, while bash runs script correctly.
I'm running tmux 2.6 and bash 4.4.18.