text:
Q: BackgroundWorker in WPF not working I have a button that navigates a web page. I was trying to put the navigation in a backgroundworker, but it doesn't navigate. If I put it in the click event of the button it works fine. I put a break point in the bgw_DoWork and it shows that it hits the point of creating a new wb object, however it skips the rest of the statements in the DoWork. I wanted to do this so that I can display a loading image while it is trying to get data from a web page. The webbrowser object is not part of the UI as the user doesn't need to see the scraping. It just downloads the information into an object and then later displays the object (outside of the BackgroundWorker).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Reflection;
using System.ComponentModel;
using mshtml;

namespace WPF1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        WebBrowser wb;
        private readonly BackgroundWorker bgw = new BackgroundWorker();

        public int i = 0;

        public MainWindow()
        {
            InitializeComponent();
            bgw.DoWork += bgw_DoWork;
            bgw.RunWorkerCompleted += bgw_RunWorkerCompleted;

       }

        private void GetSICData_Click(object sender, RoutedEventArgs e)
        {
            //mainTabControl.SelectedIndex = 1;

            //wb.Navigated += wb_Navigated;
            //wb.LoadCompleted += wb_LoadCompleted;
            //wb.Navigate("http://www.google.com");

            bgw.RunWorkerAsync();

        }

        private void bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            wb = new WebBrowser();

            wb.Navigated += wb_Navigated;
            wb.LoadCompleted += wb_LoadCompleted;
            wb.Navigate("http://www.google.com");

        }

        private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("Background Complete");
        }

        void wb_LoadCompleted(object sender, NavigationEventArgs e)
        {

            HTMLDocument doc = (HTMLDocument)wb.Document;
            doc.getElementById("ctl03_TextBox1").innerText = "2334882";

            wb.LoadCompleted -= wb_LoadCompleted;
            wb.LoadCompleted += wb_LoadCompleted_2;

            doc.getElementById("ImageButton1").click();

        }

        void wb_LoadCompleted_2(object sender, NavigationEventArgs e)
        {
            MessageBox.Show("It Worked!");
        }

        void wb_Navigated(object sender, NavigationEventArgs e)
        {

        }

    }
}

A: It sounds like what you really want is the WebClient Class. You can use a number of its methods to download either the whole web page as a file, or as a string. The best part is that you can also do this asynchronously, so it will all happen on a background thread automatically.
When using these asynchronous methods, you need to handle the relevant Download...Completed event to retrieve the results. From the DownloadStringCompletedEventHandler Delegate page on MSDN:
public static void DownloadStringInBackground2 (string address)
{
    WebClient client = new WebClient ();
    Uri uri = new Uri(address);

    // Specify that the DownloadStringCallback2 method gets called
    // when the download completes.
    client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(
DownloadStringCallback2);
    client.DownloadStringAsync (uri);
}

private static void DownloadStringCallback2 (Object sender,
DownloadStringCompletedEventArgs e)
{
    // If the request was not canceled and did not throw
    // an exception, display the resource.
    if (!e.Cancelled && e.Error == null)
    {
        string textString = (string)e.Result;

        Console.WriteLine (textString);
    }
}

Take a look at the WebClient.DownloadStringAsync Method and WebClient.DownloadFileAsync Method pages on the MSDN website for more information.

A: You cannot create a UI control on a background thread and in this case you don't need to because all of the WebBrowser methods you need are executed asynchronously anyway...
WebBrowser.Navigate

Navigate asynchronously to the document at the specified Uri.

BTW, don't forget to use Navigate method after the WebBrowser control is loaded so either use IsLoaded to check or call Navigate from Loaded event...

A: Some of the UI operations requires being invoked on the UI thread. Try
    private void bgw_DoWork(object sender, DoWorkEventArgs e)
    {
        wb.Navigated += wb_Navigated;
        wb.LoadCompleted += wb_LoadCompleted;

        wb.Dispatcher.Invoke(() =>
        {

            wb.Navigate("http://www.google.com");
        });
    }


text:
Q: bxSlider onAfterSlide callback Good morning all :) I've got an issue here, which is pain in my neck for 2 days already. I'm using bxSlider for images to slide on a page and I'm calling my own function in onAfterSlide callback. Everything works fine except one thing. When I quickly switching between slides my function is being called 2-3 times(I have 3 images on page), which is not good as it returns unexpected results. I can not use newest version of bxSlider, because the markup has been changed. I think this happens, because the animation is still not finished when the onAfterSlide callback is called.
This is how I call bxSlider:
$('#slider_bx').bxSlider({
    mode: 'fade',
    speed: 1000,
    pause: 9000,
    auto: true,
    autoControls: false,
    prevText: '',
    nextText: '',
    autoHover: true,
    captions: false,
    pager: true,
    onBeforeSlide: function () {
        if ($('.slide_in').length) {
            $('.slide_in').hide();
        }
    },
    onAfterSlide: function () {
        if ($('.slide_in').length && $('.slide_in').is(':hidden')) {
            doCrazyStuff();
        }
    }
});

And this is my function:
function doCrazyStuff() {
    var $this = $('.slide_in');
    if ($this.length > 0) {
        setTimeout(function () {
            $this.show();
            $this.rotate({
                duration: 2000,
                angle: 90,
                animateTo: -20
            });
        }, 3000);
    }
}

Any help appreciated. Thanks.
EDIT:
I've tried to add .stop(), but didn't helped.
$this.show().stop();
$this.stop().show();
$this.stop().rotate({
    duration: 2000,
    angle: 90,
    animateTo: -20
});

$this.rotate({
    duration: 2000,
    angle: 90,
    animateTo: -20
}).stop(); // throws an error

A: Try using the
$('.slide_in').stop()
in after slide function I hope it works, if possible try to give code in fiddle it will be easy to help.

A: Viewing your code I think the problem is not with your code : but as you have set auto to true so the plugin timer is not stopped and is sliding the images in its regular interval.
so I hope the use of stopAuto() bxSlider function in your custom function will solve the problem. and don't forget to start the auto show after you have finished doing your stuff.
thanks

A: You can cancel a timeout or make a check to see if it's running.
If you want only the last timeout to run:
var crazyTimeout;
function doCrazyStuff() {
    var $this = $('.slide_in');
    if ($this.length > 0) {
        if (crazyTimeout != undefined) {
            clearTimeout(crazyTimeout); // Cancel previous timeout
        }
        crazyTimeout = setTimeout(function () {
            crazyTimeout = undefined;
            $this.show();
            $this.rotate({
                duration: 2000,
                angle: 90,
                animateTo: -20
            });
        }, 3000);
    }
}

If you want only the first timeout to run:
var crazyTimeout;
function doCrazyStuff() {
    var $this = $('.slide_in');
    if ($this.length > 0) {
        if (crazyTimeout != undefined) {
            return; // A timeout is still running: don't create new one
        }
        crazyTimeout = setTimeout(function () {
            crazyTimeout = undefined;
            $this.show();
            $this.rotate({
                duration: 2000,
                angle: 90,
                animateTo: -20
            });
        }, 3000);
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: MongoDB compare within call string to int I have a MongDB collection in which my documents have a date stored as a string like this:
"data": {
    "type": "MatchData",
    "matchId": "5b34f2d527f0d904f8ee4bbf",
    "groupId": "5b2a032ffc37de04f30dc412",
    "leaderboardId": "5b2a0387fc37de04f30e149d",
    "matchTitle": "",
    "date": "20180628144304"
}

As you can see, the date is saved as a string, but I want to be able to find all records with a date older than the current:
var currDate = 20180928000000
dbCollection('matches').find( { "groupId": groupId, "$lt": {"date": currDate} } );

The current example is not working since the currDate is a integer and the date from document is a string!? How can I use parseInt inside the query or is there another way?
Hoping for help and thanks in advance :-)

A: You can either convert your input parameter currDate to string
var currDate = "20180928000000"
dbCollection('matches').find({ "groupId": groupId, "$lt": { "date": currDate } })

or If you are using 4.0
then you can use $toInt aggregation operator
dbCollection('matches').find({
  "groupId": groupId,
  "$expr": { "$lt": [{ "$toInt": "$date" }, currDate]}
})


text:
Q: What was the tallest structure built in Middle-earth? I started thinking to myself one day (scary, I know) as to which was taller of the two towers, Orthanc or Barad-dûr. And then I wondered if Minas Tirith might be even taller, which then led me to this question. What's the tallest structure built in Middle Earth (including Númenór)? I'm referring to man/Númenórean/elf/dwarf/Maia/etc-built structures.
This includes any dwarven-built structures built or hewn underground, such as the halls of Erebor. Structures built on top of mountains, such as Durin's Tower atop Zirakzigil, don't get to count the height of the mountain, just the constructed part itself.
Bonus points if any height comparisons can be made to real world structures like the Eiffel Tower or Empire State Building to get a better grasp on scale, if possible.
I prefer answers found in Tolkien's writings rather than the movies because Peter Jackson likes to 'Peter Jackson' things.
Edit: Given isanae's wealth of information in his answer, are there any graphic designers out there willing to attempt a nice looking comparison infographic to further enhance SE:SFF's reputation for being one of the best sources out there?

A: The height of Barad-dûr is not mentioned in the books, to my best knowledge, but is described several times.

"...that vast fortress, armoury, prison, furnace of great power..."
"...rising black, blacker and darker than the vast shades amid which it stood, the cruel pinnacles and iron crown of the topmost tower of Barad-dûr."
"...wall upon wall, battlement upon battlement, black, immeasurably strong, mountain of iron, gate of steel, tower of adamant... Barad-dûr, Fortress of Sauron."

As Sam Gamgee saw it "The Return of the King".

"... towers and battlements, tall as hills, founded upon a mighty mountain-throne above immeasurable pits; great courts and dungeons, eyeless prisons sheer as cliffs, and gaping gates of steel and adamant..."

In the movie, "The Return of the King", the tower is 3300 feet high. It would dwarf all buildings in real life.

According to Wikipedia, Orthanc was just over 500 feet high.

A: It depends what you mean by "structure"
In terms of freestanding structures, which I think you are most interested in, it would probably be Barad-dûr with a height of at least (and even perhaps much more than) 1000 feet (300 m), which would be about the same height as the Eiffel Tower. In second place would be a tie between Orthanc and the Temple of Armenelos on Númenor at about 500 feet (150 m). There are other tall towers, but their height is unknown.
For constructions that are above ground in general, Minas Tirith is the tallest at 1000 feet (300 m), but it was built from the side of a mountain. Underground structures are difficult to estimate, but it would probably be either Utumno or Angband, followed by Moria and its Endless Stair going to Durin's Tower.
Finally, if we go for "high mountainous things that were not really meant to be mountains", then the pillars made for the Lamps would probably take first place, followed by the whole of Angband and Thangorodrim together.
As a comparison, the Empire State Building stands at 1,454 feet (443 m), the Tokyo Skytree at 2,080 feet (634 m) and the Burj Khalifa at 2,722 feet (830 m).
I've looked for the tallest structure made by every race, although it's difficult to come up with even an approximate height for most of them.
The Valar
The pillars
Depending on your definition of "structure" and "mountain", the tallest thing the Valar built was the pillars on which the Lamps were set shortly after the creation of Arda:

Then Varda filled the lamps and Manwë hallowed them, and the Valar set them upon high pillars, more lofty far than are any mountains of the later days. One lamp they raised near to the north of Middle-earth, and it was named Illuin; and the other was raised in the south, and it was named Ormal; and the light of the Lamps of the Valar flowed out over the Earth, so that all was lit as it were in a changeless day.
The Silmarillion, Of the Beginning of Days, p. 27

The height of the pillars is unknown, but it must be higher than "any mountains of the later days", which would include Thangorodrim. Karen Wynn Fonstad, in her Atlas of Middle-earth, estimates a height of 35,000 feet (10 km) for Thangorodrim, but it is rather doubtful (see below). If it is correct, then the pillars would have to be "far more lofty" than that. If we make a wild guess and double the height to 70,000 feet, or about 13 miles (21 km), the top of the pillars would be in the stratosphere.
It is not entirely clear what the pillars are made of. Fonstad assumes they are tall mountains, but I found no texts to support this. Indeed, in very early versions of the story, Melkor deceived the Valar and made them out of ice:

As is told they desired to make lamps, and Melko offered to devise a new substance of great strength and beauty to be their pillars. And he set up these great pillars north and south of the Earth's middle yet nearer to it than the chasm; and the Gods placed lamps upon them and the Earth had light for a while.
But the pillars were made with deceit, being wrought of ice; and they melted, and the lamps fell in ruin, and their light was spilled. But the melting of the ice made two small inland seas, north and south of the middle of the Earth, and there was a northern land and a middle land and a southern
  land.
The History of Middle-earth Volume 5: The Shaping of Middle-earth, The Ambarkanta, p. 238

(Interestingly, the appearance of inland seas after the destruction of the pillars was never changed, although the story of the ice pillars was abandoned.)
Angband and Utumno
If the pillars are too mountain-like to qualify, then it would probably be either Utumno or Angband, Melkor's fortresses, but there is no indication of their depth:

Now Melkor began the delving and building of a vast fortress, deep under Earth, beneath dark mountains where the beams of Illuin were cold and dim. That stronghold was named Utumno. [...]
The Silmarillion, Of the Beginning of Days, p. 29
Deep in forgotten places that cry was heard. Far beneath the rained halls of Angband, in vaults to which the Valar in the haste of their assault had not descended, Balrogs lurked still, awaiting ever the return of their Lord [...]
ibid., Of the Flight of the Noldor, p. 85
But at the last the gates of Utumno were broken and the halls unroofed, and Melkor took refuge in the uttermost pit. [...] Nonetheless the Valar did not discover all the mighty vaults and caverns hidden with deceit far under the fortresses of Angband and Utumno.
ibid., Of the Coming of the Elves, pp. 48-49
[...] and all the pits of Morgoth were broken and unroofed, and the might of the Valar descended into the deeps of the earth. There Morgoth stood at last at bay, and yet unvaliant. He fled into the deepest of his mines [...]
ibid., Of the Voyage of Eärendil and the War of Wrath, p. 303

Thangorodrim
On top of Angband was Thangorodrim, three peaks that were created by Melkor:

There he delved anew his vast vaults and dungeons, and above their gates he reared the threefold peaks of Thangorodrim, and a great reek of dark smoke was ever wreathed about them.
ibid., Of the Flight of the Noldor, p. 86

The Atlas of Middle-earth, pp. 14-15
Tolkien never specified the height of Thangorodrim, but he did make a drawing that showed both the island of Tol Sirion and the mountains in the distance:

Pictures by J.R.R. Tolkien, #36
Fonstad calculated that for this drawing to be possible, the mountains had to be about 35,000 feet (10 km) high. As a comparison, Mount Everest, the highest mountain on Earth, stands at about 30,000 feet (9 km). I somewhat question the validity of this estimate based on such an imprecise drawing.
In any case, if we take the whole thing as one massive structure, it would be the tallest ever built after the pillars.
The Maiar
That one is easy: Sauron's Barad-dûr. It was built in the Second Age after Sauron's return to Mordor. It is also probably the tallest freestanding structure on Middle-earth ever built.
Its height was never specified in any texts. When Frodo puts on the Ring to flee from Boromir, he ends up on Amon Hen and has visions of Barad-dûr:

But against Minas Tirith was set another fortress, greater and more strong. Thither, eastward, unwilling his eye was drawn. [...] Then at last his gaze was held: wall upon wall, battlement upon battlement, black, immeasurably strong, mountain of iron, gate of steel, tower of adamant, he saw it: Barad-dûr, Fortress of Sauron.
The Lord of the Rings: The Fellowship of the Ring, The Breaking of the Fellowship, p. 527

Whether Frodo is reliable at this point is unclear. If he is, then Barard-dûr would be higher than Minas Tirith, which stands at 1000 feet (300 m).
The Elves
This is really unclear. I think it would probably be the Tower of Avallónë, where the master palantír was kept. It was the first thing sailors would see when they drew near to Aman.

[...] and there is in that land a haven that is named Avallónë, for it is of all cities the nearest to Valinor, and the tower of Avallónë is the first sight that the mariner beholds when at last he draws nigh to the Undying Lands over the leagues of the Sea.
The Silmarillion, Akallabêth, p. 310
[...] it is believed that thus [Elendil] would at whiles see far away even the Tower of Avallónë upon Eressëa, where the Masterstone abode, and yet abides.
ibid., Of the Rings of Power, p. 350

Other notable towers would be:

*

*Mindon Eldaliéva, the tower of Ingwë built in Tirion (where the Noldor lived in Valinor);

*Elostirion, one of the three White Towers built by Gil-galad for Elendil near the Grey Havens; and

*The Tower of Turgon in Gondolin. Fonstad says that "its turret [is] standing eight hundred feet above the Vale", but it seems to be based on a yet another very imprecise sketch, much like Thangorodrim above.

The Orcs
If we assume that the Orcs built the stairs to the Tower of Cirith Ungol, then that would be it, although they did not build the Tower itself. If not, then they probably contributed somehow to Barad-dûr, so they get to share the credit. Apart from that, I don't know of any other major structures built by them.
The Dwarves
It was most certainly the Endless Stair that went from the bottom of Moria to the peak of the Silvertine (Zirakzigil), upon which was Durin's Tower. Dwarves also built other strongholds and deep mines before Moria, such as Nogrod, Belegost and Erebor, but it is unclear how they compare to it.

The Atlas of Middle-earth, p. 129
Fonstad says the guardroom was 3900 feet (1190 m) deep, but I don't know where she got this information. She has no references for this particular statement and I couldn't find anything else on it.

The travellers camped beside the archway in a guardroom with a well. The guardroom has been shown about 3900 feet deep, but there were hammer sounds heard through the well shaft from a lower level. The mines could have been as deep as 12,500 feet and still have been within limits reached in our Primary World.
The Atlas of Middle-earth, p. 128

Men
Minas Tirith would probably be the tallest at over 1000 feet (300 m) high, but it was made by excavating the side of a mountain, so it is not a freestanding structure. The height from the ground to the highest level is 700 feet (210 m) and on the highest level is a 300 feet (90 m) tall tower, the Tower of Echtelion, also known as the White Tower.

Up it rose, even to the level of the topmost circle, and there was crowned by a battlement; so that those in the Citadel might, like mariners in a mountainous ship, look from its peak sheer down upon the Gate seven hundred feet below. [...] Thus men reached at last the High Court, and the Place
  of the Fountain before the feet of the White Tower: tall and shapely, fifty fathoms from its base to the pinnacle, where the banner of the Stewards floated a thousand feet above the plain.
The Lord of the Rings: The Return of the King, Minas Tirith, p. 11

The Atlas of Middle-earth, p. 139
Second place
I think it's a tie between the Temple of Armenelos and Orthanc. Both are 500 feet (150 m), plus an additional component of unknown height. The Temple was built on Sauron's orders in Armenelos, the capital of Númenor:

But Sauron caused to be built upon the hill in the midst of the city of the Númenóreans, Armenelos the Golden, a mighty temple; and it was in the form of a circle at the base, and there the walls were fifty feet in thickness, and the width of the base was five hundred feet across the centre, and the walls rose from the ground five hundred feet, and they were crowned with a mighty dome.
The Silmarillion, Akallabêth, p. 327

So the walls are 500 feet (150 m) tall but there is also a dome on the walls, making the structure taller than this. If we assume the dome is a hemisphere, then it must be 250 feet (75 m) tall, but there is no information on its shape. As for Orthanc:

A peak and isle of rock it was, black and gleaming hard: four mighty piers of many-sided stone were welded into one, but near the summit they opened into gaping horns, their pinnacles sharp as the points of spears, keen-edged as knives. Between them was a narrow space, and there upon a floor of polished stone, written with strange signs, a man might stand five hundred feet above the plain.
The Lord of the Rings: The Two Towers, The Road to Isengard, p. 192

The height of Orthanc would then be 500 feet (150 m), plus the height of the "gaping horns". Whether the dome of the Temple or the horns are taller is unclear.


text:
Q: Como eu faço para habilitar o PostGresql no Cpanel? Boa tarde. Gostaria de saber como faço para ativar o Postgres no menu do Cpanel da parte de banco de dados, preciso criar um banco em Pg. Já fiz a instalação no WHM e habilitei a configuração, entretanto ainda não está aparecendo a opção para que eu crie o banco via Cpanel. Alguém tem um tutorial para isso? eu já segui esses e nenhum deles deu jeito.
http://wiki.integrator.com.br/index.php?title=Instalando_e_configurando_o_PostgreSQL_9_no_cPanel/WHM
https://documentation.cpanel.net/display/CKB/Install+or+Update+PostgreSQL+on+Your+cPanel+Server

A: Boa Tarde,
Instalei sem problemas utilizando os passos abaixo.

*

*Execute o comando / usr / local / cpanel / scripts / installpostgres para instalar ou atualizar o PostgreSQL.

*Acesse a interface ConfigurePostgreSQL do WHM (WHM >> Home >> Serviços SQL >> Configure o PostgreSQL).

*Clique em Instalar Configuração se o PostgreSQL não existir no seu servidor.

Quais dúvidas estou a disposição.
Att,
Tiago Ceridorio


text:
Q: No output/Sound from my computer running Ubuntu 16.04 When external sound card is unplugged:

As my headphone jack stopped working I started using an External sound card so that I can use my earphones. Initially it had an option to play sound using built-in speakers but now it doesn't show the option. The external sound card still works.
When the External sound card is plugged in:


text:
Q: Advanced Pseudo Random Bit Generation Well I want to generate pseudo-random bits for a mathematical problem. The Bit size is user fed. But unlike normal problems there's a small twist here. The mathematical problem also gives valid results if the bits begin with 0's and literally match the size input by user.
Example: For User Input 4, all the following are valid outputs:
-> 0000
-> 0001
-> 1000
-> 0100

etc.
I am using this function to generate the numbers now:
int randomChoice = choice.Next(1 << (input - 1), (1 << input) - 1);
bitSize = randomChoice;

Is there any other way of random bit generation that may begin with 0's as long as it follows the literal bit length in C# without going into complex array manipulation?

A: The following line:
int randomChoice = choice.Next(1 << (input - 1), (1 << input) - 1)

for input = 4 is equivalent to:
int randomChoice = choice.Next(8, 15);

Which will per MSDN documentation pick one of the following values: 8, 9, 10, 11, 12, 13, 14 - randomly. Notice that the value 15 will not be picked as the documentation states clearly that the lower bound (8) is )inclusive_ while the upper bound (15) is exclusive.
Those values in binary are:
8 : 1000
9 : 1001
10: 1010
11: 1011
12: 1100
13: 1101
14: 1110

I believe what @Jon Skeet was saying is that you are generating random numbers that always have the MSB (left-most bit) set. And are thus missing out on all values that fit in 4 bits that would start with 0 (have the MSB unset).
I would also point out that you should probably include value 15 here, since that also fits in the 4 bits. So, with the two modifications, the line of code should read:
int randomChoice = choice.Next(0, (1 << input));

That would generate all values from 0 to 15, inclusive:
0 : 0000
1 : 0001
2 : 0010
3 : 0011
    ...
13: 1101
14: 1110
15: 1111

Is that what you're looking for?

A: In your previous question, you accepted an answer that improved your original code.  Problem was, your code was wrong to begin with.  You want only a single random bit.  You'll need to do it like this instead:
   int maxBit = AskUserForMaxBit();
   int randomBit = choice.Next(1, maxBit+1);
   int randomValue = 1 << (randomBit - 1);
   return Convert.ToString(randomValue, 2);


text:
Q: a slow templated factory The code below shows a templated factory. It takes a functor-class and returns the operator()'s return-value.
The functor-class below returns a simple struct which in this case is huge: ints.resize(10000000,0).
When I invoke this factory I get a huge slowdown. Especially when invoked very often like for (size_t i=0,j=10000; i!=j; ++i). I suspect a return-by-value (even if it returns only by reference).
Can anybody enlighten me as how to fix this slowdown?
#include <iostream>
#include <chrono>
#include <vector>

template<typename T, typename... Args>
auto generate_one(Args... args) -> decltype(T{args...}()) {
  T t{args...}; // <<---- this is so slow!!!
  return t();
}

// template<typename T, typename... Args>
// auto generate_one(Args... args) -> decltype(T{args...}()) {
//   auto start = std::chrono::system_clock::now();
//   T t{args...};
//   auto end = std::chrono::system_clock::now();
//   auto elapsed = end - start;
//   std::cout << elapsed.count() << '\n';
//   return t();
// }

struct product_t
{
  std::vector<int> ints;
};

struct initial_product_t
{
  product_t operator()()
  {
    product_t product;

    product.ints.resize(10000000,0);

    return product;
  }
};

struct updated_product_t
{
  updated_product_t(product_t & product)
  : product(product)
  {}

  product_t & operator()()
  {
    return product;
  }

  product_t & product;
};

int main()
{
  auto product = generate_one<initial_product_t>();

  for (size_t i=0,j=10000; i!=j; ++i)
  {
    std::cout << i << "/" << j << std::endl;

    product = generate_one<updated_product_t>(product);
  }
}

Edit 1
I've tried the following code after suggestions from other users. But got some compilation errors.
struct updated_product_t
{
  updated_product_t(product_t && product)
  : product(product)
  {}

  product_t operator()()
  {
    return std::move(product);
  }

  product_t product;
};

The error
$ clang++ -std=c++14 stackoverflow.cpp -o test
stackoverflow.cpp:60:15: error: no matching function for call to 'generate_one'
    product = generate_one<updated_product_t>(product);
              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
stackoverflow.cpp:6:6: note: candidate template ignored: substitution failure
      [with T = updated_product_t, Args = <product_t>]: no matching constructor
      for initialization of 'updated_product_t'
auto generate_one(Args... args) -> decltype(T{args...}()) {
     ^                                      ~
1 error generated.

I don't understand where the failure is.
Edit 2
I've changed - after digging deep into lvalue and rvalue - the factory to
template<typename T, typename... Args>
auto generate_one(Args&&... args) -> decltype(T{args...}()) {
  T t{args...};    // ^^
  return t();      // a reference to a lvalue or rvalue
}

And I changed the operator() as it now returns the product with std::move.
struct updated_product_t
{
  updated_product_t(product_t & product)
  : product(product)
  {}

  product_t operator()()
  {
    return std::move(product);
  }

  product_t & product;
};

With these changes I get fast execution.

A: The slowness is here:
product = generate_one<updated_product_t>(product);

You're doing an assignment of the large vector every time.  Here's one way to fix it:
int main()
{
    product_t product = generate_one<initial_product_t>();
    product_t* pp;

    for (size_t i=0,j=10000; i!=j; ++i)
    {
        std::cout << i << "/" << j << std::endl;

        pp = &generate_one<updated_product_t>(product);
    }
}

Or you can refactor product_t to hold a shared_ptr to avoid copying the data of the vector:
struct product_t
{
    std::shared_ptr<std::vector<int>> ints;
};

struct initial_product_t
{
    product_t operator()()
    {
        product_t product;
        product.ints = std::make_shared<std::vector<int>>(10000000);
        return product;
    }
};


text:
Q: update location in background in iOS I am working on walking track type app but facing problem that how location would upadte when app is in background . I am drawing a path on map as location update and a timer also .
Then please  suggest me how  i handle it.
here is my code
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    if(!newLocation) return;

    if ((oldLocation.coordinate.latitude != newLocation.coordinate.latitude) &&
        (oldLocation.coordinate.longitude != newLocation.coordinate.longitude))
    {
      // to  draw path as new location find
        jogPoint = [[JogPoint alloc] initWithCenterCoordinate:newLocation.coordinate];

        [jogPoints addObject:jogPoint];

         if([jogPoints count] >= 5) {

            [self.mapView addOverlay:jogPoint];

            CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:oldLocation.coordinate.latitude longitude:oldLocation.coordinate.longitude];

            CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.longitude];
            // returns distance in meters
          distnc+=[loc1 distanceFromLocation:loc2] ;
            distanceLabel.text=[NSString stringWithFormat:@"%lf",distnc];

       //  jogInfo.distance += ([loc1 distanceFromLocation:loc2]) * 0.000621371192;

           // jogInfo.eclapsedTime = (CFAbsoluteTimeGetCurrent() - startTime) * 1000 * 60;

        }
    }
 }

A: If your Application is in background mode also location is tracking/update as like if your app. active so don't worry about it :)
Just Make sure your create CLLocationManager such like
self.currentLocation = [[CLLocationManager alloc]init];
self.currentLocation.desiredAccuracy = kCLLocationAccuracyHundredMeters;
self.currentLocation.delegate = self;
[self.currentLocation startUpdatingLocation];

EDITED :
If here set distanceFilter then your method call at specific meter which value set in distanceFilter otherwise it update whenever your device is move
And This is very important to set/add Require background mode in YourProjectName-Info.plist file
Value is App Registers for location update
Such like

A: You can use the significant-change location service to receive location events.

This service offers a significant power savings and provides accuracy
  that is good enough for most apps. It uses the device's cellular radio
  to determine the user's location and report changes in that location,
  allowing the system to manage power usage much more aggressively than
  it could otherwise. This service is also capable of waking up an app
  that is currently suspended or not running in order to deliver new
  location data.

To use the significant-change location service:

Create an instance of the CLLocationManager class, assign a delegate
  to it, and call the startMonitoringSignificantLocationChanges method
  . As location data becomes available, the
  location manager notifies its assigned delegate object. If a location
  update has already been delivered, you can also get the most recent
  location data directly from the CLLocationManager object without
  waiting for a new event to be delivered.


text:
Q: hibernate уникальный результат Есть веб-приложение на БД Oracle с ORM Hibernate, проблема такова: при аутентификации пользователя вызывается метод чтения из DAO:
public Customer readByUsername(String username) {
    Customer customer=null;
    session=HibernateUtil.getSessionFactory().openSession();
    try{
        transaction = session.beginTransaction();
        String queryString = "from Customer where username= :username";
        Query query=session.createQuery(queryString);
        query.setParameter("username",username);
        customer= (Customer) query.uniqueResult();
    }catch (RuntimeException e) {
        e.printStackTrace();
    } finally {
        session.flush();
        session.close();
    }
    return  customer;
}

На строке customer= (Customer) query.uniqueResult()
выскакивает исключение NonUniqueResultException: query did not return a unique result: 6
В ручную проверил в БД там пользователь с таким username всего один.
Возможно проблема в том что я до этого неоднократно добавлял и удалял такого же пользователя и оно где-то закешировалось

A: Проблема была решена. Когда производились изменения в БД через SQL Developer не был сделан финальный commit, соответственно hibernate видел куда больше одной и той же сущности.


text:
Q: Não consigo alterar tipo de coluna -> Objeto Depende da coluna em questão Preciso modificar o tipo de coluna de uma tabela do cliente, entretanto esta alteração será feita através de um programa escrito em VB.Net e portanto precisa ser feita via comando SQL.
A questão é que ao utilizar o comando:
ALTER TABLE Customer ALTER COLUMN COLUNA int;

Recebo a seguinte mensagem:
The object 'DF__Tmp_Customer__Coluna__15BB0E23' is dependent on column 'Coluna'.
Msg 4922, Level 16, State 9, Line 1
ALTER TABLE ALTER COLUMN Coluna failed because one or more objects access this column.

Não consigo de forma alguma, aplicar nenhuma alteração sobre a coluna em questão...

A: Solução do Problema :
Script:
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[NomeDaConstraint]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[NomeDaTabela] DROP CONSTRAINT [NomeDaConstraint]
END


text:
Q: Database design - best way to store templates and instances Our database calls for having templates, for instance having a meeting template with a certain group of people who attend the meeting along with a base meeting name. The meeting can then be "instantiated" so that you can make copies of that meeting and modify the attributes. The best ways I can think of doing it are to:

*

*Store the "instances" in the same table and store related information similarly.

*Make different tables with the same attributes and store the templates in one table and the "instances" in another table.

A: I would store the templates in a separate table that mirrors the necessary columns in the instance table.  That way, you won't need to put special logic anywhere to filter out one or the other type (template or instance) when looking for a specific type of data.  Putting the templates in another table will allow you to add more metadata to the template if you need to in the future.

A: How about using one table, but adding a flag field like "isTemplate" to the table, which will serve to identify a record as the default or 'template' record.
You create a new record which has the default parameters, and set isTemplate as "1" or TRUE or YES or whatever.
When creating a new meeting, then just create is as a copy of the template, like so:
INSERT INTO meetings(place,people,time)
(SELECT place,people,time FROM meetings WHERE isTemplate = '1')

If you have multiple templates, then you will get a list of the available templates as:
SELECT * FROM meetings WHERE isTemplate = '1'

and then instantiate one of those templates by the primary key rather than 'isTemplate':
INSERT INTO meetings(place,people,time)
(SELECT place,people,time FROM meetings WHERE ID = 'xxxx')


text:
Q: Parent Div's mouse out function is called on mouseover of child element I have the below HTML in my page

1

This is content

2

This is content2

and in my javascript
function ShowEditDiv(divId)
{
  $("#divEditLink" + divId).html("").addClass("divEdit");
}
function HideEditDiv(divId)
{
  $("#divEdit" + divId).empty().addClass('divEdit');
}

My requirement is to show an edit link when user place his mouse over the master div. Now its working fine.But when i place mouse over the div which holds the edit image/link, it is disappearing. I found that when i place mouse over the edit div, the mouseout function of parent div is getting called. Can any one help me to solve this ?

A: The solution to this error is to use mouseenter and mouseleave events instead of mouseover and mouseout.
More information on this present in this link
http://jquery-howto.blogspot.com/2009/04/problems-with-jquery-mouseover-mouseout.html

A: Use
stopPropagation in child elements function.

Stops the bubbling of an event to
  parent elements, preventing any parent
  handlers from being notified of the
  event.


text:
Q: How to become full administrator in Windows 8.1 I want to move a file but I am getting below error. I thought that my account is not administrator but when I check accounts and users section from control panel I have found that  My account is admin. How can I move this file?
Note: When I right click and go to Properties-Security-Advanced tab I couln't change(even view) owner of this file. It says "You do not have permission to view or edit this object's permission settings"
You'll need to provide administrator permission to move this file.

A: There's a quick registry hack for this.  Just Google "Take Ownership .reg".  Basically, 2 registry keys - one to add and one to remove.  You just need to double-click the .reg file to add the hack to your registry, and it'll add "Take Ownership" to your Windows Explorer menu.  Then whenever you get those errors about permission, you right click the mouse on that file or folder, and it'll allow you access to it.  Be careful about exposing certain folders to editing for security reasons.  Add the other hack, Remove Take Ownership if you want the ability to lock up that file/folder again.

A: Use the following commands and replace E: with the letter of the partition you want to apply the commands or change the folder path.
Update:
In some cases, as happened to me, the context menu was missing some items and I could not create files in some places so I have disabled UAC by Regedit.
Warning:
This is not recommended, UAC is highly recommended that greater security is enabled for Windows, but as I am not a layman user as well, I leave off these screens to avoid unnecessarily requesting confirmation.
Through the run, go to regedit and navigate to the key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\system

Change the value of property EnableLUA from 1 to 0
takeown /F "E:" /A /R /D Y
icacls "E:" /setowner "Administrators" /T /C

A: The process that is moving the file must be started as administrator. If you are using a command line to do "move /here/file.txt /there/file.txt", then start a new shell by right-clicking on the "Command Prompt" icon and picking 'Run as administrator'. If using the Explorer to drag'n'drop, then start a new "Windows Explorer" in the same manner.


text:
Q: Alarm manager doesn't repeat? so I've made an code in which alarm manager should fire at exact time and repeat every minute, and it partially works, it fires for the first time but it doesn't repeat after given interval(one minute).
Main activity :
public void SetAlarm()
    {
        final Button button = findViewById(R.id.button); // replace with a button from your own UI
        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override public void onReceive( Context context, Intent _ )
            {
                Toast.makeText(context, "Nope", Toast.LENGTH_SHORT).show();
                context.unregisterReceiver( this ); // this == BroadcastReceiver, not Activity
            }
        };

        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 20);
        cal.set(Calendar.MINUTE, 30);
        cal.set(Calendar.SECOND, 0);

        this.registerReceiver( receiver, new IntentFilter("com.blah.blah.somemessage") );

        PendingIntent pintent = PendingIntent.getBroadcast( this, 0, new Intent("com.blah.blah.somemessage"), 0 );
        AlarmManager manager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));

        // set alarm to fire 5 sec (1000*5) from now (SystemClock.elapsedRealtime())
        manager.setInexactRepeating( AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() + 1000*5, 6000, pintent );
    }

    public void klik(View view) {
        SetAlarm();
    }

}

A: Try using setRepeating():
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
    cal.getTimeInMillis() + 1000*5, 6000, pintent);

For best practices you can see this doc.

A: I think the minimum repeat in ms is 60000 (1 min) for security, and battery life :)

Value will be forced up to 60000 as of Android 5.1...

A: If its all of your Main Activity i do not understand it. Why do u define button in SetAlarm() ((SetAlarm called on click)) ?!
I think you should try a fully new way. Like this....

*

*In Main Activity onCreate event define button:
Button btn_yrbnt = findViewById(R.id.btn);

*Make an event for onClick
btn_yrbnt.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        startAlarm();
    }
});

*Set the alarm in the startAlarm() event
Intent intent = new Intent(this, Alarm.class);  //In 4th step u understand it
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 10);
calendar.set(Calendar.SECOND, 1);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), REPEAT_TIME, pendingIntent);  //Repeat time is bigger than 60000ms but u can use AlarmManager.INTERVAL_DAY for example or AlarmManager.INTERVAL_FIFTEEN_MINUTES

*Make a new Java class named Alarm.class with BroadCastReceiver superclass
public class Alarm extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
     //Type what do u want to do on Alarm's fire!!!!
}}

*IMPORTANT! In ur manifest should link the Receiver
<receiver android:name=".Alarm"
    android:enabled="true"
    android:exported="true"/>

If u do everything good, your alarm works fine!
Sry my bad english!


text:
Q: NodeJS Connect/Express app.use handling Does anyone know how to implement the function chain used in connect/express. So one can do this..
var app = {}, app.stack = [];
app.use(function(r, s, n){
  // dosomething
})

require('http').createServer(function(r, s){
    // execute functions in app stack
})

A: The middleware "chain" is actually just a "stack" which is actually a simple javascript Array of functions to execute in order. Whenever you call use, connect appends your function to the middleware stack. When it's time to run middleware, connect just executes all the functions in order with a bit of logic to pass the req, res, next parameters and wire up the next callback to mean continue processing the middleware stack. I agree with @robertklep that you should read the source code as it is quite readable and illuminating.


text:
Q: Adding href in Wall of jomsocial like Facebook
In Facebook Wall, if you add a href link or URL of the website, Facebook will grab the images and description of that particular link and show it on the post.

How to implement this in Jomsocial?
At least tell how to implement using the normal PHP and Javascript or Jquery.

A: I had this laying around. Create a div with id="showthumb", create a textarea.. to be used as the obj in this function.
function getthumb ($obj)
{
     $obj.keydown (function (e) //obj is the textbox
     {
    if (e.keyCode == 32 || e.charCode == 32) { //user pressed space.
        var t_content = $obj.val ();
        var t_urls = t_content.match (/https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/);

        if (t_urls != null) {
            if (t_urls.length > 0) {
                $('#showthumb').html ('<img src='+t_urls['input']+'>');
            }
        }
    }
 });
}

you can probably set it inside an editable div.btw.. I learned this from here

A: A Simple approach would be like this:
Suppose you have a textarea where user type in their link.
Step1: Use onchange  event of textarea to  know if somebody typed in something.
Step2: Use Jquery to make sure if it is Url . Code will be something like this.
some regex to extract the correct url from textarea like this
 var regex=/Your Regex to know url/
 var url= regex.mathc($('#textareaid').val()).

Step3: Now you got the url . Send it to server using.
 $.ajax({
                       url:submit.php
                       type:'POST'
                       success:// do your dom mainpulation code here by geting the data from server.
                           });

Step 4: In your php code make httpwebrequest to get the contents html of that url. And you can use some utility to extract the images and headers out of html you got. Send it as a response to the ajax request you made.
Step 5: you are done. On the success of ajax request you append the data you sent from server to your DOM.


text:
Q: Bootstrap 4 Navbar Menus Enclosed By Borders I am new in bootstrap 4 and I want to know if there is an option in bootstrap 4 for navbar menus enclosed by borders like this: image
Thanks!

A:

.nav-item {
 border-right: 1px solid silver;
 padding-right: 15px;
}
.nav-item:first-child {
  border-left: 1px solid silver;
  padding-left: 15px;
}
<link href="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/css/bootstrap.css" rel="stylesheet"/>

      Home (current)

      Features

      Pricing

      About


text:
Q: Options to manage local vs cloud development configuration settings in Visual Studio We will use Windows Azure Websites for our basic hosting needs in the future.  And since there are very specific configuration settings for cloud vs local how do you manage these settings?  Take for example the following:
Local Development Server:
string path = AppSettings["StoragePath"];

<add key="StoragePath" value="c:\temp" />

Windows Azure:
string path = AppSettings["StoragePath"];

<add key="StoragePath" value="xyz" />

Do you manually change the StoragePath in the config file before each release OR is there something in code that can be done such as:
<add key="LocalStoragePath" value="c:\temp" />
<add key="BlobStoragePath" value="xyz" />

string path;
if (Azure)
{
   path = AppSettings["BlobStoragePath"];
}
else
{
   path = AppSettings["LocalStoragePath"];
}

If the later is possible, how can i determine if the environment is Windows Azure?

A: I typically create a new build configuration (called Azure).
Then in the web.config create your keys..
<add key="LocalStoragePath" value="c:\blah" />
<add key="AzureStoragePath" value="xyz" />

in your code write:
#if CONFIG == "Azure"
  public const String storageKey = "AzureStoragePath";
#endif CONFIG == "Debug"
  public const String storageKey = "LocalStoragePath";
#endif

And use it:
String path = AppSettings[storageKey];

A: public interface IConfigurationProvider { }

public class AzureConfigurationProvider : IConfigurationProvider { }

public class LocalConfigurationProvider : IConfigurationProvider { }

public static class ConfigurationProviderFactory
{
    private static bool _isAzure = Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.IsAvailable;

    private static Lazy<IConfigurationProvider> _provider = Lazy<IConfigurationProvider>(GetProvider);

    private static IConfigurationProvider GetProvider()
    {
         return _isAzure ?
             new AzureConfigurationProvider() :
             new LocalConfigurationProvider();
    }

    public static IConfigurationProvider Instance
    {
        get { return _provider.Value; }
    }
}

A: Assuming you're using the latest version of Web Publishing feature in VS 2010 or VS2012 you can accomplish this fairly easily with your publish profile and a web.config transform.
First, create your publish profile (right-click the project, select Publish, go through the dialog).  This will be the default place to make a variety of config change anyways, such as connection strings.
Then, right-click the the .pubxml file created for your publish profile and there should be an option to add a transform.  This will add a new web..config, which should appear next to the web.Debug.config/web.Release.config.
In that file you can add a transform for the app setting you want to change.  The transformation value will be applied when you publish using that profile; local development will still use whatever value you want.


text:
Q: How can I stop an object (file) from being accessed over http(s) using Amazon's AWS I have tried the following two methods but both of them still allow the file to be accessed using a URL such as https://bucket-example.s3.amazonaws.com/mwnl.json
(The URL is just an example)
$result = $s3Client->putObject(array(
    'ACL'    => 'private',
    'Bucket' => $bucket,
    'Key'    => 'mwnl.json',
    'Body'   => $json
));

and...
$result = $s3Client->putObjectAcl(array(
    'ACL'    => 'private',
    'Bucket' => $bucket,
    'Key'    => 'mwnl.json',
    'Body'   => $json
));


text:
Q: Run portfolio return simulation 250 times and plot efficient frontiers I've been handed a CSV file holding returns for 10 industry portfolios based on which I've estimated sample mean returns (mu) and variance-covariance matrix (sigma). Afterwards, I've conducted a simulation of 100 returns for which I've computed plug-in estimates of the efficient frontier and compared this to the "true" frontier based on the CSV returns. This part runs smooth but now I'm asked to repeat the simulation 250 times and visualize all of the simulated efficient frontiers in one plot. The simulation code is quite simple:
simulate_returns <- function(T, sigma, mu){
  set.seed(2021)
  returns <- mvrnorm(T, Sigma = sigma, mu = mu)
  return(returns)
}

sim_returns <- simulate_returns(100, sigma, mu)

Once I have the simulated returns I calculate sigma and mu:
mu_sim <- sim_returns %>%
  colMeans(na.rm = TRUE) %>%
  as.matrix()

sigma_sim <- sim_returns %>% cov(use = "pairwise.complete.obs")

And then use the formula to compute points for the efficient frontier:
compute_efficient_frontier <- function(sigma, mu){
  sigma_inv <- solve(sigma)
  N <- ncol(sigma)
  w_mvp <- sigma_inv %*% rep(1, N) #Compute mvp weights
  w_mvp <- w_mvp/sum(w_mvp)
  return_mvp <- c(t(w_mvp) %*% mu)
  mu_bar = 2 * return_mvp
  iota <- rep(1, ncol(sigma))
  C <- c(t(iota)%*%solve(sigma)%*%iota)
  D <- c(t(iota)%*%solve(sigma)%*%mu)
  E <- c(t(mu)%*%solve(sigma)%*%mu)
  lambda_tilde <- c(2*(mu_bar - D/C)/(E - D^2/C))
  w_eff <- w_mvp + lambda_tilde/2*(solve(sigma)%*%mu-D/C*solve(sigma)%*%iota)
  c <- seq(from = -0.1, to = 1.2, by = 0.01)
  res <- tibble(c = c, mu = NA, sd = NA)
  for(i in seq_along(c)){ # For loop
    w <- (1-c[i])*w_mvp + (c[i])*w_eff # Portfolio of mvp and efficient portfolio
    res$mu[i] <- t(w) %*% mu # Portfolio expected return
    res$sd[i] <- sqrt(t(w) %*% sigma %*% w) # Portfolio volatility
  }
  return(res)
}

frontier2 <- compute_efficient_frontier(sigma_sim, mu_sim)

I need to figure out a way to repeat this 250 times and plot all of the frontiers in a meaningful way. I'm new to R and the coding community; I hope I've provided you with sufficient information and that the post makes sense.


text:
Q: Why the integer data types hexadecimal, octal and binary are getting converted to decimal type and then displayed in a browser? I'm using PHP 7.1.11
I've following PHP code :
<?php
$a = 0123; // an octal number (equivalent to 83 decimal)
$b = 0x1A; // a hexadecimal number (equivalent to 26 decimal)
$c = 0b11111111; // a binary number (equivalent to 255 decimal)

var_dump($a); //Output : int(83) int(26) int(255)
var_dump($b); //Output : int(26) int(255)
var_dump($c); //Output : int(255)
?>

My question is why the data contained in integer data types of octal, hexadecimal and binary are getting converted into decimal and then displayed in browser along with the new datatype integer?
Why it's not showing the original values of variables and also not showing their original data type?
Why there is a conversion step and who does this for what reason?
If we take other data types life boolean, float, string nothing like this happen. Everything works as expected then why this weird thing is happening with these integer data types?

A: There's only one kind of (integer) number, and the format of the number is completely unimportant. The values 052, 42 and 0x2A all represent exactly the same value. PHP doesn't remember how a number was created; it doesn't store that information because it's useless information that would only waste space being stored. Binary, octal and hexadecimal notations are mere convenience affordances to allow you to express numbers in the most suited notation for the context; it's all being parsed to an int of the same value and then output in decimal notation by default.


text:
Q: Dealing with context classes in Python 2.4 I'm trying to use the python-daemon module. It supplies the daemon.DaemonContext class to properly daemonize a script. Although I'm primarily targeting Python 2.6+, I'd like to maintain backwards compatibility to version 2.4.
Python 2.5 supports importing contexts from future, but Python 2.4 has no such facility.
I figured I could just catch whatever error the with statement raises and enter and exit the context manually for 2.4, but I can't seem to catch the SyntaxError raised.
Is there any way to accomplish this short of explicitly checking the interpreter version?
Below is the gist of what I'm trying to do and the problem I'm getting. In Real Life I don't have control of the context class, so it needs to work without mangling the original class, ie not like these ideas.
Nevermind if Python 2.4 can't run python-daemon; I'd at least like to able to catch the error and implement a fallback or something.
Thanks for helping.
#!/usr/bin/python2.4
from __future__ import with_statement
# with_statement isn't in __future__ in 2.4.
# In interactive mode this raises a SyntaxError.
# During normal execution it doesn't, but I wouldn't be able to catch it
# anyways because __future__ imports must be at the beginning of the file, so
# that point is moot.

class contextable(object):
    def __enter__(self):
        print('Entering context.')
        return None
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('Exiting context.')
        return False

def spam():
    print('Within context.')

context = contextable()

try:
    with context: # This raises an uncatchable SyntaxError.
        spam()
except SyntaxError, e: # This is how I would like to work around it.
    context.__enter__()
    try:
        spam()
    finally:
        context.__exit__(None, None, None)

A: SyntaxError is diagnosed by the Python compiler as it compiles -- you're presumably trying to "catch" it from code that's being compiled as part of the same module (e.g., that's what you're doing in your code sample), so of course it won't work -- your "catching" code hasn't been compiled yet (because compilation has terminated unsuccessfully) so it can't catch anything.
You need to ensure the code that might have a syntax error gets compiled later than the catching code -- either put it in a separate module that you import in the try clause, or in a string you compile with the built-in by that name (you can later execute the bytecode resulting from the compile call, if it terminates successfully).
Neither possibility looks good for your purposes, I think.  I suspect that using two separate modules (and probably picking between them depending on the "does this compile" check, but a version check sounds much cleaner to me) is the only "clean" solution, unfortunately.
Edit: here's how to microbenchmark try/except against version checks:
$ python2.4 -mtimeit 'try:
  compile("with x: pass", "", "exec")
except SyntaxError: x=1
else: x=2'
100000 loops, best of 3: 10.8 usec per loop
$ python2.6 -mtimeit 'try:
  compile("with x: pass", "", "exec")
except SyntaxError: x=1
else: x=2'
10000 loops, best of 3: 40.5 usec per loop

$ python2.4 -mtimeit -s'import sys' 'if sys.version>="2.5": x=2
else: x=1'
1000000 loops, best of 3: 0.221 usec per loop
$ python2.6 -mtimeit -s'import sys' 'if sys.version>="2.5": x=2
else: x=1'
10000000 loops, best of 3: 0.156 usec per loop

As you see, the version I consider cleaner is 10.8 / 0.221, almost 50 times faster, on 2.4, and 40.5 / 0.156, almost 260 times faster, on 2.6.  In general (with rare exceptions), the clean (i.e., "pythonic") approach will turn out to be the better optimized one in Python -- often, at least part of the reason can be that Python core developers focus on facilitating and encouraging the use of constructs they like, rather than that of constructs they dislike.


text:
Q: Why the gridApi.on.edit.beginCellEdit in angular-ui-grid cannot update the new drop-down options immeidiately? I have the same problem with this one Why ui grid value drop-down box will be assigned in the event fires before beginCellEdit in angular
And have little bit difference. After I updated the editDropdownOptionArray it still keep the old value, It's only have the new value in the next click.
Hope everyone can help me with this one.
Thank you.
Here is my code snippet:
The html of the dropdown:
<div>
    <form name="inputForm">
        <select ng-class="'colt' + col.uid"
                ui-grid-edit-dropdown
                ng-model="MODEL_COL_FIELD"
                ng-options="field CUSTOM_FILTERS for field in editDropdownOptionsArray"></select>
    </form>
</div>

The controller code:
$scope.menuColumns = [
                        { displayName: 'Menu', field: 'name', enableCellEdit: false },
                        {
                            displayName: 'Access Level', field: 'accessLevelName',
                            editableCellTemplate: 'Scripts/application/role/directive/dropdown-menu-assignment.html',
                            editDropdownValueLabel: 'Access Level', editDropdownOptionsArray: userMgtConstant.menuAccessLevel
                        }
                    ];

                    $scope.menuOptions = {
                        data: [],
                        onRegisterApi: function (gridApi) {
                            gridApi.edit.on.beginCellEdit($scope, function (rowEntity, colDef, event) {
                                if (rowEntity.parent === true) {
                                    colDef.editDropdownOptionsArray = $scope.levelList;
                                } else {
                                    colDef.editDropdownOptionsArray = $scope.childLevelList;
                                }
                            });
                            gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
                                if (rowEntity.parent !== true) {
                                    if(rowEntity.name === 'Revenue Bench'){
                                        var accessLevel = commonUtils.getIdFromName(rowEntity.accessLevelName, userMgtConstant.menuAccessLevel);
                                        if(accessLevel > 1){
                                            $scope.isShowFunctionAssignment = false;
                                        } else if(rowEntity.functionAssignments.length !== 0) {
                                            $scope.isShowFunctionAssignment = true;
                                        }
                                    }
                                } else {
                                    // udpate child dropdown list menu
                                    var index = _(userMgtConstant.menuAccessLevel).indexOf(newValue);
                                    $scope.childLevelList = $scope.levelList.filter(function (item, i) {
                                        return i >= index;
                                    });

                                    if($scope.childLevelList.length > 2){
                                        parentSwitch = true;
                                    }

                                    if($scope.childLevelList.length < 3 && parentSwitch){
                                        colDef.editDropdownOptionsArray = $scope.childLevelList;
                                        parentSwitch = false;
                                    }

                                    // update all child value
                                    _($scope.menuOptions.data).each(function (dataItem) {
                                        if (dataItem.parent !== true) { // prevent infinite loop
                                            dataItem.accessLevelName = newValue;
                                        }
                                    });
                                }
                            });
                        }
                    };

Here is the usage of the grid:
<inline-edit-grid options="menuOptions" columns="menuColumns"></inline-edit-grid>

A: You should look into the usage of editDropdownRowEntityOptionsArrayPath instead of editDropdownOptionsArray
From the docs :

editDropdownRowEntityOptionsArrayPath can be used as an alternative to
  editDropdownOptionsArray when the contents of the dropdown depend on
  the entity backing the row.

Here is a link to tutorial


text:
Q: Facebook publish as page indefinitely without user login I want to give my app the ability to post as my own page (and app separately) and am trying to work out how best to programatically get a suitable access token. I have the following code embedded in a view, and it works, but depends on an access token I'm manually inserting for now.
event = Event.objects.get(pk=1)
try:
    graph = GraphAPI(access_token)
    graph.post(
                path = '/42636472/events',
                name = event.name,
                location = event.location,
                start_time = '2012-11-04T19:00:00-0700',
                )
    print event.date
except GraphAPI.OAuthError, e:
    print e.message

This update from Facebook suggests that hard-coding access tokens in is unsustainable and will require regular attention:
https://developers.facebook.com/roadmap/offline-access-removal/
What are people doing in this situation, to have an app update a page belonging to the app's organisation, or just getting access_tokens giving page manage access without having anyone logging in?

A: The same document you linked explains that Page access tokens will continue to be infinite if retrieved using a long-lived token for the Page's admin - see Scenario 5


text:
Q: GSON won't properly serialise a class that extends HashMap I have the following code:
public static class A
{
    public A() {}
    private List<B> bs = new ArrayList<B>();
    public List<B> getBs() {
        return bs;
    }
    public void setBs(List<B> bs) {
        this.bs = bs;
    }
}

public static class B
{
    B(String foo){this.foo=foo;}
    private String foo;
    public String getFoo() {
        return foo;
    }
    public void setFoo(String foo) {
        this.foo = foo;
    }
}

public static void main(String[] args) throws Exception {
    Gson gson = new Gson();
    A a = new A();
    a.getBs().add(new B("bar"));
    System.out.println(gson.toJson(a));
}

and as expected the output is:
{"bs":[{"foo":"bar"}]}

However, if I make A a subclass of HashMap:
public static class A extends HashMap

I get an empty set returned: {}
I have even tried:
System.out.println(gson.toJson(a, new TypeToken<A>(){}.getType()));

and:
System.out.println(gson.toJson(a, new TypeToken<HashMap>(){}.getType()));

Can someone tell me whether/how I can serialise this HashMap subclass using GSON?

A: Gson works with (default and custom) TypeAdapterFactory instances and the TypeAdapter objects they create to serialize/deserialize your objects.
It goes through the list of registered TypeAdapterFactory objects and picks the first one that can create an appropriate TypeAdapter for the type of the object your are providing. One of these TypeAdapterFactory objects, is one of type MapTypeAdapterFactory which creates a TypeAdapter (of type MapTypeAdapterFactory$Adapter) that serializes/deserializes based on the java.util.Map interface (keys/values). It does nothing about your custom sub type's fields.
If you want Gson to serialize your type as both a Map and a custom type, you will need to register either a custom TypeAdapter directly or a custom TypeAdapterFactory that creates TypeAdapter objects.

A: Here is the custom TypeAdapterFactory.
Test:
public static void main(String[] args) throws Exception{
    Gson gson = new GsonBuilder()
            .registerTypeAdapterFactory(new RetainFieldMapFactory())
            .create();

    Foo f = gson.fromJson("{'key1':'value1','key2':'value2'}", Foo.class);

    System.out.println("in map:\t" + f.toString());
    System.out.println("f.key1:\t"+f.key1);
    System.out.println("toJson:\t"+gson.toJson(f));
}

public static class Foo extends HashMap<String, String> {
    private String key1;
}

Output:
in map: {key2=value2}
f.key1: value1
toJson: {"key2":"value2","key1":"value1"}

RetainFieldMapFactory.java:
/**
 * Created by linfaxin on 2015/4/9 009.
 * Email: linlinfaxin@163.com
 */
public class RetainFieldMapFactory implements TypeAdapterFactory {

    FieldNamingPolicy fieldNamingPolicy = FieldNamingPolicy.IDENTITY;
    ConstructorConstructor constructorConstructor = new ConstructorConstructor(Collections.<Type, InstanceCreator<?>>emptyMap());
    MapTypeAdapterFactory defaultMapFactory = new MapTypeAdapterFactory(constructorConstructor, false);
    ReflectiveFilterMapFieldFactory defaultObjectFactory = new ReflectiveFilterMapFieldFactory(constructorConstructor,
            fieldNamingPolicy, Excluder.DEFAULT);

    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        final TypeAdapter<T> mapAdapter = defaultMapFactory.create(gson, type);
        if(mapAdapter!=null){
            return (TypeAdapter<T>) new RetainFieldMapAdapter(mapAdapter, defaultObjectFactory.create(gson, type));
        }
        return mapAdapter;
    }

    class RetainFieldMapAdapter extends TypeAdapter<Map<String, Object>>{
        TypeAdapter<Map<String, Object>> mapAdapter;
        ReflectiveTypeAdapterFactory.Adapter<Map<String, Object>> objectAdapter;
        RetainFieldMapAdapter(TypeAdapter mapAdapter, ReflectiveTypeAdapterFactory.Adapter objectAdapter) {
            this.mapAdapter = mapAdapter;
            this.objectAdapter = objectAdapter;
        }

        @Override
        public void write(final JsonWriter out, Map<String, Object> value) throws IOException {
            //1.write object
            StringWriter sw = new StringWriter();
            objectAdapter.write(new JsonWriter(sw), value);

            //2.convert object to a map
            Map<String, Object> objectMap = mapAdapter.fromJson(sw.toString());

            //3.overwrite fields in object to a copy map
            value = new LinkedHashMap<String, Object>(value);
            value.putAll(objectMap);

            //4.write the copy map
            mapAdapter.write(out, value);
        }

        @Override
        public Map<String, Object> read(JsonReader in) throws IOException {
            //1.create map, all key-value retain in map
            Map<String, Object> map = mapAdapter.read(in);

            //2.create object from created map
            Map<String, Object> object = objectAdapter.fromJsonTree(mapAdapter.toJsonTree(map));

            //3.remove fields in object from map
            for(String field : objectAdapter.boundFields.keySet()){
                map.remove(field);
            }
            //4.put map to object
            object.putAll(map);
            return object;
        }
    }

    /**
     * If class is extends from some custom map,
     * class should implement this to avoid serialize custom map's fields
     */
    public interface RetainFieldFlag {}

    static class ReflectiveFilterMapFieldFactory extends ReflectiveTypeAdapterFactory{
        public ReflectiveFilterMapFieldFactory(ConstructorConstructor constructorConstructor, FieldNamingStrategy fieldNamingPolicy, Excluder excluder) {
            super(constructorConstructor, fieldNamingPolicy, excluder);
        }

        @Override
        protected boolean shouldFindFieldInClass(Class willFindClass, Class<?> originalRaw) {
            if(RetainFieldFlag.class.isAssignableFrom(originalRaw)){
                return RetainFieldFlag.class.isAssignableFrom(willFindClass);
            }else{
                Class[] endClasses = new Class[]{Object.class, HashMap.class, LinkedHashMap.class,
                        LinkedTreeMap.class, Hashtable.class, TreeMap.class, ConcurrentHashMap.class,
                        IdentityHashMap.class, WeakHashMap.class, EnumMap.class};
                for(Class c : endClasses){
                    if(willFindClass == c) return false;
                }
            }
            return super.shouldFindFieldInClass(willFindClass, originalRaw);
        }
    }
    /**
     * below code copy from {@link com.google.gson.internal.bind.ReflectiveTypeAdapterFactory}
     * (little modify, in source this class is final)
     * Type adapter that reflects over the fields and methods of a class.
     */
    static class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
        private final ConstructorConstructor constructorConstructor;
        private final FieldNamingStrategy fieldNamingPolicy;
        private final Excluder excluder;

        public ReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor,
                                            FieldNamingStrategy fieldNamingPolicy, Excluder excluder) {
            this.constructorConstructor = constructorConstructor;
            this.fieldNamingPolicy = fieldNamingPolicy;
            this.excluder = excluder;
        }

        public boolean excludeField(Field f, boolean serialize) {
            return !excluder.excludeClass(f.getType(), serialize) && !excluder.excludeField(f, serialize);
        }

        private String getFieldName(Field f) {
            SerializedName serializedName = f.getAnnotation(SerializedName.class);
            return serializedName == null ? fieldNamingPolicy.translateName(f) : serializedName.value();
        }

        public <T> Adapter<T> create(Gson gson, final TypeToken<T> type) {
            Class<? super T> raw = type.getRawType();

            if (!Object.class.isAssignableFrom(raw)) {
                return null; // it's a primitive!
            }

            ObjectConstructor<T> constructor = constructorConstructor.get(type);
            return new Adapter<T>(constructor, getBoundFields(gson, type, raw));
        }

        private ReflectiveTypeAdapterFactory.BoundField createBoundField(
                final Gson context, final Field field, final String name,
                final TypeToken<?> fieldType, boolean serialize, boolean deserialize) {
            final boolean isPrimitive = Primitives.isPrimitive(fieldType.getRawType());

            // special casing primitives here saves ~5% on Android...
            return new ReflectiveTypeAdapterFactory.BoundField(name, serialize, deserialize) {
                final TypeAdapter<?> typeAdapter = context.getAdapter(fieldType);
                @SuppressWarnings({"unchecked", "rawtypes"}) // the type adapter and field type always agree
                @Override void write(JsonWriter writer, Object value)
                        throws IOException, IllegalAccessException {
                    Object fieldValue = field.get(value);
                    TypeAdapter t = new TypeAdapterRuntimeTypeWrapper(context, this.typeAdapter, fieldType.getType());
                    t.write(writer, fieldValue);
                }
                @Override void read(JsonReader reader, Object value)
                        throws IOException, IllegalAccessException {
                    Object fieldValue = typeAdapter.read(reader);
                    if (fieldValue != null || !isPrimitive) {
                        field.set(value, fieldValue);
                    }
                }
            };
        }

        private Map<String, BoundField> getBoundFields(Gson context, TypeToken<?> type, Class<?> raw) {
            Map<String, BoundField> result = new LinkedHashMap<String, BoundField>();
            if (raw.isInterface()) {
                return result;
            }

            Type declaredType = type.getType();
            Class<?> originalRaw = type.getRawType();
            while (shouldFindFieldInClass(raw, originalRaw)) {
                Field[] fields = raw.getDeclaredFields();
                for (Field field : fields) {
                    boolean serialize = excludeField(field, true);
                    boolean deserialize = excludeField(field, false);
                    if (!serialize && !deserialize) {
                        continue;
                    }
                    field.setAccessible(true);
                    Type fieldType = $Gson$Types.resolve(type.getType(), raw, field.getGenericType());
                    BoundField boundField = createBoundField(context, field, getFieldName(field),
                            TypeToken.get(fieldType), serialize, deserialize);
                    BoundField previous = result.put(boundField.name, boundField);
                    if (previous != null) {
                        throw new IllegalArgumentException(declaredType
                                + " declares multiple JSON fields named " + previous.name);
                    }
                }
                type = TypeToken.get($Gson$Types.resolve(type.getType(), raw, raw.getGenericSuperclass()));
                raw = type.getRawType();
            }
            return result;
        }
        protected boolean shouldFindFieldInClass(Class willFindClass, Class<?> originalRaw){
            return willFindClass != Object.class;
        }

        static abstract class BoundField {
            final String name;
            final boolean serialized;
            final boolean deserialized;

            protected BoundField(String name, boolean serialized, boolean deserialized) {
                this.name = name;
                this.serialized = serialized;
                this.deserialized = deserialized;
            }

            abstract void write(JsonWriter writer, Object value) throws IOException, IllegalAccessException;
            abstract void read(JsonReader reader, Object value) throws IOException, IllegalAccessException;
        }

        public static final class Adapter<T> extends TypeAdapter<T> {
            private final ObjectConstructor<T> constructor;
            private final Map<String, BoundField> boundFields;

            private Adapter(ObjectConstructor<T> constructor, Map<String, BoundField> boundFields) {
                this.constructor = constructor;
                this.boundFields = boundFields;
            }

            @Override public T read(JsonReader in) throws IOException {
                if (in.peek() == JsonToken.NULL) {
                    in.nextNull();
                    return null;
                }

                T instance = constructor.construct();

                try {
                    in.beginObject();
                    while (in.hasNext()) {
                        String name = in.nextName();
                        BoundField field = boundFields.get(name);
                        if (field == null || !field.deserialized) {
                            in.skipValue();
                        } else {
                            field.read(in, instance);
                        }
                    }
                } catch (IllegalStateException e) {
                    throw new JsonSyntaxException(e);
                } catch (IllegalAccessException e) {
                    throw new AssertionError(e);
                }
                in.endObject();
                return instance;
            }

            @Override public void write(JsonWriter out, T value) throws IOException {
                if (value == null) {
                    out.nullValue();
                    return;
                }

                out.beginObject();
                try {
                    for (BoundField boundField : boundFields.values()) {
                        if (boundField.serialized) {
                            out.name(boundField.name);
                            boundField.write(out, value);
                        }
                    }
                } catch (IllegalAccessException e) {
                    throw new AssertionError();
                }
                out.endObject();
            }
        }
    }

    static class TypeAdapterRuntimeTypeWrapper<T> extends TypeAdapter<T> {
        private final Gson context;
        private final TypeAdapter<T> delegate;
        private final Type type;

        TypeAdapterRuntimeTypeWrapper(Gson context, TypeAdapter<T> delegate, Type type) {
            this.context = context;
            this.delegate = delegate;
            this.type = type;
        }

        @Override
        public T read(JsonReader in) throws IOException {
            return delegate.read(in);
        }

        @SuppressWarnings({"rawtypes", "unchecked"})
        @Override
        public void write(JsonWriter out, T value) throws IOException {
            // Order of preference for choosing type adapters
            // First preference: a type adapter registered for the runtime type
            // Second preference: a type adapter registered for the declared type
            // Third preference: reflective type adapter for the runtime type (if it is a sub class of the declared type)
            // Fourth preference: reflective type adapter for the declared type

            TypeAdapter chosen = delegate;
            Type runtimeType = getRuntimeTypeIfMoreSpecific(type, value);
            if (runtimeType != type) {
                TypeAdapter runtimeTypeAdapter = context.getAdapter(TypeToken.get(runtimeType));
                if (!(runtimeTypeAdapter instanceof ReflectiveTypeAdapterFactory.Adapter)) {
                    // The user registered a type adapter for the runtime type, so we will use that
                    chosen = runtimeTypeAdapter;
                } else if (!(delegate instanceof ReflectiveTypeAdapterFactory.Adapter)) {
                    // The user registered a type adapter for Base class, so we prefer it over the
                    // reflective type adapter for the runtime type
                    chosen = delegate;
                } else {
                    // Use the type adapter for runtime type
                    chosen = runtimeTypeAdapter;
                }
            }
            chosen.write(out, value);
        }

        /**
         * Finds a compatible runtime type if it is more specific
         */
        private Type getRuntimeTypeIfMoreSpecific(Type type, Object value) {
            if (value != null
                    && (type == Object.class || type instanceof TypeVariable<?> || type instanceof Class<?>)) {
                type = value.getClass();
            }
            return type;
        }
    }

}


text:
Q: How can I pass a JavaScript variable to a Java program? Essentially, the question I am asking is similar to this question. However, these Q/A's were of little value to me.
Firstly, there are several people saying that it is impossible to pass a value from a clientside language to a serverside language. However, I know that this is untrue, since I know that it is possible to pass javascritpt (clientside) variables to php (serverside) variables.
Secondly, my need to do this is based on trying to retrieve data from a 3rd party website, to be processed by my program, which will not attempt to return this data to the origional web page. Instead it will be returned to a different location. So, suppose I am retrieving the data required from their webpage using javascript and storing it within a Javascript variable, say var myData = *my required data* and I wish to create a Java program which accepts this data as an input, how would this be done?

A: You can always send client side information to the server. This works in Java as well.
You can make an AJAX request and pass your variable with it.
$.ajax({
    type: 'post',
    url: 'myserverurl.ajx',
    data: 'data=' + variable1 + '&data2=' + variable2
});

You can do this without having to make an async call as well.


text:
Q: Kotlin generic type issue with reified I've following class to map request status (Loading, Success, Error)
data class Resource<out T>(
    val status: Status,
    val data: T?
) {
    sealed class Status {
        data class Success<out T>(val data: T?) : Status()

        data class Error(
            val message: String,
            val statusCode: Int
        ) : Status()

        object Loading : Status()
    }

    companion object {
        fun <T> success(data: T?): Resource<T> {
            return Resource(status = Status.Success(data), data = data)
        }

        fun <T> error(msg: String, statusCode: Int, data: T? = null): Resource<T> {
            return Resource(status = Status.Error(msg, statusCode), data = data)
        }

        fun <T> loading(data: T? = null): Resource<T> {
            return Resource(status = Status.Loading, data = data)
        }
    }
}

I use following class to map the request
inline fun <REMOTE> networkResource(
    crossinline fetchFromRemote: suspend () -> Flow<ApiResponse<REMOTE>>,
    crossinline onFetchFailed: (errorBody: String?, statusCode: Int) -> Unit = { _: String?, _: Int -> }
) = flow<Resource<REMOTE>> {
    emit(Resource.loading(null))

    fetchFromRemote().collect { apiResponse ->
        when (apiResponse) {
            is ApiSuccessResponse -> {
                apiResponse.body?.let {
                    emit(Resource.success(data = it))
                }
            }
            is ApiErrorResponse -> {
                onFetchFailed(apiResponse.errorMessage, apiResponse.statusCode)
                emit(Resource.error(msg = apiResponse.errorMessage, statusCode = apiResponse.statusCode, data = null))
            }
            is ApiEmptyResponse -> {
                emit(Resource.success(data = null))
            }
        }
    }
}

I use that class as below
fun getSomething(): Flow<Resource<SuccessResponse<GetCartResponse>>> {
        return networkResource(
            fetchFromRemote = { cartApi.getCart() },
            onFetchFailed = { _, _ -> }
        ).flowOn(Dispatchers.IO)
    }

When i try to map that flow, I'm seeing unchecked cast issue. I've tried to play with reified type but found no solution.
getSomething().collect { response ->
    when (response.status) {
        is Resource.Status.Loading -> {
            Resource.loading(null)
        }
        is Resource.Status.Success<*> -> {
            // Below line states that Unchecked cast: Resource.Status to Resource.Status.Success<Quote>
            val quote = it.status as Resource.Status.Success<Quote>
            Resource.success(quote.data)
        }
        is Resource.Status.Error -> {
            val error = it.status as Resource.Status.Error
            Resource.error(error.message, error.statusCode)
        }
    }
}

How should i make sure that i have access to type T correctly? For more details, please see this


text:
Q: How to get frame of image when using MKNetworkKit setImageFromURL? I am trying to get the size of an image after it is downloaded using setImageFromURL:
UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[UIImageView setDefaultEngine:appDelegate.imageCache];
[img setImageFromURL:[NSURL URLWithString:@"http://testurl.com/testimg.jpg"]];
//img.frame = CGRectMake (0, 0, img.image.size.width, img.image.size.height);
[self.view addSubview:img];

I'm using MKNetworkKit -- is there a way to add a completion handler to the setImageFromURL method?

A: You can apply your own completion block
Few comments, please use Grand Central Dispatch to improve code efficiency and multi-core utilization for this kind of situations.
Example:
- (void) setImageFromUrl:(NSString*)urlString {

    [self setImageFromUrl:urlString completion:NULL];
}

- (void) setImageFromUrl:(NSString*)urlString
              completion:(void (^)(void))completion {

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        NSLog(@"Starting: %@", urlString);
        UIImage *avatarImage = nil;
        NSURL *url = [NSURL URLWithString:urlString];
        NSData *responseData = [NSData dataWithContentsOfURL:url];
        avatarImage = [UIImage imageWithData:responseData];
        NSLog(@"Finishing: %@", urlString);

        if (avatarImage) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.image = avatarImage;
                //Assign the image to ur ImageView.
                //get the image frame from ur ImageView.frame
            });
            dispatch_async(dispatch_get_main_queue(), completion);
        }
        else {
            NSLog(@"-- impossible download: %@", urlString);
        }
    });
}

For more details , please visit iOS GCD magic

A: I was able to do it by adding this line:
 self.frame = CGRectMake(0, 0, fetchedImage.size.width, fetchedImage.size.height);

to UIImageView+MKNetworkKitAdditions.m:
if(imageCacheEngine) {
    self.imageFetchOperation = [imageCacheEngine imageAtURL:url
                   size:self.frame.size
      completionHandler:^(UIImage *fetchedImage, NSURL *url, BOOL isInCache) {

        self.frame = CGRectMake(0, 0, fetchedImage.size.width, fetchedImage.size.height);

        [UIView transitionWithView:self.superview
                          duration:isInCache?kFromCacheAnimationDuration:kFreshLoadAnimationDuration
                           options:UIViewAnimationOptionTransitionCrossDissolve | UIViewAnimationOptionAllowUserInteraction
                        animations:^{
                             self.image = fetchedImage;
                           } completion:nil];
          //[[NSNotificationCenter defaultCenter] postNotificationName:KW_IMAGE_LOADED object:nil];

      } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {

        DLog(@"%@", error);
      }];
  } else {

    DLog(@"No default engine found and imageCacheEngine parameter is null")
  }


text:
Q: IE 11 "Crashes" when Using Dynamic SVG Elements I recently implemented a custom SVG Icon control for my company's new html application. Not long After it was implemented our quality department started reporting that IE 11 randomly "crashes" when using the application.
I am not sure the term crash accurately describes what is happening though. The application gets to a state where elements will no longer accept mouse or keyboard input nor will the display change to show hover styles. However, the cursor image will change appropriately as you hover over buttons and input element and scrollable sections can be scrolled using the mousewheel (but only the mousewheel).
I ran the UI Responsiveness Profiler when the application was in this state and found that there were no client side scripts running, just IE's garbage collector. After a week of testing I finally determined that the state is triggered when the user clicks on an icon generated with the svg  element but only when that click fires a function which removes the clicked svg  element from the DOM.
Here is a code pen that helps explain/recreate the issue:
http://codepen.io/GooeyIdeas/pen/WvpPzP
And the Minimum Code for Recreation:

// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
    var self = this;
    this.isLocked = ko.observable(false);
    this.toggleLock = function(){
      self.isLocked(!self.isLocked.peek())
    }
}

ko.applyBindings(new AppViewModel());
svg use{
  cursor: crosshair;
}
svg{
  border: 1px solid #eeeeee;
  cursor: default;
}
svg:hover{
  border-color: #dedede;
  background: #cecece;
}
#svg-icons{
  display: none;
}

The cursor will change into a crosshair if you are hovering over the correct element.

  <svg class="ux-icon-svg" width="24" height="24"><use data-bind="click: toggleLock" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#locked"></use></svg>

  <svg class="ux-icon-svg" width="24" height="24"><use data-bind="click: toggleLock" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#unlocked"></use></svg>

<svg xmlns="http://www.w3.org/2000/svg" id="svg-icons">
  <symbol viewBox="0 0 24 24" id="unlocked">
    <path d="M18,9h-1V7c0-2.8-2.2-5-5-5S7,4.2,7,7h1.9c0-1.7,1.4-3.1,3.1-3.1s3.1,1.4,3.1,3.1v2H6c-1.1,0-2,0.9-2,2v9c0,1.1,0.9,2,2,2
             h12c1.1,0,2-0.9,2-2v-9C20,9.9,19.1,9,18,9z"></path>
  </symbol>
  <symbol viewBox="0 0 24 24" id="locked">
    <path d="M18,9h-1V7c0-2.8-2.2-5-5-5S7,4.2,7,7v2H6c-1.1,0-2,0.9-2,2v9c0,1.1,0.9,2,2,2h12c1.1,0,2-0.9,2-2v-9C20,9.9,19.1,9,18,9z
             M15.1,9H8.9V7c0-1.7,1.4-3.1,3.1-3.1s3.1,1.4,3.1,3.1V9z"></path>
  </symbol>
</svg>

Has anyone encountered this before? Does anyone know of a work around that will still let me use the SVG 'use' element? Do I need to clarify anything?
*edit
It seems that some people are not able to reproduce this error. I would like     to know if anyone else can reproduce this error and if you can't, what version of windows are you running?
**edit
It is looking like this bug does not exist on Windows 8 PCs. To be sure I added CSS to my examples that will change the cursor into a crosshair when you are hovering over the svg use element since that is the element you have to click to trigger the crash.

A: Since there hasn't been much traffic with this post I guess I will post a solution:
I added this CSS rule:
svg use {
  pointer-events: none;
}

This is not ideal but it keeps IE 11 from locking up and that is all I am required to support with this project. However I would like for this post to help others in the future who might encounter this bug and do need to support older versions of IE. If anyone is willing to take the time to come up with a more robust solution I will accept that as the answer to this post.
Also should I file a bug report to microsoft regarding this issue?

A: I was running into this with an <svg> that was dynamically added or removed from the DOM with AngularJS and ng-if.  The accepted solution did not work for me.  The solution that did work was to use ng-show instead which hides and shows the SVG instead of adding and removing it from the DOM.


text:
Q: Target div in parent of parent of parent I am trying to target an image in the parent of the parent of the parent of my button.
Tried :
$(event.target).parents().eq(2).$("img").css( "opacity", .3 );
$(event.target).parent().parent().parent().$("img").css( "opacity", .3 );
$(event.target).parent().parent().parent("img").css( "opacity", .3 );
Edit: just realized it's the parent of the parent but, even modified accordingly, the code below still doesn't function.
here is the HTML:

<button type="button" class="page3">Read more</button>

js:
$( "button.page3" ).click(function(event) {
$(event.target).parents().eq(1).$("img").css( "opacity", .3 ); //doesnt work
$(event.target).closest("img").css( "opacity", .3 ); //neither
}

A: If this is the structure of the html

            <button id="btn">Test</button>

Then you could select the image and change the css by this
$(event.target).parent().parent().parent().find('img').css('opacity', '.3');

Or simply
$(event.target).parents('div').find('img').css('opacity', '.3');

As pointed out in the comments by @jony-Y
DEMO: http://jsfiddle.net/pv6081cz/


text:
Q: Implementing EFFICIENTLY a riak pre-commit hook that does get and put I implemented a pre-commit hook for riak which gets and updates a specific "meta" key whenever commits satisfy a specific criteria. I have noticed however, that doing Client:get to retrieve the "meta" key takes long, and seriously slows down my commits (about 20 times slower). Are there any advices on how to do this correctly? I currently call riak:local_client in the commit hook and then do riak_client:get.

A: Using the riakc_client in a pre-commit hook will be slow even if you reuse the client.
If you are updating the user metadata on the record being committed, you should be able to just modify the object passed into the pre-commit hook and not have to use riakc_client at all.
If you however update other "meta" records based on the record being commited, it may make sense to instead perform this update in a post-commit hook instead as this should reduce you latency.


text:
Q: Integrate $\int \sqrt{a + x^3}dx$ How does one go about integrating:
$$\int\sqrt{a + x^3}dx$$
Wolframalpha seems to be giving a result that seems slightly too elaborate.

A: why not use u-substitution?  u = a+x^3 then du=3x^2 dx.  Should be a good start.


text:
Q: Override create method to Restrict user from creating a new record based on condition Odoo13 I want to restrict the user from creating a new record on a model based on a specific condition. for instance, I have two fields in the model both of them is Integer (move_item_count,item_number ) and they are computed field I compute their values. If their move_item_count != item_number  I should prevent the user from creating the record and raise an error message. here is my code it gives me this error 'NoneType' object has no attribute 'id'.

here is my code :
 # Overriding the Create Method in Odoo
@api.model
def create(self, vals):
    # overriding the create method to add the sequence and prevent the  user from
    # creating a new record if a condition didn't fulfilled
    for rec in self:
        if rec.move_item_count != rec.item_number:
            raise UserError(_("Some Item Are Missing."))
        if vals.get('name', _('New')) == _('New'):
            vals['name'] = self.env['ir.sequence'].next_by_code('move.sequence') or _('New')
        result = super(LogisticMove, self).create(vals)
        return result

A: Overriding the create is not recommended when applying a constraint on creation of a record as this can get really messy when 2 or more modules override the same create. You'd be better off using actual constraints (see doc right here for example).
If you feel like you must, then keep in mind that until the actual create (the super) has been called, the record is NOT in the database and also NOT present in self. All you have to go with are the values for creating this which are stored in your vals parameter.
If you inspect those values you can do the comparison and provide feedback to the user.


text:
Q: React Router, Getting location in nested child With the withRouter HOC mentioned in
https://github.com/ReactTraining/react-router/blob/master/upgrade-guides/v2.4.0.md, is there a way to get location info?
Or do we still need to use our own context provider and hoc to access it?

A: location is one of the props that withRouter injects into your component.
const withRouter(({ location }) => (

You are here: {location.pathname}

))


text:
Q: Using xargs to run multiple commands Using this post as a starting point I am running the following in bash:
seq 1 5 | xargs -d $'\n' sh -c 'for arg do echo $arg; done'

Expected output
1
2
3
4
5

Actual output
2
3
4
5

i.e. is missing the first of the intended arguments.
Am probably being a tool, but wondering why this is.

A: You have to pass some dummy value at position 0 to sh script like this:
seq 1 5 | xargs -d $'\n' sh -c 'for arg do echo $arg; done' _
1
2
3
4
5

Without passing _ to sh script 1 is passed as $0 whereas for arg loops through positional arguments starting with position 1 only.

A: In conclusion, do you want to list number or execute command by row?
Usually, use below command in bash.
seq 1 5 | xargs -n 1 -I {} echo {}

Output
1
2
3
4
5

A: The problem lies with your inline bash code.
seq 1 5 | xargs -n echo produces the desired result. It can also be simplified to seq 5 | xargs -n echo because seq assumes the range starts at 1.