text:
Q: why isn't the net force considered while calculating potential due to a system of charges? The textbook I'm reading defines potential at a point as

work done per unit charge by an external agent to move the test charge from the reference point to the point under consideration (without changing it's kinetic energy)

During calculation of potential at a point due to a system of charges, why isn't the work done against the net force due to the system considered instead of simply adding up the work done against separate forces caused by individual charges?
PS: Wherever the explanation requires math, kindly also provide it's physical implications

A:
...why isn't the work done against the net force due to the system considered instead of simply adding up the work done against separate forces caused by individual charges?

They're both equivalent, due to the principle of superposition.
Basically, the net force is what you get when you add up the separate forces from the individual charges acting on the test charge, so when you calculate the work done against the net force, it's the same as adding up the work done against the separate forces.
General two particle system:
Imagine you have two charged particles in space, $Q_1$ and $Q_2$, and your test charge. When you move your test charge, the work done against the electrostatic force, $\mathbf{F_1}$, of $Q_1$ is $W_1=-\int{\mathbf{F_1}\cdot\mathrm{d}\mathbf{r}}$. Similarly, the work done against charge 2 is $W_2=-\int{\mathbf{F_2}\cdot\mathrm{d}\mathbf{r}}$.
What is the total work done?
$$W_T=W_1+W_2=-\int{\mathbf{F_1}\cdot\mathrm{d}\mathbf{r}}-\int{\mathbf{F_2}\cdot\mathrm{d}\mathbf{r}}$$
$$=-\int{(\mathbf{F_1}+\mathbf{F_2})\cdot\mathrm{d}\mathbf{r}}$$
But wait, what is the resultant force on the test charge? It's $\mathbf{F_T}=\mathbf{F_1}+\mathbf{F_2}$. Therefore
$$W_T=-\int{\mathbf{F_T}\cdot\mathrm{d}\mathbf{r}}$$


text:
Q: Identify Story: Trying to stop nano-machine escape, but they're already out This is a short story that's about a decade or so old. In it, the protagonist is helping to quarantine an area to stop a nano-machine intelligent swarm from breaking out. The "reveal" is that they've already broken out, and that the protagonist is just a simulacrum of the original protagonist.  The kicker is that the nano-machine swarm decides to "sink" and become the substrate for a "real" world which it would run without anyone in the world knowing it.  However, in doing so it finds it is itself being run by a yet deeper level of construct.
I think that this was in a anthology.

A: "True Names" by Cory Doctorow and Benjamin Rosenbaum, discussed in this thread Novella where two vast digital civilizations simulate each other
It's collected in an anthology called "Fast Forward II" - and involves resistance to a nanotechnology outbreak called "Demiurge" only to find out that the people resisting are already inside Demiurge

How do we know, friends, that we are alive inside a real Beebe and not
traitors to Beebe living in a faux-Beebe inside a blob of captive
matter within the dark mass of the Demiurge? (How? How? they cried,
and she shook her head sadly.)

and at the end of the story, it's learned that it goes even deeper.

"Oh. Well." Paquette squinted. "It's rather odd. The numbers seemed
to imply that we were in emulation … but not in Beebe, nor in
Demiurge. In something else, with characteristics that were exceedingly
odd. So perhaps … well, research is continuing. We don't really know what > it means."
Brobdignag's tale:
Look, chuckles, don't believe everything you read.
"Simple, uniform, asentient, voracious"—well, so is your Mama
Hydrogen. "Doesn't evolve," "replication flawless over a googol
iterations"— well, like all propaganda, it's true as far as it goes.
Those little engines— void-eating, gravity-spinning, durable,
expanding through the territory of known space—those aren't us.
They're just what we're made of.
That's right: we arise in all that complex flocking logic.
Do we prefer this substrate? Not necessarily. Do we wonder what things
were like before the universe was refashioned for our kind? Sure we
do. And we read and reconstruct the void-emanations, painstakingly
re-creating the thoughts of the intelligences that came before. And,
as we grow and complexify, we've even begun to spin them out in
emulation.
That's why Paquette can't quite figure out who's emulating her. We
are! It's a bit of a blind spot of hers. That signature in the Lemma:
that's us waving hello. Hi Paquette! It's Brobdignag!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to disable or remove Socket.Io log message in user browser? I made an app that use socket.io.
It's time to put in production.
Before that, i want to remove or disable all socket.io error log in Client Side( the browser of user, So by inspecting console, he will not see the error).
Error is available at this link below
https://i.stack.imgur.com/PMDib.jpg

A: console['error'] = function(){}

did the job before all others scripts.
Thanks


text:
Q: webview and number of lines limit everyone
I have a strange problem in a webview. When I use api level 19 emulator all the lines
are displayed even when I expand all the "paragraphs"(nearby 1600 lines) but the lines
are displayed partially(1200 lines) when I use api level 24 or 25.

<!DOCTYPE html>

 <title>title</title>

 <link rel="stylesheet" media="all" title="style de la page" href="afficher_cacher_div.css" />

                  Solution:

                      part1

       part 1(important):

      nearby 900 lines of codes

            part 1(important):

                       subpart 2:

 (Display/Hide)

           subpart 2:

                        400 lines of codes

            Fin de la subpart 2.

                      subpart 3:

 (Display/Hide)

                    subpart 3:

                     nearby   300 lines of codes

            Fin de la subpart 3.

 <?xml version="1.0" encoding="utf-8"?>
 <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:scrollbarStyle="insideOverlay"  android:background="@drawable/gradient9" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="720dp">

        <View
            android:id="@+id/View1"
            android:layout_width="fill_parent"
            android:layout_height="10dp"
            android:layout_below="@+id/adView"
            android:background="#00000000" />

        <View
            android:layout_width="fill_parent"
            android:layout_height="15dp"
            android:layout_below="@+id/View1"
            android:background="#FF00FFDD" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="24dp"
            android:text="@string/activity_main_submenu2_button3"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textSize="20dip" />

        <WebView
            android:id="@+id/editText2"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/textView1"
            android:layout_marginTop="93dp"
            android:ems="20"
            android:scrollbarStyle="insideOverlay"
            android:scrollbars="horizontal|vertical" />

        <Button
            android:id="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/editText2"
            android:layout_marginTop="20dp"
            android:text="@string/Autre_exercice_button" />

        <Button
            android:id="@+id/button2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/button1"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="10dp"
            android:text="@string/activity_main_submenu2_title" />

        <Button
            android:id="@+id/button3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/button2"
            android:layout_below="@+id/button2"
            android:layout_marginTop="10dp"
            android:text="@string/activity_main_title" />

        <Button
            android:id="@+id/button4"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/button3"
            android:layout_below="@+id/button3"
            android:layout_marginTop="10dp"
            android:text="@string/button_quit" />

        <TextView
            android:id="@+id/TextView01"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:text="@string/activity_main_submenu2_title"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textSize="20dip" />
    </RelativeLayout>

</ScrollView>

           function visibilite(id) {
         var divs = document.getElementsByTagName('div');
    for(var no=0;no<divs.length;no++){
        if(divs[ no].className=='divs'){ // on cible les divs dont la class                   est 'divs'
            divs[ no].style.display = "none"; // on les masque tous
        }
    }
    document.getElementById(id).style.display = "block"; // on affiche le div appelé
}

java(just the call of wiebview)
 webView=(WebView)findViewById(R.id.editText2);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new MyWebViewClient());

        webView.setVerticalScrollBarEnabled(true);

        webView.setHorizontalScrollBarEnabled(true);

        if (EXOnumero == 1)

        {     webView.loadUrl("file:///exo01x03x01.html");}

Thanks in advance for your help.


text:
Q: How to create a query in Axapta? This is related to a my previous question. I've a (not so) 'complex' query with 3 joined table. This is the query:
    select  somefield
from WMSTRANSPORT INNER join GMSWmslocationwrkctr On WMSTRANSPORT.TOLOCATION = GMSWMSLOCATIONWRKCTR.WMSLOCATIONID
inner join WMSLOCATIONSUM on WMSTRANSPORT.TOLOCATION = WMSLOCATIONSUM.WMSLOCATIONID
where
EXPEDITIONSTATUS=3 OR EXPEDITIONSTATUS =4

How to 'convert' into X++ code ?

A: Just change the ON clauses to WHERE clauses, use == instead of =, and use || instead of OR:
select somefield
from WMSTRANSPORT
where (WMSTRANSPORT.EXPEDITIONSTATUS==3 || WMSTRANSPORT.EXPEDITIONSTATUS==4)
join GMSWmslocationwrkctr where WMSTRANSPORT.TOLOCATION == GMSWMSLOCATIONWRKCTR.WMSLOCATIONID
join WMSLOCATIONSUM where WMSTRANSPORT.TOLOCATION == WMSLOCATIONSUM.WMSLOCATIONID


text:
Q: Trying to livestream youtube through python I am trying to stream youtube through python bypassing the download part. However i am getting an error from my current solution.
The code is :
import pafy, vlc
url = str(raw_input())
video = pafy.new(str(url))
best = video.getbest()
playurl = best.url()
Instance = vlc.Instance()
player = Instance.media_player_new()
Media = Instance.media_new(playurl)
Media.get_mrl()
player.set_media(Media)
player.play()

the error i get is :
  File "musicdownplay.py", line 5, in <module>
  playurl = best.url()
  TypeError: 'unicode' object is not callable

i have declared as a string so i cant find the error

A: According to the API, video.getbest() returns a Stream object.
And a Stream object has an attribute Stream.url, not a function Stream.url().
From the docs:

Stream.url
The direct access URL of the stream. This can be used to stream the media in mplayer or vlc, or for downloading with wget or curl. To download directly, use the Stream.download() method.

TL;DR: Change playurl = best.url() to playurl = best.url


text:
Q: google play 2014 scroll to hide top image I´m trying to create an app inspired in the google play app.
I have my

*RelativeLayout
                    - RelativeLayout: * Header(this is the one that will be hidden when scrolling).
                    - RelativeLayout
                                  * ListView

When I scroll down I want the header to be pushed up the screen and then my listview will occupy the whole screen and when I scroll up the header will return to its original position.
I am currently using this code, but it flickers when I´m somewhere at the top of the list.
    // Hide top relative layout
        list.setOnScrollListener(new AbsListView.OnScrollListener() {
            int mPosition=0;
            int mOffset=0;
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            int position = list.getFirstVisiblePosition();
            View v = list.getChildAt(0);
            int offset = (v == null) ? 0 : v.getTop();

            if (mPosition < position || (mPosition == position && mOffset < offset)){
                // Scrolled up
                overridePendingTransition(R.anim.slide_up, R.anim.slide_down);
                headerLayout.setVisibility(View.GONE);

            } else {
                // Scrolled down
                headerLayout.setVisibility(View.VISIBLE);
            }
        }
    });

Can anyone please help me? It will be appreciate. I don't know if I'm using the right layouts.
Thanks in advanced!


text:
Q: jQuery UI : My resize function is not working properly I want to know that my resize function is not working properly as I aspected means the problem is when I resize the div ( increase the padding ) and leave it and when I again try to resize it padding shrinks.
Note : I am Increasing the padding not the height.
$( function() {
    $( "#resizable" ).resizable({
      resize: function( event, ui ) {
        var originalHeight = ui.originalSize.height;
        var newHeight = ui.size.height;
        var pad = 5;
        if (originalHeight < newHeight) {
          pad = newHeight - originalHeight;
        }
        $(this).css({'padding': pad, 'height': 200, 'width': 400});
      }
    });
 });

My fiddle link

A: Yeah @Botimoo seems correct. You should probably consider positioning with something other than padding. But something like this probably is close to what you want if you want to stick with padding
https://jsfiddle.net/6rh7emog/5/

Resizable

$( function() {
    $( "#resizable" ).resizable({
      aspectRatio: true,
      resize: function( event, ui ) {
        var originalHeight = ui.originalSize.height;
        var newHeight = ui.size.height;
        $('#wrapper').css({
              'padding': newHeight - 200
        });
      }
    });
 });


text:
Q: Triggering Script VIA URL variable As of now, on my page, the following html is working fine to trigger the following javascript function :
Link to other section

What I'd like to do is to have the javascript function triggered on page load when a specific variable is added to the URL. (Instead of having it as a link on the page)
For example, if url is www.mysite.com, page loads normally. If URL is www.mysite.com/?variable=1 , the script is triggered and user is redirected.
(I know there are other ways to redirect a user to another page, but I need to use this specific script, since the destination is dynamic from one type of user to another.)
I have very basic javascript knowledge and can't make the code I found here work : Triggering Script VIA URL . What they're doing is triggering a fancybox through URL variable. I believe that it's the same thing I want to achieve here. I'm just not to sure how to modify the code to go from "fancybox" to "redirectToOtherSection()"
   var $j = jQuery.noConflict();
$j(document).ready(function() {
    var url = window.location.href;
    url = url.toLowerCase();
    if (url.indexOf('globe=1') != -1) {
        $j("a#fancy").fancybox({
            'padding': 0,
            'overlayShow': false // extra comma removed
        });
    }
}); // extra curly bracket removed
$j("a#fancy").fancybox({
    'padding': 0,
    'overlayShow': false // extra comma removed
});

They are using jquery, not sure if jquery is needed in my case?
Any help is much appreciated!
Thanks

A: based on what you've said you dont need jquery, try
var url = window.location.href;
url = url.toLowerCase();
if (url.indexOf('variable=1') != -1) {  // where variable 1 is wqhats in you url
    redirectToOtherSection();
}


text:
Q: Recovering missing photos from older library Since Catalina Update, a lot of pictures are missing from Photos.
I have read about this issue that may be due to the library being used, however I would like to know if is there a way to move the photo left in an older library without loosing those in the current one. I have 4 devices synchronising photos to Icloud and don't want to mess everything!


text:
Q: Data type problems Can you  explain to me why this doesn't work:
#include <iostream>
using namespace std;

double data_convert(int n);

int main(void) {
    cout << data_convert(sizeof(int));
}

double data_convert(int n) {
    int i;
    double x;

    x = 8 * n;
    for(i = 0; i < 32; i++)
        x = x * 32;
    return x;
}

I tried using pow from cmath, but I got the same results. Apparently, this outputs "4.67681e+049". Where as it should output (using Windows Calculator) "4294967296".
The for loop is my own hardcoded pow() function for this specific task. All I wanna do is make a program that can show how big a data type is, along with it's range (bit range or something, yeah?)

A: If you want 2^32, you should be multiplying by 2 each time. Your code multiplies by 32 each time, so you'll end up with a much larger value.
Also, your x value should start from 1. 8 * n is actually the number of bits in the integer, so that should be your upper limit for the loop:
x = 1;
for (i = 0; i < 8 * n; i++)
  x = x * 2;
return x;

A simpler method would be to bitwise negate 0, which will give you the largest possible integer:
return ~0;

will give you 2^32 - 1 = 4294967295 (on a 32-bit machine).

A: Basically you are multiplying the input by 8 and are then multiplying that by 32, 32 times.
I don't understand what that is suppose to get you to.
If you want the range of an unsigned integer for x amount of bytes you should use this calculation:
max number = 2^(bytes*8) - 1
So in the loop it should multiply 2 until i goes from 0 to bytes*8 and stop there (So it ends before it gets to bytes*8)

A: I'm not sure what you're doing, but don't you meanx = x*2?


text:
Q: Field validation in magento registration form i am trying to validate a input field for email add of a specific domain and clearing the contents of the field when the condition is not met. But the input field is not cleared using the 'onblur' event. Here is my code :
<input type="text" name="email" onBlur="checkForm();" onSubmit="checkForm()"id="email_address" value="<?php echo $this->htmlEscape($this->getFormData()->getEmail()) ?>" title="<?php echo $this->__('Email Address') ?>" class="input-text validate-email required-entry" />
                        <?php echo "Enter a valid Sonata-software.com E-mail Id"?>

<script type="text/javascript">
    function validateEmail(elementValue){
       var emailPattern = /^[a-zA-Z0-9._-]+@sonata-software.com$/;
       return emailPattern.test(elementValue);
     }
    function clear(){
    document.getElementById("email_address").value = "";
    }
    function checkForm(){
        var emailId = document.getElementById('email_address').value;
        if(! validateEmail(emailId)) {
            alert("Enter a valid Sonata-software.com E-mail Id");
        clear();
                    }
    }
</script>

A: I did it simply by modifying two files:

*

*/public_html/app/design/frontend/YOURTEMPLATE/default/template/persistent/customer/form/register.phtml (added new_class here:<input type="text" name="email" id="email_address" value="<?php echo $this->htmlEscape($this->getFormData()->getEmail())? >" title="<?php echo $this->__('Email Address')? >" class="input-text validate-email required-entry new_class" />

*/public_html/js/prototype/validation.js (added new_class which looks like this:
['new_class', 'Only sonata-software.com accounts are allowed.', function (v) {
            return Validation.get('IsEmpty').test(v) || /^[a-zA-Z0-9._-]+@sonata-software.com$/.test(v)
        }],

Please tell me if it works for you.


text:
Q: 2 Columns with Fixed - Scrollable I have 2 columns and I need the first to be fixed, where the second has a long list and needs to be scrollable.

The Col-md-9 has the long list, and the Col-md-3 needs to be fixed. I've been trying for a while now to get this working but things keep breaking all the time.
When I try to position:fixed, the col-md-3 floats automatically left.
I tried to give everything width's and even removed the grid system from Bootstrap but I can't get it working.
I could hard code it like:

and

but this breaks responsiveness like hell...
@Edu Lomeli pointed out Affix Js. As the Bootstrap Documentation:

The subnavigation on the right is a live demo of the affix plugin.

and that's the EXACT behavior I'm looking for. The problem is I don't understand it fully.

A: Fixed it with Affix JS and by moving the Col-md-3 to the left

Take a look -----> Bootply

A: You need some extra definitions for position:fixed. To manage the left - right position for that element now, you have to use right,left,top,bottom css ports. For example:


text:
Q: index of a file in git has been deleted in Git Can someone tell me what does it mean when the index of a file in git has been deleted? Those files are flagged in red in my VS Code, but I still can modify the file and push the changes to a remote repository which will reflect those changes. I think this all happened when I cleared the cache in git with the command  "git rm --cached . " . I accidentally pushed the node_modules folder to the repo.

A: In this case, it sounds like you've deleted all the files from the index.  git rm --cached . does exactly that.  The index holds changes that are staged for commit, so next time you commit, you'll delete all the files from your repository.
That isn't very useful and it probably isn't what you wanted to do.  git rm --cached tells Git that you should leave the files you've mentioned (in this case, everything under the current directory and below) in the working tree, but stage them for deletion from Git.
Now that you've done that, you should look at what files are untracked, such as your node_modules folder.  Anything that you don't want Git to track and commit should be added to your .gitignore (for example, node_modules/).  Once you've listed all the patterns that you want to ignore in your .gitignore file, you'll want to run git add ., which will re-add all of the files to the index.
Then you can run git status and make sure that all the changes are the way you want them to be.  If you end up having added things that you still don't want, you can run git rm --cached FILE, where FILE is one or more files or directories that you specifically want to not commit.  You can then add appropriate entries to .gitignore that mention those paths.
Note that anything that's already staged in the index isn't affected by .gitignore, so you'll need to unstage it specifically (using a restricted git rm --cached) as mentioned above.


text:
Q: Remove special character ? from url with .htaccess I would like to redirect this url:
http://www.domena.pl/?tekst,123.html
to this
http://www.domena.pl/tekst,123.html
I just want to remove ? after first /, so I would like to redirect every url domena/?...... to domena/......
I was using this htaccess and it works for domena/testtekst,123, but I don't know how I should change it to work with special character ?
RewriteCond %{HTTP_HOST} ^www.domena.pl$
RewriteCond %{REQUEST_URI} ^/test(.*)$
RewriteRule ^test(.*)$ http://www.domena.pl/$1 [L,R=301]

This does not work:
RewriteCond %{HTTP_HOST} ^www.domena.pl$
RewriteCond %{REQUEST_URI} ^/?(.*)$
RewriteRule ^?(.*)$ http://www.domena.pl/$1 [L,R=301]

and this doesn't work too:
RewriteCond %{HTTP_HOST} ^www.domena.pl$
RewriteCond %{REQUEST_URI} ^/\?(.*)$
RewriteRule ^\?(.*)$ http://www.domena.pl/$1 [L,R=301]

A: You can use:
RewriteEngine On

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+\?([^\s&]+) [NC]
RewriteRule ^ /%1? [R=302,L,NE]


text:
Q: conditional sum over a range python I have created X as folowing
num_locations = 2
X= [ ]
for n in range(num_locations):
X.append([0 for j in range(num_locations)])

Now I want to sum these X[n][m] values for the case n != m . Such that the result should be like
X[0][1]+X[1][0]

Is there a way to do that with the sum formulation ?
X[n][m] for n in range(num_locations)for m in range(num_locations))

A: You can simply use enumerate
>>> sum(o for i, a in enumerate(X) for j, o in enumerate(a) if i!=j)
0

Where i and j are row (1st dim) and column (2nd dim) indices respectively

A: This is effectively taking the sum of the non-diagonal elements of your 2D array. One option using Numpy could simply be to subtract the sum of the main diagonal (np.trace) from the sum of the entire array.
num_locations = 2
X= [[1,2],[2,1]]

import numpy as np
s = np.sum(X) - np.trace(X)
print(s)

Outputs:
4

A: This should work
sum([sum(row) - (row[i] if len(row) < i else 0) for i,row in enumerate(X)])

It runs over every row in the 2d array, and sums it, then take out the i cell (if exists) so it won't get into sum


text:
Q: Deny NTFS permission How can I deny NTFS permission (permission to Write for some user)?
I have to prove it with Get-NTFSAccess, so I can't use Remove-NTFSAccess.
I'm using PowerShell.

A: I found a solution:
Add-NTFSAccess -Account "User X" -Path PathToFile -AccessRights write -AccessType Deny


text:
Q: Enable multi-currency support on a custom WooCommerce product builder With Woocommerce, I use a visual product builder that allow my client to build their own products and I need multi-currency support. The problem is that I can't use multi-currency plugin, because the visual builder doesn't support it.
My question is: How to modify the price of the cart for other currency?
I need for example to modify final cart price like this:

*

*10€ > 15$

*20€ > 20$

Thank you very much.

A: I would suggest you to try this free version of the plugin
https://wordpress.org/plugins/woo-multi-currency/
instead of writing from scratch and make further changes as required to this plugin.
Hope this helps.


text:
Q: Wit AI and asynchronous functions I am following the Wit AI tutorial and I got to a point where I am stuck.
I am trying to extend the quick start weather tutorial to call an actual weather API and I am having no luck.
Here is my modified getForecast method. The original can be found here: https://wit.ai/docs/quickstart

 var weather = require('weather-js');

    const actions = {
  send(request, response) {
    const {sessionId, context, entities} = request;
    const {text, quickreplies} = response;
    console.log('sending...', JSON.stringify(response));
  },
  getForecast({context, entities}) {
    var location = firstEntityValue(entities, 'location');
    weather.find({search: location, degreeType: 'F'}, function(err, result) {
        if(err){
            context.missingLocation = true;
            delete context.forecast;
        }else{
            var temperature = result[0].current.temperature;
            context.forecast = temperature+ ' degrees in '+location; // we should call a weather API here
            delete context.missingLocation;
            fs.writeFile("weather.json",JSON.stringify(result));
        }
        return context;
    });
  },
};

A: So you want to do a synchronous call to weather api but node doesn't encourage it. The way to get a synchronous call is to use Promises.
Ref - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
Also below is the link to wit's own implementation of weather bot, you can see how promises are used
https://github.com/wit-ai/witty-weather/blob/master/src/createEngine.js


text:
Q: Prove that $(a, \infty) \subseteq [b, \infty) \iff a \ge b$ This is exercise 10 - Problems II - of the book "Introduction to Mathematical Reasoning" by Peter J. Eccles.

We define half-infinite intervals as follows:
  \begin{align}
(a, \infty) & = \{x \in \mathbb{R} | x \gt a\} \\
[a, \infty) & = \{x \in \mathbb{R} | x \ge a\} \\
\end{align}
Prove that $(a, \infty) \subseteq [b, \infty) \iff a \ge b$

I would like to confirm that my proof is indeed correct. In particular, I'm concerned with the first part (on the necessity of $a \ge b$).
Proof of $\Rightarrow$: Suppose that $(a, \infty) \subseteq [b, \infty)$. Then for $x \in \mathbb{R}$, $x \in (a, \infty) \implies x \in [b, \infty)$, i.e. $x \gt a \implies x \ge b$.
$\require{enclose}\enclose{horizontalstrike}{It\ follows\ that\ a\ \ge\ b.\ }$ But $(a, \infty) \subseteq [b, \infty) \implies [a, \infty) \subseteq [b, \infty)$, so that $a \in [a, \infty) \implies a \in [b, \infty)$ and we have $a \ge b$ as required.
Proof of $\Leftarrow$: Conversely, let $a \ge b$. Then given $x \in \mathbb{R}$, $x \gt a \implies x \gt b$ and so certainly $x \ge b$.
Thus $(a, \infty) \subseteq [b, \infty)$ as required.
$\tag*{$\square$}$

EDIT:
I've improved the proof of $\Rightarrow$ as best as I can following the advice I was given, both in comments and answers.
However, I would appreciate if someone could demonstrate $(a, \infty) \subseteq [b, \infty) \implies [a, \infty) \subseteq [b, \infty)$ without using pictures, as that was the only way I could see it was true.
Thank you.

A: For the sake of perfect completeness, you might want to show why $x > a \Rightarrow x \geq b$ implies that $a > b$.

A: For the first part, show that $a<b\implies (a,\to)\not \subset [b,\to).$  Observe that $$a<b \implies a<(a+b)/2<b \implies (a+b)/2 \in (a,\to)\; \backslash  \;[b,\to).$$


text:
Q: Priority Queue Wrong Order I am programming the huffman encoding. This is the beginning of my program:
using namespace std;

//Counting methods
int *CountCharOccurence(string text)
{
    int *charOccurrence = new int[127];
    for(int i = 0; i < text.length(); i++)
    {
        charOccurrence[text[i]]++;
    }
    return charOccurrence;
}

void DisplayCharOccurence(int *charOccurrence)
{
    for(int i = 0; i < 127; i++)
    {
        if(charOccurrence[i] > 0)
        {
            cout << (char)i << ": " << charOccurrence[i] << endl;
        }
    }
}

//Node struct
struct Node
{
    public:
        char character;
        int occurrence;

        Node(char c, int occ) {
            character = c;
            occurrence = occ;
        }

        bool operator < (const Node* node)
        {
            return (occurrence < node->occurrence);
        }
};

void CreateHuffmanTree(int *charOccurrence)
{
    priority_queue<Node*, vector<Node*> > pq;
    for(int i = 0; i < 127; i++)
    {
        if(charOccurrence[i])
        {
            Node* node = new Node((char)i, charOccurrence[i]);
            pq.push(node);
        }
    }

    //Test
    while(!pq.empty())
    {
        cout << "peek: " << pq.top()->character <<  pq.top()->occurrence << endl;
        pq.pop();
    }
}

int main(int argc, char** argv) {

    int *occurrenceArray;
    occurrenceArray = CountCharOccurence("SUSIE SAYS IT IS EASY");
    DisplayCharOccurence(occurrenceArray);
    CreateHuffmanTree(occurrenceArray);

    return (EXIT_SUCCESS);
}

The program first outputs the characters with their occurence number. This looks fine:
 : 4
A: 2
E: 2
I: 3
S: 6
T: 1
U: 1
Y: 2
but the test loop which has to display the node contents in priority order outputs this:
peek: Y2
peek: U1
peek: S6
peek: T1
peek: I3
peek: E2
peek:  4
peek: A2
This is not the expected order. Why?

A: Elements in your priority queue are pointers. Since you don't provide a function that takes 2 pointers to Node objects , default compare function compares 2 pointers.
bool compareNodes(Node* val1, Node* val2)
{
   return val1->occurence < val2->occurence;
}
priority_queue<Node*, vector<Node*>,compareNodes > pq;

Your operator < is used when Node compares with Node*

A: You should tell your priority queue what it should sort by. In your case, you have to tell it to sort by Node::occurence.

A: You are storing pointers to nodes in the queue, but haven't provided a suitable comparison function, so they are sorted by comparing the pointers. The operator< you've provided will compare a node with a pointer, which isn't what you want.
There are two options:

*

*Provide a function for comparing two node pointers according to their values, and give this function to the queue, or

*Store node objects in the queue, and provide an operator< to compare two nodes.

The second option will also fix the memory leak in your code, and remove a whole pile of unnecessary memory allocations, so I would suggest that.


text:
Q: H2 vs PostgreSQL generated column with function I'm trying to setup a generated column which will also take null checks into consideration when subtracting values. In PostgreSQL I did:
ALTER TABLE session ADD COLUMN
    duration INTERVAL GENERATED ALWAYS AS age(time_ended, time_started) STORED;

H2 doesn't support age function so I another patch to create alias to function:
CREATE ALIAS age FOR "net.agileb.config.H2Functions.age";

and corresponding java code:
package net.agileb.config;

import java.time.Duration;
import java.time.LocalDateTime;

public class H2Functions {
    public static Duration age(LocalDateTime endDate, LocalDateTime startDate) {
        return Duration.between(endDate, startDate);
    }
}

I run H2 in PostgreSQL compatibility mode:
    public:
      type: com.zaxxer.hikari.HikariDataSource
      url: jdbc:h2:mem:agileb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL;
      driverClassName: org.h2.Driver

but h2 still doesn't like the syntax of the generated column:
SQL State  : 42001
Error Code : 42001
Message    : Syntax error in SQL statement "ALTER TABLE SESSION ADD COLUMN
    DURATION INTERVAL GENERATED[*] ALWAYS AS AGE(TIME_ENDED, TIME_STARTED) STORED"; expected "YEAR, MONTH, DAY, HOUR, MINUTE, SECOND"; SQL statement:
ALTER TABLE session ADD COLUMN
    duration INTERVAL GENERATED ALWAYS AS age(time_ended, time_started) STORED [42001-200]
Location   : db/migration/V1606395529__topic_calculated_duration_column.sql (/home/agilob/Projects/springowy/build/resources/main/db/migration/V1606395529__topic_calculated_duration_column.sql)
Line       : 3
Statement  : ALTER TABLE session ADD COLUMN
    duration INTERVAL GENERATED ALWAYS AS age(time_ended, time_started) STORED

I understand H2 wants me to use specific interval like INTERVAL SECOND, generated as identity and STORED keyword doesn't seem to be supported.
Is there a way to make this query work in PostgreSQL and H2?

A: There is no way to use the same syntax for generated columns in PostgreSQL and H2.

*

*INTERVAL data type without interval qualifier is a feature of PostgreSQL. Other DBMS, including the H2, support only standard-compliant intervals such as INTERVAL YEAR, INTERVAL YEAR(3) TO MONTH, INTERVAL DAY TO SECOND, etc. Hopefully, you can use standard-compliant interval data types in PostgreSQL too, they are also supported. But all these types a either year-month intervals or daytime intervals. Interval with YEAR and/or MONTH fields can't have DAY, HOUR, MINUTE, or SECOND fields and vice versa. If you really need a mixed interval with all these fields, you can use only the PostgreSQL and its forks.

*H2 1.4.200 supports only non-standard syntax for generated columns with AS keyword (upcoming H2 2.0 also supports the standard syntax GENERATED ALWAYS AS). PostgreSQL doesn't support non-standard syntax from H2. You can build H2 from its current sources to have the possibility to use the same standard syntax here.

*The biggest problem is that PostgreSQL requires non-standard STORED clause at the end of definition of generated column for a some weird reason and doesn't accept standard-compliant definitions of columns. H2 and others don't have and don't accept this clause.
So the only solution here is to use different SQL for PostgreSQL and for H2.


text:
Q: Unir dos dataFrame pandas Tengo el siguiente código:
import random
import pandas as pd
from datetime import datetime

inicio = datetime(2017, 1, 30)
final =  datetime(2019, 3, 21)

datos = []

for i in range (0, 10000):
    datos.append(inicio + (final - inicio) * random.random())

df = pd.DataFrame(datos)

df.rename(columns={0: "Fecha"}, inplace=True)

procesos = []

for a in range (1, 11):
    procesos.append('Proceso' + str(a))

total = 0

proceso = []

for i in range (0, 10):
    for j in range ( 0, 1000):
        proceso.append(procesos[total])
    total += 1

datosProceso = pd.DataFrame(proceso)

datosProceso.rename(index=str, columns={0: "Proceso"}, inplace=True)

Esto crea dos df con 10.000 datos aleatorios, uno tiene 10.000 fechas y el otro tiene 10.000 datos de procesos separados en 10 procesos aleatorios o sea 1000 datos de proceso1, 1000 datos de proceso2, etc.

Ahora como podria unir los dos dataframe en uno solo que tenga dos columnas, procesos y fechas, probe agregando ids, con concat pero lo tira abajo, join me da error, etc.
Sin usar los dos DF que se arman rápido lo hago de esta forma pero que tarda 2 a 3 min porque va linea a linea en la posición suplantando el valor ademas de que tira SettingWithCopyWarning:
import random
import pandas as pd
from datetime import datetime

inicio = datetime(2017, 1, 30)
final =  datetime(2019, 3, 21)

datos = []

for i in range (0, 10000):
    datos.append(inicio + (final - inicio) * random.random())

df = pd.DataFrame(datos)

df.rename(columns={0: "Fecha"}, inplace=True)

df['proceso'] = ''

procesos = []
for a in range (1, 11):
    procesos.append('Proceso' + str(a))

total = 0
posicion = 0

for i in range (0, 10):
    for j in range ( 0, 1000):
        df['proceso'][posicion] = procesos[total]
        print(posicion)
        posicion += 1
    total += 1

A: Lo que complica es el índice de los dos dataframes al ser distintos las opciones de merge no funcionan como lo quisiéramos en estos casos. Lo que se puede hacer es inicializar el índice de los dos data.frame a un simple número secuencial, cosa que podemos hacer con reset_index()
result = pd.merge(df.reset_index(),
                  datosProceso.reset_index(),
                  left_index=True,
                  right_index=True)

Conceptualmente, de esta forma, los dos dataframes terminan teniendo un mismo índice (1:9999) con lo cual ahora sí, el merge() hace lo que esperamos: unir secuencialmente ambos dataframes.


text:
Q: D3v6 convex hull examples Recently I noticed the convex hull possibilities in D3. For example this one:

var w = 960,
    h = 500,
    fill = d3.scale.category10(),
    nodes = d3.range(9).map(Object);

var groups = d3.nest().key(function(d) { return d & 3; }).entries(nodes);

var groupPath = function(d) {
    var fakePoints = [];
    if (d.values.length == 2)
    {
        //[dx, dy] is the direction vector of the line
        var dx = d.values[1].x - d.values[0].x;
        var dy = d.values[1].y - d.values[0].y;

        //scale it to something very small
        dx *= 0.00001; dy *= 0.00001;

        //orthogonal directions to a 2D vector [dx, dy] are [dy, -dx] and [-dy, dx]
        //take the midpoint [mx, my] of the line and translate it in both directions
        var mx = (d.values[0].x + d.values[1].x) * 0.5;
        var my = (d.values[0].y + d.values[1].y) * 0.5;
        fakePoints = [ [mx + dy, my - dx],
                      [mx - dy, my + dx]];
        //the two additional points will be sufficient for the convex hull algorithm
    }

    //do not forget to append the fakePoints to the input data
    return "M" +
        d3.geom.hull(d.values.map(function(i) { return [i.x, i.y]; })
                     .concat(fakePoints))
        .join("L")
        + "Z";
}

var groupFill = function(d, i) { return fill(i & 3); };

var vis = d3.select("#chart").append("svg")
    .attr("width", w)
    .attr("height", h);

var force = d3.layout.force()
    .nodes(nodes)
    .links([])
    .size([w, h])
    .start();

var node = vis.selectAll("circle.node")
    .data(nodes)
  .enter().append("circle")
    .attr("class", "node")
    .attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; })
    .attr("r", 8)
    .style("fill", function(d, i) { return fill(i & 3); })
    .style("stroke", function(d, i) { return d3.rgb(fill(i & 3)).darker(2); })
    .style("stroke-width", 1.5)
    .call(force.drag);

vis.style("opacity", 1e-6)
  .transition()
    .duration(1000)
    .style("opacity", 1);

force.on("tick", function(e) {

  // Push different nodes in different directions for clustering.
  var k = 6 * e.alpha;
  nodes.forEach(function(o, i) {
    o.x += i & 2 ? k : -k;
    o.y += i & 1 ? k : -k;
  });

  node.attr("cx", function(d) { return d.x; })
      .attr("cy", function(d) { return d.y; });

  vis.selectAll("path")
    .data(groups)
      .attr("d", groupPath)
    .enter().insert("path", "circle")
      .style("fill", groupFill)
      .style("stroke", groupFill)
      .style("stroke-width", 40)
      .style("stroke-linejoin", "round")
      .style("opacity", .2)
      .attr("d", groupPath);
});

Unfortunately its version 3 and I am searching for similar layouts made with version 6. I tried to adapt the code but most of functions changed completely, which makes it hard to adapt snippets.
In case somebody stumpled over similar D3v6 snippets, I would be glad.
UPDATE:
In addition I found this convex hull example, which use version 4. Still, both version require the d3.nest() functions. I was building a version 6 prototyp for d3.group() / d3.groups() testing, to receive the same output as d3.nest(). Unfortunately without success. Below the version 4 hull example.

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>D3v4 hull</title>

A: Good research finding a v4 version of that force directed graph with convex hull groupings.
To convert to v6 is just a couple more steps:
As you know, replace d3.nest with d3.groups - but the missing step is to convert the output of d3.groups from an array of arrays to an array of objects. So this:
groups = d3.groups(
  net.nodes,
  d => d.group
).map(x => ({key: x[0], values: x[1]}));

Is equivalent to this:
groups = d3.nest()
  .key(function (d) { return d.group; })
  .entries(net.nodes);

Then go through all the event handlers and update them so event is passed as an argument and drop the d3. wherevere you see d3.event.
This seems to work pretty well:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>D3v4 hull</title>


text:
Q: How to compare Between two arrays and check if all items in one are in the second? I have two arrays with values
a = [1,2,3,4,5];
b = [1,3,5];

if all items from b are in a so i want to return true
another example
a = [123,55,12,66]
b = [123,551]

will return false because 551 is not in a
i tried  to go over all items in b and return false if i get an item that isn't in a.

A: Use .every() with .indexOf().
b.every(function(n) {
    return a.indexOf(n) > -1;
});

You can also create a reusable function, and set the second argument to the array to search.
function itemIsInThis(n) {
    return this.indexOf(n) > -1;
}

And use it like this:
b.every(itemIsInThis, a);

The second argument to .every() (and most other Array iteration methods) will set the this value of the callback, so here we just set this to the a array.

A: A simple loop is all you need
function allIn(needles, haystack) {
    var i = needles.length;
    while (i--) // loop over all items
        if (haystack.indexOf(needles[i]) === -1) // normal existence check
            return false; // failed test
    return true; // none failed test
}

var a, b;
a = [1,2,3,4,5];
b = [1,3,5];
allIn(b, a); // true

a = [123,55,12,66];
b = [123,551];
allIn(b, a); // false

A: You can intersect the arrays and compare the result:
Array.prototype.intersect = function (arr1) {

    var r = [], o = {}, l = this.length, i, v;
    for (i = 0; i < l; i++) {
        o[this[i]] = true;
    }
    l = arr1.length;
    for (i = 0; i < l; i++) {
        v = arr1[i];
        if (v in o) {
            r.push(v);
        }
    }
    return r;
};

Array.prototype.containsAll = function (arr) {
    return arr.intersect(this).length === arr.length;
};

var a = [123,55,12,66],
    b = [123,551],
    c = [1,2,3,4,5],
    d = [1,3,5];

console.log(c.containsAll(d), a.containsAll(b));

http://jsfiddle.net/bgK5q/

A: You can use $.grep and $.inArray to be more jQuery'ish
$.grep(b, function(el) {return $.inArray(el, a)!=-1});

and to return a boolean compare the length
b.length == $.grep(b, function(el) {return $.inArray(el, a)!=-1}).length;

FIDDLE


text:
Q: Название файла из значения переменной Ночи! В связи с расширением функционала приложения появилась необходимость сохранять результат работы программы в небольшой текстовый отчет, для чего использую такую функцию:
def save_report():
    filepath = asksaveasfilename(
        defaultextension="txt",
        filetypes=[("Текстовые файлы", "*.txt"), ("HTML файлы", "*.html")]
    )
    if not filepath:
        return
    with open(filepath, "w", encoding="UTF-8") as output_file:
        pt_name = patientName_entry.get()
        pt_date = patientDate_entry.get()
        pt_sex = patientSelectSex.get()

        vl_manifestation = manifestationSelect.get()
        vl_hearth = hearthSelect.get()
        vl_transformation = transformationSelect.get()
        vl_deficit = deficitSelect.get()
        vl_infarct = infarctSelect.get()
        vl_thrombolysis = thrombolysisSelect.get()

        vl_conclusion = conclusion.cget("text")

        locale.setlocale(locale.LC_ALL, '')
        report_date = datetime.now()
        report_date = report_date.strftime('%d %B %Y')

        text_report = (
            f'Assessing the risk of surgical intervention in stroke (ARSiS) report.\n'
            f'=====================================================================\n'
            f'отчет сформирован: {report_date}\n\n'
            f'ПАЦИЕНТ:\n{pt_name}\n'
            f'Дата рождения: {pt_date}\n'
            f'Пол: {pt_sex}\n'
            f'---------------------------------------------------------------------\n\n'
            f'АНАМНЕЗ / ДАННЫЕ ИССЛЕДОВАНИЙ:\n'
            f'1. Время с момента манифестации первых симптомов неврологического дефицита:\n'
            f'   -> {vl_manifestation}\n\n'
            f'2. Очаг ишемического инсульта в любом из диаметров, по данным КТ или МРТ головного мозга:\n'
            f'   -> {vl_hearth}\n\n'
            f'3. Геморрагическая трансформация ишемического очага в головном мозге:\n'
            f'   -> {vl_transformation}\n\n'
            f'4. Неврологический дефицит:\n'
            f'   -> {vl_deficit}\n\n'
            f'5. Острый инфаркт миокарда:\n'
            f'   -> {vl_infarct}\n\n'
            f'6. Состояние после тромболитической терапии:\n'
            f'   -> {vl_thrombolysis}\n'
            f'---------------------------------------------------------------------\n\n'
            f'ЗАКЛЮЧЕНИЕ:\n'
            f'{vl_conclusion}'
        )
        output_file.write(text_report)

Все прекрасно работает, но я хотел бы что бы при сохранении в файл, название автоматически формировалось из значений переменных patientName_entry и patientDate_entry. Сами переменные это текстовые поля, куда пользователь вручную вводит данные. Должно получится как-то так:

Но как такое реализовать не понимаю. В качестве ориентира использовал материал этого вопроса.

A: Обратите внимание на initialfile= и initialdir= в Native Load/Save Dialogs:
from tkinter.filedialog import asksaveasfilename

patientName_entry = "Иванов Иван Иванович"
patientDate_entry = "12.12.1980"

f = asksaveasfilename(
    defaultextension="txt",
    filetypes=[("Текстовые файлы", "*.txt"), ("HTML файлы", "*.html")],
    initialfile=f'{patientName_entry} {patientDate_entry}.txt'
)

print(repr(f))

A: Благодаря ответу Stanislav Volodarskiy, удалось добиться поставленной цели. Ниже работающая функция. Может кому-то пригодится.
def save_report():
    pt_name = patientName_entry.get()
    pt_date = patientDate_entry.get()
    pt_sex = patientSelectSex.get()

    vl_manifestation = manifestationSelect.get()
    vl_hearth = hearthSelect.get()
    vl_transformation = transformationSelect.get()
    vl_deficit = deficitSelect.get()
    vl_infarct = infarctSelect.get()
    vl_thrombolysis = thrombolysisSelect.get()

    vl_conclusion = conclusion.cget("text")

    locale.setlocale(locale.LC_ALL, '')
    report_date = datetime.now()
    report_date = report_date.strftime('%d %B %Y')

    filepath = asksaveasfilename(
        defaultextension="txt",
        filetypes=[("Текстовые файлы", "*.txt"), ("HTML файлы", "*.html")],
        initialfile=f'{pt_name} {pt_date}.txt'
    )

    if not filepath:
        return
    with open(filepath, "w", encoding="UTF-8") as output_file:

        text_report = (
            f'Assessing the risk of surgical intervention in stroke (ARSiS) report.\n'
            f'=====================================================================\n'
            f'отчет сформирован: {report_date}\n\n'
            f'ПАЦИЕНТ:\n{pt_name}\n'
            f'Дата рождения: {pt_date}\n'
            f'Пол: {pt_sex}\n'
            f'---------------------------------------------------------------------\n\n'
            f'АНАМНЕЗ / ДАННЫЕ ИССЛЕДОВАНИЙ:\n'
            f'1. Время с момента манифестации первых симптомов неврологического дефицита:\n'
            f'   -> {vl_manifestation}\n\n'
            f'2. Очаг ишемического инсульта в любом из диаметров, по данным КТ или МРТ головного мозга:\n'
            f'   -> {vl_hearth}\n\n'
            f'3. Геморрагическая трансформация ишемического очага в головном мозге:\n'
            f'   -> {vl_transformation}\n\n'
            f'4. Неврологический дефицит:\n'
            f'   -> {vl_deficit}\n\n'
            f'5. Острый инфаркт миокарда:\n'
            f'   -> {vl_infarct}\n\n'
            f'6. Состояние после тромболитической терапии:\n'
            f'   -> {vl_thrombolysis}\n'
            f'---------------------------------------------------------------------\n\n'
            f'ЗАКЛЮЧЕНИЕ:\n'
            f'{vl_conclusion}'
        )
        output_file.write(text_report)


text:
Q: Notification : my Update receiver not call I new for the notification.I don't find any help for this please help me.Thank you in advance.I have to show notification in android app but It does not get call to my broadcast receiver though I added permission in manifest
<Service android:name="com.example.tajgroup.newsapplication.service.NotificationService"
            android:enabled="true"/>

        <receiver android:name=".reciever.UpdateReciever">
            <intent-filter>
                <action android:name="android.net.com.CONNECTIVITY_CHANGE" />
            </intent-filter>
            /></receiver>

and my NotificationService and UpdateReciever are

public class UpdateReciever extends BroadcastReceiver {
        ConnectivityManager connectivityManager;
        NetworkInfo networkInfo;
        String dateString;

        public static NotificationManager mNotificationManager;
        public static int SIMPLE_NOTFICATION_ID;

        static Intent serviceintent;

        @Override
        public void onReceive(Context context, Intent intent) {

                if (!isNetworkAvailable(context)) {
                        // Notification(context, "Wifi Connection Off");

                } else {

                        serviceintent = new Intent(context, NotificationService.class);
                        context.startService(serviceintent);
                        context.stopService(serviceintent);

                }
        }

        // Check for network availability
        private boolean isNetworkAvailable(Context context) {
                ConnectivityManager connectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo activeNetworkInfo = connectivityManager
                        .getActiveNetworkInfo();
                return activeNetworkInfo != null;
        }

}

public class NotificationService extends Service {
    ConnectivityManager connectivityManager;
    NetworkInfo networkInfo;
    NotificationService notification;
    String dateString,Name;
    Categories categories;

    ArrayList<String> a = new ArrayList<String>();
    public static int SIMPLE_NOTFICATION_ID;
    private Context _context;
    long count, cnt, date1;
    int flag = 0;
    public static NotificationManager mNotificationManager;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        /*Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG)
                .show();*/

    }

    @Override
    public void onStart(Intent intent, int startId) {

        //Toast.makeText(getApplicationContext(), "Service Stared", Toast.LENGTH_SHORT).show();
        date1 = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        dateString = sdf.format(date1);
        System.out.println("Ntification item1 = " + dateString);
        //dateString="07/11/2014";
        notification();
    }

    @Override
    public void onDestroy() {
        //Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();

    }

    private void notification(){

        final RestAdapter adapter = new RestAdapter.Builder()
                .setEndpoint(Config.url)
                .build();

        MainActivityInterface api = adapter.create(MainActivityInterface.class);

        api.Test(
                new Callback<Response>() {
                    @Override
                    public void success(Response result, Response response) {
                        BufferedReader reader = null;
                        String message = "";
                        String output = "";

                        try {
                            reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
                            output = reader.readLine();
                            JSONTokener tokener = new JSONTokener(output);

                            JSONObject json = new JSONObject(tokener);
                            JSONArray jsonArray = json.getJSONArray("story");

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                int id = jsonObj.getInt("id");
                                String title = jsonObj.getString("title");
                                String content = jsonObj.getString("content");
                                String picture = jsonObj.getString("picture");
                                String saved_file_name = jsonObj.getString("saved_file_name");
                                String status = jsonObj.getString("status");
                                String start_date = jsonObj.getString("start_date");
                                String end_date = jsonObj.getString("end_date");
                                String created_at = jsonObj.getString("created_at");
                                String updated_at = jsonObj.getString("updated_at");

                                categories = new Categories(id,title,content,picture,saved_file_name,status,start_date,end_date,created_at,updated_at);

                                   String[] items = categories.getUpdated_at().split(" ");
                                   String date1, time;
                                   date1 = items[0];
                                   time = items[1];
                                   System.out.println("item = " + updated_at);
                                System.out.println("noti item1 = " + date1);

                                if(date1.equals(dateString)) {
                                   notification = new NotificationService();
                                   Name = categories.getTitle();
                                   a.add("\n" + Name);
                               }
                            }

                            notification.Notification(NotificationService.this," \n" + a);

                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void failure(RetrofitError error) {

                        Toast.makeText(NotificationService.this, error.toString(), Toast.LENGTH_LONG).show();

                    }
                }
        );
    }

    void Notification(Context context, String message) {
        // TODO Auto-generated method stub
        // Set Notification Title
        String strtitle = context.getString(R.string.app_name);
        // Open NotificationView Class on Notification Click
        Intent intent = new Intent(context, MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        // Create Notification using NotificationCompat.Builder
        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                context)
                // Set Icon
                .setSmallIcon(R.drawable.pen_50px)
                // Set Ticker Message
                .setTicker(message)
                // LED
                .setLights(Color.RED, 3000, 3000)

                // Set Title
                .setContentTitle(context.getString(R.string.app_name))
                // Set Text
                .setContentText(message)
                // Add an Action Button below Notification
                .addAction(android.R.drawable.ic_menu_more, "Click to Check", pIntent)
                // Set PendingIntent into Notification
                .setContentIntent(pIntent)
                // Dismiss Notification
                .setAutoCancel(true);

        // Create Notification Manager
        NotificationManager notificationmanager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        // Build Notification with Notification Manager
        notificationmanager.notify(0, builder.build());

    }
}

A: It may need SelfCheckPermission. What API level are you working on?


text:
Q: Solving a quintic function for zero I got this  question on my homework and I cannot for the life of me figure out how to solve for $0$.
$$x^5+2x-10=0$$
I have tried this every which way and this is my last resort. Thanks in advanced.

A: Your polynomial has a unique real solution which you can estimate numerically to be around $1.478$. PARI computes the Galois group to be $S_5$, which means that you can't express this solution with radicals (roots).

A: Differentiate and you will see that the function $f(x) = x^5+2x-10$ is strictly increasing.
It is easy to see that $\lim_{x \to -\infty} f(x) = -\infty$ and
$\lim_{x \to \infty} f(x) = \infty$, so there is exactly one root.
Since $f(0) <0$ and $f(2) >0$ we see that the root lies in $(0,2)$.
You can use bisection to find a numerical approximation to the root.
Using 10 iterations of the bisection method starting with the interval $[0,2]$
gives the bracket $(1.4765625, 1.478515625)$.

A: If $$f(x)=x^5+2x-10$$ $$f'(x)=5x^4+2 >0$$ so there is only one real root since the function varies from $-\infty$ to $+\infty$ because of $x^5$.
By inspection, you can notice that $f(1)=-7$ and $f(2)=+26$ so the solution is between $1$ and $2$.
To find the solution, Newton method is quite simple : starting from a "reasonable" guess $x_0$, the method will update it according to $$x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)}$$ In the present case, this will the simply write $$x_{n+1}=\frac{4 x_n^5+10}{5 x_n^4+2}$$ Let us be lazy and start at the middle of the interval  then using $x_0=1.5$. This will generate the following iterates : $1.47826$, $1.47765$ which is the solution for six significant digits.
Edit
You could get a quite accurate approximation using Taylor series built at $x=\frac 32$. Limited to second order, this gives $$x^5+2x-10=\frac{19}{32}+\frac{437}{16} \left(x-\frac{3}{2}\right)+\frac{135}{4}
   \left(x-\frac{3}{2}\right)^2+O\left(\left(x-\frac{3}{2}\right)^3\right)$$ and the solution of the quadratic is $$\frac{1183+\sqrt{170449}}{1080}\approx 1.477643$$ while the exact solution is $\approx 1.477653$.

A: Just for completeness. The real solution of this equation can be expressed in terms of a generalized hypergeometric function
$$
5 \, {}_4F_3\!\left(\frac{1}{5},\frac{2}{5},\frac{3}{5},\frac{4}{5};\frac{1}{2},\frac{3}{4},\frac{5}{4};-\frac{1953125}{512}\right).$$


text:
Q: Wrap an object with borders without changing properties or flow I'd like to wrap an object when moused over in a border so that it is visible, however, this will be used in a WYSIWYG type editor so adding styles directly to the object would break it. I'd like to wrap it in a div and style that div without actually changing the flow of the page.
I thought to create a div then position it relative while creating four divs within it to act as borders and position:absolute so it would not change any flow.
HTML:

JavaScript with Jquery
$("div").mouseover(function(){
    $(this).wrap('

')
    .parent()
    .append('

')
    .append('

')
    .append('

')
    .append('<div class="displayNodes" style="width:1px;height:100%;position:absolute;background-color:#66f;right:0;bottom:0"
')
     })
.mouseout(function()
          {
              $(".displayNodes").remove();
              $(this).unwrap();
          });

and my CSS
.bigBox
{
    height:300px;
    position:relative;
    background-color:black;
}
.innerBox
{
    height:25px;
    width:300px;
    position:absolute;
    background-color:green;
    right:4px;
    top:15px;
}

.floatingBox
{
    position:absolute;
    width:300px;
    height:25px;
    background-color:red;
    top:400px;
}

I set up a JSFiddle: http://jsfiddle.net/94Nrb/3/
This method works great for normally positioned boxes, however, when the object is absolute or relative it messes things up since it's parent is moving, anyone have any ideas on this?
Edit: I had a slight mistake with the fiddle, updated to what it should be as version 3 http://jsfiddle.net/94Nrb/3/


text:
Q: Javascript button disable and enabled using for particular time newbie to java script , I want to do like when any one click on first Button,then second button is disabled for 30 seconds , after the enabled of second button, click on second button and third button visible to the user. I know simple disable enable buttons on tutorials Thanks.
<!DOCTYPE html>

<input type="button" id="myBtn" value="My Button">

Click the button below to disable the button above.

<button onclick="myFunction()">Try it</button>

A: Use setTimeout function to do it.

Hope it works.

A: Use setTimeout() function and variables to flag click status:
 setTimeout("myFunction();", 30000);

A: see this plunker http://embed.plnkr.co/ZUmGoGEr2TYHlfPhUJgK/preview
<!DOCTYPE html>

<input type="button" id="myBtn" value="My Button"  onclick="document.getElementById('thirdBtn').style.display='block'">
<input type="button" style="display:none;" id="thirdBtn" value="Third Button">

Click the button below to disable the button above.

<button onclick="myFunction()">Try it</button>


text:
Q: ConnectionException in Camel when trying to conenction to local SMTP server I have a local SMTP server, implemented in the Python core scripts, which simply prints the body of the email received :
python -m smtpd -n -c DebuggingServer localhost:3333. (on Windows)

When I telnet localhost 3333, the connection succeeds and I can send an email using SMTP.
However, when I build (via Java DSL) a route with an endpoint producer to this same address, the connection fails and sends an exception
.to("smtp://localhost:3333");

Part of the exception is :
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 3333;
  nested exception is:
    java.net.ConnectException: Connection refused: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
    at javax.mail.Service.connect(Service.java:295)
    at org.apache.camel.component.mail.DefaultJavaMailSender.send(DefaultJavaMailSender.java:111)
    at org.apache.camel.component.mail.MailProducer.process(MailProducer.java:56)

Any idea on what is going on ? The process hosting the CamelContext is on the same machine as the telnet client.

A: Can you check will it work if you will use "127.0.0.1" instead of "localhost"?


text:
Q: Ordering vector lists in Python I have a list with several registers from other lists. I put an index at the beginning of each element so that I can order it later, for writing purposes.
reg = index + ";" + cell[1] + ";" + hour + ";" + cell[0] + ";" + text[1] + ";"

At the end, reg should give something like this:
['5;01;11.32;RN_RT;Prep;', '9;02;2.12;ING;Prep;', '1;06;4.23;ING;Rec;']

Is there a way to order/sort it using the index at the beginning?

A: Sort with key=lambda s: int(s.split(';', 1)[0]).

A: You can write a small helper function:
def by_index(x):
    return int(x.split(';', 1)[0])

and use it for sorting:
L = ['5;01;11.32;RN_RT;Prep;','9;02;2.12;ING;Prep;','1;06;4.23;ING;Rec;']

sorted(L, key=by_index)

['1;06;4.23;ING;Rec;', '5;01;11.32;RN_RT;Prep;', '9;02;2.12;ING;Prep;']

The function sorted() takes the keyword argument key:

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

This function is called for each element in the list. So:
int(x.split(';', 1)[0])

splits off the value before the first ; and turns it into an integer. This is the index. This index will be used for sorting (the sorting key) but the sort result is the list elements in the order of the index.
lambda is just another way to define a function without using def. It is limited to expressions but can be used inline.


text:
Q: How to include var in partials calls Let's say I have a website where for each main section I have a specific sidebar.
Currently I have a single sidebar file, where im using categories to filter the correct content to show like this:
   {{#inArray page.categories "Components"}}

        DetailContent

However my goal is to have these sidebar files located at each section folder, along with the section files.
How can I include the {{dirname}} variable in the partials call {{> sidebar}}?

A: This should be possible with a conditional block helper, like {{with}} and the include helper,
B you could also create a custom helper, something like this:
var path = require('path');
var _ = require('lodash');
var matter = require('gray-matter');

module.exports.register = function (Handlebars, options, params) {

  var assemble = params.assemble;
  var grunt = params.grunt;
  var opts = options || {};

  Handlebars.registerHelper('sidenav', function(page, context) {
    if(page.published !== false && page.sidenav) {

      if(!Array.isArray(assemble.partials)) {
        assemble.partials = [assemble.partials];
      }

      var filepath = _.first(_.filter(assemble.partials, function(fp) {
        return path.basename(fp, path.extname(fp)) === page.sidenav;
      }));

      // Process context, using YAML front-matter,
      // grunt config and Assemble options.data
      var pageObj = matter(filepath) || {};
      var metadata = pageObj.context || {};

      context = _.extend(this, opts.data[page.sidenav], metadata, context);
      var partial = Handlebars.partials[page.sidenav];
      var template = Handlebars.compile(partial);
      var output = template(context);

      // Prepend output with the filepath to the original partial
      // for debugging
      var sidenav = opts.sidenav || opts.data.sidenav || {};
      if(sidenav.origin === true) {
        output = '\n' + output;
      }
      return new Handlebars.SafeString(output);
    }
  });
};

then use it in your markup like this:

    {{sidenav this}}


text:
Q: Wordpress Custom Rewrite Rule in Functions.php I am trying to add a custom rewrite rule in the functions to handle some new features that I dont want to use query strings. I had this but it doesnt seem to be working
add_action( 'init', 'wpse26388_rewrites_init' );

function wpse26388_rewrites_init(){
    add_rewrite_rule(
        'books/([^/]+/?',
        'index.php?pagename=books&book_name=$matches[1]',
        'top' );
}

add_filter( 'query_vars', 'wpse26388_query_vars' );
function wpse26388_query_vars( $query_vars ){
    $query_vars[] = 'book_name';

    return $query_vars;
}

basically I want to catch site.org/books/ANYTHING/ and point it to another template and use the book_name query in there. But as of now anything after /books/ results in a 404 error and I am not sure how to pass in a page-template.php file to use.


text:
Q: Qt5 - how to find the headers files using make? I have a issue for mac OsX
before, I was using Qt4 which installed itself in /Library/Frameworks for all Users.
So, I had a generic makefile for my all my Osx Users... using this informations.
But since, Qt5 asks you to install itself where you want  with the version number...
usually somewhere like : /Users/myname/Qt5.3.2/...
What can I use or how can i find the Headers filse to compile my program using makefile (no Cmake, Qmake ...) without asking my user : where did you install your Qt5 frameworks ?
I have tried to use *.pc in the Qt5.x.x/clang64/lib/pkgconfig directory but they seem to be wrong.
pkg-config --libs Qt5Core (ok) :
    -F/Users/myname/Qt5.3.2/5.3/clang_64/lib -framework QtCore
pkg-config --cflags Qt5Core (not ok) :
    -I/Users/myname/Qt5.3.2/5.3/clang_64/include/QtCore -I/Users/myname/Qt5.3.2/5.3/clang_64/include
but I need something like :
    -F/Users/myname/Qt5.3.2/5.3/clang_64/lib -I/Users/myname/Qt5.3.2/5.3/clang_64/lib/QtCore.framework/Headers
anyone have an idea ... or this problem ?
I found nothing interesting on google, because most people using Cmake or Qmake and i can't.
note : I have no problem on linux because i'm using pkg-config information.
thanks


text:
Q: Making ECDF plot in GGplot using double aes I kind of stuck how to obtain ECDF (line and point combined together) plot using more than 1 aes (could be color, linetype for geom_line or shape for geom_point).
So, I have this code for example
data<-mtcars
  data$cyl<-as.factor(data$cyl)
  data$am<-as.factor(data$am)

    ggplot(data,aes(qsec))+
        geom_line(stat = "ecdf",aes(linetype=cyl))+
        geom_point(stat="ecdf",size=2,aes(shape=cyl))+
        labs(x="sample")+
        theme(axis.title.y = element_blank(),
              text = element_text(size = 11, family = "serif"))+
        scale_y_continuous(labels = function(x) paste0(sprintf("%1.0f", x*100),"%"))+
        scale_x_log10(breaks = trans_breaks("log10", function(x) 10^x),
                      labels = trans_format("log10", math_format(10^.x))
        )

It is nicely formed ECDF plots by cyl type
.
But, then I wanted to mark some points based on am category, with adding color=am within the aes of geom_point, then the results were seemingly randomly scattered
.
I guess, it is because I used ECDF so, it created new individual cumulative calculations based on new category I've created. Could anybody help me out here? thanks

A: The various stats that you can use in ggplot are helpful when you want to carry out a common simple statistical transformation, but often if you're trying to do something unusual as you are doing here (show ecdfs split by one group and colors split by another group), they can make it more difficult to achieve your goal than just passing the data you actually want to plot:
data <- mtcars
  data$cyl  <- as.factor(data$cyl)
  data$am   <- as.factor(data$am)
  data$ecdf <- numeric(nrow(data))

data <- do.call(rbind, lapply(split(data, data$cyl), function(x) {
  x$ecdf <- ecdf(x$qsec)(x$qsec);
  x[order(x$ecdf),]
  }))

ggplot(data, aes(qsec, ecdf)) +
    geom_line(aes(linetype = cyl)) +
    geom_point(size = 2, aes(shape = cyl, colour = am)) +
    labs(x = "sample") +
    theme(axis.title.y = element_blank(),
          text = element_text(size = 11, family = "serif")) +
    scale_y_continuous(labels = function(x) paste0(sprintf("%1.0f", x*100), "%")) +
    scale_x_log10(breaks = trans_breaks("log10", function(x) 10^x),
                  labels = trans_format("log10", math_format(10^.x)))


text:
Q: How to use spcific HERE country data offline? I'm using Here maps evaluation (90 days) now.
My purpose is to use HERE offline (i.e., with Android phones that do not have cellular data, and even do not have WiFi, but can only make and get calls) and I want the map data to be avaailable only in 1 country.
How can I do this with HERE api?
EDIT
What I did so far:
1. I downloaded the evaluation of HERE, and built simple app. This app is only working with WiFi/Cellular data.
2. I downloaded HERE apk from Google Play and there it gave me to navigate offline after I downloaded the country map from the application.
I want this offline feature in an application that I write.

A: 1) Be sure that you are using Premium version of SDK. Starter version didn't support offline mode. Difference between versions shown on this page https://developer.here.com/develop/mobile-sdks
2) Look at example for how to download a map for specific region https://tcs.ext.here.com/sdk_examples/MapDownloader.zip


text:
Q: apply configured wordpress theme / plugins to multiple websites I am wondering if there is an ability to apply my configured custom wordpress cms theme that I customized, and configured (including use of several plugins) and apply this completed configured theme to multiple domains or websites through a shared hosting - without going in one by one installing and re-configuring the theme? over an over again.
Is there a quicker way to apply my theme and it's plugins across multiple websites / domains of shared hosting without installing Wordpress -> Applying the theme -> re-configuring everything -> installing / setting plugins etc. If the content does not matter initially? All I want is my Wordpress theme / websites pushed across about dozen of my other domains within shared hosting environment.

A: You can try using this plugin https://sr.wordpress.org/plugins/all-in-one-wp-migration/ It will transfer everything, all your settings, all your files. It will automatically change the links to the new url if you have some hardcoded. It will also transfer the database. All you need to do on the target domains/hostings is to install a new WP instance and connect it to the database and then import using this. There might be more refined solutions to this, but this one is very effective and quick to utilize.


text:
Q: Showing that $\ln(\sec 3t+\tan 3t)=2\tanh^{-1}(\tan(3t/2))$
I've been trying to show that
  $$\ln(\sec 3t+\tan 3t)=2\tanh^{-1}(\tan(3t/2))$$

I used the identity
$$\tanh^{-1}x=\frac12\ln\frac{1+x}{1-x}$$
to write:
$$\begin{array}{tcl}
2\tanh^{-1}(\tan(3t/2))&=&2\cdot\frac12\ln\dfrac{1+\tan(3t/2)}{1-\tan(3t/2)}\\
2\tanh^{-1}(\tan(3t/2))&=&\ln\dfrac{1+\tan(3t/2)}{1-\tan(3t/2)}\\
\end{array}$$
Then I used
$$\tan\frac{\theta}{2}=\frac{1-\cos \theta}{\sin\theta}$$
to write:
$$\begin{array}{tcl}
2\tanh^{-1}(\tan(3t/2))&=&\ln\dfrac{1+\dfrac{1-\cos3t}{\sin3t}}{1-\dfrac{1-\cos 3t}{\sin 3t}}\\
2\tanh^{-1}(\tan(3t/2))&=&\ln\dfrac{\sin 3t+1-\cos 3t}{\sin 3t-1+\cos 3t}
\end{array}$$
Now, in order to show that
$$\ln(\sec 3t+\tan 3t)=\ln\dfrac{\sin 3t+1-\cos 3t}{\sin 3t-1+\cos 3t}$$
I need to show that
$$\sec 3t+\tan 3t=\dfrac{\sin 3t+1-\cos 3t}{\sin 3t-1+\cos 3t}$$
Now,
$$\begin{array}{tcl}
\sec3t+\tan3t&=&\dfrac{1}{\cos 3t}+\dfrac{\sin 3t}{\cos 3t}\\
\sec3t+\tan3t&=&\dfrac{1+\sin 3t}{\cos 3t}
\end{array}$$
Now, I am stuck. How do I show that:
$$\frac{\sin 3t+1-\cos 3t}{\sin 3t-1+\cos 3t}=\frac{1+\sin 3t}{\cos 3t}$$
Here is some Matlab code that seemingly verifies the identity.
t=linspace(-1.5,1/2,1000);
y1=(sin(3*t)+1-cos(3*t))./(sin(3*t)-1+cos(3*t));
y2=(1+sin(3*t))./cos(3*t);
plot(t,y1,'b','LineWidth',4),hold on
plot(t,y2,'r','LineWidth',2)
hold off

And the image.

A: You're almost there. To prove
$$\frac{\sin 3t+1-\cos 3t}{\sin 3t-1+\cos 3t}=\frac{1+\sin 3t}{\cos 3t},$$
you need
$$(\sin 3t+1-\cos 3t)\cos 3t=(\sin 3t-1+\cos 3t)(1+\sin 3t).$$
Expand it:
$$\sin 3t\cos 3t+\cos 3t-\cos^2 3t=\sin 3t-1+\cos 3t+\sin^2 3t-\sin 3t+\cos 3t\sin 3t,$$
which can be simplified to
$$\cos^23t+\sin^2 3t=1.$$

A: You want to prove the identity $$\ln(\sec 3t+\tan 3t)=2\tanh^{-1}(\tan(3t/2))$$
We differentiate both sides and show that the derivatives are the same.
Note that $$ \frac {d}{dt}  \ln(\sec 3t+\tan 3t) = 3 \sec 3t$$
Also we have  $$ \frac {d}{dt} 2\tanh^{-1}(\tan (3t/2))$$
$$=\frac {2\sec ^ 2 ( 3t/2)}{1-\tan ^2 (3t/2)} (3/2)=3 \sec 3t$$
Thus the differennce of the two functions is a constant.
Upon evaluating the functions at $t=0$ we obtain the identity.


text:
Q: Deleting new entity throw InvalidOperationException I have two entities Customers & PhoneNumbers, my customer entity has collection of phone numbers, when I add new customer and add some phone numbers, then press click remove customer button, EF throw 'Adding a relationship with an entity which is in the Deleted state is not allowed'. this question already asked but I could not find any solution to solve this problem. I use below code to remove a customer in CustomerRepository:
public override void Remove(Customer model)
{
    Context.Customers.Remove(model);
}

A: Don't Operate on same DbContext. First dispose this object and create new dbContext and try to operate on new one. Otherwise your changetracker will be ambiguous with your operation intent and you will get this error. Here is one more solution : Removing Objects With a Relationship from DbContext


text:
Q: How to force Webpack 3 to throw TypeScript errors? // index.ts

let a = 1;
a.map();

Webpack doesn't throw this TS error about method "map" on type "number.
Do you know how check these errors automatically during webpack build?
Can't find anything on the internet.
Previously I saw this: https://cloud.githubusercontent.com/assets/376414/7276837/840b4dec-e8da-11e4-8362-c44f531d8cd9.png
How can I get the same output of webpack (TS errors) using webpack 3?
TypeScript thinks it's ok (any valid JS is also valid TypeScript), so, any project could be bundled with any JS error.
If I'm running tsc app/index.ts then I see the error:
app/index.ts(8,3): error TS2339: Property 'map' does not exist on type 'number'.
So, TypeScript compiler throws the error, but webpack (ts-loader I think) ignores it.
I'm using webpack 3.8.1
Here is config:
let path = require('path'),
    webpack = require('webpack'),
    HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

    entry: path.resolve('app/index.ts'),

    output: {
        path: path.resolve('dist'),
        filename: 'app.js'
    },

    resolve: {
        extensions: ['.js', '.vue', '.json', '.ts'],
        alias: {
            vue: path.resolve('node_modules/vue/dist/vue.js'),
            app: path.resolve('app')
        }
    },

    module:{
        rules: [
            { test: /\.tsx$/, use: 'ts-loader' },
            { test: /\.vue$/, use: 'vue-loader' },
            { test: /\.pug$/, use: 'pug-loader' }
        ]
    },

    plugins: [
        new HtmlWebpackPlugin({
            template: path.resolve('app/index.pug'),
            cache: false
        }),
        new webpack.LoaderOptionsPlugin({
            debug: true
        })
    ]

};

A: do you ever heard about linting? here's the loader for tslint for webpack


text:
Q: Como repetir o código no final no python? então, eu estou iniciando programação (apenas por apender mesmo ) e queria saber como fazer para o código reiniciar no final.
Sei que pode parecer algo simples mas eu não faço nenhum curso, estou aprendendo sozinho
lanchonete = ("500$")

açaiteria = ("900$")

uber = ("200$")

pationorte = ("1200$")

pergunta = input ("Diga o nome do estabelecimento desejado ")

if pergunta ==("lanchonete"):
   print (lanchonete)

elif pergunta ==("açaiteria"):
   print (açaiteria)

elif pergunta ==("uber"):
   print (uber)

elif pergunta ==("pationorte"):
   print (pationorte)

else:
   print ("Este estabelecimento não esta cadastrado no nosso banco de
   dados")

A: Já que está aprendendo, vale a pena comentar. O que você fez no seu código basicamente foi relacionar quatro variáveis aos seus respectivos valores e, a princípio, não variarão durante a execução. Algo assim geralmente é chamado de mapa: você define uma relação direta entre uma chave e um valor. Neste caso, a chave seria o nome do estabelecimento e o valor a quantidade monetária relacionada. No Python, a maneira mais simples de se implementar isso é com dicionário:
estabelecimentos = {
    'lanchonete': '500$',
    'açaiteria': '900$',
    'uber': '200$',
    'pationorte': '1200$'
}

Para obter o valor a partir de uma chave, basta utilizar o método get, que, inclusive, permite definir um valor padrão para caso a chave não exista:
padrão = 'Este estabelecimento não esta cadastrado no nosso banco de dados'
pergunta = input("Diga o nome do estabelecimento desejado ")
print(estabelecimentos.get(pergunta, padrão))

Colocando isso dentro de um laço de repetição, ficaria:
estabelecimentos = {
    'lanchonete': '500$',
    'açaiteria': '900$',
    'uber': '200$',
    'pationorte': '1200$'
}

padrão = 'Este estabelecimento não esta cadastrado no nosso banco de dados'

while True:
    pergunta = input("Diga o nome do estabelecimento desejado ")
    print(estabelecimentos.get(pergunta, padrão))

Veja funcionando no Repl.it

A: Basta envolver seu código num loop while True.
O while verifica uma condição, e se ela for verdadeira, executa novamente tudo o que está dentro do seu bloco de indentação. Como passamos True, ele sempre executará tudo de novo.
Como outra dica: os parênteses são desnecessários nos casos de atribuição (=) e comparação (==), e só são necessários aqui pras funções. Seu código fica um pouco mais claro sem eles!
while True:
    lanchonete = "500$"

    açaiteria = "900$"

    uber = "200$"

    pationorte = "1200$"

    pergunta = input ("Diga o nome do estabelecimento desejado ")

    if pergunta == "lanchonete":
       print (lanchonete)

    elif pergunta == "açaiteria":
       print (açaiteria)

    elif pergunta == "uber":
       print (uber)

    elif pergunta == "pationorte":
       print pationorte

    else:
       print ("Este estabelecimento não esta cadastrado no nosso banco de dados")


text:
Q: Sums of integrals converge or diverge? I want to show whether $I+J+\cdot\cdot\cdot$ converges or diverges and how to notate everything correctly.
$$ I=\int_0^1 \exp\bigg(\frac{1}{\ln(x)}\bigg)~dx$$
$$ G(x)=\int_0^x\exp\bigg(\frac{1}{\ln(x)}\bigg)~dx$$
$$ J=\int_0^1 G(x)~dx$$
$$ \cdot\cdot\cdot$$
So far I have $I=2K_1(2)$ where $K_1$ is a modified bessel function of the second kind, and $J\approx.2099$
Here's my desmos code that I've worked on for this problem: https://www.desmos.com/calculator/fj9pwsccii

A: By defining
$$ f_n(x) = \int_{0}^{x}\int_{0}^{x_n}\ldots\int_{0}^{x_2}e^{\frac{1}{\log x_1}}\,dx_1\,dx_2\cdots dx_n $$
we have
$$ f_n(x) = \int_{0<x_1 < x_2<\ldots<x_n<x}e^{\frac{1}{\log x_1}}\prod dx_k = \int_{0}^{x}\,\frac{1}{(n-1)!}(x-x_1)^{n-1}e^{\frac{1}{\log x_1}}dx_1$$
and by letting $x_1 = x v, dx_1 = x\,dv$
$$ f_n(x) = \frac{x^n}{(n-1)!}\int_{0}^{1}(1-v)^{n-1}e^{\frac{1}{\log x+\log v}}\,dv. $$
Since $\int_{0}^{1}v^m e^{\frac{1}{\log v}}\,dv = \frac{2}{\sqrt{m+1}}\,K_1\left(\frac{2}{\sqrt{m+1}}\right)$, by the binomial theorem
$$ f_n(1) = \frac{2}{(n-1)!}\sum_{k=0}^{n-1}\binom{n-1}{k}\frac{(-1)^k}{\sqrt{k+1}}\,K_1\left(\frac{2}{\sqrt{k+1}}\right). $$
It is interesting to point out that
$$ \sum_{n\geq 1}f_n(1) = \int_{0}^{1}\sum_{n\geq 1}\frac{(1-v)^{n-1}}{(n-1)!}e^{\frac{1}{\log v}}\,dv=\int_{0}^{1}\exp\left(1-v+\frac{1}{\log v}\right)\,dv $$
is convergent like $f_1(1)$, since $e^{1-v}$ is bounded between two positive constants for $v\in[0,1]$.


text:
Q: Keep-alive not working with v-if and slot I want to keep certain part of my component alive when v-if="false"
The part I want to keep alive contains a slot, and it doesn't work.
The component within the slot is still mounted every time the v-if changes.
Is it possible to keep it alive in some way?
<div v-if="index === 1">
   <keep-alive >
      <div :key="tab.id">
         <slot></slot>
      </div>
   </keep-alive>
</div>

A: Use v-show instead of v-if.  It will be rendered once, and then hidden when the expression is false.
I have only used keep-alive with dynamic components.


text:
Q: Pass two String array from doinbackground to fragment I am trying to pass 2 String[] from doinbackground to fragment where i have RecyclerView. I also tried setter getter method but still no luck
Here is my Fragment
 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=inflater.inflate(R.layout.activity_friend_list,container,false);
        recyclerView= (RecyclerView) view.findViewById(R.id.RecyclerViewForFriendList);

            //WANTS TO REPLACE THESE TWO ARRAY WITH WHICH I AM GETTING IN DOINBACKGROUND
            Name=getResources().getStringArray(R.array.left_Drawer_Menu);
            Image=getResources().obtainTypedArray(R.array.user_image);

        recyclerView.setHasFixedSize(true);

        adapter=new RecyclerFriendListAdapter(getActivity(),Distance,Image,LastSeen,Name);
        recyclerView.setAdapter(adapter);

        layoutManager=new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);

        return view;
    }

Here is my AsyncTask Class
 protected String[] doInBackground(String... params) {
        try {
            URL url=new URL(URL_Path);
            connection= (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream inputStream=connection.getInputStream();
            reader=new BufferedReader(new InputStreamReader(inputStream));
            String line;
            StringBuffer stringBuffer=new StringBuffer();
            while ((line=reader.readLine())!=null){
                stringBuffer.append(line);

            }
            String completeJSON=stringBuffer.toString();

            JSONArray parentArray=new JSONArray(completeJSON);

            String[] Name=new String[parentArray.length()];
            String[] ImagePath=new String[parentArray.length()];
            for (int i = 0; i <parentArray.length() ; i++) {
                JSONObject childObject=parentArray.getJSONObject(i);

                String Fname=childObject.getString("First_Name") ;
                String Lname=childObject.getString("Last_Name") ;

                Name[i]=Fname+" "+Lname;
                ImagePath[i]=childObject.getString("Image");
                Log.d(TAG,"String Arrays "+Name[i]+" "+ ImagePath[i]);

                     //GETTING ALL VALUES IN LOG SUCCESSFULLY

            }
            return Name;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {

            try {
                connection.disconnect();
                if (reader!=null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

@Override
    protected void onPostExecute(String[] strings) {
        super.onPostExecute(strings);
    }

I am calling AsyncTask Execute Method in Toolbar of Parent Activity Of Fragment
UPDATE:
1) As @BryanDunlap Asked for onPostExecute (its just implemented,No code inside it) And How to return both arrays to get in Fragment
2) @IrisLouis suggested to implement interface that's how i did with setter and getter but i wasn't work
ublic class WrapperClass {

    private String[] Name;
    private String[] ImagePath;

    public String[] getImagePath() {
        return ImagePath;
    }

    public void setImagePath(String[] imagePath) {
        ImagePath = imagePath;
    }

    public String[] getName() {

        return Name;
    }

    public void setName(String[] name) {
        Name = name;
    }

How i set this in AsyncTask
                Name[i]=Fname+" "+Lname;
                ImagePath[i]=childObject.getString("Image");
                Log.d(TAG,"String Arrays "+Name[i]+" "+ ImagePath[i]);
                //LOG RETURNS VALUE OF BOTH ARRAYS

                WrapperClass w=new WrapperClass();
                w.setImagePath(ImagePath);
                w.setImagePath(Name);

Getting in Fragment in onCreateView
  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
                              ....
                              ....
                              ....
    WrapperClass wrapperClass=new WrapperClass();
            String[] Name=wrapperClass.getName();
            String[] ImagePath=wrapperClass.getImagePath();
            Log.d(TAG,Name.toString()+" "+ ImagePath.toString())

             //IT RETURNS NULLS

A: Solution for you, can test it.
In class Asynctask make a interface callback results :
public class PageLoader extends AsyncTask<String, Void, String[] results> {

    private Context context;
    private LoaderListener mLoaderListener;

    public PageLoader(Context context, LoaderListener mLoaderListener) {
        this.context = context;
        this.mLoaderListener = mLoaderListener;
    }

    public interface LoaderListener {
        void onLoadCompleted(String[] results);

        void onLoadFailed();

        void onPreparing();
    }

    @Override
    protected void onPreExecute() {
        mLoaderListener.onPreparing();
    }

    @Override
    protected String[] doInBackground(String... params) {
         try {
            URL url=new URL(URL_Path);
            connection= (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream inputStream=connection.getInputStream();
            reader=new BufferedReader(new InputStreamReader(inputStream));
            String line;
            StringBuffer stringBuffer=new StringBuffer();
            while ((line=reader.readLine())!=null){
                stringBuffer.append(line);

            }
            String completeJSON=stringBuffer.toString();

            JSONArray parentArray=new JSONArray(completeJSON);

            String[] Name=new String[parentArray.length()];
            String[] ImagePath=new String[parentArray.length()];
            for (int i = 0; i <parentArray.length() ; i++) {
                JSONObject childObject=parentArray.getJSONObject(i);

                String Fname=childObject.getString("First_Name") ;
                String Lname=childObject.getString("Last_Name") ;

                Name[i]=Fname+" "+Lname;
                ImagePath[i]=childObject.getString("Image");
                Log.d(TAG,"String Arrays "+Name[i]+" "+ ImagePath[i]);

                     //GETTING ALL VALUES IN LOG SUCCESSFULLY

            }
            return Name;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {

            try {
                connection.disconnect();
                if (reader!=null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    @Override
    protected void onPostExecute(String[] results) {
        if (results!= null) {
            mLoaderListener.onLoadCompleted(results);
        } else {
            mLoaderListener.onLoadFailed();
        }
    }

}

In Activity you execute Asynctask.
In Fragment you must implements LoaderListener and Override three function.
Ex : YourFragment extends Fragment implements LoaderListener
You can handle results callback in onLoadCompleted
Ex :
@Override
public void onLoadCompleted(String[] results){
  //Do something with results
}


text:
Q: SeekBar Stops Activity | What is the error? I design and implement a seek bar which incements by 50. But if i run app it is crashing. There is no syntax error (Eclipse does not notice me about this) What is the problem?
package com.example.hello;
import com.example.hello.R.layout;
import android.app.Activity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;

public class NewPlan extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.new_plan);

    SeekBar seekBar = (SeekBar)findViewById(R.id.seekbar);
    seekBar.setProgress(0); //this is line 19
    seekBar.incrementProgressBy(50);
    seekBar.setMax(5000);

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
        TextView seekBarValue = (TextView)findViewById(R.id.seekBarValue);
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            progress = progress / 50;
            progress = progress * 50;
            seekBarValue.setText(String.valueOf(progress));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

}

}

new_plan.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<SeekBar
    android:id="@+id/seekBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="77dp" />

<TextView
    android:id="@+id/seekBarValue"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/seekbar"
    android:layout_marginLeft="30dp"
    android:layout_marginTop="28dp"
    android:text="Button" />

LOG WINDOW:
02-24 21:52:50.601: E/AndroidRuntime(2236): FATAL EXCEPTION: main
02-24 21:52:50.601: E/AndroidRuntime(2236): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hakkikonu.dailycalorie/com.hakkikonu.dailycalorie.NewPlan}: java.lang.NullPointerException
02-24 21:52:50.601: E/AndroidRuntime(2236):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
02-24 21:52:50.601: E/AndroidRuntime(2236):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
02-24 21:52:50.601: E/AndroidRuntime(2236):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-24 21:52:50.601: E/AndroidRuntime(2236):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
02-24 21:52:50.601: E/AndroidRuntime(2236):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-24 21:52:50.601: E/AndroidRuntime(2236):     at android.os.Looper.loop(Looper.java:137)
02-24 21:52:50.601: E/AndroidRuntime(2236):     at android.app.ActivityThread.main(ActivityThread.java:5039)
02-24 21:52:50.601: E/AndroidRuntime(2236):     at java.lang.reflect.Method.invokeNative(Native Method)
02-24 21:52:50.601: E/AndroidRuntime(2236):     at java.lang.reflect.Method.invoke(Method.java:511)
02-24 21:52:50.601: E/AndroidRuntime(2236):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-24 21:52:50.601: E/AndroidRuntime(2236):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-24 21:52:50.601: E/AndroidRuntime(2236):     at dalvik.system.NativeStart.main(Native Method)
02-24 21:52:50.601: E/AndroidRuntime(2236): Caused by: java.lang.NullPointerException
02-24 21:52:50.601: E/AndroidRuntime(2236):     at com.hakkikonu.dailycalorie.NewPlan.onCreate(NewPlan.java:19)
02-24 21:52:50.601: E/AndroidRuntime(2236):     at android.app.Activity.performCreate(Activity.java:5104)
02-24 21:52:50.601: E/AndroidRuntime(2236):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
02-24 21:52:50.601: E/AndroidRuntime(2236):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
02-24 21:52:50.601: E/AndroidRuntime(2236):     ... 11 more

A: Your Java code can't find the View that should have the id seekbar. You should also double-check the ids used in new_plan.xml. I suggest also cleaning your project and rebuilding. From my experience, some changes don't force R.java to be generated and then you will see confusing issues when referencing members of R from your Java code.

A: Change:
SeekBar seekBar = (SeekBar)findViewById(R.id.seekbar);

to:
SeekBar seekBar = (SeekBar)findViewById(R.id.seekBar);

Your ID in the XML file is seekBar. Java is case sensitive.