text:
Q: Backbone.js - saving a model with header params I'm trying to send a model to a REST service using save(), but I need to pass a header parameter along with the json data so that the correct service is invoked (spring can use the headers to route the call to the right handler). That is, I'm not really saving the model, I'm performing an specific action upon it (in this case, it's an approval action). The PUT url should look something like this:
http://server/name/1

And this shouldn't change because the resource identity isn't changing. But, the headers should include a header containing the action. In this case we'll call the parameter 'command', and this specific example the value of command is 'approve'.
I've tried adding an object with a data field to the save:
model.save({data: {command:'approve'}})

But that simply adds the object associated with the data to the json data in the body of the request. I've read that this approach works on the fetch side to add the given data as params, but on save it seems to not work according to my expectations. I've single stepped through the backbone code and if the data option exists on a save it is merged with the model.
As I have no control over the service interface I have to work out how to to set the header parameter. Can anyone give me some guidance as to how to achieve this at the point of saving the model?

A: You could tackle this a couple of different ways.
You could override Backbone syncwith your own implementation, as described here. Within your sync implementation, you would pull out certain params (like approve), and jam them into the URL.
Or you could override the Model.url.

A: After a few hours I finally came up with a working solution. I started with the save command:
model.save({command:'approve'})

And then I overrode backbone's ajax command:
    Backbone.ajax = function () {
    var args = Array.prototype.slice.call(arguments, 0);

    if (args[0].data) {
        var model = JSON.parse(args[0].data);
        var command = model.command;
        if (command) {
            args[0]['headers'] = { command: command};
        }
    }

    return Backbone.$.ajax.apply(Backbone.$, args);
}

This code looks for the command value on the model (Backbone.save put it there), and pushes it to the headers. The next step will be to simply remove the command from the model before returning it.


text:
Q: opening html using jquery lightbox how to open html page using j-query light box .

A: I'd recommend colorbox. It's the best IMO http://colorpowered.com/colorbox/
For implementation just use jquery to attach colorbox to a link or other element's click event
e.g.
$('#yourlink').colorbox();

Make sure the HREF of your link is set to the page you want to open e.g.
Open Lightbox

Update 26/11/2011:
I'm now using Fancybox instead. It's got a lot of powerful configuration options and works just as well as colorbox.

A: Here is a script you want.
http://jquery.com/demo/grey/
You can download it from
http://jquery.com/demo/grey/greybox.tar
Also these are others
http://www.enthropia.com/labs/ibox/
http://jquery.com/demo/thickbox/
http://planetozh.com/projects/lightbox-clones/

A: If you want to open anything other than images with jquery-lightbox (http://www.github.com/krewenki/jquery-lightbox), you can't. I'll second the recommendation for colorbox.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Building an instrumentation amplifier I am trying to develop a system for bioimpedance measurement.
I will use a frequency equivalent to 50KHz, using this project to support me.
The project uses an instrumentation amplifier. In my city I just found the INA111, but it is a very expensive component, so I decided to make my own instrumentation amplifier using three Op Amps (TL084CN).
I'm using this article to support me Design of an Instrumentation Amplifier - Justin Bauer.
My doubt is:
Since the AD5933 can only read positive voltages, an input of 2.5V is connected into the Vref terminal of instrumentation amplifier (INA118P).
This is done to 'convert' the AC voltage to DC (I think).

How do I do that? If I do not have terminal Vref on my "home Instrumentation Amplifier"?
Sorry, my English is bad (I'm not American), and I'm starting with electronics.

A: The "vref" input of a instrumentation amplifier is just a DC offset on the output.  Its use here doesn't convert AC (oscillating) to DC (steady) voltage, but just adds a DC offset to the waveform so that it is oscillating between (say) +3V and +1 V, rather than between +/- 1V.
You can see how it works in the datasheet of the INA118: http://www.ti.com/lit/ds/symlink/ina118.pdf, which shows the standard 3-opamp schematic, including the vref input.  I googled the reference you mentioned: http://www.egr.msu.edu/classes/ece480/capstone/spring15/group05/uploads/4/7/5/1/47515639/ece_480_app_note_justin_bauer.pdf here, it is just shown using ground as the reference voltage, but that is easily changed: disconnect R2 from ground, and connect it to your desired reference voltage.

A: A cheaper instrumentation amplifier can be designed by using only 2-Op Amps + 5 resistors, in place of the conventional 3-op amp + 7 resistors design . Of course, you would have to compromise on the CMRR .This can be done by following the schematic as shown below.

From simple KCL equations at inverting terminals of op-amps , we can get the equation for
Vout = (Va-Vb)(1+[Rf/Ro]+[2Rf/Rg]), where Rg is the gain tuning resistor used.
Using such a scheme may help in in cases where cost of IA being designed is an issue, but CMRR is not very stringent.


text:
Q: JPA repository return one item from db but there are multiple item in the db I have the following function in my repository
Set<Felhasznalo> findAllByNevContainsIgnoreCase(String nev);

When I use this function in the controller I got back one User.
For example, if I have a String "John" and I call the repo function with that string I got back "John Doe" but I also have "John Doe Jr" in the db and I need him too.
Why I get only one User?

A: I see you are using a Set. Maybe you have implemented an equals() function which checks the names and the Set filters out duplicate elements.
Try changing your code to this:
List<Felhasznalo> findAllByNevContainsIgnoreCase(String nev);

So use a List.

A: This is because you are storing your result in a Set which does not allow any duplicate values but here, you have duplicate names. Try changing Set to List as:
public List<Felhasznalo> findAllByNevContainsIgnoreCase(String nev);


text:
Q: Android, Remove square border around circular progress bar I have a circular progress bar that I designed through xml. The problem is, if I set layout_width and layout_height to wrap_content, it will cut off the circle. If I set the width and height manually to "__dp" then there is a huge box around the circle which expands too much. To explain more clearly, my progress bar starts when you touch it. However, with this border around it, even if you touch next to the progress bar it will start (when it shouldn't). How can I remove this border? Thanks!

    <ProgressBar
    style="?android:attr/progressBarStyleHorizontal"
    android:id="@+id/progressBar"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:indeterminate="false"
    android:progressDrawable="@drawable/circular_progress_bar"
    android:background="@drawable/circle_shape"
    android:max="100"
    android:layout_alignParentBottom="true"
    android:layout_centerInParent="true"
    />

circle_shape.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="ring"
    android:innerRadiusRatio="7"
    android:thickness="5dp"
    android:useLevel="false">

    <solid android:color="#CCC" />

</shape>

circular_progress_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="270"
    android:toDegrees="270">
    <shape
        android:innerRadiusRatio="7"
        android:shape="ring"
        android:thickness="5dp"
        android:useLevel="true">

        <gradient
            android:angle="0"
            android:endColor="#007DD6"
            android:startColor="#007DD6"
            android:type="sweep"
            android:useLevel="false" />
    </shape>
</rotate>

A: You set the wrong style.
   style="?android:attr/progressBarStyleHorizontal"

is meant for horizontal ProgressBars. Remove the style or use one that is meant to be used for circular ProgressBars like
style="@style/Base.Widget.AppCompat.ProgressBar"


text:
Q: What's the difference between $_POST, $_GET, and $_REQUEST? I am bit confused about these super global variable ($_POST, $_GET, and $_REQUEST) in PHP. In which scenario do I need to use these variables in PHP, and what are the main differences these three stand for?

A: Well, to know better, please visit GET vs. POST:

1) Both $_GET and $_POST create an array e.g. array( key => value, key2 => value2, key3 => value3, ...). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.
2) Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.
3) $_GET is an array of variables passed to the current script via the URL parameters.
4) $_POST is an array of variables passed to the current script via the HTTP POST method.
---- whereas $_REQUEST contains $_POST, $_GET and $_COOKIE .

A: $_POST is an associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.
You can use when you are sending large data to server or if you have sensitive information like passwords, credit card details etc
$_GET is an associative array of variables passed to the current script via the URL parameters. you can use when there is small amount of data, it is mostly used in pagination, page number is shown in the url and you can easily get the page number from URL using $_GET
$_REQUEST is a 'superglobal' or automatic global, variable. This simply means that it is available in all scopes throughout a script. It is an associative array that by default contains the contents of $_GET, $_POST and $_REQUEST (depending on request_order=)

A: Difference is:
$_GET retrieves variables from the querystring, or your URL.>

$_POST retrieves variables from a POST method, such as (generally) forms.

$_REQUEST is a merging of $_GET and $_POST where $_POST overrides $_GET.

A: There are 2 methods to send HTML form data from 1 Page to another or HTML page to server side (In PHP).

*

*POST
It is a method in which data gets sent using packet which is not visible to any user on web-browser. it is secured compared to GET method.

*GET
It is a method in which data gets sent with URL which is visible to user in address-bar of any web-browser. So, it's not secure as POST method.
Now, There are total three super global variables to catch this data in PHP.

*

*$_POST: It can catch the data which is sent using POST method.

*$_GET: It can catch the data which is sent using GET method.

*$_REQUEST: It can catch the data which is sent using both POST & GET methods.

Also with $_GET superglobal variable can collect data sent in the URL from submit button.


text: Q: Make a websocket that echoes Process output So I want to make an API in asp.net when a console app outputs a new line that it gets send back to the client to start the console app. I use https://learn.microsoft.com/en-us/dotnet/api/System.Diagnostics.Process?view=net-6.0 for running the console app instice of my asp.net app


text:
Q: How to use Vault as Boundary Credential Store to keep hosts ssh static credentials Integrating vault with boundary credential store , inorder to login into aws ec2 instance,
but have to statically provide the credential inorder to login into ec2.
./boundary connect ssh -target-id ttcp_1234567890 -addr=http://XXXXXXXXXXX -username hello
Credentials:
Credential Source ID: clvlt_jnEOdYQyew
Credential Source Name: new ec2
Credential Store ID: csvlt_4lWBv8Wke7
Credential Store Type: vault
Secret:
null
hello@hst_1234567890's password:
It is not taking the vault secret created in vault ,basically which it should
So is there any alternative to login into AWS resources through credential provided in vault .
the documentation has the analyst role able to connect postgres db without providing the credential.
boundary connect postgres -target-id ttcp_1r9XGCXdwE -dbname northwind
So is there the similar approach for logging into ec2 instance


text:
Q: Do we need an alternative channel for "feature requests"? I shouldn't have to post my feature requests as a "Questions". They aren't questions. They don't need an "answer", they just need a "response". But the site treats them like a regular Q/A.
If we absolutely have to use the Q/A model for feature requests, there should 2 automatic answers that say "Yes, I like this idea" and "No, I don't like this idea". That would help us gauge the interest and prioritize the feature request appropriately.
With today's model, when people don't like an idea, they downvote the question. That's the best move available, but it's just wrong. Downvoting the question says it's a bad feature request, and often that's not the case.
If a feature request is truly unnecessary, downvoting the question makes sense. But when it's a valuable addition that just isn't worth the effort, that deserves an answer (even if it gets downvoted).
Do we need an alternative channel for "feature requests"?

A:
I shouldn't have to post my feature requests as a "Questions". They aren't questions. They don't need an "answer", they just need a "response".

Meta site(s) were not created with the sole intention of making feature requests. You are not really asking the question when proposing a feature. It's just that  the general framework of all the SE sites is based on Question and Answers.

If we absolutely have to use the Q/A model for feature requests, there should 2 automatic answers that say "Yes, I like this idea" and "No, I don't like this idea".

Isn't the same thing easily done by upvote/downvote?

If a feature request is truly unnecessary, downvoting the question makes sense. But when it's a valuable addition that just isn't worth the effort, that deserves an answer (even if it gets downvoted).

Folks can add comments and answers when supporting or rejecting a proposal. Again, they may not technical be answers, but "discussion" over the proposed feature.

A:
I shouldn't have to post my feature requests as a "Questions".

Sometimes, it's possible to propose a feature request as an answer. This is often done during alpha releases of new functionality, like Moderator flag dashboard design refresh (alpha) and Custom Filters release announcement.
But most often, it is not. An alternative which sometimes works is posting a discussion stating "I'm seeing problem X. [A few paragraphs with elaboration and examples.] I'd like to do something about it, how about feature request Y? Or do you have better alternatives?".

With today's model, when people don't like an idea, they downvote the question.

Yes, that is exactly how it works: see the Help Center article What is "meta"? How does it work?.

Voting is different on meta.
...
Unlike normal Stack Exchange sites, Meta invites the community to discuss, debate and propose changes to the way the community itself behaves, as well as how the software itself works. On posts tagged feature-request, voting indicates agreement or disagreement with the proposed change rather than just the quality or usefulness of the post itself.

If you're looking for an alternative way to change how Stack Exchange works, you can try Twitter. I heard it works pretty well if you have enough followers.


text:
Q: Como agregar propriedades de objetos em JavaScript? Suponha um objeto da seguinte forma:
vendas = {
    obs1:{
        Venda1:{Regiao:"Norte", Valor: 200},
        Venda2:{Regiao:"Sul", Valor:100}
    },
    obs2:{
        Venda1:{Regiao:"Norte", Valor: 50},
        Venda2:{Regiao:"Sul", Valor:20}
    }
}

Como agregar a soma dos valores por região? É possível fazer isso sem loops?
O resultado seria um objeto como:
totais = {Norte:250, Sul:120}

As respostas podem ser em JS puro ou com bibliotecas.

A: Com a biblioteca Underscore.js dá pra fazer algo assim:
var totais = _
    .chain(vendas)
    // Primeiro: "achatar" as vendas
    .map(function(v) {
        return _
            .chain(v)
            .map(function(v2) {
                return v2;
            })
            .value();
    })
    .flatten()
    // Segundo: agrupar as vendas por região
    .groupBy('Regiao')
    // Terceiro: somar os agrupamentos e criar o objeto com os totais
    .map(function(g, key) {
        return {
            type: key,
            val: _(g).reduce(function(m, x) {
                return m + x.Valor;
            }, 0)
        };
    })
    .value();

console.log(totais);

Exemplo no jsFiddle
Resposta do mgibsonbr para a mesma pergunta no SOEN (com generalização da solução)

A: Para agregar os valores você pode usar a seguinte função:
function somarRegioes(vendas)
{
    totais = {};

    obs = Object.keys(vendas).map(function (key1)
    {
        var obs_vendas = vendas[key1];

        Object.keys(obs_vendas).map(function (key2)
        {
            var regiao = obs_vendas[key2]['Regiao'];

            // Se a região ainda não existir em totais.
            if(totais[regiao] === undefined)
                totais[regiao] = 0;

            totais[regiao] += obs_vendas[key2]['Valor'];
        });
    });

    return totais;
}

Ou com essa:
function somarRegioes(vendas)
{
    totais = {};

    for(var obs in vendas)
    {
        for(var venda in vendas[obs])
        {
            var regiao = vendas[obs][venda]['Regiao'];

            // Se a região ainda não existir em totais.
            if(totais[regiao] == undefined)
                totais[regiao] = 0;

            totais[regiao] += vendas[obs][venda]['Valor'];
        }
    }

    return totais;
}

O que fica como:
vendas = {obs1:{Venda1:{Regiao:"Norte", Valor: 200}, Venda2:{Regiao:"Sul", Valor:100}}, obs2:{Venda1:{Regiao:"Norte", Valor: 50}, Venda2:{Regiao:"Sul", Valor:20}}}
resultado = somarRegioes(vendas); // output = Object {Norte: 250, Sul: 120}

Acho um pouco complicado fazer isso sem loops, pois isso ocorrerá nem que seja indiretamente, pelo fato de que a entrada é dinâmica.

A: Consegui uma forma ainda mais sintética utilizando o jFunk e Underscore.
totais = _.chain(jF("*[Regiao]", vendas).get()).groupBy('Regiao').map(function(g, key) {
        return {
            type: key,
            val: _(g).reduce(function(m, x) {
                return m + x.Valor;
            }, 0)
        };
    })
    .value();


text:
Q: Geocode service findAddressCandidates returns no candidates with 10.0 address locator I posted this on an esri forum but nobody touched it. We've recently updated a geocoding service and I'm now unable to return addresses to my Java application. The old service is built with a 9.3 address locator and is served from a 10.0 ArcGIS Server.
The following code is used to return intersections after the user enters street names.
String url =
MessageFormat.format("{0}/findAddressCandidates?Street={1}%7C{2}&City=&Single+Line+Input=&outFields=&outSR=&f=pjson", geocodeServiceUrl, street, crossStreet);
GetMethod httpGet = new GetMethod(url);
int statusCode = client.executeMethod(httpGet);

The following JSON is returned with the old service:
response={
"spatialReference" : {
"wkid" : 2278
},
"candidates" : [
{
"address" : "EAGER ST | CALLAGHAN AVE",
"location" : {
"x" : 2132338.7499425262,
"y" : 13698061.000045776
},
"score" : 69,
"attributes" : {

}
}
]
}|

However, when I switch to the new service no candidates are returned in the response:
[#|2013-01-09T13:34:51.176-0600|INFO|sun-appserver2.1|null|_ThreadID=18;_ThreadName=httpSSLWorkerThread-8080-3;|geocodeIntersectionUsingREST: url=same URL/ArcGIS/rest/services/Locators/PWStreets/GeocodeServer/findAddressCandidates?Street=eager%7Ccallaghan&City=&Single+Line+Input=&outFields=&outSR=&f=pjson|#]

[#|2013-01-09T13:34:51.959-0600|INFO|sun-appserver2.1|null|_ThreadID=18;_ThreadName=httpSSLWorkerThread-8080-3;|geocodeIntersectionUsingREST: response={
"spatialReference" : {
"wkid" : 2278
},
"candidates" : [

]
}|#]

Strangely, when we run the same query using the ArcGIS Services directory the correct addresses are returned in JSON. The requests from the app and the services directory are identical. So it seems that only in my Java application and using a 10.0 service and address locator are no results returned.
Until I figure this out we are stuck using the old service built with a 9.3 address locator. Very confused.
Thanks!

A: This so stupid on Esri, but try "SingleLine" instead "Single+Line+Input" and let me know. I've sent a update documentation request on this and they said some versions still use it,.. but not in 10 an 10.1. Btw, who makes a service parameter with spaces?!
Check the other parameters names as well. Compare them to what the html form is sending with with URL with GET request or POST use Fiddler or Firefox Net Pane.


text:
Q: $_POST - проверка на заполнение определенной информацией Например, я хочу, чтобы мой скрипт обрабатывал данные, начинающиеся с http://google.ru/, а если пользователь передавал бы другую информацию, то он бы выводил текст "Ссылка введена не верно".
Как такое сделать? Вчера ночью копался, ничего толкового не нашел, кроме как проверку на заполнение (т.е. если поле заполнено, работает скрипт, если не заполнено, не работает).
A: чтите
ваш случай как то так
if (!preg_match("/php/i", "PHP is the web scripting language of choice.")) { //если нет совпадения "php" в строке "PHP is the web scripting language of choice."
    echo "A match was not found."; // то выводим что его нет
} else {
    echo "A match was found.";
}

A: Ну так это стандартная задача на поиск подстроки в строке. Справки в нете хоть пруд пруди.


text:
Q: bzr unable to connect to ssh host (because of python?) Until today, I have been able to use bzr pull server:path/to/trunk, but today I get an error:
Unable to connect to SSH host server; EOF during negotiation

It is not clear why this error occurs, but this is the traceback from ~/.bzr.log
Any ideas about how to fix this?
Mon 2011-02-21 16:36:04 -0600
0.022  bazaar version: 2.1.1
0.022  bzr arguments: [u'pull']
0.026  looking for plugins in /home/user/.bazaar/plugins
0.026  looking for plugins in /usr/lib/python2.6/dist-packages/bzrlib/plugins
0.062  encoding stdout as sys.stdout encoding 'UTF-8'
0.133  opening working tree '/home/user/pecan'
0.178  ssh implementation is OpenSSH
0.697  Traceback (most recent call last):
  File "/usr/lib/python2.6/dist-packages/bzrlib/commands.py", line 853, in exception_to_return_code
    return the_callable(*args, **kwargs)
  File "/usr/lib/python2.6/dist-packages/bzrlib/commands.py", line 1055, in run_bzr
    ret = run(*run_argv)
  File "/usr/lib/python2.6/dist-packages/bzrlib/commands.py", line 661, in run_argv_aliases
    return self.run_direct(**all_cmd_args)
  File "/usr/lib/python2.6/dist-packages/bzrlib/commands.py", line 665, in run_direct
    return self._operation.run_simple(*args, **kwargs)
  File "/usr/lib/python2.6/dist-packages/bzrlib/cleanup.py", line 122, in run_simple
    self.cleanups, self.func, *args, **kwargs)
  File "/usr/lib/python2.6/dist-packages/bzrlib/cleanup.py", line 156, in _do_with_cleanups
    result = func(*args, **kwargs)
  File "/usr/lib/python2.6/dist-packages/bzrlib/builtins.py", line 993, in run
    possible_transports=possible_transports)
  File "/usr/lib/python2.6/dist-packages/bzrlib/branch.py", line 169, in open
    possible_transports=possible_transports)
  File "/usr/lib/python2.6/dist-packages/bzrlib/bzrdir.py", line 843, in open
    return BzrDir.open_from_transport(t, _unsupported=_unsupported)
  File "/usr/lib/python2.6/dist-packages/bzrlib/bzrdir.py", line 873, in open_from_transport
    redirected)
  File "/usr/lib/python2.6/dist-packages/bzrlib/transport/__init__.py", line 1644, in do_catching_redirections
    return action(transport)
  File "/usr/lib/python2.6/dist-packages/bzrlib/bzrdir.py", line 860, in find_format
    transport, _server_formats=_server_formats)
  File "/usr/lib/python2.6/dist-packages/bzrlib/bzrdir.py", line 1820, in find_format
    return format.probe_transport(transport)
  File "/usr/lib/python2.6/dist-packages/bzrlib/bzrdir.py", line 1830, in probe_transport
    format_string = transport.get_bytes(".bzr/branch-format")
  File "/usr/lib/python2.6/dist-packages/bzrlib/transport/sftp.py", line 435, in get_bytes
    f = self.get(relpath)
  File "/usr/lib/python2.6/dist-packages/bzrlib/transport/sftp.py", line 425, in get
    f = self._get_sftp().file(path, mode='rb')
  File "/usr/lib/python2.6/dist-packages/bzrlib/transport/sftp.py", line 397, in _get_sftp
    connection, credentials = self._create_connection()
  File "/usr/lib/python2.6/dist-packages/bzrlib/transport/sftp.py", line 389, in _create_connection
    self._host, self._port)
  File "/usr/lib/python2.6/dist-packages/bzrlib/transport/ssh.py", line 376, in connect_sftp
    self._raise_connection_error(host, port=port, orig_error=e)
  File "/usr/lib/python2.6/dist-packages/bzrlib/transport/ssh.py", line 252, in _raise_connection_error
    orig_error=orig_error)
SocketConnectionError: Unable to connect to SSH host server; EOF during negotiation

0.698  Transferred: 0KiB (0.0K/s r:0K w:0K)
0.698  return code 3

A: This error was caused because I had added
alias bzr status='bzr status -V'

to .bashrc, and bzr status is an invalid alias name that presumably confused the server's bzr
A bug report to bzr indicates that a similar error can be caused by changes to the server's firewall settings


text:
Q: Time dependent conditions I'm trying to display a message on my website that is dependent on time of day and day of the week, its further complicated by the need to display the name of the day 24h after 2pm on the current day.
So far i have this which is close but doesn't seem to be correct, plus it's horrendously ugly and unsimple.
Can somebody please point out why/where it's not functioning as intended?
<?php if (date("w") != 0 && date("w") != 6 && date("w") != 5):
    $future_date = strtotime('tomorrow 14:00 Europe/London');
    $remaining = $future_date-strtotime('now');
    $tomorrow = strtotime('today 14:00 +601 minutes');
    $c_time = mktime('H:i');
    $open = strtotime('yesterday 14:00');
    $close = strtotime('today 14:00'); ?>

<?php if ($c_time > $open && $c_time < $close): ?>

Only
  <?php echo date('H', $remaining);?> hours, <?php echo date('i', $remaining);?> minutes left to get this product delivered on
    <?php echo date('l', $tomorrow);?> using 'Next Working Day'!

  <?php else: ?>

*Order before 2pm for next day delivery.

  <?php endif; ?>
<?php endif; ?>

A: I love the DateTime and DateInterval classes for this kind of thing.
I've taken a stab at what it looks like you're doing and so you should be able to work it out by using the following as a reference.
$now = new DateTime('now');
$orderWithin = null;
$deliveryDate = null;

switch ($now->format('w')) {

    // Order before 6pm Monday-Thursday and get it next day
    case 1: // Monday
    case 2: // Tuesday
    case 3: // Wednesday
    case 4: // Thursday
        $orderWithin = clone $now;
        $orderWithin->setTime(18, 00, 00);
        // Next day delivery
        $deliveryDate = clone $now;
        $deliveryDate->add(new DateInterval('P1D'));
        break;

    // Order before 6pm Friday and get it next working day (Monday)
    case 5: // Friday
        $orderWithin = clone $now;
        $orderWithin->setTime(18, 00, 00);
        // Next working day delivery
        $deliveryDate = clone $now;
        $deliveryDate->add(new DateInterval('P1D'));
        break;

    // Order on Sunday or Saturday then get it Tuesday
    case 0: // Sunday
        $orderWithin = clone $now;
        $orderWithin->setTime(23, 59, 59);
        // Tuesday delivery
        $deliveryDate = clone $now;
        $deliveryDate->add(new DateInterval('P1D'));
    case 6: // Saturday
        $orderWithin = clone $now;
        $orderWithin->add(new DateInterval('P1D'));
        $orderWithin->setTime(23, 59, 59);
        // Tuesday delivery
        $deliveryDate = clone $now;
        $deliveryDate->add(new DateInterval('P2D'));
        break;
}

$orderWithinInterval = $orderWithin->diff($now);

$orderWithinString = "{$orderWithinInterval->d} day(s), {$orderWithinInterval->h} hour(s), {$orderWithinInterval->i} minute(s)";

$deliveryDateString = "{$deliveryDate->format('D jS M')}";

?>

Order within <?= $orderWithinString ?> to get your item delivered by <?= $deliveryDateString ?>.

My output looked something like this:

Order within 0 day(s), 2 hour(s), 29 minute(s) to get your item delivered by Fri 19th Aug.

A: Revised version that now works as expected:
<?php if (!in_array(date("w"),array(0,6,5),true)):
                      $future_date = strtotime('tomorrow 14:00 Europe/London');
                      $remaining = $future_date-strtotime('now');
                      $tomorrow = strtotime('today 14:00 +601 minutes Europe/London');
                      $c_time = mktime();
                      $open = strtotime('yesterday 13:59 Europe/London');
                      $close = strtotime('today 13:59 Europe/London'); ?>

                      <?php if ($c_time > $open && $c_time < $close): ?>

                              Only
                                                <?php echo date('H', $remaining);?> hours, <?php echo date('i', $remaining);?> minutes left to get this product delivered on
                                                <?php echo date('l', $tomorrow);?> using 'Next Working Day'!

                  <?php else: ?>

*Order before 2pm for next day delivery.

                  <?php endif; ?>

                  <?php endif; ?>

Problem areas seemed to be mktime('H:i'); and timezone on strtotime(). next step is to clean up and make it efficient.

A: I've now taken it a bit further and made it work for 3 different scenarios, it's still bloated and ugly as hell, but as this is my first proper attempt at a making something for a real world situation i'm just happy it works!
Feel free to pick it to pieces and point out the best practice methods:

              <?php if (date("w") == 1 || date("w") == 2  || date("w") == 3 || date("w") == 4):?>
                 <?php $future_date = strtotime('tomorrow 14:00 Europe/London');
                  $remaining = $future_date-strtotime('now');
                  $tomorrow = strtotime('today 14:00 +601 minutes Europe/London');
                  $c_time = mktime();
                  $open = strtotime('yesterday 13:59 Europe/London');
                  $close = strtotime('today 13:59 Europe/London'); ?>

                  <?php if ($c_time > $open && $c_time < $close): ?>

                              Only
                            <?php echo date('H', $remaining);?> hour(s), <?php echo date('i', $remaining);?> minute(s) left to get this product delivered on
                            <?php echo date('l', $tomorrow);?> using 'Next Working Day'!

                  <?php else: ?>

                    *Order before 2pm for next working day delivery.
                  <?php endif; ?>
              <?php endif; ?>

              <?php if (date("w") == 5):?>
                  <?php
                    $future_date = strtotime('next tuesday 14:00 Europe/London');
                    $remaining = $future_date-strtotime('now Europe/London');
                    $tomorrow = strtotime('next tuesday Europe/London');
                    $c_time = mktime();
                    $open = strtotime('yesterday 13:59 Europe/London');
                    $close = strtotime('today 13:59 Europe/London');
                  ?>

                      <?php if ($c_time > $open && $c_time < $close): ?>

                              Only
                            <?php echo date('H', $remaining);?> hour(s), <?php echo date('i', $remaining);?> minute(s) left to get this product delivered on
                            <?php echo date('l', $tomorrow);?> using 'Next Working Day'!

                      <?php else: ?>

                          *Order before 2pm for next working day delivery.
                      <?php endif; ?>

                  <?php endif; ?>

              <?php if (date("w") == 0 || date("w") == 6):?>
                  <?php
                  $future_date = strtotime('next monday 14:00 Europe/London');
                  $remaining = $future_date-strtotime('now Europe/London');
                  $tomorrow = strtotime('next tuesday 14:00 +601 minutes Europe/London');
                  $number_days = (strtotime('next tuesday') - strtotime('now Europe/London'))  / (60 * 60 * 24);
                  ?>

                          Only
                        <?php echo substr($number_days, 0, 1); ?> Day(s) <?php echo date('H', $remaining);?> hour(s) <?php echo date('i', $remaining);?> minute(s) left to get this product delivered on
                        <?php echo date('l', $tomorrow);?> using 'Next Working Day'!

              <?php endif; ?>


text:
Q: django admin overriding delete_model not working with bulk delete I want to disable deleting for a specific model instance
I overrided delete_model in the ModelAdmin as follows :
def delete_model(self, request, client):
    if client.schema_name == 'public':
        messages.set_level(request, messages.ERROR)
        messages.error(request, 'Suppression interdite pour la racine')
    else:
        super().delete_model(request, client)

It works when I click the delete button on change view

But not with bulk delete as the instance is deleted without preventing

How can I fix this ? I also realized that delete_model is not called with bulk delete which makes a bit weird.

A: As bulk delete admin action documentation already warns you

The "delete selected objects" action uses QuerySet.delete() for
efficiency reasons, which has an important caveat: your model's
delete() method will not be called.
If you wish to override this behavior, you can override
ModelAdmin.delete_queryset() or write a custom action which does
deletion in your preferred manner – for example, by calling
Model.delete() for each of the selected items.
For more background on bulk deletion, see the documentation on object
deletion.


text:
Q: How to retrieve encrypted AWS secret manager password for database in AWS EC2? I have database password stored in secret manager of AWS and I need to encrypt that using KMS and use that password to connect with database after decrypting in EC2.

A: I included some Error handling.
Try This one:
import boto3
import base64
from botocore.exceptions import ClientError

def get_secret():
    secret_name = "db_password"
    region_name = "us-east-1"

    # Create a Secrets Manager client
    session = boto3.session.Session()
    client = session.client(
        service_name='secretsmanager',
        region_name=region_name
    )

    # In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
    # See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
    # We rethrow the exception by default.

    try:
        get_secret_value_response = client.get_secret_value(
            SecretId=secret_name
        )
    except ClientError as e:
        if e.response['Error']['Code'] == 'DecryptionFailureException':
            # Secrets Manager can't decrypt the protected secret text using the provided KMS key.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'InternalServiceErrorException':
            # An error occurred on the server side.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'InvalidParameterException':
            # You provided an invalid value for a parameter.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'InvalidRequestException':
            # You provided a parameter value that is not valid for the current state of the resource.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
        elif e.response['Error']['Code'] == 'ResourceNotFoundException':
            # We can't find the resource that you asked for.
            # Deal with the exception here, and/or rethrow at your discretion.
            raise e
    else:
        # Decrypts secret using the associated KMS CMK.
        # Depending on whether the secret is a string or binary, one of these fields will be populated.
        if 'SecretString' in get_secret_value_response:
            secret = get_secret_value_response['SecretString']
        else:
            decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary'])

    return secret

A: You'd have to write your own logic for that is your programming or scripting language of choice.
Make sure the following is in place:

*

*The key policy for the KMS key used to encrypt the secret has a statement that allows the account to use the key to decrypt.

*The EC2 instance profile should have permission for kms:Decrypt (for the kms key) and secretsmanager:GetSecretValue (for the secret).

*write the logic.

For example, from the boto3 docs (python)
import boto3
from botocore.exceptions import ClientError

def get_secret():
    secret_name = "MySecretName"
    region_name = "us-west-2"

    session = boto3.session.Session()
    client = session.client(
        service_name='secretsmanager',
        region_name=region_name,
    )

    try:
        get_secret_value_response = client.get_secret_value(
            SecretId=secret_name
        )
    except ClientError as e:
        if e.response['Error']['Code'] == 'ResourceNotFoundException':
            print("The requested secret " + secret_name + " was not found")
        elif e.response['Error']['Code'] == 'InvalidRequestException':
            print("The request was invalid due to:", e)
        elif e.response['Error']['Code'] == 'InvalidParameterException':
            print("The request had invalid params:", e)
        elif e.response['Error']['Code'] == 'DecryptionFailure':
            print("The requested secret can't be decrypted using the provided KMS key:", e)
        elif e.response['Error']['Code'] == 'InternalServiceError':
            print("An error occurred on service side:", e)
    else:
        # Secrets Manager decrypts the secret value using the associated KMS CMK
        # Depending on whether the secret was a string or binary, only one of these fields will be populated
        if 'SecretString' in get_secret_value_response:
            text_secret_data = get_secret_value_response['SecretString']
        else:
            binary_secret_data = get_secret_value_response['SecretBinary']

        # Your code goes here.

That should allow you to use the credentials in your python script. Of course any language can be used.


text:
Q: Saving an email to a .MSG file using EWS Managed API My current project runs a service on a Microsoft Exchange 2010-based email address, dedicated to apply custom rules to incoming emails.
As I am browsing through the possible C#-based solutions, EWS managed API seems like the best API to use for me. Every email action I need was found, but there is one extremely big one missing... Saving an email to a .msg file. Which is quite surprising to me given how easy of an action it is from Outlook (simply drag and drop from Outlook to any folder).
This is an absolute requirement as users keep their emails organized through drag and drop. Is there any way I've missed to do that with EWS? So far I've only found two non-EWS ways :

*

*Using a third-party library which I am not sure we can afford (IndependentSoft)

*Using a more complex method with MessageSave and outlook rules to execute a custom action (action being "run MessageSave" )

I am quite surprised that such a basic action requires so much work and would like to know, is there any easy way to save an email to a .msg file ?
Worst case scenario, is there a non-EWS API, C# based method to do so?
Thank you
Edit:
I have explored the .eml export solution. The issue is we use Outlook 2007, which does not support eml format. .msg is pretty much the requirement here

A: .msg is a format, which only outlook itself uses, not the exchange server you are communicating with.
For that matter, a .eml file can be created quite easily.
See here, how you can do it.

A: There is a non-EWS API, C# based method to do exactly what your looking for:
http://www.independentsoft.de/exchangewebservices/tutorial/downloadmessagetomsgfile.html
using System;
using System.IO;
using System.Net;
using Independentsoft.Exchange;

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            NetworkCredential credential = new NetworkCredential("username", "password");
            Service service = new Service("https://myserver3/ews/Exchange.asmx", credential);

            try
            {
               ItemShape itemShape = new ItemShape(ShapeType.Id);
               FindItemResponse inboxItems = service.FindItem(StandardFolder.Inbox, itemShape);

               for (int i = 0; i < inboxItems.Items.Count; i++)
               {
                   Independentsoft.Msg.Message msgFile = service.GetMessageFile(inboxItems.Items[i].ItemId);
                   msgFile.Save("c:\\test\\message" + i + ".msg", true);
               }
            }
            catch (ServiceRequestException ex)
            {
               Console.WriteLine("Error: " + ex.Message);
               Console.WriteLine("Error: " + ex.XmlMessage);
               Console.Read();
            }
            catch (WebException ex)
            {
               Console.WriteLine("Error: " + ex.Message);
               Console.Read();
            }
        }
    }
 }

It offers a feature to save messages and other items as Outlook .msg files.


text:
Q: playing multiple rtsp video streams in same activity i want to play multiple rtsp streams in a android(at least 8) app at the same time and view them in a main activity.
i was able to play 3 streams at a time using videoviews which were already defined in the layout.
but i want to add videoviews dynamincally(when a listview item is clicked). can someone give an example of how to play these streams in new threads, because i am not able to figure out how to use threads for streaming videos.
And what should be the base layout for the videoviews.
I am actually inspired by the milestone xprotect app and want to play videos like they do. Any ideas on how they do it ??
Milstone app playing multiple streams


text:
Q: Reduce Empty Space in JFrame I've got a finished application here, but there's a ton of blank space on the screen and I've been fiddling around with things for a while, but the picture below is the most I've managed to cut.

I'm assuming I'm not using a certain method or utility that I may or may not have used at all yet.
Here's the code:
public ListWindow() {

    chooser = new JFileChooser();

    this.setLayout(new GridLayout(3,1,1,1));
    JPanel sortPanel = new JPanel();
    JPanel displayPanel = new JPanel();
    JPanel btns = new JPanel();

    JLabel sortLabel = new JLabel("Sort by:");
    sortGame = new JRadioButton("Game");
    sortScore = new JRadioButton("Score");
    sortBtn = new JButton("Sort");

    ButtonGroup group = new ButtonGroup();
    group.add(sortGame);
    group.add(sortScore);

    list = new JList(reviewList.toArray());

    JScrollPane reviewPane = new JScrollPane(list);
    reviewPane.setPreferredSize(new Dimension(400, 150));

    windowBtn = new JButton("To Review Entry");

    buttonActions();

    sortPanel.add(sortLabel);
    sortPanel.add(sortGame);
    sortPanel.add(sortScore);
    sortPanel.add(sortBtn);
    displayPanel.add(reviewPane);
    btns.add(windowBtn);

    this.add(sortPanel);
    this.add(displayPanel);
    this.add(btns);
}
public static void main(String[] args) {

    ListWindow window = new ListWindow();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setTitle("CriticalStrike.com - Review Database");
    window.pack();
    window.setVisible(true);
}
}

Thanks for the help, guys!

A: This is caused by using a GridLayout, which causes equal sized spaces to be used by the components you add to it. In your case with one column and three rows, if the three components don't take up an equal amount of space from one to the next, then some of the GridLayout areas will have unused extra space.
I suggest using a BorderLayout here. You can add the first and third components to the north and south positions, which will try to use the least amount of room height wise and most amount of room width wise, and you can add the large text area to the center position, which will try to use the most amount of room height and width wise.
So something along the lines of...
this.setLayout(new BorderLayout());
...
this.add(sortPanel, BorderLayout.NORTH);
this.add(displayPanel, BorderLayout.CENTER);
this.add(btns, BorderLayout.SOUTH);

A: There's another possibility too, using GridBagLayout to push all your components up, leaving all the dead space at the bottom of your window.
You would need to add this to your main.
getContentPane().setLayout(new GridBagLayout());

You would then need something like this in ListWindow()
GridBagConstraints gBC = new GridBagConstraints();
//these two lines so it will still resize horizontally
gBC.fill = GridBagConstraints.HORIZONTAL;
gBC.weightx = 1.0;

You'll then add your panels with
this.add(panel, gBC);

Now the trick is to push everything up -- you can do this by putting an empty JLabel underneath the panels that will resize vertically. Like this:
JLabel jLabel1 = new JLabel();
gBC.fill = GridBagConstraints.VERTICAL;
gBC.weightx = 0.0;
gBC.weighty = 1.0;
this.add(jLabel1, gBC);

You might also need to set the vertical position of each component in the GridBagConstraints, but I doubt it if you add them in order.


text:
Q: How to increment a variable by 1 each time it's accessed I'm coding a recyclerview with infinite scroll.
int number = 1
Let's say
string url = "http://www.example.com?page= + 'number'"
is the URL of the first set of list.
Then when I'm appending the next page to the current page, the value of number in the url variable will become 2.
Next, it'll be 3 and so on.
I'm thinking of checking the current value of number in url and then incrementing by 1 but I don't know how to go about it.

A: The correct way should be making it private and creating accesors
private int number;

public void setNumber(int number)
{
    this.number = number
}

public int getNumber()
{
    return number;
}

Once having this you can modify the getter so it says:
public int getNumber()
{
    return number++;
}

That will increment number by 1 each time you call getNumber()
So you can just use
string url = "http://www.example.com?page=" + getNumber();

Hope this helps.

A: You could either do something like this:
int number = 1
[...]
String url = "http://www.example.com?page=" + (number++);

or create a helper method such as
int getNextNumber(){
  return ++number;
}
[...]
String url = "http://www.example.com?page=" + getNextNumber();


text:
Q: Creating two arrays with malloc on the same line In C/C++ you can initialize a set of variables to the same value by this syntax: a = b = c = 1;
Would this work for malloc? I.E. something along the lines of:
char *a, *b;
a = b = malloc(SOME_SIZE * sizeof(char));

Would this create two arrays of the same size, but each has its own memory? Or would it assign both arrays to the same place in address space?

A: If you break down your multiple assign line to single assignment lines, the solution would become more clear to you.
a = b = malloc(SOME_SIZE * sizeof(char));

OR
b = malloc(SOME_SIZE * sizeof(char)); // b points to the alloced memory
a = b; // a got the value of b i.e., a points to where b is pointing.

A:
Would this create two arrays of the same size, but each has its own memory?

No.

Or would it assign both arrays to the same place in address space?

It would assign both pointers to the same address, i.e. Both pointer a and b will point to the same allocated memory location.
In case of
int a, b, c;
a = b = c = 1;

compiler allocates memory for all variables a, b and c to store an int data type and then assigns 1 to each memory location. All memory location has its own copy of that data.

A: #include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
using namespace std;
#define SOME_SIZE 20
int main()
{

      char *a, *b;
      a = b = (char *)malloc(SOME_SIZE * sizeof(char));
      strcpy(a,"You Are Right");

      cout << &(*a) << endl;
      cout << &(*b) << endl;
      return 0;
}

OutPut:
You Are Right
You Are Right

*

*from this its clear that Both Points to the Same Memory Area.


text:
Q: Interpolate values in pandas using the nearest method? How do I interpolate the nearest number?
My pd.Series named df1
0      RK
1       1
2       2
3       3
4       4
5     NaN
6       6
7       7
8       8
9     NaN
10     10

And I would like to interpolate the nearest number to replace NaN, like this
0      RK
1       1
2       2
3       3
4       4
5       5
6       6
7       7
8       8
9       9
10     10

According to Official Doc pandas.Series.interpolate
I tried
df1 = df1.interpolate(method='nearest',axis=0)

but it doesn't change.
Need help, and thanks in advance. :~)

A: just do
df1.interpolate()

don't bother with the method='nearest' option.  The default method='linear' should do the trick.


text:
Q: Why the least action principle is always (?) used in this particular form? The least action principle in (mathematical) physics says the following.  Given a system, e.g. collection of particles, whose motion satisfies a known system of differential equations (of second order).  Then there exists a so called action functional $S$ on the space of paths of all the particles such that solutions of the above differential equations are precisely the critical paths of $S$.  Moreover in all known to me cases it is assumed that $S$ can be chosen in the form $$S=\int L(x,\dot x,t)dt,\,\,\,(1)$$
where $L$ is called Lagrangian.
The least action principle is satisfied in this form for many problems of interest in physics, but not for arbitrary system of differential equations.

Question. Why it is important that $S$ has the form (1) for some Lagrangian? Are there situations of interest in (mathematical) physics where the action functional is not given by any Lagrangian?

Remark. If one takes the action functional in the form
$$S_1:=\exp(S)=\exp(\int L(x,\dot x,t)dt)$$
then $S_1$ and $S$ have obviously the same critical paths.

A: In the form (1), if you compute the variation $\delta S / \delta x(t) = E(t)$, you find that $E(t) = E(x(t),\dot{x}(t), \ddot{x}(t) ,t)$ is a local/differential expression (the value of $E(t)$ does not depend on $x(t')$ or its derivatives at other times $t'\ne t$). This is no longer true if you use $\exp(S)$ instead of $S$. There is no dispute that $S$ and $\exp(S)$ have the same critical points (N.B.: first order variations cannot distinguish between critical points of different kinds like maxima, minima, or saddle points). But if like your $\delta S / \delta x(t)$ to be local (and some people do), then you are stuck with local action functionals, namely those in the form (1).
UPDATE: The proof that locality of $E(t)$ implies locality of $S$ is straightforward, essentially an application of the fundamental theorem of calculus. Morally, $E(x(t), \dot{x}(t), \ddot{x}(t), t)$ is the gradient of $S$ with respect to $x$. Conversely, $S$ is the primitive/anti-derivative of $E(t)$, and any two such primitives must differ by a constant. One primitive can be constructed by preserving locality: $$S = \int \left(\int_0^1 x(t) E(s x(t), s\dot{x}(t), s\ddot{x}(t), t) ds \right) dt,$$ where the expression in parentheses is known as the Vainberg-Tonti Lagrangian (Google the keywords for references). So all other primitives must differ by a constant. There may be some funny ways to express a constant which may not appear local in the way we have been discussing, but such non-locality can be dismissed as trivial. This discussion has obvious generalizations to more dependent and independent variables, as well as higher differential orders.


text:
Q: Convert strings with an unknown number of hex strings embedded in them to strings using regex So I have a list of strings (content from Snort rules), and I am trying to convert the hex portions of them to UTF-8/ASCII, so I can send the content over netcat.
The method I have now works fine for strings with single hex characters (i.e. 3A), but breaks when there's a series of hex characters (i.e. 3A 4B 00 FF)
My current solution is:
import re
import codecs

def convert_hex(match):
  string = match.group(1)
  string = string.replace(" ", "")
  decode_hex = codecs.getdecoder("hex_codec")
  try:
    result = decode_hex(string)[0]
  except:
    result = bytes.fromhex((lambda s: ("%s%s00" * (len(s)//2)) % tuple(s))(string)).decode('utf-16-le')
  return result.decode("utf-8")

strings = ['|0A|Referer|3A| res|3A|/C|3A|', 'RemoteNC Control Password|3A|', '/bbs/search.asp', 'User-Agent|3A| Mozilla/4.0 |28|compatible|3B| MSIE 5.0|3B| Windows NT 5.0|29|']

converted_strings = []

for string in strings:
    for i in range(len(string)):
        string = re.sub(r"\|(.{2})\|", convert_hex, string)
    converted_strings.append(string)

For the strings in strings, this works, but for a string like:
|08 00 00 00 27 C7 CC 6B C2 FD 13 0E|
it breaks.
I tried changing the regex to:
re.sub(r"\|.*([A-Fa-f0-9]{2}).*\|")

but that only converts the last hex.
I need this solution to work for strings like Hello|3A|World, |3A 00 FF|, and Hello|3A 00|World
I know it's an issue with the regexp, but I'm not sure what exactly.
Any help would be much appreciated.

A: It looks like a substring is either always hex i.e. (?:[A-Fa-f0-9]{2}\s)+[A-Fa-f0-9]{2} or not hex at all between | symbols?
This works:
for string in strings:
    for i in range(len(string)):
        string = re.sub(r"(?<=\|)((?:[A-Fa-f0-9]{2}\s)*[A-Fa-f0-9]{2})(?=\|)", convert_hex, string)
    converted_strings.append(string)

(extra parentheses for a capturing group 1 - you could leave out one pair of parentheses and change your function to act on group(0) instead)
But it breaks on your example |08 00 00 00 27 C7 CC 6B C2 FD 13 0E|, as that doesn't appear to be a valid UTF-8 encoding. The resulting error:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc7 in position 5: invalid continuation byte

However, a valid UTF-8 encoded multi-byte string like '|74 65 73 74 20 f0 9f 98 80|' works just fine:
import re
import codecs

def convert_hex(match):
  string = match.group(1)
  string = string.replace(" ", "")
  decode_hex = codecs.getdecoder("hex_codec")
  try:
    result = decode_hex(string)[0]
  except:
    result = bytes.fromhex((lambda s: ("%s%s00" * (len(s)//2)) % tuple(s))(string)).decode('utf-16-le')
  return result.decode("utf-8")

strings = ['|74 65 73 74 20 f0 9f 98 80|']

converted_strings = []

for string in strings:
    for i in range(len(string)):
        string = re.sub(r"(?<=\|)((?:[A-Fa-f0-9]{2}\s)*[A-Fa-f0-9]{2})(?=\|)", convert_hex, string)
    converted_strings.append(string)

print(converted_strings)

Result:
['|test |']

If you don't really need a printable representation of the data, you could just have your function return the bytes object and only apply the function to matching parts - instead of constructing a new string.
Based on what @Selcuk was saying, perhaps a result with byte-strings makes more sense - this works on all three types of input:
import re
import codecs

def convert_hex(match):
  string = match.group(1)
  string = string.replace(b" ", b"")
  decode_hex = codecs.getdecoder("hex_codec")
  try:
    result = decode_hex(string)[0]
  except:
    result = bytes.fromhex((lambda s: ("%s%s00" * (len(s)//2)) % tuple(s))(string)).decode('utf-16-le')
  return result

strings = ['|0A|Referer|3A| res|3A|/C|3A|', '|74 65 73 74 20 f0 9f 98 80|', '|08 00 00 00 27 C7 CC 6B C2 FD 13 0E|']

converted_strings = []

for string in strings:
    string = re.sub(rb"(?<=\|)((?:[A-Fa-f0-9]{2}\s)*[A-Fa-f0-9]{2})(?=\|)", convert_hex, string.encode())
    converted_strings.append(string)

print(converted_strings)

Result:
[b'|\n|Referer|:| res|:|/C|:|', b'|test \xf0\x9f\x98\x80|', b"|\x08\x00\x00\x00'\xc7\xcck\xc2\xfd\x13\x0e|"]

No encoding issues, because no encoding is chosen. (Note that I didn't attempt to change convert_hex too much - there's some encoding juggling in there that you may need to look at, I just got it to work for bytes)


text:
Q: Fold/unfold all groups at given level via keyboard shortcut The combination ctrl+' can be used to fold/unfold a selected group.
Is there a way to fold/unfold all cells at a given nesting level, and possibly also to fold/unfold all groups?
I'm thinking something along the lines of ctrl+k ctrl+j, ctrl+k ctrl+1 and so on, that are used for these kinds of folding actions in Visual Studio Code, Atom, and possibly other editors.
Given that in a Mathematica notebook the "nesting" works different than in a regular code editor (no nesting inside code for one), by "nesting level" I here mean to fold/unfold all chapters, sections, subsections and so on.
Edit:
I've just found this other post where Kuba gives a function to open/close all groups at a given level. It therefore only remains to find a way to bind this to the appropriate keyboard shortcuts.
I'm however not sure how to use the above mentioned bindings to do this.


text:
Q: server.session.cookie.max-age doesn't seem to work I added in my configuration the following property:
server.session.cookie.max-age=3600

The Set-Cookie HTTP header is:
Set-Cookie: JSESSIONID=3407BD3E1C7153D70EFC5DBD16B059E4; Path=/; Secure; HttpOnly

So it seems like Spring ignores this property. Is it deprecated? If not, why isn't it working?
Here's my configuration:
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .anyRequest()
            .authenticated()
            .and()
            .formLogin()
            .successForwardUrl("/")
            .defaultSuccessUrl("/", true)
            .permitAll()
            .and()
            .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .deleteCookies("JSESSIONID")
            .invalidateHttpSession(true)
            .and()
            .rememberMe()
            .key("key")
            .tokenValiditySeconds(86400);
}

A: With Spring Boot 2.1.4 you have to use the property server.servlet.session.cookie.max-age instead of server.session.cookie.max-age, see Spring Boot Reference Guide:

Appendix A. Common application properties
Various properties can be specified inside your application.properties file, inside your application.yml file, or as command line switches. This appendix provides a list of common Spring Boot properties and references to the underlying classes that consume them.
[...]
# EMBEDDED SERVER CONFIGURATION (ServerProperties)
[...]
server.servlet.session.cookie.max-age= # Maximum age of the session cookie. If a duration suffix is not specified, seconds will be used.

and Spring Boot 2.0.0 RC1 Configuration Changelog.


text:
Q: How to Solve Disjunction Elimination Proof How would you prove the following by disjunction elimination?
Premises:
A ∨ B ,
A ∨ C
Conclusion:
A ∨ (B ∧ C)

A: *

*Premise: A v B

*Case 1: A

*Then, we can just get A v (B ∧ C) and it's works.

*Case 2: B (where A is false)

*Premise: A v C

*since NOT A, we get C (because A v C is true)

*so, A v (B ∧ C)


text:
Q: How does template argument deduction works recursively? I was reading this article : http://accu.org/index.php/journals/409 . Let's take a simple example :
template<typename T>
void foo(T& param){}

and call to above function like foo("String") . Now how does deduction works recursively? . What I understood was deduction works something like this :
Type of Arg =  const char[6] and type of parameter is T& ->
so T must be -> T1[] -> which makes Parameter like T1 (&) []
-> now T1 must of const char -> which makes Parameter like const char (&)[] .
Am I right path? Thanks
P.S -> I recently started learning c++ and programming, so is it ok if I learn cores of language first with examples rather than paying my attention to projects or huge algorithms? Thanks

A: Template deduction does not work recursively, at least in conventional sense of the term 'recursion'. (I feel you are using the term incorrectly). The actual deduction is rather straightforward.
In this particular case, T& is const char(&) [6] (as you correctly pointed out), which means T is const char[6].


text:
Q: Securing an EC2 Instance which Hosts a Static Public Website I am trying to host a public website on an Amazon EC2 small linux instance. My website is pretty simple, in that, it doesn't have a database and any fancy server components. It's just a bunch of plain old html hosted on an Apache webserver.
What security measures do I need to take (firewall configuration?, ddos prevention?) to prevent my website from being defaced or denied access to? My linux knowledge is limited, so I would appreciate any suggestions/help here.

A: If you only have static HTML pages, don't run a webserver.
Use an object store (like Amazon S3 or Rackspace CloudFiles) to distribute your static html files. It's way less expensive, you don't have to handle application security, and is much faster.

*

*Hosting a Static Website on Amazon S3

*Static Websites on Rackspace CloudFiles

A: Host your website inside a private subnet of a VPC and have a public facing load balancer (e.g .nginx or Haproxy) or use AWS elastic load balancer in public subnet of VPC. The point is, use AWS VPC. Check this out.
In EC2-classic (non-VPC nevironment), the only security you have is the rules you configure in your security groups. With VPC, you have an added layer of security as your website won't be public facing. Instead the load balancer will be public facing.


text:
Q: How to select AES Encryption version from SynCrypto? SynCrypto is a open source library for data encryption included in this pack.
In this unit (SynCrypto.pas) is the following comment at the begining of file:

AES128 cypher   84 MB/s         uncypher   81 MB/s  asm version
  AES128 cypher   57 MB/s         uncypher   57 MB/s  pascal version
  AES192 cypher   72 MB/s         uncypher   70 MB/s  asm version
  AES192 cypher   48 MB/s         uncypher   48 MB/s  pascal version
  AES256 cypher   62 MB/s         uncypher   61 MB/s  asm version
  AES256 cypher   42 MB/s         uncypher   42 MB/s  pascal version

From this I understand that are two versions of code: pascal-slower and asm-faster. But the problem is, how can I select between these two ?
Edit: And a secondary question, if you allow me: how cand I select the bitwidth of the key: 128, 192 and 256 ?
I use this code to encrypt and decrypt:
  outp := TAESCFB.SimpleEncrypt(inp,'privatekey',true,true);
  inp := TAESCFB.SimpleEncrypt(outp,'privatekey',false,true);

... and Delphi 2009.

A: Short answer: the fastest code will always be used for you, depending on the compiler and computer.
Long answer:
There is only a single code version compiled at a time, either pascal or optimized asm. It depends on conditional defines when running in the unit, set automatically depending on your compiler version (from Delphi 5 up to latest Delphi or FPC revision), and CPU platform (if it has Intel or ARM). Then at runtime, on Intel, AES-NI hardware opcodes can be detected and used, or, on VIA, Padlock hardware opcodes. Even the pascal implementation may be rolled or unrolled.
{$define AES_ROLLED}
// if defined, use rolled version, which is faster (at least on my AMD CPU)

{$ifdef DELPHI5OROLDER}
  {$define AES_PASCAL} // Delphi 5 internal asm is buggy :(
  {$define SHA3_PASCAL}
{$else}
  {$ifdef CPUINTEL} // AES-NI supported for x86 and x64
    {$ifdef CPU64}
      {$ifdef HASAESNI}
        {$define USEAESNI}
        {$define USEAESNI64}
      {$else}
        {$define AES_PASCAL} // Delphi XE2/XE3 do not have the AES-NI opcodes :(
      {$endif}
      {$define AESPASCAL_OR_CPU64}
    {$else}
      {$define USEAESNI}
      {$define USEAESNI32}
    {$endif}
  {$else}
    {$define AES_PASCAL} // AES128 unrolled pascal(Delphi7)=57MB/s rolled asm=84MB/s :)
    {$define SHA3_PASCAL}
  {$endif CPUINTEL}
{$endif}

To sumup, when working with AES, the unit has six diverse versions of the algorithm: pascal rolled, pascal unrolled, x86/x64 asm without AES-NI, x86/x64 asm with AES-NI, x86 with padlock, Windows API.
SimpleEncrypt:
There are two overloaded SimpleEncrypt methods. One with fixed size of 256 bits (the one you used), another with a KeySize parameter (either 128, 192 or 256):
class function TAESAbstract.SimpleEncrypt(const Input: RawByteString; const Key;
   KeySize: integer; Encrypt, IVAtBeginning: boolean): RawByteString;

Of course, you should first hash the input password text into a THash128 or THash256 secret key, before calling the function. We recommend using PBKDF2_HMAC_SHA256 for this purpose (with a high round number).
Some numbers:
With a modern CPU, including AES-NI, you will have tremendous performance. This is the fastest native AES implementation in Delphi/FPC, for sure (no other uses AES-NI). Some numbers run my laptop, taken from TTestCryptographicRoutines.Benchmark regression tests:
 50000 AES128CFB in 229.60ms i.e. 217764/s or 463.4 MB/s
 50000 AES128OFB in 183.66ms i.e. 272237/s or 579.3 MB/s
 50000 AES128CFBCRC in 227.61ms i.e. 219674/s or 467.5 MB/s
 50000 AES128OFBCRC in 181.18ms i.e. 275954/s or 587.2 MB/s
 50000 AES256CFB in 288.57ms i.e. 173265/s or 368.7 MB/s
 50000 AES256OFB in 243.96ms i.e. 204944/s or 436.1 MB/s
 50000 AES256CFBCRC in 294.38ms i.e. 169844/s or 361.4 MB/s
 50000 AES256OFBCRC in 244.49ms i.e. 204507/s or 435.2 MB/s
 50000 SHAKE128 in 473.34ms i.e. 105631/s or 224.8 MB/s
 50000 SHAKE256 in 596.74ms i.e. 83787/s or 178.3 MB/s

Forget about the Windows API, which are dead slow in comparison. The TAES...CRC class adds a 128-bit crc32c to the input and output during compression with no speed penalty, to authentication and validate the content. I also included SHAKE128/SHAKE256 encryption (not AES compatible), which is comparable to HMAC-SHA-256 + AES-256 in a single step, and is very fast on all CPUs without AES-NI.


text:
Q: C++ WinSock sending commands to telnet server So I'm making a C++ program that connects through telnet. The connection seems to be working, because I get output from the server. The problem is that I need to send a specific command to telnet. For example a command:

login user password

Just sending it via send() doesn't seem to do anything (or maybe I'm doing something wrong, but don't see it).
There are some information on the page ftp://ftp.rfc-editor.org/in-notes/rfc854.txt but I don't really understand it.
Can someone show me on an example and explain how should I do it to make it work? Tried to google but I didn't really find exactly what I want. I literally need it to send two commands.
Here's what I have tried (not the full code):
int main() {
  int iR;
  std::string input;
  std::cout << "Telnet ip: ";
  std::getline(std::cin, input);
  std::cout << std::endl;

  u_long ip = 0;
  u_short port = DEFAULT_PORT;
  u_long * ptr = &ip

  const char * cptr = input.c_str();
  inet_pton(AF_INET, cptr, ptr);

  std::cout << "Telnet port: ";
  std::getline(std::cin, input);
  std::cout << std::endl;
  iR = std::stoi(input);
  if((iR > SHRT_MAX) || (iR < 0)) {
    std::cout << "Wrong port number, using default." << std::endl;
  }
  else {
    port = iR;
  }

  WSADATA wsaData;
  iR = WSAStartup(MAKEWORD(2, 2), &wsaData);
  if (iR != 0) { return 1; }
  SOCKET server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (server == INVALID_SOCKET) { WSACleanup(); return 1; }

  sockaddr_in addr;
  addr.sin_family = AF_INET;
  addr.sin_addr.s_addr = ip;
  addr.sin_port = htons(port);

  std::string user;
  std::string pass;
  std::cout << "Username: ";
  std::getline(std::cin, user);
  std::cout << std::endl; << "Password: ";
  std::getline(std::cin, pass);
  std::cout << std::endl;

  std::cout << "Connecting..." << std::endl;
  if ((connect(server, (SOCKADDR *)&addr, sizeof(addr))) == SOCKET_ERROR) {
    std::cout << "Couldn't connect. << std::endl;
    WSAcleanup();
    Sleep(2000);
    return 0;
  }

  int bRecv = 0;
  char buff[2048];

  bRecv = recv(server, buff, sizeof(buff), 0);
  if ((bRecv == SOCKET_ERROR) || (bRecv == 0)) {
    std::cout << "Disconnected from the server." << std::endl;
    WSACleanup();
    return 0;
  }

  buff[bRecv] = 0;
  // When it connects successfully, a message appears on the screen from server
  std::cout << buff << std::endl;

  memset(buff, 0, sizeof(buff));
  std::string command = "login ";
  command.append(user);
  command.append(" ");
  command.append(pass);

  cptr = login.c_str();
  strcpy_s(buff, cptr);

  iR = send(server, buff, (u_int)strlen(buff), 0);
  if (iR == SOCKET_ERROR) { std::cout << "Couldn't send data." << std::endl; WSACleanup(); return 0;
  while (true) {
    bRecv = recv(server, buff, sizeof(buff), 0);
    if ((bRecv == SOCKET_ERROR) || (bRecv === 0)) {
      std::cout << "Disconnected from the server." << std::endl;
      break;
    }
    buff[bRecv] = 0;
    std::cout << buff << std::endl;
  }
  WSACleanup();
  return 0;
}

I mean I hope I'm not doing this the wrong way. I'm pretty much a begginer in C++.

A: You are not sending a line break after your command.
std::string command = "login ";
command.append(user);
command.append(" ");
command.append(pass);
command.append("\r\n"); // <-- add this

You also do not need to use buff to hold the command, you can send command directly:
iR = send(server, command.c_str(), (u_int) command.length(), 0);


text:
Q: how to insert jpeg image into excel sheet in unix I am able to insert bmp images using insert_bitmap command of the xlwt module in python using the following code:
import xlwt
from PIL import Image
book = xlwt.Workbook()
sheet3 = book.add_sheet('diagrams')
Image.open('violations.png').convert("RGB").save('violations.bmp')
sheet3.insert_bitmap('violations.bmp',5,13)
book.save('simple.xls')

This is correctly inserting the bmp image into the sheet but my concern is that the bmp image is around 3MB and I am unable to compress it without significant quality loss.
Is there some way to insert jpeg images into a worksheet in unix ?

A: From looking at the code it looks like xlwt only supports 24bit bitmap images.
The XlsxWriter Python module can insert PNG images (or JPEG or Bitmap). Here is an example:
from xlsxwriter.workbook import Workbook

# Create an new Excel file and add a worksheet.
workbook = Workbook('images.xlsx')
worksheet = workbook.add_worksheet()

# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 30)

# Insert an image.
worksheet.write('A2', 'Insert an image in a cell:')
worksheet.insert_image('B2', 'python.png')

workbook.close()

Output:

See the relevant section of the docs for further information.

A: from
http://xlsxwriter.readthedocs.org/en/latest/example_images.html
if you need to offset -and- scale an image in one insert:

worksheet.insert_image('B5', 'python.png', {'x_offset': 2, 'y_offset': 2, 'x_scale': 0.5, 'y_scale': 0.5})

this took me a second to figure out, thought it might save others some time


text:
Q: Postgres Transaction OOM on 100k DDL statements We execute approximately 100k DDL statements in a single transaction in PostgreSQL. During execution, the respective Postgres connection gradually increases on its memory usage and once it can't acquire more memory (increasing from 10MB to 2.2GB usage on 3GB ram), OOM killer hits it with 9 which results in Postgres being gone to recovery mode.
BEGIN;

CREATE SCHEMA schema_1;
-- create table stmts - 714
-- alter table add pkey stmts - 714
-- alter table add constraint fkey stmts - 34
-- alter table add unique constraint stmts - 2
-- alter table alter column set default stmts - 9161
-- alter table alter column set not null stmts - 2405
-- alter table add check constraint stmts - 4
-- create unique index stmts - 224
-- create index stmts - 213

CREATE SCHEMA schema_2;
-- same ddl statements as schema_1 upto schema_7
-- ...
-- ...
-- ...
CREATE SCHEMA schema_7;

COMMIT

Including the create schema statement, approximately 94304 DDL statements were meant to be executed.
As per Transactional DDL in PostgreSQL

Like several of its commercial competitors, one of the more advanced features of PostgreSQL is its ability to perform transactional DDL via its Write-Ahead Log design. This design supports backing out even large changes to DDL, such as table creation. You can't recover from an add/drop on a database or tablespace, but all other catalog operations are reversible.

We have even imported approximately 35GB of data into PostgreSQL in a single transaction without any problem, but why does the Postgres connection requires huge memory when executing thousands of DDL statements in single transaction?
We can temporarily resolve it by increasing the RAM or allocating swap, but we can say that the number of schema creation in a single transaction can increase up to 50 - 60 (Approx 1M DDL statements) which would require 100+ Gigs of RAM or swap which isn't feasible right now.
PostgreSQL version: 9.6.10
Is there any reason why executing lots of DDL statements requires more memory while dml statements does not? Isn't both handles transactions by writing to underlying WAL? So why, for DLL it's different?
Reason for Single Transaction
We sync the entire database of customers from Customer Premise (SQL Server) to cloud (PostgreSQL). All customers have different no of databases. Process is, entire data will be generated as CSV from SQL Server and import into PostgreSQL using Temp Tables, COPY and ON CONFLICT DO UPDATE. During this process, we treat each customer as a single database in PG and individual DB in customer's SQL Server as schemas in customer's PG DB.
So based on the CSV data, we will create the schemas dynamically and import data into it. As per our application design, the data in PG should be strictly consistent at any point of time and there shouldn't be any partial schema / tables / data. So we had to achieve this in a single transaction. Also we incrementally sync from customer to cloud DB every 3 minutes. So the schema creation can happen either in first sync or incremental sync. But the probability of creating so many schemas in first sync itself is very high.
Update 1
Commenting the ALTER TABLE ALTER COLUMN statements greatly reduced the memory usage as it now takes only 300MB atmost. Have to merge those into the CREATE TABLE statements itself.
Will ask the core problem in PG Hackers mailing list.

A: A better idea entirely is to use SQL Server FDW which actually has the logic to pull in Microsoft SQL Server into PostgreSQL format (for example, Bit gets mapped to Bool). From this point
Then every three minutes,

*

*you import the foreign schema into last_fetch_schema

*if the last_fetch_schema is different from local_schema

*

*you resync schemas

*you copy all of the data over with a INSERT INTO ... SELECT ON CONFLICT DO UPDATE, and you can select only the newest data.

*you drop the foreign schema last_fetch_schema
What do you gain?

*

*On first load, you can simply use CREATE TABLE local.foo ( LIKE foreign.foo)

*You can easily compare meta-data differences

*CSVs loses types and leave you to infer things, FDW can read meta-data catalog.

*Grabbing only the newest stuff is very simply if the rows are versioned/ you don't have to send the entire database anymore.

A: This bit of comment in src/backend/utils/cache/relcache.c seems relevant:
    * If we Rebuilt a relcache entry during a transaction then its
    * possible we did that because the TupDesc changed as the result
    * of an ALTER TABLE that ran at less than AccessExclusiveLock.
    * It's possible someone copied that TupDesc, in which case the
    * copy would point to free'd memory. So if we rebuild an entry
    * we keep the TupDesc around until end of transaction, to be safe.
    */
    if (remember_tupdesc)
        RememberToFreeTupleDescAtEOX(relation->rd_att);

I don't really understand it, as who is this "someone" that might have a pointer?  This is private memory, not shared memory.  Anyway, it does seem to explain the bloat, as every 'alter table' statement in the same transaction leaves behind another copy of TupDesc for that table.  And apparently, even if you use multiple actions in one alter table, each separate action also leaves behind a copy.  But whatever the merits, this does explain an big part of the memory usage.
See the pg hackers maillist for more discussion.


text:
Q: No tidy method for objects of class coxme I'm very new to using R, or any type of coding for that matter, so this problem may be obvious, but i cant seem to get this part of my code to run as i keep getting the error in the title.
> tidy_fit1 <- tidy(fit1_full)
Error: No tidy method for objects of class coxme
I've tried restarting the session from scratch and reinstalling and updating all the packages, as well as trying to use tidy.come and tidy.coxph but none have seemed to work.


text:
Q: echo php values in table - strange behaviour, not all values are shown I am currently despairing on a for me very strange behaviour when echoing php values to html table cells.
I simply want to loop through an array and print out the values into a table but only some information is shown under special conditions.
Outside of the table the values are shown.
<?php

foreach ($mpbs_overview_tab4_bookings as $tab4_arr) {
 echo "
";
  $tab4startDate = new DateTime($tab4_arr->starttime);
  $tab4endDate = new DateTime($tab4_arr->endtime);
  echo '' . $tab4startDate->format('d.m.Y H:i') .'	';
  echo '' . $tab4endDate->format('d.m.Y') .'	';
  echo '' . $tab4_arr->username .'	';
 echo "
";
}
?>

Using this code, $tab4startDate->format('d.m.Y H:i') is shown, $tab4endDate->format('d.m.Y') not. Adding H:i to $tab4endDates format results to the fact, that it is shown again.
$tab4_arr->username is also not shown.
If I change  content to
echo "";
 echo $tab4startDate->format('d.m.Y H:i');
 echo $tab4_arr->username;
echo "	";

for testing purposes, also the username is visible...
Has anybody an idea, what I am doing wrong?
This is my array:
{"id":"185","starttime":"2017-11-26 00:00:00","endtime":"2017-11-29 00:00:00","username":"lsgit"},
{"id":"186","starttime":"2017-11-26 00:00:00","endtime":"2017-11-29 00:00:00","username":"lsgit"},
{"id":"187","starttime":"2017-11-19 00:00:00","endtime":"2017-11-22 00:00:00","username":"lsgit"},
{"id":"188","starttime":"2017-11-30 00:00:00","endtime":"2017-12-03 00:00:00","username":"lsgit"},
{"id":"189","starttime":"2017-12-05 00:00:00","endtime":"2017-12-08 00:00:00","username":"lsgit"},
{"id":"190","starttime":"2017-12-05 00:00:00","endtime":"2017-12-08 00:00:00","username":"lsgit"},
{"id":"191","starttime":"2017-12-05 00:00:00","endtime":"2017-12-08 00:00:00","username":"lsgit"}

A: You have an error here echo '' . $tab4_arr->username; .'	';
Remove the ;

A: Elements of $mpbs_overview_tab4_bookings array are json encoded. Your code should be:
<?php
echo '
';
foreach ($mpbs_overview_tab4_bookings as $tab4_arr) {
  $tab4_arr = json_decode($tab4_arr);
  echo '
';
  $tab4startDate = new DateTime($tab4_arr->starttime);
  $tab4endDate = new DateTime($tab4_arr->endtime);
  echo '' . $tab4startDate->format('d.m.Y H:i') .'	';
  echo '' . $tab4endDate->format('d.m.Y') .'	';
  echo '' . $tab4_arr->username .'	';
  echo '
';
}
echo '
';
?>

A: I'm really embarrassed about that now, but the reason was some javascript, I had working on the page...
Sorry. I did not recognize that!
Thanks a lot for your help.


text:
Q: SQL check if the value of some column is null inside a where statement and if so set it to some value I have this SQL query
SELECT *
FROM   ##tempt
WHERE  ( minstock <= 0
         AND numitems - backorder - cstock >= 1 )
        OR ( minstock >= 1
             AND numitems - backorder + minstock - cstock >= 1 )

How would I check if the value of minstock is null and if its null then set it to some number?

A: you can use isnull(minstock, 0) - it will return 0 if minstok is null.
you can also use coalesce(minstock, other_field, 0) for more than two values

A: You cannot update the column using UPDATE in the same SQL query but you can use another value if a particular column's value is NULL in the database for a given row, using the ISNULL() function, as follows:
SELECT *
FROM   ##tempt
WHERE  ( ISNULL(minstock, 0) <= 0
         AND numitems - backorder - cstock >= 1 )
    OR ( minstock >= 1
         AND numitems - backorder + minstock - cstock >= 1 )

A: SELECT *
FROM   ##tempt
WHERE  ( ISNULL(minstock,0)<= 0
     AND numitems - backorder - cstock >= 1 )
    OR ( ISNULL(minstock,0)>= 1
         AND numitems - backorder + ISNULL(minstock,0)- cstock >= 1 )


text:
Q: Working demo of state management in Polymer 2.x using Mixins Here, I'm trying to build a working demo to implement the code contained in this blog article written by @CaptainCodeman — Managing State in Polymer 2.0 - Beyond Parent / Child Binding
Share state between separated DOM elements without Redux.
I'm getting the following errors.

run.plnkr.co/:5 GET https://cdn.rawgit.com/download/polymer-cdn/2.0.0/lib/webcomponentsjs/webcomponents-lite.min.js
run.plnkr.co/:1 GET https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/my-options.html 500 ()
run.plnkr.co/:1 GET https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/shared-styles.html 500 ()
my-view2.html:26
Uncaught ReferenceError:
MyOptionsMixin is not defined at my-view2.html:26

Does anyone have a working demo of this?
my-options.html
<link rel="import" href="../bower_components/polymer/polymer-element.html">
<link rel="import" href="../bower_components/paper-checkbox/paper-checkbox.html">

<dom-module id="my-options">
  <template>

Options

      <paper-checkbox checked="{{ options.subscribe }}">Send Notifications</paper-checkbox>

  </template>

</dom-module>

my-view2.html
<link rel="import" href="../bower_components/polymer/polymer-element.html">

<link rel="import" href="my-options.html">
<link rel="import" href="shared-styles.html">

<dom-module id="my-view2">
  <template>

2

View Two

Ea duis bonorum nec, falli paulo aliquid ei eum.

Id nam odio natum malorum, tibique copiosae expetenda mel ea.Detracto suavitate repudiandae no eum. Id adhuc minim soluta nam.Id nam odio natum malorum, tibique copiosae expetenda mel ea.

Send notifications option is: [[ options.subscribe ]]

  </template>

</dom-module>

Edit: Working Demo (accepted answer forked and edited)

A: working plunker

run.plnkr.co/:5 GET https://cdn.rawgit.com/download/polymer-cdn/2.0.0/lib/webcomponentsjs/webcomponents-lite.min.js

Your

run.plnkr.co/:1 GET https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/my-options.html 500 ()
run.plnkr.co/:1 GET https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/shared-styles.html 500 ()

my-view2.html sets <base href> to polygit.org, and then tries to import my-options.html and shared-styles.html, both of which only exist in the Plunker sandbox:

<base href="https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/">
<link rel="import" href="polymer/polymer-element.html">

<link rel="import" href="my-options.html">
<link rel="import" href="shared-styles.html">

The only file imported here that needs to come from polygit.org is polymer-element.html, so you could remove the <base> tag and move the URL prefix to that import:
<link rel="import" href="https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/polymer/polymer-element.html">

my-view2.html:26 Uncaught ReferenceError:
  MyOptionsMixin is not defined at my-view2.html:26

my-view2 does not declare/instantiate my-options, so the script that defines MyOptionsMixin is never executed. You could resolve this simply by declaring it in my-view2's template:
 <dom-module id="my-view2">
    <template>
      <my-options></my-options>
    </template>
    ...
 </dom-module>


text:
Q: Lasagne / Theano gradient values I'm currently working on recurrent neural nets using Lasagne / Theano.
While training, updates are calculated using Theano's symbolic gradient.
grads = theano.grad(loss_or_grads, params)

While the gradient expression is perfectly fine in general, I'm also interested in the gradient values in order to monitor training.
My question now is if there is a built-in method to also get gradient values, which I haven't found so far, or if I'll have to do it myself.
Thanks in advance

A: I'm not aware of any lasagne function to evaluate the gradient, but you can get it yourself with simple theano function.
Say we have the following theano variables:

*

*inputs = Inputs to the network

*targets = Target outputs of the network

*loss = Value of the loss function, defined as a function of network outputs and targets

*l_hid = Recurrent layer of the network, type lasagne.layers.RecurrentLayer
Say we're interested in the gradient of the loss function w.r.t. the recurrent weights:
grad = theano.grad(loss, l_hid.W_hid_to_hid)

Define a theano function to get a numerical value for the gradient
get_grad = theano.function([inputs, targets], grad)

Now, just call get_grad for any value of the inputs and targets (e.g. the current minibatch). get_grad() doesn't need to be passed the value of the weights because they're stored as a theano shared variable.


text:
Q: Reference classes across dynamic web projects on Tomcat I have two dynamic web projects - A & B.  Project B references classes in Project A.  Project A runs great on Tomcat locally.  Project B runs on Tomcat locally too, but when I run it referencing Project A classes on Tomcat, the classes from Project A are missing in Tomcat and thus throwing a class not found exception.
Since I cannot jar the Project A files, how can I get the classes from Project A to a local Tomcat deployment so that Project B can run when referencing Project A classes?

A: If two web applications share some common classes then these classes should be refactored out of the web application code base and put into a separate library (jar file). This jar can then be added to your web applications as a dependency.


text:
Q: Spring Security Oauth - Basic access authentication needed when sending token request I've got one problem with Spring Security OAuth 2.0.
There is basic configuration of spring-security, taken from sample:
<http pattern="/oauth/token" create-session="stateless"
    authentication-manager-ref="clientAuthenticationManager"
    xmlns="http://www.springframework.org/schema/security">
    <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
    <anonymous enabled="false" />
    <http-basic entry-point-ref="clientAuthenticationEntryPoint" />
    <custom-filter ref="clientCredentialsTokenEndpointFilter"
        after="BASIC_AUTH_FILTER" />
    <access-denied-handler ref="oauthAccessDeniedHandler" />
</http>

<http pattern="/path/**" create-session="never"
    entry-point-ref="oauthAuthenticationEntryPoint"
    access-decision-manager-ref="accessDecisionManager"
    xmlns="http://www.springframework.org/schema/security">
    <anonymous enabled="false" />
    <intercept-url pattern="/path/*" access="ROLE_USER" />
    <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" />
    <access-denied-handler ref="oauthAccessDeniedHandler" />
</http>

<bean id="oauthAuthenticationEntryPoint"
    class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
    <property name="realmName" value="path" />
</bean>

<bean id="clientAuthenticationEntryPoint"
    class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
    <property name="realmName" value="path/client" />
    <property name="typeName" value="Basic" />
</bean>

<bean id="oauthAccessDeniedHandler"
    class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />

<bean id="clientCredentialsTokenEndpointFilter"
    class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
    <property name="authenticationManager" ref="clientAuthenticationManager" />
</bean>

<bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"
    xmlns="http://www.springframework.org/schema/beans">
    <constructor-arg>
        <list>
            <bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
            <bean class="org.springframework.security.access.vote.RoleVoter" />
            <bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
        </list>
    </constructor-arg>
</bean>

<bean id="oauthAuthenticationProvider" class="my.package.OAuthAuthenticationProvider" xmlns="http://www.springframework.org/schema/beans" />

<authentication-manager id="clientAuthenticationManager"
    xmlns="http://www.springframework.org/schema/security">
    <authentication-provider user-service-ref="clientDetailsUserService" />
</authentication-manager>

<authentication-manager alias="authenticationManager"
    xmlns="http://www.springframework.org/schema/security">
    <authentication-provider ref="oauthAuthenticationProvider" />
</authentication-manager>

<bean id="clientDetailsUserService"
    class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
    <constructor-arg ref="clientDetails" />
</bean>

<bean id="tokenStore"
    class="org.springframework.security.oauth2.provider.token.InMemoryTokenStore" />

<bean id="tokenServices"
    class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
    <property name="tokenStore" ref="tokenStore" />
    <property name="supportRefreshToken" value="true" />
    <property name="clientDetailsService" ref="clientDetails" />
</bean>

<bean id="userApprovalHandler"
    class="org.springframework.security.oauth2.provider.approval.TokenServicesUserApprovalHandler">
    <property name="tokenServices" ref="tokenServices" />
</bean>

<!-- authorization-server aka AuthorizationServerTokenServices is an interface
    that defines everything necessary for token management -->
<oauth:authorization-server
    client-details-service-ref="clientDetails" token-services-ref="tokenServices"
    user-approval-handler-ref="userApprovalHandler">
    <oauth:authorization-code />
    <oauth:implicit />
    <oauth:refresh-token />
    <oauth:client-credentials />
    <oauth:password />
</oauth:authorization-server>

<oauth:resource-server id="resourceServerFilter"
    resource-id="test" token-services-ref="tokenServices" />
<!-- ClientsDeailsService: Entry Point to clients database (given is in
    memory implementation) -->
<oauth:client-details-service id="clientDetails">
    <!-- client -->
    <oauth:client client-id="the_client"
        authorized-grant-types="authorization_code,client_credentials"
        authorities="ROLE_USER" scope="read,write,trust" secret="secret" />

    <oauth:client client-id="my-trusted-client-with-secret"
        authorized-grant-types="password,authorization_code,refresh_token,implicit"
        secret="somesecret" authorities="ROLE_USER" />

</oauth:client-details-service>

<sec:global-method-security
    pre-post-annotations="enabled" proxy-target-class="true">
    <sec:expression-handler ref="oauthExpressionHandler" />
</sec:global-method-security>

<oauth:expression-handler id="oauthExpressionHandler" />

<oauth:web-expression-handler id="oauthWebExpressionHandler" />

It works, when in my web.xml file looks like this:
...
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring-security.xml</param-value>
</context-param>
...
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
...
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
...
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
...
<servlet>
    <servlet-name>Dispatcher Servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
...
<servlet-mapping>
    <servlet-name>Dispatcher Servlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

But in this case, the "old part" of system doesn't work.
So I have to change Dispatcher Servlet mapping:
<servlet-mapping>
    <servlet-name>Dispatcher Servlet</servlet-name>
    <url-pattern>/somepath/*</url-pattern>
</servlet-mapping>

Now the old part works, but not Oauth Spring security. I've tried with two url-patterns:
<servlet-mapping>
    <servlet-name>Dispatcher Servlet</servlet-name>
    <url-pattern>/somepath/*</url-pattern>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

Then oauth works, old part doesn't.
I did one more try and changed:
<http pattern="/somepath/oauth/token" create-session="stateless"
    authentication-manager-ref="clientAuthenticationManager"
    xmlns="http://www.springframework.org/schema/security">
    <intercept-url pattern="/somepath/oauth/token" access="IS_AUTHENTICATED_FULLY" />
    <anonymous enabled="false" />
    <http-basic entry-point-ref="clientAuthenticationEntryPoint" />
    <custom-filter ref="clientCredentialsTokenEndpointFilter"
        after="BASIC_AUTH_FILTER" />
    <access-denied-handler ref="oauthAccessDeniedHandler" />
</http>

And now it works like this:

*

*I'm accessing address (which worked before):
https://localhost.server:8443/system/somepath/oauth/token?grant_type=password&client_id=my-trusted-client-with-secret&client_secret=somesecret&username=user&password=pass

*Web browser asks for login and password (Basic access authentication).

*I need to enter client-id in login field and secret in password field.

*Request to oauth is generated and then authentication method in my.package.OAuthAuthenticationProvider is called.
What should I change to avoid this Basic auth prompt?

A: Your problems with the servlet and filter mappings stem from the fact that Spring OAuth needs a DispatcherServlet for its OAuth related endpoints. I recommend you put those in the default servlet mapping (/), but it's up to you. In any case your one-stop-shop security configuration is a servlet configuration file, not a root context (so you need to load it with a DispatcherServlet not a ContextLoaderListener). This would be the same as in the sample (you need a servlet init param in web.xml), but there is nothing to stop you adding your own additional servlets (as long as the mappings don't clash of course).
The authentication question is different. The OAuth2 spec recommends that the /token endpoint is secured with Basic Authentication, so the prompt is a good thing in principle, although I can see that you tried to avoid it.  Putting secrets in form fields like you are doing is not really secure enough to be used in a production system, but if for some reason you need it you can use the ClientCredentialsTokenEndpointFilter (as you did).  The reason that filter is not working might have been because you are sending a GET (not a POST), which is an even worse idea for security purposes than using the filter in the first place, but I don't see the flag being set anywhere that switches on POST-only validation in the filter (although I recommend you set it if you use this thing in anger anywhere).
You haven't shown 2 Spring XML files but your web.xml refers to 2. I think the problem ultimately will be traceable to the fact that your have them mixed up or bean definitions duplicated across the two. Maybe you can clarify that (or switch to loading a single file from the DispatcherServlet as recommended above)?

A: You can avoid the login page using a configuration like this:
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    ...

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .authorizeRequests()
                .antMatchers("/").permitAll()
            .and()
                .authorizeRequests().anyRequest().hasRole("USER")
            .and()
                .csrf()
                .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/**")).disable();
        // @formatter:on
    }
    ...
}

By default this method include a login page. With this new implementation in case you try to do a request without token a 403 error page will be displayed (you also can manage this error in order to redirect to a customized page)