text:
Q: Having trouble with Google Assistant repeating previous message in Dialogflow I'm working on a very simple Dialogflow with about 15-20 intents. All of these intents use a text response except one. The only intent that does not use a text response is called 'repeat'. The intent (repeat) should be able to repeat whatever was previously said by Google Assistant.

I've tried to set this up using Multivocal but have not been successful. When I type a command into the test simulator I'll get the initial response, but when I follow up with 'repeat' the default response of 'Not available' is returned. The webhook times out when I look at the Diagnostic Info. My sense is that I've configured something wrong because I've read these answers and not been able to solve my problem:

*

*How to repeat last response of bot in dialogflow

*Dialogflow - Repeat last sentence (voice) for Social Robot Elderly

*Use multivocal libary to configure repeat intent in Dialogflow for VUI
I'm using the inline editor within Dialogflow my index.js looks like:
const Multivocal = require('multivocal');
const conf = {
Local: {
    en: {
      Response: {
        "Action.multivocal.repeat": "Let me try again",
      }
    }
  }
};
new Multivocal.Config.Simple( conf );
exports.webhook = Multivocal.processFirebaseWebhook;
exports.dialogflowFirebaseFulfillment = Multivocal.processFirebaseWebhook;

And my package.json includes the Multivocal dependency:
"multivocal": "^0.15.0"

My understanding based on the above SO questions is that these config values would be enough and I don't need to do any coding, but I'm clearly screwing something (many things?) up. How can I get the prior response in Google Assistant to repeat when a user says 'repeat' or something similar? Multivocal seems like a simple solution, if I can do it that way.
Additional logs:
Fulfillment request (removed project id information):
{
  "responseId": "--",
  "queryResult": {
    "queryText": "repeat",
    "action": "multivocal.repeat",
    "parameters": {},
    "allRequiredParamsPresent": true,
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            ""
          ]
        }
      }
    ],
    "outputContexts": [
      {
        "name": "project info",
        "parameters": {
          "no-input": 0,
          "no-match": 0
        }
      }
    ],
    "intent": {
      "name": "project info",
      "displayName": "repeat"
    },
    "intentDetectionConfidence": 1,
    "languageCode": "en"
  },
  "originalDetectIntentRequest": {
    "payload": {}
  },
  "session": "project info"
}

Raw API response (removed project and response id)
{
  "responseId": "",
  "queryResult": {
    "queryText": "repeat",
    "action": "multivocal.repeat",
    "parameters": {},
    "allRequiredParamsPresent": true,
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            ""
          ]
        }
      }
    ],
    "intent": {
      "name": "projects info",
      "displayName": "repeat"
    },
    "intentDetectionConfidence": 1,
    "diagnosticInfo": {
      "webhook_latency_ms": 4992
    },
    "languageCode": "en"
  },
  "webhookStatus": {
    "code": 4,
    "message": "Webhook call failed. Error: DEADLINE_EXCEEDED."
  }
}

My simple intent that I've added based on the recommendation that for repeat to work on an intent it must use fulfillment and not based text response in Dialogflow

Here is my index.js file using the inline editor with suggestion to add text response in the config:
const conf = {
  Local: {
    en: {
      Response: {
        "Intent.help": [
          "I'm sorry, I'm not able to help you.",
          "You, John, Paul, George, and Ringo ey?"
        ],
        "Action.multivocal.repeat": "Let me try again"
      }
    }
  }
};

This line at the end of my index.js seems odd to me, but may be unrelated:
exports.webhook = Multivocal.processFirebaseWebhook;
exports.dialogflowFirebaseFulfillment = Multivocal.processFirebaseWebhook;

A: It sounds like you're triggering the Fallback Intent. You also need an Intent defined in Dialogflow that has an Action set to "multivocal.repeat". That might look something like this:

In the dialogflow directory of the npm package (or on github) you'll find a zip file with this and several other "standard" Intents that you can use with mulivocal.
Additionally, all the other Intents that you want to be repeated must use fulfillment to send the response (the library doesn't know what might be sent unless it can send it itself). The simplest way to do this is to enable fulfillment on each, and move the text responses from their Dialogflow screens into the configuration under an entry such as "Intent.name" (replacing "name" with the name of the Intent) or "Action.name" if you set an action name for them.
So your configuration might be something like
const conf = {
Local: {
    en: {
      Response: {
        "Intent.welcome": [
          "Hello there!",
          "Welcome to my Action!"
        ],
        "Action.multivocal.repeat": [
          "Let me try again"
        ]
      }
    }
  }
};


text:
Q: how to use a value (which is get by .text() when a li is clicked) as a selector to hide some div i have a ul li list like

batch1

batch2

batch3

batch4

batch5

batch6

now, i can get the text value of every li, the problem is, i cannot use the text value as
selector.what i want to do is: i have some div(id are "batch1, batch2...batch6"),which i want to hide if a li is clicked(except clicked li). code are=
html:

 ......

jquery:
$(document).ready(function(e) {
    $('body').click(function(event) {

    if($(event.target).is('#l1')) {
       var id = "'#"+$('#l2').text()+"'";
       $(id).hide();
    }
});
});

what should i do. i am trying about 24 hours but still in dark. and thanks in advance

A: You should add a common class to all #batch1, #batch2 elements so you can target them all at once..
Then use the id as the exception...
Html

javascript
$('#dropdown').on('click','a', function(e){
    e.preventDefault();
    var id = '#' + $.trim( $(this).text() ); // create the id based on the text

    $('.batch').hide(); // hide all batch elements
    $(id).show(); // show the one that corresponds to the clicked li
});

Demo at http://jsfiddle.net/A5Vxm/

A: $('body').click(function(event) {
    if(event.target.id  == 'l1' ) {
       var id = "#" + $.trim( $('#l2').text() );
       $(id).hide();
    }
});

DEMO
But if you divs are dynamic that means added into DOM after page load then try
    $('body').on('click', 'a', function(event) {
        event.preventDefault();
        if(event.target.id  == 'l1' ) {
           var id = "#" + $.trim( $('#l2').text() );
           $(id).hide();
        }
    });

redpajama_set_name: RedPajamaStackExchange


text: Q: How to stop amplify PubSub to publish message after regaining internet connection? I am using amplify PubSub with react. This react app has a button and clicking on it publishes a messages to Aws Iot. But if the user clicks without internet connection amplify queue this request for some time and publishes message when internet connection regains. How can I stop this behaviour. I don't want it to retry/queue message publish requests.


text:
Q: iPhone application Autologin Using below code, I am trying to show a uialertview, it is being shown properly and also my application is going properly to next screen through [self getlogin]; method. The issue I am facing is that alert view does not gets disappear when another view is loaded, as when the [self getLogin] is called alert view should disappear itself and new screen should be shown, while it is not.
Also I want to add a progress bar above the alert view cancel button, How can I do that
    if ((user != nil) && (passwd != nil)) {

    NSLog(@"Data found");

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Signing in..." message:nil delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil ];

    [alert show];

    [self getLogin];
}else {

    NSLog(@"No data saved");
}

I am using this alert view on a login screen, if username and password is saved then that alert view will appear and starts signing in automatically through [self getLogin]; and when it gets logged on alert view will be disappear and new screen will be shown, and if while auto signing in user clicks cancel button user will be at login screen

A: In this case what you have to do is, you should move  [self getLogin] to the UIAlertView delegate method that gets called on button click

A: To dismiss an alert view you can use - (void)dismissWithClickedButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animated and you can add a progress bar simply by adding a subview to the UIAlertView. But you should rethink if a UIAlertView is really the right view for this. It sound strange, a alert view that disappears on int's own and still has a cancel button. User might be confused when it disappears.


text:
Q: transform_geom: couldn't parse proj4 output string: projection not named I recently upgraded my Amazon PostgreSQL RDS to version 10.3 but while fetching the projections I am getting error:
ERROR:  transform_geom: couldn't parse proj4 output string: '3857': projection not named
CONTEXT:  SQL function "st_transform" statement 1

Same records i am able to fetch prior to version 9.5.xx
My PostGIS version is 2.4.2 which is compatible to RDS intance.

A: I perhaps faced the same problem after upgrading from postgis 2.2 to 2.3, some of my queries did no work anymore.
Old-query:
SELECT ST_X(ST_TRANSFORM(ST_SETSRID(ST_MAKEPOINT($1,$2),$3),$4));

query-params $1...$4:
602628,6663367,3857,3857
error message:
"transform_geom: couldn't parse proj4 output string: '3857': projection not named"
Reason:
ST_TRANSFORM comes in multiple flavours, two of them:

*

*public.st_transform(geometry, integer)

*public.st_transform(geometry, text)

Latter one, I assume new in postgis 2.3, caused my problem, because $4 (3857) was regarded as (proj4-) string and not as (SRID-) integer.
Workaround in my case: type-hint for param $4
SELECT ST_X(ST_TRANSFORM(ST_SETSRID(ST_MAKEPOINT($1,$2),$3),$4::int));


text:
Q: SQL Server WHERE IS NULL OR IN MULTIPLE ROWS (VALUES) --Main Query
SELECT * FROM tblUser u
WHERE
--Search Criteria 1
-- Sub Query
((SELECT se.SearchEntityId FROM tblSearchEntity se WHERE se.SearchEntityTitle
like 'MaritalStatus')
IS NULL
OR
u.MaritalStatus IN
-- Sub Query
(SELECT se.SearchEntityId FROM tblSearchEntity se WHERE se.SearchEntityTitle
like 'MaritalStatus'))

AND
--Search Criteria 2
-- Sub Query
((SELECT se.SearchEntityId FROM tblSearchEntity se WHERE se.SearchEntityTitle
like 'CountryOfResidence')
IS NULL
OR
u.CountryOfResidence IN
-- Sub Query
(SELECT se.SearchEntityId FROM tblSearchEntity se WHERE se.SearchEntityTitle
like 'CountryOfResidence'))

-- When sub-query
 (SELECT se.SearchEntityId FROM tblSearchEntity se WHERE
 se.SearchEntityTitle like 'MaritalStatus')

returns:
NULL [main query] works fine
1 ROW [main query] works fine
2 or more ROWS [main query] DOES NOT work.
IS NULL can't accpet multiple values so what should I do?

A: REPLACE you condition on this
 WHERE EXISTS (SELECT se.SearchEntityId FROM tblSearchEntity se
    WHERE se.SearchEntityTitle like 'MaritalStatus'
    AND se.SearchEntityId = sp.SearchEntityId)
    AND s.UserId = @UserId))

A:  WHERE EXISTS (SELECT se.SearchEntityId FROM tblSearchEntity se
    WHERE se.SearchEntityTitle like 'MaritalStatus'
    AND se.SearchEntityId = sp.SearchEntityId)
    AND s.UserId = @UserId))

Instead of doing the above, it would be better to use JOINS's. For example, the above would have the following joins
LEFT OUTER JOIN [tblSearchEntity] se ON se.searchentityId = sp.searchentityId

A: Assuming I understand what you tried to do, I think with the help of a couple of CTEs and a few changes in the main query you will get what you want.
Here is what I came up with. Bare in mind that I can't test it since you have not provided sample data or desired results.
;WITH MaritalStatusCte AS
(
    SELECT SearchEntityId
    FROM tblSearchEntity
    WHERE SearchEntityTitle = 'MaritalStatus'
), CountryOfResidenceCte AS
(
    SELECT SearchEntityId
    FROM tblSearchEntity
    WHERE se.SearchEntityTitle = 'CountryOfResidence'
)

SELECT *
FROM tblUser as u
WHERE
(
    (SELECT COUNT(*) FROM MaritalStatusCte) = 0)
    OR EXISTS
    (
        SELECT 1
        FROM MaritalStatusCte
        WHERE SearchEntityId = uMaritalStatus
    )
)
AND
(
    (SELECT COUNT(*) FROM CountryOfResidenceCte) = 0)
    OR EXISTS
    (
        SELECT 1
        FROM CountryOfResidenceCte
        WHERE SearchEntityId = CountryOfResidence
    )
)


text:
Q: Update post not working in wordpress - URL not found error I am working on a wordpress website.
My wp admin is working fine, I can use all the admin features. But when i try to update a page/post content Iget a blank page with this error
"The specified URL cannot be found. "
It was working well on friday. I have not changed anything in code or settings, but now it is giving this error.
Quick help would be appreciated.
Thank

A: I Guess this is a "PERMALINK" issue.
What you need to do is GoTo Admin panel: Settings->Permalinks->select "Default" or "Post Name".
And then try updating or posting new post.

A: Change the permalink as default from the settings.


text:
Q: AWS Databricks cluster start failure I am currently unable to spin up any clusters in our databricks AWS environment.
When I attempt to start up an on-demand cluster, it remains in "pending" for 20+ minutes (on relatively small clusters which usually take 2-3 min to start up).
Similarly, all of my scheduled jobs are failing due to their job clusters not being able to start either. This is a sample error message:
Run result unavailable: job failed with error message Unexpected failure while waiting for the cluster [cluster_name] to be ready. Cause Cluster [cluster_name] is unusable since the driver is unhealthy.

When I try to investigate the issue, the driver logs are completely empty. I have tried to initiate clusters with runtimes 9.1 and 10.4 and see the same issue.
Has anyone seen this before? Is this a databricks issue or an AWS issue?

A:
Has anyone seen this before? Is this a databricks issue or an AWS issue?

Yes I have seen this before. In almost all cases it was a cloud provider problem which resolved itself within a few hours. I have also seen this after a networking change where a new VPC was set up. Unless your networking has changed, and if the problem still persists I would register a support ticket with databricks.


text:
Q: invalid literal for int() with base 10: 'I'm trying to use pre-trained word2vec in Google Colab. Previously I downloaded the model onto my C:/, and then uploaded it to my Google Drive. However, I get this error I can't seem to find anywhere.
My code is:
from gensim.models import word2vec
import urllib.request

urllib.request.urlretrieve("https://drive.google.com/file/d/1lgCddPxJC__QA-qGtYTdNNoHRiYWyOpQ/view?usp=sharing/GoogleNews-vectors-negative300.bin", "GoogleNews-vectors-negative300.bin")

word2vec_path = 'GoogleNews-vectors-negative300.bin'
word2vec = gensim.models.KeyedVectors.load_word2vec_format(word2vec_path, binary=True)

Error Message:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-354-492ef9dcbbcc> in <module>()
      1 word2vec_path = 'GoogleNews-vectors-negative300.bin'
----> 2 word2vec = gensim.models.KeyedVectors.load_word2vec_format(word2vec_path, binary=True)

2 frames
/usr/local/lib/python3.7/dist-packages/gensim/models/utils_any2vec.py in <genexpr>(.0)
    171     with utils.smart_open(fname) as fin:
    172         header = utils.to_unicode(fin.readline(), encoding=encoding)
--> 173         vocab_size, vector_size = (int(x) for x in header.split())  # throws for invalid file format
    174         if limit:
    175             vocab_size = min(vocab_size, limit)

ValueError: invalid literal for int() with base 10: '<!DOCTYPE'

A: As use ~deceze notes, that error hints that the file has some typical HTML boilerplate (<~DOCTYPE) where the code is expecting 2 ints declaring the forthcoming count-of-vectors (vocab_size) & their dimensionality (vector_size).
It's likely your urlrequest() action didn't receive the file you expected, and perhaps got a 'file not found' or other error instead. So:

*

*Check its size & contents to see if it's what you expect.

*Check your request code, to ensure it can even get what you need from a random cloud notebook. (Maybe the Google Drive URL requires a logged-in user, and your Colab notebook isn't able to make web requests as a logged-in version of you?)

*If you have the valid file elsewhere, see if you can send that valid copy directly to the scratch storage space of the notebook.


text:
Q: Why is $[\mathbb{Q}(e^{2\pi i/p}):\mathbb{Q}] = p-1 $? I know that $e^{2\pi i/p}$ is a root of $x^{p}-1$ and we can write:
$ x^{p}-1=\left(x-1\right)\left(\sum_{i=0}^{p-1}x^{i}\right) $
So $e^{2\pi i/p}$ is a root of $\sum_{i=0}^{p-1}x^{i}$, which means $[\mathbb{Q}(e^{2\pi i/p}):\mathbb{Q}] \leq p-1 $.
Can someone show the other direction?

A: You can get both directions from the fact that $e^{\frac{2 \pi i}{p}}$ is a root of $P(X)=X^{p-1}+X^{p-1}+..+X+1$, and that $P(X)$ is irreducible over $\mathbb Q[X]$.
You can prove the irreducibility by observing that $P(X)=\frac{X^p-1}{X-1}$ for $x\neq 1$, thus, for $X \neq 0$ we have
$$P(X+1)=\frac{(X+1)^p-1}{X}=\sum_{k=1}^p \binom{p}{k}X^{k-1}$$
use Eisenstein Criteria.


text:
Q: Refused to execute inline event handler because of Content-Security-Policy What do I need to change here so that the JavaScript code works with the manifest version 2 and the security policy?
Screenshot:

Code:
function init()
{
    chrome.tabs.getSelected(null, function(tab)
    {
        url = tab.url;
        if(url.indexOf('chrome://') == -1 && url.indexOf('about:blank') == -1){
            document.main.q.value = url;
        }
    });
}

A: I got it working after I put the JavaScript code from the HTML file into an own file and added the following to the manifest file:
"content_scripts": [ {"js": [ "popup.html" ], "matches": [ "http://*/" ]} ],
"permissions": [ "tabs" ]

A: The inline event handler definition must be rewritten in terms of addEventListener and extracted into popup.js, so you should remove the onfocus="this.select()" in your popup.html, and in the popup.js, add the following lines:
document.addEventListener('DOMContentLoaded', function () {
  document.getElementById('address_box').addEventListener('onfocus', this.select);
});

A: Make sure you are using the latest versions of your library. I don't think you are using jQuery but if you do make sure you are using the latest version which supports CSP.
http://bugs.jquery.com/ticket/11249
Both the extension and libraries code need to support CSP when you update to manifest version 2.


text:
Q: Laravel form using LaravelCollection to redirect to URL with parameter when dropdown selected In my blade I have the following dropdown list
{!! Form::select('plans', $named_plans, null,['class' => 'form-control'] ) !!}

which is populated by a list named $named_plans passed by the controller. So far so good.
I need to take the value selected by the user from the dropdown and add it as a parameter to a URL. I can't figure out (and the LaravelCollective documentation is minimal at best) how to append the selected string to a URL (or route) and redirect the user there. Similar to how a dropdown menu works.
For instance, if the user selected "foo" from the dropdown, I want to send them to mylaravelsite/public/displaypage/foo. I have a route that will process displaypage/{foo} just fine if I could just code for the redirect.
Any suggestions would be very helpful.
I'm using Laravel 5.5 with PHP 7 on XAMPP

A: First take the value of selectbox option and add the attribute action to the form
$('#selectboxid').change(function(){
    var optionSelected = $("option:selected", this);
    optionValue = this.value;
    $('#idoftheform').attr('action','public/displaypage/'+optionValue);
});

A: Thank you Jigs for pointing me in the right direction. The following code worked beautifully for me, added below the form::select element. I was able to grab the selected value and append it to the Laravel route (my route "my-plans" directs to 'public/displaypage')
<script>
$('[name="plans"]').change(function(){
    var optionSelected = $("option:selected", this);
        optionValue = this.value;
    document.location.href="{!!route('my-plans')!!}" + "/" + optionValue;
});
</script>

Many thanks.


text:
Q: Center image within div I've looked around and tried the suggestions to center an image, and it usually works just fine, but I've got a situation where something isn't right.
If you go to the test page:
http://www.503rephotography.com/_temp/ - you will see the image is pushed to the right a little bit, and if you increase or decrease the size of your screen, you will see it may shift a little further away from the center position.
I'm new to CSS and may have something messed up that is making this not work; I used some tips on here to make the div with the content on the page be somewhat centered. Now I'm just trying to center an image within that div box. Any help is much appreciated!!

A: You have to create a div container with margin-left:auto: and margin-right:auto; to center the content.

SERVICES

PORTFOLIO

CONTACT 503

Content will go here....why can't I get this div box to be centered???

Try this fiddle see if it's what you need: http://jsfiddle.net/ftPa3/


text:
Q: C# Watermark an image without overlapping What i'm trying to do is write a string to an image without overlapping the image.  So i want to watermark an image putting the watermark (string) at the bottom without actually affecting the image or stretching the image out.  I already know how to turn a string into an image, just having problems accomplishing the watermark.
1) Write string to Image on bottom right hand side
2) don't stretch the original image
3) extend the bitmap a little bit to include watermark?
Does anybody have an example or an idea where to start?  If i don't make any sense i'll try to answer any questions.
Bitmap example:
here is the code I use to get the bitmap, how do I increase just the size by X like 20?
Bitmap original = (Bitmap)System.Drawing.Image.FromFile(coveted);
Bitmap newImage = new Bitmap(original);

And I guess the 2nd part is how do i determine the space that I need in order to write out a string to the very bottom right of the image, while fitting in the entire string...
@ROY:   This is the edit that i did.
This sorta works but the one watermark appears below the other.  if i could get them on the same line it would be perfect!
private static Bitmap WatermarkImage2(Bitmap bmpOriginal, String waterMark2)
    {
        using (Graphics gfxOriginal = Graphics.FromImage(bmpOriginal))
        {
            using (Font fntWatermark = new Font("Arial", 24, FontStyle.Regular))
            {
                SizeF szWatermark = gfxOriginal.MeasureString(waterMark2, fntWatermark, int.MaxValue);
                Bitmap bmpWatermarked2 = new Bitmap(bmpOriginal.Width, bmpOriginal.Height + (int)(szWatermark.Height * 2));
                using (Graphics gfxWatermarked = Graphics.FromImage(bmpWatermarked2))
                {
                    gfxWatermarked.Clear(Color.White);
                    gfxWatermarked.DrawImageUnscaled(bmpOriginal, 0, 0);
                    gfxWatermarked.DrawString(waterMark2, fntWatermark, Brushes.Black, 0, (bmpOriginal.Height + szWatermark.Height) - (szWatermark.Height / 2));
                }
                return bmpWatermarked2;
            }
        }
    }

A: This may work for you:
    private static Bitmap WatermarkImage(Bitmap bmpOriginal, String waterMarkLeft, String waterMarkRight)
    {
        using (Graphics gfxOriginal = Graphics.FromImage(bmpOriginal))
        {
            using (Font fntWatermark = new Font("Arial", 12, FontStyle.Regular))
            {
                SizeF szWatermarkLeft = gfxOriginal.MeasureString(waterMarkLeft, fntWatermark, int.MaxValue);
                SizeF szWatermarkRight = gfxOriginal.MeasureString(waterMarkRight, fntWatermark, int.MaxValue);

                float heightWatermark = szWatermarkLeft.Height > szWatermarkRight.Height ? szWatermarkLeft.Height : szWatermarkRight.Height;

                Bitmap bmpWatermarked = new Bitmap(bmpOriginal.Width, bmpOriginal.Height + (int)(heightWatermark * 2));

                using (Graphics gfxWatermarked = Graphics.FromImage(bmpWatermarked))
                {
                    gfxWatermarked.Clear(Color.White);
                    gfxWatermarked.DrawImageUnscaled(bmpOriginal, 0, 0);
                    gfxWatermarked.DrawString(waterMarkLeft, fntWatermark, Brushes.Black, 0, (bmpOriginal.Height + heightWatermark) - (szWatermarkLeft.Height / 2));
                    gfxWatermarked.DrawString(waterMarkRight, fntWatermark, Brushes.Black, (bmpOriginal.Width - szWatermarkRight.Width), (bmpOriginal.Height + heightWatermark) - (heightWatermark / 2));
                }

                return bmpWatermarked;
            }
        }
    }

Then you would call it like this:
using (Bitmap bmpWatermarked = WatermarkImage((Bitmap)Bitmap.FromFile(@"c:\\test.bmp"), @"Copyright (C) A Corp."))
{
    bmpWatermarked.Save(@"c:\watermarked.bmp");
}

Combined with your code above:
Bitmap original = (Bitmap)System.Drawing.Image.FromFile(coveted);
Bitmap newImage = new Bitmap(original);
using (Bitmap bmpWatermarked = WatermarkImage(newImage, @"Copyleft (C) A Corp.", @"Copyright (C) B Corp."))
{
  bmpWatermarked.Save(@"c:\watermarked.bmp");
}

A: It sounds like what you want to do is simply make the image larger than the original, and include your "watermark" at the bottom like an image footer.
What you need to do is to create a new Bitmap object that is larger than the original image (by the amount of the watermark).  Then use the Graphics DrawImageUnscaled method to draw the original image at 0,0 and then draw your Watermark Image at the bottom (or right, or wherever).


text: Q: What is the conventional way to import own packages in Java with IntelliJ IDEA? I'm confused with importing custom packages in IntelliJ IDEA. I specified CLASSPATH, added my package, but nothing occured. What's wrong with my actions? And what the common way to import packages?


text:
Q: To exclude Class from Body on Click eevent I want to Toggle a Class on body click. But if specific DIV having class "mainDIV" is reflecting on the same body then I want to
exclude body click event for that DIV. So that when user click on "mainDIV" body click event must not be occur.
I am using this CODE in jQuery but its not working:
$("body :not(.mainDIV)").bind("click", function() {
  $('.offerClass').show();
});

A: The bind() method is deprecated in jQuery 3.0 so it's better to go with on() method instead.
Bind click event on body and prevent event bubbling up when clicked inside .mainDIV using event.stopPropagation() method.
$("body").on("click", function() {
  $('.offerClass').show();
}).on('click','.mainDIV',function(e){
  e.stopPropagation();
});

A: Firstly note that bind() was deprecated some time ago. You should now use on() instead.
To solve your issue you could let the event bubble up to the document and then check the class on the element referenced in the target of the event, like this:
$(document).on("click", function(e) {
  if (!$(e.target).hasClass('mainDIV'))
    $('.offerClass').show();
});


text:
Q: Javascipt code showing on website instead of processing it I have just installed react and made and opened the folder in Vscode then deleted everything in the src folder and made a javascipt file.Next, I wrote the following code:
import React from "react";
import ReactDOM from "react-dom";
const element=
 Hello
;
console.log(element);

The problem is instead of processing the code,It was diplayed in the web page and even when I linked an html file to it.The console displayed the error"SyntaxError: Cannot use import statement outside a module"

A: import React from "react";
import ReactDOM from "react-dom";

ReactDOM.render(
Hello
, document.getElementById('root'));

const element =
Hello
;
console.log(element);

This code imports the React and ReactDOM libraries, which are necessary for creating React components. It then uses ReactDOM.render() to render a Hello element to the HTML element with the id 'root'. The last line creates a React element and stores it in the variable 'element', which is then logged to the console.


text:
Q: AuraClientService.postProcess: error in processing [RangeError: Maximum call stack size exceeded] - Client Side Action I have a lightning component that is using ui:inputSelect.
The component code:
            <div class="slds-form-element__control">
                <ui:inputSelect class="slds-select" aura:id="quals" change="{!c.getPreCodes}">
                    <aura:iteration items="{!v.questions}" var="q">
                         <ui:inputSelectOption aura:id="question" text="{!q.Id}" label="{!q.Question_Text__c}"/>
                    </aura:iteration>
                </ui:inputSelect>
            </div>

The controller:
    getPreCodes : function(cmp, event, helper){
        var selected = cmp.find("quals").get("v.value");

        var action = cmp.get("c.getPreCodes");
        action.setParams({
            "qualID" : selected
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {

                console.log('precodes: ', response.getReturnValue());

            }
        });

        $A.enqueueAction(action);
    }

The basic logic is that the uiSelect is dynamically populated on init (this works fine). When a user makes a selection the "change" parameter function is fired to retrieve a list from the database and pass it to another component.
However, the change function {!c.getPreCodes} seems to be called recursively causing a

"Something has gone wrong. AuraClientService.postProcess: error in
  processing [RangeError: Maximum call stack size exceeded] . Please try
  again."

error. If I comment out the enqueueAction the function only runs once (nothing is called recursively) so I suspect it has something to do with the controller call.

A: As per the doc, it is recommended to use different names for the client side and server side methods/actions.

Use unique names for client-side and server-side actions in a
  component. A JavaScript function (client-side action) with the same
  name as a server-side action (Apex method) can lead to hard-to-debug
  issues.

So all you need to do is, change your client-side controller's method  getPreCodes to something like getPreCodeData


text:
Q: How to automate post-installation setup of a distribution? As you all know, setting up a fresh installation of a distribution can be time consuming.
Manually installing and setting up various packages and apps takes a lot of time, even with all the dotfiles on hand.
Thus recently I have been wondering about whether there are any tools/best practices concerning the automation of this process?
Are there any universal tools? Or should plain ol' shell scripts (for different distros/hardware configurations) be plenty enough?
Here's a link for some more information on this topic.
Author's post-install shell script contains ~2000 lines of code.

A: Many methods:
in the case of RHEL: chose different packages in anaconda (?) install definition
debian: have deb-installer add wanted packages.
some type of configuration management :

*

*cfengine

*ansible

*puppet

In the case of Solaris there was the installer daemon, force machines to boot via network at first boot and in that net boot install do deployment to the local disk and then reboot - done.
If you later on needed to modify the machine(s) (think network of workstation, not a server), modify the install server and force the machines to net boot.

A: I usually use my own scripts as well. Sure there's almost as many useful projects, curl <my-installer> | bash-scripts or even simple shell functions as there are Linux users out there.
I like cloud-init a lot and may go and use that for my next quick server/dev box setups.
Ansible et al. may help re-using community or personal/company modular system config setups.
But a simple 'cloud-init' script could do that as well, if you care for it [I do wonder if cloud-init supports doing checksums on web-content it pull in, something I would look at first].
Its a bit immature as a 'project' (and will require a confident/experienced shell user cautious of other peoples scripts) but my own 'apt-get.list' evolved into this: https://github.com/dotmpe/user-conf.
Getting setup script LoC down is something I've spend a lot of time on. If you don't spend too much time on a specific VM/container/"virtual app" system (or like Vagrant, just know what they can do) there is a lot you can do with a bit of automated shell and minimal manual copy-paste/ssh-copy-id/scp/adduser/usermod/etc. steps.
Most importantly: all this requires some structure with choices, probably a repository or server for dotfiles but also some ideas about keys and tokens, network, maybe different users and whatever component-view/abstraction you (need to) care about. I still just use cURL/GIT/Bash a lot and cloud-init can do that well. I am looking at Ansible modules/ roles as well, but the key point there is I think you should look which configuration system setup your are comfortable with. Agents or just SSH or something else maybe.


text:
Q: PHP OOP vs Procedurial MySQL function reference I'm familiar with creating procedural style PHP functions to select information from a database, but in making the switch to using Object oriented prepared SQL statements, my functions do not work anymore. I do not yet understand OOP as I do procedural PHP, and am trying to learn, so this is my problem:
This works as expected:
if ($stmt = $mysqli->prepare("SELECT state FROM country WHERE city = ?")) {
    $stmt->bind_param("s", $city);
    $city = 'la';
    $stmt->execute();
    $stmt->bind_result($state);
    $stmt->fetch();
    $stmt->close();
    echo $state;
}

Yet, this does not:
function get_state( $city ) {
if ($stmt = $mysqli->prepare("SELECT state FROM country WHERE city = ?")) {
        $stmt->bind_param("s", $city);
        $stmt->execute();
        $stmt->bind_result($state);
        $stmt->fetch();
        $stmt->close();
        echo $state;
    }
}

get_state('la');

Both examples are requiring a database mysqli connection, yet the function version does not work for some reason, what am I doing wrong?

A: The variable $mysqli is out of scope in the function. You have to declare it as global if you don't want to pass it to the function as argument.
function get_state( $city ) {
    global $mysqli;

    if ($stmt = $mysqli->prepare("SELECT state FROM country WHERE city = ?")) {
        $stmt->bind_param("s", $city);
        $stmt->execute();
        $stmt->bind_result($state);
        $stmt->fetch();
        $stmt->close();
        echo $state;
    }
}

get_state('la');

The variable available outside of the function cannot be accessible in a user-defined function unless it is declared as global or passing it as argument to the function.

A: The first thing you should do s enable error reporting. That will tell you that you are calling a method (prepare) on something that is not a object (mysqli), since $mysqli does not exist in the function scope. You will have to pass $mysqli to your function or devise some other mechanism on how the function can access that variable.

A: $mysqli is not defined, I guess. See manual on scope

A: pass the $mysqli in parameter and also pass the mysqli connection object to query.


text:
Q: Roaming Profile Control I noticed that with Roaming Profiles enabled that even applications have been roaming. Is this normal? Is there a way to keep applications from roaming? I like how Firefox bookmarks move from machine to machine(does cache move as well???) as it is a great way to remain in-sync but I do not like how every application is moved.
I always thought that Roaming Profiles kept just the USERDIR in motion.

A: By "applications have been roaming" I think you're saying that EXEs stored in the portion of the user's profile that is "Roaming" are being copied to the server and back down to client computers when the user logs-on.  (Hopefully I'm understanding what you're saying. If not, please let me know and I'll edit accordingly.)
This is normal behavior. Roaming user profiles aren't much more than a convoluted and glorified file copying mechanism. If EXEs end up in the roaming portion of a user's profile then they'll be copied.
You can use Group Policy to exclude folders from roaming. (That article references Windows Server 2003 but those particular settings work on all current versions of Windows.)


text:
Q: How to create a tabbed interface in Javascript I'm trying to create a tabbed interface in Javascript which will allow a user to click on a button atop each interface in order to make the div under it become active while the other 'tabs'/divs recede to the background. I'm not quite sure I got that out right so attached is a screenshot of what I'm trying to make:

My code attaches one button -- beside the first div-- instead of all three and returns an error that says nodeChildren[j].getAttribute("data-tabname") is not a function although as far as I know, it seems it is.
I'll post my JavaScript code then add a link to fiddle where everything is.
function asTabs(node) {
var button = document.createElement("BUTTON");
var tempArray = [];
var nodeChildren = Array.prototype.slice.call(node.childNodes);

nodeChildren.filter(function(){
for (var i = 0; i < nodeChildren.length; i++) {
if (nodeChildren[i].nodeType === 1) {
tempArray += nodeChildren[i];
return tempArray;
}
}
});
nodeChildren.forEach(function (){
for (var j = 0; j < nodeChildren.length; j++) {
node.insertBefore(button, nodeChildren[j]);
var buttons = document.getElementsByTagName("button");
for (var k = 0; k < buttons.length; k++) {
buttons[k].innerHTML = nodeChildren[j].getAttribute("data-tabname").textContent;
}
}
});

var hide = nodeChildren.slice(1);
for (var l = 0; l < hide.length; l++) {
hide[l].className = "hide";
}
buttons[k].addEventListener("click", function (){
if (nodeChildren[j].className = "") {
nodeChildren[j].className = "hide";
}
else nodeChildren[j].className = "";
});
  }
  asTabs(document.querySelector("#wrapper"));

Then here's my fiddle containing comments explaining what is being tried to achieve on each line
https://jsfiddle.net/nmeri17/nmswdota/


text:
Q: Checkov scan particular folder or PR custom branch files Trying to run Checkov (for IaC validation) via Azure DevOps YAML pipelines, for ARM template files stored in Azure DevOps version control. The code below:
trigger: none

pool:
  vmImage: ubuntu-latest

stages:
  - stage: 'runCheckov'
    displayName: 'Checkov - Scan ARM files'
    jobs:
      - job: 'RunCheckov'
        displayName: 'Checkov solution'
        steps:
          - bash: |
              docker pull bridgecrew/checkov
            workingDirectory: $(System.DefaultWorkingDirectory)
            displayName: 'Pull bridgecrew/checkov image'

          - bash: |
              docker run \
                --volume $(pwd):/scripts bridgecrew/checkov \
                --directory /scripts \
                --output junitxml \
                --soft-fail > $(pwd)/CheckovReport.xml
            workingDirectory: $(System.DefaultWorkingDirectory)
            displayName: 'Run checkov'

          - task: PublishTestResults@2
            inputs:
              testRunTitle: 'Checkov run results'
              failTaskOnFailedTests: false
              testResultsFormat: 'JUnit'
              testResultsFiles: 'CheckovReport.xml'
              searchFolder: '$(System.DefaultWorkingDirectory)'
              mergeTestResults: false
              publishRunAttachments: true
            displayName: 'Publish Test results'

The problem -  how to change the path/folder of ARM templates to scan. Now it scans all ARM templates found under my whole repo1, regardless what directory value I set.
Also, how to scan PR files committed to custom branch during PR review, so it would trigger the build but the build would scan only those files in the custom branch. I know how to set to trigger build via DevOps repository settings, but again, how to assure build pipeline uses/scan particular PR commit files, not whole repo1 (and master branch).

A: I recommend you use the Docker image bridgecrew/checkov to set up a container job to run the Checkov scan. The container job will run all the tasks of the job into the Docker container started from this image.
In the container job, you can check out the source repository into the container, then use a script task (such as Bash task) to run the related Checkov CLI to do the files scan. On the script task, you can use the 'workingDirectory' option to specify the path/folder where the command lines run in. Normally, the command lines will only act on files which are in the specified directory and its subdirectories.
If you want to only scan the files in a specific branch in the job, you can clone/checkout the specific branch to the working directory of the job in the container, then like as above mentioned, use the related Checkov CLI to scan files under the specified directory.
[UPDATE]
In the pipeline job, you can try to call the Azure DevOps REST API "Commits - Get Changes" to get all the changed files and folders for the particular commit.
Then use the Checkov CLI with the parameter --directory (-d) or --file (-f) to scan the specified file or folder.


text:
Q: Entities groups in transactions In the context of "Keys and Entity Groups" article by google:
http://code.google.com/appengine/docs/python/datastore/transactions.html
1) "Only use entity groups when they are needed for transactions"
2) "Every entity belongs to an entity group, a set of one or more entities that can be manipulated in a single transaction."
It seems like entity groups exist only for the use of transactions, i.e. making one transaction possible between all entities in a group.
My question is then why are there parent-child relations between entities and not just a simple declaration of entities to be in a single group (that is defining A,B,C to be in the same group as opposed to defining relations between them "A (parent of) B, B (parent of C)").
What is the benefit from using parent-child relation model when the only purpose is for entities to be in the same group to make transaction possible?
Thanks
Joel

A: I think your question makes sense, but how would we define a group of entities without making the relationship explicit? Besides that, being able to know the parent of a model instance by the key path is useful sometimes. Furthermore, it makes these methods possible:

parent()
Returns a model instance for the parent entity of this instance, or None
  if this instance does not have a parent.
parent_key()
Returns the Key of the parent entity of this instance, or None if this instance
  does not have a parent.


text:
Q: Place name google places api I have an array of place names like 'Hazrat Nizamuddin Railway Station, New Delhi, Delhi, India' and so on. The array also contains alternative names to the above like 'Nizamuddin Railway Station, Nizamuddin East, New Delhi, India' etc. They are both the same.
I now have a variable 'reference'. I need to use the reference place string and find all the places in the array that correspond to that place.
How should i go about this?

A: Are you trying to find out which elements in the array equal the reference variable? Is it an string just like the element in the array, or is it maybe a search query ie only part of the desired place name?
for (i=0; i < placeNamesArray.length; i++) {
    if (placeNamesArray[i] === reference) {
        // You now have the index you want, which is the current i.
    }
}


text:
Q: asp.net mvc razor reuse editor view for display (with custom helper) I have to make a large amount of forms for a project I'm working on. Every form has a large amount of fields in them. Would it be possible to create an HTML helper that can display an element or edit element depending on some variable? Maybe someone has tried this already. I could imagine that It would be something like:
@Html.EditOrDisplayFor(m=>m.Field, isReadonly)

When it is readonly it displays only the variable and when it is not it shows an textbox. Beside this helper I need some if's in my views, but it saves a couple of 100 lines of code if this would be possible)

A: Just found an alternative (I think quite neat way) to do it:
    public static MvcHtmlString EditOrDisplayFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> p,bool readOnly){
        if (readOnly){
            return new MvcHtmlString(string.Format("{0}", html.DisplayFor(p)));
        }  else{
            return new MvcHtmlString(string.Format("{0}", html.EditorFor(p)));
        }

    }

A: You can do two things to help you here.
Extension Methods
The first is to write an extension method that allows you to construct an input box with your specifications, e.g:
public static class Extensions
{
    public static string EditOrDisplayFor(this HtmlHelper helper, Field field, bool readOnly)
    {
        StringBuilder builder = new StringBuilder();
        if(readOnly)
        {
            builder.Append(field.Value);
        }
        else
        {
            builder.Append("<input type=\"text\" name=\"")
                   .Append(field.Name)
                   .Append("\" value=\"")
                   .Append(field.Value)
                   .Append("\" />");
        }
        return helper.Raw(builder.ToString());
    }
}

Which you can now use as you have described.
Partial Views
If these forms end up having common groupings between them, you might want to consider putting these common sections in to partial views to cut down on redundant layout code.


text:
Q: DATEDIFF with specific cutoff time I'm trying to calculate the number of days between 2 dates and times, but need to cut off at 19:00 rather than 00:00
select datediff (dd, '2019-03-14 19:28:00','2019-03-19 10:07:00'),
       datediff (dd, '2019-03-14 19:34:00','2019-03-22 10:20:00'),
       datediff (dd, '2019-03-14 17:13:00','2019-03-25 19:17:00')

I would expect to get the results of:
'2019-03-14 19:28:00','2019-03-19 10:07:00' = 4, has only passed the 19:00 cut off 4 times.

'2019-03-14 19:34:00','2019-03-22 10:20:00' = 7

'2019-03-14 17:13:00','2019-03-25 19:17:00' = 12

SQL calculates these as 5, 8, 11 respectively due to it cutting days off at 00:00

A: Just add five hours:
select datediff(day, dateadd(hour, 5, s), dateadd(hour, 5, e))
from (values ('2019-03-14 19:28:00', '2019-03-19 10:07:00'),
             ('2019-03-14 19:34:00','2019-03-22 10:20:00'),
             ('2019-03-14 17:13:00','2019-03-25 19:17:00')
     ) v(s, e);

Or equivalently, subtract 19 hours:
select datediff (day, dateadd(hour, -19, s), dateadd(hour, -19, e))
from (values ('2019-03-14 19:28:00', '2019-03-19 10:07:00'),
             ('2019-03-14 19:34:00','2019-03-22 10:20:00'),
             ('2019-03-14 17:13:00','2019-03-25 19:17:00')
     ) v(s, e);

A: If you want to do a DATEDIFF using 19:00 as though it were 00:00, just subtract 19 hours from all the datetime values and do the DATEDIFF on that.


text:
Q: Back from third to first fragment in android I have a problem with android fragment backstack. This is my situation.

// I can't post images yet, so I passed a link to it.
As you can see, I want to go from Fragment 1 to Fragment 2 and at the end to Fragment 3, but when I press back button at Fragment 3, I want to back to Fragment 1.
I do this like I describe on pic, but when I press Back Button nothing happen and when I press it second time, the app is closing.
My BackStack looks as expected, I have on it only "Main" entry.
Also, when I add to backstack Fragment 2 I can back normally from Frag3 to Frag2 to Frag1 (but this is not what I want).
//Edit:
First:
I debug my app a little and I notice that when I press back button, Fragment is poped out from backstack and his lifecycle methods were invoked, but current fragment (Fragment 3) do nothing (I logged his onPause and onStop methods and they weren't invoked). Maybe this is a problem?
Second:
I found a solution that I implement onBackStackChange listener and in onBackStacChange method I simply replace Fragment3 with Fragment1. This works, but is it correct?

A: do it using....
FragmentManager fmManager = activity.getSupportFragmentManager();
if (fmManager.getBackStackEntryCount() > 0) { fmManager.popBackStack(fmManager.getBackStackEntryAt(fmManager.getBackStackEntryCount()-2).getId(), fmManager.POP_BACK_STACK_INCLUSIVE); }

-2 is because you want to go two 2 fragment step back

A: @Override
public void onPageScrollStateChanged(int state) {
   int currentPage = mChannelPager.getCurrentItem();
   if (currentPage == mChannelsList.size() - 1 || currentPage == 0) {
          previousState = currentState;
          currentState = state;
          if (previousState == 1 && currentState == 0) {
              mChannelPager.setCurrentItem((currentPage == 0 ? mChannelsList.size() - 1 : 0), false);
            }
        }
     }
});

Write this code in your onPageChangeListner's onPageScrollStateChanged(int state)

A: 1) Add First Fragment using below code
android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager();
        android.support.v4.app.FragmentTransaction ft=fm.beginTransaction();
        if (fm.findFragmentById(R.id.fragment_container) != null) {
            ft.hide(fm.findFragmentById(R.id.fragment_container));
        }
        ft.add(R.id.fragment_container, new OneFragment(),OneFragment.class.getCanonicalName())
                .addToBackStack(OneFragment.class.getCanonicalName()).commit();

2) Add Second Fragment From First fragment using below code
  android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager();
                    android.support.v4.app.FragmentTransaction ft=fm.beginTransaction();
                    if (fm.findFragmentById(R.id.fragment_container) != null) {
                        ft.hide(fm.findFragmentById(R.id.fragment_container));
                    }
                    ft.add(R.id.fragment_container,new TwoFragment(),TwoFragment.class.getCanonicalName())
.addToBackStack(TwoFragment.class.getCanonicalName()).commit();

3) Add Third Fragment From Second fragment using below code
android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager();
                android.support.v4.app.FragmentTransaction ft=fm.beginTransaction();
                if (fm.findFragmentById(R.id.fragment_container) != null) {
                    ft.hide(fm.findFragmentById(R.id.fragment_container));
                }
                ft.add(R.id.fragment_container, new ThreeFragment(),ThreeFragment.class.getCanonicalName())
                        .addToBackStack(ThreeFragment.class.getCanonicalName()).commit();

4) onBackPressed() please write below code
@Override
    public void onBackPressed() {
        hideKeyboard(MainActivity.this);
        Fragment currentFragment = this.getSupportFragmentManager().findFragmentById(R.id.fragment_container);

        if (currentFragment.getClass().getName().equalsIgnoreCase(ThreeFragment.class.getName())) { // Using this code come from third fragment to first fragment
            Fragment f = this.getSupportFragmentManager().findFragmentByTag(TwoFragment.class.getCanonicalName());
            if (f != null) {
                this.getSupportFragmentManager().popBackStackImmediate(f.getClass().getCanonicalName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
            }
        }else {
            super.onBackPressed();
        }
    }


text:
Q: JavaBearer Token validation in Azure AD I'm trying to validate a token (just using postman), final solution would be written in Java (spring). The problem is I don't find the exact URL to validate the token against AAD.
I found this helpful article : https://learn.microsoft.com/en-us/answers/questions/884100/azure-ad-access-token-validation.html
And in that article they said to validate the token against this URL: https://login.microsoftonline.com/<<<tenant_id>>>/v2.0/
The problem is I got 404 when I hit that URL.
I also got "200 OK status" when I hit this URL https://login.microsoftonline.com/<<<tenant_id>>/oauth2/v2.0/authorize no matter what I put in the token !! Which is strange!
This link works for me: https://login.microsoftonline.com/<<<tenant_id>>/discovery/v2.0/keys  - and I get back a very descriptive JSON, but I am still stuck.
Could you please provide me the URL which would give me 200-ok when I have a valid token, and also to give me a bad-invalid response when I have a wrong token ?
I found some sample Postman requests here: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth-ropc?WT.mc_id=AZ-MVP-5003203
I got same behavior with them.
Thank you.

A: There is no introspection endpoint listed in https://login.microsoftonline.com/common/.well-known/openid-configuration
This authorization-server obviously supports JWTs only. To validate access-tokens, you'll have to configure a JWT decoder/validator in your Java app.
With Spring, this is done by configuring a JWT resource-server. Sample in this article. Skip the part about Keycloak and use

*

*spring.security.oauth2.resourceserver.jwt.issuer-uri=https://login.microsoftonline.com/common in properties

*not sure this authorization-server provides with user roles or groups or whatever claim to map spring authorities from (try to submit an access-token to https://jwt.io to see if you have a claim like that)


text:
Q: How to upgrade tomcat8 server on ubuntu? I'm running ubuntu xenial 16.04. Running aptitude install tomcat8 results in a tomcat version of 8.0.32.
But the current release is 8.0.46. How can I force an aptitude install or upgrade with exactly this version? aptitude versions tomcat8 only shows the 8.0.32 versions.
I'd like to keep my existing configurations and apps from v32, but would like to upgrade to v46. But how?

A: In a given Ubuntu release, software typically doesn't get upgraded to newer upstream versions, it only gets security patches and fixes for serious bugs. In Tomcat's case, Ubuntu 16.04 has 8.0.32 plus a number of security fixes (see the package page for details). So running 8.0.32 is still safe.
If you really need to upgrade to 8.0.46 (and I don't think there's much reason you would, given the above), you'll need to build it yourself.


text:
Q: Parse XML with Python resolving an external ENTITY reference In my S1000D xml, it specifies a DOCTYPE with a reference to a public URL that contains references to a number of other files that contain all the valid character entities.  I've used xml.etree.ElementTree and lxml to try to parse it and get a parse error with both indicating:
undefined entity −: line 82, column 652

Even though − is a valid entity according to the ENTITY Reference specfied.
The xml top is as follow:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dmodule [
<!ENTITY % ISOEntities PUBLIC 'ISO 8879-1986//ENTITIES ISO Character Entities 20030531//EN//XML' 'http://www.s1000d.org/S1000D_4-1/ent/ISOEntities'>
%ISOEntities;]>

If you go out and get http://www.s1000d.org/S1000D_4-1/ent/ISOEntities, it will include 20 other ent files with one called iso-tech.ent which contains the line:
<!ENTITY minus "−"> <!-- MINUS SIGN -->
in line 82 of the xml file near column 652 is the following:
....Refer to 70−41....
How can I run a python script to parse this file without get the undefined entity?
Sorry I don't want to specify parser.entity['minus'] = chr(2212) for example.  I did that for a quick fix but there are many character entity references.
I would like the parser to check Entity reference that is specified in the xml.
I'm surprised but I've gone around the sun and back and haven't found how to do this (or maybe I have but couldn't follow it).
if I update my xml file and add
<!ENTITY minus "−">
It won't fail, so It's not the xml.
It fails on the parse.  Here's code I use for ElementTree
 fl = os.path.join(pth, fn)
 try:
     root = ET.parse(fl)
 except ParseError as p:
     print("ParseError : ", p)

Here's the code I use for lxml
fl = os.path.join(pth, fn)
try:
    parser = etree.XMLParser(load_dtd=True, resolve_entities=True)
    root = etree.parse(fl, parser=parser)
except etree.XMLSyntaxError as pe:
    print("lxml XMLSyntaxError: ", pe)

I would like the parser to load the ENTITY reference so that it knows that − and all the other character entities specified in all the files are valid entity characters.
Thank you so much for your advice and help.

A: I'm going to answer for lxml. No reason to consider ElementTree if you can use lxml.
I think the piece you're missing is no_network=False in the XMLParser; it's True by default.
Example...
XML Input (test.xml)
<!DOCTYPE doc [
<!ENTITY % ISOEntities PUBLIC 'ISO 8879-1986//ENTITIES ISO Character Entities 20030531//EN//XML' 'http://www.s1000d.org/S1000D_4-1/ent/ISOEntities'>
%ISOEntities;]>
<doc>
    <test>Here's a test of minus: −</test>
</doc>

Python
from lxml import etree

parser = etree.XMLParser(load_dtd=True,
                         no_network=False)

tree = etree.parse("test.xml", parser=parser)

etree.dump(tree.getroot())

Output
<doc>
    <test>Here's a test of minus: −</test>
</doc>

If you wanted the entity reference retained, add resolve_entities=False to the XMLParser.

Also, instead of going out to an external location to resolve the parameter entity, consider setting up an XML Catalog. This will let you resolve public and/or system identifiers to local versions.
Example using same XML input above...
XML Catalog ("catalog.xml" in the directory "catalog test" (space used in directory name for testing))
<!DOCTYPE catalog PUBLIC "-//OASIS//DTD XML Catalogs V1.1//EN" "http://www.oasis-open.org/committees/entity/release/1.1/catalog.dtd">
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
    <!-- The path in @uri is relative to this file (catalog.xml). -->
    <uri name="http://www.s1000d.org/S1000D_4-1/ent/ISOEntities" uri="./ents/ISOEntities_stackoverflow.ent"/>
</catalog>

Entity File ("ISOEntities_stackoverflow.ent" in the directory "catalog test/ents". Changed the value to "BAM!" for testing)
<!ENTITY minus "BAM!">

Python (Changed no_network to True for additional evidence that the local version of http://www.s1000d.org/S1000D_4-1/ent/ISOEntities is being used.)
import os
from urllib.request import pathname2url
from lxml import etree

# The XML_CATALOG_FILES environment variable is used by libxml2 (which is used by lxml).
# See http://xmlsoft.org/catalog.html.
try:
    xcf_env = os.environ['XML_CATALOG_FILES']
except KeyError:
    # Path to catalog must be a url.
    catalog_path = f"file:{pathname2url(os.path.join(os.getcwd(), 'catalog test/catalog.xml'))}"
    # Temporarily set the environment variable.
    os.environ['XML_CATALOG_FILES'] = catalog_path

parser = etree.XMLParser(load_dtd=True,
                         no_network=True)

tree = etree.parse("test.xml", parser=parser)

etree.dump(tree.getroot())

Output
<doc>
    <test>Here's a test of minus: BAM!</test>
</doc>


text:
Q: Bind a property to the body of a request without the FromBody attribute in ASP.NET Core MVC The Problem
I need to find a way to bind a property on a class to the body of an http request in ASP.NET Core MVC, and I need to do it without using the FromBody attribute.
I have the following class:
public class SaveEntity
{
    // This property should be bound from the URL.
    public Guid Id { get; set; }
    // This property should be bound from the body.
    public SaveEntityParameters Payload { get; set; }
}

Here's how I intend to use it in a controller.
[Route("api/v1/[controller]")]
public class EntitiesController : Controller
{
    readonly IBus _bus;
    public EntitiesController(IBus bus)
    {
        if (bus == null)
            throw new ArgumentNullException(nameof(bus));
        _bus = bus;
    }
    [HttpPut("{id}")]
    public async Task<IActionResult> Put(SaveEntity command)
    {
        var response = await _bus.SendAsync(command);
        return Ok(response);
    }
}

The SaveEntity class is located in a class library that does not have a dependency on MVC, so that's why the FromBody attribute is unavailable. How can I bind the Payload property of the SaveEntity class to the body while keeping the Id property bound to the url?
A Less Ideal Work-Around
I've thought about splitting up the Id and Payload properties. Then I could do this:
[HttpPut("{id}")]
public async Task<IActionResult> Put(Guid id, [FromBody]SaveEntityParameters payload)
{
    SaveEntity command = new SaveEntity {Id = id, Payload = payload};
    var response = await _bus.SendAsync(command);
    return Ok(response);
}

But then I have to manually assign the properties of the SaveEntity instance before I can use it. I'd like to avoid the manual assignment, if possible, because this type of thing will be happening in several controllers.

A: This does not answer your question, but you could also do something like below:
public class SaveEntityDTO
{
    [FromRoute]
    public Guid Id { get; set; }

    [FromBody]
    public SaveEntityParameters Payload { get; set; }

    public SaveEntity GetEntity()
    {
      return new SaveEntity { Id = Id, Payload = Payload };
    }
}

Action: public async Task<IActionResult> Put(SaveEntityDTO saveEntityDTO)
I think ideally you need a custom model binder which knows to bind SaveEntity


text:
Q: Object is possible 'undefined' in constructor New features in Typescript look strange for me. In such construction it shows a warning that the _process variable can be undefined, however next command is ok, check the picture
constructor(
  private _process: NodeJS.Process | child_process.ChildProcess
) {
  super();
  _process.send({});
  _process.on('message', (_msg: any) => {
    //
  });
  ...
}

A: That wasn't about _process object that was about send method wich may be undefined in NodeJS.Process


text:
Q: JSON - find element I have JSON that looks like this -
[{
    "Columnd58eae9aee6a43b9836e59254e914f43": 1,
    "Metric": "7e70661f-e266-4745-9b1b-c5c5691e9746",
    "MetricDisplay": "Active Users",
    "Pivot1": 40.00000,
    "Pivot2": 38.00000,
    "Pivot3": 18.00000,
    "Total": 96.00000,
    "Average": 32.00000,
    "IsTotal": 0,
    "MetricOrder": 1
}]

but in this example I have 3 "Pivot" columns, there could and most likely will be more. How do I determine the number of Pivot columns I have and the values for those elements using jQuery?

A: Change your structure of Pivot to an array:
var obj = [{
    "Columnd58eae9aee6a43b9836e59254e914f43": 1,
    "Metric": "7e70661f-e266-4745-9b1b-c5c5691e9746",
    "MetricDisplay": "Active Users",
    "Pivots": [40.00000, 38.00000, 18.00000],
    "Total": 96.00000,
    "Average": 32.00000,
    "IsTotal": 0,
    "MetricOrder": 1
}]

This way, you can find the length of the Pivots element using either of the following:
obj["Pivots"].length
obj.Pivots.length

A: Ideally, you'd use an array:
Pivot: [ 40.00, 38.00, 18.00, ... ],

But you could solve this using bracket notation, something like this:
var i = 1;
while (data['Pivot' + i]) {
    console.log(data['Pivot' + i]);
    i++;
}

A: If Pivot key keep same manner then you can try this code to find get Pivot values
var jsonData = [{
        "Columnd58eae9aee6a43b9836e59254e914f43": 1,
        "Metric": "7e70661f-e266-4745-9b1b-c5c5691e9746",
        "MetricDisplay": "Active Users",
        "Pivot1": 40.00000,
        "Pivot2": 38.00000,
        "Pivot3": 18.00000,
        "Total": 96.00000,
        "Average": 32.00000,
        "IsTotal": 0,
        "MetricOrder": 1
    }];
    var arr = $.map(jsonData[0], function(value, index){
        if(/^(\Pivot)[0-9]+$/.test(index)){
            return value;
        }

      });
    console.log(arr);

    //[40, 38, 18]

A: JSON format you have provided is not a valid one.
I made a slight modification.
 {
  "item": {
    "Columnd58eae9aee6a43b9836e59254e914f43": "1",
    "Metric": "7e70661f-e266-4745-9b1b-c5c5691e9746",
    "MetricDisplay": "Active Users",
    "pivot": {
      "Pivot1": "40",
      "Pivot2": "38",
      "Pivot3": "18"
    },
    "Total": "96",
    "Average": "32",
    "IsTotal": "0",
    "MetricOrder": "1"
  }
};

Object.keys(x.item.pivot).length
This will gives the required length!!


text:
Q: How to center button inside VStack Swift UI var body: some View {
    VStack(alignment: .leading) {
        Text("Title")
            .bold()
            .font(Font.custom("Helvetica Neue", size: 36.0))

        ...

        Button(action: {}){
            Text("Create")
            .bold()
            .font(Font.custom("Helvetica Neue", size: 24.0))
            .padding(20)
            .foregroundColor(Color.white)
            .background(Color.purple)
            .cornerRadius(12)
        }

    }.padding(20)
}

I want different alignments for these two particular elements. Title must have a leading alignment, but on the other hand button is located in the center. Now I set VStack alignment to leading. I'm not familiar with the Swift UI quite well, so the first idea is to use several vertical stacks with different alignments, but I assume it can be done easier. If I add alignment guide to the button, it doesn't work either.

A: I would use included HStack as in demo below

var body: some View {
    VStack(alignment: .leading) {
        Text("Title")
            .bold()
            .font(Font.custom("Helvetica Neue", size: 36.0))

        HStack {
            Spacer()
            Button(action: {}){
                Text("Create")
                .bold()
                .font(Font.custom("Helvetica Neue", size: 24.0))
                .padding(20)
                .foregroundColor(Color.white)
                .background(Color.purple)
                .cornerRadius(12)
            }
            Spacer()
        }
    }.padding(20)
}

A: You could use GeometryReader for this:

A container view that defines its content as a function of its own size and coordinate space.

https://developer.apple.com/documentation/swiftui/geometryreader
GeometryReader { geometry in
    VStack(alignment: .leading) {
        Text("Title")
            .bold()
            .font(Font.custom("Helvetica Neue", size: 36.0))

        Button(action: {

        }) {
            Text("Create")
                .bold()
                .font(Font.custom("Helvetica Neue", size: 24.0))
                .padding(20)
                .foregroundColor(Color.white)
                .background(Color.purple)
                .cornerRadius(12)
                .frame(width: geometry.size.width / 2, height: geometry.size.height / 2, alignment: .center)
        }
    }.padding(20)
}

A: One more way is to use a VStack with center alignment and maxWidth.
VStack(alignment: .leading) {

        Text("Title")
            .bold()
            .font(Font.custom("Helvetica Neue", size: 36.0))

        VStack(alignment: .center) {
            Button(action: {}){
                Text("Create")
                .bold()
                .font(Font.custom("Helvetica Neue", size: 24.0))
                .padding(20)
                .foregroundColor(Color.white)
                .background(Color.purple)
                .cornerRadius(12)
            }
        }.frame(maxWidth: .infinity)

    }.padding(20)


text:
Q: Highcharts: export image show wrong color and line width if user change the color and/or line width I created a chart, and a button to change series color to red. However, after the series color got changed to red, the export image (PNG/JPEG/PDF/SVG) still show the original color (blue) instead of the new color (red).
The way that I change a series color is as follows:
series.color = "#FF3030";
series.graph.attr({
    stroke: "#FF3030"
});
series.legend.colorizeItem(series, series.visible);
$.each(series.data, function (i, point) {
    point.graphic.attr({
        fill: "#FF3030"
    });
});
series.redraw();

I expect the exported image has the new color (red). The code is shared here. The same issue can happen if user change the line width programmatically. Anyone can help me to resolve these 2 issues, i.e., export the new color and width when exporting images.
Thanks in advance!
Alex

A: When you export chart, then it is created again. So as a result, dynamic elements (modified in SVG) like color are skipped. You need to use series.update() and then exported image will be correct.
http://jsfiddle.net/anVxk/2/
 series.update({
        color:'red'
    });

http://api.highcharts.com/highcharts#Series.update()


text:
Q: Need help creating IsValidPassword for PBKDF2 in C# Having the hardest time trying to create a PBKDF2 valid password checker. The PBKDF2 code comes from a SharpHash project; https://github.com/ron4fun/SharpHash. The Class is: SharpHash/SharpHash.Tests/KDF/PBKDF2_HMACTests.cs
The example shows how to implement it but does not have any examples on how to verify the hash afterwards. I managed to tried several different "IsValidPassword" is one of the methods, but none of them seem to work. Each and every one of them the result is false no matter what values I add to the PBKDF2 or IsValidPassword methods. I also tried changing to a hex and also base64 but got the same results; it failed.
I even replaced Rfc2898DeriveBytes.
Does anyone have any experience with PBKDF2 password verification. This would be application based, not website based. IDE environment Visual Studios 2019 - C#.
Thank you.
    public void TestOne()
    {
        IPBKDF2_HMAC PBKDF2 = HashFactory.KDF.PBKDF2_HMAC.CreatePBKDF2_HMAC(hash, Password, Salt, 100000);
        byte[] Key = PBKDF2.GetBytes(64);
        PBKDF2.Clear();

        string ActualString = Converters.ConvertBytesToHexString(Key, false);

        Assert.AreEqual(ExpectedString, ActualString);
    }

public bool IsValidPassword(string password, string hashPass)
    {
        bool result = false;

        // Extract the bytes
        byte[] hashBytes = Encoding.ASCII.GetBytes(hashPass);
        // Get the salt
        byte[] salt = new byte[20]; // Doesn't matter what values and here; same issue… False
        Array.Copy(hashBytes, 0, salt, 0, 20);// Doesn't matter what values and here; same issue… False
        // Compute the hash on the password the user entered
        var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 100000);
        byte[] hash = pbkdf2.GetBytes(64);
        // compare the results
        for (int i = 0; i < 20; i++) // If I go to 64 I get an error
        {
            if (hashBytes[i + 20] != hash[i])
            {
                return false;
            }
        }

        return true;
    }

// Replaced Rfc2898DeriveBytes
        public bool IsValidPassword(string password, string hashPass)
    {
        bool result = false;
        IHash hash1 = HashFactory.Crypto.CreateSHA1();
        // Extract the bytes
        byte[] hashBytes = Encoding.ASCII.GetBytes(hashPass);
        byte[] Password = Encoding.ASCII.GetBytes(password);
        // Get the salt
        byte[] salt = new byte[20]; // Doesn't matter what values and here; same issue… False
        Array.Copy(hashBytes, 0, salt, 0, 20); // Doesn't matter what values and here; same issue… False
        // Compute the hash on the password the user entered
        var pbkdf2 = HashFactory.KDF.PBKDF2_HMAC.CreatePBKDF2_HMAC(hash1, Password, salt, 100000); // Replaced Rfc2898DeriveBytes
        byte[] Key = pbkdf2.GetBytes(64);
        pbkdf2.Clear();
        string test = Converters.ConvertBytesToHexString(Key, false); // Taking a peek
        string test2 = Encoding.ASCII.GetString(hashBytes); // Taking a peek
        // compare the results
        for (int i = 0; i < 20; i++)
        {
            if (hashBytes[i + 20] != Key[i])
            {
                return false;
            }
        }

        return true;
    }

A: taking a quick look at this, the issue you are encountering is simply a misrepresentation of the data contents involved.
password is a base256 based data while hashPass is a base16 based data.
You have to use the appropriate conversion routine when converting hashPass to byte[].
To do that, simply use this method found in the Converters class too.
byte[] hashBytes = Converters.ConvertHexStringToBytes(hashPass);

Do note that I assumed that your password is in base256 (since you didn't specify this in the question) so you can leave it as it is.
The only change you need to make is the one I described above.

A: Well, I suppose this will help someone else down the road apiece. I had to do some serious searching and banging my head up against the wall because this was my first attempt at PBKDF2 to come up with a functional verification method that isn't included with the SharpHash project. Just so that anyone reading this would understand what my problem was. The code generated the password with no issues whatsoever. However, there was no function in the code project that actually verified the password using the salt, generated password and iteration.
The code provided is the simple version because I have also added overloads to the methods that I don't need to post. This method has default settings whereas one of the overloads allows for complete customization of the hash algorithm, salt and iteration. Each of these I had tested and they worked as expected.
Hope this helps someone. :-)
private static Int32 Salt256bit { get; } = 256 / 8; // 256 bits = 32 Bytes
        public static string GetHashPBKDF2Password(string password)
    {
        // Notes:
        // Create a 32-byte secure salt and the same size of the key. This 32-byte produces 256 bits key output.
        // Add the same 32-byte size to the pbkdf2.GetBytes.
        // KDF.PBKDF2_HMAC.CreatePBKDF2_HMAC hashes these values using the crypto SHA presented.
        // Double the hashBytes bytes then add the salt and pbkdf2.GetBytes value.
        // Copy each of the 32-bytes to the hashBytes bytes from the hashed salt and hashed value.
        //
        byte[] Password = Encoding.Unicode.GetBytes(password);
        string hashPass = string.Empty;

        // Create the salt value with a cryptographic PRNG
        byte[] salt;
        new RNGCryptoServiceProvider().GetBytes(salt = new byte[ByteSize]); // 32 Bytes = 256 bits.

        // Create the KDF.PBKDF2_HMAC.CreatePBKDF2_HMAC and get the hash value using the SHA presented.
        // I know SHA1 is not that secured at all anymore. Just using it to test with. :-)
        IHash sha = HashFactory.Crypto.CreateSHA1();
        IPBKDF2_HMAC pbkdf2 = HashFactory.KDF.PBKDF2_HMAC.CreatePBKDF2_HMAC(sha, Password, salt, Pbkdf2Iterations);
        byte[] hash = pbkdf2.GetBytes(ByteSize); // 32 Bytes = 256 bits.

        // Double the size of the byte array to include the "pbkdf2.GetBytes" and salt.
        Int32 g = hash.Length + salt.Length;
        byte[] hashBytes = new byte[g];

        // Combine the salt and password bytes.
        Array.Copy(salt, 0, hashBytes, 0, ByteSize);
        Array.Copy(hash, 0, hashBytes, ByteSize, ByteSize);

        // Turn the combined salt+hash into a string for storage
        hashPass = Convert.ToBase64String(hashBytes);

        return hashPass;
    }

    public static bool ValidatePBKDF2Password(string password, string hashPass)
    {
        try
        {
            byte[] Password = Encoding.Unicode.GetBytes(password);
            bool result = true;

            // Extract the bytes
            byte[] hashBytes = Convert.FromBase64String(hashPass);
            // Get the salt
            byte[] salt = new byte[32];
            Array.Copy(hashBytes, 0, salt, 0, 32);
            // Compute the hash on the password that user entered.
            // I know SHA1 is not that secured at all anymore. Just using it to test with. :-)
            IHash hash1 = HashFactory.Crypto.CreateSHA1();
            IPBKDF2_HMAC pbkdf2 = HashFactory.KDF.PBKDF2_HMAC.CreatePBKDF2_HMAC(hash1, Password, salt, Pbkdf2Iterations);
            byte[] hash = pbkdf2.GetBytes(32);
            // compare the results
            for (int i = 0; i < 32; i++)
            {
                if (hashBytes[i + 32] != hash[i])
                {
                    result = false;
                }
            }
            return result;
        }
        catch (Exception)
        {
            return false;
        }
    }

    How to use:     string GeneratedHash = PBKDF2Helper.GetHashPBKDF2Password("password");
    Results: hv6t8N4rrVSKYFm80cCoVUEiUk2o11xLBc6lJb5kBXKTcwcKwl9dZwSdce01X0bi8BBhJY/QGGnNVAcR7ZhSvQ==

    Verify Paword:  Boolean tester = PBKDF2Helper.ValidatePBKDF2Password("password", GeneratedHash);
                    txtVerificationResults.Text = tester.ToString();


text:
Q: Hibernate update does not work I have SpringMVC/Hibernate web application. When I try to update one of the entries nothing happens.
I try to update the entry using :org.hibernate.Session.merge(object)
I don't have any exceptions.
I enabled mysql to log all the request that receives, In the log I found that there is the update statement but right after that there is a rollback which obviously cancels the update. This is the mysql log
168 Query     SET sql_mode='STRICT_TRANS_TABLES'
 168 Query     SET autocommit=0
 156 Query     SET autocommit=0
 156 Query     select tasks0_.id as id1_0_0_, tasks0_.assigneeId as assignee7_0_0_, tasks0_.description as descript2_0_0_, tasks0_.dueDate as dueDate3_0_0_, tasks0_.name as name4_0_0_, tasks0_.shortName as shortNam5_0_0_, tasks0_.status as status6_0_0_ from tasks tasks0_ where tasks0_.id=2
 156 Query     select user0_.id as id1_1_0_, user0_.email as email2_1_0_, user0_.fullName as fullName3_1_0_, user0_.password as password4_1_0_, user0_.username as username5_1_0_ from users user0_ where user0_.id=1
 156 Query     update tasks set assigneeId=1, description='task1 desc', dueDate='2012-01-01', name='nameaddsaqqq1111111', shortName='task 1 shrt name', status='READY' where id=2
 156 Query     rollback
 156 Query     SET autocommit=1
 168 Query     commit
 168 Query     SET autocommit=1
I don't know what might cause the rollback. Does anyone have an idea?
The code of the controller :
@Controller
public class TaskController {

@Autowired
private TasksService tasksService;

@RequestMapping(value = "/task/update", method = RequestMethod.POST)
    public ModelAndView editTask(@Valid Tasks task, BindingResult result) {

        if (result.hasErrors()) {
            return new ModelAndView("owners/createOrUpdateOwnerForm");
        } else {
            Tasks t = tasksService.findTaskById(task.getId());
            update(task, t);
            t.setName("addsaasddsa");

            tasksService.update(t);
            ModelAndView modelAndView = new ModelAndView("task/editOrCreate");
            modelAndView.addObject("task",
                    tasksService.findTaskById(task.getId()));
            return modelAndView;

        }
    }

The code of the service :
public interface TasksService {

    public void update(Tasks task);

}

The code of the service implementation :
@Transactional
@Service
public class TasksServiceImpl implements TasksService {

    @Autowired
    TaskDAO taskDao;

    @Override
    public void update(Tasks task) {
        taskDao.updates(task);
    }

}

The code of the DAO:
public interface TaskDAO {

    public void updates(Tasks task);

}

The code of DAO implementation :
@Repository
public class TaskDAOImpl extends DbDaoImpl<Tasks> implements TaskDAO {

    @Override
    public void updates(Tasks task) {
        update(task);
    }
}

The code of DbDaoImpl :
import org.hibernate.SessionFactory;
import org.hibernate.Session;

public abstract class DbDaoImpl<T> implements Dao<T> {

@Autowired
    private SessionFactory factory;

    protected Session getSession() {
        return factory.getCurrentSession();
    }

@Override
    @SuppressWarnings("unchecked")
    public T update(final T entity) {
        return (T) getSession().merge(entity);
    }
}

public interface Dao<T> extends Serializable {

    T update(final T entity);
}

The hibernate configuration properties :
dataSource.driverClassName=com.mysql.jdbc.Driver
dataSource.url=jdbc\:mysql\://localhost\:3306/qwerty
dataSource.username=root
dataSource.password=root

hibernate.dialect=org.hibernate.dialect.MySQLDialect

The code of the JPA configuration :
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = { "com.task.tracker.DAO", "my.pack" } /*
                                                                             * basePackageClasses
                                                                             * =
                                                                             * Application
                                                                             * .
                                                                             * class
                                                                             */)
class JpaConfig implements TransactionManagementConfigurer {

    @Value("${dataSource.driverClassName}")
    private String driver;
    @Value("${dataSource.url}")
    private String url;
    @Value("${dataSource.username}")
    private String username;
    @Value("${dataSource.password}")
    private String password;
    @Value("${hibernate.dialect}")
    private String dialect;

    private static final String HIBERNATE_CONFIGURATION_FILE = "hibernate.properties";

    @Bean
    public DataSource configureDataSource() {
        DriverManagerDataSource config = new DriverManagerDataSource();
        config.setDriverClassName(driver);
        config.setUrl(url);
        config.setUsername(username);
        config.setPassword(password);

        config.setConnectionProperties(hibernateConfiguration());

        return config;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean configureEntityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(configureDataSource());
        entityManagerFactoryBean.setPackagesToScan("my.pack",
                "com.task.tracker.DAO");
        entityManagerFactoryBean
                .setJpaVendorAdapter(new HibernateJpaVendorAdapter());

        Properties jpaProperties = new Properties();
        jpaProperties.put(org.hibernate.cfg.Environment.DIALECT, dialect);
        entityManagerFactoryBean.setJpaProperties(jpaProperties);

        return entityManagerFactoryBean;
    }

    @Bean
    // @Qualifier(value = ComponentName.BEAN_SESSION_FACTORY)
    public LocalSessionFactoryBean sessionFactory() {
        final LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();

        localSessionFactoryBean
                .setHibernateProperties(hibernateConfiguration());
        localSessionFactoryBean.setAnnotatedPackages(new String[] { "my.pack",
                "com.task.tracker.DAO" });
        localSessionFactoryBean.setPackagesToScan("my.pack",
                "com.task.tracker.DAO");

        return localSessionFactoryBean;
    }

    /**
     * Loads the hibernate properties from the <b>hibernate.properties</b>
     * configuration file.
     *
     * @return The {@link Properties} object holding all hibernate
     *         configurations.
     */
    @Bean
    // @Qualifier(value = ComponentName.HIBERNATE_PROPERTIES)
    public Properties hibernateConfiguration() {
        final ClassLoader loader = Thread.currentThread()
                .getContextClassLoader();
        final URL url = loader.getResource(HIBERNATE_CONFIGURATION_FILE);
        final Properties properties = new Properties();

        try {
            properties.load(url.openStream());
        } catch (IOException ioe) {
            System.out.println("sfdsfsdf");
        }

        return properties;
    }

    @Bean
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new JpaTransactionManager();
    }

    @Bean
    public org.springframework.orm.hibernate4.HibernateTransactionManager getTransMang() {
        org.springframework.orm.hibernate4.HibernateTransactionManager tr = new org.springframework.orm.hibernate4.HibernateTransactionManager(
                sessionFactory().getObject());
        return tr;
    }

}

The code of the security config :
@Configuration
@EnableWebMvcSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public UserService userService() {
        return new UserService();
    }

    @Bean
    public TokenBasedRememberMeServices rememberMeServices() {
        return new TokenBasedRememberMeServices("remember-me-key",
                userService());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new StandardPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.eraseCredentials(true).userDetailsService(userService());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/", "/favicon.ico", "/resources/**", "/signup")
                .permitAll().anyRequest().authenticated().and().formLogin()
                .loginPage("/signin").permitAll().failureUrl("/signin?error=1")
                .loginProcessingUrl("/authenticate").and().logout()
                .logoutUrl("/logout").permitAll()
                .logoutSuccessUrl("/signin?logout").and().rememberMe()
                .rememberMeServices(rememberMeServices())
                .key("remember-me-key");
        http.csrf().disable();
    }
}

The application configuration :
@Configuration
@ComponentScan(basePackages = { "com.task.tracker.services", "com.task.tracker.DAO.impl" }, excludeFilters = @Filter({
        Controller.class, Configuration.class }))
class ApplicationConfig {

    @Bean
    public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
        PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        ppc.setLocation(new ClassPathResource("/persistence.properties"));
        return ppc;
    }

}

A: The problem is that in JpaConfigI have two beans returning PlatformTransactionManager one that returns JpaTransactionManager and one that returns HibernateTransactionManager. The solution is to remove the JpaTransactionManager.
Thanks to everyone who commented on the question.


text:
Q: How to verify entire content of Geb module using Spock at once without asserting each element individually? I have a Module with content defined for each element on the webpage I am working with:
package com.abc.modules

import geb.Module

class Member extends Module {
    static content = {
        // Member fields
        mbrID {$("div.subject-details div.memberDetails input.projMbrId")}
        mbrName {$("input.projMbrName")}
        mbrRegion {$("select.projMbrReg")}
        mbrAdd1 {$("input.projMbrAdd1")}
        mbrAdd2 {$("input.projMbrAdd2")}
        mbrAdd3 {$("input.projMbrAdd3")}
        mbrCity {$("input.projMbrCity")}
        mbrState {$("select.projMbrState")}
        mbrZip {$("input.projMbrZip")}
        mbrHomePhone {$("input.projMbrHomePhone")}
        mbrHomePhoneExt {$("input.projMbrHomePhoneExt")}
        mbrWrkPhone {$("input.projMbrWorkPhone")}
        mbrWrkPhoneExt {$("input.projMbrWorkPhoneExt")}
        mbrEmail {$("input.projMbrPersonalEMail")}
        mbrWrkEmail {$("input.projMbrWorkEMail")}
    }
}

In my test spec I am asserting that each element contained in my module is present, but the only way I know how to do it is by asserting each element individually:
package cmdr.ProjectCover

import com.gdit.qa.fwa.geb.cmdr.pages.HomePage
import com.gdit.qa.fwa.geb.cmdr.pages.ProjectCover
import geb.spock.GebReportingSpec

class VerifyMemberFields extends GebReportingSpec {
    def setupSpec() {
        // Log in to app
        via HomePage
        loginPage.signIn("marco", "abc123")

        // Navigate to Member Page
        memberPageButton.click()
    }

    def "Verify Member fields exist"() {
        when: "User selects Member option for subject type"
        at ProjectCover
        projSubject.click()
        projCoverMbrFields.projSubjectMbrOption.click()

        then: "All expected member fields are displayed in the left panel"
        assert projCoverMbrFields.mbrID.present
        assert projCoverMbrFields.mbrName.present
        assert projCoverMbrFields.mbrRegion.present
        assert projCoverMbrFields.mbrAdd1.present
        assert projCoverMbrFields.mbrAdd2.present
        assert projCoverMbrFields.mbrAdd3.present
        assert projCoverMbrFields.mbrCity.present
        assert projCoverMbrFields.mbrState.present
        assert projCoverMbrFields.mbrZip.present
        assert projCoverMbrFields.mbrHomePhone.present
        assert projCoverMbrFields.mbrHomePhoneExt.present
        assert projCoverMbrFields.mbrWrkPhone.present
        assert projCoverMbrFields.mbrWrkPhoneExt.present
        assert projCoverMbrFields.mbrEmail.present
        assert projCoverMbrFields.mbrWrkEmail.present
    }

I am wondering if there is a way for me to (instead of asserting each element of my module individually) assert the entire content of the module at once so that my feature method then block conditions can be reduced.

A: I don't know a way to do it at the moment but it will be possible and relatively easy when GEB-369 is implemented.

A: I don't have time to test this, but I think this should work if you want to give it a try:
def "Verify Member fields exist"() {
    when: "User selects Member option for subject type"
    at ProjectCover
    projSubject.click()
    projCoverMbrFields.projSubjectMbrOption.click()

    then: "All expected member fields are displayed in the left panel"
    projCoverMbrFields.content.each{ element ->
        assert element.present
    }
}


text:
Q: Rigidity and superflow In the book "Introduction to Many-Body Physics" by Piers Coleman, it is argued (page 406) that a momentum supercurrent (superflow) corresponds to sheer stress in a crystal. What would be a simple example to understand this?
I can easily imagine a charge supercurrent in a superconductor due to an electric field.
I also understand the fact that it is a "supercurrent", as otherwise there would be a plastic deformation involved.
However, I have trouble coming up with a simple example which shows momentum superflow.
For example, if I have a glass rod which is being compressed from both sides, what is the direction of momentum superflow?

A: It turns out that answers to these questions have been elaborated in a series of articles by Friedrich Herrmann from Karlsruhe and his collaborators. The first article on the subject is "Statics in the momentum current picture" (paywalled).
Examples illustrating application of this technique to bodies under tension or compression are given in "Momentum flow diagrams for just-rigid static structures" (also paywalled, but available from the website of the author as a pdf). See in particular the paragraph under Fig. 2.


text:
Q: Allow cleveref to break between name and number Assume that for external reasons which are related to style but not to (La)TeX and not to be discussed here, I wish to allow cleveref to break a line inside "Section xxx"?  I.e., I am happy with

...[some long formula]... In Section
4.10.7 you will find the full proof.

The same goes for "Lemma xxx", "Definition xxx", and all similar situations. How do I allow cleveref to introduce line breaks?

A: The package crossreftools (current version is 0.6 which is available on CTAN) provides two macros named \crthypercref and \crthyperCref that basically act like \cref and \Cref (with nameinlink option) and allow for breaking of cross - references and displaying like cleveref would do, but only for a standard format, i.e. it does not take some \crefformat settings into account (This is on my TODO - list for the package, however!)
If no hyperlinks are desired, use \crtcref and \crtCref instead.
\documentclass{article}

\usepackage{hyperref}
\usepackage[nameinlink]{cleveref}% nameinlink is not really necessary
\usepackage{crossreftools}

\begin{document}
% Just for testing:
\parindent=0em
\section{A very long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long, long , long, long, long, long, long, long section title} \label{foosection}

Using \verb!\crthypercref!

Now some dummy text in order to force breaking at the end of the line: \crthypercref{foosection} we see...

Using \verb!\crthyperCref!

Now some dummy text in order to force breaking at the end of the line: \crthyperCref{foosection} we see...

Using \verb!\crtcref!

Now some dummy text in order to force breaking at the end of the line: \crtcref{foosection} we see...

Using \verb!\crtCref!

Now some dummy text in order to force breaking at the end of the line: \crtCref{foosection} we see...

Using \verb!\cref!

Now some dummy text in order to force breaking at the end of the line: \cref{foosection} we see...

Using \verb!\Cref!

Now some dummy text in order to force breaking at the end of the line: \Cref{foosection} we see...

Using \verb!\cref! again with extra letters on the line

Now some dummy text in order to force breaking at the end of the line (ext): \cref{foosection} we see...

Using \verb!\Cref! again with extra letters on the line

Now some dummy text in order to force breaking at the end of the line (ext): \Cref{foosection} we see...
\end{document}


text:
Q: Transformation Matrices
Possible Duplicate:
Why can any affine transformaton be constructed from a sequence of rotations, translations, and scalings?

Assuming that I have a set of points in a co-ordinate system (I know their coordinates), then I use a combination of transformations (Rotation, Scaling, Shearing and Translation) to get it to a new system (where again, I know the new co-ordinates), How do I find out the values of shearing, rotation, scaling and translation? Any method other than Iwasawa?
What I have tried:
The only thing I've realized is that if I have set of old coordinates and a set of new co-ordinates,
$$[Old] \times Transformation Matrix = [New]$$
$$Transformation Matrix = [Old] ^{-1}[New]$$
This gives me the cumulative Transformation matrix, how do I break it down to tell me what the shear, rotation, scale and translation was?

A: The translation, of course, will not be expressed in the matrix, but rather it is given by adding a fixed vector to all the old coordinates.
Now supposing your old and new coordinates share the same origin (after translation), you can compute the matrix $M$ for which transforms old coordinates to new: $[x_1\dots x_n]M=[y_1\dots y_n]$. I'm pretty sure the conditions you want make $M$ nonsingular, so the polar decomposition of $M$ will tell you what rotation and what stretching has occurred.
I don't know about shear explicitly: is it just the result of stretching going at different rates in different directions?