问:
Account balance system with Stripe
For the past two days I've been trying to understand how Stripe works.. What I'm trying to build is a simple system that lets the user to add funds to his account on the site.
I followed a tutorial I found on the internet that uses Laravel Cashier but as I've read on the laravel documentation if I need to perform single charges I should use directly Stripe. The thing is, there are not many tutorials on how this should be done with laravel..

Here's what I have so far:

VIEW:

```<code>    <form class="app-form" style="margin-bottom: 0px;" action="/add-funds" method="POST">
      {{ csrf_field() }}

      <select id="funds-options" style="width: 20%; margin-bottom: 20px;" name="add-funds-select">
        <option value="30">$30</option>
        <option value="50">$50</option>
        <option value="100">$100</option>
        <option value="200">$200</option>
        <option value="300">$300</option>
        <option value="500">$500</option>
      </select>

      <p style="margin-bottom: 0px;">
        <script src="https://checkout.stripe.com/checkout.js"></script>

        <button id="customButton">Purchase</button>

        <script>
        var handler = StripeCheckout.configure({
          key: '{{ getenv('STRIPE_KEY') }}',
          image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
          locale: 'auto',
          token: function(token) {
            // You can access the token ID with `token.id`.
            // Get the token ID to your server-side code for use.
          }
        });

        document.getElementById('customButton').addEventListener('click', function(e) {
          // Open Checkout with further options:
          var userAmount = $("#funds-options").val();

          handler.open({
            name: 'Demo Site',
            description: '2 widgets',
            amount: userAmount*100
          });
          e.preventDefault();
        });

        // Close Checkout on page navigation:
        window.addEventListener('popstate', function() {
          handler.close();
        });
        </script>
      </p>
    </form>
</code>```

I have this select tag where the user can select the amount he wants to add to his account. Now, this opens the widget from Stripe but as soon as I hit pay, I'm getting that info: "You did not set a valid publishable key".
I tried this using the publishable key directly and I'm able to pass this but as soon as it gets into the controller it throws pretty much the same error, something like API key was not set.

I set the keys in the env file and I also reference them in the services.php..

ENV:

```<code>STRIPE_KEY=pk_test_....
STRIPE_SECRET=sk_test_...
</code>```

SERVICES:

```<code>'stripe' => [
    'model' => App\User::class,
    'key' => env('STRIPE_KEY'),
    'secret' => env('STRIPE_SECRET'),
],
</code>```

Anyway, even if I pass this "error" I'm still not sure if I'm doing this right.

Controller:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;

class WalletController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function index()
    {
        return view('user.wallet.index');
    }

     public function postPayWithStripe(Request $request)
     {
         return $this->chargeCustomer($request->input('add-funds-select'), $request->input('stripeToken'));
     }

     public function chargeCustomer($amount, $token)
     {
        \Stripe\Stripe::setApiKey(getenv('STRIPE_SECRET'));

         if (!$this->isStripeCustomer())
         {
             $customer = $this->createStripeCustomer($token);
         }
         else
         {
             $customer = \Stripe\Customer::retrieve(Auth::user()->stripe_id);
         }

         return $this->createStripeCharge($amount, $customer);
     }
     public function createStripeCharge($amount, $customer)
     {
         try {
             $charge = \Stripe\Charge::create(array(
                 "amount" => $amount,
                 "currency" => "brl",
                 "customer" => $customer->id,
                 "description" => "Add funds to your account"
             ));
         } catch(\Stripe\Error\Card $e) {
             return redirect()
                 ->route('index')
                 ->with('error', 'Your credit card was been declined. Please try again or contact us.');
     }

         return $this->postStoreAmount($amount);
     }

     public function createStripeCustomer($token)
     {
         \Stripe\Stripe::setApiKey(getenv('STRIPE_SECRET'));

         $customer = \Stripe\Customer::create(array(
             "description" => Auth::user()->email,
             "source" => $token
         ));

         Auth::user()->stripe_id = $customer->id;
         Auth::user()->save();

         return $customer;
     }

    /**
     * Check if the Stripe customer exists.
     *
     * @return boolean
     */
     public function isStripeCustomer()
     {
         return Auth::user() && \App\User::where('id', Auth::user()->id)->whereNotNull('stripe_id')->first();
     }

     public function postStoreAmount($amount)
     {
        $userBalance = Auth::user()->balance;
        $userBalance = $userBalance + $amount;

        Auth::user()->save();

        session()->flash('message', 'You just added funds to your account.');
        return redirect()->route('index');
     }
}
</code>```

I have a field in the users table that holds the user balance.

As I mentioned, I followed a tutorial I found on the internet.. I'm not sure how this should work. Any suggestions?

答:
You will follow this tutorial. I am integrated it in my cart functionality previous week. Its very easy to integrate ...have Fun :)

  http://justlaravel.com/integrate-stripe-payment-gateway-laravel/

Title: Account balance system with Stripe

Body:
For the past two days I've been trying to understand how Stripe works.. What I'm trying to build is a simple system that lets the user to add funds to his account on the site.
I followed a tutorial I found on the internet that uses Laravel Cashier but as I've read on the laravel documentation if I need to perform single charges I should use directly Stripe. The thing is, there are not many tutorials on how this should be done with laravel..

Here's what I have so far:

VIEW:

    <form class="app-form" style="margin-bottom: 0px;" action="/add-funds" method="POST">
      {{ csrf_field() }}

      <select id="funds-options" style="width: 20%; margin-bottom: 20px;" name="add-funds-select">
        <option value="30">$30</option>
        <option value="50">$50</option>
        <option value="100">$100</option>
        <option value="200">$200</option>
        <option value="300">$300</option>
        <option value="500">$500</option>
      </select>

        <button id="customButton">Purchase</button>

    </form>

I have this select tag where the user can select the amount he wants to add to his account. Now, this opens the widget from Stripe but as soon as I hit pay, I'm getting that info: "You did not set a valid publishable key".
I tried this using the publishable key directly and I'm able to pass this but as soon as it gets into the controller it throws pretty much the same error, something like API key was not set.

I set the keys in the env file and I also reference them in the services.php..

ENV:

STRIPE_KEY=pk_test_....
STRIPE_SECRET=sk_test_...

SERVICES:

'stripe' => [
    'model' => App\User::class,
    'key' => env('STRIPE_KEY'),
    'secret' => env('STRIPE_SECRET'),
],

Anyway, even if I pass this "error" I'm still not sure if I'm doing this right.

Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;

class WalletController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function index()
    {
        return view('user.wallet.index');
    }

     public function postPayWithStripe(Request $request)
     {
         return $this->chargeCustomer($request->input('add-funds-select'), $request->input('stripeToken'));
     }

     public function chargeCustomer($amount, $token)
     {
        \Stripe\Stripe::setApiKey(getenv('STRIPE_SECRET'));

         if (!$this->isStripeCustomer())
         {
             $customer = $this->createStripeCustomer($token);
         }
         else
         {
             $customer = \Stripe\Customer::retrieve(Auth::user()->stripe_id);
         }

         return $this->createStripeCharge($amount, $customer);
     }
     public function createStripeCharge($amount, $customer)
     {
         try {
             $charge = \Stripe\Charge::create(array(
                 "amount" => $amount,
                 "currency" => "brl",
                 "customer" => $customer->id,
                 "description" => "Add funds to your account"
             ));
         } catch(\Stripe\Error\Card $e) {
             return redirect()
                 ->route('index')
                 ->with('error', 'Your credit card was been declined. Please try again or contact us.');
     }

         return $this->postStoreAmount($amount);
     }

     public function createStripeCustomer($token)
     {
         \Stripe\Stripe::setApiKey(getenv('STRIPE_SECRET'));

         $customer = \Stripe\Customer::create(array(
             "description" => Auth::user()->email,
             "source" => $token
         ));

         Auth::user()->stripe_id = $customer->id;
         Auth::user()->save();

         return $customer;
     }

    /**
     * Check if the Stripe customer exists.
     *
     * @return boolean
     */
     public function isStripeCustomer()
     {
         return Auth::user() && \App\User::where('id', Auth::user()->id)->whereNotNull('stripe_id')->first();
     }

     public function postStoreAmount($amount)
     {
        $userBalance = Auth::user()->balance;
        $userBalance = $userBalance + $amount;

        Auth::user()->save();

        session()->flash('message', 'You just added funds to your account.');
        return redirect()->route('index');
     }
}

I have a field in the users table that holds the user balance.

As I mentioned, I followed a tutorial I found on the internet.. I'm not sure how this should work. Any suggestions?


来源: stackexchange

问:
Call test.php page inside a div
I wonder if you can, how to call up a page for example test.php, so that it opens in a div and not in the new page, thank you.

```<code><!DOCTYPE html PUBLIC ">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Menu</title>
<script type="text/javascript">

var loadedobjects=""
var rootdomain="http://"+window.location.hostname

function ajaxpage(url, containerid){
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}
page_request.open('GET', url, true)
page_request.send(null)
}

function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
document.getElementById(containerid).innerHTML=page_request.responseText
}

function loadobjs(){
if (!document.getElementById)
return
for (i=0; i<arguments.length; i++){
var file=arguments[i]
var fileref=""
if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
if (file.indexOf(".js")!=-1){ //If object is a js file
fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css")!=-1){ //If object is a css file
fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref!=""){
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects+=file+" " //Remember this object as being already added to page
}
}
}

</script>

<style type="text/css">
#leftcolumn{
float:left;
width:150px;
height: 400px;
border: 3px solid black;
padding: 5px;
padding-left: 8px;

}

#leftcolumn a{
padding: 3px 1px;
display: block;
width: 100%;
text-decoration: none;
font-weight: bold;
border-bottom: 1px solid gray;
}

#leftcolumn a:hover{
background-color: #FFFF80;
}

#rightcolumn{
float:left;
width:550px;
min-height: 400px;
border: 3px solid black;
margin-left: 10px;
padding: 5px;
padding-bottom: 8px;
}

* html #rightcolumn{ /*IE only style*/
height: 400px;
}
</style>
</head>

<body>

<div id="leftcolumn">
<a href="javascript:ajaxpage('http://localhost/cars/player/menu.php', 'rightcolumn');">Menu</a>
<a href="javascript:ajaxpage('http://www.google.it', 'rightcolumn');">Google</a>

<div style="margin-top: 2em">Load CSS & JS files</div>
<a href="javascript:loadobjs('ajaxfiles/style.css', 'ajaxfiles/tooltip.js');">Load "style.css" and "tooltip.js"</a>

</div>

<div id="rightcolumn"><h3>Choose a page to load.</h3></div>
<div style="clear: left; margin-bottom: 1em"></div>

</body>

</html>
</code>```

In this way, if menu.php recall works and I view the page on the local server, but if you call the page with google, does not open.

答:
```<code><a href="javascript:void(0)" id="menu">Menu</a>
<div id="rightcolumn"></div>
<script>
$(document).ready(function(){
     $("#menu").click(function(){
           $("#rightcolumn").load("http://localhost/player/menu.php");
     });
 });
</script>
</code>```

You can do like this...and so on for all elements...

ContentLicense: CC BY-SA 3.0

Title: Call test.php page inside a div

Body:
I wonder if you can, how to call up a page for example test.php, so that it opens in a div and not in the new page, thank you.

<!DOCTYPE html PUBLIC ">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Menu</title>

Menu
Google

Load CSS & JS files

Load "style.css" and "tooltip.js"

Choose a page to load.

In this way, if menu.php recall works and I view the page on the local server, but if you call the page with google, does not open.

Body:
<a href="javascript:void(0)" id="menu">Menu</a>
<div id="rightcolumn"></div>
<script>
$(document).ready(function(){
     $("#menu").click(function(){
           $("#rightcolumn").load("http://localhost/player/menu.php");
     });
 });
</script>

You can do like this...and so on for all elements...


问:
Best practices for updating current data Firebase database after adding some more denormalization
I wanted to check on the best and recommended practices for updating current data in a Firebase database after I decide to have some more duplicated data to support some complex querying or just to make it easier to read data. For e.g., I have list of users in my Firebase database and each user look like

```<code>users
 -KGvMIPwul2dUYABCDEF
   countryCode: 1
   id: -KGvMIPwul2dUYABCDEF
   mobileNumber: 1231231234
   name: Varun Gupta
</code>```

I have been querying a user based on his mobile number which works with current data. Now, I get a requirement to also query a user based on the combination of the country code and mobile number. So, I decide to add some duplicated data in order to make the query easy and the new user would look like

```<code>users
 -KGvMIPwul2dUYABCDEF
   countryCode: 1
   id: -KGvMIPwul2dUYABCDEF
   mobileNumber: 1231231234
   name: Varun Gupta
   mobileNumberWithCC: 11231231234
</code>```

I will have the mobileNumberWithCC for all the new users but I also want to update the current users with this information. I want to ask for the best practices for updating the database in such a scenario. Should I just write some code using admin SDK to update the required data and run it once or are there any other suggested ways to do this.

Thanks!

答:
Create a method like this in which you can update your data at once:

```<code>private static void updateUser(String userId) {
    Map<String, Object> map = new HashMap<>();
    map.put("/users/" + userId + "/", new HashMap<>().put("mobileNumber", 1231231234));
    map.put("/users/" + userId + "/", new HashMap<>().put(mobileNumberWithCC, 11231231234));
    yourReference.updateChildren(map);
}
</code>```

Or even simpler:

yourReference.child(users).child(userId).child(mobileNumber).setValue(1231231234);
yourReference.child(users).child(userId).child(mobileNumberWithCC).setValue(11231231234);

Body:
I wanted to check on the best and recommended practices for updating current data in a Firebase database after I decide to have some more duplicated data to support some complex querying or just to make it easier to read data. For e.g., I have list of users in my Firebase database and each user look like

users
 -KGvMIPwul2dUYABCDEF
   countryCode: 1
   id: -KGvMIPwul2dUYABCDEF
   mobileNumber: 1231231234
   name: Varun Gupta

I have been querying a user based on his mobile number which works with current data. Now, I get a requirement to also query a user based on the combination of the country code and mobile number. So, I decide to add some duplicated data in order to make the query easy and the new user would look like

users
 -KGvMIPwul2dUYABCDEF
   countryCode: 1
   id: -KGvMIPwul2dUYABCDEF
   mobileNumber: 1231231234
   name: Varun Gupta
   mobileNumberWithCC: 11231231234

I will have the mobileNumberWithCC for all the new users but I also want to update the current users with this information. I want to ask for the best practices for updating the database in such a scenario. Should I just write some code using admin SDK to update the required data and run it once or are there any other suggested ways to do this.

Thanks!

Body:
Create a method like this in which you can update your data at once:

private static void updateUser(String userId) {
    Map<String, Object> map = new HashMap<>();
    map.put("/users/" + userId + "/", new HashMap<>().put("mobileNumber", 1231231234));
    map.put("/users/" + userId + "/", new HashMap<>().put(mobileNumberWithCC, 11231231234));
    yourReference.updateChildren(map);
}

Or even simpler:

yourReference.child(users).child(userId).child(mobileNumber).setValue(1231231234);
yourReference.child(users).child(userId).child(mobileNumberWithCC).setValue(11231231234);


问:
Java lesson: public void displayMessage() Doesn't working
I have a Java book and im trying to learn obviously Java Programming.

I have a lesson that tells me simply to put this Code on Eclipse.

I copied from the Book and i put it on Eclipse program that i test and learn there. When i run it, it doesn't says any error. But at the moment that i run it, it shows me this error:

Code on Eclipse

Code on the Book

Does anyone knows what happens here? Is the book wrong or what?

Thanks.

答:
You have to write the main method as suggested by the compiler here. When you run a Java Program, the JVm searches for the main method in the class. There is no main method defined in this case, so it is giving this error.

```<code>public static void main(String[] args){
 new GradeBook().displayMessage();
}
</code>```

Add the above code snippet to your class and run it. It will work.
To learn more about main method in Java check this link
Java Main Method

Body:
You have to write the main method as suggested by the compiler here. When you run a Java Program, the JVm searches for the main method in the class. There is no main method defined in this case, so it is giving this error.

public static void main(String[] args){
 new GradeBook().displayMessage();
}

Add the above code snippet to your class and run it. It will work.
To learn more about main method in Java check this link
Java Main Method


问:
How can I change the font color in a groupbox when I disable the groupbox
I am using a Groupbox in c# and at first, it is Enabled.

when I use Groupbox1.Enabled = false, it's fore color (and everythings' forecolor which is in it) change to default black. and even the command label1.Forecolor = Color.White does not work. (Which label1 is in the Groupbox1).
when I Enable Groupbox, it fixes. But I want it to be White whether Groupbox1 is enabled or disabled.

答:
I manually changed the Groupbox's foreColor which affected the Text properties, font like so:

Changed all occurrences of Enabled false with -

```<code>            grpGeneral.ForeColor = SystemColors.GrayText;
            grpGeneral.Enabled = false;
</code>```

And changed all occurrences of Enabled true with -

```<code>            grpGeneral.Enabled = true;
            grpGeneral.ForeColor = SystemColors.ActiveCaptionText;
</code>```

Body:
I manually changed the Groupbox's foreColor which affected the Text properties, font like so:

Changed all occurrences of Enabled false with -

            grpGeneral.ForeColor = SystemColors.GrayText;
            grpGeneral.Enabled = false;

And changed all occurrences of Enabled true with -

            grpGeneral.Enabled = true;
            grpGeneral.ForeColor = SystemColors.ActiveCaptionText;


问:
instanceOf operator in java
Why is this line of code in Java not printing the message?

```<code>System.out.println("a instanceof String:"+a instanceof String);
</code>```

Why is it just printing true and not the String before it???

答:
Ah, the joys of operator precedence. That line is effectively:

```<code>System.out.println(("a instanceof String:" + a) instanceof String);
</code>```

... so you're doing string concatenation, and then checking whether the result is a string. So it will always print true, regardless of the value of a.

You just need parentheses

```<code>System.out.println("a instanceof String:" + (a instanceof String));
</code>```

See the Java tutorial page on operators for a precedence list.

Title: instanceOf operator in java

Body:
Why is this line of code in Java not printing the message?

System.out.println("a instanceof String:"+a instanceof String);

Why is it just printing true and not the String before it???

Body:
Ah, the joys of operator precedence. That line is effectively:

System.out.println(("a instanceof String:" + a) instanceof String);

... so you're doing string concatenation, and then checking whether the result is a string. So it will always print true, regardless of the value of a.

You just need parentheses

System.out.println("a instanceof String:" + (a instanceof String));

See the Java tutorial page on operators for a precedence list.


问:
Capitalizing words in a string using C#
I need to take a string, and capitalize words in it. Certain words ("in", "at", etc.), are not capitalized and are changed to lower case if encountered. The first word should always be capitalized. Last names like "McFly" are not in the current scope, so the same rule will apply to them - only first letter capitalized.

For example: "of mice and men By CNN" should be changed to "Of Mice and Men by CNN". (Therefore ToTitleString won't work here.)

What would be the best way to do that?

I thought of splitting the string by spaces, and go over each word, changing it if necessary, and concatenating it to the previous word, and so on.
It seems pretty naive and I was wondering if there's a better way to do it. I am using .NET 3.5.

答:
A non-clever approach that handles the simple case:</p>

```<code>var s = "of mice and men By CNN";
var sa = s.Split(' ');
for (var i = 0; i < sa.Length; i++)
    sa[i] = sa[i].Substring(0, 1).ToUpper() + sa[i].Substring(1);
var sout = string.Join(" ", sa);
Console.WriteLine(sout);
</code>```

ContentLicense: CC BY-SA 4.0

Title: Capitalizing words in a string using C#

Body:
A non-clever approach that handles the simple case:

var s = "of mice and men By CNN";
var sa = s.Split(' ');
for (var i = 0; i < sa.Length; i++)
    sa[i] = sa[i].Substring(0, 1).ToUpper() + sa[i].Substring(1);
var sout = string.Join(" ", sa);
Console.WriteLine(sout);

ContentLicense: CC BY-SA 2.5


问:
FATAL: Cannot generate COM file : invalid initial entry point adress
While linking this asembly file  using Tlink /tdc command I got the FATAL: Cannot generate COM file : invalid initial entry point adress. error message. I don't know how repair this BUG. What should I change in my code to make this program able to start.

```<code>.MODEL HUGE
org    100h

;.386
.code
Dane            SEGMENT
DL_TABLICA      EQU     10
Tablica         DB      01h, 02h, 00h, 10h, 12h, 33h
                DB      15h, 09h, 11h, 08h, 0Ah, 00h
Najmniejsza     DB      ?
Dane ends
Kod SEGMENT
ASSUME  CS:Kod, DS:Dane
                ;jmp     Poczatek

Start:

                mov     ax, 4C00h
                int     21h
Kod ENDS

End     ;Endprog
Start
</code>```

答:
The .MODEL for .COM programs is "tiny".

.COM programs have only one segment. So you shouldn't use any SEGMENT, ENDS or ASSUME directive in it. A single .CODE serves the purpose. Therefore, at the beginning should be code, not data.

A .COM program starts always at the beginning. To give it a label is just for satisfying TLINK.

A .COM program starts with DS=CS. You don't need to initialize DS (mov ax, @data mov ds, ax).

A simple Hello World program:

```<code>MODEL tiny
.CODE
.386                        ; Just to show at what position it has to be
ORG 0100h

Start:

    mov ah, 09h             ; http://www.ctyme.com/intr/rb-2562.htm
    mov dx, OFFSET hello
    int 21h

    mov ax, 4C00h           ; http://www.ctyme.com/intr/rb-2974.htm
    int 21h

hello:  db "Hello World", '$'

End Start
</code>```

Body:
While linking this asembly file  using Tlink /tdc command I got the FATAL: Cannot generate COM file : invalid initial entry point adress. error message. I don't know how repair this BUG. What should I change in my code to make this program able to start.

.MODEL HUGE
org    100h

;.386
.code
Dane            SEGMENT
DL_TABLICA      EQU     10
Tablica         DB      01h, 02h, 00h, 10h, 12h, 33h
                DB      15h, 09h, 11h, 08h, 0Ah, 00h
Najmniejsza     DB      ?
Dane ends
Kod SEGMENT
ASSUME  CS:Kod, DS:Dane
                ;jmp     Poczatek

Start:

                mov     ax, 4C00h
                int     21h
Kod ENDS

End     ;Endprog
Start

Body:
The .MODEL for .COM programs is "tiny".

.COM programs have only one segment. So you shouldn't use any SEGMENT, ENDS or ASSUME directive in it. A single .CODE serves the purpose. Therefore, at the beginning should be code, not data.

A .COM program starts always at the beginning. To give it a label is just for satisfying TLINK.

A .COM program starts with DS=CS. You don't need to initialize DS (mov ax, @data mov ds, ax).

A simple Hello World program:

MODEL tiny
.CODE
.386                        ; Just to show at what position it has to be
ORG 0100h

Start:

    mov ah, 09h             ; http://www.ctyme.com/intr/rb-2562.htm
    mov dx, OFFSET hello
    int 21h

    mov ax, 4C00h           ; http://www.ctyme.com/intr/rb-2974.htm
    int 21h

hello:  db "Hello World", '$'

End Start


问:
Should I always do $em->clear(); in Symfony?
I have seen some stuff online about the need to use $em->clear(); in order to prevent memory leaks. I don't know anything about memory leaks.

In the official docs, I see $em->clear(); isn't used much. Should I make it a practice to do this on each request that uses the entity manager?

答:
No, you shouldn't. $em->clear(); will detach all entities that are currently managed by this EntityManager. This will only be useful when running batch-scripts with huge amounts of data.

$em->flush(); will be most likely sufficient, unless you are starting to struggle with memory limits.


答:
Your code will be executed as follows:

System.out.println(("a instanceof String:"+a) instanceof String);

So, the whole string i.e., ("a instanceof String:"+a) has been considered for the instanceof check.

In order to print, "a instanceof String:true", you need to use parenthesis at the right place:

```<code>System.out.println("a instanceof String:" + (a instanceof String));
</code>```

Title: instanceOf operator in java

Body:
Your code will be executed as follows:

System.out.println(("a instanceof String:"+a) instanceof String);

So, the whole string i.e., ("a instanceof String:"+a) has been considered for the instanceof check.

In order to print, "a instanceof String:true", you need to use parenthesis at the right place:

System.out.println("a instanceof String:" + (a instanceof String));


答:
You have to use brackets.</p>

```<code>System.out.println(("a instanceof String:"+a) instanceof String);
</code>```

Title: instanceOf operator in java

Body:
You have to use brackets.

System.out.println(("a instanceof String:"+a) instanceof String);


问:
What is usage of method rest.use(methodOverride()) in node.js?
In nodejs applications i found method-override module and the project which i am studing contains this code

var methodOverride=require('method-override');

and after creating rest server

rest.use(methodOverride())

It seems like it is a middleware. But my question is there we are not passing any arguments. Then what actually it does ?

答:
From method-override README:

Lets you use HTTP verbs such as PUT or DELETE in places where the
  client doesn't support it.

Usage: methodOverride(getter, options)

You are calling this same function, but the defaults for getter and options are being applied. Which are:

getter: X-HTTP-Method-Override

options: ['POST']

It will be easier if you simply check the API next time.

Usually typing www.npmjs.com/package/<name> takes you there. (www.npmjs.com/package/method-override in this case)


问:
How does Lagom manage communication patterns?
I'm referring to the "Managing  Communication Patterns" section of Reactive Microservices Architecture by Jonas Boner.

Usually when communicating between services (ESB is one example), one would need:
1) A queue for pub-sub communication, and to queue up events for back pressure and fault tolerance
2) A routing layer - Camel Or Akka Streams
3) A mediation later for communicating with different protocols - Camel is one example.

How does Lagom handle the above?

答:
I'm not sure you "usually" need routing and mediation within the message bus. Jonas Bonér points out that publish/subscribe is a very useful addition to using HTTP calls for microservices. This is provided by Lagom in form of the message bus.
This in accordance with the "smart endpoints, dumb pipes" approach.

If you want to follow a different approach and put mediation and orchestration in the bus, rather than in services and possibly their anti-corruption layers, you could leverage Camel and/or RabbitMQ or the likes, but there's no Lagom-specific integration. You'd just use the Scala (or Java) connectors they provide.


问:
Extracting data from nested json file using javascript
I'm stuck with this issue. I've the below nested json.

```<code>{
  "current": {
    "timeSeries": [
      {
        "results": [
          {
            "count": 426
          }
        ],
        "beginTimeSeconds": 1490928320,
        "endTimeSeconds": 1490930120,
        "inspectedCount": 426
      },
      {
        "results": [
          {
            "count": 510
          }
        ],
        "beginTimeSeconds": 1490930120,
        "endTimeSeconds": 1490931920,
        "inspectedCount": 510
      }
    ]
  },
  "previous": {
    "timeSeries": [
      {
        "results": [
          {
            "count": 426
          }
        ],
        "beginTimeSeconds": 1490928320,
        "endTimeSeconds": 1490930120,
        "inspectedCount": 426
      },
      {
        "results": [
          {
            "count": 510
          }
        ],
        "beginTimeSeconds": 1490930120,
        "endTimeSeconds": 1490931920,
        "inspectedCount": 510
      }
    ]
  }
}
</code>```

And I'm trying to extract data from the above json and present it on webpage using google visualization api.

I've tried with below js and it didn't work.

```<code>function drawChart() {
  var jsonData = $.ajax({
      url: "https://api.myjson.com/bins/bay0v",
      dataType: "json",
      async: false
      }).responseText;

   var options = {
      title : 'Sample json line chart',
      curveType : 'function',
    };

//var obj = JSON.parse(jsonData);
console.log(jsonData);
console.log(jsonData.current.timeSeries[0].beginTimeSeconds);

    var options = {
       hAxis: {
         title: 'Time',
         textStyle: {
           color: '#01579b',
           fontSize: 20,
           fontName: 'Arial',
           bold: true,
           italic: true
         },
         titleTextStyle: {
           color: '#01579b',
           fontSize: 16,
           fontName: 'Arial',
           bold: false,
           italic: true
         }
       },
       vAxis: {
         title: 'Popularity',
         textStyle: {
           color: '#1a237e',
           fontSize: 24,
           bold: true
         },
         titleTextStyle: {
           color: '#1a237e',
           fontSize: 24,
           bold: true
         }
       },
       colors: ['#a52714', '#097138']
     };

  // Instantiate and draw our chart, passing in some options.
  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
  chart.draw(data, {width: 1400, height: 360});
}
</code>```

I'm seeing below output in browser console.

```<code>Uncaught TypeError: Cannot read property 'timeSeries' of undefined
</code>```

Can someone please help me to solve this problem?

Thanks in advance.

答:
The output of console.log can be misleading because browsers tend to only look at the contents of the logged variable when you actually drill down in the nested structure that the console provides.

This means you can come under the false impression that that nested data was already there when the console.log call was made, which is not at all guaranteed.

Add to this that the async: false option has been deprecated, so that the Ajax call will most probably ignore this setting and run asynchronously.

So, rewrite your code to use a callback function that gets called when the response is available, for instance with .done(). Note also that jQuery offers the $.getJSON method as a shortcut for your Ajax call:

$.getJSON("https://api.myjson.com/bins/bay0v").done(function (jsonData) {
    console.log(jsonData.current.timeSeries[0].beginTimeSeconds);
    var options = {
        title : 'Sample json line chart',
        curveType : 'function',
    };
    // ...etc. Rest of your code comes here, or is called from here.
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
I'm stuck with this issue. I've the below nested json.

{
  "current": {
    "timeSeries": [
      {
        "results": [
          {
            "count": 426
          }
        ],
        "beginTimeSeconds": 1490928320,
        "endTimeSeconds": 1490930120,
        "inspectedCount": 426
      },
      {
        "results": [
          {
            "count": 510
          }
        ],
        "beginTimeSeconds": 1490930120,
        "endTimeSeconds": 1490931920,
        "inspectedCount": 510
      }
    ]
  },
  "previous": {
    "timeSeries": [
      {
        "results": [
          {
            "count": 426
          }
        ],
        "beginTimeSeconds": 1490928320,
        "endTimeSeconds": 1490930120,
        "inspectedCount": 426
      },
      {
        "results": [
          {
            "count": 510
          }
        ],
        "beginTimeSeconds": 1490930120,
        "endTimeSeconds": 1490931920,
        "inspectedCount": 510
      }
    ]
  }
}

And I'm trying to extract data from the above json and present it on webpage using google visualization api.

I've tried with below js and it didn't work.

function drawChart() {
  var jsonData = $.ajax({
      url: "https://api.myjson.com/bins/bay0v",
      dataType: "json",
      async: false
      }).responseText;

   var options = {
      title : 'Sample json line chart',
      curveType : 'function',
    };

//var obj = JSON.parse(jsonData);
console.log(jsonData);
console.log(jsonData.current.timeSeries[0].beginTimeSeconds);

    var options = {
       hAxis: {
         title: 'Time',
         textStyle: {
           color: '#01579b',
           fontSize: 20,
           fontName: 'Arial',
           bold: true,
           italic: true
         },
         titleTextStyle: {
           color: '#01579b',
           fontSize: 16,
           fontName: 'Arial',
           bold: false,
           italic: true
         }
       },
       vAxis: {
         title: 'Popularity',
         textStyle: {
           color: '#1a237e',
           fontSize: 24,
           bold: true
         },
         titleTextStyle: {
           color: '#1a237e',
           fontSize: 24,
           bold: true
         }
       },
       colors: ['#a52714', '#097138']
     };

  // Instantiate and draw our chart, passing in some options.
  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
  chart.draw(data, {width: 1400, height: 360});
}

I'm seeing below output in browser console.

Uncaught TypeError: Cannot read property 'timeSeries' of undefined

Can someone please help me to solve this problem?

Thanks in advance.

Body:
The output of console.log can be misleading because browsers tend to only look at the contents of the logged variable when you actually drill down in the nested structure that the console provides.

This means you can come under the false impression that that nested data was already there when the console.log call was made, which is not at all guaranteed.

Add to this that the async: false option has been deprecated, so that the Ajax call will most probably ignore this setting and run asynchronously.

So, rewrite your code to use a callback function that gets called when the response is available, for instance with .done(). Note also that jQuery offers the $.getJSON method as a shortcut for your Ajax call:

$.getJSON("https://api.myjson.com/bins/bay0v").done(function (jsonData) {
    console.log(jsonData.current.timeSeries[0].beginTimeSeconds);
    var options = {
        title : 'Sample json line chart',
        curveType : 'function',
    };
    // ...etc. Rest of your code comes here, or is called from here.
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Classpath option works for javac but not for java (Windows)
After usually working with C# I tried writing some Java code yesterday to process an XML file. I didn't use an IDE or anything, just Notepad++, SDK and a lot of Google :)

I needed to include some jar files for which I found out, that one needs to set the classpath as a command line parameter to find the jar file. That worked well:

```<code>javac -cp "./metadata-extractor-2.9.1.jar;./xmpcore-5.1.2.jar" DescribeIt.java
</code>```

Although using the same syntax when running it with java.exe I had less luck:

```<code>java DescribeIt -cp "./metadata-extractor-2.9.1.jar;./xmpcore-5.1.2.jar"
</code>```

Leads to:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: com/drewimaging/ImageMetadataReader at DescribeIt.main(DescribeIt.java:53)
Caused by: java.lang.ClassNotFoundException: com.drew.imaging.ImageMetadataReader
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 1 more
</code>```

When I unzip the jar files, it works perfectly fine, but I guess that's not the way jar files are supposed to be used.

Code and build batch file can be found here

答:
Ouch! The problem was the order of parameters (and adding the current directory):</p>

```<code>java -cp "metadata-extractor-2.9.1.jar;xmpcore-5.1.2.jar;." DescribeIt
</code>```

Body:
After usually working with C# I tried writing some Java code yesterday to process an XML file. I didn't use an IDE or anything, just Notepad++, SDK and a lot of Google :)

I needed to include some jar files for which I found out, that one needs to set the classpath as a command line parameter to find the jar file. That worked well:

javac -cp "./metadata-extractor-2.9.1.jar;./xmpcore-5.1.2.jar" DescribeIt.java

Although using the same syntax when running it with java.exe I had less luck:

java DescribeIt -cp "./metadata-extractor-2.9.1.jar;./xmpcore-5.1.2.jar"

Leads to:

Exception in thread "main" java.lang.NoClassDefFoundError: com/drewimaging/ImageMetadataReader at DescribeIt.main(DescribeIt.java:53)
Caused by: java.lang.ClassNotFoundException: com.drew.imaging.ImageMetadataReader
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 1 more

When I unzip the jar files, it works perfectly fine, but I guess that's not the way jar files are supposed to be used.

Code and build batch file can be found here

Body:
Ouch! The problem was the order of parameters (and adding the current directory):

java -cp "metadata-extractor-2.9.1.jar;xmpcore-5.1.2.jar;." DescribeIt


问:
Syntax errror in SQL code
I have sql code for inser test value to db:

```<code>INSERT INTO log (from, value) VALUES ('ABC', 'DEF')
</code>```

I have table log:

```<code>from | value
</code>```

from and value are varchar(255).

When I run my code I a getting error:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

near 'from, value) VALUES ('ABC', 'DEF')' at line 1

I don't know why, can you give me advice? I have a syntax error in code? Or what?

答:
fromis a MySQL keyword. Rename the column if you can.

```<code>ALTER TABLE `log`
CHANGE COLUMN `from` `something_else` VARCHAR(255)
</code>```

If you can't, use backticks around the column names.

```<code>INSERT INTO `log` (`from`, `value`) VALUES ('ABC', 'DEF')
</code>```

Title: Syntax errror in SQL code

Body:
I have sql code for inser test value to db:

INSERT INTO log (from, value) VALUES ('ABC', 'DEF')

I have table log:

from | value

from and value are varchar(255).

When I run my code I a getting error:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

near 'from, value) VALUES ('ABC', 'DEF')' at line 1

I don't know why, can you give me advice? I have a syntax error in code? Or what?

Body:
fromis a MySQL keyword. Rename the column if you can.

ALTER TABLE `log`
CHANGE COLUMN `from` `something_else` VARCHAR(255)

If you can't, use backticks around the column names.

INSERT INTO `log` (`from`, `value`) VALUES ('ABC', 'DEF')


问:
Avoiding duplicates, SQLITE, android
I have a button, when user clicks it it passes some value and im adding this value with cv.put("name", name), how can i avoid adding duplicates?</p>

答:
it`s better to do it in your database structure
in your

```<code> SQLiteOpenHelper

 db.execSQL("CREATE TABLE "+MyDatabaseColums.USERINFOEntry.TABLE_NAME+" ("
                + MyDatabaseColums.USERINFOEntry.U_id+ " INTEGER , "
                + MyDatabaseColums.USERINFOEntry.mrname+ " TEXT, "
                + MyDatabaseColums.USERINFOEntry.meEmail+ " TEXT, "
"UNIQUE ( " +YOUR_id+") ON CONFLICT IGNORE"+");";
</code>```

this will ignore any conflict in your Field

or use

```<code> db.execSQL("CREATE TABLE "+MyDatabaseColums.USERINFOEntry.TABLE_NAME+" ("
                + MyDatabaseColums.USERINFOEntry.U_id+ " INTEGER , "
                + MyDatabaseColums.USERINFOEntry.mrname+ " TEXT, "
                + MyDatabaseColums.USERINFOEntry.meEmail+ " TEXT, "
"UNIQUE ( " +YOUR_id+") ON CONFLICT REPLACE"+");";
</code>```

to replace when conflict in Field

Title: Avoiding duplicates, SQLITE, android

Body:
it`s better to do it in your database structure
in your

 SQLiteOpenHelper

 db.execSQL("CREATE TABLE "+MyDatabaseColums.USERINFOEntry.TABLE_NAME+" ("
                + MyDatabaseColums.USERINFOEntry.U_id+ " INTEGER , "
                + MyDatabaseColums.USERINFOEntry.mrname+ " TEXT, "
                + MyDatabaseColums.USERINFOEntry.meEmail+ " TEXT, "
"UNIQUE ( " +YOUR_id+") ON CONFLICT IGNORE"+");";

this will ignore any conflict in your Field

or use

 db.execSQL("CREATE TABLE "+MyDatabaseColums.USERINFOEntry.TABLE_NAME+" ("
                + MyDatabaseColums.USERINFOEntry.U_id+ " INTEGER , "
                + MyDatabaseColums.USERINFOEntry.mrname+ " TEXT, "
                + MyDatabaseColums.USERINFOEntry.meEmail+ " TEXT, "
"UNIQUE ( " +YOUR_id+") ON CONFLICT REPLACE"+");";

to replace when conflict in Field


问:
i am stucking when i submitt my contact form
I have made a contact from... which is supposed to redirect a user to the "THANK YOU" page once the details of the same is submitted; However on submitting.. the user is not getting directed to the "THANK YOU PAGE". Can you please find out the mistake ? I would be really grateful.. THANK YOU SO MUCH!!  </p>

```<code><?php
include("company_profile/lib/data.config.php");
$btnsubmit  =isset($_POST['btnsubmit'])?$_POST['btnsubmit']:'';
if(isset($_POST['btnsubmit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$cource = $_POST['cource'];
$message = $_POST['message'];
$created_date = date('Y-m-d');
$time = date('H:i:s');
$q="Insert INTO enquiry_form SET name='$name',email='$email',
contact='$phone',message='$message',cource='$cource',
created_date='$created_date',etime='$time'";

    $r = mysqli_query($conn,$q);

   if($r)
    {
    //echo "Thankyou for Inquery";
    header("location:thanks.php");
    //echo "<script>alert('Message Send')</script>";

  }else
  {
    echo "there was a problem";
  }

  }

  ?>
</code>```

答:
In php you need to write ob_start(); at the start of your code to get your headers to buffer. You can see this previous post on the importance of ob_start: What's the use of ob_start() in php? or check out the php manual: http://php.net/manual/en/function.ob-start.php .

 If you don't have that snippit of code, your header won't work.

Body:
I have made a contact from... which is supposed to redirect a user to the "THANK YOU" page once the details of the same is submitted; However on submitting.. the user is not getting directed to the "THANK YOU PAGE". Can you please find out the mistake ? I would be really grateful.. THANK YOU SO MUCH!!

<?php
include("company_profile/lib/data.config.php");
$btnsubmit  =isset($_POST['btnsubmit'])?$_POST['btnsubmit']:'';
if(isset($_POST['btnsubmit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$cource = $_POST['cource'];
$message = $_POST['message'];
$created_date = date('Y-m-d');
$time = date('H:i:s');
$q="Insert INTO enquiry_form SET name='$name',email='$email',
contact='$phone',message='$message',cource='$cource',
created_date='$created_date',etime='$time'";

    $r = mysqli_query($conn,$q);

   if($r)
    {
    //echo "Thankyou for Inquery";
    header("location:thanks.php");
    //echo "";

  }else
  {
    echo "there was a problem";
  }

  }

  ?>


问:
Linux control a running vlc process through command line
is there any way to control an already running VLC player on ubuntu.
For example, i am trying to start a vlc video full screen with a default audio.

and then control the volume and other features through netcat or some other command remotely. is it possible?

答:
The script player control from exic's answer is just a wrapper for some dbus commands.
To use them without the script, try the following:

```<code>dbus-send --type=method_call --dest=org.mpris.MediaPlayer2.vlc /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.PlayPause
</code>```

The last PlayPause can be replaced with, e.g., Play, Pause, Previous, Next.

If you have qdbus installed, it can be used as an alternative to dbus-send:

```<code>qdbus org.mpris.MediaPlayer2.vlc /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.PlayPause
</code>```

A list of all available calls can be obtained by leaving out the last argument:

```<code>qdbus org.mpris.MediaPlayer2.vlc /org/mpris/MediaPlayer2
</code>```

Body:
The script player control from exic's answer is just a wrapper for some dbus commands.
To use them without the script, try the following:

dbus-send --type=method_call --dest=org.mpris.MediaPlayer2.vlc /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.PlayPause

The last PlayPause can be replaced with, e.g., Play, Pause, Previous, Next.

If you have qdbus installed, it can be used as an alternative to dbus-send:

qdbus org.mpris.MediaPlayer2.vlc /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.PlayPause

A list of all available calls can be obtained by leaving out the last argument:

qdbus org.mpris.MediaPlayer2.vlc /org/mpris/MediaPlayer2


问:
Webpack bundling failed - no such file node_modules\svgo\.svgo.yml
Am trying to bundle my angular 2 applications using webpack .my application both contain component typescript classes and css and html files.
i was able to bundle the js files(app.bundle.js).and i put the bundle.js file into the index html file and try to run it . but while running am getting error in the browser console .
this is my index html file

<!DOCTYPE html>

    <title>Angular QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <my-app>Loading client...</my-app>

```
</div>
</div>
</p>

<p>and this is the error am getting .</p>

```Error: moduleId should be a string in "e". If you're using Webpack you should inline the template and the styles.
```

<p>so i hope that this is because of not bundling the css files(bootstrap.min.css) .
so i tried to bundle that also.this is my web pack configuration file .</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry:'./app/main.ts',
output:{
    path:__dirname+'/dist',
    filename:'app.bundle.js'
},
module:{
    loaders:[
        {test:/\.ts$/,loader:'ts-loader'},
       {
        test: /\.css$/,
         use: ExtractTextPlugin.extract({
                use: 'css-loader'
            })
      }
    ]
},
plugins: [
        new ExtractTextPlugin('styles.css'),
    ],
resolve:{
    extensions:['.js','.ts','.css']
}

} </code>```

but while running this (webpack -p) am getting errors , the bundling not get successful.

this is the error am getting while running the webpack -p command

```<code>ERROR in ./bower_components/bootstrap/dist/css/bootstrap.min.cssModule build failed: Error: ENOENT: no such file or directory, open 'G:\mywork\Node\MyTaskList\client\node_modules\svgo\.svgo.yml'
at Error (native)
</code>```

could anyone please help me on this ?

New Update  : i tried to add the bootstrap.min.css manually into the index html file , then also it wont work , got the first error .so i hope there is something with the webpack bundle.

please help me on this

答:
Webpack expects the moduleId as string, while in Angular it's number. So in order to solve the issue, we should make the moduleId as string by using</p>

```<code>ModuleId:module.id.toString()
</code>```

Body:
Am trying to bundle my angular 2 applications using webpack .my application both contain component typescript classes and css and html files.
i was able to bundle the js files(app.bundle.js).and i put the bundle.js file into the index html file and try to run it . but while running am getting error in the browser console .
this is my index html file

<!DOCTYPE html>

    <title>Angular QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <my-app>Loading client...</my-app>

and this is the error am getting .

Error: moduleId should be a string in "e". If you're using Webpack you should inline the template and the styles.

so i hope that this is because of not bundling the css files(bootstrap.min.css) .
so i tried to bundle that also.this is my web pack configuration file .

var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry:'./app/main.ts',
output:{
    path:__dirname+'/dist',
    filename:'app.bundle.js'
},
module:{
    loaders:[
        {test:/\.ts$/,loader:'ts-loader'},
       {
        test: /\.css$/,
         use: ExtractTextPlugin.extract({
                use: 'css-loader'
            })
      }
    ]
},
plugins: [
        new ExtractTextPlugin('styles.css'),
    ],
resolve:{
    extensions:['.js','.ts','.css']
}

}

but while running this (webpack -p) am getting errors , the bundling not get successful.

this is the error am getting while running the webpack -p command

ERROR in ./bower_components/bootstrap/dist/css/bootstrap.min.cssModule build failed: Error: ENOENT: no such file or directory, open 'G:\mywork\Node\MyTaskList\client\node_modules\svgo\.svgo.yml'
at Error (native)

could anyone please help me on this ?

New Update  : i tried to add the bootstrap.min.css manually into the index html file , then also it wont work , got the first error .so i hope there is something with the webpack bundle.

please help me on this

Body:
Webpack expects the moduleId as string, while in Angular it's number. So in order to solve the issue, we should make the moduleId as string by using

ModuleId:module.id.toString()


问:
Can a 3rd party iPhone web browser (based on the SDK) access the contents of a page?

Can a 3rd party iPhone web browser (based on the SDK) access the contents of a page?

For example, can I select a portion of a page I'm viewing in my custom-made 3rd party iPhone app-based web browser and then instruct the browser app to perform an operation with the selected text and/or html-embedded image?

答: You can't access the content of a UIWebView directly. You can however use javascript to access the selected text in a UIWebView. There is even a tutorial that explains how you would do just that.


问:
Set MacVim default font
How do I set the default font for MacVim?

I have tried adding the following line

```<code>set guifont = Monaco:h12
</code>```

to either of the following files:

```<code>~/.vimrc
~/.gvimrc
~/Applications/MacVim/MacVim.app/Contents/Resources/vim/vimrc
~/Applications/MacVim/MacVim.app/Contents/Resources/vim/gvimrc
~/Applications/MacVim/MacVim.app/Contents/Resources/vim/.vimrc
~/Applications/MacVim/MacVim.app/Contents/Resources/vim/.gvimrc
</code>```

I restarted MacVim, but it still won't set the default font. Anything I missed?

UPDATE: I can issue the set guifont command in runtime and it works fine. It just doesn't seem to read it off my startup files.

答:
To deal with not just English characters, you can put this in your .vimrc file (guifontwide deals with Chinese characters):

```<code>if has("gui_running")
    set guifont=Consolas:h14
    set guifontwide=Hiragino\ Sans\ GB
    set linespace=2
endif
</code>```

Title: Set MacVim default font

Body:
How do I set the default font for MacVim?

I have tried adding the following line

set guifont = Monaco:h12

to either of the following files:

~/.vimrc
~/.gvimrc
~/Applications/MacVim/MacVim.app/Contents/Resources/vim/vimrc
~/Applications/MacVim/MacVim.app/Contents/Resources/vim/gvimrc
~/Applications/MacVim/MacVim.app/Contents/Resources/vim/.vimrc
~/Applications/MacVim/MacVim.app/Contents/Resources/vim/.gvimrc

I restarted MacVim, but it still won't set the default font. Anything I missed?

UPDATE: I can issue the set guifont command in runtime and it works fine. It just doesn't seem to read it off my startup files.

Body:
To deal with not just English characters, you can put this in your .vimrc file (guifontwide deals with Chinese characters):

if has("gui_running")
    set guifont=Consolas:h14
    set guifontwide=Hiragino\ Sans\ GB
    set linespace=2
endif


问:
Requiring a mongoose model from a file which creates the model during a series of promise.then.then chains.
no, you're not my wife, but it sure seems I spend more time with you than her lately.

Anyway, I'm converting a php site to node.js and have gotten the hang of creating mongoose schemas and then models. The only odd part is the fact that you need the model to be able to do any queries on the database.

So I've been var etc = require("./models/etc");'ing my models to be used in my index.js server for app.get requests. I model.find the data I want and pass it to a jade/pug template render.

This has been okay because in all my model files I create the schemas by hand, ie: I write the object, then make a model out of it, and then create documents with those schemas and save them.

But, now I have a product schema/object which relies on fetching products from a shopify api, creating a schema out of that product with a node module generate-schema, then creating the model, then looping through the products from shopify, creating a new document for each and appending some image urls and a couple of other properties and then saving the document.

This all happens in a series of .then(function())'s where an objects object is passed through the entire chain and stores all the variables I need from each function. Then at the end of that promise chain I try to module.exports = objects.variable (in this case it's a mongoose model). But because in index.js when I var product = require('./models/products') it does this asynchronously so the variable product is just {} instead of waiting for the .then promise chain to occur and then use the module.exports which is written at the end.

Is there a way to make require(x) wait for the module.exports to be populated or wait until the whole file has run it's course before assigning the variable?

Thank you.

Here's the code if you need it

```<code>var MongoClient = require('mongodb');

// mongodb = MongoClient.connect('mongodb://localhost/myleisure');

var mongoose = require('mongoose');

var fs = require('fs');
var path = require('path');

var generateSchema = require('generate-schema');

// mongoose.connect("mongodb://localhost/myleisure");
//
// var db = mongoose.connection;

var Schema = mongoose.Schema;

var shopify = require('shopify-buy');

var client = shopify.buildClient({
  accessToken: 'private',
  domain: 'my-leisure.myshopify.com',
  appId: 'X'
});

var write = true;

//Only uncomment if you want to export hell
// module.exports = function (callback) {

client.fetchProduct('8461073805').then(function(products) {
  var objects = {};

  objects.schema = generateSchema.mongoose(products.attrs.variants[0]);
  objects.products = products;

  return objects;

})
.then(function(objects){

  var productSchema = new Schema(objects.schema);

  productSchema.add({
    images: {type: [], default: null},
    thumbnail: {type: String, default: "thumb.jpg"},
    name: {type: String, default: "lettini"},
    colour: {type: String, default: null},
    finish: {type: String, default: null},
    size: {type: String, default: null},
    id: {type: String, default: objects.products.attrs.product_id},
    variantId: {type: String, default: null}
  });

  var product = mongoose.model("product", productSchema);

  product.remove({});
  objects.product = product;
  // callback(product)
  return objects;

}).then(function(objects){

  if(write)
    return objects.product.remove({name: "lettini"}).then(function(){

      return objects
    });

}).then(function(objects){
  if(write)
    var productsDir = "./img/products/lettinis/400x";
    var products = objects.products;
    var product = objects.product;
    // console.log(products.variants.length);
    // console.log(i);

    // console.log(schema);
    // console.log(products.attrs.variants);

    fs.readdir(productsDir, (err, skus) => {
      skus.forEach(sku => {
        for (var i = 0; i < products.variants.length - 1; i++) {
          if ( products.variants[i].attrs.variant.sku === sku) {

            var tempProduct = products.variants[i].attrs.variant;
            var newProduct = new product(tempProduct);

            fs.readdir(productsDir + "/" + sku, (err, images) => {
              images.forEach(image => {
                newProduct.colour = tempProduct.option_values[1].value;
                newProduct.frame = tempProduct.option_values[2].value;
                newProduct.size = tempProduct.option_values[0].value;
                newProduct.images.push(image);
              });
              newProduct.save();
            });

          };
        };
      });
    });

    return objects

}).then(function(objects){
  // console.log(objects.product);
  module.exports = objects.product;
});
</code>```

And in the index.js is simply

```<code>var product = require('./models/products');
console.log(product);
</code>```

output:

```<code>{}
</code>```

答:
Then at the end of that promise chain I try to module.exports = objects.variable (in this case it's a mongoose model). But it does this asynchronously

Don't asynchronously export something. Export the promise instead - immediately:

```<code>module.exports = client.fetchProduct(…).then(…)
.…
.then(function(objects){
  // console.log(objects.product);
  return objects.product;
});
</code>```

So that you can use the promise techniques (also things like Promise.all in case you load more modules) to wait for it in index.js:

```<code>require('./models/products').then(function(product) {
  console.log(product);
});
</code>```

Body:
no, you're not my wife, but it sure seems I spend more time with you than her lately.

Anyway, I'm converting a php site to node.js and have gotten the hang of creating mongoose schemas and then models. The only odd part is the fact that you need the model to be able to do any queries on the database.

So I've been var etc = require("./models/etc");'ing my models to be used in my index.js server for app.get requests. I model.find the data I want and pass it to a jade/pug template render.

This has been okay because in all my model files I create the schemas by hand, ie: I write the object, then make a model out of it, and then create documents with those schemas and save them.

But, now I have a product schema/object which relies on fetching products from a shopify api, creating a schema out of that product with a node module generate-schema, then creating the model, then looping through the products from shopify, creating a new document for each and appending some image urls and a couple of other properties and then saving the document.

This all happens in a series of .then(function())'s where an objects object is passed through the entire chain and stores all the variables I need from each function. Then at the end of that promise chain I try to module.exports = objects.variable (in this case it's a mongoose model). But because in index.js when I var product = require('./models/products') it does this asynchronously so the variable product is just {} instead of waiting for the .then promise chain to occur and then use the module.exports which is written at the end.

Is there a way to make require(x) wait for the module.exports to be populated or wait until the whole file has run it's course before assigning the variable?

Thank you.

Here's the code if you need it

var MongoClient = require('mongodb');

// mongodb = MongoClient.connect('mongodb://localhost/myleisure');

var mongoose = require('mongoose');

var fs = require('fs');
var path = require('path');

var generateSchema = require('generate-schema');

// mongoose.connect("mongodb://localhost/myleisure");
//
// var db = mongoose.connection;

var Schema = mongoose.Schema;

var shopify = require('shopify-buy');

var client = shopify.buildClient({
  accessToken: 'private',
  domain: 'my-leisure.myshopify.com',
  appId: 'X'
});

var write = true;

//Only uncomment if you want to export hell
// module.exports = function (callback) {

client.fetchProduct('8461073805').then(function(products) {
  var objects = {};

  objects.schema = generateSchema.mongoose(products.attrs.variants[0]);
  objects.products = products;

  return objects;

})
.then(function(objects){

  var productSchema = new Schema(objects.schema);

  productSchema.add({
    images: {type: [], default: null},
    thumbnail: {type: String, default: "thumb.jpg"},
    name: {type: String, default: "lettini"},
    colour: {type: String, default: null},
    finish: {type: String, default: null},
    size: {type: String, default: null},
    id: {type: String, default: objects.products.attrs.product_id},
    variantId: {type: String, default: null}
  });

  var product = mongoose.model("product", productSchema);

  product.remove({});
  objects.product = product;
  // callback(product)
  return objects;

}).then(function(objects){

  if(write)
    return objects.product.remove({name: "lettini"}).then(function(){

      return objects
    });

}).then(function(objects){
  if(write)
    var productsDir = "./img/products/lettinis/400x";
    var products = objects.products;
    var product = objects.product;
    // console.log(products.variants.length);
    // console.log(i);

    // console.log(schema);
    // console.log(products.attrs.variants);

    fs.readdir(productsDir, (err, skus) => {
      skus.forEach(sku => {
        for (var i = 0; i < products.variants.length - 1; i++) {
          if ( products.variants[i].attrs.variant.sku === sku) {

            var tempProduct = products.variants[i].attrs.variant;
            var newProduct = new product(tempProduct);

            fs.readdir(productsDir + "/" + sku, (err, images) => {
              images.forEach(image => {
                newProduct.colour = tempProduct.option_values[1].value;
                newProduct.frame = tempProduct.option_values[2].value;
                newProduct.size = tempProduct.option_values[0].value;
                newProduct.images.push(image);
              });
              newProduct.save();
            });

          };
        };
      });
    });

    return objects

}).then(function(objects){
  // console.log(objects.product);
  module.exports = objects.product;
});

And in the index.js is simply

var product = require('./models/products');
console.log(product);

output:

{}

Body:
Then at the end of that promise chain I try to module.exports = objects.variable (in this case it's a mongoose model). But it does this asynchronously

Don't asynchronously export something. Export the promise instead - immediately:

module.exports = client.fetchProduct(…).then(…)
.…
.then(function(objects){
  // console.log(objects.product);
  return objects.product;
});

So that you can use the promise techniques (also things like Promise.all in case you load more modules) to wait for it in index.js:

require('./models/products').then(function(product) {
  console.log(product);
});


问:
How do I pass variable value of one activity to baseactivity in android
I have BaseActivity and LoginActivity in my application where access token is being fetched from web service. I do not want to save access token in static or shared preference so I want to make it available accessToken to BaseActivity from LoginActivity so it can be access across the application which extends BaseActivity using simple method.

BaseActivity.java

```<code>@Override
public String getAccessToken() {
    return accessToken;
}
</code>```

Any idea how I can do this

答:
I do not want to save access token in static or shared preference so
  I want to make it available accessToken to BaseActivity from
  LoginActivity so it can be access across the application which extends
  BaseActivity using simple method.

if the field is not static each class extending BaseActivity will have its own instance of accessToken, meaning that this field has to be filled every time. If you want to fetch/fill it only once you could use the Singleton pattern. You can read more about it here

E.g. You could use enum to create a thread safe singleton

```<code>public enum AccessToken {
    INSTANCE("myaccesstoken");

    AccessToken (String accessToken) {
        mAccessToken = accessToken;
    }

    String mAccessToken;

    public String getAccessToken() {
        return mAccessToken;
    }
}
</code>```

and then   AccessToken.INSTANCE.getAccessToken();

Body:
I have BaseActivity and LoginActivity in my application where access token is being fetched from web service. I do not want to save access token in static or shared preference so I want to make it available accessToken to BaseActivity from LoginActivity so it can be access across the application which extends BaseActivity using simple method.

BaseActivity.java

@Override
public String getAccessToken() {
    return accessToken;
}

Any idea how I can do this

Body:
I do not want to save access token in static or shared preference so
  I want to make it available accessToken to BaseActivity from
  LoginActivity so it can be access across the application which extends
  BaseActivity using simple method.

if the field is not static each class extending BaseActivity will have its own instance of accessToken, meaning that this field has to be filled every time. If you want to fetch/fill it only once you could use the Singleton pattern. You can read more about it here

E.g. You could use enum to create a thread safe singleton

public enum AccessToken {
    INSTANCE("myaccesstoken");

    AccessToken (String accessToken) {
        mAccessToken = accessToken;
    }

    String mAccessToken;

    public String getAccessToken() {
        return mAccessToken;
    }
}

and then   AccessToken.INSTANCE.getAccessToken();


问:
400 error with bing news search api
I'm having a couple of problems with the bing news search api, the strangest one is searching by category, according to the documentation, the category must be a string, I found multiple resources for which values it accepts so i decided to go with console (https://dev.cognitive.microsoft.com/docs/services/56b43f72cf5ff8098cef380a/operations/56b449fbcf5ff81038d15cdf/console). Once you select a category and put it your key, it works fine.
The problem is when i copy the exact same URL from the console to postman, i use the same key and i get "400 Bad Request" header with this body:

```<code>{
  "_type": "ErrorResponse",
  "errors": [
    {
      "code": "RequestParameterInvalidValue",
      "message": "Parameter has invalid value.The category parameter is invalid.",
      "parameter": "category",
      "value": "Entertainment"
    }
  ]
}
</code>```

any idea what i'm doing wrong here?

答:
Here's a very Hacky workaround:
since the request works fine via the developer console, i inspected the request and tried to repeate it thought curl, seems to work fine, the command is as follows:

```<code>curl 'https://dev.cognitive.microsoft.com/console/query'  -H 'Content-Type: application/json' --data-binary '{"httpMethod":"GET","host":"api.cognitive.microsoft.com","scheme":"https","path":"bing/v5.0/news/?Category=Entertainment","headers":[{"name":"Host","value":"api.cognitive.microsoft.com","inputTypeValue":"text","revealed":false,"options":null,"required":true,"readonly":true,"custom":false},{"name":"Ocp-Apim-Subscription-Key","value":"<your key value>","inputTypeValue":"password","revealed":false,"options":[],"required":true,"readonly":false,"custom":true,"secret":true}],"parameters":[{"name":"Category","value":"Entertainment","inputType":"text","required":false,"options":["Business","Entertainment","Health","Politics","ScienceAndTechnology","Sports","US/UK","World"],"custom":false,"description":"<p>Specifies which category of news articles the caller wants returned.</p>\n","typeName":"string"}],"body":""}'
</code>```

The json data I'm sending is this (copied from the command above)

{     "httpMethod": "GET",    "host": "api.cognitive.microsoft.com",
    "scheme": "https",  "path": "bing/v5.0/news/?Category=Entertainment",
    "headers": [{       "name": "Host",         "value":
  "api.cognitive.microsoft.com",        "inputTypeValue": "text",
        "revealed": false,      "options": null,        "required": true,
        "readonly": true,       "custom": false     }, {        "name":
  "Ocp-Apim-Subscription-Key",      "value": "",
        "inputTypeValue": "password",       "revealed": false,      "options": [],
        "required": true,       "readonly": false,      "custom": true,         "secret":
  true  }],     "parameters": [{        "name": "Category",         "value":
  "Entertainment",      "inputType": "text",        "required": false,
        "options": ["Business", "Entertainment", "Health", "Politics",
  "ScienceAndTechnology", "Sports", "US/UK", "World"],      "custom":
  false,        "description": "
Specifies which category of news articles
  the caller wants returned.
\n",        "typeName": "string"    }],
    "body": "" }

I'll mark this as correct for now since i can't find any other solution

Title: 400 error with bing news search api

Body:
I'm having a couple of problems with the bing news search api, the strangest one is searching by category, according to the documentation, the category must be a string, I found multiple resources for which values it accepts so i decided to go with console (https://dev.cognitive.microsoft.com/docs/services/56b43f72cf5ff8098cef380a/operations/56b449fbcf5ff81038d15cdf/console). Once you select a category and put it your key, it works fine.
The problem is when i copy the exact same URL from the console to postman, i use the same key and i get "400 Bad Request" header with this body:

{
  "_type": "ErrorResponse",
  "errors": [
    {
      "code": "RequestParameterInvalidValue",
      "message": "Parameter has invalid value.The category parameter is invalid.",
      "parameter": "category",
      "value": "Entertainment"
    }
  ]
}

any idea what i'm doing wrong here?

Body:
Here's a very Hacky workaround:
since the request works fine via the developer console, i inspected the request and tried to repeate it thought curl, seems to work fine, the command is as follows:

curl 'https://dev.cognitive.microsoft.com/console/query'  -H 'Content-Type: application/json' --data-binary '{"httpMethod":"GET","host":"api.cognitive.microsoft.com","scheme":"https","path":"bing/v5.0/news/?Category=Entertainment","headers":[{"name":"Host","value":"api.cognitive.microsoft.com","inputTypeValue":"text","revealed":false,"options":null,"required":true,"readonly":true,"custom":false},{"name":"Ocp-Apim-Subscription-Key","value":"<your key value>","inputTypeValue":"password","revealed":false,"options":[],"required":true,"readonly":false,"custom":true,"secret":true}],"parameters":[{"name":"Category","value":"Entertainment","inputType":"text","required":false,"options":["Business","Entertainment","Health","Politics","ScienceAndTechnology","Sports","US/UK","World"],"custom":false,"description":"<p>Specifies which category of news articles the caller wants returned.</p>\n","typeName":"string"}],"body":""}'

The json data I'm sending is this (copied from the command above)

{     "httpMethod": "GET",    "host": "api.cognitive.microsoft.com",
    "scheme": "https",  "path": "bing/v5.0/news/?Category=Entertainment",
    "headers": [{       "name": "Host",         "value":
  "api.cognitive.microsoft.com",        "inputTypeValue": "text",
        "revealed": false,      "options": null,        "required": true,
        "readonly": true,       "custom": false     }, {        "name":
  "Ocp-Apim-Subscription-Key",      "value": "",
        "inputTypeValue": "password",       "revealed": false,      "options": [],
        "required": true,       "readonly": false,      "custom": true,         "secret":
  true  }],     "parameters": [{        "name": "Category",         "value":
  "Entertainment",      "inputType": "text",        "required": false,
        "options": ["Business", "Entertainment", "Health", "Politics",
  "ScienceAndTechnology", "Sports", "US/UK", "World"],      "custom":
  false,        "description": "
Specifies which category of news articles
  the caller wants returned.
\n",        "typeName": "string"    }],
    "body": "" }

I'll mark this as correct for now since i can't find any other solution


问:
Configure a first cell by default in Jupyter notebooks
TIs there a way to configure a default first cell for a specific python kernel in the Jupyter notebook? I agree that default python imports go against good coding practices.

So, can I configure the notebook such that the first cell of a new python notebook is always

```<code>import numpy as np
</code>```

for instance?

答:
Creating an IPython profile as mentioned above is a good first solution, but IMO it isn't totally satisfying, especially when it comes to code sharing.

The names of your libraries imported through the command exec_lines do not appear in the notebook, so you can easily forget it. And running the code on another profile / machine would raise an error.

Therefore I would recommend to use a Jupyter notebook extension, because the imported libraries are displayed. It avoids importing always the same libraries at the beginning of a notebook.
First you need to install the nbextension of Jupyter.
You can either clone the repo : https://github.com/ipython-contrib/jupyter_contrib_nbextensions
or use the pip : pip install jupyter_contrib_nbextensions

Then you can create a nb extension by adding a folder 'default_cells' to the path where the nb extensions are installed. For example on Ubuntu it's /usr/local/share/jupyter/nbextensions/., maybe on windows : C:\Users\xxx.xxx\AppData\Roaming\jupyter\nbextensions\

You have to create 3 files in this folder:

main.js which contains the js code of the extension

default_cells.yaml description for the API in Jupyter

README.MD the usual description for the reader appearing in the API.

I used the code from : https://github.com/jupyter/notebook/issues/1451my main.js is :

    define([
        'base/js/namespace'
    ], function(
        Jupyter
    ) {
        function load_ipython_extension() {
          if (Jupyter.notebook.get_cells().length===1){
       //do your thing
            Jupyter.notebook.insert_cell_above('code', 0).set_text("# Scientific libraries\nimport numpy as np\nimport scipy\n\n# import Pandas\n\nimport pandas as pd\n\n# Graphic libraries\n\nimport matplotlib as plt\n%matplotlib inline\nimport seaborn as sns\nfrom plotly.offline import init_notebook_mode, iplot, download_plotlyjs\ninit_notebook_mode()\nimport plotly.graph_objs as go\n\n# Extra options \n\npd.options.display.max_rows = 10\npd.set_option('max_columns', 50)\nsns.set(style='ticks', context='talk')\n\n# Creating alias for magic commands\n%alias_magic t time");
          }
        }
        return {
            load_ipython_extension: load_ipython_extension
        };
    });
```
<p>the .yaml has to be formatted like this :</p>
<pre class="lang-yaml prettyprint-override"><code>    Type: IPython Notebook Extension
    Compatibility: 3.x, 4.x
    Name: Default cells
    Main: main.js
    Link: README.md
    Description: |
      Add a default cell for each new notebook. Useful when you import always the same libraries$

    Parameters:
    - none
</code>```

and the README.md

    default_cells
    =========

    Add default cells to each new notebook. You have to modify this line in the main.js file to change your default cell. For example

    `Jupyter.notebook.insert_cell_above('code', 0).set_text("import numpy as np/nimportpandas as pd")`

    You can also add another default cell by creating a new line just below :

    `Jupyter.notebook.insert_cell_above('code', 1).set_text("from sklearn.meatrics import mean_squared_error")`

    **Don't forget to increment 1 if you want more than one extra cell. **
```

Then you just have to enable the 'Default cells' extension in the new tab 'nbextensions' which appeared in Jupyter.

The only issue is that it detects if the notebook is new, by looking at the number of cells in the notebook. But if you wrote all your code in one cell, it will detect it as a new notebook and still add the default cells.

Body:
TIs there a way to configure a default first cell for a specific python kernel in the Jupyter notebook? I agree that default python imports go against good coding practices.

So, can I configure the notebook such that the first cell of a new python notebook is always

import numpy as np

for instance?

Body:
Creating an IPython profile as mentioned above is a good first solution, but IMO it isn't totally satisfying, especially when it comes to code sharing.

The names of your libraries imported through the command exec_lines do not appear in the notebook, so you can easily forget it. And running the code on another profile / machine would raise an error.

Therefore I would recommend to use a Jupyter notebook extension, because the imported libraries are displayed. It avoids importing always the same libraries at the beginning of a notebook.
First you need to install the nbextension of Jupyter.
You can either clone the repo : https://github.com/ipython-contrib/jupyter_contrib_nbextensions
or use the pip : pip install jupyter_contrib_nbextensions

Then you can create a nb extension by adding a folder 'default_cells' to the path where the nb extensions are installed. For example on Ubuntu it's /usr/local/share/jupyter/nbextensions/., maybe on windows : C:\Users\xxx.xxx\AppData\Roaming\jupyter\nbextensions\

You have to create 3 files in this folder:

main.js which contains the js code of the extension

default_cells.yaml description for the API in Jupyter

README.MD the usual description for the reader appearing in the API.

I used the code from : https://github.com/jupyter/notebook/issues/1451my main.js is :

    define([
        'base/js/namespace'
    ], function(
        Jupyter
    ) {
        function load_ipython_extension() {
          if (Jupyter.notebook.get_cells().length===1){
       //do your thing
            Jupyter.notebook.insert_cell_above('code', 0).set_text("# Scientific libraries\nimport numpy as np\nimport scipy\n\n# import Pandas\n\nimport pandas as pd\n\n# Graphic libraries\n\nimport matplotlib as plt\n%matplotlib inline\nimport seaborn as sns\nfrom plotly.offline import init_notebook_mode, iplot, download_plotlyjs\ninit_notebook_mode()\nimport plotly.graph_objs as go\n\n# Extra options \n\npd.options.display.max_rows = 10\npd.set_option('max_columns', 50)\nsns.set(style='ticks', context='talk')\n\n# Creating alias for magic commands\n%alias_magic t time");
          }
        }
        return {
            load_ipython_extension: load_ipython_extension
        };
    });

the .yaml has to be formatted like this :

    Type: IPython Notebook Extension
    Compatibility: 3.x, 4.x
    Name: Default cells
    Main: main.js
    Link: README.md
    Description: |
      Add a default cell for each new notebook. Useful when you import always the same libraries$

    Parameters:
    - none

and the README.md

    default_cells
    =========

    Add default cells to each new notebook. You have to modify this line in the main.js file to change your default cell. For example

    `Jupyter.notebook.insert_cell_above('code', 0).set_text("import numpy as np/nimportpandas as pd")`

    You can also add another default cell by creating a new line just below :

    `Jupyter.notebook.insert_cell_above('code', 1).set_text("from sklearn.meatrics import mean_squared_error")`

    **Don't forget to increment 1 if you want more than one extra cell. **

Then you just have to enable the 'Default cells' extension in the new tab 'nbextensions' which appeared in Jupyter.

The only issue is that it detects if the notebook is new, by looking at the number of cells in the notebook. But if you wrote all your code in one cell, it will detect it as a new notebook and still add the default cells.


问:
How to see exception generated into django template variable?
Inside a Django template, one can call an object method like this :

```<code>{{ my_object.my_method }}
</code>```

The problem is when you get an exception/bug in 'def my_method(self)', it is hidden when rendering the template (there is an empty string output instead, so no errors appears).

As I want to debug what's wrong in 'def my_method(self)', I would like to turn on something like a global django flag to receive such exception.

in settings.py, I already have

```<code>DEBUG = True
TEMPLATE_DEBUG = True
</code>```

I can receive many kind of template exceptions, but none when I trig an object method.

What can I do ?

答:
Finally I Found a solution: I developed a template debug tag :

```<code>from django import template
import traceback

class DebugVariable(template.Variable):
    def _resolve_lookup(self, context):
        current = context
        for bit in self.lookups:
            try: # dictionary lookup
                current = current[bit]
            except (TypeError, AttributeError, KeyError):
                try: # attribute lookup
                    current = getattr(current, bit)
                    if callable(current):
                        if getattr(current, 'alters_data', False):
                            current = settings.TEMPLATE_STRING_IF_INVALID
                        else:
                            try: # method call (assuming no args required)
                                current = current()
                            except:
                                raise Exception("Template Object Method Error : %s" % traceback.format_exc())
                except (TypeError, AttributeError):
                    try: # list-index lookup
                        current = current[int(bit)]
                    except (IndexError, # list index out of range
                            ValueError, # invalid literal for int()
                            KeyError,   # current is a dict without `int(bit)` key
                            TypeError,  # unsubscriptable object
                            ):
                        raise template.VariableDoesNotExist("Failed lookup for key [%s] in %r", (bit, current)) # missing attribute
                except Exception, e:
                    if getattr(e, 'silent_variable_failure', False):
                        current = settings.TEMPLATE_STRING_IF_INVALID
                    else:
                        raise
            except Exception, e:
                if getattr(e, 'silent_variable_failure', False):
                    current = settings.TEMPLATE_STRING_IF_INVALID
                else:
                    raise

        return current

class DebugVarNode(template.Node):
    def __init__(self, var):
        self.var = DebugVariable(var)

    def render(self, context):
        return self.var.resolve(context)

@register.tag('debug_var')
def do_debug_var(parser, token):
    """
    raise every variable rendering exception, TypeError included (usually hidden by django)

    Syntax::
        {% debug_var obj.my_method %} instead of {{ obj.my_method }}
    """
    bits = token.contents.split()
    if len(bits) != 2:
        raise template.TemplateSyntaxError("'%s' tag takes one argument" % bits[0])
    return DebugVarNode(bits[1])
</code>```

So now in my template I just replace

```<code>{{ my_object.my_method }} by {% debug_var my_object.my_method %}
</code>```

Body:
Inside a Django template, one can call an object method like this :

{{ my_object.my_method }}

The problem is when you get an exception/bug in 'def my_method(self)', it is hidden when rendering the template (there is an empty string output instead, so no errors appears).

As I want to debug what's wrong in 'def my_method(self)', I would like to turn on something like a global django flag to receive such exception.

in settings.py, I already have

DEBUG = True
TEMPLATE_DEBUG = True

I can receive many kind of template exceptions, but none when I trig an object method.

What can I do ?

Body:
Finally I Found a solution: I developed a template debug tag :

from django import template
import traceback

class DebugVariable(template.Variable):
    def _resolve_lookup(self, context):
        current = context
        for bit in self.lookups:
            try: # dictionary lookup
                current = current[bit]
            except (TypeError, AttributeError, KeyError):
                try: # attribute lookup
                    current = getattr(current, bit)
                    if callable(current):
                        if getattr(current, 'alters_data', False):
                            current = settings.TEMPLATE_STRING_IF_INVALID
                        else:
                            try: # method call (assuming no args required)
                                current = current()
                            except:
                                raise Exception("Template Object Method Error : %s" % traceback.format_exc())
                except (TypeError, AttributeError):
                    try: # list-index lookup
                        current = current[int(bit)]
                    except (IndexError, # list index out of range
                            ValueError, # invalid literal for int()
                            KeyError,   # current is a dict without `int(bit)` key
                            TypeError,  # unsubscriptable object
                            ):
                        raise template.VariableDoesNotExist("Failed lookup for key [%s] in %r", (bit, current)) # missing attribute
                except Exception, e:
                    if getattr(e, 'silent_variable_failure', False):
                        current = settings.TEMPLATE_STRING_IF_INVALID
                    else:
                        raise
            except Exception, e:
                if getattr(e, 'silent_variable_failure', False):
                    current = settings.TEMPLATE_STRING_IF_INVALID
                else:
                    raise

        return current

class DebugVarNode(template.Node):
    def __init__(self, var):
        self.var = DebugVariable(var)

    def render(self, context):
        return self.var.resolve(context)

@register.tag('debug_var')
def do_debug_var(parser, token):
    """
    raise every variable rendering exception, TypeError included (usually hidden by django)

    Syntax::
        {% debug_var obj.my_method %} instead of {{ obj.my_method }}
    """
    bits = token.contents.split()
    if len(bits) != 2:
        raise template.TemplateSyntaxError("'%s' tag takes one argument" % bits[0])
    return DebugVarNode(bits[1])

So now in my template I just replace

{{ my_object.my_method }} by {% debug_var my_object.my_method %}


问:
Azure AD B2C, get MFA verified phone number programmatically
When I create a user in my web app using a B2C policy, and use a number for MFA, that number gets stored under "Authentication Contact Info" in the portal. It does not get stored in the claim from what I can see.

How can I access this number programmatically? If I wanted to access for example the users surname I'd use:

```<code>var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
var name = identity.Claims.Where(c => c.Type == ClaimTypes.Surname).Select(c => c.Value).SingleOrDefault();
</code>```

Is there any way, like above or any other way like for example using Graph API, to access the stored phone number used during MFA?

答:
It's possible to retrieve the phone number for the MFA through Microsoft's provisioning API published here.

If you generate the code through svcutil.exe you will have to manually inject the soap authentication and version headers though. You can then use the GetUser or ListUser service call to actually retrieve the phone number of a specific user from your Azure AD B2C.

Body:
When I create a user in my web app using a B2C policy, and use a number for MFA, that number gets stored under "Authentication Contact Info" in the portal. It does not get stored in the claim from what I can see.

How can I access this number programmatically? If I wanted to access for example the users surname I'd use:

var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
var name = identity.Claims.Where(c => c.Type == ClaimTypes.Surname).Select(c => c.Value).SingleOrDefault();

Is there any way, like above or any other way like for example using Graph API, to access the stored phone number used during MFA?


问:
TDD - write test first?
I am trying to understand what is TDD.

After some reading if I understand correctly - for Laravel development, I need to write some PHPUnit Test BEFORE implementing functionality in controllers, routes, model, etc?

It should not be other way around? Implement functionality and then do some PHPUnit Test?

答: Your understanding is correct.  Following a test-driven development approach to software development your tests will set the expectation for the functionality that is yet to be written.  Therefore, initially any given test you write will fail and you will continue to develop a unit of code until it passes.  It's worth mentioning that in addition to the more common TDD approach towards unit tests, you may also embrace a similar methodology with an ATDD approach towards any potential acceptance tests.</p>

Title: TDD - write test first?


Title: Removing the last 2 elements in an array - Ruby

Body: If I have this array - [49, 33, 8, 45, 20, 6, 34, 50, 31, 36, 28, 42, 35, 32, 7, 2, 9, 1, 18, 21] how can I get this return - [49, 33, 8, 45, 20, 6, 34, 50, 31, 36, 28, 42, 35, 32, 7, 2, 9, 1] I've tried this and it doesn't work. array.size - 2..

Body:
Use

array = [49, 33, 8, 45, 20, 6, 34, 50, 31, 36, 28, 42, 35, 32, 7, 2, 9, 1, 18, 21]

for removing last two elements use

a[0..-3]

or

a[0..a.length-3]


问:
How do I rebuild parameter pack from TypeList
I have a variadic template typelist:

```<code>template <class... Types>
struct typelist {};
</code>```

Then how can I pass it to some external code that expects a parameter pack, say std::tuple. In other word, I need to store the parameter pack as a member or typedef in my typelist, like

```<code>...
struct typelist {
    using types = Types; // Imaginary syntax
}
</code>```

Yet this is rejected by the compiler saying Types is unexpanded.

Any workaround?

This question is mentioned in another way in comments of this question, yet was not covered by the existing answer.

Details as requested in comments:

If I compile (-std=c++17):

```<code>template <class... T>
struct typelist {};

std::tuple<typelist<int, int>> tp{0,1};
</code>```

g++ gives error: no matching function for call to ‘std::tuple<typelist<int, int> >::tuple(<brace-enclosed initializer list>)’
 std::tuple<typelist<int, int>> tp{0,1};

If I compile (-std=c++17):

```<code>template <class... T>
struct typelist {
    using types = T;
};
</code>```

g++ gives error: parameter packs not expanded with ‘...’:
     using types = T;

答:
You can't store a parameter pack in a type alias. You need to use template argument deduction to extract the arguments of your type_list for reuse. One way is to use a dummy function like so:

```<code>template <typename... Args>
struct type_list {};

template <typename... Args>
std::tuple<Args...> to_tuple(type_list<Args...>);

template <typename TypeList>
struct type_list_to_tuple {
  using type = decltype(to_tuple(std::declval<TypeList>()));
};

template <typename TypeList>
using type_list_to_tuple_t = typename type_list_to_tuple<TypeList>::type;

int main() {
  using my_type_list = type_list<int, float>;
  using my_tuple = type_list_to_tuple_t<my_type_list>;
  static_assert(std::is_same_v<my_tuple, std::tuple<int, float>>);
}
</code>```

Body:
I have a variadic template typelist:

template <class... Types>
struct typelist {};

Then how can I pass it to some external code that expects a parameter pack, say std::tuple. In other word, I need to store the parameter pack as a member or typedef in my typelist, like

...
struct typelist {
    using types = Types; // Imaginary syntax
}

Yet this is rejected by the compiler saying Types is unexpanded.

Any workaround?

This question is mentioned in another way in comments of this question, yet was not covered by the existing answer.

Details as requested in comments:

If I compile (-std=c++17):

template <class... T>
struct typelist {};

std::tuple<typelist<int, int>> tp{0,1};

g++ gives error: no matching function for call to ‘std::tuple<typelist<int, int> >::tuple(<brace-enclosed initializer list>)’
 std::tuple<typelist<int, int>> tp{0,1};

If I compile (-std=c++17):

template <class... T>
struct typelist {
    using types = T;
};

g++ gives error: parameter packs not expanded with ‘...’:
     using types = T;

Body:
You can't store a parameter pack in a type alias. You need to use template argument deduction to extract the arguments of your type_list for reuse. One way is to use a dummy function like so:

template <typename... Args>
struct type_list {};

template <typename... Args>
std::tuple<Args...> to_tuple(type_list<Args...>);

template <typename TypeList>
struct type_list_to_tuple {
  using type = decltype(to_tuple(std::declval<TypeList>()));
};

template <typename TypeList>
using type_list_to_tuple_t = typename type_list_to_tuple<TypeList>::type;

int main() {
  using my_type_list = type_list<int, float>;
  using my_tuple = type_list_to_tuple_t<my_type_list>;
  static_assert(std::is_same_v<my_tuple, std::tuple<int, float>>);
}


问:
Database which can remove records automatically by checking date column
Suppose there is a database which contains a table that has date and events column, there are total 10 records now I want that the records which are older then the current date should automatically be deleted and the present date records should be present in the database so as the future records should also be present, does anyone know something like this or can help me how to achieve this. any references would be helpful. I am open to php, phpmyadmin, sql. Any help would be appreciated.</p>

答:
Activate event support :

```<code>SET GLOBAL event_scheduler = ON;
</code>```

Add sheduler :

```<code>DELIMITER |
DROP EVENT IF EXISTS `clear_old_rows`|
CREATE EVENT `clear_old_rows`
    ON SCHEDULE
    EVERY 1 HOUR STARTS CURRENT_TIMESTAMP
    ON COMPLETION PRESERVE
    ENABLE
    COMMENT 'clear all rows < CURRENT_TIMESTAMP'
    DO
    BEGIN
        DELETE FROM tablename WHERE date < CURRENT_TIMESTAMP ;
    END |
DELIMITER ;
</code>```

Body:
Activate event support :

SET GLOBAL event_scheduler = ON;

Add sheduler :

DELIMITER |
DROP EVENT IF EXISTS `clear_old_rows`|
CREATE EVENT `clear_old_rows`
    ON SCHEDULE
    EVERY 1 HOUR STARTS CURRENT_TIMESTAMP
    ON COMPLETION PRESERVE
    ENABLE
    COMMENT 'clear all rows < CURRENT_TIMESTAMP'
    DO
    BEGIN
        DELETE FROM tablename WHERE date < CURRENT_TIMESTAMP ;
    END |
DELIMITER ;