text:
Q: Wondering if its possible to have a file running and checking if a value in database/row Basically, If a value in Row is same for 3 days I want to remove the column, like if someone hasn't verified their account remove the account to save space.
Is there a way to make a script for this?
If so can someone help me make it?

A: Have a column like
modified timestamp default current_timestamp on update current_timestamp

in your table. Then write a query to delete entries of the table and execute it via event scheduler.

A: You can setup a cron job to run every day and execute this query on the database:
DELETE FROM table WHERE insert_date BETWEEN DATE_SUB(NOW(), INTERVAL 3 DAY) AND NOW();

Note: similar problem here.


text:
Q: Protocol buffers on Game Consoles Have anyone tried google protocol buffers on game consoles? I'm more interested in High End consoles such as PS3 or Xbox360 than handheld systems.
Things I'm interested in hearing about are:

*

*Does it compile nicely out of the box or do you need to deal with the protobuf compiler to get the generated code right right?

*Are there any controversial library dependencies that may cause problems?

*Are there any concerns about generating too much code making the code size of the game explode?

I'm thinking of using it in a C++ environment. Feel free to add more concerns you think I should consider. I'm not only looking for problems, success stories are just as interesting.

A: *

*It compiles pretty cleanly. You just need to put the protobuf headers in your include path and then link with the libraries. I haven't had any strange warnings from it either, which happens sometimes with generated code.

*I do not believe there are any dependencies. I was able to get it compiling on Windows, Linux, and Mac OS X.

*The generated files are pretty nasty, but I haven't had any problems with them adding to the code size, or drastically increasing build times.

I have been able to easily integrate protobuf with other networking libraries (such as POCO). My experience was pretty positive, but then it was just a test project, nothing for production.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Smallest sphere intersecting lines in R^3 I have N lines in R^3 (that are very likely skew). I'm looking for an efficient method of computing the radius (and position) of the smallest sphere that intersects every line.
I suspect that there's a solution related to the 'smallest sphere enclosing points' problem, but I failed to find it.
(The purpose is to be able to do bundle adjustment without needing to make the inferred point positions visible to the optimizer).

A: The distance from a point to a line is a convex function, and the maximum of convex functions in convex, so locating a point that minimizes the maximum of its distances to the lines is a convex problem, therefore it should be relatively easy to solve using modern software for convex optimization.

A: Here is a starting point. For each line $L$ in $\newcommand{\bR}{\mathbb{R}}$ $\bR^3$ we denote by $C_r(L)$ the cylinder of axis $L$ and radius $R$. Given  $N$ lines you need to find  the smallest $r$ such that the convex sets $C_r(L_1),\dotsc, C_r(L_N)$ have nonempty overlap.
According to Helly's theorem,  a collection of convex subsets  in $\bR^k$ has nonempty overlap if and only if, any subcollection of $k+1$ subsets in that  collection has a nonempty overlap. Thus, in your case, you need to make sure  that  any four cylinders in your collection  have nonempty overlap.
This reduces the problem to $N=4$ which looks less scary, yet still challenging.
If we are given $4$-lines  $L_1,\dotsc, L_4$ passing through   distinct point $p_1,\dotsc, p_4$  and spanned by the unit vector $\newcommand{\bu}{\boldsymbol{u}}$ $\bu_1,\dotsc,\bu_4$, then the distance  from a point $x$ to the line $L_k$ is achived along a segment $[x, y]$ where,
$$y\in L_k,\;\; [x,y]\perp L_k. $$
This means
$$y= p_k+t\bu_k,\;\;  (x-p_k -t\bu_k, \cdot \bu_k)=0, $$
so that
$$ t=(x-p_k, \bu_k),\;\; y= p_k +(x-p_k, \bu_k)\bu_k, $$
$${\rm dist}(x, L_k)^2=\bigl| x-p_k -(x-p_k,\bu_k)\bu_k\;\bigr|^2=|x-p_k|^2-(x-p_k,\bu_k)^2. $$
At this point some ugly, but  machine approachable algebra is needed.


text:
Q: Rails Autocomplete with Ajax Find or create I am new to rails so please explain it like i'm a three year old :)
i cannot get this to trigger on autocompletion
view
 <div class="controls">
  <%= f.hidden_field :vehicle_id, :class => 'text_field', :id =>'veh_id' %>
  <%= f.autocomplete_field :vehicle_reg, autocomplete_vehicle_reg_number_vehicles_path, :id_element => '#veh_id', :class => 'text_field ui-autocomplete-input', :update_elements => {}  %>
</div>

java
$(document).ready(function() {
    console.log('Ready')
    $('#veh_id').bind('insertion-callback',
        function() {
            $('.autocomplete').bind('railsAutocomplete.select', function(event, data){
                console.log('Hello World')
                });

            });
    });


text:
Q: How does the debugger get type information about an object initialized to null? If an object is initialized to null, it is not possible to get the type information because the reference doesn't point to anything.
However, when I debug and I hover over a variable, it shows the type information. Only the static methods are shown, but still, it seems to know the type. Even in release builds.
Does the debugger use other information than just reflection of some sort to find out the datatype? How come it knows more than I? And if it knows this, why isn't it capable of showing the datatype in a NullReferenceException?

A: Jared's answer is of course correct. Just to add a little to it:

when I debug and I hover over a variable, it shows the type information

Right. You have a bowl. The bowl is labelled "FRUIT". The bowl is empty. What is the type of the fruit in the bowl? You cannot say, because there isn't any fruit in the bowl. But that does not mean that you know nothing about the bowl. You know that the bowl can contain any fruit.
When you hover over a variable then the debugger can tell you about the variable itself or about its contents.

Does the debugger use other information than just reflection of some sort to find out the datatype?

Absolutely. The debugger needs to know not just what is the type of the thing referred to by this reference but also what restrictions are placed on what can be stored in this variable. All the information about what restrictions are placed on particular storage locations are known to the runtime, and the runtime can tell that information to the debugger.

How come it knows more than I?

I reject the premise of the question. The debugger is running on your behalf; it cannot do anything that you cannot do yourself. If you don't know what the type restriction on a particular variable is, it's not because you lack the ability to find out. You just haven't looked yet.

if it knows this, why isn't it capable of showing the datatype in a NullReferenceException?

Think about what is actually happening when you dereference null. Suppose for example you do this:
Fruit f = null;
string s = f.ToString();

ToString might be overloaded in Fruit. What code must the jitter generate? Let's suppose that local variable f is stored in a stack location. The jitter says:

*

*copy the contents of the memory address at the stack pointer offset associated with f to register 1

*The virtual function table is going to be, lets say eight bytes from the top of that pointer, and ToString is going to be, let's say, four bytes from the top of that table. (I am just making these numbers up; I don't know what the real offsets are off the top of my head.) So, start by adding eight to the current contents of register 1.

*Now dereference the current contents of register 1 to get the address of the vtable into register 2

*Now add four bytes to register 2

*Now we have a pointer to the ToString method...

But hold on a minute, let's follow that logic again. The first step puts zero into register 1, because f contains null. The second step adds eight to that. The third step dereferences pointer 0x00000008, and the virtual memory system issues an exception stating that an illegal memory page has just been touched. The CLR handles the exception, determines that the exception happened on the first 64 K of memory, and guesses that someone has just dereferenced a null pointer. It therefore creates a null reference exception and throws it.
The virtual memory system surely does not know that the reason it dereferenced pointer 0x00000008 was because someone was trying to call f.ToString(). That information is lost in the past; the memory manager's job is to tell you when you touched something you don't have any right to touch; why you tried to touch memory you don't own is not its job to figure out.
The CLR could maintain a separate side data structure such that every time you accessed memory, it made a note of why you were attempting to do so. That way, the exception could have more information in it, describing what you were doing when the exception happened. Imagine the cost of maintaining such a data structure for every access to memory! Managed code could easily be ten times slower than it is today, and that cost is borne just as heavily by correct code as by broken code. And for what? To tell you what you can easily figure out yourself: which variable that contains null that you dereferenced.
The feature isn't worth the cost, so the CLR does not do it. There's no technical reason why it could not; it's just not practical.

A: It seems like you're confusing the type of the reference with the type of the value that it points to.  The type of the reference is embedded into the DLL metadata and as readily accessible by the debugger.  There is also aditional information stored in the associated PDB that the debugger leverages to provide a better experience.  Hence even for null references a debugger can determine information like type and name.
As for NullReferenceException.  Could it also tell you the type on which it was querying a field / method ... possibly.  I'm not familiar with the internals of this part of the CLR but there doesn't seem to be an inherent reason why it couldn't do so.
But I'm not sure the added cost to the CLR would be worth the benefit.  I share the frustration about the lack of information for a null ref exception.  But more than the type involved I want names!  I don't care that it was an IComparable, i wanted to know it was leftCustomer.
Names are somethnig the CLR doesn't always have access to as a good portion of them live in the PDB and not metadata.  Hence it can't provide them with great reliability (or speed)


text:
Q: jQuery function not working if anchored link clicked in different page My simple jQuery function works fine if I click an anchored link on page-1 (body turns black fine) BUT if I have the same anchored link on another page-2 to link back and anchor to my page-1 the function doesn't work? It goes back to page-1 fine but body on page-1 doesn't turn black as expected?
HTML on page-1:

  Key features

HTML on page-2:

  Key features

jQuery:
$("#offcanvas a").click(function(){
    $('.offcanvas').offcanvas('hide');
    $("body").css('background-color', '#000000')
});

Many thanks in advance for your help.
B]

A: please use below html structure
you have not define id on html structure

    Key features

A: So I manage to find the solution, this works:
$("#offcanvas a").on("click", function() {
    if (window.location.hash) {
      $("body").css('background-color', 'black');
}

:)


text:
Q: what is the proper way of writing the following php echo command please somebody help me make this correct. I have no knowledge in php
echo bowob_api_get_code(/* BOWOB_APP_ID */, /* BOWOB_SERVER_ADDRESS */);

am supposed to substitute values BOWOB_APP_ID with somevalue 67890 and BOWOB_SERVER with http://euwest1.bowobcloud1.com/
I did it as shown below, but i keep getting error on this line
echo bowob_api_get_code('67890, http://euwest1.bowobcloud1.com/ ');

A: As it is right now, you have a single string argument, whereas you need an integer and a string.
echo bowob_api_get_code(67890, "http://......./");


text:
Q: configuring the image file reducer Google Firestore The following google cloud function properly uploads an image, but I would also like to compress the image as to avoid unnecessary charges due to large files being uploaded.  I am using the image reducer extension from Firebase and it works but the issue is that the image file no longer shows up on my user table.  is there something i need to configure in the extension so that the image url in the user table is overwritten by the reduced image??
exports.uploadImage = (req, res) => {
  const BusBoy = require("busboy")
  const path = require("path")
  const os = require("os")
  const fs = require("fs")

  const busboy = new BusBoy({ headers: req.headers })

  let imageToBeUploaded = {}
  let imageFileName

  busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
    if (mimetype !== `image/jpeg` && mimetype !== `image/png`) {
      return res.status(400).json({ error: `Not an acceptable file type` })
    }

    // my.image.png => ['my', 'image', 'png']
    const imageExtension = filename.split(".")[filename.split(".").length - 1]
    // 32756238461724837.png
    imageFileName = `${Math.round(
      Math.random() * 1000000000000
    ).toString()}.${imageExtension}`
    const filepath = path.join(os.tmpdir(), imageFileName)
    imageToBeUploaded = { filepath, mimetype }
    file.pipe(fs.createWriteStream(filepath))
  })

  busboy.on("finish", () => {
    admin
      .storage()
      .bucket(config.storageBucket)
      .upload(imageToBeUploaded.filepath, {
        resumable: false,
        metadata: {
          metadata: {
            contentType: imageToBeUploaded.mimetype
          }
        }
      })
      .then(() => {
        const imageUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media`
        return db.doc(`/users/${req.user.uid}`).update({ imageUrl })
      })
      .then(() => {
        return res.json({ message: "image uploaded successfully" })
      })
      .catch(err => {
        console.error(err)
        return res.status(500).json({ error: "something went wrong" })
      })
  })
  busboy.end(req.rawBody)
}

A: The Resize Images extension only handles the resizing of the image in Cloud Storage. It does not update data in any other location, including Cloud Firestore. If you need such functionality, you'll need to create it yourself.
Also see:

*

*this discussion on the extensions open-source repo about allowing to specify a callback that gets invoked after resizing.


text:
Q: Obter diferença entre horas Definida/Atual Gostaria de obter quantas horas se passou, de uma determinada data, para a data atual. Por exemplo:
day = "Thu May 19 2016 05:00:00 GMT-0300 (BRT)";
today = "tue May 23 2016 09:00:00 GMT-0300 (BRT)";

Variável day possui a data inicial, a partir dessa data gostaria de começar a contar as horas. E a variável today possui a data atual.

A:

day = new Date("Thu May 19 2016 05:00:00 GMT-0300");
today = new Date("tue May 23 2016 09:00:00 GMT-0300");

document.write(diferencaDias(day,today));

function diferencaDias(data1, data2){
    var dif =
        Date.UTC(data1.getYear(),data1.getMonth(),data1.getDate(),0,0,0)
      - Date.UTC(data2.getYear(),data2.getMonth(),data2.getDate(),0,0,0);
      dif=Math.abs((dif / 1000 / 60 / 60));
      difH=Math.abs(today.getHours()-day.getHours());
      difM=Math.abs(today.getMinutes()-day.getMinutes());
      difS=Math.abs(today.getSeconds()-day.getSeconds());
    return ((dif+difH)+"Horas   "+difM+"Minutos    "+difS+"Segundos");
}

A: Você pode usar a biblioteca Moment.js e fazer algo parecido com isso:

var today  = moment("Tue May 23 2016 09:00:00 GMT-0300 (BRT)");
var day = moment("Thu May 19 2016 05:00:00 GMT-0300 (BRT)");

var duracao = moment.duration(today.diff(day));
var horas = duracao.asHours();
console.log(horas)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>

A: Resposta simplista talvez, mas se só queres as horas de diferênça podes fazer :
var horas = Math.abs(data_A - data_B) / 36e5;

*

*Math.abs para dar um numero positivo e ser assim indiferente a ordem das datas

*/ 36e5 porque esse valor é o mesmo que 3600000 que é 60 segundos x 60 minutos x 1000 milisegundos. Isto porque datas em javascript são em milisegundos.

Exemplo:

var day = "Thu May 19 2016 05:00:00 GMT-0300 (BRT)";
var today = "tue May 23 2016 09:00:00 GMT-0300 (BRT)";

var horas = Math.abs(new Date(day) - new Date(today)) / 36e5;
alert(horas); // 100


text:
Q: How would I pass my program a string from the start menu search in Windows (like ping)? When my program is launched from the start menu shortcut I would like to send it a string. I see that ping does this because I can type in ping [and a domain] and it will pop the cmd window and do the ping. However I think this must be working differently than what I have setup because even though the shortcut to the program is in the start menu, it will disappear when I am searching for it as soon as I start typing any parameters. Then windows will just launch a windows explorer window attempting to search for what I typed. What must I do to get it to register like the ping program?
Also, do you think it is just using the string[] args to capture this?

A: Did you try running your program from CMD and passing the parameters from there?  Something like: <path to your executable> <arg1> <arg2>...<arg N>
And yes, any parameters that are given to the program (as shown above) are then available in the args variable that the main method takes.


text:
Q: Possible to get user's photos in FB messenger extension using JS in webview? I have a Facebook chat extension with a Webivew accessible via a persistent menu button.
On the Webview I load the messenger Extensions.js code and I can query for the user's page-scoped ID, permissions allowed, etc.
I'd like to be able to let the user share their photos, is there any way I can get access to that in the JS on my Webview? Or even on the server. Something like:
curl -X GET "https://graph.facebook.com/v2.6/<PAGE_SCOPED_USER_ID>?fields=photos,first_name,last_name,profile_pic,locale,timezone,gender&access_token=PAGE_ACCESS_TOKEN"

except the photos field doesn't work of course:
{u'error': {u'code': 100,
  u'fbtrace_id': u'xxxx/xxxxx',
  u'message': u'(#100) Tried accessing nonexisting field (photos) on node type (MessengerPageScopedID)',
  u'type': u'OAuthException'}}

I have the user_profile and user_messaging permissions currently.
So far I have only been able to get the standard fields (listed here) to work which are just first, last, gender, etc.
I'm fine with the user needing to allow more permissions (and clicking to add something), but I wanted to avoid a non-messenger auth flow like most FB apps. I assumed the point of messenger was to make less friction in that way.
I'm curious if I'm missing something or if there actually isn't a way to get other FB user data from Messenger chat extensions.
Thanks!

A: The only way I've seen this done is to create your own Facebook Login page on the web using both the Login Javascript SDK and the Messenger Extensions SDK. Basically all you need to do is add both of these SDKs in the Javascript and create an html button for the user to press on to trigger the login. Don't forget to add the permissions you need to the Login SDK.
You can send a link to this login page via your bot in a url button. Make sure you enable Messenger Extensions on that button. When the user clicks on the button a webview will open with the Facebook login page you've created.
If the user is already logged in to Facebook they should just see a page asking them to accept the new permissions. Once they've accepted the permissions the page should return both the app-scoped-id (and an access token) as well as the page-scoped-id (Messenger id). You've now linked the app-scoped-id and the page-scoped-id and you can use this app-scoped-id and access token to query the Graph API for the permissions you asked for.
It's annoying having to take people out of the bot flow and into a webview but it's not a terrible user experience.


text:
Q: Can you Distribute a Ruby on Rails Application without Source? I'm wondering if it's possible to distribute a RoR app for production use without source code?  I've seen this post on SO, but my situation is a little different.  This would be an app administered by people with some clue, so I'm cool with still requiring an Apache/Mongrel/MySQL setup on the customer end.  All I really want is for the source to be protected.  Encoding seems a popular way to go for distributing PHP apps (eg: Helpspot).
I've found these potential solutions:

*

*Zenobfuscate - not all types of Ruby code is supported however, so that counts that out

*Ruby Encoder - may be the best option, as their PHP encoder looks alright (I haven't tried it however) but it's not available yet.  I've used IONcube for PHP before and it worked well, but it doesn't seem that IONcube is interested yet.

*Slingshot - it was mentioned in the other SO post, but it solves a different problem to mine and the source is still visible.

*RubyScript2Exe - from the doco, it's not production ready, so that counts that out.

I've heard that potentially using JRuby and distributing bytecode might be a way to achieve this, but I've never used JRuby so I'm not sure what's involved.
Can anyone offer any ideas and/or known examples?  Ideally I'd love to have some kind of automated build scenario as well.

A: If you release the source, obfuscated or otherwise, your app will be pirated.  See, for example, Mint.  It depends on what you're building, but you may find that you're better off releasing the app as a hybrid of sorts:  A hosted app with a well-defined API, and a component that runs on the customer's server.  As long as the true value of your product lives on the server side, you don't need to obfuscate your code, and you can just release the source code unmodified.  Additionally, this may also give you the opportunity to reach clients running, say, PHP rather than Ruby.  See, for example, Google Analytics, HopToad, Scout, etc, etc.

A: Your best option right now is to use JRuby. A little bit of background: My company (BitRock) works with many proprietary and commercial open source vendors. We help them package their server software, which is typically based on PHP, Java or Ruby together with a web server or application server (Apache, Tomcat), the language runtime and a database (typically Postgres, MySQL) into a self-contained, easy to use installer. We have a large number of PHP-based customers (including HelpSpot, which you mention) but also several Rails-based ones. In the case of the RoR customers the norm is to use JRuby together with Tomcat or Glassfish although in some cases we also bundle a native Ruby interpreter to run specific scripts that rely on libraries not yet ported to JRuby (usually not core to the application). JRuby has matured quickly and in many cases it actually runs their code faster than regular Ruby. You will need to also consider that although porting your code to JRuby is fairly straightforward, you will need to invest some time on that. You may want to check JRuby Stack which is a free installer of everything you need to get started. Good luck!

A: You can, but it wouldn't do anything to prevent somebody from reverse-engineering or modifying it. I remember there was an article about similar attempts to obfusticate Perl and how they could be effectively bypassed by a debugger and 5 minutes of effort.

A: If you can't wait for the delivery of RubyEncoder, then I think ZenObfuscate is the most promising. Though it may require some modifications to your source code, they do say this on their site:

ZenObfuscate costs $2500 for a site license or is individually negotiable for other licensing schemes. Yes, that is expensive. That was on purpose. But don't let that thwart you too much. If your product is really cool and we want to see it succeed, we'll make it work. "Really cool" is not freecell.

Of course, for $2500 (or more), you'd hope to get a few tweaks to the compiler that'd make your codebase fully supported. It might be worth engaging them in the conversation.

A: You can also take a look at Mingle from ThoughtWorks studios as an example of using JRuby for this.
It's a Ruby on Rails app, they run it using JRuby. They've customized jruby to load encrypted .rb files.

A: Take a look at JumpBox.
I've had conversations with them on the topic, and they seem to have a solution that will work soon for Rails apps.

A: I'm wondering if you could just "compile" the ruby code into an executable using something like RubyScript2Exe ?
To be honest I haven't used it but it seems like it could be what you want, even if it just packages up the scripts with the interpreter into a single executable.


text:
Q: How would I .show( ) a div when scrolling Lets say I had a website full of pictures posted vertically. As a scroll down, I want to use javascript/jquery to load in their description (and have the previous description hide). How would I go about doing this?
Please let me know. Thanks.
An example would be this page here.
https://stackoverflow.com/about
As you scroll, many jquery events take place.

A: Using something like scroll to etc that you can then find the co-ordinates / location and then perform the script you require etc

A: Could try something like the jquery appear plugin
It fires when the element comes into view.
Could do it manually as well, when scrolling, check all the container elements holding your hidden description to see if they fall within the viewable browser and show their description elements if so.


text:
Q: Securing API Secrets On Clients Using Custom API I am writing a mobile application using Phonegap/Cordova.
The mobile application needs information from a server-side application, which I have written. I created an API to get this information.
One of the first things the API does is verify the mobile application is an application which I have written.
It does this using a public API key and a secret API key. (They are used in generating the authorization header).
The authorization header is generated on the mobile application and on the server-side application and the server will check them against eachother for discrepancies.
It goes something like this:
Mobile Application (Javascript/jQuery)
var SIGNATURE = SHA512( MY_APP + MY_PUBLIC_API_KEY + TIMESTAMP + NONCE + MY_SECRET_API_KEY );
var auth = "path=MY_APP,key=MY_PUBLIC_API_KEY,time=TIMESTAMP,nonce=NONCE,signature=SIGNATURE"
$.ajax( {
    type = "POST",
    url: url,
    headers : {
        "Authorization" : auth
    }
} );

Server Side (PHP)
// there is some regex to "decode" the auth header
// now, recreate the signature from the public variables in the auth header and check for a match (note: this includes fetching the secret from an xml file as it is not in the public information)

The problem obviously lies in the fact that I need the secret API key to generate the signature on the client side.
After reading articles online, a lot of people have said to store the secret on the server (then use the server as an intermediary), but I believe that only applies if you're using a third party API.
This also just moves the problem away from the client. What stops somebody from just making a call to the intermediary, which will just stick the secret on anyway?
A very similar solution is to store the secret on the server and fetch it when the app loads, but surely that's the same problem...what's stopping somebody from simply going to api.mydomain.com/getsecretkey?
Storing secrets on the client is just not viable. Especially with phonegap. So how do people do it?
Any and all help is appreciated.

A: On the server you may detect your "authentication" data first, like checking the required basic data, user-agent and etc etc.
Second, try to encrypt your data, you may use the app secret first to get a new key to your server (for the next session), and then use the retrivered new key as next encryption key.
 End to End encryption are suggested.
JWT.io liblaries may help those issue. https://jwt.io/
And your server may refuse the connection or send the error code if those requirements didn't meet.

A: I think that the bottom line here is just: "you can't do it."  The work is being done on the user's machine, using source code that is also present on the machine.  Therefore, a determined thief can discern all of your "secrets," and there's nothing that you can do about it.
You can add various forms of checks to your host that simply look for something that is required to be present in every request, and to refuse to respond (even, "just drop the packet") if this characteristic is not there. This would, for example, allow you to ignore "junk" requests that are being thrown at you by some script-kiddie's robot:   they'd have to have a copy of your client-side application in order to figure out how to phrase their message correctly, and that automatically implies "a more-determined, less-than-casual thief."  (Many of the attackers on the Internet are just trying to make noise and cause mischief, and it's worth your while (IMHO) to do a little something to let you ignore such things quickly.)


text:
Q: Is there anyway to export with selected area on map with [Openlayers]? AS i am trying to export map with open layers. i am able to export map but by default it exports all the map.
I want to export selected area on the map. is there anyway to do it with Openlayers ?
I'm following this link to export map with Openlayers:
https://openlayers.org/en/latest/examples/export-map.html


text:
Q: Cannot send email using Exim and Dovecot I've been trying to debug this issue since last week, but I have no clue on what's going on, I have tried to find the answers myself but no luck.
I've been trying to send emails, from info@domain.com to info@domain.com, or from myaccount@other-domain.com to info@domain.com, but the recipient was always flagged as never_users.
it always produces this kind of log in the main.log file:
2022-07-19 12:51:56 1oDfDA-0000gU-4D <= info@mail.domain.com H=smtpbrn09tsel.my-isp-provider.com [114.124.216.1] P=esmtpa A=dovecot_plain:info S=690 id=9b34c0ae-bee0-c656-dc92-5ef332cf9f8b@domain.com
2022-07-19 12:51:56 1oDfDA-0000gU-4D User 0 set for mail_test_transport transport is on the never_users list
2022-07-19 12:51:56 1oDfDA-0000gU-4D == root@mail.domain.com <info@domain.com> R=mail_test_router T=mail_test_transport defer (-29): User 0 set for mail_test_transport transport is on the never_users list
2022-07-19 12:51:56 1oDfDA-0000gU-4D ** root@mail.domain.com <postmaster@mail.domain.com>: retry timeout exceeded
2022-07-19 12:51:56 1oDfDA-0000gY-6l <= <> R=1oDfDA-0000gU-4D U=exim P=local S=2022
2022-07-19 12:51:56 1oDfDA-0000gU-4D Completed
2022-07-19 12:51:56 1oDfDA-0000gY-6l User 0 set for mail_test_transport transport is on the never_users list
2022-07-19 12:51:56 1oDfDA-0000gY-6l == root@mail.domain.com <info@mail.domain.com> R=mail_test_router T=mail_test_transport defer (-29): User 0 set for mail_test_transport transport is on the never_users list
2022-07-19 12:51:56 1oDfDA-0000gY-6l ** root@mail.domain.com <postmaster@mail.domain.com>: retry timeout exceeded
2022-07-19 12:51:56 1oDfDA-0000gY-6l root@mail.domain.com <postmaster@mail.domain.com>: error ignored
2022-07-19 12:51:56 1oDfDA-0000gY-6l Completed

Note that, this is my config for the never_users:
never_users = root

When I run exim -bt info, it produces this:
root@mail.domain.com
    <-- postmaster@mail.domain.com
    <-- info@mail.domain.com
  router = mail_test_router, transport = mail_test_transport

it looks like the info@domain.com is translated to root@mail.domain.com, CMIIW, but I have no idea how to fix this.

A: I have finally found the workaround for this, and put it here, hopefully, it can be useful for anyone having the same issue.
So I decided to create another user:
useradd -s /sbin/nologin mail-test
passwd mail-test

Then I commented out 2 lines in the exim.conf:
web_test_transport:
  driver = pipe
  command = /usr/bin/php /var/www/html/mail-exim/artisan mail:process
  #user = root
  #group = root

Then, I restarted the exim service.
After that I sent an email to mail-test@domain.com, and voila! it's not marked as never_users anymore.


text:
Q: How method calls are resolved by argument in category classes in Objective C? I have a root class and number of child classes.
I have also a DataManager class that is supposed to hold static methods in various categories that act on particular child of this root class.
Let's say for root class R, Child classes are C1 & C2.
For C1, I have category called DataManager+C1.
For C2, I have category called DataManager+C2.
I have a base DataManager class where I have declared this method - from where it is accessed everywhere - and there are no other declarations:
//DataManager.h
+ (NSDictionary *) Method1 : (DataModelRoot*) R;
//Note that R is my root class. Individual class implementations belong to DataManager+C1.m, DataManager+C2.m etc.

Implementation of Method1 lies in DataManager+C1 as well as DataManager+C2.
But I fail to see polymorphic behaviour.
That is, when Method1 invocation of DataManager+C2 is expected, the one inside DataManager+C1 is invoked, although the call itself initiates from DataManager+C2 source file. (the caller can be any DataManager category though - this is one extreme case).
How do number of categories on objects lying in same class hierarchy resolve function calls?
PS:
Note again, that the above method Method1 is ONLY EXPOSED in .h file of one class (plain DataManager.h) with root class as the argument. I assume this will ensure proper invocation using child object type, but it's failing.

A: Objective-C supports polymorphism on class methods when the target of the message actually is polymorphic.
Example:
[DataManager Method1:nil];

... would not select a target polymorphically because the target is the concrete class DataManager. It would just always send the message to the implementation in DataManager.
If, on the other hand, the target is a dynamically determined, there's actual polymorhism as expected. A typical example is an instance method implementation in the same class or a subclass:
- (void)foo
{
    [[self class] Method1:nil];
}

This would indeed call the closest overridden implementation of Method1: and thus granting polymorphic behavior.
Sidenote: The behavior described above is not affected by categories. Provided there are no name clashes, categories have little influence on how messages are dispatched.


text:
Q: Possible to bind virtual element without binding to a container? In the current version of jQuery Mobile it seems to be necessary to keep all data-role="page" elements on one level (at least when one wants to establish links between them). Since I am using knockout to dynamically produce pages, I have the requirement to bind virtual elements directly, e.g. in

I want to bind one model A to page1 and one model B to the virtual element (which is a template: foreach binding in the real application). More detailed fiddle: http://jsfiddle.net/timvdh/t3Cyd/3/
Is this doable somehow?

A: With the limited information I would say you have 3 options:
(1) Wrap your virtual element in another virtual element or div and use the with binding.

(2) Use the template binding in the virtual element and use the data property to supply a new context.

(3) Create your own custom binding that supports virtual elements and apply bindings to descendants. This is just an example to lead you in the right direction:
ko.bindingHandlers.bindModel = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel, context) {
        var newContext = new ModelA();
        ko.applyBindingsToDescendants(newContext, element);
        return { controlsDescendantBindings: true };
    }
};
ko.virtualElements.allowedBindings.bindModel = true;


text:
Q: How to add an existing folder to a VS project which might contain some dlls of same name? I have written an application(C# project) which i want it to be launched through website (clickonce application).
I want to add an existing folder which contains some dlls, xml files.
It has its own folder structure. I want to add this folder to my project.
Problem is, few dlls which this folder contains are also present in my project and its under references. Both dlls are of different version so I have to add that folder..
Can you please let me know a way to add an existing folder to a project?
Thanks in advance.

A: You can't do this.
Mutliple versions of the same class library may be stored in the GAC, a special folder; but within a project, you're working with a standard file system, which can't contain multiple files with identical names side by side (even if of different casing, when on Windows.)
You could probably get away with storing them in a Solution Folder (one maintained within the solution itself, not physically, but a virtual folder) and have files stored in there from different physical locations, but I've never played with this to be certain how well it would pan out. Also, it could just mount confusion, so I'd steer blear, personally.


text:
Q: R: How do I rotate x-axis labels in a ctreeobj from the party package I'm using the party package in R to create a decision tree with some data. My dependent variable has some long strings and so the horizontal presentation of the x-axis labels means that all levels of my dependent variable are not showing.
Using the survey data from the MASS package as a trivial example, with the party package loaded:
 data(survey)
 #remove missing value
 survey2 <- subset(survey, !is.na(Clap))
 TreeResults <- ctree(Clap ~ Sex + Exer + Smoke, data=survey2)
 plot(TreeResults)

The labels I wish to rotate are for Clap, and I would like these to print at 45 degrees for each node. My real data has two terminal nodes, just like this example.
I have looked at node_barplot and I cannot see an option within there to modify the orientation of the x-axis labels.
Could someone advise how to do the label reorientation?
Thanks in advance.
Update: printing the labels up the sides as per the suggestion produced this plot:

A: Did you want something like?
plot(TreeResults,tp_args = list(beside=F))

UPDATE OP indicated this was not appropriate.
Unfortunately I cant see an easy fix. You can redefine the node_barplot() function as follows:
altbp<-function (ctreeobj, col = "black", fill = NULL, beside = NULL,
    ymax = NULL, ylines = NULL, widths = 1, gap = NULL, reverse = NULL,
    id = TRUE,rot=45)
{
    getMaxPred <- function(x) {
        mp <- max(x$prediction)
        mpl <- ifelse(x$terminal, 0, getMaxPred(x$left))
        mpr <- ifelse(x$terminal, 0, getMaxPred(x$right))
        return(max(c(mp, mpl, mpr)))
    }
    y <- response(ctreeobj)[[1]]
    if (is.factor(y) || class(y) == "was_ordered") {
        ylevels <- levels(y)
        if (is.null(beside))
            beside <- if (length(ylevels) < 3)
                FALSE
            else TRUE
        if (is.null(ymax))
            ymax <- if (beside)
                1.1
            else 1
        if (is.null(gap))
            gap <- if (beside)
                0.1
            else 0
    }
    else {
        if (is.null(beside))
            beside <- FALSE
        if (is.null(ymax))
            ymax <- getMaxPred(ctreeobj@tree) * 1.1
        ylevels <- seq(along = ctreeobj@tree$prediction)
        if (length(ylevels) < 2)
            ylevels <- ""
        if (is.null(gap))
            gap <- 1
    }
    if (is.null(reverse))
        reverse <- !beside
    if (is.null(fill))
        fill <- gray.colors(length(ylevels))
    if (is.null(ylines))
        ylines <- if (beside)
            c(3, 2)
        else c(1.5, 2.5)
    rval <- function(node) {
        pred <- node$prediction
        if (reverse) {
            pred <- rev(pred)
            ylevels <- rev(ylevels)
        }
        np <- length(pred)
        nc <- if (beside)
            np
        else 1
        fill <- rep(fill, length.out = np)
        widths <- rep(widths, length.out = nc)
        col <- rep(col, length.out = nc)
        ylines <- rep(ylines, length.out = 2)
        gap <- gap * sum(widths)
        yscale <- c(0, ymax)
        xscale <- c(0, sum(widths) + (nc + 1) * gap)
        top_vp <- viewport(layout = grid.layout(nrow = 2, ncol = 3,
            widths = unit(c(ylines[1], 1, ylines[2]), c("lines",
                "null", "lines")), heights = unit(c(1, 1), c("lines",
                "null"))), width = unit(1, "npc"), height = unit(1,
            "npc") - unit(2, "lines"), name = paste("node_barplot",
            node$nodeID, sep = ""))
        pushViewport(top_vp)
        grid.rect(gp = gpar(fill = "white", col = 0))
        top <- viewport(layout.pos.col = 2, layout.pos.row = 1)
        pushViewport(top)
        mainlab <- paste(ifelse(id, paste("Node", node$nodeID,
            "(n = "), "n = "), sum(node$weights), ifelse(id,
            ")", ""), sep = "")
        grid.text(mainlab)
        popViewport()
        plot <- viewport(layout.pos.col = 2, layout.pos.row = 2,
            xscale = xscale, yscale = yscale, name = paste("node_barplot",
                node$nodeID, "plot", sep = ""))
        pushViewport(plot)
        if (beside) {
            xcenter <- cumsum(widths + gap) - widths/2
            for (i in 1:np) {
                grid.rect(x = xcenter[i], y = 0, height = pred[i],
                  width = widths[i], just = c("center", "bottom"),
                  default.units = "native", gp = gpar(col = col[i],
                    fill = fill[i]))
            }
            if (length(xcenter) > 1)
                grid.xaxis(at = xcenter, label = FALSE)
            grid.text(ylevels, x = xcenter, y = unit(-1, "lines"),
                just = c("center", "top"), default.units = "native",
                check.overlap = TRUE,rot=rot)
            grid.yaxis()
        }
        else {
            ycenter <- cumsum(pred) - pred
            for (i in 1:np) {
                grid.rect(x = xscale[2]/2, y = ycenter[i], height = min(pred[i],
                  ymax - ycenter[i]), width = widths[1], just = c("center",
                  "bottom"), default.units = "native", gp = gpar(col = col[i],
                  fill = fill[i]))
            }
            if (np > 1) {
                grid.text(ylevels[1], x = unit(-1, "lines"),
                  y = 0, just = c("left", "center"), rot = 90,
                  default.units = "native", check.overlap = TRUE)
                grid.text(ylevels[np], x = unit(-1, "lines"),
                  y = ymax, just = c("right", "center"), rot = 90,
                  default.units = "native", check.overlap = TRUE)
            }
            if (np > 2) {
                grid.text(ylevels[-c(1, np)], x = unit(-1, "lines"),
                  y = ycenter[-c(1, np)], just = "center", rot = 90,
                  default.units = "native", check.overlap = TRUE)
            }
            grid.yaxis(main = FALSE)
        }
        grid.rect(gp = gpar(fill = "transparent"))
        upViewport(2)
    }
    return(rval)
}

all this did was add rot= to the grid.text call when beside=T
then call the following:
plot(TreeResults,terminal_panel=altbp(TreeResults,ylines=1.2, gap=0.05,rot=45))

SUMMARY:
you can hack the node_barplot function a painless way to do it would be as follows:
altbp<-node_barplot
body(altbp)[[8]][[3]][[3]][[23]][[3]][[5]]<-substitute(
grid.text(ylevels, x = xcenter, y = unit(-1, "lines"), just = c("center",
    "top"), default.units = "native", check.overlap = TRUE,rot=45)
)
plot(TreeResults,terminal_panel=altbp(TreeResults))

and use the altbp which will rotate text by 45 degrees.


text:
Q: Using surf to make a 3d imshow I'm struggling with some difficulties to understand how surf really works and how can I use it's approach in my context. I'm trying to use surf from Mayavi to plot a 3D representation of a 2D imshow(). I do know know if it's the correct path so I'm able to use other suggestions also.
Basically I have reached this so far: data is an array that contains the values respectfully to x and y coordinates. Thus, the shape of data is (50L, 50L) and each element corresponds to the value of the pairs of my 50*50 elements.
imshow(data, cmap=cm.jet, origin='upper', interpolation=None) # My 2D imshow... working fine here.

# Trying to have a 3D representation
nx = linspace(0, 4, 50)
ny = linspace(0, 4, 50)
x_3d, y_3d = meshgrid(nx, ny)
s = surf(x_3d, y_3d, data)

The script launches with no errors, however I do not have any visualization on the Mayavi scene.
Thanks for your help, and if anyone has a better suggestion of how to plot a 3D representation of a 2D imshow I'm happy to accept also.

A: You forgot the mlab.show() command at the end and surf needs three arguments I think x and y are just the position of your points, you need a third array to determine the z-coordinate.


text:
Q: ASP.NET MVC - Preserving invalid DateTime selection with 3 dropdown lists I'm still fairly new to ASP.NET and MVC and despite days of googling and experimenting, I'm drawing a blank on the best way to solve this problem.
I wrote a BirthdayAttribute that I want to work similar to the EmailAddressAttribute. The birthday attribute sets the UI hint so that the birthday DateTime will be rendered using an editor template that has 3 dropdown lists. The attribute can also be used to set some additional meta data that tells the year dropdown how many years it should display.
I know I could use jQuery's date picker, but in the case of a birthday I find the 3 dropdowns much more usable.
@model DateTime
@using System;
@using System.Web.Mvc;
@{
    UInt16 numberOfVisibleYears = 100;
    if (ViewData.ModelMetadata.AdditionalValues.ContainsKey("NumberOfVisibleYears"))
    {
        numberOfVisibleYears = Convert.ToUInt16(ViewData.ModelMetadata.AdditionalValues["NumberOfVisibleYears"]);
    }
    var now = DateTime.Now;
    var years = Enumerable.Range(0, numberOfVisibleYears).Select(x => new SelectListItem { Value = (now.Year - x).ToString(), Text = (now.Year - x).ToString() });
    var months = Enumerable.Range(1, 12).Select(x => new SelectListItem{ Text = new DateTime( now.Year, x, 1).ToString("MMMM"), Value = x.ToString() });
    var days = Enumerable.Range(1, 31).Select(x => new SelectListItem { Value = x.ToString("00"), Text = x.ToString() });
}

@Html.DropDownList("Year", years, "<Year>") /
@Html.DropDownList("Month", months, "<Month>") /
@Html.DropDownList("Day", days, "<Day>")

I also have a ModelBinder to rebuild my date afterwards. I've removed the content of my helper functions for brevity, but everything works great up to this point. Normal, valid dates, work just fine for creating or editing my members.
public class DateSelector_DropdownListBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (controllerContext == null)
            throw new ArgumentNullException("controllerContext");
        if (bindingContext == null)
            throw new ArgumentNullException("bindingContext");

        if (IsDropdownListBound(bindingContext))
        {
            int year    = GetData(bindingContext, "Year");
            int month   = GetData(bindingContext, "Month");
            int day     = GetData(bindingContext, "Day");

            DateTime result;
            if (!DateTime.TryParse(string.Format("{0}/{1}/{2}", year, month, day), out result))
            {
                //TODO: SOMETHING MORE USEFUL???
                bindingContext.ModelState.AddModelError("", string.Format("Not a valid date."));
            }

            return result;
        }
        else
        {
            return base.BindModel(controllerContext, bindingContext);
        }

    }

    private int GetData(ModelBindingContext bindingContext, string propertyName)
    {
        // parse the int using the correct value provider
    }

    private bool IsDropdownListBound(ModelBindingContext bindingContext)
    {
        //check model meta data UI hint for above editor template
    }
}

Now that I'm looking at it, I should probably be using a nullable DateTime, but that's neither here nor there.
The problem I'm having is with very basic validation of invalid dates such as February 30th, or September 31st. The validation itself works great, but the invalid dates aren't ever saved and persisted when the form is reloaded.
What I'd like is to remember the invalid date of February 30th and redisplay it with the validation message instead of resetting the dropdowns to their default value. Other fields, like the email address (decorated with the EmailAddressAttribute) preserve invalid entries just fine out of the box.
At the moment I am just trying to get the server side validation working. To be honest, I haven't even started thinking about the client side validation yet.
I know there is lots I could do with javascript and ajax to make this problem a moot point, but I would still rather have the proper server side validation in place to fall back on.

A: I finally managed to solve my problem, so I wanted to share my solution.
DISCLAIMER:
Although I used to be great with .NET 2.0 back in the day, I'm only now updating my skills to the latest versions of C#, ASP.NET, MVC, and Entity Framework. If there are better ways to do anything I've done below please I'm always open to feedback.
TODO:

*

*Implement client side validation for invalid dates such as February 30th. Client side validation for [Required] attribute is already built in.

*Add support for cultures so that the date shows up in desired format
The solution came to me when I realized that the problem I was having is that DateTime will not allow itself to be constructed with an invalid date such as February 30th. It simply throws an exception. If my date wouldn't construct, I knew of no way to pass my invalid data back through the binder to the ViewModel.
To solve this problem, I had to do away with the DateTime in my view model and replace it with my own custom Date class. The solution below will provide fully functioning server side validation in the event that Javascript is disabled. In the event of a validation error the invalid selections will persist after the validation message is displayed allowing the user to easily fix their mistake.
It should be easy enough to map this view-ish Date class to the DateTime in your date model.
Date.cs
public class Date
{
    public Date() : this( System.DateTime.MinValue ) {}
    public Date(DateTime date)
    {
        Year = date.Year;
        Month = date.Month;
        Day = date.Day;
    }

    [Required]
    public int Year  { get; set; }

    [Required, Range(1, 12)]
    public int Month { get; set; }

    [Required, Range(1, 31)]
    public int Day   { get; set; }

    public DateTime? DateTime
    {
        get
        {
            DateTime date;
            if (!System.DateTime.TryParseExact(string.Format("{0}/{1}/{2}", Year, Month, Day), "yyyy/M/d", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
                return null;
            else
                return date;
        }
    }
}

This is just a basic date class that you can construct from a DateTime. The class has properties for Year, Month, and Day as well as a DateTime getter that can try to retrieve you a DateTime class assuming you have a valid date. Otherwise it returns null.
When the built in DefaultModelBinder is mapping your form back to this Date object, it will take care of the Required and Range validation for you. However, we will need a new ValidationAtribute to make sure that invalid dates such as February 30th aren't allowed.
DateValidationAttribute.cs
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class DateValidationAttribute : ValidationAttribute
{
    public DateValidationAttribute(string classKey, string resourceKey) :
        base(HttpContext.GetGlobalResourceObject(classKey, resourceKey).ToString()) { }

    public override bool IsValid(object value)
    {
        bool result = false;
        if (value == null)
            throw new ArgumentNullException("value");

        Date toValidate = value as Date;

        if (toValidate == null)
            throw new ArgumentException("value is an invalid or is an unexpected type");

        //DateTime returns null when date cannot be constructed
        if (toValidate.DateTime != null)
        {
            result = (toValidate.DateTime != DateTime.MinValue) && (toValidate.DateTime != DateTime.MaxValue);
        }

        return result;
    }
}

This is a ValidationAttribute that you can put on your Date fields and properties. If you pass in the resource file class and the resource key it will search the corresponding resource file in your "App_GlobalResources" folder for the error message.
Inside the IsValid method, once we're sure we're validating a Date we check it's DateTime property to see if it's not null to confirm that it's valid. I throw in a check for DateTime.MinValue and MaxValue for good measure.
So that's about it really. With this Date class, I managed to do away completely with the custom ModelBinder. This solution relies completely on the DefaultModelBinder, which means all of the validation works right out of the box. It apparently even checks my new DateValidationAttribute, which I was super excited about. I stressed forever thinking I might have to muck with validators in a custom binder. This feels a lot cleaner.
Here is the complete code for the partial view I'm using.
DateSelector_DropdownList.cshtml
@model Date
@{
    UInt16 numberOfVisibleYears = 100;
    if (ViewData.ModelMetadata.AdditionalValues.ContainsKey("NumberOfVisibleYears"))
    {
        numberOfVisibleYears = Convert.ToUInt16(ViewData.ModelMetadata.AdditionalValues["NumberOfVisibleYears"]);
    }
    var now = DateTime.Now;
    var years = Enumerable.Range(0, numberOfVisibleYears).Select(x => new SelectListItem { Value = (now.Year - x).ToString(), Text = (now.Year - x).ToString() });
    var months = Enumerable.Range(1, 12).Select(x => new SelectListItem { Text = new DateTime(now.Year, x, 1).ToString("MMMM"), Value = x.ToString() });
    var days = Enumerable.Range(1, 31).Select(x => new SelectListItem { Value = x.ToString(), Text = x.ToString() });
}

@Html.DropDownList("Year", years, "<Year>") /
@Html.DropDownList("Month", months, "<Month>") /
@Html.DropDownList("Day", days, "<Day>")

I'll also include the attribute I use that sets up the template hint and the number of visible years to show.
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public sealed class DateSelector_DropdownListAttribute : DataTypeAttribute, IMetadataAware
{
    public DateSelector_DropdownListAttribute() : base(DataType.Date) { }

    public void OnMetadataCreated(ModelMetadata metadata)
    {
        metadata.AdditionalValues.Add("NumberOfVisibleYears", NumberOfVisibleYears);
        metadata.TemplateHint = TemplateHint;
    }

    public string TemplateHint { get; set; }
    public int NumberOfVisibleYears { get; set; }
}

I think the solution turned out a lot cleaner than I expected it to. It solves all of my problems in the exact way that I was hoping to. I do wish that I was somehow able to keep the DateTime, but this is the only way I could figure out how to maintain an invalid selection using only server side code.
Are there any improvements you would make?


text:
Q: Is this normal? When booting from live usb install, initram error and stdin invalid argument Im really struggling to install a system that boots properly once installed.
During live usb booting i get this:
Errors on bootup
My live usb booting starts with initramfs failure error then stdin invalid argument just before checking system integrity,  it shows up twice.  See picture for detail.  Help is much appreciated.
I read somewhere that very fast hardware can cause issues. Is this the case here? I have new generation ryzen 64gb 3600mhz ram and using an ssd
Once i install from this live usb, i have graphics corruption upon loading of fresh install, i have to boot in recovery mode and then install nvidia drivers which seems to fix the problem of corrupt graphics. However after a while the booting doesnt happen successfully and i get an error to do with "you must load kernel first".and hd2 gpt not found.
Is my SSD dead perhaps?
Im thinking my fresh system install doesn't work due to the earlier mentioned errors with live usb...
More details to follow...


text:
Q: Не принимаются параметры jQuery.load() в PHP Есть обработчик:
$(document).delegate('#fakeButton', 'click', function() {
    var url = 'index.php?route=checkout/guest/freetimes';
    $('#timeselect').load(url, {'date': $('#input-payment-orderdate').val()});
});

и функция в php:
function freetimes() {
$myCurl = curl_init();
$date = $_POST('date');

curl_setopt_array($myCurl, array(
    CURLOPT_URL => "http://localhost:56987/api/orders/freetimes?date=".$date,
    CURLOPT_RETURNTRANSFER => true
    ));
$response = curl_exec($myCurl);
curl_close($myCurl);

$times = array();
$times[] = split("/", str_replace("\"","",$response));

$rez = '';

$max = sizeof($times[0]);
for ($i = 0; $i < $max; $i++) {
    list($value, $start, $end) = split('-', $times[0][$i]);
    $rez = $rez.'<option value="'.$value.'">'.$start.'-'.$end.'</option>';
}

echo $rez;
}

Функция php полностью рабочая и с $date = date("Y-n-j") работает замечательно, но при попытке принять параметры методом POST вылетает
Не знаю как исправить

A: http://api.jquery.com/load/

It is roughly equivalent to $.get(url, data, success)
[ примерно соответствует $.get(url, data, success) ]

То есть в load запрос GET,  а не POST.  Или измените код php на
$date = $_GET['date']; (а то и $_REQUEST['date'])

или используйте
$.ajax({
  type: "POST",
  url: "index.php?route=checkout/guest/freetimes",
  data: { 'date': $('#input-payment-orderdate').val() },
  dataType: "html",
  success: function(data) {
    $('#timeselect').html(data);
  }
});


text:
Q: "The file I sent (to) you". Using the preposition
to send somebody something
    to send something to somebody

Is it necessary to use the preposition in sentences like these, in which the direct object stands before the verb?

Open the file I sent (to) you.
    What does she give (to) him?

I suppose both options are correct and the preposition might or might not be used. Am I right?

A: The conventional rule for indirect objects is that the preposition can be omitted if the indirect object goes between the verb and the direct object:

I gave the message to him - verb-direct-to-indirect
  I gave him the message - verb-indirect-direct

What's happening in the first sentence is that there is a relative clause with the relative pronoun that. In spoken English, the relative pronoun can be omitted: here is your first sentence as it would be written in formal English, with the relative pronoun included:

Open the file that I sent (to) you.

In the second sentence, what is acting like a pronoun that represents the direct object.
In both cases, then, the direct object is a pronoun at the front of the clause, so the indirect object cannot go between verb and direct object. When parsing the sentence, we understand that the direct object has been fronted, so it's OK to omit the preposition even though we just have verb + indirect object. One of the answers to this question confirms that the omission is permissible.
Note that it is also OK to omit the preposition for, for example:

He ate the sandwich that I made for him
  He ate the sandwich that I made him

Note that, if the relative pronoun is used to represent the indirect object, the preposition cannot be omitted. In some cases, you end up with a dangling preposition:

the girl that I lent my jacket to
  the person that I poured a drink for
  I don't know the man to whom you sold the house

Note that, in very informal spoken English, you may hear the preposition omitted from sentences like the first one. You may also hear final sentence produced incorrectly, but in this case the to is never omitted:

I don't know the man who you sold the house to

A: The preposition is not required.
The structure here is Noun - relative clause. The noun is an object of the verb in the relative clause, and so the relative pronoun may be omitted. The verb "send" can take two objects, and in relative clause either can be in front of the verb.
These are all possible:

The file I sent you
  The file that I sent you
  The file I sent to you
  The person (that) I sent the file
  The person (that) I sent the file to
  The person to whom I sent the file


text:
Q: loginservlet example code Servlets and jsp is new to me, so I`ve started to look at example code of a login servlet. Does a new player get inserted into the gamelogic, because this servlet should actually work? I can only see the errors being handled.
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import de.ustg.quiz.application.*;
import de.ustg.quiz.error.*;

//Servlet Implementation

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public void init() {

}

//@see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse       response)

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("doPost");
    Quiz quiz = Quiz.getInstance();
    QuizError quizError = new QuizError();
    response.setContentType("text/html;charset=UTF-8");

    //insert player into gamelogic
    if(request.getParameter("username").equals("")) {
        request.setAttribute("LoginError", true);
        request.setAttribute("LoginErrorMessage", "username required");
    } else {
        if(quiz.createPlayer((String) request.getParameter("username"), quizError) == null) {
            System.out.println(quizError.getDescription());
            request.setAttribute("LoginError",true);
            request.setAttribute("LoginErrorMessage", quizError.getDescription());
        }
    }
    // write player frome gamelogic into list
    List<Player> playerList = new ArrayList<Player>(quiz.getPlayerList());
    request.setAttribute("playerList", playerList);
    RequestDispatcher requestDispatcher = request.getRequestDispatcher("index.jsp");
    requestDispatcher.forward(request, response);

}

}


text:
Q: Filtering the AD group I used the below code for pulling out AD group of users
$users = Get-Content u:\users.txt
ForEach ($User in $users) {
$user1 = Get-ADUser -Identity $User -Properties *;
$GroupMembership = ($user1.memberof | % { (Get-ADGroup $_).Name; }) -join ';';
$User1.SamAccountName + ';' + $GroupMembership >>test4.csv
}

I would like to add a filter which fetches the only particular type of ad group say starting with SG
I had tried putting a filter but it gave me a boolean true or false but not the filtered value.

A: You want to filter the Name property starting with SG?, try this:
Get-ADGroup -filter 'Name -like "SG*"'


text:
Q: Stick Force Layout with D3js V4 I noticed that the source code for D3 V4 does not have d.fixed has a setting for disabling the force simulation.  How does one create fixed nodes as in the example below with v4?
//from line 6299 of v3
if (o.fixed) {
      o.x = o.px;
      o.y = o.py;
    } else {
      o.x -= (o.px - (o.px = o.x)) * friction;
      o.y -= (o.py - (o.py = o.y)) * friction;
    }

http://bl.ocks.org/mbostock/3750558

A: You need to use o.fx and o.fy. From the docs:

To fix a node in a given position, you may specify two additional properties:

*

*fx - the node's fixed x-position

*fy - the node's fixed y-position

https://github.com/d3/d3-force/blob/master/README.md


text:
Q: introducig changes in style by jQuery i've created simple code that should set/change image background depending on window width
var backgroundBig = "url(../img/logo1.svg)";
var backgroundSmall = "url(../img/logo2.svg)";
function logoBG(){

    var windowWidth = $(window).width();

    if (windowWidth < 700){

        $("#wrapper1").css({"background-image": backgroundSmall});

    } else {

        $("#wrapper1").css({"background-image": backgroundBig});

    };

};

logoBG();
$(window).resize(logoBG);

as simple as that...
optional background image proprieties are set in css file
#wrapper1{

background-repeat: no-repeat;
background-size: cover;}

everything works fine in website code - when i'm tracking changes by firebug, code changes as it should. however, images don't load, nothing changes regarding website display. what is wrong with that?
thanks in advance
PM

A: Try this https://jsfiddle.net/2Lzo9vfc/23/
JS
var backgroundBig = "url(http://placehold.it/1980x960)";
var backgroundSmall = "url(http://placehold.it/1980x960/000000)";
function logoBG(){

    var windowWidth = $(window).width();

    if (windowWidth <= 700){

        $("#wrapper1").css("background-image", backgroundSmall);

    } else {

        $("#wrapper1").css("background-image", backgroundBig);

    };

};

logoBG();
$(window).resize(logoBG);
$(document).ready(logoBG);

HTML

Lorem

A: Because the images must be loaded FIRST, why it's working with firebug ? it's surely because firebug reload the DOM so he can parse it, and when he do so, the images are already loaded.
I can recommend you jquery.waitForImages because it can even wait for images background, so your JavaScript code is not executed before your images are loaded, and you dont need to Reload the DOM too.

A: Thank you for all advices. The problem with my code was... the paths to my image files.
url(../img/logo1.svg)

works in css file, that's why I assumed that it's must be correct, but
url(img/logobg.svg)

should be inserted by the jQuery script. What a lame mistake :)


text:
Q: JSP / JSTL - Why am I getting the error "The end tag "</c:forEach" is unbalanced"? "HTTP Status 500 - /process.jsp (line: 42, column: 10) The end tag "</c:forEach" is unbalanced" is the error I'm getting.
I'm looping through a list of objects that I'm passing through from a servlet. The objects have a list of formProperties that I'm looping through from within.
My .jsp:

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<link href="jquery/jquery-ui.css" rel="stylesheet" type="text/css">
<link href="css/style.css" rel="stylesheet" type="text/css">
<title>Process</title>

    BACK

                <c:if test="${pastTasksList.size() > 0}">
                    <c:forEach items="${pastTasksList}" var="pastTask">

${pastTask.getName()}

                    </c:forEach>
                </c:if>
                <c:forEach items="${taskList}" var="task">

${task.getName()}

                </c:forEach>

            <c:if test="${pastTasksList.size() > 0}">
                <c:forEach items="${pastTasksList}" var="pastTask">

Previous Details:

                            <c:forEach items="${pastTask.getFormProperties()}" var="property">
                                <c:if test="${!fn:contains(property.getName(), 'task')}">

                                        ${property.getName()}
                                        ${property.getVariable()}

                                </c:if>
                            </c:forEach>

                </c:forEach>
            </c:if>
            <form action="CompleteTask" method="post" name="taskForm" id="taskForm">
            <c:forEach items="${formPropertiesList}" var="formProperties" varStatus="status">

${taskList[status.index].getDescription()}

                    <c:forEach items="${formProperties}" var="property">

${property.getName()}:

                        <c:set var="type" value="${property.getType().getName()}" />
                        <c:if test="${type == 'string'}">
                            <c:if test="${property.isRequired() == 'true' }">
                                <input type="text" id="${property.getId()}" name="${property.getId()}" value="${property.getValue()}" required />

                            </c:if>
                            <c:if test="${property.isRequired() == 'false' }">
                                <input type="text" id="${property.getId()}" name="${property.getId()}" value="" />

                            </c:if>
                        </c:if>
                        <c:if test="${type == 'long'}">
                            <c:if test="${property.isRequired() == 'true' }">
                                <input type="text" id="${property.getId()}" name="${property.getId()}" value="${property.getValue()}" required />

                            </c:if>
                            <c:if test="${property.isRequired() == 'false' }">
                                <input type="text" id="${property.getId()}" name="${property.getId()}" value="" />

                            </c:if>
                        </c:if>
                        <c:if test="${type == 'date'}">
                            <c:if test="${property.isRequired() == 'true' }">
                                <input type="date" id="${property.getId()}" name="${property.getId()}" value="" required />

                            </c:if>
                            <c:if test="${property.isRequired() == 'false' }">
                                <input type="date" id="${property.getId()}" name="${property.getId()}" value="" />

                            </c:if>
                        </c:if>
                        <c:if test="${type == 'enum'}">
                            <select id="${property.getId()}" name="${property.getId()}">
                                <c:forEach var="entry" items='${property.getType().getInformation("values")}'>
                                    <option value="${entry.key}">${entry.value}</option>
                                </c:forEach>
                            </select>

                        </c:if>
                        <c:if test="${type == 'product'}">

Product:

                                            <input class="checkBoxes" type="checkbox" name="product" value="anaesthetic"> Anaesthetic

                                            <input class="checkBoxes" type="checkbox" name="product" value="analgesic"> Analgesic

                                            <input class="checkBoxes" type="checkbox" name="product" value="antacid"> Antacid

Process:

Equipment:

                        </c:if>
                    </c:forEach>
                    <input type="hidden" name="task${status.index}" value="${taskList[status.index].getId()}" />

            </c:forEach>
            </form>

        <input id="submit" form="taskForm" type="submit" value="Complete Task" />

I've attached all the code because I have no idea where the problem could originate.


text:
Q: JavaScript function declarations in Native browser and Node.js, get differnt results The code below will get different in Browser and Node.js.
Result of browser is a.
Result of Node.js is b.
if (1) {
    function foo() { return 'a'; }
} else {
    function foo() { return 'b'; }
}

console.log(foo());

Although this code style is anti-pattern, the code still can be run in environment.
How to explain it?

FYI.

*

*Node.js environment Link:
https://repl.it/CgWh

*Native Browser environment Link:
https://repl.it/CgWj
These links maybe not permanent.

A: Javascript engines are not hoisting javascript function the same way, so you can expect different behavior between browser/node.
One exemple of this: http://statichtml.com/2011/spidermonkey-function-hoisting.html

A: Ok, So I looked at your code and analyzed it on both native browser and nodeJS. As far as I know, In node the function with same name on second declaration gets overwritten but its not the case in native browser javascript. To look further into the working of the two environments use following code and you will see the difference:
if (1) {
    console.log('In condition 1');
    function foo() {
        console.log('Inside first declaration');
        return 'a';
    }
} else {
    console.log('In condition 2');
    function foo() {
        console.log('Inside second declaration');
        return 'b';
    }
}

console.log(foo());

A: if (1) {
    foo();
} else {
foo1();
}
function foo() { return 'a'; }
function foo1() { return 'b'; }
console.log(foo());

Function behavior in a block may be different. Above code works perfectly as expected.


text:
Q: docker can't find mountend socket of the docker command I have a container with the base image python. The containers job is to execute a python script, the relevant part to this question is here:
client = docker.from_env()
output = client.containers.run("ubuntu:latest", "echo hello world")
print (output)

I mount the socket of the docker in the container at startup:
docker run -tv /var/run/docker.sock:/var/run/docker.sock -ti python_docker

But everytime I run the container I get following error:
FileNotFoundError: [Errno 2] No such file or directory: 'docker': 'docker'

I've tried to see if the script is at fault but when it is run outside of a container it works prefectly.
The library I am using for running containers in python:
https://pypi.org/project/docker/
And the dockerfile of the container:
FROM python
MAINTAINER jocomol
ADD ./run_container.py .
RUN pip3 install colorful docker
CMD python3 ./run_container.py

A: I was able to fix this. All I did was just mount the Docker binary aswell.
docker run -v /usr/bin/docker:/usr/bin/docker -v /var/run/docker.sock:/var/run/docker.sock -ti python_docker


text:
Q: python object typecasting Ive been trying search how to pass object reference in python and type cast it similar to Java but no to avail. I duno if this topic exists somewhere here.
My trouble is i have to pass the object reference to a class constructor. But i duno how to typecast the reference to an object. In java though I have accomplish this but i have to transfer the code to the server side.
many thanks,
Jack
class SearchRectangle:
    def __init__(self, lower_left_subgrid_x, lower_left_subgrid_y, rectangle_width, rectangle_height):

        self.min_subgrid_x = int(lower_left_subgrid_x)
        self.max_subgrid_x = int(self.min_subgrid_x + rectangle_width -1)
        self.min_subgrid_y = int(lower_left_subgrid_y)
        self.max_subgrid_y = int(self.min_subgrid_y + rectangle_height -1)

     ...blah

class SearchRectangleMultiGrid:
 # parent rectangle should be a SearchRectangle instance
    def __init__(self, parent_rectangle):
        self.parent_rectangle = SearchRectangle()parent_rectangle

    # test codes
    test_rect = SearchRectangle(test_subgrid.subgrid_x, test_subgrid.subgrid_y, 18, 18)
    print "\n\nTest SearchRectangle";
    print test_rect.to_string()
    print test_rect.sql_clause

    test_rec_multi = SearchRectangleMultiGrid(test_rect)
    print "\n\nTest SearchRectangleMulti"
    test_rec_multi.parent_rectangle.to_string()

A: Python is a dynamically typed language and as such, it doesn't make much sense to cast something unless you specifically need it in that type.
In Python you should use Duck Typing instead: http://en.wikipedia.org/wiki/Duck_typing
So instead of trying to convert parent_rectangle to a SearchRectangle() you should simply test if SearchRectangle() has the properties you need.
Or if you really want to be sure that you'll always get a SearchRectangle(), use isinstance like this:
if isinstance(parent_rectangle, SearchRectangle):

This might be a good read for you: http://dirtsimple.org/2004/12/python-is-not-java.html

A: There's no reason to cast anything in python. What are you trying to do? Just use the object like you would, and if it's not of the correct type it will fail. There's no such thing as casting since variable names don't have a type associated with them.

A: Further explanation:
Casting is the act of taking a pointer/reference to one type of object, and say to the compiler "Yeah, I know this is a foo reference but please pretend it is a bar reference".
Python do not have pointers/references in that sense (although in another sense, everything is references). Also, the compiler/interpreter doesn't care what the type is in the first place. Hence, casting is both impossible and pointless.
So in your example: Just skip the type casting. It'll work anyway. And if it doesn't. then make a question on that problem.


text:
Q: Font Awesome 5: some unicode won't display in html select I have a html select with 2 items, each one should show a FA icon, but only one of them works.
Both icons only have the "sold" version available FA5 free.
Changing the font family to "Font Awesome 5 Free", did not help and then none of icons displayed.

  <select style='font-weight: 900;'>
    <option> Broke</option>
    <option> Working</option>
  </select>

 Code valid as this shows 

 But displayed icons have the solid style as free and the other styles are pro only
 https://fontawesome.com/icons/graduation-cap?style=solid f19d
 https://fontawesome.com/icons/th-large?style=solid
  f009

Thanks in advance

A: You are using the JS+SVG method to load your icons so the one used inside the content  will get transformed into an SVG. The unicde inside the select aren't considered by this and will rely on the font-family: 'FontAwesome' which is the old version and the first icon you are trying to show exist only in the V5 (unlike the second one).
To fix your issue, you need to load the CSS version and correct the font-family

select {
  font-family: 'Font Awesome 5 Free';
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.12.0-1/css/all.css">

<select style='font-weight: 900;'>
  <option> Broke</option>
  <option> Working</option>
</select>

 Code valid as this shows 

 But displayed icons have the solid style as free and the other styles are pro only
 https://fontawesome.com/icons/graduation-cap?style=solid f19d
 https://fontawesome.com/icons/th-large?style=solid
f009


text:
Q: execute multiple update command on Excel I have an Excel file and I want update multiple rows in a sheet.So I write this code :
OleDbConnection cn = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0; Data Source = " + serverPath + ";Extended Properties = Excel 8.0;");
        try
        {

            strUpd = "";
            strUpd += "update [Data14City$] set  B_1_1 = 5 ,B_1_2 = 26 ,B_1_3 = 44 ,B_1_4 = 8  where id = 1 ";
            strUpd += " update [Data14City$] set  B_1_1 = 0 ,B_1_2 = 8 ,B_1_3 = 17 ,B_1_4 = 0  where id = 2";
            cn.Open();
            OleDbCommand cmdInsert = new OleDbCommand(strUpd, cn);
            cmdInsert.ExecuteNonQuery();
            cn.Close();
        }
        catch
        {
        }

and I got this error:

Syntax error (missing operator) in query expression 'id = 1  update [Data14City$] set  B_1_1 = 0 ,B_1_2 = 8 ,B_1_3 = 17 ,B_1_4 = 0  where id = 2'.

and I when I add ; to this line :
strUpd += "update [Data14City$] set  B_1_1 = 5 ,B_1_2 = 26 ,B_1_3 = 44 ,B_1_4 = 8  where id = 1;";

I got this error:

Characters found after end of SQL statement.

how I can execute multiple statement in Excel?
thanks

A: You don't really need to stack up your updates like that (in fact, as has been pointed out above, you can't). It doesn't take much longer to execute them individually. Here's the code I've been using and it works fine (I actually have mine in a loop, but it'll work equally well if you can't loop your updates).
cn.Open();

using (OleDbCommand cmd = cn.CreateCommand())
{
    cmd.CommandText = "update [Data14City$] set  B_1_1 = 5 ,B_1_2 = 26 ,B_1_3 = 44 ,B_1_4 = 8  where id = 1";
    cmd.ExecuteNonQuery();
    cmd.CommandText = "update [Data14City$] set  B_1_1 = 0 ,B_1_2 = 8 ,B_1_3 = 17 ,B_1_4 = 0  where id = 2";
    cmd.ExecuteNonQuery();

    // ... and so on
}

cn.Close();


text:
Q: git(osis) and Xcode I installed (successfully) gitosis. I want to use it at my debian (rootserver) to access my Xcode projects (and merge, etc.). I'm able to clone the git repo with Xcode successfully, but if I try to push some (committed) changes, Xcode tells me "Choose the Remote to witch to push the changes" But I can't select any. I am able to push via Terminal.app, but that's not very comfortable. So why is Xcode telling me, there are no remotes available? I tried to add the remote manually (it is something like "gitosis@myserver.com:repositories/gitosis-admin.git"), I tried with ssh://gitosis@my..., but this dosen't even work with terminal.app.
So why is Xcode telling me "No Remotes available"?

A: Go to the organizer, click repositories, click yours, go to remote, click add remote, should be able to add it from there. should ask for verification and such. never used gitosis but that's how it works for git.


text:
Q: unit testing for iPad Which is the most recommended unit test framework for iPad development?
I knew that there is a unit testing framework available inside the SDK. Is this toolset fine, or should I go for another framework?
Is unit testing is done on iPad device or just on simulator?
What pointers can you give for techniques on how to write best unit test cases for iPad?

A: The included SenTestKit is quite limited and only runs in the simulator but GHUnit seems to be highly recommended.
Here is a list of GHUnit features

*

*Run tests, breakpoint and interact
directly with the XCode Debugger.

*Run from the command line or via a
Makefile.

*Run tests in parallel.

*Allow testing of UI components.

*Capture and display test metrics.

*Search and filter tests by keywords.

*View logging by test case.

*Show stack traces and useful
debugging information.

*Be embeddable as a framework (using
@rpath) for Mac OSX apps, or as a
static library in your iPhone
projects.


text:
Q: Wordpress ajax success response I'm trying to create a contact form in Wordpress using wp_mail and ajax
The emial works but I'm having problems with the ajax success reponse.
After the email is sent I need to show the user a message that the email was sent.
The js to validate the form and show the succes message.
    $atj(function(){
      $atj('#training-submit').click(function(e) {
        e.preventDefault();
        e.stopPropagation();
        if(verfiyFields()) {
            alert('here');
            requestData = {
              'action' : 'myajax-submit',
              'firstName' : $atj("#name").val(),
              'email' : $atj("#email").val(),
          }
          $atj.post(MyAjax.ajaxurl, requestData).done(function(result){
            result = jQuery.parseJSON( result );
            console.log(result);
            if(result == 'success'){
              $atj('.training-form [type=text]').val('');
              $atj('.training-form-message').append('
Thank you for the  email
');
            }
          });
        }
      });
    })

    //Verfiy
    function verfiyTrainingFields() {
      var flag = true;

      var name =        $atj('#name');
      var email =       $atj('#email');

      if(name.val().indexOf(' ') === -1 ){
        name.parent().prepend('
Please enter name, first space last
');
        errorMessage($atj('.form-error'));
        flag = false;
      }
      if(!IsEmail(email.val())){
        email.parent().prepend('
Please enter valid email address
');
        errorMessage($atj('.form-error'));
        flag = false;
      }
      return flag;
    }

The functions.php file to send the email and send the ajax reponse.
    function myajax_submit() {

        $name = sanitize_text_field($_POST['firstName']);
        $email = sanitize_text_field($_POST['email']);

        $headers[] = 'From: ' . $name . ' <' . $email . '>' . "\r\n";
        $headers[] = 'Content-type: text/html' . "\r\n"; //Enables HTML ContentType. Remove it for Plain Text Messages

        $to = 'me@mysite.co.uk';

        $message = 'Name: ' . $name . "\r\n" . 'email: ' . $email;

        add_filter( 'wp_mail_content_type', 'set_html_content_type' );
        wp_mail( $to, 'Email Test', $message );
        remove_filter( 'wp_mail_content_type', 'set_html_content_type' );

        echo 'email sent';

        // generate the response
        $response = json_encode( array( 'success') );

        // response output
        header( "Content-Type: application/json" );
        echo $response;

        exit;
    }

The email is sent and the 'email sent' echo fires but the if(result == 'success'){ in the js doesn't work.
The console.log(result) in the js file gives the following.

    Warning:  call_user_func_array() expects parameter 1 to be a valid callback, function 'set_html_content_type' not found or invalid function name in /Users/user.name/Desktop/MAMP-DocRoot/appname/src/php/wp-includes/plugin.php on line 192

    email sent

    Warning:  Cannot modify header information - headers already sent by (output started at /Users/user.name/Desktop/MAMP-DocRoot/appname/src/php/wp-includes/plugin.php:192) in /Users/user.name/Desktop/MAMP-DocRoot/appname/src/php/wp-content/themes/sitename/functions.php on line 66

    ["success"]

A: You can't use 2 echos for an ajax response.
Try this:
js:
  $atj.post(MyAjax.ajaxurl, requestData).done(function(result){
    console.log(result);
    if(result == 'success'){
      $atj('.training-form [type=text]').val('');
      $atj('.training-form-message').append('
Thank you for the  email
');
    }
  });

php
function myajax_submit() {
// snip...

 $mail_check = wp_mail( $to, 'Email Test', $message );
 remove_filter( 'wp_mail_content_type', 'set_html_content_type' );

 if( $mail_check)
   echo 'success';
 else
   echo 'failure';
 exit;
}


text:
Q: Position of labels as updated in a beamer slide tikz block I am having trouble with updating labels of tikz blocks in a beamer presentation. So far I have been using \onslide to update the block size and location from code in this answer. For the label text, \onslide shifts things up and down (as expected). With \only the label text shifts horizontally a little?
\documentclass[pd,xcolor={dvipsnames}]{beamer}
\usetheme{Frankfurt}
\usepackage[absolute,overlay]{textpos}

\usepackage{tikz}
\usetikzlibrary{shapes,arrows,backgrounds,positioning,patterns}
\tikzset{onslide/.code args={<#1>#2}{%
  \only<#1>{\pgfkeysalso{#2}} % \pgfkeysalso doesn't change the path
}}

\begin{document}
\begin{frame}

\centering
\tikzstyle{blocka} = [text width=3.0em, text centered, rectangle, rounded corners, fill, fill=red]
\tikzstyle{every node}=[font=\boldmath,color=white]
\tikzstyle{ann} = [draw=none,fill=white,rounded corners]

\begin{tikzpicture}
\node[blocka,
onslide=<1-2>{minimum height=10.00em},
onslide=<3-4>{minimum height=8.00em},
onslide=<5>{minimum height=7.67em},
onslide=<2-3>{pattern=crosshatch,pattern color=red}] (Aa1) {
\only<1>{$100$}
\only<2-3>{ }
\only<4>{$80$}
\only<5->{$76.7$}
%\onslide<1>{$100$},
%\onslide<2-3>{ },
%\onslide<4>{$80$},
%\onslide<5->{$76.7$};
};
\node[ann, left=0.25em of Aa1.180, color=red, fill=white] {A};

\end{tikzpicture}
\end{frame}

\end{document}

A: The \only<>{} command should be followed by a %-sign if you which to hit enter for a new line. A new line is interpreted as a white space in LaTeX. This white space was set in front of your numbers and therefore moved them out of the centre.
% arara: pdflatex

\documentclass{beamer}
\usetheme{Frankfurt}
\usepackage{tikz}
\usetikzlibrary{positioning,patterns}
\tikzset{%
    ,onslide/.code args={<#1>#2}{\only<#1>{\pgfkeysalso{#2}}}
    ,every node/.style={font=\boldmath,color=white}
    ,blocka/.style={text width=3.0em, text centered, rectangle, rounded corners, fill, fill=red}
    ,ann/.style={draw=none,fill=white,rounded corners}
    }

\begin{document}
\begin{frame}
    \begin{center}
        \begin{tikzpicture}
        \node[blocka,
            onslide=<1-2>{minimum height=10.00em},
            onslide=<3-4>{minimum height=8.00em},
            onslide=<5>{minimum height=7.67em},
            onslide=<2-3>{pattern=crosshatch,pattern color=red}] (Aa1) {%
                \only<1>{$100$}% <= this one centeres the first slide
                \only<2-3>{ }% <= this one centeres the fourth slide
                \only<4>{$80$}% <= this one centeres the fifth slide
                \only<5->{$76.7$}%
                };
        \node[ann, left=0.25em of Aa1.180, color=red, fill=white] {A};
        \end{tikzpicture}
    \end{center}
\end{frame}
\end{document}


text:
Q: Google Appengine , Django, Haystack and CloudSQL Does anyone know what haystack backends work on appengine with the cloudsql db?

A: I had a similar problem and did not find any GAE friendly way to use Django Haystack. You may be able to do something with Whoosh as it is pure Python, but I have my doubts.
An alternative is the use of Django nonrel search.  It does not contain all the features of Haystack and its associated backends, but it may provide what you need.

A: Try a hosted Elastic Search solution, such as searchbox.io. More information on getting it working with Haystack here.


text:
Q: Django queryset always reload instances I'm having some problems with a homemade caching descriptor and debugging I came up to this (strange) behaviour I can't figure out. Consider the following Django1.7 model (actually very simplified compared to my original project):
class Step(models.Model):
    game = models.ForeignKey('Game', on_delete=models.PROTECT)
    number = models.PositiveIntegerField()
    is_active = models.BooleanField(default=False)

    def __str__(self):
        return '{0}'.format(id(self))

If in terminal I run python manage.py shell and then
In [1]:ss = Step.objects.filter(game=1)

In [2]: ss
Out[2]:[<Step: 139934116973392>, <Step: 139934116971472>]

In [17]: ss[0]
Out[17]: <Step: 139934117084944>

In [18]: ss[0]
Out[18]: <Step: 139934117098512>

In [19]: ss[0]
Out[19]: <Step: 139934117098320>

I don't understand why ss[0] id keeps changing... is it standard behaviour? It seems that at each time ss is accessed all step instances era reloaded from the database (and so it is since django.db.connection.queries contains always new items).

A: They are, as the queryset is not fully evaluated and cached (printing it does not cache the results). As a result, the query is executed every time you access ss[0]:
>>> ss = Step.objects.filter(game=1)
>>> ss
[<Step: 139934116973392>, <Step: 139934116971472>]
>>> print ss._result_cache
None
>>> bool(ss)
True
>>> print ss._result_cache
[<Step: 139934117084944>, <Step: 139934117098512>]

Only when the queryset is fully evaluated (by iterating over it or calling len, list or bool), will the results be cached.


text:
Q: How to OR Query for contains in Dynamoose? I want to search(query) a bunch of strings from a column in DynamoDB. Using Dynamoose https://github.com/dynamoose/dynamoose
But it returns nothing. Can you help if this type of query is allowed or is there another syntax for the same.
Code sample
Cat.query({"breed": {"contains": "Terrier","contains": "husky","contains": "wolf"}}).exec()

I want all these breeds , so these are OR queries. Please help.

A: Two major things here.
First. Query in DynamoDB requires that you search for where a given hasKey that is equal to something. This must be either the hashKey of the table or hashKey of an index. So even if you could get this working, the query will fail. Since you can't do multiple equals for that thing. It must be hashKey = _______. No or statements or anything for that first condition or search.
Second. Just to answer your question. It seems like what you are looking for is the condition.in function. Basically this would change your code to look like something like:
Cat.query("breed").in(["Terrier", "husky", "wolf"]).exec()

Of course. The code above will not work due to the first point.
If you really want to brute force this to work. You can use Model.scan. So basically changing query to scan` in the syntax. However, scan operations are extremely heavy on the DB at scale. It looks through every document/item before applying the filter, then returning it to you. So you get no optimization that you would normally get. If you only have a handful or couple of documents/items in your table, it might be worth it to take the performance hit. In other cases like exporting or backing up the data it also makes sense. But if you are able to avoid scan operations, I would. Might require some rethinking of your DB structure tho.
Cat.scan("breed").in(["Terrier", "husky", "wolf"]).exec()

So the code above would work and I think is what you are asking for, but keep in mind the performance & cost hit you are taking here.


text:
Q: Php Startup : Unable to load dynamic library 'D:\xampp\php\ext\php_mongo.dll ' - The specified module could not be found I am trying to install mongo driver in xampp.I put php_mongo.dll in ext folder of php and added extension=php_mongo.dll in php.ini file.Now I restarted the xampp and I am getting this error

Php Startup : Unable to load dynamic library
  'D:\xampp\php\ext\php_mongo.dll ' - The specified module could not be
  found.

Please help me out with it.Am I missing any step.?

A: *

*please visit "https://pecl.php.net/package/mongodb", choose corresponding version mongodb .dll

*use phpinfo() to check "Thread Safety" ,if "enabled" upload "Thread Safe(TS)" version ,otherwise upload "Thread Safe(NTS)"
I know my english is poor ,so I hope this could help you.

A: *

*Go to this link:
https://learn.microsoft.com/en-us/sql/connect/php/system-requirements-for-the-php-sql-driver?view=sql-server-2017

*Create a php page and copy paste this code:

It will give the php version.

*Go and check the SQL Server version in your computer

*Basis this choose the Thread Safe dll version mentioned in the page:
https://learn.microsoft.com/en-us/sql/connect/php/system-requirements-for-the-php-sql-driver?view=sql-server-2017

*Download the .exe

*Install this in the php extension path. If Xampp is installed, it is of default:
C:\xampp\php\ext

*Then create a .php page:

*It should work.