text:
Q: Android Height Mapping Imported OBJ file in OpenGL ES 2.0? I am working on a sample project in Java, specifically Android, with OpenGL ES 2.0. I am looking to create a terrain for a player to move across. The player needs to move up and down the terrains hieght following the heightmap. The terrain is not flat. I am using Blender to create the terrain and heightmap. The terrain is being imported as an obj file.
The import and the drawing is working fine but i am having issues making the coordinates follow the heightmap. It doesn't seem to follow it 100%. The player moves up or down too soon every so often or  he drops below the terrain.
What I Have So Far:
1)What I am doing is importing the OBJ file into project. Reading the farthest point from terrain object and using this as the object length ( this value * 2 ). This tells me how many vertices are in the object along one side.
2)I then get the difference in the players position to terrain origin in world coordinates. I take the x and z values and divide each by the OBJ object length*2 to give the region of the terrain the object is in. This will give me the percentage of where the x and z position the player is in reference to the terrain.
3) I open the heightmap and multiply the percentages above to the image of the heightmap to get the x and y position on the heightmap to read the height from.
Below is what I am working with.

   public float getHeightOfTerrain(float worldX, float worldZ){
       // worldX and worldZ are the players position
       // Currentmatrix is the matrix used for positioning the terrain
       float terrainX = worldX - CurrentMatrix[12] + objLength;
       float terrainZ = worldZ - CurrentMatrix[14] + objLength;

       return getHeight(terrainX, terrainZ);
    }
   ................
float MAX_HEIGHT = 20;
float MAX_PIXEL_COLOR = 256*256*256;
   ................

   public float getHeight(float x, float z){
       float posX = x / (objLength*2);
       float posZ = z / (objLength*2);

       if(posX < 0 || posX > 1 || posZ < 0 || posZ > 1){ // if over 1 which is 100% of terrain then return
           return 0;
       }
       float imgX = posX * bitmapOfMap.getWidth();
       float imgZ = bitmapOfMap.getHeight() - (posZ * bitmapOfMap.getHeight()); // subtract BC bitmap y reads in reverse

       if(imgX < 0 || imgX >= bitmapOfMap.getWidth() || imgZ < 0 || imgZ >= bitmapOfMap.getHeight()){ // if over then return
           return 0;
       }
       float height = bitmapOfMap.getPixel((int)imgX, (int)imgZ);
       height += MAX_PIXEL_COLOR/2f;
       height /= MAX_PIXEL_COLOR/2f;
       height *= MAX_HEIGHT;
       return height;
   }

The smaller the terrain height, the better this setup works. The bigger change in terrain height, the worse this system works. I have tried different obj and heightmaps, recreating over and over thinking this may be the issue but the same problems exist.
Am I doing this completely wrong? Any help would be appreciated. Anyone know a better way? I really want to keep my OBJ file import and read from that for customization.

A: I went ahead and created the terrain just by the heightmap, no OBJ import. Then applied my code above and had the same exact issue. So I dug a bit deeper in what is exactly going on step by step. It all started from the way I was keep track of the terrains location on x, y, and z then subtract that from the players position. I was tracking the players position from a seperate array of x, y, z and then terrains position from the matrix[12], matrix[13], matrix[14] as x, y, z.
This was the issue. I can't use the floats in the matrices as positioning relative values. I had to keep a seperate x, y, z for the terrain as well.
So from.....
   float terrainX = worldX - CurrentMatrix[12] + objLength;
   float terrainZ = worldZ - CurrentMatrix[14] + objLength;

to
   float x, y, z = 0;

   .....

   float terrainX = z;
   float terrainZ = x;

Now the model works perfect! .... moves up and down the terrain appropriately following the heightmap. I hope this helps anyone that may be having the same issue.


text:
Q: Unable to preload and display SVG with CreateJS I am trying to preload a set of SVG objects and display them using CreateJS/PreloadJS. So far I was able to display a SVG object without preloading, but as soon as I use the LoadQueue from PreloadJS, I can't get my sample to work.
Does somebody know what I am doing wrong here? Thanks!
http://jsfiddle.net/trudeo/05eqqp49/
Javascript
var imageManifest = [
  { id: "MySvgImage", src: "http://dev.w3.org/SVG/tools/svgweb/samples/svg-files/check.svg" }
];

var stage = new createjs.Stage(document.getElementById('gameCanvas'));

var assetQueue = new createjs.LoadQueue(true);
assetQueue.loadManifest(imageManifest);
assetQueue.on('complete', complete);

function complete(e) {
    // DOESN'T WORK
    var svgImage = new createjs.Bitmap(assetQueue.getResult('MySvgImage'));
    stage.addChild(svgImage);

    // WORKS
    var svgImage2 = new createjs.Bitmap("http://dev.w3.org/SVG/tools/svgweb/samples/svg-files/circles1.svg");
    stage.addChild(svgImage2);

    stage.update();
    createjs.Ticker.setFPS(40);
    createjs.Ticker.addListener(tick);
}

function tick() {
    stage.update();
}

HTML
<!DOCTYPE html>

<html lang="en">
<head>
    <script src="http://code.createjs.com/createjs-2013.12.12.min.js"></script>
    <script src="http://code.createjs.com/preloadjs-0.4.1.min.js"></script>
    <script src="app.js"></script>
</head>
<body>
    <canvas id="gameCanvas" width="800" height="800"></canvas>
</body>
</html>

A: There are a few issues with your sample, which prevent the preloading of the asset, but unfortunately if those are addressed, it still will not draw into the Canvas.
Getting Preloading to work:
The asset will need to be hosted on a server with CORS enabled to do cross-domain loading. PreloadJS will use XHR to load SVG, which can not load cross-domain without some extra work. The updated sample below shows that in action.
// Note: Requires very latest PreloadJS (NEXT in GitHub)
var assetQueue = new createjs.LoadQueue(true, null, true);
// 3rd parameter is "crossOrigin", and requires a CORS server.

http://jsfiddle.net/lannymcnie/hhd4fwks/
Once preloaded, the asset can be appended to the DOM, but not used as a source for an EaselJS Bitmap. It appears that Canvas can not use drawImage with a local SVG source. It CAN be appended to the DOM thought.
The reason your second approach did work was that it was automatically treating the source of the Bitmap as an image path, so it loaded it as an image (Bitmap creates an image behind the scenes when it is passed a string path)
It is probably a good idea to add image-based preloading to PreloadJS - I will add an issue to the GitHub.

A: I found simple solution. Just force PreloadJS to use image loader, not SVGLoader.
{src:"img/bg.svg", id:"bg", type: createjs.LoadQueue.IMAGE}

Then you can convert it
var bg = new createjs.Bitmap(loader.getResult('bg'));
stage.addChild(bg);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change radio button to 'checked' when another is selected? I hope you guys can help me with this one.
How can I have a radio button id="A" change it's attribute to 'checked' when radio button id="B" is selected?
Radio buttons A and B are in different groups.
Thanks!

A: <input type="radio" name="group1" id="A">Radio A
<input type="radio" name="group2" id="B">Radio B
<input type="radio" name="group2" id="C">Radio C

$("input[type='radio'][name='group2']").change(function() {
  if ($('#B').is(':checked')) {
    $('#A').prop("checked", true);
  } else {
    $('#A').prop("checked", false);
  }
});

Here is the jsFiddle
http://jsfiddle.net/8kdb7d6o/

A: $("#B").change(function(){
    $("#A").prop('checked', true);
});

A: to check if radio input checked or not
if($('#B').is('checked')){
   $("#A").prop('checked', true);
}


text:
Q: Using SFINAE to test if a pointer type can be static_cast to another pointer type Background
I'm writing a take on a moveable QScopedPointer; basically std::unique_pointer with some extra accessors. I started it before I had access to a C++11-compatible compiler, but now I'm determined to get it right (even though I'm reinventing the wheel).
The Issue
Let's call my smart pointer MyUniquePointer.
I need to know if type U * can be converted into type T * via a static_cast, specifically:
template<class T, class Cleanup>
class MyUniquePointer
{
...
template<class U, class CleanupU, class = std::enable_if_t<detail::is_safely_castable<U, T>()>
MyUniquePointer(MyUniquePointer<U, CleanupU> && other) noexcept
    : d(static_cast<T *>(other.release()))
{}
...

The First Half of the Question
My first attempt was to use static_cast inside of an enable_if, but you can't take the address of std::declval() to get a pointer for static_cast!
Is there a way to use test if a pointer to U can be static_cast to a pointer to T using template magic?
The Attempted Workaround
Based on cppreference and this answer, I tried to create a template test to emulate when a static_cast is legal and, if downcasting, safe. Here's what I've put together so far:
#include <iostream>
#include <type_traits>
template <class From, class To>
struct is_safely_castable //should probably be is_safely_castable_pointer or something
        : std::integral_constant<bool,
               std::is_pointer<From>() && std::is_pointer<To>()
            && ((std::is_base_of<To, From>()/* && std::has_virtual_destructor<From>()*/)
               || std::is_convertible<From, To>()
               || std::is_same<To,void *>()
               || std::is_same<From, void *>())>
{
};

struct base_type
{
    base_type() = default;
    base_type(base_type &&) = default;
    base_type(const base_type &) = default;
    virtual ~base_type() { }
    base_type &operator=(const base_type &) = default;
    base_type &operator=(base_type &&) = default;
};

struct derived_type : public base_type
{
};

struct unrelated_type
{
};

struct convertible_type
{
    convertible_type(const base_type *) {}
    convertible_type(base_type *) {}
    convertible_type() = default;

    operator base_type *() { return nullptr; }
};

int main(int argc, char *argv[])
{
    (void)(argc);
    (void)(argv);

    base_type *b = new base_type;
    derived_type *d = new derived_type;
    unrelated_type *u = new unrelated_type;
    uint32_t *i32 = new uint32_t{1};
    uint64_t *i64 = new uint64_t{2};
    void *v = static_cast<derived_type *>(d);

    std::cout << std::boolalpha
        << "Base to base:        " << (bool)static_cast<base_type *>(b) << '\n'
        << "Base to derived:     " << (bool)static_cast<derived_type *>(b) << '\n'
        << "Derived to base:     " << (bool)static_cast<base_type *>(d) << '\n'
        << "Unrelated to base:   false\n" //<< static_cast<base_type *>(u) << '\n'
        << "uint32 to uint64:    false\n" //<< static_cast<uint64_t *>(i32) << '\n'
        << "uint64 to uint32:    false\n" //<< static_cast<uint32_t *>(i64) << '\n'
        << "Base to void:        " << (bool)static_cast<void *>(b) << '\n'
        << "Void to derived:     " << (bool)static_cast<derived_type *>(v) << '\n'
        << "Convertible to base: false\n" //<< static_cast<base_type *>(c) << '\n'
        << "Base to convertible: false\n";//<< static_cast<convertible_type *>(b) << '\n';

    std::cout << "-----------\n"
        << "Base to base:        " << is_safely_castable<base_type *, base_type *>() << '\n'
        << "Base to derived:     " << is_safely_castable<base_type *, derived_type *>() << '\n'
        << "Derived to base:     " << is_safely_castable<derived_type *, base_type *>() << '\n'
        << "Unrelated to base:   " << is_safely_castable<unrelated_type *, base_type *>() << '\n'
        << "uint32 to uint64:    " << is_safely_castable<uint32_t *, uint64_t *>() << '\n'
        << "uint64 to uint32:    " << is_safely_castable<uint64_t *, uint32_t *>() << '\n'
        << "Base to void:        " << is_safely_castable<base_type *, void *>() << '\n'
        << "Void to derived:     " << is_safely_castable<void *, derived_type *>() << '\n'
        << "Convertible to base: " << is_safely_castable<convertible_type *, base_type *>() << '\n'
        << "Base to convertible: " << is_safely_castable<base_type *, convertible_type *>() << '\n';

    delete b;
    delete d;
    delete u;
    delete i32;
    delete i64;
    return 0;
}

Wandbox Link
which returns:
Base to base:        true
Base to derived:     true
Derived to base:     true
Unrelated to base:   false
uint32 to uint64:    false
uint64 to uint32:    false
Base to void:        true
Void to derived:     true
Convertible to base: false
Base to convertible: false
-----------
Base to base:        true
Base to derived:     false
Derived to base:     true
Unrelated to base:   false
uint32 to uint64:    false
uint64 to uint32:    false
Base to void:        true
Void to derived:     true
Convertible to base: false
Base to convertible: false

The second half to my questions is if this workaround is on the right track, and, more specifically, if || std::is_convertible<From, To>() should be
included. Is it possible to have is_convertible return true when passed
pointers to types as template parameters? The code above includes my own ham-handed attempt to get it to work.
Footnote: I'm aware that base_type * casts to derived_type * successfully, but I'm not the compiler and cannot make that assumption.

A: It seems you want:
template <typename T, typename U, typename = void>
struct is_safely_castable : std::false_type {};

template <typename T, typename U>
struct is_safely_castable<T, U,
                          std::void_t<decltype(static_cast<U>(std::declval<T>()))>>
: std::true_type
{};

Demo


text:
Q: Number of passes in external merge There doesn't seem to be any preexisting questions on this, at least from a title search. I am seeking to find the optimal amount of passes for an external merge. So, if we have 1000 chunks of data, one pass would be a 1000 way merge. Two pass could be 5 groups of 200 chunks, then a final merge of 1 group of 5 chunks. And so on. I've done some math, which must have a flaw, because it looks like two passes never beats one pass. It could very well be a misunderstanding in how data is read, though.
First, a numerical example:
Data: 100 GB
Ram: 1 GB
Since we have 1GB memory, we can load in 1GB at a time to sort using quicksort or mergesort. Now we have 100 chunks to sort. We can do a 100 way merge. This is done by making RAM/(chunks+1) size buckets = 1024MB/101 = 10.14MB. There are 100 10.14MB buckets for each of the 100 chunks, and one output bucket also of size 10.14MB. As we merge, if any input buckets empty, we do a disk seek to refill that bucket. Likewise, when the output bucket gets full, we write to the disk and empty it. I claim that the number of "times the disk needs to read" is (data/ram)*(chunks+1). I get this from the fact that we have ram/(chunks+1) sized input buckets, and we must read in the entire data for a given pass, so we read (data/bucket_size) times. In other words, every time an input bucket empties we must refill it. We do this over 100 chunks here, so numChunks*(chunk_size/bucket_size) = datasize/bucket_size or 100*(1024MB/10.14MB). BucketSize = ram/(chunks+1) so 100*(1024/10.14) =  (data/ram) * (chunks+1) = 1024*100MB/1024MB * 101 = 10100 reads.
For a two pass system, we do A groups of B #chunks, then a final merge of 1 group of A #chunks. Using previous logic, we have numReads = A*( (data/ram)*(B+1)) + 1*( (data/ram)*(A+1)). We also have A*B = Data/Ram. For instance, 10 groups of 10 chunks, where each chunk is a GB. Here, A = 10 B = 10. 10*10 = 100/1 = 100, which is Data/Ram. This is because Data/Ram was the original number of chunks. For 2 pass, we want to break Data/Ram into A groups of B #chunks.
I'll try to break down the formula here, let D = data, A = #groups, B = #chunks/group, R = RAM
A*(D/R)*(B+1) + 1*(D/R)*(A+1) - This is A times the number of reads of an external merge on B #chunks plus the final merge on A #chunks.
A = D/(R*B) => D^2/(B*R^2) * (B+1) + D/R * (D/(R*B)+1)

(D^2/R^2)*[1 + 2/B] + D/R is number of reads for a 2 pass external merge. For 1 pass, we have (data/ram)*(chunks+1) where chunks = data/ram for 1 pass. Thus, for one pass we have D^2/R^2 + D/R. We see that a 2 pass only reaches that as the chunk size B goes to infinity, and even then the additional final merge gives us D^2/R^2 + D/R. So there must be something about the reads I'm missing, or my math is flawed. Thanks to anyone who takes the time to help me!

A: You ignore the fact that the total time it takes to read a block of data from disk is the sum of

*

*The access time which is roughly constant and on the order of several milliseconds for rotating hard disk drives.

*The transfer time which depends on the size of the data block and the transfer rate.

As the number of chunks increases, the size of the input buffers (you call them buckets) decreases. The smaller the input buffers get, the more pronounced is the effect of the constant access time on the total time is takes to fill a buffer. At a certain point, the time to fill a buffer will be almost completely dominated by the access time. So the total time for a merge pass begins to scale with the number of buffers and not the amount of data read.
That's where additional merge passes can speed up the process. It allows to use fewer and larger input buffers and mitigates the effect of access time.
Edit: Here's a quick back-of-the-envelope calculation to give an idea about where the break-even point is.
The total transfer time can be calculated easily. All the data has to read and written once per pass:
total_transfer_time = num_passes * 2 * data / transfer_rate

The total access time for buffer reads is:
total_access_time = num_passes * num_buffer_reads * access_time

Since there's only a single output buffer, it can be made larger than the input buffers without wasting too much memory, so I'll ignore the access time for writes. The number of buffer reads is data / buffer_size, buffer size is about ram / num_chunks for the one-pass approach, and the number of chunks is data / ram. So we have:
total_access_time1 = num_chunks^2 * access_time

For the two-pass solution, it makes sense to use sqrt(num_chunks) buffers to minimize access time. So buffer size is ram / sqrt(num_chunks) and we have:
total_access_time2 = 2 * (data / (ram / sqrt(num_chunks))) * acccess_time
                   = 2 * num_chunks^1.5 * access_time

So if we use transfer_rate = 100 MB/s, access_time = 10 ms, data = 100 GB, ram = 1 GB, the total time is:
total_time1 = (2 * 100 GB / 100 MB/s) + 100^2 * 10 ms
            = 2000 s + 100 s = 2100 s
total_time2 = (2 * 2 * 100 GB / 100 MB/s) + 2 * 100^1.5 * 10 ms
            = 4000 s + 20 s = 4020 s

The effect of access time is still very small. So let's change data to 1000 GB:
total_time1 = (2 * 1000 GB / 100 MB/s) + 1000^2 * 10 ms
            = 20000 s + 10000 s = 30000 s
total_time2 = (2 * 2 * 1000 GB / 100 MB/s) + 2 * 1000^1.5 * 10 ms
            = 40000 s + 632 s = 40632 s

Now half the time in the one-pass version is spent with disk seeks. Let's try with 5000 GB:
total_time1 = (2 * 5000 GB / 100 MB/s) + 5000^2 * 10 ms
            = 100000 s + 250000 s = 350000 s
total_time2 = (2 * 2 * 5000 GB / 100 MB/s) + 2 * 5000^1.5 * 10 ms
            = 200000 s + 7071 s = 207071 s

Now the two-pass version is faster.

A: To get an optimum you need a more sophisticated model of the disk.  Let time to fill a block of size S be rS + k where k is seek time and r is read rate.
If you divide RAM of size M into C+1 buffers of size M/(C+1), then the time to load RAM once is (C+1) (r M/(C+1) + k) = rM + k(C+1).  So as you'd expect, making C smaller speeds up read time by eliminating seeks.  It's fastest to read all of memory in one sequential block, but merging doesn't allow it.  We must make a tradeoff. That's where we need to look for the optimum.
With total data size of c times RAM size, there are c chunks to be merged.
In the one pass scheme, C=c, and the total read time must be just the time to fill RAM c times over: c (rM + k(c+1)) = c(rM + kc + k).
In the two pass scheme with an N-way division of data for the first pass, that pass has C=c/N and in the second pass, C=N.  So total cost is
c ( rM + k(c/N+1) ) + c ( rM + k(N+1) ) = c ( 2rM + k(c/N + N) + 2k )

Note this model omits write time.  You should fill that in eventually unless you're assuming it's overlapped I/O on a different device and thus can be ignored.
It's not hard to see here that if c and k are suitably large, then the c/N+N term in the 2-pass model can be so small compared to the c in the one-pass that the 2-pass model will be faster.
I'm going to stop now, but you can carry this logic on to (probably) get a closed approximation formula for an arbitrary number of passes.  THis will require solving an infinite series. Then you can set the derivative to zero and solve for an estimate of the optimal pass number.  If life is good you'll also learn the optimal value of N by setting the gradient of a 2d function in pass number and N to zero. My intuition says N ~ sqrt(c).
If the math gets intractable, you could still simulate a reasonable range of numbers of passes with the kind of simple algebra above at the start and pick an optimum that way.
This is an interesting problem and I'm sorry I don't have more time to work on it at the moment.  I hope the analysis framework is enough to let you punch through to a nice result.


text:
Q: How to go from C/C++ & Python Game programming into Web Programming? I have been programming in C/C++ for about five years and Python for three; I mainly program in Python though. My main focus has been on Game programming and Network programming (centered on making scalable multi-player servers.) Recently I have been wanting to switch over to web programming; predominately client-side based applications written in javascript. I was looking to find some advice as to where to get started. I would like to know if there are any decent-good materials on learning javascript, mixed with web programming, for a more advanced programmer. My main problem is that there are just so many sources out there that I don't know where to start. Any advice would be much appreciated.

A: First of all, you've probably heard about flash, which can be a pretty consistent game platform, but requires a browser plugin. ActionScript 3 is pretty similar to JavaScript and is actually based on ES4, which is trashed in favor of ES5 (ES == EcmaScript == JavaScript).
To create pure HTML/JS games, canvas based frameworks are your best chance in terms of standards and wide browser support, whilst SVG is actually a better candidate imo. due to interactivity options, but <canvas> is becomming the standard.
3D is possible however very processor intensive so in the end not YET viable, flash for 3D is still a better option.
Below are a few links of JS game engines I googled quickly for, I am sure there are more out there.
GameJS
GameQuery


text:
Q: How do the sniper rifle modifications work?
*

*If I'm a soldier or infiltrator, can I get an even higher level of time dilation during scoping by adding the concentration mod for the sniper rifle?

*Does the sniper rifle clip size mod round up or down?  If I have a Mantis and I put in a 70% clip size mod, will I now have 2 shots or still 1?

*How exactly does the extended scope mod work with smoke, will it let me see through it or does it highlight targets inside smoke?

A: Both the concentration mod and adrenaline rush (soldier) or operational mastery (infiltrator) stack.
This is on the ME wiki under weapon mods/sniper concentration mod.
Slows time briefly when zooming in. (Stacks with Adrenaline Rush and Operational Mastery).
This is the link to the site this information is pulled from.
Both of the other mods you mention are below, however they don't clearly state the answer you are looking for, so unless it is tested we cannot find out.
The sniper clip I think can be tested at the target practice, however the smoke grenade would require real combat to test.

A: *

*Yes, the concentration mod will stack with the Infiltrator's Operational Mastery, or the Soldier's Adrenaline Rush.

*The Spare Thermal Clip upgrade increases your overall ammo capacity for the rifle, but doesn't impact the clip size. So, in the case of the Mantis, your clip size will always be one. Your spare ammo capacity, on the other hand, will be increased by the given percentage, rounded down (need to verify the rounding, but memory-maths tells me this is the case).

*The Extended Scope upgrade highlights targets within the smoke, using an orange/red outline. I found this had mixed success depending on how close the target was to the smoke, since sometimes they would fade out of view.

A: *

*To put it simply Samuels correct, but if you want to get into more technical terms the concentration mod is connected to your brain somehow and increases concentration by increasing hormone production or creating more bioelectrical currents.

2.I am almost certain it rounds down.
3.It highlights the target like if you were targeting him.


text:
Q: Session data not retaining in Ajax requests to https On my localhost I am making an ajax call to a url which is on https i.e. from http://localhost/MySite to https://localhost/MySite/user/register. So basically I am doing ajax request from http to https. To avoid CORS error I have also set following header.
$accessControlAllowOrigin = 'http://localhost';
header("Access-Control-Allow-Origin: $accessControlAllowOrigin");
Now on the first Ajax request I am setting some data in Session. But on the subsequent Ajax requests, I am not getting that Session data.Also when I print session id for the first & subsequent requests, they are different.
So I am not able to access session data in the later requests. Where I am going wrong?


text:
Q: Python generator pre-fetch? I have a generator that takes a long time for each iteration to run.  Is there a standard way to have it yield a value, then generate the next value while waiting to be called again?
The generator would be called each time a button is pressed in a gui and the user would be expected to consider the result after each button press.
EDIT: a workaround might be:
def initialize():
    res = next.gen()

def btn_callback()
    display(res)
    res = next.gen()
    if not res:
       return

A: No.  A generator is not asynchronous.  This isn't multiprocessing.
If you want to avoid waiting for the calculation, you should use the multiprocessing package so that an independent process can do your expensive calculation.
You want a separate process which is calculating and enqueueing results.
Your "generator" can then simply dequeue the available results.

A: If I wanted to do something like your workaround, I'd write a class like this:
class PrefetchedGenerator(object):
    def __init__(self, generator):
         self._data = generator.next()
         self._generator = generator
         self._ready = True

    def next(self):
        if not self._ready:
            self.prefetch()
        self._ready = False
        return self._data

    def prefetch(self):
        if not self._ready:
            self._data = self._generator.next()
            self._ready = True

It is more complicated than your version, because I made it so that it handles not calling prefetch or calling prefetch too many times. The basic idea is that you call .next() when you want the next item. You call prefetch when you have "time" to kill.
Your other option is a thread..
class BackgroundGenerator(threading.Thread):
    def __init__(self, generator):
        threading.Thread.__init__(self)
        self.queue = Queue.Queue(1)
        self.generator = generator
        self.daemon = True
        self.start()

    def run(self):
        for item in self.generator:
            self.queue.put(item)
        self.queue.put(None)

    def next(self):
            next_item = self.queue.get()
            if next_item is None:
                 raise StopIteration
            return next_item

This will run separately from your main application. Your GUI should remain responsive no matter how long it takes to fetch each iteration.

A: You can definitely do this with generators, just create your generator so that each next call alternates between getting the next value and returning it by putting in multiple yield statements.  Here is an example:
import itertools, time

def quick_gen():
    counter = itertools.count().next
    def long_running_func():
        time.sleep(2)
        return counter()
    while True:
        x = long_running_func()
        yield
        yield x

>>> itr = quick_gen()
>>> itr.next()   # setup call, takes two seconds
>>> itr.next()   # returns immediately
0
>>> itr.next()   # setup call, takes two seconds
>>> itr.next()   # returns immediately
1

Note that the generator does not automatically do the processing to get the next value, it is up to the caller to call next twice for each value.  For your use case you would call next once as a setup up, and then each time the user clicks the button you would display the next value generated, then call next again for the pre-fetch.

A: I was after something similar. I wanted yield to quickly return a value (if it could) while a background thread processed the next, next.
import Queue
import time
import threading

class MyGen():
    def __init__(self):
        self.queue = Queue.Queue()
        # Put a first element into the queue, and initialize our thread
        self.i = 1
        self.t = threading.Thread(target=self.worker, args=(self.queue, self.i))
        self.t.start()

    def __iter__(self):
        return self

    def worker(self, queue, i):
        time.sleep(1) # Take a while to process
        queue.put(i**2)

    def __del__(self):
        self.stop()

    def stop(self):
        while True: # Flush the queue
            try:
                self.queue.get(False)
            except Queue.Empty:
                break
        self.t.join()

    def next(self):
        # Start a thread to compute the next next.
        self.t.join()
        self.i += 1
        self.t = threading.Thread(target=self.worker, args=(self.queue, self.i))
        self.t.start()

        # Now deliver the already-queued element
        while True:
            try:
                print "request at", time.time()
                obj = self.queue.get(False)
                self.queue.task_done()
                return obj
            except Queue.Empty:
                pass
            time.sleep(.001)

if __name__ == '__main__':
    f = MyGen()
    for i in range(5):
#        time.sleep(2) # Comment out to get items as they are ready
        print "*********"
        print f.next()
        print "returned at", time.time()

The code above gave the following results:
*********
request at 1342462505.96
1
returned at 1342462505.96
*********
request at 1342462506.96
4
returned at 1342462506.96
*********
request at 1342462507.96
9
returned at 1342462507.96
*********
request at 1342462508.96
16
returned at 1342462508.96
*********
request at 1342462509.96
25
returned at 1342462509.96


text:
Q: C++ call a function that outputs info from a txt file So I am a beginner in C++ and just completely stuck on a problem. I have background using Java which I am trying to apply but I end up just confusing myself even more. My teacher really hasn't taught us enough on C++ so I've been researching and youtubing for hours on end for something that could help me.
The problem is this:
Write a C++ program that:

*

*Uses input redirection to go through the file of sections and counts how many of the 2660 courses are GERs. Output the count to the screen. Note that the section number sometimes contains letters, so you should read it in as a string (same as the course number).

*Calls a function for each section. The function should output the course subject and number if the course is a GER and has CSCE as the course subject.

I already did part one and it works correctly. The txt file Im using contains the CRN, subject, course number, and yes/no on whether it is a GER for 2660 different courses.
My problem is with number 2. I haven't learned how to call a string or even use a string in a function like this.
This is what I have so far. The first part i am probably completely off but my int main i know is correct
Any input or a push in the right direction is greatly appreciated! thanks
#include <iostream>
#include <string>
using namespace std;

void printCsce(int total, int CRN, std::string subject, std::string courseNum,
std::string courseSection, std::string yesNo);

void  printCsce(int total, int CRN, std::string subject, std::string courseNum,
std::string courseSection, std::string yesNo){
    total=2660;
    for (int i=0; i <total; i++){
    cin >> CRN;
    cin >> subject;
    cin >> courseNum;
    cin >> courseSection;
    cin >> yesNo;

    if (subject=="CSCE" && yesNo=="Yes"){
    std::cout << CRN << subject << endl;
}
}
}

int main()
{
    int total=2660;
    int CRN;
    string subject;
    string courseNum;
    string courseSection;
    string yesNo;
    int sum=0;

    cin >> total;
    for (int i=0; i<total; i++)
    {
cin >> CRN;
    cin >> subject;
    cin >> courseNum;
    cin >> courseSection;
    cin >> yesNo;

    if (yesNo=="Yes") {
     sum++;
    }
}
cout << "There are "<< sum << " courses that are GERS."<<  endl;
    cout << printCsce << endl;
}

A: You have to take references for your arguments. When you pass by-value, the compiler makes copies so the extraction (cin >> x) only affects a local copy of the object:
void printCsce(int& total, int& CRN, std::string& subject,
    std::string& courseNum, std::string& courseSection, std::string& yesNo);


text:
Q: There are class methods. Can I have class attributes? Consider the code snippet for the base class Base and its two child classes ChildA and ChildB:
class Base():
    map = {}

    def __init__(self, x):
        type(self).map[x] = self

    @classmethod
    def get_state(cls, x):
        if x in cls.map:
             return cls.map[x]
        return None

class ChildA(Base):
    pass

class ChildB(Base):
    pass

When creating an instance a = ChildA('foo') and calling ChildB.get_state('foo') after this, it returns the instance of ChildA.
However, expected (or rather the wishful behaviour) was None. The map attribute seems to be attached to the parent class Base, and the child classes share it.
Of course I could simply add a specific attribute to the child classes
class ChildA(Base):
    map = {}

class ChildB(Base):
    map = {}

but this is verbose if you have many child classes and several of those attributes. Is there any way to solve this by inheritance from Base?

A: You can use the init subclass hook:
class Base:
    def __init_subclass__(cls, **kwargs):
        cls.map = {}

Demo:
>>> class ChildA(Base):
...     ...
...
>>> class ChildB(Base):
...     ...
...
>>> ChildA.map == ChildB.map == {}
True
>>> ChildA.map is ChildB.map
False


text:
Q: Asymptotic for primitive Dirichlet characters over primes The Polya-Vinogradov's inequality states that if $\chi$ is a primitive character mod $q$ then $|\sum_{n\le x}\chi(n)|\le \sqrt{q}\log q$. I now want to give the estimation for the sum over primes, i.e. $\sum_{p\le x}\chi(p)$ and wonder if we can apply the Polya-Vinogradov's method?
It is proved in the book of H. Iwaniec and E. Kowalski (Corollary 5.29) that $\sum_{p\le x}\chi(p)<< \sqrt{q}x(\log x)^{-A}$ for any $A>0$ but the proof is somewhat complicated. Can we have the simpler proof for this fact?


text:
Q: Visual Java App that runs on Windows and Linux This is a noob question I know, but is it possible to really write a program in Java that runs on Linux and Windows? The equivalent to what is known as a Windows Form Application in the .Net world?
I don't want a "console app", but I'm after a rich front end type application that will run on Windows 7 (64bit) and Linux Ubuntu.
Is a write once solution possible?
EDIT, what I'm after is a yes (absolutely) or yes with difficulty or no, language X is more suitable, type of answer.

A: As Daniel mentioned, you can use SWT but also if you just look for a tutorial on Swing this will give a good foundation on Java GUI that will work on both platforms.  There isn't really a more suitable application language that's as high level.

A: Of course! If you use SWT, you even get native widgets for free! :)
We have written a complete ERP that runs on Windows, Mac OS and Linux. There are some gotchas, but the parts of the app that have to be modified to be really platform independent are about 0.1%, if you do it right.


text:
Q: Check whether SMS available in unity3D (ios, android) I'm trying to find out a way in unity to check whether device supports SMS or not. I'm using Etcetera plugins for Android and IOS. It works like a charm in IOS but in Android, EtceteraAndroid.isSMSComposerAvailable(), it always gives 'false' even your device supports SMS. This is a bug in this plugin.
Is there any other way can I detect SMS in unity3D?

A: Prime31 EtceteraAndroid uses hasSystemFeature(PackageManager.FEATURE_TELEPHONY) to check if telephony feature exist on target device.
PackageManager.FEATURE_TELEPHONY works since Android API level 7(Android OS 2.1)
hasSystemFeature works since Android API level 5(Android OS 2.0)
Can you report your OS version on your target phone?


text:
Q: Simplify integral considering only the real part I happened to stumble on the following simplification of an integral:
$$ \frac{1}{\pi} \int_{0}^{\infty} dx \ e^{-ax}  \cdot \cos(kx) = \frac{1}{\pi} Re \left[ \int_{0}^{\infty} dx \ e^{x (ik - a)}  \right]   $$
According to my reasoning: $ \cos(kx) = \frac{1}{2} \left( e^{ikx} + e^{-ikx}  \right)  $, so the term on the exponent on the right side comes somehow from the first term of the complex form of $\cos(kx)$, but the second term gets cancelled, why?

A: Consider first $e^{ikx} = \cos(kx) + i \sin(kx)$ then you can easily deduce that
$$
Re(e^{ikx}) = \cos(kx).
$$


text:
Q: RestController with a mapping to retrieve entity with or without children I'm sure this should be simple, but I just can't seem to figure out how to do this.
We have an entity with a oneToMany relationship to another entity. Basic parent/child relationship (Using Spring/JPA).
The requirement is to have an api '/parents' which provides all of the parents and another '/parents_with_children' that provides all of the parents and their related child entities.
Now to get the parents with their children, we can specify "@OneToMany(fetch = FetchType.EAGER) and this is working fine.
But, how can I tell my RestController class to return only the top level components without cascading?
// Works fine with eager fetching
@GetMapping("/parents_with_children")
public List<Parent> list() {
    return ParentService.getParents();
}

// How can I tell this one to NOT print out the children?
@GetMapping("/parents")
public List<Parent> list() {
    return ParentService.getParents();
}

Should I manually print & return JSON data from the entities some how?

A: You can use a DTO pattern (simple POJO) as an abstraction of your Entity. You can define these such as ParentDto and create all the methods that you want to return in the JSON.
The idea is to grab your entity from the DB, map it to the DTO. In the case of your /parents without children, you would simply not set the children list (leave it null).
You can then mark that field with @JsonInclude(JsonInclude.Include.NON_NULL) which will only show this field in the JSON if it's set.
public class ParentDto {

   @JsonInclude(JsonInclude.Include.NON_NULL)
   private List<Children> children;

   // other private members
   // getters/setters
}

There are a few libraries that can do the mapping for you such as mapstruct or ModelMapper or you can map the Parent entity to ParentDto yourself.
Then your controller would return DTOs.
public List<ParentDto> list();


text:
Q: Powershell Loop though specific json files from multiple folders and use that json file to push into Loop $tenantID = (Get-AzureADTenantDetail).ObjectId
$mg = "/providers/Microsoft.Management/managementGroups/" + $tenantID

foreach($subfolder in Get-ChildItem -Path C:\Users\xxxx\Desktop\AzurePolicies -Depth 2 -Recurse){
    Write-Host "Subfolder is " $subfolder
    foreach($file in Get-ChildItem -Path $subfolder -File *.json -Recurse){
        foreach($policy in $file){
            $displayname = (Get-Content $file -Raw | ConvertFrom-Json).properties.displayName
            Write-Host "Display name is" $displayname
            $policyname = (Get-Content $policy -Raw | ConvertFrom-Json).properties.name
            Write-Host "Policy name is" $policyname
            foreach ($item in $policy) {
                function DefinePolicies {
                    New-AzPolicyDefinition -Name $policyname -DisplayName $displayname -Policy $policy   -ManagementGroupName $tenantID
                    Start-Sleep -Seconds 2
                }
                DefinePolicies
                function AssignPolicies {
                    $policy = Get-AzPolicyDefinition -Name $policyname  -ManagementGroupName $tenantID
                    New-AzPolicyAssignment -Name $policyname -PolicyDefinition $policy -Scope $mg
                     Start-Sleep -Seconds 2
                }
                AssignPolicies
            }
            }
    }
}

My Files are organized as Azurepolicies/Keyvaults/Somepolicy/azurepolicy.json


text:
Q: HashiCorp Vault doesn't inject SideCar container to new pods Our application runs on Kubernetes and secrets are basically stored in HashiCorp Vault. We are using the AppRole Authentication method where the Vault agent resides in the same cluster but, the Vault Server runs in a different Kubernetes cluster.
I'm passing the below annotations to my Kubernetes manifests but the issue I'm having is, when the Pod gets automatically ReScheduled (Due to autoscaling etc.) the Vault agent doesn't inject the SideCar container to the newly rescheduled pod.
NOTE: This only happens when the Pod gets ReScheduled automatically.
annotations:
        vault.hashicorp.com/agent-inject: 'true'
        vault.hashicorp.com/agent-vault-addr: 'URL-Of-Vault-Server'
        vault.hashicorp.com/auth-type: 'approle'
        vault.hashicorp.com/auth-path: 'auth/approle'
        vault.hashicorp.com/auth-config-role-id-file-path: '/vault/custom/role-id'
        vault.hashicorp.com/auth-config-secret-id-file-path: '/vault/custom/secret-id'
        vault.hashicorp.com/agent-extra-secret: 'my-approle'
        vault.hashicorp.com/role: 'myrole'
        vault.hashicorp.com/auth-config-remove_secret_id_file_after_reading: 'false'
        vault.hashicorp.com/agent-inject-secret-config.env: 'kv/mysecrets/secrets'
        vault.hashicorp.com/agent-inject-template-config.env: |
          {{ with secret "kv/mysecrets/secrets/" -}}
             export JAVA_TOOL_OPTIONS="Some_Key={{ .Data.data.SECRET }} "
          {{- end }}

Any idea why it doesn't inject the SideCar container to the newly rescheduled pods?
Do I need to pass these Annotations also?
vault.hashicorp.com/agent-inject-status
vault.hashicorp.com/agent-pre-populate


text:
Q: How to fix the error caused by" when used with numbers and tapply? R, package arrangements I'm using the package arrangements v1.1.5 with R v3.5.3 in Windows 10.
And I think I have found a strange error or I'm doing something wrong.
This is working
library(arrangements)
myDF <- data.frame(A=c("a","b","c"), B=c(2000,2000,2002))
tapply(myDF$A,myDF$B, permutations)

$`2000`
     [,1] [,2]
[1,] a    b
[2,] b    a
Levels: a b c

$`2002`
     [,1]
[1,] c
Levels: a b c

But this isn't working:
library(arrangements)
myDF <- data.frame(A=c(200,200,200), B=c(0,0,2))
tapply(myDF$A,myDF$B, permutations)

Error in FUN(X[[i]], ...) : too many results

What am I doing wrong?
I just want to generate the permutations of the elements of A defined by the group B.
The result should be like the former example but with numbers instead of letters.

A: Check out the documentation at ?permutations. Note that the first parameter is described as

x -- an integer or a vector, will be treated as n if integer; otherwise, will be treated as v

So the function behaves differently if you pass in a number or a factor. If you want to those values to be drawn from like the first example, you can just pass the value directly to the v= parameter.
tapply(myDF$A, myDF$B, function(x) permutations(v=x))


text:
Q: Django application not running with Gunicorn and Supervisor I am trying to run a Django application from gunicorn and supervisord. I have configured bash script to run application from gunicorn which is working fine and I am able to see the GUI but when I was trying to start this application from supervisorctl. I am not able to see the GUI. However, Gunicorn processes are running.
gunicorn_start2
#!/bin/bash
export ANALYTICS_ENV="dev"
NAME="analytics"                                  # Name of the application
DJANGODIR=/home/ubuntu/code/current/analytics/analytics/analysis/             # Django project directory
SOCKFILE=/home/ubuntu/code/current/analytics/analytics/run/gunicorn.sock  # we will communicte using this unix socket
USER=ubuntu                                       # the user to run as
GROUP=ubuntu                                     # the group to run as
NUM_WORKERS=3                                     # how many worker processes should Gunicorn spawn
DJANGO_SETTINGS_MODULE=analytics.settings             # which settings file should Django use
DJANGO_WSGI_MODULE=analytics.wsgi                     # WSGI module name

echo "Starting $NAME as `whoami`"

# Activate the virtual environment
cd $DJANGODIR
echo $DJANGODIR
source /home/ubuntu/code/current/analytics/analytics/bin/activate
export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
#export PYTHONPATH=$DJANGODIR:$PYTHONPATH
#export PYTHONPATH=/home/ubuntu/code/analytics/bin/python
# Create the run directory if it doesn't exist
RUNDIR=$(dirname $SOCKFILE)
test -d $RUNDIR || mkdir -p $RUNDIR

# Start your Django Unicorn
# Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon)
exec /home/ubuntu/code/current/analytics/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \
  --name $NAME \
  --workers $NUM_WORKERS \
  --user=$USER --group=$GROUP \
  --bind=unix:$SOCKFILE \
  --log-level=all \
  --log-file=-

gunicorn_start.conf
[program:analytics]
command = bash /home/ubuntu/code/current/analytics/analytics/analysis/gunicorn_start2                    ; Command to start app
user = ubuntu                                    ; User to run as
stdout_logfile = /home/ubuntu/code/current/analytics/analytics/analysis/gunicorn_start2.log   ; Where to write log messages
redirect_stderr = true                                                ; Save stderr in the same log
environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8,ANALYTICS_ENV=dev                     ; Set UTF-8 as default encoding

Gunicorn Processes:
(analytics) ubuntu@ip-172-31-25-151:~/code/current/analytics/analytics/analysis$ ps aux | grep [g]unicorn
ubuntu   16039  0.3  0.9  57152 18436 ?        S    14:47   0:00 /home/ubuntu/code/current/analytics/bin/python2 /home/ubuntu/code/current/analytics/bin/gunicorn analytics.wsgi:application --name analytics --workers 3 --user=ubuntu --group=ubuntu --bind=unix:/home/ubuntu/code/current/analytics/analytics/run/gunicorn.sock --log-level=all --log-file=-
ubuntu   16050  1.1  2.3 276744 48792 ?        Sl   14:47   0:00 /home/ubuntu/code/current/analytics/bin/python2 /home/ubuntu/code/current/analytics/bin/gunicorn analytics.wsgi:application --name analytics --workers 3 --user=ubuntu --group=ubuntu --bind=unix:/home/ubuntu/code/current/analytics/analytics/run/gunicorn.sock --log-level=all --log-file=-
ubuntu   16053  1.1  2.3 276760 47212 ?        Sl   14:47   0:00 /home/ubuntu/code/current/analytics/bin/python2 /home/ubuntu/code/current/analytics/bin/gunicorn analytics.wsgi:application --name analytics --workers 3 --user=ubuntu --group=ubuntu --bind=unix:/home/ubuntu/code/current/analytics/analytics/run/gunicorn.sock --log-level=all --log-file=-
ubuntu   16056  1.1  2.3 276768 47228 ?        Sl   14:47   0:00 /home/ubuntu/code/current/analytics/bin/python2 /home/ubuntu/code/current/analytics/bin/gunicorn analytics.wsgi:application --name analytics --workers 3 --user=ubuntu --group=ubuntu --bind=unix:/home/ubuntu/code/current/analytics/analytics/run/gunicorn.sock --log-level=all --log-file=-
(analytics) ubuntu@ip-172-31-25-151:~/code/current/analytics/analytics/analysis$

It seems that the issue is with the environmental variable. Because when I am trying to run python manage.py runserver then its also not working. But when I am running ANALYTICS_ENV=dev python manage.py runserver then it's working.
However, I am unable to run it with gunicorn in anyway.
Any idea?

A: This has been solved by below steps.

*

*source virtualenv

*Export ANALYTICS_ENV.

*Export PYTHONPATH of virtualenv.

Supervisor Configuration:
[program:analytics]
command = gunicorn analytics.wsgi:application --name analytics --workers 4 --user=ubuntu --timeout=3600 --bind 127.0.0.1:8000 ; Command to start app
user = ubuntu ; User to run as
stdout_logfile = /home/code/example/gunicorn_start2.log ; Where to write log messages
redirect_stderr = true ; Save stderr in the same log
environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8,ANALYTICS_ENV=dev,PYTHONPATH=/home/ubuntu/code/current/analytics/bin/python ; Set UTF-8 as default encoding


text:
Q: How to change SQLite version used by Python? I have Python 3.8 installed alongside SQLite 3.16.2 on Debian 9.12 and I need to upgrade to a newer version of SQLite. I've downloaded and compiled the amalgamation available on the SQLite's site, and put it in /usr/bin, so when I do
$ sqlite3 --version

I get 3.32.3 in response (which is the version I compiled).
However, when I do
$ python3.8
>>> import sqlite3
>>> sqlite3.sqlite_version

I get 3.16.2, which is the earlier version. How do I change the SQLite version picked up by Python?
mkrieger1 suggested that this question may answer mine. It won't work here, as the solution provided there is directed at Python 2, not Python 3. pysqlite2 does not work with Python 3.

A: In my case I cannot replace with newer version because I cannot find these files. (I installed the sqlite-autoconf-3350500)
I used another manner to let it work just execute below command
export LD_LIBRARY_PATH="/usr/local/lib"

>>> import sqlite3
>>> sqlite3.sqlite_version
'3.35.5'

A: The way I would go around it, is by finding out the path to the old sqlite version that you are importing:
import sqlite3
print(sqlite3.__file__)

For me, this outputs:
C:\Users\YOUR_USERNAME_HERE\AppData\Local\Programs\Python\Python38\lib\sqlite3\__init__.py

Go to the lib path:
C:\Users\YOUR_USERNAME_HERE\AppData\Local\Programs\Python\Python38\lib

Then find the sqlite3 folder and delete it, then replace it with your up-to-date version. Re-try:
>>> import sqlite3
>>> sqlite3.sqlite_version

You should get your new version.


text:
Q: bitter intensity What is the meaning of bitter intensity? For example:

Here and there we find a slight suggestion of the bitter intensity of
  the poet X.

A: I don't think the phrase has any idiomatic significance. Its meaning is derived from the words constituting it.
Bitter has a negative connotation. For example, if we say that A and B are bitter enemies, it indicates a heightened level of animosity between them. Bitterness can also indicate cynicism or contempt. For example, one might say that losing his wife to a doctor's negligence has made XYZ bitter towards the medical profession.
Merriam-Webster:Bitter
Intensity implies ardency, fervour or passion.
Merriam-Webster:Intensity
Therefore, it is my guess that bitter intensity of a poet would indicate a generally negative outlook that the poet has harped upon with great fervor. In other words, saying that a person is bitterly intense implies that he is someone who might be persistently negative or bleak in his worldview.
However, this is only my interpretation.


text:
Q: ConTeXt SciTE tries to open sumatrapdf by default I just installed SciTE and ConTeXt on windows using the directions from this website http://wiki.contextgarden.net/Windows_Installation:_ConTeXt_Suite_with_SciTe
And it appears everything works but for one issue. When I press Ctrl+F12 to compile the tex file into a pdf, it complains because I don't have sumatrapdf installed. But I do have adobe's pdf viewer installed. I installed sumatrapdf and it launches sumatrapdf.
I would like to get it to launch Adobe's pdf reader. Any idea how to go about doing this?


text:
Q: Running App By Xcode in iOS simulator getting error. But in real device working Error-

*

*No such module 'AppsFlyerLib'

*Could not read serialized diagnostics file: error("Invalid diagnostics signature"). Command CompileSwift failed with a nonzero exit code


text:
Q: Prove that $\frac{\int_{0}^\infty x^n e^{-x^n} dx}{\int_{0}^\infty e^{-x^n} dx} = \frac{1}{n}$ What is the simplest way to prove that
$$\frac{\int_{0}^\infty x^n e^{-x^n} dx}{\int_{0}^\infty e^{-x^n} dx} = \frac{1}{n}$$
for all real $n > 0$? As an example, integration by parts can easily solve $n=2$:
$$\frac{\int_{0}^\infty x^2 e^{-x^2} dx}{\int_{0}^\infty e^{-x^2} dx} = \frac{xe^{-x^2}|_{0}^\infty - \int_{0}^\infty -\frac{1}{2}e^{-x^2}dx}{\int_{0}^\infty e^{-x^2}dx} = \frac{0+\frac{1}{2}\int_{0}^\infty e^{-x^2}dx}{\int_{0}^\infty e^{-x^2}dx} = \frac{1}{2}$$

A: It suffices to prove that
$$\int_0^\infty (x^n - 1/n)\mathrm{e}^{- x^n}\mathrm{d} x = 0$$
or
$$\int_0^\infty \left[-\frac{1}{n} x \mathrm{e}^{-x^n}\right]' \mathrm{d} x = 0$$
or
$$\left[-\frac{1}{n} x \mathrm{e}^{-x^n}\right]\Bigg\vert_0^\infty = 0$$
which is true.

A: Consider $$ \int_0^\infty x^\alpha e^{-x^\beta}\, dx$$ with $\alpha ≥ 0,\beta > 0$. Letting $y=x^\beta$ gives \begin{align*}
\int_0^\infty x^\alpha e^{-x^\beta}\, dx= \frac 1 \beta \int_0^\infty y^{\frac{\alpha+1}\beta-1} e^{-y}\, dy = \frac 1 \beta \Gamma \bigg (\frac{\alpha+1}\beta \bigg )
\end{align*} where $\Gamma$ is the Euler-Gamma function. Hence, $$ \frac{\int_0^\infty x^n e^{-x^n}\, dx}{\int_0^\infty e^{-x^n}\, dx}=\frac{\Gamma \big (\frac{1}n+1 \big )}{\Gamma \big (\frac1n \big )}=\frac{1}n$$ for all $n>0$.

A: Using integration by parts, we get $$
\begin{aligned}
 \int_{0}^{\infty} x^{n} e^{-x^{n}} d x
&=-\frac{1}{n} \int_{0}^{\infty} x d\left(e^{-x^{n}}\right) \\
\\&=-\frac{1}{n} \left[ x e^{-x^{n}} \right]^{\infty}+\frac{1}{n} \int_{0}^{\infty} e^{-x^{n}} d x\\& =\frac{1}{n} \int_{0}^{\infty} e^{-x^{n}} d x
\end{aligned}
$$
Hence we can conclude that $$
\frac{\int_{0}^{\infty} x^{n} e^{-x^{n}} d x}{\int_{0}^{\infty} e^{-x^{n}} d x}=\frac{1}{n}
$$


text:
Q: Find the minimum value $f(x) = \dfrac{e^x}{x^n}$ for $x>0$
Find the minimum value $f(x) = \dfrac{e^x}{x^n}$ for $x>0$ and conclude that $f(x) > \dfrac{e^n}{n^n}$ for $x > n$.

I found the derivative $\dfrac{d}{dx}\left(\dfrac{e^x}{x^n}\right) = e^x x^{-n-1} (x-n)$ and set it equal to zero to find that $x = n$ is the solution. Then I found the second derivative, which is $e^x x^{-2-n} (n+n^2-2 n x+x^2)$, and plugged in $x = n$ to find that it was positive implying that this is a global minimum.

A: A preliminary remark: note that the result is false for $n<0$ (because $f(x)$ assumes arbitrarily large negative values for small negative $x$ if $n$ is odd). You might think $n>0$ was implicit, but a careful reading shows it is not. [Thanks to @BarryCipra]
However, let us assume that $n>0$.
Yes, your proof is partially correct. To finish off you need to note that since $f(x)$ has a global minimum at $x=n$ we have $f(x)>f(n)$ for all $x>0$. [Thanks to @user1892304]
But it is not enough to find that the 2nd derivative is positive at a zero of the first derivative. That might or might not indicate a global minimum. To establish a global minimum at $x=n$ you need that the 1st derivative is $<0$ for $x<n$ and $>0$ for $x>n$. It is easy to see directly from the expression for the 1st derivative that this is true here. [Thanks to @AndreNicholas]
Alternatively, note that $n+n^2-2nx+x^2=n+(n-x)^2>0$ so that $f''(x)>0$ for all $x$, not just $f''(n)>0$. [Thanks to @BarryCipra]
The plot shows the case $n=3$


text:
Q: Express.js, I get colon in front of the value if my parameter value contains colon somewhere in a value This is my simple express.js code, and GET routing:
app.get(path + hashKeyPath, function (req, res) {
  res.json({
    data: JSON.stringify(req.params.CognitoIdentity),
    dekor: JSON.stringify(
      req.apiGateway.event.requestContext.identity.cognitoIdentityId
    ),
  });

const path = '/address';
const partitionKeyName = 'CognitoIdentity';
const hashKeyPath = '/:' + partitionKeyName;

now when I send a request, my parameter can contain colon inside of the string (aws cognito identity is built like that not sure why would they put colon inside instead of dash but ok):
eu-west-1:ea6b2959-8718-42b9-b8b8-ce82e9d9e7a0 which returns only colon back in response.
config: {url: 'https://xxx.execute-api.eu-west-1.amazonaws…s/:eu-west-1:ea6b2959-8718-42b9-b8b8-ce82e9d9e7a0', method: 'get', data: null, headers: {…}, transformRequest: Array(1), …}

data: {data: ':eu-west-1:ea6b2959-8718-42b9-b8b8-ce82e9d9e7a0', dekor: 'null'}
how can I get real value which would be eu-west-1:ea6b2959-8718-42b9-b8b8-ce82e9d9e7a0 and not colon as first char eu-west-1:ea6b2959-8718-42b9-b8b8-ce82e9d9e7a0 when I have coon inside of parameter value? well I assume it is doing it because of colon after eu-west-1...
Edit:
So it seems like no matter what you pass it gets : in front lol, what??
config: {url: 'https://xxx.execute-api.eu-west-1.amazonaws.com/dev/address/:kontono-test', method: 'get', data: null, headers: {…}, transformRequest: Array(1), …}
data: {data: ':kontono-test', dekor: 'null'}

A: In your examples you are sending values with leading : in URL param:
/:kontono-test
/:eu-west-1:ea6b2959-8718-42b9-b8b8-ce82e9d9e7a0
Try calling these endpoints without : in front.
Express won't remove the leading : from param value, because that can be a valid part of it.
You don't have to add : in URL when you are using URL params. For example:
in /address/:identity :identity will be available under req.params.identity, and you call this endpoint like so:
GET http://localhost:3000/address/foobar -> req.params.identity == 'foobar'
GET http://localhost:3000/address/:foobar -> req.params.identity == ':foobar'
GET http://localhost:3000/address/foo:bar: -> req.params.identity == 'foo:bar:'
GET http://localhost:3000/address/:foo:bar: -> req.params.identity == ':foo:bar:'


text:
Q: Is this a crazy way to handle multi Validation types with IDataError and WPF? We are using the standard method for our controls to report broken BO rules. This is done via the interface IDataError in our BO's and in XAML the control is bound to the BO's property etc. This approach works OK. But we need to show 2 types of visuals in the UI depending on the type (or category if you like) of the invalidation error. If it's a required field then we show a CueBanner (water mark) but for other types we change the colour of the controls boarder. In both scenarios we set the tool type of the error message.
The Problem with IDataError is that it doesn't support a method/property to distinguish between error types.
The only way I can do that is by examining the error text, required field text must contain the key word "required". The following approach doesn't feel right but it's the only way I can determine the type of error and then deal with it accordingly. All required field rules must have as part of the error text "required field".
To make this all work I have created a custom dependency property called ErrorMessage. In my ResourceDictionary I have a Style.Trigger for Validation.HasError. In there I set my dependency properties value to the ErrorContent. Now when my dependency properties value changes I can examine the text and set the Validation.SetErrorTemplate( myControl, newErrorTemplate) to the template to suit the error type. I have to wire up a few events to the control such as lost and got focus to manage removing or adding the cueBanner template but the whole thing will work. It's just that I'm not sure it's the best way to do it.
PS. When I set the ErrorTemplate i'm doing this in code, thats building and adding it. Is there a way to point Validation.SetErrorTemplate to a static resource keeping in mind that I need to switch between at least 2 types?
Your thoughts please..

A: Would it be possible to derive an interface IDataError that adds an extra property which is an enumeration of the error type. Then you could try and bind against it.

A: If you're okay with an (untested)approach that suffers a little bit of clarity, then you could do the following:
throw an exception instead of returning an string with the IDataErrorInfo Interface. In your ErrorTemplate, you can access the ValidationErrors (and the ValidationError.Exception Property).
Then, you use a DataTrigger on the Exception in combination with a converter, that checks for the right Exception-Type and return true or false. It should be enough to do the job.


text:
Q: How can I serialize a RealmObject to JSON in Realm for Java? I am implementing a DB for my Application and I am trying "connect" it to my REST interface. The data comes in as JSON and with the new JSON-Support (as of Realm 0.76) I can throw the JSON at my Realm.createObjectFromJson(MyType.class, jsonString) and it creates the appropiate obejcts and RealmLists.
But how can I do the opposite? That is, take a RealmObject and serialize it to JSON? It also should serialize any RealmList inside that object.

A: to deserialize JSON into RealmObject use on of the following
say you have a class definition like this
 @RealmClass
 public class Foo extends RealmObject{
  private String name;
  public void setName(String name){ this.name = name}
  public String getName(){ return this.name}
}

and a json payload like this:
 String json = "{\"name\":\"bar\"}";
 Foo fooObject= realm.createObjectFromJson(Foo.class, json);
 //or
 String jsonArray = "[{\"name\":\"bar\"},{\"name\":\"baz\"}]";
 RealmList<Foo> fooObjects = realm.createAllFromJson(Foo.class, jsonArray);

However the reverse is not natively supported in realm-core. so this is how i work around it. i attempted to use GSON, but ended up writing too many codes that i myself did not understand so i implemented my own adapter like this.The problem is RealmObjects are not 'realm' java.lang.Object.
create an adapter that takes instance of your realm object and return its JSON representation.
example.
 public class RealmJsonAdapter{
    public JSONObject toJson(Foo foo){
     JSONObject obj = new JSONObject();
     obj.putString("name",foo.getName());
     //if you have more fields you continue
     return obj;
     }
   }

you can now use this adapter in your classes to serialize you RealmObject to
JSON. prefferably you would make the adapter an interface so that you let callers (might be you yourself) pass you the adapter the want to use.
you can then call say, adapter.toJSON(realmObjectInstance). and get your JSONObject implementation
after all you care only about the JSON and not the RealmObject.
NOTE
This solution is a bit oudated. RealmObjects are now real java objects so you should be able to use it with GSON with no problems. Just make sure you are using version 0.89 or later and everything will work fine.

A: Christian from Realm here.
Realm for Android currently doesn't have any such methods, although the core database actually supports JSON serialisation, so for now you would either have to do it manually or use a 3rd party tool like GSON (caveat, I havn't tested that scenario yet).

A: Simply, all you need to do is:
Gson gson = //... obtain your Gson
YourRealmObject realmObj = realm.where(YourRealmObject.class).findFirst();
if(realmObj != null) {
    realmObj = realm.copyFromRealm(realmObj); //detach from Realm, copy values to fields
    String json = gson.toJson(realmObj);
}

A: Following is how you would do that with GSON library.
Suppose we have the following json reply from the server :
{
   "data": [
      {
         "id": "1",
         "name": "John",
         "surname": "Doe"
      }
   ]
}

For this Json object we create a helper class with corresponding properties
    public class JsonHelperClass {

    String id;
    String name;
    String surname;

    public JsonHelperClass() {
    }

    public JsonHelperClass(String id, String name, String surname) {
        this.id = id;
        this.name = name;
        this.surname = surname;
    }

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSurname() {
        return surname;
    }
    public void setSurname(String surname) {
        this.surname = surname;
    }
}

Now in the following jsonReply is the string containing reply from server
    JSONArray jsonArray = new HttpManager().getJsonArrayFromReply(jsonReply);

    if(jsonArray == null || jsonArray.length <0){
        return;
    }

    for (int i = 0; i < jsonArray.length(); i++) {

        JSONObject json = null;
        try {
        json = (JSONObject) array.get(i);
        } catch (JSONException e) {
        return null;
        }

        Gson gson = new Gson();

        JsonHelperClass helperClass = gson.fromJson(json.toString(), JsonHelperClass.class);

        createRealmObject(helperClass);

}

    public void createRealmObject(JsonHelperClass helperClass){

        Realm realm = Realm.getInstance(context);

        realm.beginTransaction();

        RealmDataObject obj = realm.createObject(RealmDataObject.class);

        obj.setId(helperClass.getId());
        obj.setName(helperClass.getName());
        obj.setSurname(helperClass.getSurname());

        realm.commitTransaction();

}

     public JSONArray getJsonArrayFromReply(String reply){

        JSONArray array = null;

        try {
            JSONObject jsonResp = new JSONObject(reply);
            array = jsonResp.getJSONArray("data");

        } catch (JSONException e) {
            return null;
        }

        return array;
    }

And the Realm Data Object
    public class RealmDataObject extends RealmObject {

    private String id;
    private String name;
    private String surname;

    public RealmDataObject() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

}

A: Try this
  private JSONArray convertRealmintoJSONArray(Activity context){
    try {
        RealmResults<ModelMyCart> results = RealmControllerMyCart.with(context).getBooks();
        JSONArray jsonArray = new JSONArray();
        for (ModelMyCart myCart : results
                ) {
            JSONObject object = new JSONObject();
            object.put(Constants.PRODUCT_ID, myCart.getId());
            object.put(Constants.PRODUCT_TITLE, myCart.getProduct_title());
            object.put(Constants.PRODUCT_SIZE, myCart.getProduct_size());
            object.put(Constants.PRODUCT_SELLINGFEE, myCart.getProduct_sellingfee());
            object.put(Constants.PRODUCT_SELLINGFEE, myCart.getShipping_price());
            object.put(Constants.PRODUCT_IMAGE, myCart.getProduct_image());
            object.put(Constants.PRODUCT_BRAND, myCart.getProduct_brand());
            object.put(Constants.PRODUCT_CATEGORY_ID, myCart.getProduct_category_id());
            object.put(Constants.PRODUCT_CATEGORY_NAME, myCart.getProduct_category_name());
            object.put(Constants.PRODUCT_COLOR, myCart.getProduct_color());
            object.put(Constants.PRODUCT_COLORTYPE, myCart.getProduct_colortype());
            object.put(Constants.PRODUCT_CONDITION, myCart.getProduct_condition());
            object.put(Constants.PRODUCT_CREATED_DATE, myCart.getProduct_created_date());
            object.put(Constants.PRODUCT_MYSALEPRICE, myCart.getProduct_mysaleprice());
            object.put(Constants.PRODUCT_ORIGINALPRICE, myCart.getProduct_originalprice());
            object.put(Constants.PRODUCT_POTENTIALEARNINGS, myCart.getProduct_potentialearnings());
            object.put(Constants.PRODUCT_SHIPPINGCHARGES, myCart.getProduct_shippingcharges());
            object.put(Constants.USER_ID, myCart.getUser_id());
            object.put(Constants.USER_UNAME, myCart.getUser_uname());
            jsonArray.put(object);
        }
        Log.e("Converted",""+jsonArray);
        return jsonArray;
    }catch (Exception e){

    }
    return null;
}

A: For my case new Gson().toJson(realm.copy(realmObj)); causes UI freezing (sometimes out of memory exception). So I updated my Gson instance like that
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

String jsonString = gson.toJson(realm.copy(realmObj));


text: Q: Draw a line with gradually increasing width How can I draw a line on canvas which starts with a width of for example 2dp and ends with 10dp? I can't find a function for this. Would drawing a 10dp line and then clipping it work ?


text:
Q: NestJs - ParseUUIDPipe - Validation failed (uuid vundefined is expected) I have a basic controller setup:
@Controller('')
export class AController {
 @Get(':id')
  async getThing(@Param('id', ParseUUIDPipe) id: string): Promise<RegisterRead[] | IntervalRead[]> {
      return id
  }
}

And I get the following error:
{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "Validation failed (uuid vundefined is expected)"
}

Also see: https://github.com/nestjs/nest/issues/2960

A: This issue was caused because I did not have a version specified. It shows version as an optional field, but it appears to be required:
new ParseUUIDPipe({version: '4'})


text:
Q: On bounding the eigenvalue of a sum of a symmetric matrix and a bounded matrix. Let $A$ be a $n \times n$ symmetric matrix with eigenvalues bounded between $\ell \in \mathbb{R}$ and $L \in \mathbb{R}$, that is $ \ell <\lambda_i < L$  for $i \in \{ 1, \dots , n \}$ where $ \lambda_i$ represent the eigenvalues of $A$ and $\ell < L$.
Let  $B$ be a $n \times n$ generic matrix such that $\| B \| < M \in \mathbb{R}$  (alternatively let $B$ have each element $b_{ij} < M$).
then I would like to say that  the eigenvalues of $B - A $ are bounded between $\ell - M$ and $L + M$, is this true?
EDIT: As pointed out in a comment as stated $B - A $ could have complex eigenvalues, so to keep the question relevant assume $B$ also symmetric.

A: I would say they are bounded between $-L-M$ and $M-\ell$ in the case of symmetric $B$. It is well known that for symmetric $A$ and $B$
$$ \lambda_\max(A+B) \leq \lambda_\max(A) + \lambda_\max(B) $$
holds. This means
$$\begin{align}
\lambda_\max((-A)+(-B)) &\leq \lambda_\max(-A) + \lambda_\max(-B) \\
-\lambda_\min(A+B) &\leq -\lambda_\min(A) - \lambda_\min(B) \\
\lambda_\min(A+B) &\geq \lambda_\min(A) + \lambda_\min(B)
\end{align}$$
Hence,
$$
-L-M \leq \lambda_\min(-A) + \lambda_\min(B) \leq \lambda_i(B-A) \leq \lambda_\max(-A) + \lambda_\max(B) \leq M-\ell
$$


text:
Q: SQL Logic - Record field Changed but no Changes since I have a situation where I need to locate all member records that changed from a status of active to a status of freeze in a period of time. The issue is, a member can change statuses multiple times. For example, a member can change their status from active to freeze on June 1. Then back to active on September 1 and then back to freeze for December 1. I am trying to run a query to identify all of the members who froze from June 1 and are still frozen but that have not changes their status in between.
The code I have identifies all of the people, but does not eliminate people who changes multiple times.
The code I have so far is:
SELECT
    MEMBERUDFS.memid, MEMBERUDFS.udfid, MEMBERUDFS.udfvalue,
    MEMBERUDFSETUPS.udflabel,
    MEMBERS.lname, MEMBERS.fname, MEMBERTYPES.description,
    SITES.sitename, MEMBERS.status,
    MEMBERCHANGES.datechange, MEMBERCHANGES.newvalue,
    MEMBERCHANGES.columnname
FROM
    MEMBERUDFS
INNER JOIN
    MEMBERUDFSETUPS ON MEMBERUDFS.udfid = MEMBERUDFSETUPS.udfid
INNER JOIN
    MEMBERS ON MEMBERUDFS.memid = MEMBERS.memid
INNER JOIN
    MEMBERTYPES ON MEMBERS.mtypeid = MEMBERTYPES.mtypeid
INNER JOIN
    SITES ON MEMBERS.siteid = SITES.siteid
INNER JOIN
    MEMBERCHANGES ON MEMBERS.memid = MEMBERCHANGES.memid
WHERE
    (MEMBERUDFSETUPS.udflabel = 'Freeze Reason')
    AND (MEMBERUDFS.udfvalue = 'Medical')
    AND (MEMBERS.status = 'F')
    AND (MEMBERS.siteid = '777')
    AND (MEMBERCHANGES.columnname = 'status')
    AND (MEMBERCHANGES.newvalue = 'F')
    AND (MEMBERCHANGES.datechange BETWEEN '2015-07-01' AND '2015-12-31')

A: AND NOT EXISTS (
SELECT *
FROM
MEMBERCHANGES c2
WHERE
c2.memid = MEMBERCHANGES.memid AND
c2.datechange > MEMBERCHANGES.datechange
);


text:
Q: Magento2 - Override Magento/Checkout/view/frontend/web/js/view/shipping.js How can we override  Magento/Checkout/view/frontend/web/js/view/shipping.js file?
I need to add some custom code to selectShippingMethod function so i can hide/show a block if a specific shipping method is selected.
Is there a better way to do this?
Thank you!

A: Just in case the requirejs-config.js file should look like this:
var config = {
     config:
       {
         mixins:
           {'Magento_Checkout/js/view/shipping':
               {'Namespace_Module/js/view/shipping': true }
           }
       }
   };

This worked for me

A: You can override core module js by using custom theme.
You have to copy js file from
Magento/Checkout/view/frontend/web/js/view/shipping.js

and put it given path
/app/design/frontend/Theme/Packadge/Magento_Checkout/web/js/view/shipping-information.js

modify by your changes in the file.
Run below command for deploy static content
php bin/magento setup:static-content:deploy

Now check your changes and let me know if you have any query.

A: Just found a way to override that function using 'mixins'.

On requirejs-config.js file I had to add:

  config: {
            mixins: {
                'Magento_Checkout/js/view/shipping': {
                    'Mynamespace_Mymodule/js/view/shipping': true
                }
            }
        }

Create a file
  Mynamespace/Mymodule/view/frontend/web/js/view/shipping.js

define(
    [
        'jquery',
        'underscore',
        'Magento_Ui/js/form/form',
        'ko',
        'Magento_Customer/js/model/customer',
        'Magento_Customer/js/model/address-list',
        'Magento_Checkout/js/model/address-converter',
        'Magento_Checkout/js/model/quote',
        'Magento_Checkout/js/action/create-shipping-address',
        'Magento_Checkout/js/action/select-shipping-address',
        'Magento_Checkout/js/model/shipping-rates-validator',
        'Magento_Checkout/js/model/shipping-address/form-popup-state',
        'Magento_Checkout/js/model/shipping-service',
        'Magento_Checkout/js/action/select-shipping-method',
        'Magento_Checkout/js/model/shipping-rate-registry',
        'Magento_Checkout/js/action/set-shipping-information',
        'Magento_Checkout/js/model/step-navigator',
        'Magento_Ui/js/modal/modal',
        'Magento_Checkout/js/model/checkout-data-resolver',
        'Magento_Checkout/js/checkout-data',
        'uiRegistry',
        'mage/translate',
        'Magento_Checkout/js/model/shipping-rate-service'
    ],function (
        $,
        _,
        Component,
        ko,
        customer,
        addressList,
        addressConverter,
        quote,
        createShippingAddress,
        selectShippingAddress,
        shippingRatesValidator,
        formPopUpState,
        shippingService,
        selectShippingMethodAction,
        rateRegistry,
        setShippingInformationAction,
        stepNavigator,
        modal,
        checkoutDataResolver,
        checkoutData,
        registry,
        $t) {
    'use strict';

    var mixin = {

        selectShippingMethod: function (shippingMethod) {
            console.log("method overriden");
            selectShippingMethodAction(shippingMethod);
            checkoutData.setSelectedShippingRate(shippingMethod.carrier_code + '_' + shippingMethod.method_code);

            return true;
        }
    };

    return function (target) { // target == Result that Magento_Ui/.../default returns.
    return target.extend(mixin); // new result that all other modules receive
};
});

Helpful info:
https://github.com/magento/magento2/issues/1864
Magento2 - Override Magento/Checkout/view/frontend/web/js/view/shipping.js


text:
Q: How do I do a where clause in sql and return a count back? I am using mssql and I want to make a query that returns a count back with a where clause.
Like say I have a product Table
ProductId
ProductName
Active

So how would I make it
I have like
Select Count(*)
From Product

now I don't know how to filter it so it only could if Active = true;
So if there are 3 active products then it would return a count of 3 even if there is a hundred rows in the db and the other 97 are only not active.
so the where clause would be probably like
where active = true

I am not sure how to put them together though.

A: You are there..just use:
Select Count(*)
From Product
where active = 'true'

Assuming your active field is of varchar or something similar.


text:
Q: iOS printing a PDF via printingItem appears to add a blank header; can it be removed? I am using iOS 4.3 and Apple's suggested method for printing a PDF, which is to set the shared UIPrintInteractionController's printingItem property to an NSData object containing PDF data. It's very easy, which is great, but I've found that when printing a PDF via this method, the content starts 4mm lower on the page than if I print via Preview.app on my Mac. As I am printing to pre-cut labels, precise positioning is important.
It appears that somewhere in the process, a (blank) header is being added to the page, which is causing the content to shift down the page. The resulting horizontal margins are the same on both iOS and Mac OS X so I suspect it really is a header, and not an all-around margin.
I have checked the following:

*

*Is the printer adding the header? No, because the same results can be seen when printing to the Printer Simulator.

*Is the iPad using a different paper size to the Mac? I have used the delegate method to ensure that the UIPrintPaper is the same for both.

*Can I edit headerHeight for the UIPrintPageRenderer? No, because a renderer is not created when setting a printing item directly.

My workaround is to make the PDF generator (the server) create the PDF content 4mm higher up than it ought to be, but this breaks printing from Mac OS.
Out of ideas now! Thanks for any assistance.

A: You should check Apple's sample code PrintWebView. I believe the problem your having is because of the hardware margins. See SIMPLE_LAYOUT constant in PrintWebView sample to learn more. Hope this helps.


text:
Q: validate and capture selected button-group checkbox i am using bootstrap button-group checkbox with toggle. To easily identify selected option, using the toggle function (courtesy - one of the post here). Working example here.

Boxes

AA

BB

CC

stumped with:
1) how to validate that user has to select at least 1 button and
2) how to capture value(s) of selected buttons to be sent to PHP (form).
very novice with web development. Need help. Thanks.

A: there is many ways to do this if you want to submit a form with PHP than its very simple you can add a class and use a hidden fields on the click you can add a class and put a value on hidden field and after the submit you can easily get all the value form hidden fields. you can easily check value of hidden fields, so with this you can validate as well that user select any button or not..

A: Suppose you have three buttons as shown below:
<input type="button" class="button" value="Button1">
<input type="button" class="button" value="Button2">
<input type="button" class="button" value="Button3">

You can make a hidden field there with an array as given below:
<input type="hidden" class="newField" name="buttonValue[]">

Now, use it in Jquery:
$(document).ready(function(){
    $('.button').click(function(){
        var values = $(this).val();
        $('.hidden').val(values);
    });
});

and now when you submit a form then you can easily get value from that field and make a validation accordingly.


text:
Q: high frequency insert in cassandra with java loses some data I have 5,000,000 insert query in file. I want read them from file and write to cassandra with java driver and executeAsync method, in loop statement like following code:
public static void main(String[] args) {
        FileReader fr = null;
        try {
            fr = new FileReader("the-file-name.txt");
            BufferedReader br = new BufferedReader(fr);
            String sCurrentLine;
            long time1 = System.currentTimeMillis();
            while ((sCurrentLine = br.readLine()) != null) {
                session.executeAsync(sCurrentLine);
            }

            System.out.println(System.currentTimeMillis() - time1);
            fr.close();
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

my table definition is:
CREATE TABLE test.climate (
    city text,
    date text,
    time text,
    temprature int,
    PRIMARY KEY ((city, date), time)
) WITH CLUSTERING ORDER BY (time ASC)
    AND bloom_filter_fp_chance = 0.01
    AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'}
    AND comment = ''
    AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32', 'min_threshold': '4'}
    AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'}
    AND crc_check_chance = 1.0
    AND dclocal_read_repair_chance = 0.1
    AND default_time_to_live = 0
    AND gc_grace_seconds = 864000
    AND max_index_interval = 2048
    AND memtable_flush_period_in_ms = 0
    AND min_index_interval = 128
    AND read_repair_chance = 0.0
    AND speculative_retry = '99PERCENTILE';

But after running program the count of row in table is 2,569,725
cqlsh:test> select count(*) from climate ;

 count
---------
 2569725

I tested more than 10 times and each time the result of select count(*) was between 2,400,00 and 2,600,000

A: You are issuing async inserts faster than they execute so they eventually exceed the queue size and fail. You can increase your queue size which would work, but then your just applying back pressure to memory instead of your producer and still possibly hitting a wall. Try limiting the in flight queries like:
public static void main2(String[] args) {
    FileReader fr = null;
    int permits = 256;
    Semaphore l = new Semaphore(permits);
    try {
        fr = new FileReader("the-file-name.txt");
        BufferedReader br = new BufferedReader(fr);
        String sCurrentLine;
        long time1 = System.currentTimeMillis();
        while ((sCurrentLine = br.readLine()) != null) {
            l.acquire();
            session.executeAsync(sCurrentLine)
                .addListener(()->l.release(), MoreExecutors.directExecutor());
        }
        l.acquire(permits);

        System.out.println(System.currentTimeMillis() - time1);
        fr.close();
        br.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

It will likely run just as fast, just need to find the right size of the semaphore. Also note the blocking until all the permits have been returned (acquiring max at end), otherwise you can shutdown jvm before the requests were all sent that are possibly in queue.
disclaimer: i did not test the above code


text: Q: Unix - Terminal and Shell differentiation This probably sounds like a stupid question but I'm having a lot of trouble clearly differentiating between a Shell (such as Bourne) and the Terminal application like on an installation of Ubuntu or Fedora. I realise that both are completely different but I can't seem to find a clear answer written in text. Could anyone clearly distinguish between both?


text:
Q: How can I convert AI to HTML & CSS to use in ASP.Net Application In my firm, one of my colleague who is a graphic designer had designed some pages for our new Application (in Adobe illustrator). These are in AI format. We are going to develop the Application in ASP.Net as Web Application (Forms). We want to have the same design as in AI. How can it be achieved? We thought of converting the AI to html but that will be of no use to us as it will generate html with some divs and image tags but we have buttons, text fields, and other tools as well. What could be the best way to achieve the html files. Do we need to hire a web designer or graphic designer with knowledge of html and css for this purpose or is there any software?

A: You'll have to hire a Front-end Developer to convert it to a web page. I would not recommend any software as the code will certainly be low quality.
If the budget permits, hire a good dev with good knowledge of performance, as it will be worth it.


text:
Q: split large XML file with node.js I've got a big 1.8gb XML file with all of its contents on one line.
The main structure of the file is this:
<xml>
    <mutateieoverzicht>
        <mutatiebericht> ... </mutatiebericht>
        <mutatiebericht> ... </mutatiebericht>
        ...
    </mutatieoverzicht>
</xml>

But then on one line :)
I want to parse the file and do some actions on the mutatiebericht elements (storing in db). Because loading and parsing the whole document at once takes to much memory and is terribly slow, I was thinking of parsing the file line-by-line.
But the original file has only one line.
So my first step would be to traverse the file and create a new file with every mutatiebericht on its own line.
I can load the file in node.js and do things with the content, but am lost regarding the splitting of the string with contents.

A: You could use the xml-stream module, it reads a XML file into a stream and emit events on each elements start and end. It would look something like this (untested):
var stream = fs.createReadStream(pathtoyourfile);
var xml = new XmlStream(stream);
xml.on('endElement: mutatiebericht', function(item) {
  console.log(item); //item contains your element
});


text:
Q: How to query specified minutes from datetime kind of gae datastore? eg: "xx:20:xx" i have a problem using Google App Engine Datastore.
My db class:
class pm25(db.Model):
    pttime=db.DateTimeProperty()

Datastore:
pttime
2011-11-01 12:00:00
2011-11-01 12:20:00
2011-11-02 08:00:00
.....

What i want to do is get the entities which time is 20 past any hour.eg: XXXX-XX-XX XX:20:XX
How do i write this gql?
Thanks in advance
ofive

A: This query isn't possible with the model above, because minutes are not indexed. To accomplish this, you'll need to store minutes explicitly at write time. You can do this easily with DerivedProperty:
class pm25(db.Model):
    pttime = db.DateTimeProperty()
    pttime_minute = DerivedProperty(lambda self: self.pttime.minute)

With this change, you can query pttime_minute like any other integer.


text:
Q: Splitting csv like string using regex I have a regex pattern defined as
var pattern = ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))";

and I am trying to split some CSV like strings to get fields
Some example strings that WORK with this regex are
_input[0] = ""; // expected single blank field
_input[1] = "A,B,C"; // expected three individual fields
_input[2] = "\"A,B\",C"; // expected two fields 'A,B' and C
_input[3] = "\"ABC\"\",\"Text with,\""; // expected two fields, 'ABC"', 'Text with,'
_input[4] = "\"\",ABC\",\"next_field\""; // expected two fields, '",ABC', 'next_field'

However, this is not working
_input[5] = "\"\"\",ABC\",\"next_field\"";

I am expecting three fields
'"', 'ABC"', 'next_field'

But I am getting two fields
'"",ABC', 'next_field'

Can anybody help with this regex?
I think the strange part is that the second column doesn't have quotes at the start and end of the value, just at the end.  So the first column's value is empty, and the second column is ABC"
Thanks,
Rob

A: I think you need to be even more specific about what your logic is in terms of how the double quotes should be treated, as it appears that your requirements conflicts with each other.
My quick version that I think comes closest to what you are trying to achieve is this (please note 1) The missing escaping of double quotes, because I am using an external tool to validate the regex, and 2) I have changed how to retrieve the matched values, see the bottom for an example):
(?<Match>(?:"[^"]*"+|[^,])*)(?:,(?<Match>(?:"[^"]*"+|[^,])*))*

It has the following logic:

*

*If there is a double quote, then include everything in it, until an end double quote is hit.

*When reaching an end double quote, double quotes following immediately after will also be included.

*If the next character is anything but a comma, it is included, and the above is tested again.

*If it is a comma, the current match is concluded and a new one begins after the comma.

The above logic conflicts with what you expect from index 4 and 5 however, because I get:
[4] = '""' and 'ABC","next_field"'
[5] = '"""' and 'ABC","next_field"'

If you could point out why the above logic is wrong for your needs/expectations, I'll edit my answer with a fully working regex.
To retrieve your values, you could do it like this:
string pattern = @"(?<Match>(?:""[^""]*""+|[^,])*)(?:,(?<Match>(?:""[^""]*""+|[^,])*))*";

string[] testCases = new[]{
  @"",
  @"A,B,C",
  @"A,B"",C",
  @"ABC"",""Text with,",
  @""",ABC"",""next_field""",
  @""""",ABC"",""next_field"""
};

foreach(string testCase in testCases){
  var match = System.Text.RegularExpressions.Regex.Match(testCase, pattern);
  string[] matchedValues = match.Groups["Match"].Captures
    .Cast<System.Text.RegularExpressions.Capture>()
    .Select(c => c.Value)
    .ToArray();
}


text:
Q: VBA Object variable or with block I keep getting the

Object variable or with block variable not

set error even though I have defined all variables. I know there are plenty of other questions regarding this being asked here, however non of them seem to help me.
I am simply trying to update a number of graphs. I have used the code before in other workbooks, which is why i cannot find the error.
Sub Update_All_Graphs()
    Call SETWorksheets

    Dim Lastrow As Long
    Dim ShName As String
    Dim FindRow, FindRowNumber As Double

    Set FindRow = ScTotalWs.Range("AF10:AF47").Find(What:="Grand Total", LookIn:=xlValues)
    FindRowNumber = FindRow.Row
    Lastrow = FindRowNumber - 1

    ScTotalWs.ChartObjects("1_EOST").Activate
    ActiveChart.SeriesCollection(1).Select
    ActiveChart.SetSourceData Source:=Range("AJ10:AJ" & Lastrow & ", AK10:AK" & Lastrow & ", AL10:AL" & Lastrow)
End Sub

The error shows up on the FindrowNumber = FindRow.row line.

A: The Range.Find() method is not guaranteed to return anything (logical, if you think about it). The documentation states clearly:

Remarks
This method returns Nothing if no match is found.

Never use the result of such a method call without checking that it is valid.
Set FindRow = ScTotalWs.Range("AF10:AF47").Find(What:="Grand Total", LookIn:=xlValues)

If Not FindRow Is Nothing Then
    Lastrow = FindRow.Row - 1
    ' etc
End If

A: Find() method of Range object has a subtle trap in that it assumes for some parameters, if not explicitly declared, their last value, with last being   their values used during the last use of that method, even if from Excel UI!
so you'd better always explicitly specify all those parameters and assure you're actually searching as you want it to be done:
Set FindRow = ScTotalWs.Range("AF10:AF47").Find(What:="Grand Total", LookIn:=xlValues, lookat:=xlPart, MatchCase:=False)

but you could also avoid the setting and checking against Nothing of the Range object returned by the Range object Find() method by using WorksheetFunction.CountIf() function, as follows:
Sub Update_All_Graphs()
    Dim Lastrow As Long

    With ScTotalWs.Range("AF10:AF47") '<--| reference relevant range of wanted worksheet
        If WorksheetFunction.CountIf(.Cells, "Grand Total") > 0 Then '<--| if there's at least one occurrence of "Grand Total"
            Lastrow = .Find(What:="Grand Total", LookIn:=xlValues, lookat:=xlPart, MatchCase:=False).row - 1 '<--| set your 'LastRow'
            With .Parent '<--| reference the parent worksheet of referenced range, for all subsequent ranges references
                .ChartObjects("1_EOST").Activate
                ActiveChart.SeriesCollection(1).Select
                ActiveChart.SetSourceData source:=.Range("AJ10:AJ" & Lastrow & ", AK10:AK" & Lastrow & ", AL10:AL" & Lastrow)
            End With
        End If
    End With
End Sub

A: Probably, you need to define "ScTotalWs".
Set ScTotalWs = ThisWorkbook.Worksheets("Table1")

Of course,  you need to Change [Table1] according to your file.


text:
Q: preferred pattern for conditional execution of a Talend job I have a Talend job (call it A) that I want to run when an Oracle stored procedure (not executed by Talend) has completed.  I have an Oracle control table that I can check to see if the Oracle SP has finished.
I am imagining having my Talend job A run on a schedule - perhaps every 15 minutes - and the first thing that it would do is determine if A has already executed today.  If it has already run today it would stop execution immediately.  If it has not yet run today, it will check to see if the Oracle SP has completed, and if not, it will stop execution immediately.  This should result in Talend job A only executing once a day, and only after the Oracle SP has completed.
Is there a more elegant way to accomplish this?
Thanks.

A: As you've stated in the comments,  Oracle SP has a CronJob.
You should make a Talend Job (A) which will be executed shortly after the Oracle SP start. This would have an Iterate + tOracleInput-tJavaRow + tRunJob + tJava
Iterate (i<=80 && somevalue==1 --> tOracleInput - row1 - tJava --
         --IF--> row1.field.equals("true") --> tJava i = 101; --> tRunJob(JobB)
         --IF--> !row1.field.equals("true") --> tJava Thread.Sleep(15*60*1000);

This way when you execute the JobB you'll exit from the loop. Also your Talend Job will run once a day, and does the calculation once a day. I know it seems to be a little dirty but it will work.
Having i set to 80 you'll end up with 81 trys thats 20hour 15min for the worst case not counting the query runtime.
Thread.Sleep accepts miliseconds thats why you need to multiply by 1000 to get the seconds and 60 to get the minutes

A: You can also think below options
1) export/build your talend job (A) as shell/batch file and execute it via same unix crontab job which executes your SP. You have to set dependency may be based on exit code of SP job.
OR
2) you can run your SP from talend job either using tOracleSP or even you can run your unix shell if any existing using tSystem and onSubJobOk run your talend job (A).


text:
Q: Text between delimiters starting from the end of the string I'm really new to python and programming in general, and to practice I'm doing projects where I try to tackle problems from my day to day work, so please excuse me if this may be a silly question. I'm trying to combine a group of files located on a remote folder into a single monthly one based on the date, I've already combined files based on date so I think I can do that, but I'm having trouble with the regex to pick the date from the file name string, the string with the filepath is as follows

\\machinename123\main folder\subfolder\2021-01-24.csv

The file name will always have the same format since it's and automated process, only changing the date on the name, I was trying to pick the date from this string using a regex to select the text between the last \ of the string and the . from the format, so I can get a 2021-01-24 as a result but at the level I'm at, regex are like witchcraft and I don't really know what I'm doing, I've been trying for a few hours to no success, so far this is the closest I can get by trial and error (?:[0-9\-]) but this selects all the numbers on the string, including the ones on the machine name, besides the issue of not knowing why it works the way it works (for example I know that the ?: works by testing, but I don't understand the theory behind it so I couldn't replicate it in the future).
How can I make it ignore the other numbers on the string, or more specifically pick only the text between the last \ and the . from the csv, xlsx or whatever the format is?
I'd like the former option better, since it would allow me to learn how to make it do what I need it to do and not get the result by coincidence.
Thanks for any help

A: Use re.search() to find a pattern: <4 digits>-<2 digits>-<2 digits>.
s = r'\\machinename123\main folder\subfolder\2021-01-24.csv'
m = re.search(r'\d{4}-\d{2}-\d{2}', s).group(0)

A: You can use the following regex, that summarizes the structure of your full path:
import re

filename_regex = re.compile(r'^\\\\[(?:\w| )+\\]+((?:\d{4,4})-(?:\d{2,2})-(?:\d{2,2})).csv$')

m = filename_regex.match(r"\\machinename123\main folder\subfolder\2021-01-24.csv")
if m is not None:
    print(f'File found with date: {m.groups()[0]}')
else:
    print('Filename not of interest')

The output will be:
File found with date: 2021-01-24

filename_regex accepts string starting with \\, followed by a repetition of characters (alphanumeric and underscores) and spaces followed by \, but with the final part corresponding to 4 digits, followed by a minus, then 2 digits, a minus again, 2 digits and the string .csv. The regular expression used here to match the date is very simple, but you can use a more complex one if you prefer.
Another simpler approach would be using ntpath library, extracting the name of the file from the full path and applying the regular expression only to the name of the file:
import ntpath
import re

filename_regex = re.compile(r'^((?:\d{4,4})-(?:\d{2,2})-(?:\d{2,2})).csv$')

filename = ntpath.basename(r"\\machinename123\main folder\subfolder\2021-01-24.csv")
m = filename_regex.match(filename)

m here will have the same value as before.


text:
Q: Finding all words ending in "ion" with regex in JavaScript I'm getting 0 matches when using the regex below in JavaScript. I'm trying to find all words that end in "ion"
/^[a-z]+(ion)$/i

Does anyone know what I'm doing wrong? I've also tried this below, but it doesn't work either:
/^[a-z]+ion$/i

Edit: This checks against a form text field that will contain only one word:

*

*Example

*example

*nation

*Nation