text:
Q: jQuery: undefined on object with the correct selector I've got a problem with jQuery: I've the following html code:

            Autos >

                    Bauteile >

Innenfutter

Something else here

Separated link

< Zurück

Another action

Something else here

Separated link

< Zurück

And this jQuery code:
    var $finderTopObj = $('#finder-menu');
    var $originalTopHtml = $finderTopObj.html();

    $('.slide-left1').click(function(e) {
        console.log('click 1');
        var $clickedItem = $(this);
        var $sourceId = $(this).attr('data-source');
        console.log('step 2 ('+$sourceId+')');

        $clickedItem.addClass('active');
        var $sourceHtml = $($sourceId).html();
        var $targetObj = $('#finder-child1');
        console.log('set html to '+$targetObj.selector);
        $targetObj.html($sourceHtml);
        $finderTopObj.animate({
            width: "50%"
        }, 200, function () {
            $finderTopObj.addClass('col-md-6');
            $targetObj.addClass('col-md-6');
            $targetObj.removeClass('hide');
            console.log('done step 1------------');

            $('.slide-left2').click(function(e) {
                console.log('click 2');
                var $clickedItem2 = $(this);
                var $sourceId2 = $clickedItem2.attr('data-source');
                console.log('step 2 ('+$sourceId2+')');

                $clickedItem2.addClass('active');
                var $sourceHtml2 = $($sourceId2).html();
                console.log($sourceHtml2);
                var $targetObj2 = $('#finder-child2');
                console.log('set html to '+$targetObj2.selector);
                $targetObj2.html($sourceHtml2);
                $finderTopObj.animate({
                    width: "33%"
                }, 200, function () {
                    $finderTopObj.removeClass('col-md-6');
                    $finderTopObj.addClass('col-md-4');
                    $targetObj.removeClass('col-md-6');
                    $targetObj.addClass('col-md-4');
                    $targetObj.animate({
                        width: "33%"
                    }, 200, function () {
                        $targetObj2.addClass('col-md-4');
                        $targetObj2.removeClass('hide');
                        console.log('done step 2------------');
                    });
                });
            });
        });
    });

The problem is: the var "$sourceHtml2" is undefined and I can't find the wrong code. Is there someone who can help? Thanks!
For testing: It's based on bootstrap 3. Maybe this css code will also help to test it.
.side-finder {
    font-size: 12px;
    font-weight: 200;
    background-color: #2e353d;
    top: 0px;
    width: 100%;
    color: #333333;
    height: 100vh;
}

.side-finder .brand {
    background-color: #23282e;
    line-height: 50px;
    display: block;
    text-align: center;
    font-size: 14px;
}

.side-finder li a, .side-finder li a:hover,.side-finder li a:focus {
    background-color: transparent;
    -webkit-border-radius: 0px;
    -moz-border-radius: 0px;
    border-radius: 0px;
    color: #cacaca;
    font-weight: bold;
    border-bottom: 1px solid #53585e;
}

.side-finder li a:hover {
    color: #efefef;
}

.side-finder li a.active  {
    background-color: #3e656d;
}

.side-finder .finder-content {
    overflow: auto;
    height: 100%;
}

A: You have a data attribute that looks like
#sc1.1423423

note the period, then you do some getting and use a variable and you end up with
$('#sc1.1423423')

Note how that matches an element with the ID sc1 and the  class 1423423
To make it work in jQuery the period has to be escaped
$('#sc1\\.1423423')

The right thing to do would be to not use periods in the ID, but if that's not an option, you can try replacing it
$sourceId2 = $clickedItem2.attr('data-source').replace('.', '\\.');


text:
Q: MapView marker show previous on iOS With Firemonkey 10.4.2.
I had a problem when I click on marker.
If I do that

*

*Click on Marker A

*Click on Marker B

*Click on Map

*Click on Marker A => I see info of Marker B, the MapMarker of MapViewMarkerClick is bad

I find a problem on FMX.Maps.iOS the last Marker is keep in memory and never set to nil, that's why I always have the same. When you click on a marker, it's look like you go to MapClick and then MapMarkerClick. That's not really clear.
When the map is shown with all marker. If click on Marker A, I first go to MapClick, I need to click a second time on the Marker to see it. Then I can naviguate to each marker, but if I click on map. The next time I click on marker I need to do it 2x.
All is good on Android, I think it's a problem in FMX.Maps.iOS again.
Any idea ?
Here is the original code with my edit :
procedure TMapKitMapView.MapEvent(const Event: TMapEvent);
// added
var
  SelectedMarker: TMapMarker;
// end added
begin
// added
  SelectedMarker := FSelectedMarker;
// end added

  case Event.Kind of
    TMapEventKind.CameraChanged:
      begin
        SyncCameraPosition;
        FHostControl.DoCameraChanged;
      end;
    TMapEventKind.MarkerClick:
      begin
        // Marker has been selected
        FSelectedMarker := Event.Marker;
        FHostControl.DoMarkerClick(Event.Marker);
      end;
    TMapEventKind.MarkerDeselect:
        FSelectedMarker := nil;
    TMapEventKind.MarkerDragStart:
      FHostControl.DoMarkerDragStart(Event.Marker);
    TMapEventKind.MarkerDrag:
      FHostControl.DoMarkerDrag(Event.Marker);
    TMapEventKind.MarkerDragEnd:
      FHostControl.DoMarkerDragEnd(Event.Marker);
    TMapEventKind.MapClick:
      if FDragState = MKAnnotationViewDragStateNone then
        if FSelectedMarker = nil then
          FHostControl.DoMapClick(Event.LatLng)
        else
          FHostControl.DoMarkerClick(FSelectedMarker);
    TMapEventKind.MapLongClick:
      if FDragState = MKAnnotationViewDragStateNone then
        if FSelectedMarker = nil then
          FHostControl.DoMapLongClick(Event.LatLng);
    TMapEventKind.MapDoubleClick:
      if FSelectedMarker = nil then
        FHostControl.DoMapDoubleClick(Event.LatLng)
      else
        FHostControl.DoMarkerDoubleClick(FSelectedMarker);
  end;

// added
  if FSelectedMarker = SelectedMarker then
    FSelectedMarker := nil;
// end added
end;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find all records where between 2 dates have a certain value for each record I have a table with vacation houses which have some availability (column value, value 1 means available ).
How can I find all houses (column unit_id) that are are available between 2 dates.
table
CREATE TABLE `houseavailability` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `date` varchar(100) DEFAULT NULL,
  `value` varchar(100) DEFAULT NULL,
  `unit_id` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `houseavailability_unit_id_IDX` (`unit_id`,`date`) USING BTREE,
  KEY `houseavailability_unit_id_IDX_solo` (`unit_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=16648943 DEFAULT CHARSET=latin1;

test data
INSERT INTO houseavailability
(id, `date`, value, unit_id)
VALUES(15814115, '2022-07-23', '1', '1004004');
INSERT INTO houseavailability
(id, `date`, value, unit_id)
VALUES(15814116, '2022-07-24', '1', '1004004');
INSERT INTO houseavailability
(id, `date`, value, unit_id)
VALUES(15814117, '2022-07-25', '1', '1004004');
INSERT INTO houseavailability
(id, `date`, value, unit_id)
VALUES(15814118, '2022-07-26', '1', '1004004');
INSERT INTO houseavailability
(id, `date`, value, unit_id)
VALUES(15814119, '2022-07-27', '1', '1004004');
INSERT INTO houseavailability
(id, `date`, value, unit_id)
VALUES(15814120, '2022-07-28', '1', '1004004');
INSERT INTO houseavailability
(id, `date`, value, unit_id)
VALUES(15814121, '2022-07-29', '1', '1004004');
INSERT INTO houseavailability
(id, `date`, value, unit_id)
VALUES(15814122, '2022-07-30', '0', '1004004');

attempt
SELECT houseavailability.*
FROM houseavailability
WHERE houseavailability.date BETWEEN '2022-07-23' AND '2022-07-30'
AND houseavailability.unit_id = 1004004;

http://sqlfiddle.com/#!9/094547/2

A: For example, find a  unit_id which is available during the whole specified period.
SELECT unit_id
FROM houseavailability
WHERE date BETWEEN '2022-07-23' AND '2022-07-30'
GROUP BY unit_id
HAVING sum(value) = datediff('2022-07-30','2022-07-23') + 1;

A: You can try to use the condition aggregate function in HAVING to compare whether all the rows for which this is true between your date condition.
Query 1:
SELECT unit_id
FROM houseavailability
WHERE date BETWEEN '2022-07-23' AND '2022-07-30'
GROUP BY unit_id
HAVING COUNT(DISTINCT date) = COUNT(DISTINCT CASE WHEN value = '1' THEN date END)

Results:
DISTINCT which is in aggregate function will count only once, if there are duplicate days have 1 value in your tables, but if you want to count multiple when you met that situation you can remove DISTINCT from the aggregate function.
EDIT
Due to there being a UNIQUE constraint from your unit_id and date columns, you don't need to use DISTINCT on your aggregate function.
SELECT unit_id
FROM houseavailability
WHERE date BETWEEN '2022-07-23' AND '2022-07-30'
GROUP BY unit_id
HAVING COUNT(*) = COUNT(CASE WHEN value = '1' THEN date END)


text:
Q: Iniciar servicio no me funciona mediante Systemctl Hola, mencionar antes de nada que soy novatillo y que si tenéis cualquier cosa que creéis que puedo hacer mejor a la hora de redactar la pregunta me lo podéis decir y intentare arreglarlo cuanto antes.
Primero de todo comentar que los comandos que lanza y que están definidos en él ".service" funcionan si los lanzas manualmente.
A continuación el contenido del fichero:
[Unit]
Description=Node Red Express
After=networking.service

[Service]
Type=oneshot
ExecStart=/home/pi/node-red-express/script_gestionador.sh start
ExecStatus=/home/pi/node-red-express/script_gestionador.sh status
ExecStop=/home/pi/node-red-express/script_gestionador.sh stop
User=pi
RootDirectory=/
WorkingDirectory=/home/pi/node-red-express/

[Install]
WantedBy=multi-user.target

Mas cosas a comentar es que es necesario que se lancen con el usuario "pi", que tenga acceso a todo des de la raíz hacia abajo (siempre que tenga permisos) esto simplemente establece la "jail", y el working directory debe de ser el indicado pues sino algunos comandos de más adentro no irán correctamente...
Los permisos del archivo a ejecutar también están bien puestos para el usuario PI.
-rwxrwxr--   1 pi pi     4412 may 20 16:07 script_gestionador.sh

Y para que el usuario sin privilegios de PI puede ejecutar systemctl he usado sudoers sin contraseña para systemctl en concreto, justo debajo la línea...
pi ALL=(ALL) NOPASSWD:/sbin/shutdown, /bin/systemctl

Tal y como he dicho antes si ejecuto los comandos manualmente des de la terminal funcionan, pero si ejecuto un sudo systemctl start node.service, es raro porque no parece que realice ninguna acción ni nada... Extrañado realice un journalctl -xe y esto es lo que me sale...
    may 20 16:51:58 raspberrypi sudo[871]:       pi : TTY=pts/0 ; PWD=/home/pi ; USER=root ; COMMAND=/bin/systemctl start node.service
may 20 16:51:58 raspberrypi sudo[871]: pam_unix(sudo:session): session opened for user root by pi(uid=0)
may 20 16:51:58 raspberrypi systemd[1]: Starting Node Red Express...
-- Subject: Unit node.service has begun start-up
-- Defined-By: systemd
-- Support: https://www.debian.org/support
--
-- Unit node.service has begun starting up.
may 20 16:51:58 raspberrypi script_gestionador.sh[877]: /home/pi/node-red-express
may 20 16:51:58 raspberrypi script_gestionador.sh[877]: Proceso iniciado con pid... 880
may 20 16:51:58 raspberrypi script_gestionador.sh[877]: Proceso Monitorizacion iniciado con exito con PID... 881
may 20 16:51:58 raspberrypi script_gestionador.sh[882]: /home/pi/node-red-express
may 20 16:51:58 raspberrypi script_gestionador.sh[882]: Aviso: Se trataran de parar AMIGABLEMENTE asi que puede tardar unos cuantos segundos,
may 20 16:51:58 raspberrypi script_gestionador.sh[882]: en caso de que tarde demasiado y no se pare mediante este script se debera borrar tambien el
may 20 16:51:58 raspberrypi script_gestionador.sh[882]: el archivo /home/pi/node-red-express/pid.txt y /home/pi/node-red-express/pid_m.txt
may 20 16:51:58 raspberrypi script_gestionador.sh[882]: donde se guarda los pid de cada proceso
may 20 16:51:58 raspberrypi script_gestionador.sh[882]: Se va a terminar el proceso con PID... 880
may 20 16:51:58 raspberrypi script_gestionador.sh[882]: Se va a terminar el proceso de monitoraje con PID... 881
may 20 16:51:58 raspberrypi script_gestionador.sh[882]:
may 20 16:51:58 raspberrypi script_gestionador.sh[882]: Proceso terminado con exito
may 20 16:51:58 raspberrypi script_gestionador.sh[877]: Signal 15 (TERM) caught by ps (3.3.12).
may 20 16:51:58 raspberrypi script_gestionador.sh[877]: ps:ps/display.c:66: please report this bug
may 20 16:51:58 raspberrypi systemd[1]: Started Node Red Express.
-- Subject: Unit node.service has finished start-up
-- Defined-By: systemd
-- Support: https://www.debian.org/support
--
-- Unit node.service has finished starting up.
--
-- The start-up result is done.
may 20 16:51:58 raspberrypi sudo[871]: pam_unix(sudo:session): session closed for user root
lines 1686-1723/1723 (END)

La verdad es que es bastante curioso porque según veo en esto último es como si el los comandos de start y stop se ejecutasen uno después del otro... Cuando, insisto, el script que recibe los parámetros si lo ejecuto tal cual sale en el archivo de configuración ".service" funcionan a la perfección...
Por no hablar de la linia de "ps:ps/display.c:66: please report this bug"
Voy a seros sincero... No sé por dónde empezar a coger este problema...
¿A alguien se le ocurre algo?
Gracias de Antemano

A: humm no se si te servirá.
yo al final opte por una solución mas sencilla.
(aunque menos robusta que un servicio).
he añadido esta linea al final de /etc/rc.local
(cd /home/pi/ ;su  pi -c "nohup node-red --max-old-space-size=196&")&

cada vez que se inicia la maquina se carga el node en segundo plano.
Ademas le limita la memoria que puede consumir.
Lo tengo corriendo en una Pi1 desde hace ya unos años.


text:
Q: What is the difference between v-html and v-text? I had the following code using v-text:

Output:

Brand Name is B&C

So I fixed it using v-html in the previous line:

Output:

Brand Name is B&C

My question is the following:
Why does it works using v-html and not v-text? I already read the Vue documentation but I don't clearly understand the difference.

A: v-text sets the textContent of the node. v-html sets the innerHTML of the element. & is an HTML entity. If you want HTML entities interpreted and replaced, you need to have them interpreted as HTML and not text.

A: The v-html directive is  used to update a element's innerHTML with our data. This is what separates it from v-text which means while v-text accepts string and treats it as a string it will accept string and render it into HTML.

A: Simply stated, if you know js:

*

*v-html == innerHTML

*v-text == innerText


text:
Q: How to calculate the mean of a list in a row in csv? I have a data like this in an CSV file;
x         Y
[2,3,4]   [3.4,2.5,3.1]
[4,5,2]   [6.2,7.5,9.7]
[2,6,9]   [4.6,2.5,2.4]
[1,3,6]   [8.9,7.5,9.2]

I want to calculate the mean for each list in a row
x                Y
[2,3,4] < mean   [3.4,2.5,3.1] < mean
[4,5,2] < mean   [6.2,7.5,9.7] < mean
[2,6,9] < mean   [4.6,2.5,2.4] < mean
[1,3,6] < mean   [8.9,7.5,9.2] < mean

and output the mean value to a CSV file.
How can it achieve it using python (pandas)?
EDIT
After some research, I found the solution to my issue above;
import csv
import pandas as pd
import numpy as np
from ast import literal_eval

#csv file you want to import
filename ="xy.csv"
fields = ['X','Y'] #field names

df = pd.read_csv(filename,usecols=fields,quotechar='"', sep=',',low_memory = True)
df.X = df.X.apply(literal_eval)
df.X = df.X.apply(np.mean) #calculates mean for the list in field 'X'
print(df.X) #print result

df.Y = df.Y.apply(literal_eval)
df.Y = df.Y.apply(np.mean) #calculates mean for the list in field 'Y'
print(df.Y)

A: Via applymap:
# df = df.applymap(lambda x: sum(eval(x))/ len(eval(x)))
df = df.applymap(np.mean) # suggested by alex
df = df.applymap(lambda x: sum(x)/ len(x))

OUTPUT:
          x         Y
0  3.000000  3.000000
1  3.666667  7.800000
2  5.666667  3.166667
3  3.333333  8.533333

A: You can use .applymap() with np.mean() to map the dataframe element-wise.
import numpy as np

df = df.applymap(eval)     # optional step if your column is a string like a list instead of truly a list
df = df.applymap(np.mean)

Result:
print(df)

          x         Y
0  3.000000  3.000000
1  3.666667  7.800000
2  5.666667  3.166667
3  3.333333  8.533333


text:
Q: ELB HAproxy and cookies I'm using ELB in front of HA-Proxy. Stickiness is disable on ELB and I have this configuration in HA-Proxy:
backend endpoint
    balance leastconn
    cookie  VALUE insert nocache maxidle 30

I'm using curl to query and I noticed that if I query directly HA-Proxy I get a cookie for each query. However with ELB, I would get a cookie at the first query but not with the next ones, I have to wait few minutes before it give me a cookie.
Any idea why?
HA-Proxy version 1.4.18 2011/09/16

A: Turned out that I needed to ask HA-Proxy to close the connection as soon as possible using option http-server-close or option forceclose.
More information about ELB keepalive can be found here

ELB's HTTP listeners present an HTTP 1.1 endpoint to clients, which means that:

*

*HTTP Keepalive will be enabled by default for an HTTP 1.1 client

*HTTP Keepalive will be disabled by default for an HTTP 1.0 client

*In either case, the client can explicitly turn keepalive on or off by including the "Connection: keep-alive" or "Connection: close" headers, respectively, in the request.

Source: https://forums.aws.amazon.com/thread.jspa?messageID=200999&#200999


text:
Q: Excluding specific column I am looking at some trade data on which I want to run some Knn stuff... The Table hat the following columns: Quantity - Price - Years to Marutiry - Buy/sell - Segment - Broker
To run the analytics, I already encoded "Buy/sell" and "Segment". The Broker I want to use as a label, so I cannot encode him. The problem: in the Other Columns are sometime NaNs. So I need to remove these lines. but since "Broker" is always not a number, dropna does not work. Is there a way that I can say "Drop the row, if any columen buy Broker contains a NaN?"
... In Reality I got a lot of columns, so I would like a solution that allows me to "exclude the broker column" instead of needing to deinfe all columns on which this should work...
Maybe I could first split the dataframe in two pieces: BROKERLIST and REST. Then I could run dropna on REST and remerge it with the BROKERLIST. but for that i would need to remove the same rows of the BROKERLIST than I removed in REST. Any way I can easily do this?
Thanks

A: you can use the subset parameter of the dropna() method
import pandas

columns = set(df.columns)
columns_to_keep = columns.remove('Broker')

print(columns_to_keep)

df.dropna(subset=columns_to_keep, inplace=True)


text:
Q: Using case statement to compare columns I'd like to use a case statement to compare multiple rows on 2 columns. For example, if row 1 column 1 and row 2 column 1 match but row 1 column 2 and row 2 column 2 don't, then xx. I have
CASE
  WHEN (pprof.description = pprof.description and PCtrl.[sequence] <> PCtrl.[sequence])
  THEN xx

but that doesn't return any values, which I know to be incorrect. I'm new to SQL so apologies if I've got this all wrong.
Edit:
Here's some sample data:

Column 1
Column 2
Column 3

123
-A
-No

123
-B
-Yes

Can't figure out the formatting here but there are 3 columns of data above. I'd like the case statement to evaluate whether column 1 match in 2 different rows (i.e., 123 = 123) and also whether column 2 doesn't (A <> B) and if both those conditions are true, return a value in column 3 (in my case, make the No a Yes, since 123-B is Yes). It might be worth noting that the "Yes" and "No" themselves are built into the larger case statement here:
(CASE WHEN tenure.description not in ('casual','co-op','fswep') THEN CASE WHEN (pprof.description = pprof.description and PCtrl.[sequence] <> PCtrl.[sequence])
     THEN CASE WHEN (PEmp.Employee_Number = PEmp3.Supervisor_Number) THEN 'Yes' ELSE 'No' END END END) as 'People Manager'

A: You will want to do a self join here. Without seeing your data, I can't really give you an answer, but you want something like this.
Update A
Set column_3 = 'YES' /* or put CASE statement here /*
FROM pprof A
INNER JOIN pprof B
ON a.description = b.description
AND a.sequence != b.sequence

You may need more join conditions depending on the form of your data and what you want.


text:
Q: Angular JS Refresh Pager Directive I have pager directive which depends on data which is received async in controller. Since pager needs to know total count to correctly render pages, I would like to hide whole pager until async data is downloaded, and then show it (but before showing, run link function to setup pager information) along with the data.
How is this possible?
(function () {
'use strict';

angular
    .module('App.widgets')
    .directive('customPager', customPager);

function customPager() {
    var pager = {
        scope: {
            pageIndex: '=',
            pageSize: '=',
            recordCount: '=',
            pageClick: '&onPageClick'
        },
        replace: true,
        restrict: 'E',
        templateUrl: 'custom-pager.html',
        link: link
    }

    return pager;

    function link(scope) {
        ....
    }
}})();

A: I hope this help you ;)

<!DOCTYPE html>
<html ng-app="testApp">
<head>
    <title>My ParseApp site</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="/Scripts/angular.js"></script>
</head>
<body>

    <refresh></refresh>

    <script>
        angular.module("testApp", [])
            .directive("refresh", function () {
                return {
                    restrict: "E",
                    template: "<button ng-click=\"refreshPage()\">Refresh this page</button>",
                    link: function (scope, elem) {
                        scope.refreshPage = function () {
                            location.reload();
                        }
                    }
                };
            });

    </script>
</body>
</html>

A: First, In template 'custom-pager.html', set an ng-show or ng-hide attribute to hide the content of the template.
Second, you'll need to flip the show or hide variable. You can make it visible in several different ways. If the you're caching the $http request in your service, you can simply call it again in your directive and wait for the promise to fire.
Alternatively, your service or controller could broadcast an event when completing the request (check out $emit)


text:
Q: Learn how to make Flair for my users (javascript snippets) I wanted to give my users a little piece of JavaScript or HTML code that they could put on their site and show information about them. Kind of like StackOverFlows new feature Flair.
I have an idea of how to code it. I was going to give them some JS with a HTML that had a DIV id="MySite_Info". Then the JS would go to my site and pull some JSON or XML and then fill in the data with a DIV in the HTML I gave them on their site.
Is there a better way to do this? Or any examples online I should follow? Whats the best way to create these javascript snippets? (Not sure what the proper name is)

A: There are two basic options.

*

*Images (and pictures of text suck)

*JavaScript - as you described

The approach I would take would be to:

*

*Dynamically generate the JS using a server side process. This would include data for the user (using a JSON generator to easily produce the data in a suitable format).

*Build the badge using standard DOM methods

*Find the element with the document id and appendChild the generated badge


text:
Q: How to Retrieve JavaScript Window.PostMessage data inside ATL BHO C++ I am able to get JavaScript listener for window.postMessage working inside ATL BHO by following this article. Javascript post message event handler in ATL C++ BHO
But How to i retrieve message data out of it ?
JavaScript Code:
window.postMessage({
            type: 'data_received',
                  Cross : {
            data: data_Id
            }
            }, '*');

Event listener:
STDMETHODIMP CListener::InvokeEx(DISPID dispidMember, LCID, WORD, DISPPARAMS* params, VARIANT*, EXCEPINFO*, IServiceProvider*)
{
HRESULT hr;

::MessageBox(NULL, L"Hello", L"World", MB_OK);

if (dispidMember != DISPID_VALUE)
{
    return DISP_E_MEMBERNOTFOUND;
}

CComDispatchDriver dispDomEvent(params->rgvarg[1].pdispVal);
if (!dispDomEvent)
{
    Logger::LogInfo(L"Could not get the DOM event");
    return E_INVALIDARG;
}

CComVariant eventTarget;
hr = dispDomEvent.GetPropertyByName(L"target", &eventTarget);
if (FAILED(hr))
{
    Logger::LogInfo(L"Could not get the target for the DOM event: 0x%x", hr);
    return hr;
}
}


text:
Q: Is there a way to make Google App Engine print out any and all Python errors whenever it encounters them? I'm getting server errors, but no idea why So many times I have seen this screen:
Server error
The website encountered an error while retrieving http://localhost:8080/. It may be down for maintenance or configured incorrectly.
Here are some suggestions:
Reload this webpage later.
HTTP Error 500 (Internal Server Error):
An unexpected condition was encountered while the server was attempting to fulfill the request.

Obviously, that gives absolutely no useful information. So I have to systematically undo everything I've previously coded, with each step reloading the page to see if I've found what ever it is that app engine doesn't like, and the whole process is just... demoralizing.
I just spent a half-hour digging through my code trying to figure out what was broken. Turned out GAE didn't like a module I was importing -- note that I still have no idea why it doesn't like it, but that's beside the point.
My question is this, is there a way to have report any and all errors? I have Debug set to true, but it very finicky about when it will actually print out the stack trace.

A: Whatever framework you're using is generating that.  There's probably an exception handler that will generate your 500 message.  You'll have to find that and adjust it to not catch all exceptions.
Can't help you figure out where though, I'm not sure what framework you're using.

A: By default - for most frameworks - exceptions are logged rather than output to the user, since there's no point in showing your user a stacktrace of your app's internal details. If you're running the dev_appserver, these show up in the console window; in production these can be accessed via the log viewer.


text:
Q: CSRF session token missing in a nginx + gunicorn + flask architecture my website developed in flask works fine on gunicorn, it is using flask_wtf for setting up CSRF. Login and other html pages are using CSRF.
As i run it behind nginx reverse proxy i got a "The CSRF session token is missing." error.
As everything works fine on gunicorn i suppose problem is in my current nginx configuration.
follows the nginx.conf I m using:
'''

user ec2-user;
worker_processes auto;
error_log /var/log/nginx/error.log debug;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;
    error_log /var/log/nginx/error.log;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   120;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    include /etc/nginx/conf.d/*.conf;

    ##
    # SSL Settings
    ##

    ssl_session_timeout 10m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

##
    # Gzip Settings
    ##

    gzip on;

    gzip_proxied any;
    gzip_min_length 500;
    gzip_disable "MSIE [1-6]\."
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    upstream app_servers {
        server  127.0.0.1:8000;
    }

    server {
        listen 80;
        return 301 https://$host$request_uri;

    }

    server {
        listen 443 ssl;

        ssl_certificate /home/cert/cert.pem;
        ssl_certificate_key /home/cert/privkey.pem;
        keepalive_timeout 120;

        location / {
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_connect_timeout   3;
            proxy_send_timeout      3;
            proxy_read_timeout      3;
            proxy_ignore_headers Set-Cookie;
            proxy_hide_header    Set-Cookie;
            proxy_cache                     off;
            proxy_pass http://app_servers;
            # Headers for client browser NOCACHE + CORS origin filter
            proxy_cache                     off;
            proxy_pass http://app_servers;
            # set all cookies to secure, httponly and samesite by modifying "path"
                proxy_cookie_path / "/; secure; HttpOnly; SameSite=lax";
            expires -1;

        }

        location ^~ /static/ {
            root /home/ec2-user/blabla/application/;
        }

    }
'''

any help, hint, suggestion how to investigate further the problem, how to trace the request will be more than welcome.

A: adding
proxy_set_header Cookie $http_cookie;
as per below
'''
location / {
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header Cookie $http_cookie;

'''
fixed all.


text:
Q: Add content to frames of an OpenOffice odp presentation in ODFToolkit I want to use a Open Office / Libre Office Presentation as a template and insert text and images into slides. I am trying to use odftoolkit. If I have a slide with the boxes, they are represented as <draw:frame> in the XML
How do I access those to place an image in them? Should I use these classes?

*

*org.odftoolkit.simple.PresentationDocument

*org.odftoolkit.simple.presentation.Slide
When I have a slide open the related methods I see are:

*

*.getOdfElement

*.getFrameContainerElement
But I am not able to see how to select frames in the slide. When I open the XML I have the 5 frames under <draw:page>.
The have attributes like: presentation:style-name="pr2" draw:layer="layout"

A: As Eugene commented, I had to find the target frame and do more work. There is no method to add images to a frame, only to a slide. I went into the methods and succeeded as follow:
DrawPageElement drawPageElement = slide.getOdfElement();
DrawFrameElement drawFrame = OdfElement.findFirstChildNode(DrawFrameElement.class, drawPageElement);
DrawImageElement image = drawFrame.newDrawImageElement();
OdfPackage mOdfPackage = odp.getPackage();
String imageRef = "/some/path/to/chart.png";

String packagePath = odp.getDocumentPath() + OdfPackage.OdfFile.IMAGE_DIRECTORY.getPath() + "/" + someMethodToCreateRandomString();

mOdfPackage.insert(new URI(imageRef), packagePath, OdfFileEntry.getMediaTypeString(imageRef));
packagePath = packagePath.replaceFirst(odp.getDocumentPath(), "");
URI uri = new URI(AnyURI.encodePath(packagePath).toString());
image.setXlinkHrefAttribute(AnyURI.decodePath(uri.toString()));
image.setXlinkActuateAttribute("onLoad");
image.setXlinkShowAttribute("embed");
image.setXlinkTypeAttribute("simple");

I was hoping for something closer to the GUI because I think I have missed some styles and better way to find frames. But anyway it is not bad.


text:
Q: Modifying fs/binfmt_elf.c to fetch a custom-added section content I am trying to modify fs/binfmt_elf.c to fetch the content of a new ELF section I have added to my sample C program.
Sample C program:
#include <stdio.h>

/* Adding my own ELF section*/
char my_custom_section[128][2] __attribute__ ((section (".mysection"))) = { 0 };

int main() {
      return 0;
}

Here's the output of readelf -l a.out:
Elf file type is EXEC (Executable file)
Entry point 0x4003d0
There are 9 program headers, starting at offset 64

Program Headers:
  Type           Offset             VirtAddr           PhysAddr
                 FileSiz            MemSiz              Flags  Align
  PHDR           0x0000000000000040 0x0000000000400040 0x0000000000400040
                 0x00000000000001f8 0x00000000000001f8  R E    8
  INTERP         0x0000000000000238 0x0000000000400238 0x0000000000400238
                 0x000000000000001c 0x000000000000001c  R      1
      [Requesting program interpreter: /lib64/ld-linux-x86-64.so.2]
  LOAD           0x0000000000000000 0x0000000000400000 0x0000000000400000
                 0x000000000000067c 0x000000000000067c  R E    200000
  LOAD           0x0000000000000e28 0x0000000000600e28 0x0000000000600e28
                 0x00000000000002f8 0x0000000000000308  RW     200000
  DYNAMIC        0x0000000000000e50 0x0000000000600e50 0x0000000000600e50
                 0x0000000000000190 0x0000000000000190  RW     8
  NOTE           0x0000000000000254 0x0000000000400254 0x0000000000400254
                 0x0000000000000044 0x0000000000000044  R      4
  GNU_EH_FRAME   0x00000000000005ac 0x00000000004005ac 0x00000000004005ac
                 0x000000000000002c 0x000000000000002c  R      4
  GNU_STACK      0x0000000000000000 0x0000000000000000 0x0000000000000000
                 0x0000000000000000 0x0000000000000000  RW     8
  GNU_RELRO      0x0000000000000e28 0x0000000000600e28 0x0000000000600e28
                 0x00000000000001d8 0x00000000000001d8  R      1

 Section to Segment mapping:
  Segment Sections...
   00
   01     .interp
   02     .interp .note.ABI-tag .note.gnu.build-id .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rela.dyn .rela.plt .init .plt .text .fini .rodata .eh_frame_hdr .eh_frame
   03     .ctors .dtors .jcr .dynamic .got .got.plt .data .mysection .bss
   04     .dynamic
   05     .note.ABI-tag .note.gnu.build-id
   06     .eh_frame_hdr
   07
   08     .ctors .dtors .jcr .dynamic .got

So .mysection is assigned to segment 03 of type LOAD.
However, going through the source of fs/binfmt.c, I am unable to understand how exactly can I fetch the content/value of .mysection. It seems that load_elf_binary() only iterates through program headers and segments, and not section headers or sections.
(which presumably makes sense because it's a loader and hence, views an ELF file as segments and not as sections).
But even when it iterates through the program segments, I don't understand how is it iterating through the sections within a segment.
Basically, I need to fetch the value of my own section .mysection, through modifying fs/binfmt.c, so that whenever an ELF executable with .mynewsection is loaded in my kernel, its value is stored in some variable/CPU registers. Any pointers which can help in doing this job are much appreciated.
EDIT:
My primary goal is to extend the ELF file format into my own custom file format, which I plan to use for a research project on extending the x86 architecture. The executables in that extended architecture need to have a unique identity key used to perform cryptographic operations on its code/data segments. Therefore, a new section in the file could store that key, and the kernel loader can fetch it for further cryptographic processes.

A:
But even when it iterates through the program segments, I don't
  understand how is it iterating through the sections within a segment.

Since load_elf_binary() mmaps all the PT_LOAD segments into memory, and those segments contain all the needed sections (e. g. segment 03 contains sections .ctors .dtors .jcr .dynamic .got .got.plt .data .mysection .bss), there is no need for iterating through the sections.


text:
Q: How do I cancel the event in a setTimeout() after clearing the timeout in Javascript So I'm trying to make a live console for a Discord so that I can see errors while I'm away from my computer. I'm trying to make it so that every time the listener will receive data it will clear the previous timeout and make a new one so that the same thing is not sent x amount of times because the listener was called x amount of times. Now I'm at my problem. I can clear the timeout but not the event inside of it.
child.stdout.on("data", (data) => {
    stdout = stdout + data.toString();

    clearTimeout(timeout);

    timeout = setTimeout(() => {
        message.channel.send([stdout], {
            code: true,
            split: true
        });
    })
});

So this code ends up still sending x amount of times. How would I cancel the event inside to fix this?
Edit: Dumb mistake by me. I accidentally deleted the timeout while cleaning up my code. The code bellow solves everything.
child.stdout.on("data", (data) => {
    stdout = stdout + data.toString();

    clearTimeout(timeout);

    timeout = setTimeout(() => {
        message.channel.send([stdout], {
            code: true,
            split: true
        });
    }, 3000)
});

A: Dumb mistake by me. I accidentally deleted the timeout while cleaning up my code. The code bellow solves everything.
child.stdout.on("data", (data) => {
    stdout = stdout + data.toString();

    clearTimeout(timeout);

    timeout = setTimeout(() => {
        message.channel.send([stdout], {
            code: true,
            split: true
        });
    }, 3000)
});


text:
Q: thread safe vector of functions, each of which can remove access that vector lets say I have a class that contains a vector of functions (eg. std::vector<T(*)(...)>). That class has methods for adding and removing functions from that vectors, as well as invoking them from first to last.
I want this class to be thread safe, so in each of the methods(add, remove and invoke) I use a semaphore(specifically win32 semaphore object) to lock the access to the vector while method finishes working with it. however id like to be able to remove functions from vector in the same thread(only time this would happen is when a function from a vector modifies the vector using add, remove or invoke methods). Is there a way to accomplish this - to lock the vector from being accessed from the other threads, but be able to be accessed from the same thread?


text:
Q: Нахождение нечетных и их количество На промежутке от 0 до 1000 включительно, для каждого нечетного числа выводите в консоль слово Found. Найдите сумму таких чисел. Если их сумма умноженная на 5 больше 5000, выводите в консоль текст Bigger, в другом случае выводите текст Smaller or equal
Основные требования:
Выводить в консоль слово Found нужное количество раз
Не выводить в консоль значение суммы
Выводить верный текст в конце (Bigger или Smaller or equal)
Сделал такой цикл, но он очень плохо работает. Поясните, что к чему пожалуйста.
      for(let i = 0; i<=1000; i++) {
      let sum = 0;
      if(i%2===1) {
         console.log('Found');
         sum+=i;
        if((sum*5)>5000){
         console.log('Bigger');
        }else {
           console.log('Smaller or equal');
       }
      }
     }

A: Думаю ка-то так

let sum = 0;
for(let i = 0; i<=1000; i++) {
  if(i%2 != 0) {
     console.log('Found');
     sum+=i;
  }
}

if((sum*5)>5000){
 console.log('Bigger');
}else {
 console.log('Smaller or equal');
}


text:
Q: Why does adding a new value to list<> overwrite previous values in the list<> I'm essentially trying to add multiple items to a list but at the end all items have the same value equal to last item.
public class Tag
{
    public string TagName { get; set; }
}

List<Tag> tags = new List<Tag>();
Tag _tag = new Tag();
string[] tagList = new[]{"Foo", "Bar"};

foreach (string t in tagList)
{
    _tag.tagName = t; // set all properties
    //Add class to collection, this is where all previously added rows are overwritten
    tags.Add(_tag);
}

The code above produces list of two items with TagName set to "Bar" when I expect one for "Foo" and one with "Bar". Why all items have the same properties in the resulting list?
Bonus point for explanation why changing public class Tag to public struct Tag makes this code work as expected (different items have different values).

If that matter my actual goal is to create derived collection class, but since issue happens with just list it likely optional, still showing what my goal is below.
Following a few tutorials and such I was able to successfully create a collection class which inherits the functionality needed to create a DataTable which can be passed to a Sql Server's stored procedure as a table value parameter. Everything seems to be working well; I can get all of the rows added and it looks beautiful. However, upon closer inspection I notice that when I add a new row, the data for all of the previous rows is overwritten with the value for the new row. So if I have a row with a string value of "foo" and I add a second row with the value "bar", the second row will be inserted (making a DataTable with two rows) but both rows will have the value "bar". Can anyone see why this would be? Here is some of the code, which works but has been a bit simplified (the Tag class has been reduced for ease of explanation).
The following is the Collection class's:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using Microsoft.SqlServer.Server;

namespace TagTableBuilder
{
public class TagCollection : List<Tag>, IEnumerable<SqlDataRecord>
{
    IEnumerator<SqlDataRecord> IEnumerable<SqlDataRecord>.GetEnumerator()
    {
        var sdr = new SqlDataRecord(
            new SqlMetaData("Tag", SqlDbType.NVarChar)
            );

        foreach (Tag t in this)
        {
            sdr.SetSqlString(0, t.tagName);

            yield return sdr;
        }
    }
}

public class Tag
{
    public string tagName { get; set; }
}
}

These are called as follows:
//Create instance of collection
TagCollection tags = new TagCollection();

//Create instance of object
Tag _tag = new Tag();

foreach (string t in tagList)
{
    //Add value to class propety
    _tag.tagName = t;
    //Add class to collection, this is where all previously added rows are overwritten
    tags.Add(_tag);
}

A: You're using the same instance of the Tag object inside the loop, so each update to the TagName is to the same reference. Move the declaration inside the loop to get a fresh object on each pass of the loop:
foreach (string t in tagList)
{
    Tag _tag = new Tag(); // create new instance for every iteration

    _tag.tagName = t;
    tags.Add(_tag);
}

For bonus part - when you change Tag from class to struct copy operation (that happens when you call tags.Add(_tag)) copies whole instance (essentially creating new one) unlike in original class case when only reference to the same single instance is copied into the parameter of the call and then to the list's element (see C# pass by value vs. pass by reference for explanation on how struct passed to method calls).

A: In the loop where you add the tags to the collection, you're using the same object instance of Tag. Essentially, you're setting a Tag's name to the first value in tagList and adding it to the collection, then you're changing that same Tag's name to the second value in tagList and adding it again to the collection.
Your collection of Tags contains several references to the same Tag object! Instantiate _tag inside the for loop each time before setting the Tag's name and adding it to the collection.


text:
Q: Special letters without changing Latex objects names I am preparing a document in English.
In the preamble I have (amongst other things):
\documentclass[11pt, a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

There are two Icelandic words in the document containing the letters ð and Þ (uppercase þ).
So I change the preamble to my usual
\usepackage[icelandic]{babel}
\usepackage[T1]{fontenc}

But that changes the name of all the in-built beauties such as my \tableofcontents.
Is there an easy way around this perhaps by introducing a new language for only one paragraph?

A: The main language in babel is the last specified language:
\usepackage[icelandic, english]{babel}

But I would not use icelandic for just two words. The symbols can be used as macros or direct, depending on the loaded input encoding (package inputenc). Thorn is not available in font encoding OT1, therefore font encoding T1 is used:
\documentclass{article}
\usepackage[english]{babel}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\begin{document}
Two Icelandic words with \dh\ and \TH.
\end{document}

A: The T1 encoding supports the letters:
\documentclass[11pt, a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\begin{document}

We can use Icelandic letters with no
problem: Ð ð Þ þ

\end{document}

Beware that not all fonts support the letters, even in T1 encoding, so  check carefully if you use a different font.


text:
Q: Polynomial in $z$ not bounded on $\mathbb{C}^-$ This is part of a proof that shows that explicit Runge-Kutta-methods are not A-stable. It states the following:
Given we have a polynomial $R(z)\in P_s$ in $z$  of degree at most $s\geq p>0$, then $R(z)$ is not bound on the set
$$
\mathbb{C}^-:= \{z\in \mathbb{C}: Re(z)\leq0 \}
$$
This was stated without a proof or explanation and is the only part in the proof I am struggeling with, so I would appreciate your help.

A: I'm assuming $s>0$, as $0$ order methods don't make sense as explained to me in the comments. Polynomials are entire (holomorphic on the complex plane). So by Liouville's theorem, which states that a bounded entire complex function must be constant, $R(z)$ your polynomial must be unbounded on $\mathbb{C}$. To show it is unbounded on $\mathbb{C}^-$ you can first work with a monic polynomial and note it is unbounded on $\mathbb{C}^-$ by symmetry. To see this, suppose $z^m$ it is unbounded on just the right half plane. Then $(re^{i\theta})^m = r^m (\cos(m\theta)+i\sin(m\theta))$ is unbounded on the right half plane. Then reflecting across the imaginary axis yields $r^m(\cos(m\pi-m\theta)+i\sin(m\pi-m\theta))$ is also unbounded.
Since a polynomial $R$ of degree $s$ is such that $\lim_{|z|\to\infty} \frac{z^{s-1}}{R(z)}=0$ then $R(z)$ is unbounded, since $z^{s-1}$ is unbounded by the previous paragraph.

A: But... $x^s$ is unbounded, isn't it ?


text:
Q: 504 Gateway Time-out for backend on docker swarm overlay network I have a 3 node swarm running on openstack. There are 2 docker services running using the same overlay network. One is the Nexus 3 private repository and the other is a nginx reverse proxy. Only nginx has exposed ports. This setup works fine but intermittently (possibly after many hours of not being accessed) I get a 504.
When I get on the nginx container...
nslookup:
root@7c7f5b09302f:/# nslookup nexus
Server:     127.0.0.11
Address:    127.0.0.11#53

Non-authoritative answer:
Name:   nexus
Address: 10.0.0.6

wget:
root@7c7f5b09302f:/# wget -O- nexus:8081
--2017-05-09 23:23:18--  http://nexus:8081/
Resolving nexus (nexus)... 10.0.0.6
Connecting to nexus (nexus)|10.0.0.6|:8081... failed: Connection timed out.
Retrying.

--2017-05-09 23:25:26--  (try: 2)  http://nexus:8081/
Connecting to nexus (nexus)|10.0.0.6|:8081... ^C
root@7c7f5b09302f:/#

ping:
root@7c7f5b09302f:/# ping nexus
PING nexus (10.0.0.6): 56 data bytes
64 bytes from 10.0.0.6: icmp_seq=0 ttl=64 time=0.077 ms
64 bytes from 10.0.0.6: icmp_seq=1 ttl=64 time=0.098 ms
64 bytes from 10.0.0.6: icmp_seq=2 ttl=64 time=0.054 ms
64 bytes from 10.0.0.6: icmp_seq=3 ttl=64 time=0.071 ms
^C--- nexus ping statistics ---
4 packets transmitted, 4 packets received, 0% packet loss
round-trip min/avg/max/stddev = 0.054/0.075/0.098/0.000 ms
root@7c7f5b09302f:/#

So it can find the nexus container address. I can ping it but cannot connect to port 8081.
On the nexus container itself(on a different node on the swarm) the repository URL is accessible but from anywhere else, I get a 504 error:
bash-4.2$ curl -v http://nexus:8081/
* About to connect() to nexus port 8081 (#0)
*   Trying 10.0.0.6...
* Connected to nexus (10.0.0.6) port 8081 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: nexus:8081
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Tue, 09 May 2017 23:23:03 GMT
< Server: Nexus/3.1.0-04 (OSS)
< X-Frame-Options: SAMEORIGIN
< X-Content-Type-Options: nosniff
< Content-Type: text/html
< Last-Modified: Tue, 09 May 2017 23:23:03 GMT
< Pragma: no-cache
< Cache-Control: post-check=0, pre-check=0
< Expires: 0
< Content-Length: 4659
<

<!DOCTYPE html>

  <title>Nexus Repository Manager</title>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <meta name="description" content="Nexus Repository Manager"/>
  <meta http-equiv="X-UA-Compatible" content="IE=9"/>

  <link rel="icon" type="image/png" href="http://nexus:8081/static/rapture/resources/favicon-32x32.png?_v=3.1.0-04" sizes="32x32">
  <link rel="mask-icon" href="http://nexus:8081/static/rapture/resources/safari-pinned-tab.svg?_v=3.1.0-04" color="#5bbad5">
  <link rel="icon" type="image/png" href="http://nexus:8081/static/rapture/resources/favicon-16x16.png?_v=3.1.0-04" sizes="16x16">
  <link rel="shortcut icon" href="http://nexus:8081/static/rapture/resources/favicon.ico?_v=3.1.0-04">
  <meta name="msapplication-TileImage" content="http://nexus:8081/static/rapture/resources/mstile-144x144.png?_v=3.1.0-04">
  <meta name="msapplication-TileColor" content="#00a300">

            <link rel="stylesheet" type="text/css" href="http://nexus:8081/static/rapture/resources/loading-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nexus:8081/static/rapture/resources/baseapp-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nexus:8081/static/rapture/resources/nexus-rapture-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nexus:8081/static/rapture/resources/nexus-proximanova-plugin-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nexus:8081/static/rapture/resources/nexus-coreui-plugin-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nexus:8081/static/rapture/resources/nexus-proui-plugin-prod.css?_v=3.1.0-04">

      Loading ...

<form id="history-form" class="x-hide-display">
  <input type="hidden" id="x-history-field"/>

</form>

* Connection #0 to host nexus left intact
bash-4.2$

Here, I can ping the nginx container:
bash-4.2$ ping nginx_nexus
PING nginx_nexus (10.0.0.8) 56(84) bytes of data.
64 bytes from 10.0.0.8 (10.0.0.8): icmp_seq=1 ttl=64 time=0.089 ms
64 bytes from 10.0.0.8 (10.0.0.8): icmp_seq=2 ttl=64 time=0.066 ms
64 bytes from 10.0.0.8 (10.0.0.8): icmp_seq=3 ttl=64 time=0.047 ms
64 bytes from 10.0.0.8 (10.0.0.8): icmp_seq=4 ttl=64 time=0.076 ms
^C
--- nginx_nexus ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 2999ms
rtt min/avg/max/mdev = 0.047/0.069/0.089/0.017 ms
bash-4.2$

Note: Till now, when I try to access nexus through nginx reverse proxy from any external point I get a "504 Gateway Time-out". However, the moment I run the following command on the nexus container, the error vanishes.
bash-4.2$ curl -v nginx_nexus
* About to connect() to nginx_nexus port 80 (#0)
*   Trying 10.0.0.8...
* Connected to nginx_nexus (10.0.0.8) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: nginx_nexus
> Accept: */*
>
< HTTP/1.1 200 OK
< Server: nginx/1.13.0
< Date: Tue, 09 May 2017 23:33:44 GMT
< Content-Type: text/html
< Content-Length: 4681
< Connection: keep-alive
< Keep-Alive: timeout=5
< X-Frame-Options: SAMEORIGIN
< X-Content-Type-Options: nosniff
< Last-Modified: Tue, 09 May 2017 23:33:44 GMT
< Pragma: no-cache
< Cache-Control: post-check=0, pre-check=0
< Expires: 0
<

<!DOCTYPE html>

  <title>Nexus Repository Manager</title>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <meta name="description" content="Nexus Repository Manager"/>
  <meta http-equiv="X-UA-Compatible" content="IE=9"/>

  <link rel="icon" type="image/png" href="http://nginx_nexus/static/rapture/resources/favicon-32x32.png?_v=3.1.0-04" sizes="32x32">
  <link rel="mask-icon" href="http://nginx_nexus/static/rapture/resources/safari-pinned-tab.svg?_v=3.1.0-04" color="#5bbad5">
  <link rel="icon" type="image/png" href="http://nginx_nexus/static/rapture/resources/favicon-16x16.png?_v=3.1.0-04" sizes="16x16">
  <link rel="shortcut icon" href="http://nginx_nexus/static/rapture/resources/favicon.ico?_v=3.1.0-04">
  <meta name="msapplication-TileImage" content="http://nginx_nexus/static/rapture/resources/mstile-144x144.png?_v=3.1.0-04">
  <meta name="msapplication-TileColor" content="#00a300">

            <link rel="stylesheet" type="text/css" href="http://nginx_nexus/static/rapture/resources/loading-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nginx_nexus/static/rapture/resources/baseapp-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nginx_nexus/static/rapture/resources/nexus-rapture-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nginx_nexus/static/rapture/resources/nexus-proximanova-plugin-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nginx_nexus/static/rapture/resources/nexus-coreui-plugin-prod.css?_v=3.1.0-04">
            <link rel="stylesheet" type="text/css" href="http://nginx_nexus/static/rapture/resources/nexus-proui-plugin-prod.css?_v=3.1.0-04">

      Loading ...

<form id="history-form" class="x-hide-display">
  <input type="hidden" id="x-history-field"/>

</form>

* Connection #0 to host nginx_nexus left intact
bash-4.2$

This keeps happening intermittently. After few hours when the repository is not in use, I will find the "504 Gateway Time-out" again and have to login to the swarm node and nexus container and run curl again to resolve it. Please help me figure out a solution to the 504 error. This issue does not exist if the containers are running on same host and no overlay network is used.

A: The problem disappeared with openstack upgrade. I no longer have the version details or the setup available to me so I cannot provide more information about that.


text:
Q: How to add a button an ipad app to go to home screen without using the home button I am working on this app for iPad. This app disables the home button inorder to force users to use the open app only but not go to other apps or safari. I am trying to add a button on the app which minimizes the app only if the user is a manager. When the application loads, it checks if the user is a manager or not. If the user is a manager, the app will have additional button which says "minimize". So far, I have completed the part which checks if the user is a manager and loads the app with that additional button. My problem came when I try to write the code behind the minimize button.
Is there any efficient and known way (library or method) that I can use to do this task without using the home button?

A: There are two ways of doing this, depending on how you want to app to close.

*

*If you want the app to go into the background, and be in the suspended state, use:
UIApplication *app = [UIApplication sharedApplication];
[app performSelector:@selector(suspend)];

*If you want to completely kill the app (as in it will not be running in the background), use:
exit(0);

Note killing the app has a "rough" looking effect.  So you may want to combine the two approaches into the following smoother transition:
UIApplication *app = [UIApplication sharedApplication];
[app performSelector:@selector(suspend)];  //Put the app into the background

[NSThread sleepForTimeInterval:2.0];   //Pause while the app goes to background

exit(0);  //Actually kill the app


text:
Q: Determining the camera direction of a geotagged image Is there an easy way to determine the camera direction of a geotagged image?
Maybe there are several methods for this.

A: It depends on the camera that captured the image: The camera has to have a sensor capable of capturing the direction, and it has to record that data when it captures a photo. Whether the image is geotagged is not relevant.
When a digital camera captures an image, it stores metadata about the image in the EXIF tags (text data embedded in the image file). There are EXIF tags which store the latitude and longitude of an image (Exif.GPSInfo.GPSLatitude and Exif.GPSInfo.GPSLongitude). The term 'geotag' refers to the data in those EXIF tags. There is also a tag which stores the direction the camera was pointing, Exif.GPSInfo.GPSImgDirection.
However, not all cameras save all the EXIF data about an image. Sometimes that's because the camera manufacturer just doesn't care enough (or think their customers care enough) to  record all the metadata. It can also be because the camera doesn't have the sensors necessary to actually capture a given piece of metadata, for example an older budget digital camera with no location sensor would not save the Lat/Long info.
So, you will want to look at the images' EXIF data and see if the Direction tag is populated. If it's not, then there's no easy way to determine the images' direction. Depending on how important it is, you can of course use the geotag info to locate the photo in the real world, then manually cross-reference other imagery to figure out the direction the camera was pointing. But that's definitely not easy if you have lots of images.

A: If this information is stored in the image's metadata (e.g. EXIF data), you could display the information e.g. using https://www.gimp.org/.
Just open the image with GIMP and choose from the menu bar: Image → Metadata
Depending on the OS and the standard image viewer you are using, you could try if this standard viewer is also able to display the image's metadata (e.g. right click and show image information or something like this...)


text:
Q: Regex word with all letters I'm trying to write some regex to match word which is writen with any characters and highlights them using preg_replace
Example :
Search "cera" in "my sentence which contain cera, or Céra CErA or even cERa"

Return expected :
my sentence which contain cera, or Céra and CErA or even cERa"

Here is my regex but it doesn't work any ideas ?!
$string = preg_replace('\bcera\b\p{L}', '$1', $text);

A: This function while return the regex search for looking for the value.
$text and $search set for demo
function txt_replace($search) {
    mb_regex_encoding('UTF-8');
    $match=Array("aáàâäåãAÁÀÂÄÅÃ","cçCÇ","eéèêëEÉÈÊË","iíìîïIÍÌÎÏ","nñNÑ","oóòôöõOÓÒÔÖÕ","uúùûüUÚÙÛÜ","yÿýYÝ","æÆ", "ɶŒœ");
    foreach($match as $key => $value) {
            $search=mb_ereg_replace("([$value])", "[$value]*", $search);
    }
    return "({$search})";
}

$text="sàlut bonjour new york salut";
$search="sàlut";
$string=preg_replace('/'.txt_replace($search).'/i','$1', $text);
echo $string;

A: Try $string = preg_replace('/(c[e|é|è]ra)/i{L}', '$1', $text);
I deleted \b i don't saw why that used.


text:
Q: How can we import Flutter App to Unity 3d I want to make a cross-platform app that uses 3d models and animation from unity but making good layout and widgets is very difficult in unity. So, can I make designs in Flutter and import that to unity?
It seems vice-versa is not possible as OpenGL bindings are not currently supported by flutter.

A: Yes you make designs in Flutter and import that to Unity3D. What you want is called embedding flutter in native app (Unity3D). To embed flutter check this article.
So, basically you will have to create a flutter application, convert it into a library, import that library in Unity3D project and call your activity.
To launch your own activity from Unity3D, check this question


text:
Q: How to create Unique Identifier and save it to identify user(device) I want to create unique identifier on iOS 5 and use it for identifying user (user device) every time app is started. I am able to create a unique identifier by following code
 CFUUIDRef theUUID = CFUUIDCreate(NULL);
 CFStringRef string = CFUUIDCreateString(NULL, theUUID);
 CFRelease(theUUID);

But unable to save it on user device so that particular identifier is not deleted even when app is uninstalled. I tried using SSKeychain approach but it gives Apple Mach-o Linker error.
Please let me know the the way I can accomplish the same.
Any help is appreciated.

A: I had exactly the same problem after adding SSKeyChain to my project following the author's instructions online. I eventually discovered that the implementation file was not included in my list of source files in build phases. To rectify the issue do the following:
1) Select your project, then its target.
2) Then select the Build Phases tab
3) On the Build Phases tab you will see a group called Compile Sources, expand it to view contents
4) Check to see if SSKeyChain is in the list
5) If not (as in my case) click the little plus sign at the bottom of the group and navigate to where you added SSKeyChain.m and add it.
Build your project and the error should have disappeared...
I hope this helps!


text:
Q: JAXB XML Unmarshaller error. Getting null value for all Object I get the following error when I tried to parse the below string
<?xml version="1.0" encoding="UTF-8"?>
<CC5Response>
  <OrderId>ORDER-17305KXSH11966</OrderId>
  <GroupId>ORDER-173053333KXSH11966</GroupId>
  <Response>Approved</Response>
  <AuthCode>0293333584</AuthCode>
  <HostRefNum>73051033333011833</HostRefNum>
  <ProcReturnCode>00</ProcReturnCode>
  <TransId>17305K33245XSH11968</TransId>
  <ErrMsg></ErrMsg>
  <Extra>
    <SETTLEID>1</SETTLEID>
    <TRXDATE>20171101 10:23:18</TRXDATE>
    <ERRORCODE></ERRORCODE>
    <CARDBRAND>VISA</CARDBRAND>
    <CARDISSUER>CDM</CARDISSUER>
    <NUMCODE>00</NUMCODE>
  </Extra>
</CC5Response>

Code snippet for Unmarshalling is given below
JAXBContext jaxbContext = JAXBContext.newInstance(CC5Response.class);
XMLInputFactory xif = XMLInputFactory.newFactory();
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
XMLStreamReader xsr = xif.createXMLStreamReader(IOUtils.toInputStream(sb.toString(), "UTF-8"));
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
CC5Response res = (CC5Response) jaxbUnmarshaller.unmarshal(xsr);
System.out.println("*************"+res.toString());

bean class is given below
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType
@XmlRootElement(name = "CC5Response")
public class CC5Response {
    @XmlAttribute
    private String ProcReturnCode;
    // @XmlAttribute
    // private Extra Extra;
    /*public Extra getExtra() {
        return Extra;
    }

    public void setExtra(Extra extra) {
        Extra = extra;
    }*/

    @XmlAttribute
    private String AuthCode;
    @XmlAttribute
    private String OrderId;
    @XmlAttribute
    private String TransId;
    @XmlAttribute
    private String ErrMsg;
    @XmlAttribute
    private String Response;
    @XmlAttribute
    private String HostRefNum;
    @XmlAttribute
    private String GroupId;

I always get a plain object with null values.

A: To enable JAXB unmarshaller to work fine, you should simulate your XML into right structure of JAVA classes ...  Follow the following steps and it will work with you.

*

*Your XML should be like :
<?xml version="1.0" encoding="UTF-8"?>
  <CC5Response>
     <OrderId>ORDER-17305KXSH11966</OrderId>
     <GroupId>ORDER-173053333KXSH11966</GroupId>
     <Response>Approved</Response>
     <AuthCode>0293333584</AuthCode>
     <HostRefNum>73051033333011833</HostRefNum>
     <ProcReturnCode>00</ProcReturnCode>
     <TransId>17305K33245XSH11968</TransId>
     <ErrMsg>error message</ErrMsg>
     <Extra>
         <SETTLEID>1</SETTLEID>
         <TRXDATE>20171101 10:23:18</TRXDATE>
         <ERRORCODE>0000</ERRORCODE>
         <CARDBRAND>VISA</CARDBRAND>
         <CARDISSUER>CDM</CARDISSUER>
         <NUMCODE>00</NUMCODE>
    </Extra>
  </CC5Response>

*We will create 2 necessary classes in Java :
2.1 create class named "CC5Response.java" like :
@XmlRootElement(name = "CC5Response")
public class CC5Response {

    private String ProcReturnCode;
    private String AuthCode;
    private String OrderId;
    private String TransId;
    private String ErrMsg;
    private String Response;
    private String HostRefNum;
    private String GroupId;
    private List<Extra> Extra;

    /**
     * @return the ProcReturnCode
    */
   @XmlElement(name="ProcReturnCode")
   public String getProcReturnCode() {
          return ProcReturnCode;
   }

  /**
   * @param ProcReturnCode the ProcReturnCode to set
  */

  public void setProcReturnCode(String ProcReturnCode) {
        this.ProcReturnCode = ProcReturnCode;
  }

   /**
   * @return the AuthCode
   */
   @XmlElement(name="AuthCode")
   public String getAuthCode() {
          return AuthCode;
   }

   /**
   * @param AuthCode the AuthCode to set
   */
  public void setAuthCode(String AuthCode) {
        this.AuthCode = AuthCode;
   }

  /**
  * @return the OrderId
  */
   @XmlElement(name="OrderId")
   public String getOrderId() {
       return OrderId;
  }

   /**
   * @param OrderId the OrderId to set
   */
   public void setOrderId(String OrderId) {
         this.OrderId = OrderId;
   }

   /**
    * @return the TransId
   */
  @XmlElement(name="TransId")
  public String getTransId() {
       return TransId;
  }

  /**
   * @param TransId the TransId to set
  */
  public void setTransId(String TransId) {
        this.TransId = TransId;
  }

  /**
   * @return the ErrMsg
  */
  @XmlElement(name="ErrMsg")
  public String getErrMsg() {
       return ErrMsg;
  }

  /**
   * @param ErrMsg the ErrMsg to set
  */
  public void setErrMsg(String ErrMsg) {
         this.ErrMsg = ErrMsg;
  }

  /**
   * @return the Response
  */
   @XmlElement(name="Response")
   public String getResponse() {
       return Response;
   }

  /**
    * @param Response the Response to set
   */
   public void setResponse(String Response) {
       this.Response = Response;
   }

  /**
   * @return the HostRefNum
  */
 @XmlElement(name="HostRefNum")
 public String getHostRefNum() {
      return HostRefNum;
 }

 /**
  * @param HostRefNum the HostRefNum to set
 */
  public void setHostRefNum(String HostRefNum) {
        this.HostRefNum = HostRefNum;
  }

   /**
     * @return the GroupId
   */
   @XmlElement(name="GroupId")
   public String getGroupId() {
        return GroupId;
   }

  /**
   * @param GroupId the GroupId to set
   */
   public void setGroupId(String GroupId) {
        this.GroupId = GroupId;
   }

   /**
    * @return the Extra
    */
   @XmlElement(name="Extra")
   public List<Extra> getExtra() {
        return Extra;
   }

    /**
    * @param Extra the Extra to set
    */
    public void setExtra(List<Extra> Extra) {
              this.Extra = Extra;
   }
  }

2.2 create class named "Extra.java" like :
 public class Extra {

    private String SETTLEID;
    private String TRXDATE;
    private String ERRORCODE;
    private String CARDBRAND;
    private String CARDISSUER;
    private String NUMCODE;

    /**
     * @return the SETTLEID
     */
    public String getSETTLEID() {
        return SETTLEID;
    }

    /**
     * @param SETTLEID the SETTLEID to set
     */
    public void setSETTLEID(String SETTLEID) {
        this.SETTLEID = SETTLEID;
    }

    /**
     * @return the TRXDATE
     */
    public String getTRXDATE() {
        return TRXDATE;
    }

    /**
     * @param TRXDATE the TRXDATE to set
     */
    public void setTRXDATE(String TRXDATE) {
        this.TRXDATE = TRXDATE;
    }

    /**
     * @return the ERRORCODE
     */
    public String getERRORCODE() {
        return ERRORCODE;
    }

    /**
     * @param ERRORCODE the ERRORCODE to set
     */
    public void setERRORCODE(String ERRORCODE) {
        this.ERRORCODE = ERRORCODE;
    }

    /**
     * @return the CARDBRAND
     */
    public String getCARDBRAND() {
        return CARDBRAND;
    }

    /**
     * @param CARDBRAND the CARDBRAND to set
     */
    public void setCARDBRAND(String CARDBRAND) {
        this.CARDBRAND = CARDBRAND;
    }

    /**
     * @return the CARDISSUER
     */
    public String getCARDISSUER() {
        return CARDISSUER;
    }

    /**
     * @param CARDISSUER the CARDISSUER to set
     */
    public void setCARDISSUER(String CARDISSUER) {
        this.CARDISSUER = CARDISSUER;
    }

    /**
     * @return the NUMCODE
     */
    public String getNUMCODE() {
        return NUMCODE;
    }

    /**
     * @param NUMCODE the NUMCODE to set
     */
    public void setNUMCODE(String NUMCODE) {
        this.NUMCODE = NUMCODE;
    }

}

*Main Method should be like :
  /**
     * @param args the command line arguments
     * @throws javax.xml.bind.JAXBException
     */
    public static void main(String[] args) throws JAXBException {
        // TODO code application logic here
        try {

            File file = new File("file.xml");

            if (file.exists()) {
                JAXBContext jaxbContext = JAXBContext.newInstance(CC5Response.class);

                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                CC5Response response = (CC5Response) jaxbUnmarshaller.unmarshal(file);

                if (response != null) {
                    System.out.println("*************" + response.getAuthCode());
                    System.out.println("*************" + response.getErrMsg());
                    System.out.println("*************" + response.getGroupId());
                    System.out.println("*************" + response.getOrderId());
                    System.out.println("*************" + response.getResponse());
                    //you can get any field from Exta class
                    System.out.println("*************" + response.getExtra());
                }
            }
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }


text:
Q: Parsing a stream of data for control strings I feel like this is a pretty common problem but I wasn't really sure what to search for.
I have a large file (so I don't want to load it all into memory) that I need to parse control strings out of and then stream that data to another computer. I'm currently reading in the file in 1000 byte chunks.
So for example if I have a string that contains ASCII codes escaped with ('$' some number of digits ';') and the data looked like this... "quick $33;brown $126;fox $a $12a". The string going to the other computer would be "quick brown! ~fox $a $12a".
In my current approach I have the following problems:

*

*What happens when the control strings falls on a buffer boundary?

*If the string is '$' followed by anything but digits and a ';' I want to ignore it. So I need to read ahead until the full control string is found.

I'm writing this in straight C so I don't have streams to help me.
Would an alternating double buffer approach work and if so how does one manage the current locations etc.

A: If I've followed what you are asking about it is called lexical analysis or tokenization or regular expressions.  For regular languages you can construct a finite state machine which will recognize your input.  In practice you can use a tool that understands regular expressions to recognize and perform different actions for the input.
Depending on different requirements you might go about this differently.  For more complicated languages you might want to use a tool like lex to help you generate an input processor, but for this, as I understand it, you can use a much more simple approach, after we fix your buffer problem.
You should use a circular buffer for your input, so that indexing off the end wraps around to the front again.  Whenever half of the data that the buffer can hold has been processed you should do another read to refill that.  Your buffer size should be at least twice as large as the largest "word" you need to recognize.  The indexing into this buffer will use the modulus (remainder) operator % to perform the wrapping (if you choose a buffer size that is a power of 2, such as 4096, then you can use bitwise & instead).
Now you just look at the characters until you read a $, output what you've looked at up until that point, and then knowing that you are in a different state because you saw a $ you look at more characters until you see another character that ends the current state (the ;) and perform some other action on the data that you had read in.  How to handle the case where the $ is seen without a well formatted number followed by an ; wasn't entirely clear in your question -- what to do if there are a million numbers before you see ;, for instance.
The regular expressions would be:
 [^$]

Any non-dollar sign character.  This could be augmented with a closure ([^$]* or [^$]+) to recognize a string of non$ characters at a time, but that could get very long.
$[0-9]{1,3};

This would recognize a dollar sign followed by up 1 to 3 digits followed by a semicolon.
[$]

This would recognize just a dollar sign.  It is in the brackets because $ is special in many regular expression representations when it is at the end of a symbol (which it is in this case) and means "match only if at the end of line".
Anyway, in this case it would recognize a dollar sign in the case where it is not recognized by the other, longer, pattern that recognizes dollar signs.
In lex you might have
[^$]{1,1024}          { write_string(yytext); }
$[0-9]{1,3};          { write_char(atoi(yytext)); }
[$]                   { write_char(*yytext); }

and it would generate a .c file that will function as a filter similar to what you are asking for.  You will need to read up a little more on how to use lex though.

A: The "f" family of functions in <stdio.h> can take care of the streaming for you.  Specifically, you're looking for fopen(), fgets(), fread(), etc.
Nategoose's answer about using lex (and I'll add yacc, depending on the complexity of your input) is also worth considering.  They generate lexers and parsers that work, and after you've used them you'll never write one by hand again.


text:
Q: Crash: mutating method sent to immutable object I am attempting to delete an object for a particular key in an NSMutableDictionary but the application crashes when trying to do so. Here is my code:
    NSArray *allWebDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
    self.results = [[NSMutableArray alloc] initWithArray:allWebDictionary];

    for (NSMutableDictionary *dic2 in self.results) {
        NSMutableArray *incidents = [dic2 valueForKey:@"incidents"];
        for (NSMutableDictionary *incident in incidents) {
            [incident removeObjectForKey:@"type"];
        }
    }

My app crashes with the following log:

* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary removeObjectForKey:]: mutating method sent to immutable object'

Any ideas? Thanks in advance!

A: You made a mutable copy of the array, but the dictionary which is in the array is still immutable.
You need mutable containers.
Replace
NSArray *allWebDictionary = [NSJSONSerialization JSONObjectWithData:webData
                                                            options:0
                                                              error:nil];

with
NSMutableArray *allWebDictionary = [NSJSONSerialization JSONObjectWithData:webData
                                                                   options:NSJSONReadingMutableContainers
                                                                     error:nil];


text:
Q: Why cannot move DOM nodes in Chrome anymore? I am not able to move the DOM nodes in the Google Chrome, in the Inspect Element tab, when I select them and try to grab/drag them nothing happens anymore.
I have reset the settings on both the browser and the dev tool, but there is no change.
In case you wonder what I am referring to, please click on this link: Move DOM node.
Chrome version: 73.0.3664.3 (Official Build) dev (64-bit)
Any help is appreciated, thank you.

A: I'm able to move DOM Nodes in the elements tab of the inspector by clicking and holding - I'm on Version 84.0.4147.89 (Official Build) (64-bit) FWIW.


text:
Q: returning address of local variable
Possible Duplicate:
Can a local variable's memory be accessed outside its scope?

I'm trying to understand why I get this output for the below program
[hello] [0xbfde68f4]
[world] [0xbfde68f4]
[world] [0xbfde68f4]

The program is
int main(void)
{
    char **ptr1 = NULL;
    char **ptr2 = NULL;

    ptr1 = func1();
    ptr2 = func2();
    printf(" [%s] [%p]\n",*ptr1, (void*)ptr1);

    printf(" [%s] [%p]\n",*ptr2, (void*)ptr2);

    printf(" [%s] [%p]\n",*ptr1, (void*)ptr1);

    return 0;
}

char** func1()
{
    char *p = "hello";
    return &p;
}

char** func2()
{
    char *p = "world";
    return &p;
}

I understand that it's not a good practice to return address of local variables but this is just an experiment.

A: The memory address is re-used. First it holds the address of the constant holding "hello", then it is re-used to hold the address of the constant holding "world".
Once memory is no longer in use, it is available for re-use. It's generally most efficient to re-use the most recently used memory, so that's what compilers and memory managers typically try to do.
Note that it's definitely not guaranteed. You may find that this program crashes or gives different addresses on different compilers or platforms. However, re-use is very, very likely in this particular scenario, since both variables are local and assigned on the stack and no intervening code uses any stack space. If you add an intervening use of stack space, you will get different behavior.

A: Local variables live on the stack. When you called func1(), the local variable was created, then destroyed as it went out of scope. func2() used the same space for its local variable, since func1() wasn't using it anymore.

A: ptr1 = func1(); use the memory block as below.
prt1
 ↓
[h][e][l][l][o][\0]
 ↑
0xbfde68f4

ptr2 = func2(); use the same memory block because after exiting func1, this memory block can be reused.
     prt2
      ↓
prt1→[w][o][r][l][d][\0]
      ↑
    0xbfde68f4


text:
Q: Laravel dusk not working .env.dusk.local I have an application and I want to use Laravel Dusk.
I created a file named .env.dusk.local with a database for tests and a file named .env with my default database.
I ran the php artisan command and created a user by /register.
After I created a login test with the same email but with a different password, this would not be a problem because in .env.dusk.local it would be a different bank and would not have any users registered.
But when I run the php artisan dusk command it takes the information from the original .env and ends up erasing all records from my default database.
I would like to know how to load the information from my .env.dusk.local and use my test database.
.env default
APP_ENV=local
APP_KEY=base64:K8otIkxJk0rFsZYSEq1hwBuaxQX3QI3Bb7ZmemJRIWg=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost:8000

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_dusk
DB_USERNAME=root
DB_PASSWORD=123456

.env.dusk.local
APP_ENV=local
APP_KEY=base64:K8otIkxJk0rFsZYSEq1hwBuaxQX3QI3Bb7ZmemJRIWg=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost:8000

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_dusk_test
DB_USERNAME=root
DB_PASSWORD=123456

Mu function for testLogin
namespace Tests\Browser;

use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Support\Facades\App;
use Tests\DuskTestCase;

class LoginTest extends DuskTestCase
{

    use DatabaseMigrations;
    /**
     * A Dusk test example.
     *
     * @return void
     */
    public function testLogin()
    {
        $user = factory(\App\User::class)->create(['email' => 'lucas@example.com']);

        $this->browse(function ($browser) use ($user) {
            $browser->visit('/login')
                    ->type('email', $user->email)
                    ->type('password', 'secret')
                    ->press('Login')
                    ->assertPathIs('/home');
        });
    }
}

Here is this project in github

A: Instead of .env.dusk.local try .env.dusk
Also instead of using your mysql database I would recommend using a temporary sqlite db since it gets created and destroyed during tests.
you will have to have a sqilte config in your database.php that points at an actual .sqlite file that you have in your installation
so copy the sqlite config in database.php and then paste it, name it sqlite_dusk maybe, then for the location of the db put it as storage_path('dusk.sqlite') or something like that. Then create a blank dusk.sqlite file in the root of your storage folder.
Then in your .env.dusk set:
DB_CONNECTION=sqlite_dusk

Hope that helps!


text:
Q: Flink managed state as transient Why is it important to mark flink state as transient.
Example below uses ValueState and is marked as transient.
https://nightlies.apache.org/flink/flink-docs-master/docs/dev/datastream/fault-tolerance/state/#using-keyed-state

A: The RichFunction is serialized by the Flink client and sent to the Flink cluster, where each task manager will deserialize a copy of it. It doesn't make sense for the ValueState object to be included -- instead we want each task manager to have its own ValueState object that gets initialized in the open method.


text:
Q: How to get and compare current scene name I tried to compare scene name but I am getting the error below:

error CS0019: Operator ==' cannot be applied to operands of type
  method group' and `string'

I can't figure out how to fix this error. please help me! the error is located on the arrow
void CheckCurrentLevel()
{
    for(int i = 1; i < LevelAmount; i++)
    {
    --->    if (SceneManager.LoadScene == "Level" + i) {
            CurrentLevel = i;
            SaveMyGame ();
        }
    }
}

A: SceneManager.LoadScene is a void function used to load a scene. It does not return anything so you can't compare it with a string.
It looks like you want to compare the current scene name with "Level" + i. If that's true then you are looking for SceneManager.GetActiveScene().name
void CheckCurrentLevel()
{
    for (int i = 1; i < LevelAmount; i++)
    {
        if (SceneManager.GetActiveScene().name == "Level" + i)
        {
            CurrentLevel = i;
            SaveMyGame();
        }
    }
}

A: Keep in mind that the == operator Checks if the values of two operands are equal or not, subject to the condition that both the operands should be same type. From the error message it is clear that LoadScene is defined as a method.
Your code will works fine if you use like this:
if (SceneManager.LoadScene(params if any) == "Level" + i)
{
    // Code here
}

Subject to the condition that LoadScene() method should return a string object or else the return type will be a business object in this case use a string property for comparison


text:
Q: Problem with high current draw in circuit design I am working on a project where I've taken an LDC1612evm (inductance to digital converter) and removed the connected micro controller portion to communicate with a TM4C123G LaunchPad via I2C. I have been able to get the circuit working correctly when connecting the launchpad to my computer through micro usb, the circuit looking like the picture below (the pull-up resistors are for the I2C communication)
I connected an ammeter to the LDC input to determine the current draw of the chip, which being 5mA was within the operating limits found in the datasheet. For the end product, this circuit is going to have a 12V source passed through a MC7805CT 5V regulator to control this particular section. I have attempted to simulate this as is shown in the below diagram

Here is where the problem occurs. When I read the ammeter I see a current of 500mA flowing into the LDC which, not surprisingly, instantly damages it.
So my question is what is causing the huge current draw?
I have checked the LDC input voltages and in both cases I get the expected 3.3V. It has been suggested that the micro controller section of the ldc1612evm has a regulator on it thus by removing that portion the regulator is bypassed allowing for the higher current draw, but from what I can tell from the launchpad's datasheet power schematic the 3.3V output contains a similar regulator, so I don't understand why that would be the problem.
Thank you in advance for any insights into the cause.
EDIT: changed out the wiring diagrams for schematics

A: Looks like LCD1612 3.3 volts is an output from a linear regulator derived from the USB and Launchpad 3.3 volts is also an output from a linear regulator.  You have two voltage outputs tied together.  You don't need to connect these.


text:
Q: Change top padding of nine-patch image after stretching I have TextView with nine-patch background image:

The vertical padding is set to fit text into bottom grey rectangle like this:

But when the image is stretched vertically, it's top padding saves its absolute value, so text goes above of expected place:

How to make TextView increase top padding after vertical stretch and fit text into bottom area which is not stretchable?


text:
Q: org.jdom2.xpath doesn't return results on queries from html head element I am using org.jdom2.xpath to evaluate XPath queries on html documents.
Attempting to retreive a script text from the head element, I tried this query:
/html/head/script[contains(text(), 'expression1') and contains(text(), 'expression2')]/text()

This query returns a single result in both XPath Helper and Chrome console ($x queries) but retuns an empty result set using org.jdom2.xpath.
Trying the simpler (but heavier) query:
//script[contains(text(), 'expression1') and contains(text(), 'expression2')]/text()

produces the same results.
Code sample:
String xpath = "/html/head/script[contains(text(), 'expression1') and contains(text(), 'expression2')]/text()";
List<Text> tokeScriptResults = (List<Text>) xpathFactory.compile(xpath).evaluate(document);

Afterthought: looking at the Document object, I see that since the script text is very long that jdom2 split it into an array of Texts instead of one long Text. Could this be the issue?

A: Short answer - use . instead of text(), i.e. contains(., 'expression1')
Longer answer - text() is a path step that selects the set of all text nodes that are immediate children of the context node. The contains function expects it's arguments to be strings, not node sets, and the rule to convert a node set to a string in XPath 1.0 is to take the string value of the first node in the set in document order and ignore the other nodes completely. Therefore the test contains(text(), 'expression1') only looks in the first text node child.
If instead you do contains(., 'expression1') then the first argument is a set containing a single node (the script element), and the string value of an element node is the concatenation of all its descendant text nodes in document order. So this will look in all the text under the script tag, not just the first text node child.
In general you should very rarely need to use text() in XPath. It is only required when you absolutely must handle each separate text node individually. In predicates I find testing the string value of an element node almost always captures the intention better.


text:
Q: ADODB doesn't raise SQL errors in VBA I've noticed that when a query is run in VBA, VBA doesn't always inform errors raised by it. For example if I try to do a bulk insert with a null value in a row that doesn't accept nulls I get this error in SQL Server:
Msg 4869, Level 16, State 1, Line 1
The bulk load failed. Unexpected NULL value in data file row 2, column 7. The destination column (IFSFxRate) is defined as NOT NULL.

However it doesn't raise any errors when I execute it with ADODB, though I noticed that if I do rs.NextRecordset I get an debug window with the error message.
Public Sub ExecuteQuery(sql As String)    Dim Error As ADODB.Error
    Dim Error As ADODB.Error
    Dim rs As ADODB.recordset
    Dim Conn As New ADODB.Connection
    Conn.CommandTimeout = 0
    Call Conn.Open(ConfigFactory.DB_CONNECTION)
    Set rs = Conn.Execute(sql) ' "raiserror ('xyz', 10, 127)"
    Debug.Print Conn.Errors.Count ' Returns 0
    rs.NextRecordset ' The bulk load failed. Unexpected NULL value in data file row 2
    Connection.Close
    Set Connection = Nothing
End Sub

Why is the error not raised on .Execute? Is there something I can do to get the log in these cases?

A: SQL Server with ADO will generate a recordset for every "result set" which is returned.
That is, for every statement in the batch which either produces a "rows affected" output or an output rowset. You must use Set rs = rs.NextRecordSet to page through the results.
Each error is attached to an individual statement, so they will may not be processed on the client, (and added to the Connection object) until you reach that resultset of that statement.
Generally you won't be interested in empty resultsets, so you will see your code sprinkled with this:
While rs.EOF Do
  Debug.Print "Empty Recordset with " & rs.RecordCount & " rows affected"
  Set rs = rs.NextRecordset
Next

If you are interested, you can get the "rows affected" information by consulting the RecordCount property as above.
Alternatively, you can suppress the empty recordsets by using SET NOCOUNT ON in your SQL statement (or stored procedure).


text:
Q: gtk 3.0 use the same callback for several switches I'm creating a Linux GUI using GTK3.0 and C and I want to use the same callback for several switches. In order to differentiate the switch that was clicked, I am trying to use the gpointer argument in g_signal_connect, but the callback doesn't seem to receive the right value.
I create the signals this way:
g_signal_connect(led1_switch, "state-set", G_CALLBACK(on_gpio_btn_click), (gpointer)"LED1");
g_signal_connect(led2_switch, "state-set", G_CALLBACK(on_gpio_btn_click), (gpointer)"LED2");

And the callback tries to get the gpointer passed:
    static void on_gpio_btn_click(GtkWidget *wid, gpointer ptr)
    {
        int gpio;
        int val = 0;
        char *gpio_switch = ptr;
...

But when I debug the application, the ptr pointer has the value 0x1, a wrong memory address.

Shouldn't it point to the memory address where the constant string "LED1" is stored?
what am I doing wrong? How can I share the same callback for several widgets? I have 8 switches to control GPIOs and I would prefer to have one callback for all of them instead of creating eight.

A: Your function signature is wrong: the 2nd argument is the value of the switch's state, as can be found in the documentation of the "state-set" signal. That's also the reason why the value is 1: that's the actual value of TRUE.
In other words, your callback will like this:
    static void on_gpio_btn_click(GtkSwitch *swtch, gboolean state, gpointer ptr)
    {
        int gpio;
        int val = 0;
        char *gpio_switch = ptr;
        // ...
    }


text:
Q: How to properly use standalone TransactionManager in web application? I'd like to write my next tiny Java webapp by using one of micro-frameworks. E.g. Spark or Jooby. The problem is that both of them doesn't support JTA, so I need to use one of third-party libraries. I've googled for open-source JTA implementations and found two: Atomikos and Bitronix. It seems that the latter project is slightly abandoned so I've decided to go with Atomikos. Unfortunately documentation is scarce so I can't find answers to my questions.
Here is the use case. Suppose we have two DAO classes which methods should be executed under single transaction:
class SomeService {

    // both injected by Guice
    private FooDao fooDao;
    private BarDao barDao;

    public void someMethod() {
        // both methods should be executed in a single transaction
        fooDao.insert(new Foo());
        barDao.insert(new Bar());
    }
}

I've never used javax.transaction API directly/manually before (you know declarative transactions are very simple with Spring) so I'm a bit confused. JTA provides two general abstractions(UserTransaction and TransactionManager) and they both have methods to handle JDBC transaction. As far as I understand TransactionManager operates UserTransaction objects by using ThreadLocal variables. Therefore UserTransaction should be thread-confined and TransactionManager supposed to be thread-safe. Am I correct?
So there are several approaches possible:

*

*I can inject TransactionManager into my service (via Guice) and use it directly.

*I can share TransactionManager via public static variable.

*I can create an UserTransaction provider/factory (via Guice) and get objects from it.

Which is correct/best-practice?
Another question if someone familiar with Atomikos is that it provides two transaction manager implementations (maybe even more): J2eeTransactionManager and UserTransactionManager. Again documentation is too scarce so I don't see any difference except JNDI. I suppose UserTransactionManager should be enough for my purposes but description states the following

J2eeTransactionManager
An implementation of TransactionManager that should be used by J2EE
  applications.

.. without any explanation.
ps. Sorry my english isn't well I know it.

A: Ок, since no-one answered me, after digging into source code, I think I'm ready to answer my own question:

*

*Both Atomikos and Bitronix TMs implemented as singletons [1], [2]

*Both Atomikos and Bitronix TMs are thread-safe. Particularly, Atomikos uses intrinsic synchronization and Bitronix simply doesn't share state between threads.

*Both Atomikos and Bitronix TMs implement both (oops) TransactionManager and UserTransaction interfaces so in basically doesn't matter which one you'll use. Even if you look at the Atomikos UserTransactionImp class you'll see that it internally instantiates and uses corresponding TransactionManager implementation.

So it is safe to have one TM-per-webapp instance, which you can share any way you like. Since Atomikos TM supposed to be instantiated it's better to share it through dependency injection. Bitronix TM can be used through public static method as any other singleton.
Additionally you can manage transactions via JNDI. You can find an example in the Java Persistence with Hibernate book source code.


text:
Q: paypal actionType CREATE completes without ExecutePayment I'm using the adaptive payments API making a parallel payment with the actionType "CREATE". The buyer accepts the payment and is redirected to the returnUrl, but i see in my notifications that the transaction was complete without me calling "ExecutePayment".
I would like to capture the payment and Execute it within 48 hours, without any additional authorization from neither the buyer nor any of the receivers.
Similar issue (not resolved) here: Adaptive Payments payment COMPLETED although actionType is CREATE
and here:
Paypal CREATE type
I also tried this:
Are you doing a split payment, or why exactly are you doing Adaptive Payments? If you just use the Express Checkout API you can run it as an Authorization and then run DoCapture when you're ready to actually move the funds.
but the last step (DoCapture) doesn't allow me to transfer the amount to the second user.
error code:
Array
(
    [AUTHORIZATIONID] => O-0GJ340210A068152T
    [TIMESTAMP] => 2015-04-03T12:24:46Z
    [CORRELATIONID] => f4841861b9b5
    [ACK] => Failure
    [VERSION] => 74.0
    [BUILD] => 16057073
    [L_ERRORCODE0] => 10007
    [L_SHORTMESSAGE0] => Permission denied
    [L_LONGMESSAGE0] => You do not have permissions to make this API call
    [L_SEVERITYCODE0] => Error
)

Any clues?

A: In short, Adaptive Payments doesn't support the notion of authorizing and capturing later.  Further, if the sender goes over to the PayPal website and approves the payment, the payment is going to complete immediately — regardless of what you set actionType to.  actionType=CREATE is primarily useful for implicit payments -- e.g., those payments where the API caller and the sender are the same party, or payments where you are using a preapproval that the sender has previously approved.


text:
Q: Azure Pipeline Get Template name from variable Please consider the following:
- job: Backend
   steps:

    - template: $(ClassLibraryTemplate)
      parameters:
        projectName: 'Core'
        solutionPath: 'Source/Core.sln'

ClassLibraryTemplate is defined as a pipeline variable. But when I run the build, it fails because the variable is not replaced by its value and the template is not found.
Is it not possible to store the template name in a variable ?

A: For Azure DevOps YAML pipeline, the template get processed at compile time. However, the $(ClassLibraryTemplate) get processed at the runtime. That's why it fails.
More information: Understand variable syntax
You could define variable or parameter in your YAML pipeline, then use template expression. For parameter, you could specify value when queue/run pipeline in pop-up window.
For example:
parameters:
- name: temName
  displayName: template name
  type: string
  default: steps/test.yml

trigger:
  - none

variables:
- name: tem
  value: steps/build.yml

jobs:
- job: Linux
  pool:
    vmImage: 'ubuntu-16.04'
  steps:
  - template: ${{ variables.tem }}
  - template: ${{ parameters.temName }}