text:
Q: In django 1.11, how to allow users to login on a read-only database? I have 2 instances each running its own postgres database.
One is for production usage. The other is a read-only database that performs replication from the production database.
Both instances run the same django 1.11 application codebase.
When I attempt to login to the django read-only version, I cannot login because the very action of login apparently execute some update or insert statements.
I get an internal error about read-only database: cannot execute INSERT in a read-only transaction
What are my options if I want to allow users to access the read-only database using the same codebase?
UPDATE
I have already tried django-postgres-readonly. Same results.

A: On the codebase that's talking to the read-only database
Step 1: install django-no-last-login v0.1.0
Step 2: inside settings.py add/change the following
SESSION_ENGINE = 'django.contrib.sessions.backends.file'

INSTALLED_APPS += [
    'nolastlogin',
]
NO_UPDATE_LAST_LOGIN = True

By default Django uses database for session engine, so switch to something else.
Also the plugin makes it easy to turn off the update last login behavior by Django.
Django auto updates the last login time. Since we want zero database writes, so we need to use that.

A: Django need to update tables like django_session.
My advice is to use 2 different databases for the "django-tables" and your "read-only-tables"
How?
Create a simple and empty sqlite3 database and use the class AuthRouter
for managed them.
For your database settings use something like:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
    'otherdb': {
        'NAME': 'user_data',
        'ENGINE': 'django.db.backends.postgresql',
        'USER': 'ypurusername',
        'PASSWORD': 'yourpassword',
        'HOST': '0.0.0.0'
    }
}

Example of AuthRouter:
class AuthRouter:
"""
A router to control all database operations on models in the
auth application.
"""
def db_for_read(self, model, **hints):
    """
    Attempts to read auth models go to auth_db.
    """
    if model._meta.db_table == 'django-table':
        return 'defaul'
    return otherdb

def db_for_write(self, model, **hints):
    """
    Attempts to write auth models go to auth_db.
    """
    if model._meta.app_label == 'auth':
        return 'auth_db'
    return None

def allow_migrate(self, db, app_label, model_name=None, **hints):
    """
    Make sure the auth app only appears in the 'auth_db'
    database.
    """
    if app_label == 'migrations':
        return db == 'default'
    return otherdb

Here the link to the docs


text:
Q: Strange temporary network outage in Linux I'm facing a very annoying problem that I noticed a week from now and for which I can't find an answer: my network suddenly stops responding, usually coming back exactly 25 seconds later. I was using kernel 3.10.4 and now migrated to 3.11-rc4 to see if something changed, but no, the behavior is the same. And since it is a hard to spot problem due to the fact usual web surfing is in "bursts" and the outage is completely random, I can't really tell this problem was present in a previous kernel as well (I always use custom but unpatched kernels from kernel.org, all compiled by myself)
I can't tell the kernel is the culprit either, but I can say there are no clues on the system logs (I checked both /var/log/syslog and /var/log/messages and there is nothing unusual there) and that hardware doesn't seem at fault, for the problem shows up using either one of my network cards:
lspci output:
02:00.0 Ethernet controller: Broadcom Corporation NetXtreme BCM5751 Gigabit Ethernet PCI Express (rev 01)
04:00.0 Ethernet controller: 3Com Corporation 3c905B 100BaseTX [Cyclone] (rev 30)

and I already tried to exchange the ethernet switch ports and still no one else where I work has a problem except me (although we use similar machines, I'm the only one using Linux, so I had to take some infamous jokes about it as well... hehe).
I ran up wireshark on my machine and left it continuously pinging our gateway and another machine on the same network segment. Then, at the first sign of network malfunction I would check it and verify the gateway stopped responding pings, but the other machine was still there responding normally. Some other times is the other machine which stops responding and the gateway is fine, and some other times both stop responding. I don't know what else to do, so I'd like some help or tips on how to further debug this, since the system logs are completely normal.
I have my kernel config file and a capture file from wireshark showing the situation. I can post here or at some pastebin site in case anyone finds it useful to understand the case, just please let me know the detail level I should use (I guess the packet level without the raw data would be enough).

A: The symptoms are consistent with an IP address conflict. An IP address conflict arises when your machine and some other machine on the same network are trying to use the same IP address.
On a local link network, addressing is based on MAC addresses. Every Ethernet card has its own MAC address (barring gross misconfiguration or malice). A router deciding where to send an IP packet will send an ARP request for the target IP address on all its ports. That message is sometimes known as "who has": the router is trying to find out which of its peers is responsible for this IP address. Once the router receives a reply containing a MAC address, it can build and send an Ethernet frame (Ethernet packet) containing the IP packet to that MAC address. Since this exchange takes a while, the router keeps a cache of recent ARP information. (There are other types of ARP messages, but what I've explained here is sufficient to understand the present issue.)
So in a nutshell, routers need to know what physical device have each IP address that they're sending IP packets to. So what happens when there are two devices claiming the same IP address? The router receives a reply from one of the devices, and from then on it decides that this IP address belongs to that device, until the corresponding cache entry expires. After the cache entry expires, the router will send a new ARP request, and maybe the other device will reply faster this time. This explains why such situations are unstable: one minute the router is talking to you, the next minute it's talking to the other guy.
If you continuously ping someone, then the router keeps your IP address in its ARP cache pretty much all the time. So while you're pinging, there's only a small window during which the other guy can replace you in the cache (after your cache entry expires, before the next ping comes). That's why observing the problem makes it mostly go away, which can be frustrating until you realize what the problem might be.
In your case, it looks like your local router keeps entries in its cache for 25 seconds. When you're in the cache, you're good for 25 seconds. Then sometimes the other guy comes, at random-looking moments, and you're out of it for 25 seconds.
When you try to contact multiple machines on the same local link, each has its own ARP table, so you may observe inconsistent results, with one machine deciding that you own the IP address and another machine deciding that the other guy does.
High-end routers log IP address conflicts, so if you think you're encountering one, enlist the help of your system administrator. Make sure first that it isn't your machine that's trying to use an IP address that it shouldn't be using!

A: I'm going to suggest that you've got 2 "nameserver" entries in /etc/resolv.conf, and the first entry refers to a DNS server that is down or unreachable or soemthing periodically.  The resolver code in libc will try the first nameserver IP address, get a timeout and then try the second nameserver IP address, which succeeds.
To test this, you could replace the "nameserver" IP addresses in /etc/resolv.conf with just one, 8.8.8.8, which is Google's public DNS server. If the outage doesn't occur, your nameserver is the problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to print certain row from specific file name that multiple appears under subdirectories I got following file system
dir1/subDir1/index.html
dir1/subDir2/index.html
dir1/subDir3/index.html

index.hml contains tag [some text]
I want to print the tag row from all index.html instances
Something like this:
dir1/subDir1/index.html -> <name>[some text]</name>
dir1/subDir2/index.html -> <name>[some text]</name>
dir1/subDir3/index.html -> <name>[some text]</name>

Currently I use
cat */index.html |grep "name"
But I am getting only the tag list without subdirectories referral
Thanks

A: If you don't give grep filenames he is not going to print them. So give it.
grep "name" */index.html


text:
Q: Unable to get an event interrupter for preventing form submission to work corrctly in a basic JavaScript and PHP tutorial I am trying to learn JavaScript, PHP and some basic client-side form validations in trying to build this basic JavaScript tutorial that interacts with PHP and HTML. WHat I am trying to do is interrupt a form submission event, i.e. user forgets to enter a valid email format in the email submission input and clicks on the submit button which should then display an error message and not allow the form to be submitted. But I can't get this to work for me. What happens is that I am instead taken to the support_process.php page when that should not happen. Any help at all would be greatly appreciated.
Here is my index.html code for the form:

  <form id="frmSupport" name="frmSupport"  method="post" action="support_process.php">
    <fieldset id="fastSupport">
      <legend>Fast Support</legend>

If you've already booked the Singing Rails Girls  coach,
 and have not gotten a confirmation number,
 drop us a line and we'll respond within 24 hours.

        Email:
            <input type="text" value="your email" name="name" id="email" tabindex="10" />

            <input type="submit" value="Submit">

Ed's "Blah Blah Blah" Tour Status

            <input type="radio" name="tour status" value="booked" id="tourStatus_0" tabindex="40" />Ed already toured here

            <input type="radio" name="tour conf" value="paid" id= "tourStatus_1" tabindex="50" />Ed confirmed his tour date

    </fieldset>
  </form>

Comments Section

            Comments:

And here is my corresponding JavaScript file:
//alert("Hello, world!"); // this is a JavaScript alert button //
var year = 2014;
var userEmail = "";
var todaysDate = "";
/*var donation = 20;

if (donation < 20) {
alert("For a $20 you get a cookie. Change your donation?");
}
else {
alert("Thank you!");
} */

var mainfile = document.getElementById("mainTitle");
console.log("This is an element of type: ", mainTitle.nodeType);
console.log("The inner HTML is ", mainTitle.innerHTML);
console.log("Child nodes: ", mainTitle.childNodes.length);

var myLinks = document.getElementsByTagName("a");
console.log("Links: ", myLinks.length);

var myListElements = document.getElementsByTagName("li");
console.log("List elements: ", myListElements.length);

var myFirstList = document.getElementById("2 paragraphs");
/* you can also use: var limitedList = myFirstList.getElementsByTagName("li");
to dig deeper into the DOM */
var myElement = document.createElement("li");
var myNewElement = document.createElement("li");
//myNewElement.appendChild(myNewElement);

var myText = document.createTextNode("New list item");
myNewElement.appendChild(myText);

// creating elements
var newListItem = document.createElement("li");
var newPara = document.createElement("p");

// To add content, either use inner HTML
// or create child nodes manually like so:
// newPara.innerHTML = "blah blah blah...";
var paraText = document.createTextNode("And now for a beginner level intro...");
newPara.appendChild(paraText);

//And we still need to attach them to the document
document.getElementById("basic").appendChild(newPara);

var myNewElement = document.createElement("li");
var secondItem = myElement.getElementsByTagName("li")[1];
myElement.insertBefore(myNewElement, secondItem);

// An example of using an anonymous function: onclick.
//When you click anywhere on the page, an alert appears.
//document.onclick = function() {
//  alert("You clicked somewhere in the document");
//}

// And example of restricting the click alert to
// an element on the page.
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
alert("You clicked on the picture!");
}

function prepareEventHandlers() {
var myImage = document.getElementById("mainImage");
myImage.onclick = function() {
  alert("You clicked on the picture!");
}
//onfocus and onblur event handler illustration
var emailField = document.getElementById("email");
emailField.onfocus = function() {
if (emailField.value == "your email") {
    emailField.value = "";
}
};

emailField.onblur = function() {
if (emailField.value == "") {
    emailField.value = "your email";
}
};
// Handling the form submit event
document.getElementById("frmSupport").onsubmit = function(){
    //prevent a form from sumbitting if no email.
    if (document.getElementById("email").value == "") {
        document.getElementById(errorMsg).innerHTML = "OOPS!";
        //to stop the form from submitting:
        return false;
    }else {
        //reset and allow form submission:
        document.getElementById("errorMsg").innerHTML = "";
        return true;
    }
};
}

window.onload = function() {
// preps everything and ensures
// other js functions don't get
// called before document has
// completely loaded.
prepareEventHandlers();
// This is a named function call nested inside an anonymous function.
}

//Sometimes we want js to run later or call a
// function in 60 seconds or every 5 sec, etc.
// Two main methods for timers: setTimeout and setInterval
// these timer functions are in milliseconds

var myImage = document.getElementById("mainImage");
var imageArray = ["images/Blue-roses.jpg", "images/Purple-Rose.jpg", "images/White- Rose.jpg", "images/orange-rose.jpg", "images/pink-roses.jpg", "images/red-roses.jpg", "images/yellow-roses.jpg", "images/murdock.jpg", "images/dorothy-red-ruby-slippers.jpg"];
var imageIndex = 0;

function changeImage(){
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
    imageIndex = 0;
}
}
var intervalHandle = setInterval(changeImage, 5000);
myImage.onclick = function() {
clearInterval(intervalHandle);
}

//Sometimes we may want some random alert
// to pop up x-number of seconds later.
//So we use the setTimeout, like so:
/*function simpleMessage() {
alert("Get ready to learn!");
}
setTimeout(simpleMessage, 5000); */

/*var_dump($_POST);
if var_dump($_POST) = "";
return var($_GET);
error_log($_POST); */

And here is my corresponding php file for the event interrupter (for refusing to allow the form to be submitted if user leaves email field blank or something):
<?php
//some php script can go here
echo "This is the support confirmation page...sorry, nothing fancy here!"
?>

Thank you, we will contact you shortly!

Back

<?php
// More php code can go here, and so forth and so on..
/*var_dump($_POST);
  if var_dump($_POST) = "";
  return var($_GET);

error_log($_GET); */
error_log(message);

?>

A: Here's a problem:
if (document.getElementById("email").value == "") {
    document.getElementById(errorMsg).innerHTML = "OOPS!";
    //to stop the form from submitting:
    return false;
}else {
    //reset and allow form submission:
    document.getElementById("errorMsg").innerHTML = "";
    return true;
}

In the first part of the if, you're trying to get a reference to the errorMsg element using a non-existent variable:
    document.getElementById(errorMsg).innerHTML = "OOPS!";

In the second, you're accessing the element by its id properly:
    document.getElementById("errorMsg").innerHTML = "";

You need to surround 'errorMsg' with single or double quotes.
You should definitely look into using a debugger to help you find problems like these. Chrome Developer Tools are a good place to start.


text:
Q: Suppress layout animation on one child view I'm setting layout animation to list view (my items are dropping down). In list view I have a header that I don't what to animate.
How can I suppress animation on my header?

A: If it is a static view present at all times, have you considered using a separate view not part of the list view for your header?

A: I managed to solve this with the help of this Google Group discussion.
https://groups.google.com/forum/?fromgroups#!topic/android-developers/F7_zE_k9KO8
I end up creating a custom view and overriding getAnimation() witch returned null.
public class HeaderSearchNoAnimationVIew extends LinearLayout {
public HeaderSearchNoAnimationVIew(Context context) {
    super(context);
    LayoutInflater i = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    i.inflate(R.layout.list_header_search, this);
}
@Override
public Animation getAnimation() {
    return null;
}
}


text:
Q: AKTableView issue 100% CPU usage I'm trying to assign a table view to an already existing UIView object on my storyboard but every time I assign it by specifying the correct frame I get an issue.
let sampleTable = AKTableView(AKTable(file: sampleReferences[indexPath.row].sampleFile!), frame: samplePlot.bounds)
        samplePlot.addSubview(sampleTable)

This is the code I'm using at the moment. I've also used samplePlot.frame.
Basically the sampleReferences[indexPath.row].sampleFile! is an AKAudioFile stored earlier from a recording stored as a reference from a UITableView element. It's quite a large program split into multiple files so it's hard to show everything.
The only extra issue I can think of is I haven't stopped any of the current AudioKit processes. I'm not sure if the table can only be drawn at startup.
The following works with a .sine specifier AKTable(.sine) so it's not an issue with my UI code. It also fails when trying to load even a basic .mp3 file from .resources.
Update:
I've compressed the test .mp3 file significatly and shortened it's overall length to 2 seconds and I'm still getting the same issue. I think it might be an issue with the actual function used to draw the file. Although I could be wrong.
Another update:
So everything works fine using the following code
let file = EZAudioFile(url: sampleAudio!.url)
        guard let data = file?.getWaveformData() else {
            print("Failed to get waveform data")
            return }

        let waveform = EZAudioPlot()
        waveform.frame = samplePlot.bounds
        waveform.plotType = EZPlotType.buffer
        waveform.shouldFill = true
        waveform.shouldMirror = true
        waveform.color = UIColor.black
        waveform.updateBuffer(data.buffers[0], withBufferSize: data.bufferSize )
        samplePlot.addSubview(waveform)

but obviously I'm using EZAudioPlot. I grabbed this from a previous stack overflow issue for the same thing and edited it a bit.


text:
Q: JasperReports runtime exception - SAXParseException Good day! I am working with Jasper Reports 6.2, JSF 2.2, NetBeans 8.1 and WildFly 8.2, and after one build an exception appeared:

SAXParseException; lineNumber: 1; columnNumber: 27; The reference to entity "SOFT" must end with the ';' delimiter.

It is very strange, because I think there is no errors in XML file. The first line that was mentioned, looks like this:
<?xml version="1.0" encoding="UTF-8"?>

Since there is no solution currently on the net, I hope that someone who has faced similar problem, will help. Best Regards!

A: Is it possible that you have some direct URL or HTML characters provided unescaped in the report? You provided only the first line but I suspect something to be wrong within the source code.
For example, if you call somewhere
/my/url?param1=2&param2=4

this will confuse the SAX parser. So this should become
/my/url?param1=2&param2=4


text:
Q: How do I recursively copy a directory using vala? I'm new to Vala, so this may be a stupid question.
According to #vala on gimpnet, it is not possible to recursively copy directories using Glib.File.copy. At the moment I am using:
Posix.system("cp -r absolutesource absolutedestination")

Is there a better method of doing this?

A: As I told you in IRC, you can just write a function to do it yourself by calling GLib.File.copy for each file you want to copy.  Here is a basic example:
public bool copy_recursive (GLib.File src, GLib.File dest, GLib.FileCopyFlags flags = GLib.FileCopyFlags.NONE, GLib.Cancellable? cancellable = null) throws GLib.Error {
  GLib.FileType src_type = src.query_file_type (GLib.FileQueryInfoFlags.NONE, cancellable);
  if ( src_type == GLib.FileType.DIRECTORY ) {
    dest.make_directory (cancellable);
    src.copy_attributes (dest, flags, cancellable);

    string src_path = src.get_path ();
    string dest_path = dest.get_path ();
    GLib.FileEnumerator enumerator = src.enumerate_children (GLib.FileAttribute.STANDARD_NAME, GLib.FileQueryInfoFlags.NONE, cancellable);
    for ( GLib.FileInfo? info = enumerator.next_file (cancellable) ; info != null ; info = enumerator.next_file (cancellable) ) {
      copy_recursive (
        GLib.File.new_for_path (GLib.Path.build_filename (src_path, info.get_name ())),
        GLib.File.new_for_path (GLib.Path.build_filename (dest_path, info.get_name ())),
        flags,
        cancellable);
    }
  } else if ( src_type == GLib.FileType.REGULAR ) {
    src.copy (dest, flags, cancellable);
  }

  return true;
}

Also, it's worth noting that you might want to use one of the functions in GLib.Process instead of Posix.system.

A: I came across this question looking for something similar in C using GLib/GIO.
Here's my attempt at converting the C++ code above to C
gboolean
copy_recursive(GFile *src, GFile *dest, GFileCopyFlags flags, GCancellable *cancellable, GError **error) {
    GFileType src_type = g_file_query_file_type(src, G_FILE_QUERY_INFO_NONE, cancellable);
    if (src_type == G_FILE_TYPE_DIRECTORY) {
        g_file_make_directory(dest, cancellable, error);
        g_file_copy_attributes(src, dest, flags, cancellable, error);

        GFileEnumerator *enumerator = g_file_enumerate_children(src, G_FILE_ATTRIBUTE_STANDARD_NAME, G_FILE_QUERY_INFO_NONE, cancellable, error);
        for (GFileInfo *info = g_file_enumerator_next_file(enumerator, cancellable, error); info != NULL; info = g_file_enumerator_next_file(enumerator, cancellable, error)) {
            const char *relative_path = g_file_info_get_name(info);
            copy_recursive(
                g_file_resolve_relative_path(src, relative_path),
                g_file_resolve_relative_path(dest, relative_path),
                flags, cancellable, error);
        }
    } else if (src_type == G_FILE_TYPE_REGULAR) {
        g_file_copy(src, dest, flags, cancellable, NULL, NULL, error);
    }

    return TRUE;
}

As a bonus, here's a function that recursively deletes a directory
gboolean
delete_recursive(GFile *file, GCancellable *cancellable, GError **error) {
    GFileType file_type = g_file_query_file_type(file, G_FILE_QUERY_INFO_NONE, cancellable);
    if (file_type == G_FILE_TYPE_DIRECTORY) {
        GFileEnumerator *enumerator = g_file_enumerate_children(file, G_FILE_ATTRIBUTE_STANDARD_NAME, G_FILE_QUERY_INFO_NONE, cancellable, error);
        for (GFileInfo *info = g_file_enumerator_next_file(enumerator, cancellable, error); info != NULL; info = g_file_enumerator_next_file(enumerator, cancellable, error)) {
            delete_recursive(
                g_file_resolve_relative_path(file, g_file_info_get_name(info)),
                cancellable, error);
        }
        g_file_delete(file, cancellable, error);
    } else if (file_type == G_FILE_TYPE_REGULAR) {
        g_file_delete(file, cancellable, error);
    }

    return TRUE;
}


text:
Q: NavigationPush not working in flutter as it should do Navigation Push is working for the first Row() but after the Divider() its not working on the second Row(). WITHOUT ANY ERRORS. I DID WRAP MY MAIN PAGE IN Material App. I did cut some of the unnecessary code cuz it was too long. Any help would be highly appreciated. thanks in advance. and by the this feature in StackOverflow sucks that i have to write the detail of my problem as long as my code it self
    return Container(
      height: 200,
      width: double.infinity,
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage("assets/b1.jpg"),
          fit: BoxFit.cover,
        ),
      ),
      child: Stack(
        fit: StackFit.expand,
        clipBehavior: Clip.none,
        children: [
          Positioned(
            top: 20,
            left: 20,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  "Buy. Sell. Exchange.",
                  style: TextStyle(
                    color: Colors.white,
                    fontFamily: "eng",
                    fontSize: 15,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 5),
                Container(
                  width: MediaQuery.of(context).size.width / 1.1,
                  height: 40,
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(
                      Radius.circular(2),
                    ),
                  ),
                  child: const Padding(
                    padding: EdgeInsets.only(left: 5),
                    child: TextField(
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: "Search",
                        icon: Icon(Icons.search, color: Colors.lightBlueAccent),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          ////////////////////////////////////////////////////////////////////// Cats
          Positioned(
            top: 130,
            left: 20,
            child: Container(
              height: 315,
              width: MediaQuery.of(context).size.width / 1.1,
              decoration: const BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey,
                    spreadRadius: 1,
                    blurRadius: 3,
                  )
                ],
                borderRadius: BorderRadius.all(Radius.circular(2)),
              ),
              child: Padding(
                padding: const EdgeInsets.all(5.0),
                child: Column(
                  children: [
                    Row(
                      children: [
                        ////////////////////////////////////////////                Houses
                        InkWell(
                          onTap: (() {
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => const HouseRent()));
                          }),
                          child: Container(
                            height: 145,
                            width: MediaQuery.of(context).size.width / 3 - 20,
                            decoration: const BoxDecoration(
                                color: Colors.white,
                                border: Border(
                                    right: BorderSide(
                                        color: Colors.grey, width: 0.2))),
                            child: Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Column(
                                children: const [
                                  Image(
                                    image: AssetImage("assets/house.png"),
                                    height: 50,
                                  ),
                                  SizedBox(height: 20),
                                  Text(
                                    "Houses",
                                    style: TextStyle(
                                      color: Colors.black,
                                      fontSize: 15,
                                      fontFamily: "eng",
                                      //fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                  Text(
                                    "خانه",
                                    style: TextStyle(
                                      color: Colors.black,
                                      fontSize: 17,
                                      fontFamily: "dari2",
                                      //  fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    const Divider(
                      color: Colors.grey,
                      thickness: 0.2,
                      indent: 10,
                      endIndent: 10,
                    ),
                    Row(
                      children: [
                        ////////////////////////////////////////////Mobiles
                        InkWell(
                          onTap: (() {
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => const Electronics()));
                          }),
                          child: Container(
                            height: 144,
                            width: MediaQuery.of(context).size.width / 3 - 20,
                            decoration: const BoxDecoration(
                                color: Colors.white,
                                border: Border(
                                    right: BorderSide(
                                        color: Colors.grey, width: 0.2))),
                            child: Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Column(
                                children: const [
                                  Image(
                                    image: AssetImage("assets/mobile.png"),
                                    height: 70,
                                  ),
                                  SizedBox(height: 1),
                                  Text(
                                    "Mobiles",
                                    style: TextStyle(
                                      color: Colors.black,
                                      fontSize: 15,
                                      fontFamily: "eng",
                                      //fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                  Text(
                                    "موبایل",
                                    style: TextStyle(
                                      color: Colors.black,
                                      fontSize: 17,
                                      fontFamily: "dari2",
                                      //  fontWeight: FontWeight.bold,
                                    ),), ],), ), ), ),),), ],),],),), ),)],),);}}```

A: I solved it by extending the parent Container of Stack to cover all its children.


text:
Q: How to do a synchronous call with jaydata I'm a bit confused about the asynchous call to the DataBase.
I just want to have a javasctipt adapter class for the calls to the web sql. But I'm not quite sure how to do this. Propably somebody have a good hint for me.
The function OfflneAppDBAdapter.prototype.IsDeviceConfigured() should return true or false depending if there are any items in the Table DeviceConfig.
function OfflneAppDBAdapter() {
self = this;
this.deviceIsConfigured = false;

this.Init = function () {

    $data.Entity.extend("$de.offlineapp.DeviceConfig", {
        Id: { type: "int", key: true, computed: true },
        Name: { type: "string", required: true },
        Token: { type: "string" },
        Type: { type: "string" }
    });

    $data.EntityContext.extend("$de.offlineapp.DataContext", {
        DeviceConfig: { type: $data.EntitySet, elementType: $de.offlineapp.DeviceConfig }
    });

}
self.Init();

$de.offlineapp.context = new $de.offlineapp.DataContext({
    name: "webSql", databaseName: "OfflineApp"
});

$de.offlineapp.context.onReady(function () {

});

}

// ************************************************************************
// PUBLIC METHODS -- ANYONE MAY READ/WRITE
// ************************************************************************
OfflneAppDBAdapter.prototype.AddDeviceConfig = function (deviceName, deviceToken, deviceTyp) {
$de.offlineapp.context.onReady(function () {
    var promise = $de.offlineapp.context.DeviceConfig.toArray(function (x) {
        if (x.length == 0) {
            var emp = new $de.offlineapp.DeviceConfig({ Name: deviceName, Token: deviceToken, Type: deviceTyp });
            $de.offlineapp.context.DeviceConfig.add(emp);
            $de.offlineapp.context.saveChanges();
        }
    }
)
});

}

OfflneAppDBAdapter.prototype.IsDeviceConfigured = function () {

$de.offlineapp.context.onReady(function () {
    var promise = $de.offlineapp.context.DeviceConfig.toArray(function (x) {
        if (x.length == 0) {
            this.deviceIsConfigured = true;
        }
    }
)
});

return this.deviceIsConfigured;
}

var myOfflineAppDBAdapter = new OfflneAppDBAdapter();
myOfflineAppDBAdapter.AddDeviceConfig("DeviceName", "Token", "iPad");
console.log(myOfflineAppDBAdapter.IsDeviceConfigured());

As expected the console prints "false". I' aware that the jaydata call works with callbacks and the callbacks are not part of the main class. But there must be a possibility to do so?
I would really apprechiate any help.
Thank you in advance....
Chris
UPDATE:
As you requested the startup code:
function OfflineApplication()
    {
        self = this;
    }

    OfflineApplication.prototype.StartApplication = function () {

        //Check if online, then sync and
        if (navigator && navigator.onLine === true) {
            this.IsDeviceConfigured();
        }
        else {

        }

    }

    ///check if the device has a base configuration
    OfflineApplication.prototype.IsDeviceConfigured = function () {

        myOfflineAppDBAdapter.GetDeviceConfiguration(function (result) {
            if (result.length > 0) {
                myOfflineAppDBAdapter.deviceIsConfigured = true;
                myOfflineApplication.HasDeviceAnApplication();
            }
            else {
                ///Get the device base conf from the server.
                myOfflineAppSynchronisationAdapter.getDeviceConfigurationByToken(token, myOfflineApplication.HasDeviceAnApplication);
                myOfflineAppDBAdapter.deviceIsConfigured = true;
            }
        });
    }
    ///check if the device has an "application config" in general
    OfflineApplication.prototype.HasDeviceAnApplication = function () {
        myOfflineAppDBAdapter.GetDeviceAnApplication(function (result) {
            if (result.length > 0) {
                myOfflineApplication.IsDeviceApplicationVersionLatest(result);
            }
            else {
                myOfflineApplication.GetApplication(false);
            }
        });
    }

    ///the application config could differ from time to time, so we have to check if a different application should be synct with the device
    OfflineApplication.prototype.IsDeviceApplicationVersionLatest = function (result) {

        myOfflineAppDBAdapter.DeleteDeviceAnApplication(function () {  });
        console.log(result);
    }

    ///get the application from the server
    OfflineApplication.prototype.GetApplication = function (clearConfig) {
        if (clearConfig === true)
        {

        }

        myOfflineAppSynchronisationAdapter.getDeviceApplicationByToken(token, myOfflineApplication.LoadApplication);

    }

    OfflineApplication.prototype.LoadApplication = function () {
        console.log('Now everything is finde and the application gets loaded..');
    }

    var myOfflineAppDBAdapter = new OfflneAppDBAdapter();
    var myOfflineAppSynchronisationAdapter = new OfflineAppSynchronisationAdapter();
    var myOfflineApplication = new OfflineApplication();

    myOfflineApplication.StartApplication();

A: There is no sync way. You handling promises wrong. Make your code simple :) You'll need something like this:
$data.Entity.extend("$de.offlineapp.DeviceConfig", {
    Id: { type: "int", key: true, computed: true },
    Name: { type: "string", required: true },
    Token: { type: "string" },
    Type: { type: "string" }
});

$data.EntityContext.extend("$de.offlineapp.DataContext", {
    DeviceConfig: { type: $data.EntitySet, elementType: $de.offlineapp.DeviceConfig }
});

var context = new $de.offlineapp.DataContext({
    name: "webSql", databaseName: "OfflineApp"
});

function AddDeviceConfig(deviceName, deviceToken, deviceTyp) {
    return context.DeviceConfig.toArray()
    .then(function (x) {
        if (x.length == 0) {
            var emp = new $de.offlineapp.DeviceConfig({ Name: deviceName, Token: deviceToken, Type: deviceTyp });
            context.DeviceConfig.add(emp);
            return context.saveChanges();
        }
    })
}

function IsDeviceConfigured() {
    return context.DeviceConfig.toArray()
    .then(function (x) {
        return x.length > 0;
    })
}

context.onReady()
.then(IsDeviceConfigured)
.then(console.log)
.then(function() { return AddDeviceConfig("DeviceName", "Token", "iPad"); })
.then(IsDeviceConfigured)
.then(console.log);

here's a fiddle which does this: http://jsfiddle.net/JayData/cpT5q/1/


text:
Q: Join JSON Objects as one I have multiple JSON objects and I want to combine them into one bigger JSON Object and then only pass this JSON object to a server. How would I go about doing this? Also, how would I then extract those objects from the server side using C#?
This is what I have right now.
    var newBillerJSON = this.ConvertListToJSON(newBillerResults);
    var benchJSON = this.ConvertListToJSON(benchResults);
    var sixtyDayJSON = this.ConvertListToJSON(sixtyDayResults);
    var unassignedJSON = this.ConvertListToJSON(unassignedResults);
    var totalSummaryJSON = this.ConvertListToJSON(countResults);

Each of these contains the individual JSON Object, created from this.ConvertListToJSON()
Can I combine these into one JSON object? When the server reads this object, how would I then extract those JSON objects from it?
This is an example of what one JSON object looks like
{
  "TotalSummaryCounts": [
    {
      "BenchHours": "1316",
      "EffectiveBench": "29",
      "Contributors": "37",
      "FourtyHourContributors": "14",
      "AvailableBench": "26",
      "EffectiveBillers": "79.533333"
    }
  ]
}


text:
Q: Partial derivative with Dirac Delta as initial condition I am trying to reproduce the Faynman-Kac results from this Wikipedia page:
Faynman-Kac
This is the equation that I am trying to solve:
$$
\frac{\partial w(t,x)}{\partial t} = \frac{1}{2} \frac{\partial^2 w(t,x)}{\partial x^2} - uV(x)w(t,x)
$$
With initial condition $ w(0,x)= \delta(x) $.
As an example lets set
$$ uV(x) = ux^2   $$
I tried two different methods. I knew there was no way the first method was not going to work - but I believe in magic. Perhaps, someone knows some trick to propagate the initial condition.
Method 1 - NDSolve
w[u_] = (-u*x^2*f[t, x] + 0.5*D[f[t, x], x, x]);

wsol[u_] := NDSolve[{
     D[f[t, x], t] == w[u],
     f[0, x] == DiracDelta[x],
     f[t, -50] == Exp[-1000 t],
     f[t, 50] == Exp[-1000 t]},
    f, {t, 0, 100}, {x, -50, 50}, MaxStepSize -> 0.5,
    AccuracyGoal -> 8, PrecisionGoal -> 8,
    Method -> {"MethodOfLines",
      "SpatialDiscretization" -> {"TensorProductGrid",
        "MinPoints" -> 1000}}];

Method 2 - Fourier Transforms
    FourierTransform[1/2*D[f[t, x], x, x], x, w]

(* -(1/2) w^2 FourierTransform[f[t, x], x, w] *)

FourierTransform[-u*x^2, x, w]

(* Sqrt[2 π] u (DiracDelta^′′)[w] *)

FourierTransform[DiracDelta[x], x, w]

(* 1/Sqrt[2 π] *)

DSolve[{D[f[t], t] ==
       f[t]*(Sqrt[2 π] u (DiracDelta^′′)[w] - 1/2 w^2 ),
       f[0] == 1/Sqrt[2 π]}, f[t], t]

(* {{f[t] -> E^(
       1/2 t (-w^2 + 2 Sqrt[2 π] u (DiracDelta^′′)[w]))/
       Sqrt[2 π]}} *)

So, at this point - I get a solution but I wish I could get the inverse.
InverseFourierTransform[E^(
 1/2 t (-w^2 +
    2 Sqrt[2 π] u (DiracDelta^′′)[w]))/Sqrt[
 2 π], w, x]
(* InverseFourierTransform[E^(
 1/2 t (-w^2 +
    2 Sqrt[2 π] u (DiracDelta^′′)[w]))/Sqrt[
 2 π], w, x] *)

I think its the transform of $ x^2 $ that Mathematica does not know how to inverse.
Now, I also tried substituting the Delta function with the derivative of the HeavisideTheta[] but that still does not work.
Can someone help please? The Faynman-Kac is a very important theorem.
Update!
Based on the comment of xzczd - I was able to get some results. However, I can't get rid of the errors when I plot. Can I get some help with the plot errors please.
Numerical method - This is with a Triangular Distribution Probability Density but I get the same errors with xzczd's function. I followed Mathematica's suggestion but they do not get resolved.
w3[u_] = (-u*x^2*f[t, x] + 0.5*D[f[t, x], x, x]);

wsol3[u_] := NDSolve[{
    D[f[t, x], t] == w3[u],
    f[0, x] ==
     Evaluate[PDF[TriangularDistribution[{-0.001, 0.001}, 0.0], x]],
    f[t, -50] == 0,
    f[t, 50] == 0},
   f, {t, 0, 100}, {x, -50, 50},
   Method -> {"MethodOfLines",
     "SpatialDiscretization" -> {"TensorProductGrid"}}];

Manipulate[
 Plot3D[Evaluate[f[t, x] /. wsol3[u]], {t, 0, 10}, {x, -5, 5},
  PlotRange -> {0, 10}], {u, 0.01, 1}]

A: This problem looks interesting enough to do both analytically and numerically.  Start with the analytical solution using V[x] = x^2
pde = (1/2)*D[w[x, t], x, x] - D[w[x, t], t] - u*x^2*w[x, t] == 0

Separate variables
w[x_, t_] = X[x] T[t]

pde/w[x, t] // Expand
(*-T'[t]/T[t]-u x^2 + X''[x]/(2 X[x]) == 0*)

% + T'[t]/T[t]

Each side must be equal to a constant.  We will use a negative constant necessary to satisfy the bc's.
Solve the x equation
xeq = X''[x]/(2 X[x]) - u x^2 == -α^2

DSolve[xeq, X[x], x] // Flatten

X1 = X[x] /. % /. {C[1] -> c1, C[2] -> c2}
(*c1 ParabolicCylinderD[(Sqrt[2] α^2 - Sqrt[u])/(2 Sqrt[u]),
   2^(3/4) u^(1/4) x] +
 c2 ParabolicCylinderD[(-Sqrt[2] α^2 - Sqrt[u])/(2 Sqrt[u]),
   I 2^(3/4) u^(1/4) x]*)

teq = T'[t]/T[t] == -α^2

DSolve[teq, T[t], t] // Flatten

T1 = T[t] /. % /. C[1] -> 1
(*E^(α^2 (-t))*)

Now we have a first pass at w
w[x_, t_] = X1 T1

First off, go for real solutions by getting rid of c2.
c2 = 0

Which leaves us with:
w[x, t]
c1 E^(α^2 (-t)) ParabolicCylinderD[(Sqrt[2] α^2 - Sqrt[u])/(2 Sqrt[u]),2^(3/4) u^(1/4) x]

The problem doesn't really state bc's, but I assume we want the solution bounded at x = +-infinity which requires the first argument of the ParabolicCylinderD to be an integer, and that will set α
α = α /. Solve[(Sqrt[2] α^2 - Sqrt[u])/(2 Sqrt[u]) == n, α][[2]]
(*(Sqrt[2 n + 1] u^(1/4))/2^(1/4)*)

$Assumptions = n ∈ Integers

Now w is
w[x_, t_] = c1 E^(-α^2 t) ParabolicCylinderD[n, 2^(3/4) u^(1/4) x]

We will have an infinite sum as n goes from 0 to ∞.  This solutions solves the end point bc's, so
now we just need to solve c1 from the initial condition.
w[x, 0] == DiracDelta[x]
c1 ParabolicCylinderD[n, 2^(3/4) u^(1/4) x] == DiracDelta[x]

Use orthogonality to solve for c1.
c1*Integrate[ParabolicCylinderD[n, 2^(3/4)*u^(1/4)*x]^2, {x, -Infinity, Infinity}] ==
  Integrate[DiracDelta[x]*ParabolicCylinderD[n, 2^(3/4)*u^(1/4)*x], {x, -Infinity, Infinity}]

MMa cannot do the first integral for general n, but we can infer it from:
Table[Integrate[ParabolicCylinderD[n, 2^(3/4)*u^(1/4)*x]^2, {x, -Infinity, Infinity}], {n, 0, 5}]
(*{Sqrt[π]/2^(1/4), Sqrt[π]/2^(1/4), 2^(3/4) Sqrt[π],
 3 2^(3/4) Sqrt[π], 12 2^(3/4) Sqrt[π],
 60 2^(3/4) Sqrt[π]}*)

(c1*n!*Sqrt[Pi])/(2^(1/4)*u^(1/4)) == Integrate[DiracDelta[x]*ParabolicCylinderD[n, 2^(3/4)*u^(1/4)*x],
   {x, -Infinity, Infinity}]

c1 = c1 /. Solve[%, c1][[1]]

w[x, t] will be an infinite sum from n = 0 to ∞, but for computing and plotting use a finite sum.  Use wan for the analytic solution.
wan[x_, t_, mm_] := (2*u)^(1/4)*Sum[(2^(n/2)*ParabolicCylinderD[n, 2^(3/4)*u^(1/4)*x])/(E^(((2*n + 1)*t*Sqrt[u])/Sqrt[2])*(n!*Gamma[1/2 - n/2])), {n, 0, mm}]

Clear[w]
The numeric solution.  We obviously cannot use the actual DiracDelta for the numeric solution, but we can use an approximation that has nearly the same inpulse effect.  Try
f[x_] = aa E^(-10000 x^2)

Choose aa so that like the DiracDelta, the area under the curve is 1.
Integrate[f[x], {x, -Infinity, Infinity}] == 1;

aa = aa /. Solve[%, aa][[1]]
(*100/Sqrt[π]*)

The numeric solution.  A little quicker than the analytic one.  First we need to set u
u = 1

sol = NDSolve[{pde, w[x, 0] == f[x], w[100, t] == 0, w[-100, t] == 0},
    w[x, t], {x, -100, 100}, {t, 0, 10},
   MaxSteps -> {50000, Automatic}] // Flatten

wnum[x_, t_] = w[x, t] /. sol

We are setting x = +-100 for the boundaries instead of inf.  The solution damps out much sooner than those values anyway.
Comparison plots of analytic and numerical solutions
Plot[{wnum[x, .01], wan[x, .01, 200]}, {x, -2, 2}, PlotRange -> All]

Plot[{wnum[x, .1], wan[x, .1, 50]}, {x, -2, 2}, PlotRange -> All]

Both are reasonable matches for times away from 0.  For smaller times the analytic solution converges very slowly and takes numerous terms.  The more terms used, the higher the peak at x = 0, t = 0 but eventually with many more terms computational instability occurs.  The exponential term promotes quick convergence with a higher time. Animating the numerical solution:
tb = Table[ Plot[Evaluate[wnum[x, t]], {x, -5, 5}, PlotRange -> {0, 1.5}], {t, 0, 6, .1}];
ListAnimate[tb]

As requested a 3D plot
Plot3D[wnum[x, t], {x, -5, 5}, {t, 0, 5}, PlotRange -> {0, 1},
 AxesLabel -> Automatic]


text:
Q: Extract subsidence data from MODFLOW-2000 binary output using FloPy I am using MODFLOW-2000 to run a land subsidence model. However, the output of the subsidence file is in binary data. Is there any way to use the python script to convert it into text since I am doing hundreds of scenarios for the model.

A: Binary output from the SUB package has the same format as MODFLOW binary head files. You need to know the name of the output text string written to the binary file. See Table 1 in the MODFLOW-2005 online documentation for the SUB package to determine the text string for a given SUB package binary file.
The following shows how to convert Z DISPLACEMENT data in a binary subsidence file to an ascii file using flopy and numpy:
import numpy as np
import flopy

# open the binary file
sobj = flopy.utils.HeadFile('model.zdisplacement.bin',
                            text='Z DISPLACEMENT')

# get all of the available times in the file
times = sobj.get_times()

# extract the data for the last time in the file
zd = sobj.get_data(totim=times[-1])

# save the z-displacement for the first layer (layer 0) to an ascii file
# zd is a 3D numpy array with a shape of (nlay, nrow, ncol)
np.savetxt('layer0.zdisplacement.txt', zd[0])

If you have more than one layer you will need to save the data for each layer.
You could output all of the data in the file using:
for t in sobj.get_times():
    zd = sobj.get_data(totim=t)
    for k in range(nlay):
        fpth = 'layer{}_{}.zdisplacement.txt'.format(k, t)
        np.savetxt(fpth, zd[k])


text:
Q: Digits removed from a number Tell someone to pick a positive integer, double it, add $9$, multiply by $5$ and then subtract the number that person started with. Tell that person to remove any nonzero digits in any order the person wishes. Then you tell the person the digit the person removed.
Explain how this is done.
So lets say the person pick $10$
doubling: $20$
add $9$: $29$
multiply by $5$: $145$
subtract beginning number: $135$
Lets say, the person removed $3$. So the person final answer would be $15$,
so how would i be able to tell the digits a person removed. the person could have removed $3$, $1$, $5$ as well.

A: "Tell someone to pick a positive integer"
Okay, I call it N.  (Example: 10)
"double it, add 9,"
2N + 9  (Example: 29
"multiply by 5"
10N + 45  (Example: 145)
"and then subtract the number that person started with."
9N + 45.  (Example: 135)
This number is a multiple of nine.  The digits add up to a multiple of nine.  (Example: 1 + 3 + 5 = 9)
"Tell that person to remove any nonzero digits in any order the person wishes. Then you tell the person the digit the person removed."
When you remove a digit, v, the digits will no longer add up to a multiple of nine.  They will add up to 9 - v.
(Example:  135, remove the 1 leaving 35:  3 + 5 = 8 = 9 -1.  So I know a 1 was removed.)
(Example:  135, remove the 3 leaving 15:  1 + 5 = 6 = 9 -3.  So I know a 3 was removed.)
(Example:  135, remove the 5 leaving 13:  1 + 3 = 4 = 9 -5.  So I know a 5 was removed.)


text:
Q: "Illegal characters in path" while cloning with git from Visual Studio 2017 On Visual Studio 2017, I can not clone a repository with git.
I'm having this error message:

The repository url is good and the destination folder is also fine (no spaces or special characters).
I tried on another computer and everything works perfectly.
When I'm cloning the same project with GitKraken, SourceTree or in command line, everything works.
I tried to uninstall git, cleaning  my tfs/git credentials, uncheck "Git for Windows" option on the Visual Studio installer, in vain....
Has anyone ever had the same problem? How did you solve it? Thanks for the help!
Visual Studio 2017: 15.9.11
Git version: 2.21.0
Git url path: https://tfs.mysubdomain.mydomain.fr/dev/PROJECT/_git/PROJECT
TFS Server: https://tfs.mysubdomain.mydomain.fr/dev/PROJECT/PROJECT%20Team/_git/PROJECT

A: I'm not sure what's the cause of it. I've been running git commands in the Windows Terminal. And the same problem happened when I try to pull in Visual Studio.
Here's how I got the problem resolved:
Restart the computer

A: I finally fixed it by this way:

*

*uncheck the "Git for Windows" checkbox in Visual Studio Installer

*uninstall git (for me it was version 2.21.0)

*uninstall other git apps (for me it was GitKraken and SourceTree)

*delete all git and tfs credentials via the credential manager

*reboot (just in case)

*install git

*launch visual studio and connect to the TFS server

*you can now clone and work peacefully

Et voilà :)
Everything works perfectly now. I think uninstall only git was not enough. I don't really understand why I had this issue but the bulldozer strategy was efficient.

A: I finally fixed it by deleting index.lock in /git folder

A: I've resolved this by deleting .\obj and .\bin folders in my startup project.


text:
Q: Inverting a cellphone charger Hey guys id like to convert a charger brick to reverse the volts so invert it what. i mean is in my country its 220v so the charger brick must be able to take 5v and convert it into the said 220v now all .i need it for is a fun usb killer project i bought a fly zapper but its not enough volts so what componets would i need to turn or modify .
Ive tried to just put 5v into the usb port but nothing on the 220v side

A: Switched mode power supplies used in phone chargers are one-way, non-reversible devices.

Figure 1. Not all processes are reversible. Pushing minced meat into the outlet of the mincer and turning the handle backwards will not produce a steak. Image source: SousChef.
See How does a cell phone charger work? to understand why your scheme won't work.

Update:

now all .i need it for is a fun usb killer (sic)

I didn't understand this bit at first but it seems from the comments that you wish to create a device to destroy USB ports. I hope nobody here will assist you in this childish stupidity.

A: You would have as much luck doing this as inserting a 120V charger upside down into 230V.

Start by learning how things work before trying to be an inventor.
Shop, buy, open-up, test, break, fix, capiche?   That's how I learnt as a kid, by fixing things.  But at some time you must learn to read a lot.


text:
Q: How to load the Python Parser in Pharo Smalltalk? What would be the proper way to load the PythonParser project in Pharo 3.0? The current configuration is broken with the following message:

The symbolic version #stable is not defined in
  ConfigurationOfPythonParser for the current platform. Possible
  symbolic version values include: #(#bleedingEdge #development)

I'm looking for a Python parser that can be used in Smalltalk and give me access to line and file informations about each artefact of the analysed code.

A: The error you are seeing means that the configuration hasn't been prepared for 3.0 and that the project will very likely not work without errors (though it's possible that it will work more or less). You can force a load with all the latest code by using #bleedingEdge but you have to be aware that loading of dependencies might fail for the same reason (which would require you to hack the configuration; that's something you don't want to do if you're not familiar with configurations). So try this:
(ConfigurationOfPythonParser project version: #bleedingEdge) load.

A: This will probably work (you might need a github account):
Gofer it
    smalltalkhubUser: 'Pharo' project: 'MetaRepoForPharo30/';
    configurationOf: 'PythonParser';
    loadStable


text:
Q: print a calendar for a given date in Ruby I am trying to create a method that takes user entered month and year and prints out an accurate calendar for the month and year.  I am about halfway through but have no idea how to move on.
The guidelines Below in Bold is where i am having issues
Determine the beginning of the next month.  Calculate the last day of the month by doing the following: Get the next month date, now get the previous day of that next month.  Print the Calendar heading for the full month name and year.  Print the header row that contains the abbreviated name of the days of the week.  Create an array with a length of 7 and a default value of 4 spaces (" ").
Using the date range from the beginning of the month to the end of the month do the following:
Get the numerical representation of the day of the week using the" %w" formatter and convert to an integer. (This will be the index to the array.)
Use the index to set the day of the month within the array, using the "%d" formatter to get the day of the month.
If index equals 6 OR the date equals the last day of the month, then do the following:
Loop through the array
Print the day of the month
Print a blank line  Re-initialize the array so that all values are of 4 spaces
def printMonth(year, month)
  now= Date.new(year, month, 1)
  a= now >> 1
  b= a - 1
  puts("Calendar for: #{b.strftime("%B, %Y")}")
  puts("")
  puts("Sun\tMon\tTue\tWed\tThu\tFri\tSat")
  days= Array.new(7,"    ")

  c= b.strftime("%w").to_i
end


text:
Q: Sending data from parent machine to child machine using actors I'm trying to understand Actors to be able to pass data from a sibling component to another.
I have these machines: parent and child. parentMachine sends a GET event to childMachine in the success transition. Once childMachine receives an event.value it should be assigned to a user property in its context.
const [currentChild, sendChild] = useMachine(childMachine);

Now, when I log currentChild.context after clicking fetch, the user property is empty. How do I use the data received from parentMachine in a component that depends on childMachine?
CodeSandbox: https://codesandbox.io/s/patient-frost-9lxoh
const parentMachine = Machine({
  id: "parent",
  initial: "idle",
  context: {
    ref: undefined
  },
  states: {
    idle: {
      on: {
        FETCH: {
          target: "loading"
        }
      }
    },
    loading: {
      invoke: {
        id: "getUser",
        src: (_, event) => fetchUser(event.value),
        onDone: {
          target: "success",
          actions: assign({
            user: (_, event) => {
              return event.data;
            }
          })
        },
        onError: {}
      },
      entry: assign({
        ref: () => spawn(childMachine)
      })
    },
    success: {
      entry: (ctx, evt) => ctx.ref.send({ type: "GET", value: ctx.user })
    },
    failure: {}
  }
});

const childMachine = Machine(
  {
    id: "child",
    initial: "waitingForData",
    context: {
      user: []
    },
    states: {
      waitingForData: {
        on: {
          GET: {
            actions: [
              assign({
                user: (ctx, evt) => [...ctx.user, evt.value]
              }),
              "logger"
            ]
          }
        }
      }
    }
  },
  {
    actions: {
      logger: ctx => console.log(ctx.user)
    }
  }
);

A: For doing that you can invoke Promises, Callbacks, Observables and Machines, as mention here, when you invoke machines you have to wait until invoked machine reaches its final state, and you will receive the result in the onDone, and when you invoke a Promise you have to wait until it finishes and you will receive the result in the onDone too.
Here you go an example of invoking a Machine and a Promise.


text:
Q: how to return a number with 2 decimal places all the time from a function I have a random number generator function that returns a random number. It looks like the problem is that sometimes it returns only one decimal place the, tenths place(i think it's called). I always want it to output a number with 2 decimal places (some times i would get 10.5 when i want 10.50).
in my code i put a plus sign to convert it into a number.I believe this is what is causing the hundredth's place to be deleted. what is the best way to solve this problem?
function randomGen() {
    return +(Math.random() * 11).toFixed(2)
}
// console.log(randomGen())
// some times i would get 10.5 when i want 10.50
var num1 = randomGen(); // i want 10.50, for example not 10.5
var num2 = randomGen();
console.log(num1, " ", num2)

console.log(+(num1 + num2).toFixed(2))

Thank you

A:
in my code i put a plus sign to convert it into a number.I believe this is what is causing the hundredth's place to be deleted. what is the best way to solve this problem?

Yes - don't convert it to a number!
Numerically, there is no such thing as 10.50. There is only 10.5
Only a string is capable of holding a value like 10.50, and you get a string from toFixed(), but then convert it back to a number.
So I couldn't have said it better than itd:

Loose the + signs

A: Lose the + signs and you should be fine:
function randomGen(){
        return (Math.random()*11).toFixed(2)
    }
     // console.log(randomGen())
     // some times i would get 10.5 when i want 10.50
    var num1 = randomGen(); // i want 10.50, for example not 10.5
    var num2 = randomGen();
    console.log(num1, " ", num2)

    console.log((num1 + num2).toFixed(2))

If you want to convert a string to a number in JavaScript, use the 'parseFloat' function. Be aware that if you convert a string to a number, it will always cut off the decimal zeroes (for example 10.50 becomes 10.5).
Use numbers to make calculations and after you have the final result, convert it to string with the 'toFixed' method, so you can display it with two decimal places.

A: Use the following:
randomGen(){
   result=(Math.random()*11)
   return parseFloat(result,10).toFixed(2)
    }


text:
Q: How to show that $\bar X$ is a consistent estimator Can someone give me an hint with this exercise,please?
Let $X_1,\dots,X_n$ be i.i.d. from a population with p.d.f. $(x|\theta)$ =$\theta x^ {θ−1}$
$0<x<1$
,$\theta>0$
Show that  $\bar X$ is a consistent estimator of $\frac{\theta}{\theta+1}$
I know that to be consistent the limit of $n \to \infty$ of  the MSE must equal $0$.
How can I find the bias and the variance in order to calculate the MSE? Any help would be very appreciated.

A: Call your parameter $\gamma:=\frac{\theta}{\theta+1}$ and call your estimator $\hat\gamma:=\bar X$. You are trying to show MSE converges to zero, i.e.
$$E[\|\hat\gamma -\gamma \|^2]\rightarrow 0,$$
but this is equivalent to showing convergence in $L^2$. Note this convergence is stronger than consistency, so it is not generally true that the "limit ...of the MSE must be equal zero" for consistency to hold (it is sufficient, although not necessary for consistency).
Consistency, by definition, means convergence in probability, i.e.
$$\hat\gamma\overset{p}{\rightarrow }\gamma,$$
which in your case follows immediately by the weak law of large numbers once you show $E[\hat\gamma]=\gamma.$

A: Presumably $\overline{X}_n$ is the sample mean, that is
$$\overline{X}_n=\frac1n\sum^n_{n=1}X_j$$
and the $(X_j:j\in\mathbb{N})$ are i.i.d. with common distribution
$$P=[X\in dx]=\theta x^{\theta-1}\mathbb{1}_{(0,1]}(x)$$
In such case,
$$E[\overline{X}_n]=E[X_1]=\frac{\theta}{\theta+1}$$
There are many ways to show that $\overline{X}_n$ is consistence, that is that
$\overline{X}_n$ converges in probability to $\frac{\theta}{1+\theta}$. The quickest one is by the strong law of large numbers which states in fact that $\overline{X}_n$ converges almost surely and in $L_1$ to $E[X_1]=\frac{\theta}{\theta+1}$. Convergence almost surely will imply convergence in probability.
As for convergence in MSE, notice that the quadratic error $E[(\overline{X}_n-\tfrac{\theta}{\theta+1})^2]$ coincides in this case with the variance of $\overline{X}_n$; hence
$$E[(\overline{X}_n-\tfrac{\theta}{\theta+1})^2]=\operatorname{var}(\overline{X}_n)=\frac{1}{n^2}n\operatorname{var}(X_1)=\frac{1}{n}\operatorname{var}(X_1)\xrightarrow{n\rightarrow\infty}0$$


text:
Q: DOM parsing with php is returning zero child elements I want to extract url data just like as facebook. For that I am using php DOMDocument.While retrieving the DOM content i.e while retrieving "title" the DOMDocument is returning 0 elements. Here is my code
    <?php
    header("Content-Type: text/xml");
    echo '<?xml version="1.0" encoding="UTF-8" ?>';
    //$url = $_REQUEST["url"];
    $url = "http://business.tutsplus.com/articles/how-to-set-up-your-first-magento-store--fsw-43137";
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_HEADER,0);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
    $data = curl_exec($ch);
    curl_close($ch);
    $dom = new DOMDocument();
    @$dom->loadHTML($data);
    $title = $dom->getElementsByTagName("title");
    //$title = $dom->find("title");
    echo "<urlData>";
        echo "<title>";
            echo $title->length;
        echo "</title>";
    echo "</urlData>";
?>

Here $title->length is returning 0 elements. What is the problem?


text:
Q: Trigonometry - Limits yet again I am having the solution, but don't know why it works:
\begin{align*} \quad \lim_{x \to 0}\frac{\tan(2x)}{x}&=
  \lim_{x \to 0}\frac{\sin(2x)}{x\cos(2x)}\\
&= \lim_{2x \to 0}\frac{\sin(2x)}{2x} \cdot \lim_{x \to 0}\frac{2}{\cos(2x)}\\
&= 1 \cdot 2\\
&=2 \end{align*}
I don't understand why I am allowed to turn \begin{align*} \lim_{x \to 0} \end{align*} into \begin{align*} \lim_{2x \to 0} \end{align*} I am learning this on my own for a entry exam for university and feel a bit lost...

A: Ok I'm trying to justify the conversion with just logic.Suppose x is negligibly small even 2x will be negligibly small,and for that matter any nx is negligibly small where n is a natural number (unless n tends to infinity),so the conversion you stated is valid.

A: We can prove this works. Consider the $\delta$-$\epsilon$ definition of limit
as found, for example, at
https://www.math.ucdavis.edu/~kouba/CalcOneDIRECTORY/preciselimdirectory/PreciseLimit.html
Now suppose you have already shown that
$$\lim_{2x \to 0}\frac{\sin(2x)}{2x} = 1.$$
Then (by the definition of limit)
you know that for any positive number $\epsilon$,
there is a number $\delta$ such that
$\left|\frac{\sin(2x)}{2x} - 1\right| < \epsilon$
whenever $0 < 2x < \delta$.
But if $0 < x < \frac\delta2$, then $0 < 2x < \delta$,
so you have just proved the following statement:
For any positive number $\epsilon$,
there is a number $\frac\delta2$ such that
$\left|\frac{\sin(2x)}{2x} - 1\right| < \epsilon$
whenever $0 < x < \frac\delta2$.
But that's just what the definition of $\lim_{x \to 0}\frac{\sin(2x)}{2x} = 1$
says, except that the last paragraph says there is a number $\frac\delta2$
instead of a number $\delta$.  The definition doesn't actually "care"
how you write each number as long as you use the same value wherever the
definition uses the same value, so you have shown that
$$\lim_{x \to 0}\frac{\sin(2x)}{2x} = 1.$$
As noted in comments, you can generalize this to a limit taken as some
continuous, invertible function of $x$ goes to zero,
where the function $x\mapsto2x$
is just one example of the more general fact.

A: Functions $ \sin x, \tan x $ are straight for small values of $x$, they can be approximated by x as they behave like $y=x$ in the neighborhood of x=0.So,
$$ \dfrac{\sin 2 x}{x} \approx 2,\, \dfrac{\tan 3 x}{\tan 7 x} \approx \frac37  $$
A function like $$ \dfrac{\sin 3.2 x + \tan 6.8 x}{2.5 x} \approx 4.$$

A: $$\lim_{x \to 0}\frac{\tan(2x)}{x}=
  \lim_{x \to 0}\frac{\sin(2x)}{x\cos(2x)}$$
You have to make a change of variable. Let's say $y=2x$ or $\displaystyle x= \frac{y}{2}.$
when $x \to 0$ also $y \to 0$.
So we have the following limit:
$$\lim_{y \to 0}{\frac{\sin y}{\frac{y}{2}\cos y}}$$
$$\lim_{y \to 0}{\frac{2 \sin y}{y\cos y}}.$$
Is it OK?


text:
Q: SQL group by from multiple tables I am using SQL Workbench/J and want to create two columns 'web_sales' and 'app_sales' (see case statements) combining sales data from sales2019 and sales2020 tables. However, my current code is still showing 2 records for a specific item/member combination, based off if data is coming from the 2019 or 2020 table. How can I combine 2019 and 2020 data into one record (see desired output)? The group by statement that exists outside of the subquery does not accomplish this.
select *
from (
    select id
      ,item
      ,member
      ,SUM(CASE WHEN platform = 'web' THEN revenue ELSE 0 END) AS web_sales
      ,SUM(CASE WHEN platform = 'app' THEN revenue ELSE 0 END) AS app_sales
    from sales2019
    group by id, item, member
    union
    select id
      ,item
      ,member
      ,SUM(CASE WHEN platform = 'web' THEN revenue ELSE 0 END) AS web_sales
      ,SUM(CASE WHEN platform = 'app' THEN revenue ELSE 0 END) AS app_sales
    from sales2020
    group by id, item, member) A
group by A.id, A.item, A.member
order by A.item asc;

Current Output:
id  item    member  web_sales   app_sales
2   desk-blue   y   132.5   374.6
2   desk-blue   n   348.9   2597.9
2   desk-blue   y   753.1   2209.9
2   desk-blue   n   23.3    234.9
3   desk-brown  y   245.4   271.2
3   desk-brown  n   192.4   5295.8
3   desk-brown  n   1.6     776.5

Desired Output:
id  item    member  web_sales   app_sales
2   desk-blue   y   885.6   2584.5
2   desk-blue   n   372.2   2832.8
3   desk-brown  y   245.4   271.2
3   desk-brown  n   194.0   6072.3

A: You can do the union all before aggregating:
select id, item, member,
       SUM(CASE WHEN platform = 'web' THEN revenue ELSE 0 END) AS web_sales,
       SUM(CASE WHEN platform = 'app' THEN revenue ELSE 0 END) AS app_sales
from ((select id, item, member, platform, revenue
       from sales2019
      ) union all
      (select id, item, member, platform, revenue
       from sales2020
      )
     ) s
group by id, item, member


text:
Q: Elevated Content Search for anonymous I need to create a search web part with Visual Studio for SharePoint 2013 On-Prem that enables anonymous users to search for Items and People which they may have no accessed to (Example: The List is not set to anonymous accessible).
This scenario is needed as some information within the Item should not be shown to the public. Hence I would like to obtain all public information to be shown within the Web Part.
I have tried using CoreResultsSearchWebPart with elevated privileges
http://kjellsj.blogspot.sg/2012/04/elevated-search-results-sharepoint-2010.html
However, this CoreResultsSearchWebPart  will not allow searching of people(As People search has a PeopleCoreResultsWebPart) or a text box for user search(I could not find a connection to send query to the CoreResultsSearchWebPart)
Do I really need to create a search webpart from scratch? If so could anybody give me some examples? I have tried using SharePoint rest API of Client Object Model but it does not work.
Here is the sample code of mine
using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Search;
using Microsoft.SharePoint.Client.Search.Query;
namespace CustomSearchWebPartTrial.CustomSearchWebPart
{
    [ToolboxItemAttribute(false)]
    public partial class CustomSearchWebPart : WebPart
    {
        // Uncomment the following SecurityPermission attribute only when doing Performance Profiling on a farm solution
        // using the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready
        // for production. Because the SecurityPermission attribute bypasses the security check for callers of
        // your constructor, it's not recommended for production purposes.
         [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]

        public CustomSearchWebPart()
        {
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            SPSite site = SPContext.Current.Site;
            using (ClientContext clientContext = new ClientContext(site.Url))
            {
                KeywordQuery keywordQuery = new KeywordQuery(clientContext);

                keywordQuery.QueryText = "SPContentType:\"Custom Announcement\"";
                keywordQuery.ClientType = "CSOM";

                SearchExecutor searchExecutor = new SearchExecutor(clientContext);

                ClientResult<ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery);
                clientContext.ExecuteQuery();
                int count = 0;
                foreach (var resultRow in results.Value[0].ResultRows)
                {
                    count++;
                }
                lblCount.Text = count.ToString();//checking for number of items. Example of this query for my authenticate users is 5, it should return 5 for anonymous as well.
            }
        }
    }
}

I got errors of IgnoreSafeQueryPropertiesTemplateUrl = true as my users and anonymous users don't have the UseRemoteAPIs() permission.
So i set within the code to IgnoreSafeQueryPropertiesTemplateUrl = false, which brings up another error where it mentions
Microsoft.Office.Server.Search.REST.SearchServiceException: The SafeQueryPropertiesTemplateUrl "The SafeQueryPropertiesTemplateUrl "{0}" is not a valid URL." is not a valid URL.
And Followed the guide of
http://blog.mastykarz.nl/configuring-sharepoint-2013-search-rest-api-anonymous-users/
 protected void Page_Load(object sender, EventArgs e)
        {

            SPSite site = SPContext.Current.Site;
            using (ClientContext clientContext = new ClientContext(site.Url))
            {
                KeywordQuery keywordQuery = new KeywordQuery(clientContext);
                keywordQuery.IgnoreSafeQueryPropertiesTemplateUrl = false;
                keywordQuery.QueryText = "SPContentType:\"Custom Announcement\"" + "&QueryTemplatePropertiesUrl=\"spfile://webroot/queryparametertemplate.xml\"";

                keywordQuery.ClientType = "CSOM";

                SearchExecutor searchExecutor = new SearchExecutor(clientContext);

                ClientResult<ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery);
                clientContext.ExecuteQuery();
                int count = 0;
                foreach (var resultRow in results.Value[0].ResultRows)
                {
                    count++;
                }
                lblCount.Text = count.ToString();
            }

But it still failed.

A: I see that you are using ClientContext which is ment to be used when developing Apps for SharePoint, as Apps can't use the SharePoint API.
Since it's a full-trust solution you are developing, use the SharePoint API.
In your PageLoad method, use SPSecurity.RunWithElevatedPrivileges() to elevate the permissions of the current user, anonymous or not, and execute the Search code.
Also, since you are going to elevate permissions for users who don't have access to lists and libraries, you have to change the web context.
Here's a snippet:
// Store the current site ID in a variable, you'll need it
Guid siteId = SPContext.Current.Site.ID;

// Get the user token for the System Account
// The System Account should automatically have Site Collection permissions
SPUserToken systemAccountUserToken = SPContext.Current.Site.SystemAccount.UserToken;

// And store the current web context in a variable as well.
// As I mentioned before, you'll have to change it, but also change it back again
HttpContext currentUserContext = HttpContext.Current;

// Clear the current context
if (SPContext.Current != null)
    HttpContext.Current = null;

// Elevate privileges
SPSecurity.RunWithElevatedPrivileges(() =>
{
    // Impersonate the System Account
    using (SPSite elevatedSite = new SPSite(siteId, systemAccountUserToken))
    {
        // Here begins the magic
        // Creating a new Web Context
        HttpRequest httpRequest = new HttpRequest(string.Empty, elevatedSite.RootWeb.Url, string.Empty);
        HttpContext.Current = new HttpContext(httpRequest, new HttpResponse(new StringWriter()));
        // And here we set the new Web Context. Muy importante
        SPControl.SetContextWeb(HttpContext.Current, elevatedSite.RootWeb);

        // By this point user should be running as the System Accounts
        // and be able to execute code with the right level of privileges
        KeywordQuery keywordQuery = new KeywordQuery(elevatedSite);
        keywordQuery.QueryText = "SPContentType:\"Custom Announcement\"" + "&QueryTemplatePropertiesUrl=\"spfile://webroot/queryparametertemplate.xml\""
        SearchExecutor searchExecutor = new SearchExecutor();
        ResultTableCollection resultTableCollection = searchExecutor.ExecuteQuery(keywordQuery);
        var resultTables = resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults);
        resultTable = resultTables.FirstOrDefault();
    }
});

// Remember I said change back the Web Context? Here we go:
HttpContext.Current = currentUserContext;

A: Just a thought, but rather than follow this course of action and gut security with a full trust web part. Why not create anonymous content "summaries" that users have access to and just return those results? You can customize the result so that it links to the original secure content. I have don't this for several clients and it works very well with zero customization.


text:
Q: How to pass a string that contains single and double quotes? I have string variable called name. name contains the string 14'6". I'm trying to pass name to a function. I'm trying to add an onclick to a tablerow this like this:
$("#trID").attr('onclick', 'testFunction(' + name + ')');

I tried using the escape character to achieve this, however I didn't get this to work because the string contains both a single quote (') and a double quote (").
Is there a way I can pass thing string in to a function or do I have to change the string completely?
Thanks!

A: To do what you require you need to escape the single/double quotes within the name string. To do that you could use a regex:
name = name.replace(/([\""|\''])/g, '\\$1');
$("#trID").attr('onclick', 'testFunction(' + name + ')');

However it should be noted that using inline event handlers, ie. the onclick attribute in your example, is not good practice. You should use unobtrusive event handlers instead.
As you've already included jQuery in the page it would be achieved with an event handler and a data attribute, like this:

let $div = $("#trID").on('click', function() {
  console.log($(this).data('foo'));
});

$('button').on('click', function() {
  $div.data('foo', (new Date()).getTime());
});

Click me to display value

<button>Click me to change value</button>

A: Try the string template of javascript
$("#trID").attr('onclick', `testFunction(${name})`);

A: You can use JSON as proxy since its array syntax is based on JavaScript and JSON.stringify() can cope with JSON fragments (such a standalone string):

function testFunction(param){
    console.log(param);
}
var rawName = "one\n\"two\"\n'three'\nfour";
var encodedName = JSON.stringify(rawName);
console.log(rawName, encodedName);
$("#trID").attr('onclick', 'testFunction(' + encodedName + ')');

<button id="trID">Click Me!</button>

It's worth noting anyway that you don't need it in the first place. Dynamically generated code is hard. Since you're using jQuery, a cleaner way would be:

function testFunction(param){
    console.log(param);
}
var name = "one\n\"two\"\n'three'\nfour";
$("#trID").on('click', function() {
    testFunction(name);
});

<button id="trID">Click Me!</button>


text:
Q: How to get a reference height or width of an image in the console I have been trying hard to reference the width of an image all to no avail. Let's say I set an image height to be 375.0. Ordinarily, the width adjust itself by default based on the set height. Please, how can i be able to print the corresponding width which wasn't specified to the console?
Any help will be appreciated.

A: You need to provide a GlobalKey to the image. Then you can pass the key and the context to the following function:
Size getSize(GlobalKey _key, BuildContext context) {
  final RenderBox renderBox = _key.currentContext.findRenderObject();
  final boxSize = renderBox.size;
  return boxSize;
}


text:
Q: Using Microsoft.AspNetCore.SpaTemplates new angular project, but build forever I'm using visual studio 2017, and I want to develop an Angular 2 project. This project is only for front-end pages, services are already built with a web api.
So, I installed Microsoft.AspNetCore.SpaTemplates first, then I executed dotnet new angular to create a new angular project:
{
  "compilerOptions": {
    "moduleResolution": "node",
    "target": "es5",
    "sourceMap": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipDefaultLibCheck": true,
    "lib": [ "es6", "dom" ],
    "types": [ "node" ]
  },
  "exclude": [ "bin", "node_modules" ],
  "atom": { "rewriteTsconfig": false }
}

But when I open it in Visual Studio and tried to run it, it takes forever to build. No error occurs, it just keeps on building. What have I missed?

A: I watch video here https://channel9.msdn.com/Events/Visual-Studio/Visual-Studio-2017-Launch/WEB-103 found out, what i missed is restore and npm install.


text:
Q: I cannot build python.dll as a static library (/MTd) using Visual Studio I am working with the 3.6.4 source release of Python. I have no trouble building it with Visual Studio as a dynamic library (/MDd) I can link the Python .dll to my own code and verify its operation.
But when I build it (and my code) with (/MTd) it soon runs off the rails when I try to open a file with a Python program. A Debug assertion fails in read.cpp  ("Expression: _osfile(fh) & FOPEN").  What I believe is happening is the Python .dll is linking with improper system libraries.  What I can't figure out is how to get it to link with the correct ones (static libraries).

A: This is what I needed to do to build and use python statically embedded in another application.
To build the static python library  (e.g., python36_d.lib, python36.lib)

*

*Convert ALL projects in the python solution (pcbuild.sln) to static.  This is about 40 projects, so it may take awhile.  This includes setting library products to be build as 'static lib', and setting all /MD and /MDd build options to /MT and /MTd.

*For at least the pythoncore project alter the Preprocess define to be Py_NO_ENABLE_SHARED.  This tells the project it will be looking for calls from static libraries.

*By hook or crook, find yourself a pyconfig.h file and put it in the Include area of your Python build.  It is unclear how this file is built from Windows tools, but one seems to be able to snag one from other sources and it works ok.  One could probably grab the pyconfig.h from the Pre-compiled version of the code you are building.  [By the way, the Python I built was 3.6.5 and was built with Windows 2015, update 3.]
Hopefully, this should enable you to build both python36.lib and python36_d.lib.  Now you need to make changes to your application project(s) to enable it to link with the python library.  You need to do this:

*

*Add the Python Include directory to the General->Include Directories list.

*Add the Python Library directories to the General->Library Directories lists.
This will be ..\PCBuild\win32   and ..\PCBuild\amd64.

*Add the define Py_NO_ENABLE_SHARED to the C/C++ -> Preprocessor area.

*For Linker->input add (for releases) python36.lib;shlwapi.lib;version.lib and (for debugs) python36_d.lib;shlwapi.lib;version.lib.

And that should be it.  It should run and work.  But one more thing. In order to be able to function, the executable needs to access the Lib directory of the python build.  So a copy of that needs to be moved to wherever the executable (containing the embedded python) resides.  Or you can add the Lib area to the execution PATH for windows.  That should work as well.
That's about all of it.


text:
Q: Vectorisation of complex function I'm trying to speed up some of my for loops using vectorisation. Unfortunately, the functions inside the loops are more complex than simple arithmetic operations. I want to take each item of an array, manipulate it using a function with multiple inputs, and then place it in the correct place in a dictionary. To do this, I have a function called increase_element:
def increase_element(number, word, factor=0.05):
    print(2.*factor)
    return {'factor': 2.*factor, 'number': number, 'word': word}

What I am trying to achieve is going from the array:
array([0., 0.1, 0.2])

to the array:
array([
       {factor: 0., number: 5, word: 'hi'},
       {factor: 0.2, number: 5, word: 'hi'},
       {factor: 0.4, number: 5, word: 'hi'}
      ])

in an efficient manner (i.e. not using a for loop) as in reality the function increase_element takes a long time to run.
What I have tried to do is use a function to convert all the inputs to a single input, then map this onto a numpy array as so:
import numpy as np

muls = np.linspace(0, 1, 11)

def increase_element(number, word, factor=0.05):
    print(2.*factor)
    return {'factor': 2.*factor, 'number': number, 'word': word}

def single_increase_element(inputs):
    return increase_element(inputs[0], inputs[1], factor=inputs[2])

single_array = np.array(list(map(lambda x: (5, 'hi', x), muls)))

np.array(list(map(single_increase_element, single_array)))

However I get the below error when trying to print 2.*factor

TypeError: can't multiply sequence by non-int of type 'float'

Any advice would be great appreciated!

A: the factor in your print is of type <class 'numpy.str_'>.
the error is because you are tring to multiple string with 2.0.
As for the code, I suggest you explain what you are trying to achieve because it is very complex to comprehend.
Edit: below it a your code fixed. The root cause was that dtype=np.object was missing and numbers were treated as strings.
import numpy as np

muls = np.linspace(0, 1, 11)

def increase_element(number, word, factor=0.05):
    print(2.*factor)
    return {'factor': 2.*factor, 'number': number, 'word': word}

def single_increase_element(inputs):
    return increase_element(*inputs)  # fixed
    # return increase_element(inputs[0], inputs[1], factor=inputs[2]) # original

# single_array = np.array(list(map(lambda x: (5, 'hi', x), muls)))  # original
single_array = np.array(list(map(lambda x: (5, 'hi', x), muls)), dtype=np.object) # fixed

np.array(list(map(single_increase_element, single_array)))


text:
Q: How do I count how many distinct values a row possess? Suppose I'm given a database of paper routes.
Create table routes(route_number varchar(100), route_length varchar(1000)
Create table deliverers(deliv_name varchar(100))
Create table deliveries(Deliv_name varchar(100), route_number varchar(100),
                        number_of_papers varchar(100), date_of delivery date(yyyy-mm-dd))

(i know this isn't complete but we dont need to know the keys for this example)
I want to know the number of routes that each deliverer has, not the amount of deliveries that have taken place on each route. if delivery boy A has 3 routes and he delivers on this route 100 times a year, i only want to know how many routes he has.
I think i need to use set theory or an outer join but im unable to solve this problem so far.

A: Try this:
SELECT deliverers.deliv_name As DeliveryPerson, COUNT(DISTINCT route_number) As RoutesCount
FROM deliverers
INNER JOIN deliveries ON deliveries.Deliv_name =  deliverers.deliv_name
GROUP BY (deliverers.deliv_name)

A: Use this:
SELECT      A.deliv_name, COUNT(DISTINCT route_number) AS "NoOfRoutes"
FROM        dbo.deliverers A
            LEFT OUTER JOIN dbo.deliveries B
                ON A.deliv_name = B.Deliv_name
GROUP BY    A.deliv_name

A: Aggregate functions can use DISTINCT to aggregate only distinct values:
SELECT deliv_name,
       count(DISTINCT route_number) AS routes
FROM deliveries
GROUP BY deliv_name;

But if you want to include deliverers that have not yet many any delivieries, you have to look into the deliverers table, too. This can be done either with an outer join:
SELECT deliv_name,
       count(DISTINCT route_number)
FROM      deliverers
LEFT JOIN deliveries USING (deliv_name)
GROUP BY deliv_name;

or a correlated subquery:
SELECT deliv_name,
       (SELECT count(DISTINCT route_number)
        FROM deliveries
        WHERE deliv_name = deliverers.deliv_name
       ) AS routes
FROM deliverers;


text:
Q: Rails 5 sum and group My DB columns for model Taxline:
ID, RECEIPT, TAXID, BASE, AMOUNT
Let say I have db entries:
1,1,001,30$,3$
2,1,001,50$,5$
3,2,001,20$,2$
I want to show sum of amount for each receipt. Result should be:
1,8$
2,2$
My controller
    class TaxlinesController < ApplicationController

  def index
    @taxlines = Taxline.group(:RECEIPT).sum(:AMOUNT)
  end

end

My View:
 <% @taxlines.each do |taxline| %>

        <%= taxline.RECEIPT %>
        <%= taxline.AMOUNT %>

But I get error undefined method `RECEIPT' for ["01a8fdd7-8eb6-44d0-a686-8010b9e30206", 145000.0]:Array
145000.0 and 01a8fdd7-8eb6-44d0-a686-8010b9e30206 refer to real vaules in db not to the example above. But it gives the idea.
App is built on existing db with column names uppercase.
What am I doing wrong?

A: Your problem is that Taxline.group(:RECEIPT).sum(:AMOUNT) returns a Hash object rather than a set of Taxline instances like you are expecting. They keys are the grouped values (RECEIPT) and the values are the corresponding sums. Something like:
{ "01a8fdd7-8eb6-44d0-a686-8010b9e30206" => 145000.0, ... }

When you do @taxlines.each the Hash gets coerced into an Array.
With your current code you could simply change your view to this:
<% @taxlines.each do |receipt, amount| %>
    <%= receipt %>
    <%= amount %>


text:
Q: How to initialize passport (issue with exporting) I have some issues to initiate passport.

*

*I call the function app.use(passport.initialize()); in the file server.js

*In the file auth.controllers.js passport is not detected as initialized

Somebody could explain how to "connect" app.use(passport.initialize()) in the server.js to the file auth.controllers.js ?
here my files :
Server.js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const helmet = require("helmet");
const morgan = require("morgan");
const networkConfig = require("./config/network.config");

const app = express();

const db = require("./config/models");
db.sequelize.sync();

var corsOptions = {
    origin: networkConfig.corsOptions.ORIGIN
};

app.use(helmet());
app.use(cors(corsOptions));
app.use(morgan('combined'));

// parsing sur les requetes en type json
app.use(bodyParser.json());

// parsing des urls encodés
app.use(bodyParser.urlencoded({ extended: true }));

// route de vérification de bon fonctionnement
app.get("/", (req, res) => {
    res.json({message: "Bienvenue ici"});
});

require("./routes/user.routes")(app);
require("./routes/oauth2.route")(app);
require("./routes/client.routes")(app);
require("./routes/beer.routes")(app);

const ejs = require('ejs');
const session = require('express-session');
const passport = require('passport');

/*
const beerController = require('./controllers/beer');
const userController = require('./controllers/user');
const authController = require('./controllers/auth');
const oauth2Controller = require('./controllers/oauth2');
const clientController = require('./controllers/client');
*/

// Set view engine to ejs
app.set('view engine', 'ejs');

// Use express session support since OAuth2orize requires it
app.use(session({
  secret: 'Super Secret Session Key',
  saveUninitialized: true,
  resave: true
}));

// Use the passport package in our application
app.use(passport.initialize());

// Start the server
app.listen(3000);

user.routes.js
module.exports = app => {

const users = require("../controllers/user.controllers");
const auths = require("../controllers/auth.controllers")(app);

const router = require("express").Router();

// Create endpoint handlers for /users
router.route('/')
  .post(users.create)
  .get(auths.isAuthenticated, users.findAll);

app.use('/api/users', router);
};

auth.controllers.js
// Load required packages
var passport = require('passport');
var BasicStrategy = require('passport-http').BasicStrategy;
var BearerStrategy = require('passport-http-bearer').Strategy
const db = require("../config/models");
const User = db.user;
const Client = db.client;
const Token = db.token;
const Op = db.Sequelize.Op;

passport.use(new BasicStrategy( (username, password, done) => {
    User.findOne({where: { username: username }})
      .then(function (data) {
        if (!data) {
          return done(null, false, { message: 'user does not exist'});
        } else {
          var verify = data.verifyPassword(password);
          if(verify == true) { console.log("verify true"); return done(null, data, {message: 'authentication succeded'})}
        }
      })
      .catch( (err) => {
        console.log("Error reason : "+ err);
        return done(null, false, { message: 'Something went wrong with you authentication'});
        }
      )
  }
));

passport.use('client-basic', new BasicStrategy(
  function(username, password, callback) {
    console.log("CLIENT-BASICCLIENT-BASICCLIENT-BASICCLIENT-BASICCLIENT-BASICCLIENT-BASICCLIENT-BASICCLIENT-BASICCLIENT-BASIC");
    Client.findOne({ id: username }, function (err, client) {
      if (err) { return callback(err); }

      // No client found with that id or bad password
      if (!client || client.secret !== password) { return callback(null, false); }

      // Success
      return callback(null, client);
    });
  }
));
exports.isAuthenticated = passport.authenticate('basic', { session : false });
exports.isClientAuthenticated = passport.authenticate('client-basic', { session : false });

How could I resolve this problem ?
Regards,


text:
Q: What does this Japanese message in the App Store when updating apps mean? I have been using the Japanese version of App Store for quite a while but lately I can't update my downloaded apps.

Every time I try to update my apps this message comes up and since I can't read Japanese I have no idea what App Store wants. Can somebody please help me?

A: It says the Apple ID you used is invalid.


text:
Q: webNavigation.onCompleted fires when typing in address bar I've made a Chrome extension that monitors the webNavigation.onCompleted event to detect when the user navigates to a different page. However, I think the API works a little differently that I initially thought.
Basically, if I set focus to the address bar I immediately get a couple of onCompleted events for google.com (I assume that's the search functionality of the address bar). However, when I then enter certain addresses, such as evolvehq.com. and before I hit Enter, I get an onCompleted event for the page. Hitting Enter afterwards doesn't fire another event when the page has actually loaded.
What's going on and how do I reliably detect page changes, i.e. when the destination page has been fully loaded and shown to the user?
Update: After some more investigation, it looks like hitting Enter after the target website has (ostensibly) been preloaded by Chrome causes a single onBeforeNavigate event (but none of the other events that are supposed to follow it).
Even more interesting, after the history.onVisited event has fired, I get a webNavigation.onErrorOccurred event with net::ERR_ABORTED in it, even though the page loaded just fine.
Argh...

A: I have a theory.  I'm not saying that's it.
May be, Chrome Instant is firing those events.
And may be, while you continue typing, Chrome Instant change the page causing the ERR_ABORTED.
You can check if Chrome Instant is enabled in Options/Basic/Search.


text:
Q: Select columns from data frames in a list using a column names vectors list I have a list of data frames:
all_trials <- list(data1 = data.frame(trial1 = 1:5,
                                      trial2 = 6:10,
                                      trial3 = 11:15,
                                      trial4 = 16:20),
                   data2 = data.frame(trial2 = 1:4,
                                      trial3 = 5:8,
                                      trial5 = 9:12))

And a list of variables that I would like to select from each of the data frames, preferably with purrr.
trials_to_select <- list(data1 = c("trial1", "trial3", "trial4"),
                         data2 = c("trial2", "trial5"))

Desired output:
selected_trials <- list(data1 = data.frame(trial1 = 1:5,
                                           trial3 = 11:15,
                                           trial4 = 16:20),
                        data2 = data.frame(trial2 = 1:4,
                                           trial5 = 9:12))

$data1
  trial1 trial3 trial4
1      1     11     16
2      2     12     17
3      3     13     18
4      4     14     19
5      5     15     20

$data2
  trial2 trial5
1      1      9
2      2     10
3      3     11
4      4     12

I found how to select the same columns from each data frame in a list using map(), but I need to select different columns in each data frame.

A: Map(`[`, all_trials, trials_to_select)

$data1
  trial1 trial3 trial4
1      1     11     16
2      2     12     17
3      3     13     18
4      4     14     19
5      5     15     20

$data2
  trial2 trial5
1      1      9
2      2     10
3      3     11
4      4     12

A: With purrr:
purrr::map2(all_trials, trials_to_select, dplyr::select)
$data1
  trial1 trial3 trial4
1      1     11     16
2      2     12     17
3      3     13     18
4      4     14     19
5      5     15     20

$data2
  trial2 trial5
1      1      9
2      2     10
3      3     11
4      4     12