问:
API URL not working in volley and working in browser url hit
URL example = http://webapi.example.com/api/order?data={...list[{...},{...}]}

```<code> GsonRequest request = new GsonRequest<OrderResponse>("URL example", null,
            OrderResponse.class, null, new Response.Listener<OrderResponse>() {
        @Override
        public void onResponse(OrderResponse response) {
            if (response.isSuccess()) {
                //sendNotification();
            } else {
                Toast.makeText(DeliveryManagementActivity.this, "Error in Server", Toast.LENGTH_SHORT).show();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.e("Error: " + error.getMessage());
        }
    });
</code>```

For the above code I am getting 400 error.

```<code>GsonRequest request = new GsonRequest<OrderResponse>(UrlConstants.SEND_ORDERS_URL, getParams(),
            OrderResponse.class, header, new Response.Listener<OrderResponse>() {
        @Override
        public void onResponse(OrderResponse response) {
            if (response.isSuccess()) {
                sendNotification();
            } else {
                Toast.makeText(DeliveryManagementActivity.this, "Error in Server", Toast.LENGTH_SHORT).show();
            }
            hideLoader();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            VolleyLog.e("Error: " + error.getMessage());
            Toast.makeText(DeliveryManagementActivity.this, "Error " + error.getMessage(), Toast.LENGTH_SHORT).show();
            hideLoader();
        }
    });

public Map<String, String> getHeaders() throws AuthFailureError {
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/json");
    return headers;
}

private Map<String, String> getParams() {
    Map<String, String> params = new HashMap<String, String>();
    params.put("orderData", requestData.getOrderRequest(requestData));

    return params;
}
</code>```

For the above I am getting always false wrong response from server. I copied the  request from 1st request method and used browser url to hit the API. It worked well.

Edited:

After changing to second way, the request is going like below.

url = www.url.com/addOrder.php?

params = {"orderData":"{\"deliveryTime\":\"2017-12-10 01:13:00\",\"orderDetail\":[{\"courseId\":\"1\",\"foodQuantity\":\"2\",\"offer_id\":\"-1\",\"type\":\"1\"}],\"userID\":\"7\",\"userLocation\":\"17\"}"}

The orderData also parsing inside the json and missing =. Is that is the issue. The url at the top of question is actual and it is working.

答:
Is the query param name orderData? The query param used in the url is data.
Else code looks ok.

Body:
URL example = http://webapi.example.com/api/order?data={...list[{...},{...}]}

 GsonRequest request = new GsonRequest<OrderResponse>("URL example", null,
            OrderResponse.class, null, new Response.Listener<OrderResponse>() {
        @Override
        public void onResponse(OrderResponse response) {
            if (response.isSuccess()) {
                //sendNotification();
            } else {
                Toast.makeText(DeliveryManagementActivity.this, "Error in Server", Toast.LENGTH_SHORT).show();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.e("Error: " + error.getMessage());
        }
    });

For the above code I am getting 400 error.

GsonRequest request = new GsonRequest<OrderResponse>(UrlConstants.SEND_ORDERS_URL, getParams(),
            OrderResponse.class, header, new Response.Listener<OrderResponse>() {
        @Override
        public void onResponse(OrderResponse response) {
            if (response.isSuccess()) {
                sendNotification();
            } else {
                Toast.makeText(DeliveryManagementActivity.this, "Error in Server", Toast.LENGTH_SHORT).show();
            }
            hideLoader();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            VolleyLog.e("Error: " + error.getMessage());
            Toast.makeText(DeliveryManagementActivity.this, "Error " + error.getMessage(), Toast.LENGTH_SHORT).show();
            hideLoader();
        }
    });

public Map<String, String> getHeaders() throws AuthFailureError {
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/json");
    return headers;
}

private Map<String, String> getParams() {
    Map<String, String> params = new HashMap<String, String>();
    params.put("orderData", requestData.getOrderRequest(requestData));

    return params;
}

For the above I am getting always false wrong response from server. I copied the  request from 1st request method and used browser url to hit the API. It worked well.

Edited:

After changing to second way, the request is going like below.

url = www.url.com/addOrder.php?

params = {"orderData":"{\"deliveryTime\":\"2017-12-10 01:13:00\",\"orderDetail\":[{\"courseId\":\"1\",\"foodQuantity\":\"2\",\"offer_id\":\"-1\",\"type\":\"1\"}],\"userID\":\"7\",\"userLocation\":\"17\"}"}

The orderData also parsing inside the json and missing =. Is that is the issue. The url at the top of question is actual and it is working.


来源: stackexchange

问:
python flask: mimic werkzeug FileStorage object
I have the following route in a flask application which accepts an uploaded file and throws the file object into a function for validation. Here's a barebones example:

```<code>def is_file_valid(file):
    if file.filename == 'test':
        return True
    return False

@app.route('/validate', method=['POST'])
def validate():
    file = request.files['file']
    if is_file_valid(file):
        return redirect(url_for('somewhere'))
    return redirect(url_for('somewhere_else'))
</code>```

I'm trying to create a unittest to test the is_file_valid function but I'm having trouble creating the FileStorage object flask uses which appears to be very similar to a standard python file object (docs).

Here's what I've tried so far:

```<code>import io
with io.open('/path/to/file', 'rb') as f:
    print(f.filename)
</code>```

But I'm getting the following error:

```<code>AttributeError: 'io.TextIOWrapper' object has no attribute 'filename'
</code>```

Any idea how I can mimic werkzeug's FileStorage object in a regular python script?

答: Answered here. Just need to wrap the python file object in the werkzeug FileStorage class.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have the following route in a flask application which accepts an uploaded file and throws the file object into a function for validation. Here's a barebones example:

def is_file_valid(file):
    if file.filename == 'test':
        return True
    return False

@app.route('/validate', method=['POST'])
def validate():
    file = request.files['file']
    if is_file_valid(file):
        return redirect(url_for('somewhere'))
    return redirect(url_for('somewhere_else'))

I'm trying to create a unittest to test the is_file_valid function but I'm having trouble creating the FileStorage object flask uses which appears to be very similar to a standard python file object (docs).

Here's what I've tried so far:

import io
with io.open('/path/to/file', 'rb') as f:
    print(f.filename)

But I'm getting the following error:

AttributeError: 'io.TextIOWrapper' object has no attribute 'filename'

Any idea how I can mimic werkzeug's FileStorage object in a regular python script?


问:
Collect custom data from every connected client
In my MMORPG project from scratch, i'm currently stuck in getting the actual positions (x,y,z) of nearby online players to the place where a new character is about to login so he sees them in their right positions.
I have a variable that keeps track of the player's position, but i need to get all the nearby players without requesting the position from the client cuz as i said i have it stored in a variable.
Further explanation: A new player logged in and he's about to spawn. Near him there is 5 other players already logged in, so he should see them as soon as he spawn. On my multithreaded server code i have variable to keep updated position.

How can i implement that variable to get every connected client
  position or any other suggestions?

答:
The Foundation:

You are going to want to define a global update interval like 100ms, so that all clients remain in sync. Then you are going to want to use the UDP protocol to transmit their positions between the client and server. UDP is crucial to games as it is much faster, and TCP in this case will take too long.

Using UDP:

UDP is not hard to work with in C#. You establish a target server and the server establish a incoming port and then you can start accepting incoming and sending outgoing traffic. You will have to devise a way to remember which packet is for which player, but that is easy as long as you add to each UDP packet a unique tag. A beautiful explanation to getting started with UDP can be found here.


问:
How to parse unpredictable JSON objects?
My app parse JSON from an API based on user's selection. Since each user's search might be different I can't predict what the user will search and have a established parsing structure waiting for them every time I finish a API call.

The problem is how can I have a JSON parsing structure in my app that will handle this undefined/unpredictable JSON object from the different API call?

Basically what I need is a way to handle unpredictable and unknown JSON object like they were known and I could parse their keys and the data inside them.

Thank you.

答:
I would help more if I had your Code but hope my explanation will work for you. I recently made an app that picks stuff entered by users on the server-side and display on phone. For instance you choose rice and fish while another person chooses rice, fish, coffee and baked beans. These are different stuff but I made an array to hold the stuff, the length of the array depends on the number of stuff you pick. then I build a json object to parse. Note: you can count the number of items the user put and safe in the variable then use that variable as the length.

```<code>JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.getString(KEY_SUCCESS).equals("true")) {
              JSONArray dataArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < dataArray.length(); i++) {

                   JSONObject dataobj = dataArray.getJSONObject(i);
</code>```

I had saved all user input with "data". One thing my answer may not fit your description because I am not sure if you are getting a list input from user or something like a long paragraph/article. I assumed you are getting a list so I gave you an option to use arrays

Body:
I would help more if I had your Code but hope my explanation will work for you. I recently made an app that picks stuff entered by users on the server-side and display on phone. For instance you choose rice and fish while another person chooses rice, fish, coffee and baked beans. These are different stuff but I made an array to hold the stuff, the length of the array depends on the number of stuff you pick. then I build a json object to parse. Note: you can count the number of items the user put and safe in the variable then use that variable as the length.

JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.getString(KEY_SUCCESS).equals("true")) {
              JSONArray dataArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < dataArray.length(); i++) {

                   JSONObject dataobj = dataArray.getJSONObject(i);

I had saved all user input with "data". One thing my answer may not fit your description because I am not sure if you are getting a list input from user or something like a long paragraph/article. I assumed you are getting a list so I gave you an option to use arrays


问:
Bootstrap 3.3.7 hidden-xs not working
```<code>                <div class="col-md-6 hidden-xm hidden-sm">
                <div class="col-md-12 hidden-xm"><h3>ההזמנה שלך</h3></div>
                <div class="col-md-12 hidden-xm">
                    <div class="table-responsive hidden-xm">
                        <table class="table table-default">
                            <thead>
                                <tr>
                                    <th class="text-right">סה"כ</th>
                                    <th class="text-right">מוצר</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                    $totalPrice = 0;
                                    $arr = [];
                                    foreach($_SESSION['cart'] as $product){
                                        $productDetails = get_product($product['id']);
                                        array_push($arr,$product['amount']." x".$productDetails->get_name());
                                        $totalPrice+= $productDetails->get_price()*$product['amount'];
                                ?>
                                <tr>
                                    <td class="text-right"> <?php echo $productDetails->get_price()*$product['amount']; ?>$</td>
                                    <td class="text-right"><?php echo $productDetails->get_name()." <b>".$product['amount']."x</b>"; ?></td>
                                </tr>
                                <?php };?>
                                <tr>
                                    <td class="total_price">משלוח</td>
                                    <td>9$</td>
                                </tr>
                                <tr>
                                    <td class="text-right total_price">סה"כ</td>
                                    <td class="text-right"> <?php echo $totalPrice+9 ?>$</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="col-md-12 hidden-xm text-right"> אחריות מלאה על המוצרים ל-28 יום</div>
                    <input type="hidden" name="products" value="<?php echo implode("<br>",$arr) ?>">
                    <div class="text-left">
                        <input type="submit" name="submit" class="btn btn-lg btn-pay" value="שליחת הזמנה">
                    </div>
                </div>
            </div>
</code>```

I've tried for pretty long time to find out why the : hidden-xm/hidden-sm not working for me. Can someone tell me what am i doing wrong?

also I want to notice that this div is inside a bigger container but I want to hide it if its at a mobile point of view.

答: I'ts hidden-xs instead of hidden-xm

Title: Bootstrap 3.3.7 hidden-xs not working

Body:
ההזמנה שלך

                                    סה"כ
                                    מוצר

                                <?php
                                    $totalPrice = 0;
                                    $arr = [];
                                    foreach($_SESSION['cart'] as $product){
                                        $productDetails = get_product($product['id']);
                                        array_push($arr,$product['amount']." x".$productDetails->get_name());
                                        $totalPrice+= $productDetails->get_price()*$product['amount'];
                                ?>

                                     <?php echo $productDetails->get_price()*$product['amount']; ?>$
                                    <?php echo $productDetails->get_name()." ".$product['amount']."x"; ?>

                                <?php };?>

                                    משלוח
                                    9$

                                    סה"כ
                                     <?php echo $totalPrice+9 ?>$

 אחריות מלאה על המוצרים ל-28 יום

                    <input type="hidden" name="products" value="<?php echo implode("
",$arr) ?>">

                        <input type="submit" name="submit" class="btn btn-lg btn-pay" value="שליחת הזמנה">

I've tried for pretty long time to find out why the : hidden-xm/hidden-sm not working for me. Can someone tell me what am i doing wrong?

also I want to notice that this div is inside a bigger container but I want to hide it if its at a mobile point of view.

Body: I'ts hidden-xs instead of hidden-xm


问:
cordapp-template-java "No matching constructor found..."
I tried testing the Hello, World! Tutorial example and received the following error:

```<code>No matching constructor found:
- [arg0: Integer, arg1: Party]: missing parameter arg0
</code>```

This was generated by running the command:

```<code>start IOUFlow iouValue: 99, otherParty: "O=PartyB,L=New York,C=US"
</code>```

Please see here.

答:
Resolved this issue by using the command:

```<code>start IOUFlow arg0: 99, arg1: "O=PartyB,L=New York,C=US"
</code>```

According to this comment, you're only supposed to pass variables by name when using Kotlin Cordapps. When using Java Cordapps specify arg0, arg1, etc.

Body:
I tried testing the Hello, World! Tutorial example and received the following error:

No matching constructor found:
- [arg0: Integer, arg1: Party]: missing parameter arg0

This was generated by running the command:

start IOUFlow iouValue: 99, otherParty: "O=PartyB,L=New York,C=US"

Please see here.

Body:
Resolved this issue by using the command:

start IOUFlow arg0: 99, arg1: "O=PartyB,L=New York,C=US"

According to this comment, you're only supposed to pass variables by name when using Kotlin Cordapps. When using Java Cordapps specify arg0, arg1, etc.


问:
Angular *ngFor not populating any data
```<code>export class AppComponent {
  pickBtnClicked = false;
  selectedPickNumber: 'string';
  selectedRegion: 'string';
  currentPickSelection: any[];
  channelList: any[];

  constructor(private pickGroupService: PickGroupService, private channelsService: ChannelsService) {}

  onPkClick(btnPicked) {
    this.pickBtnClicked = true;
    this.selectedPickNumber = btnPicked;
  }
  onRegionClick(regionPicked) {
    this.selectedRegion = regionPicked;
    this.currentPickSelection = this.pickGroupService.getPickSet(this.selectedPickNumber, this.selectedRegion);
    console.log(this.currentPickSelection);
  }
}
</code>```

The console.log prints out this data to the browser console

But the ngFor in the below doesn't pick up any data from the "currentPickSelection" array.

```<code><ul class="w3-ul w3-card-4" align="right" >
          <li class="list-group-item" *ngFor="let channels of currentPickSelection">
            <strong><font size="2">{{ channels.channel }}</font><span class="w3-right"><font size="2">{{ channels.pickCode }}</font></span></strong>
          </li>
        </ul>
</code>```

Please advise! thanks

答:
Your html looks incorrect.
You have an array (which you use *ngFor on) with arrays inside that contain objects. Therefore you need to first access the object in each channels and then the props.

```<code><ul class="w3-ul w3-card-4" align="right" >
    <li class="list-group-item" *ngFor="let channels of currentPickSelection">
         <strong><font size="2">{{ channels[0].channel }}</font><span class="w3-right"><font size="2">{{ channels[0].pickCode }}</font></span></strong>
    </li>
</ul>
</code>```

Title: Angular *ngFor not populating any data

Body:
export class AppComponent {
  pickBtnClicked = false;
  selectedPickNumber: 'string';
  selectedRegion: 'string';
  currentPickSelection: any[];
  channelList: any[];

  constructor(private pickGroupService: PickGroupService, private channelsService: ChannelsService) {}

  onPkClick(btnPicked) {
    this.pickBtnClicked = true;
    this.selectedPickNumber = btnPicked;
  }
  onRegionClick(regionPicked) {
    this.selectedRegion = regionPicked;
    this.currentPickSelection = this.pickGroupService.getPickSet(this.selectedPickNumber, this.selectedRegion);
    console.log(this.currentPickSelection);
  }
}

The console.log prints out this data to the browser console

But the ngFor in the below doesn't pick up any data from the "currentPickSelection" array.

            {{ channels.channel }}{{ channels.pickCode }}

Please advise! thanks

Body:
Your html looks incorrect.
You have an array (which you use *ngFor on) with arrays inside that contain objects. Therefore you need to first access the object in each channels and then the props.

<ul class="w3-ul w3-card-4" align="right" >
    <li class="list-group-item" *ngFor="let channels of currentPickSelection">
         <strong><font size="2">{{ channels[0].channel }}</font><span class="w3-right"><font size="2">{{ channels[0].pickCode }}</font></span></strong>
    </li>
</ul>


问:
WooCommerce auto restore stock on order cancel
I'm looking for a solution to automatically restore stock when order is canceled. I'm using PayU gateway on my client's site and it works by setting all orders on hold when waiting for payment and cancels them after 24 hours if there's no valid payment made. However, this means that WooCommerce built-in mechanism for freezing stock and then restocking after given time doesn't work (as the payment gateway sets the status to on hold).

There was a plugin called WooCommerce Auto Restore Stock by Gerhard Potgieter but it's an oldie and I was unable to find a similar solution in WordPress plugin repository or on Codecanyon.

Perhaps someone stumbled upon a solution to auto restore stock for cancelled orders that works with WC 3.0+?

答:
According to woocommerce github issue here, they say that (24 hours hold stock & cancel without restock) is correct behavior. Orders can be cancelled for a variety of reasons - incorrect stock levels, faulty products, user choice etc etc therefore the re-increment of stock should be an entirely (manual) admin decision.

So, i try to override the function in my child theme`s functions.php and it works!

Here's the code :

```<code>remove_filter( 'woocommerce_cancel_unpaid_orders', 'wc_cancel_unpaid_orders' );
add_filter( 'woocommerce_cancel_unpaid_orders', 'override_cancel_unpaid_orders' );

function override_cancel_unpaid_orders() {
    $held_duration = get_option( 'woocommerce_hold_stock_minutes' );

    if ( $held_duration < 1 || 'yes' !== get_option( 'woocommerce_manage_stock' ) ) {
        return;
    }

    $data_store    = WC_Data_Store::load( 'order' );
    $unpaid_orders = $data_store->get_unpaid_orders( strtotime( '-' . absint( $held_duration ) . ' MINUTES', current_time( 'timestamp' ) ) );

    if ( $unpaid_orders ) {
        foreach ( $unpaid_orders as $unpaid_order ) {
            $order = wc_get_order( $unpaid_order );

            if ( apply_filters( 'woocommerce_cancel_unpaid_order', 'checkout' === $order->get_created_via(), $order ) ) {
                //Cancel Order
                $order->update_status( 'cancelled', __( 'Unpaid order cancelled - time limit reached.', 'woocommerce' ) );

                //Restock
                foreach ($order->get_items() as $item_id => $item) {
                    // Get an instance of corresponding the WC_Product object
                    $product = $item->get_product();
                    $qty = $item->get_quantity(); // Get the item quantity
                    wc_update_product_stock($product, $qty, 'increase');
                }
            }
        }
    }
    wp_clear_scheduled_hook( 'woocommerce_cancel_unpaid_orders' );
    wp_schedule_single_event( time() + ( absint( $held_duration ) * 60 ), 'woocommerce_cancel_unpaid_orders' );
}
</code>```

Hope it helps.

Body:
According to woocommerce github issue here, they say that (24 hours hold stock & cancel without restock) is correct behavior. Orders can be cancelled for a variety of reasons - incorrect stock levels, faulty products, user choice etc etc therefore the re-increment of stock should be an entirely (manual) admin decision.

So, i try to override the function in my child theme`s functions.php and it works!

Here's the code :

remove_filter( 'woocommerce_cancel_unpaid_orders', 'wc_cancel_unpaid_orders' );
add_filter( 'woocommerce_cancel_unpaid_orders', 'override_cancel_unpaid_orders' );

function override_cancel_unpaid_orders() {
    $held_duration = get_option( 'woocommerce_hold_stock_minutes' );

    if ( $held_duration < 1 || 'yes' !== get_option( 'woocommerce_manage_stock' ) ) {
        return;
    }

    $data_store    = WC_Data_Store::load( 'order' );
    $unpaid_orders = $data_store->get_unpaid_orders( strtotime( '-' . absint( $held_duration ) . ' MINUTES', current_time( 'timestamp' ) ) );

    if ( $unpaid_orders ) {
        foreach ( $unpaid_orders as $unpaid_order ) {
            $order = wc_get_order( $unpaid_order );

            if ( apply_filters( 'woocommerce_cancel_unpaid_order', 'checkout' === $order->get_created_via(), $order ) ) {
                //Cancel Order
                $order->update_status( 'cancelled', __( 'Unpaid order cancelled - time limit reached.', 'woocommerce' ) );

                //Restock
                foreach ($order->get_items() as $item_id => $item) {
                    // Get an instance of corresponding the WC_Product object
                    $product = $item->get_product();
                    $qty = $item->get_quantity(); // Get the item quantity
                    wc_update_product_stock($product, $qty, 'increase');
                }
            }
        }
    }
    wp_clear_scheduled_hook( 'woocommerce_cancel_unpaid_orders' );
    wp_schedule_single_event( time() + ( absint( $held_duration ) * 60 ), 'woocommerce_cancel_unpaid_orders' );
}

Hope it helps.


问:
Assit with FATAL EXCEPTION IN MAIN in android studio
I am new to android programming and am trying to the program to run but the problem is that the app builds and runs successfully but crashes whenever I press the GO button. My professor gave me this to accomplish as something to get started with android programming as he thought it would be challenging task that will be motivational and interesting. I looked everywhere for the solution but could not find it. My professor himself is unable to debug the code and hence.

The code is as given below:

```<code>**CODE 1**

package com.example.thispc.myapplication;
import android.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;

import java.util.Scanner;

import edu.princeton.cs.algs4.EdgeWeightedDigraph;
import edu.princeton.cs.algs4.DirectedEdge;
import edu.princeton.cs.algs4.BellmanFordSP;

public class Arbitrage extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_arbitrage);

    Button Check_Arbitrage = findViewById(R.id.Check_Arbitrage);
    Check_Arbitrage.setOnClickListener(new View.OnClickListener() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onClick(View view) {

            EditText inputcurrencynumber;
            EditText inputdata;
            TextView outputarbitrage;
            inputcurrencynumber = findViewById(R.id.GetNoCurrencies);
            inputdata = findViewById(R.id.currency_table_input);
            outputarbitrage = findViewById(R.id.result);

            inputcurrencynumber = findViewById(R.id.GetNoCurrencies);
            int V;
            V = Integer.parseInt(inputcurrencynumber.getText().toString());
            outputarbitrage = findViewById(R.id.result);

            double rate,stake;

            inputdata = findViewById(R.id.currency_table_input);

            EdgeWeightedDigraph G = new EdgeWeightedDigraph(V);
            outputarbitrage.setText("Hello World");

            String [] name = new String[V];
            // The error occures here when i try to take an input
            for (int v = 0; v < V ; v++)
            {`enter code here`
                name[v] = inputdata.getText().toString();
                for (int w = 0; w < V ; w++)
                {
                    rate = Double.parseDouble(inputdata.getText().toString());
                    DirectedEdge e = new DirectedEdge(v, w, -Math.log(rate));
                    G.addEdge(e);

                }
           }

            BellmanFordSP spt = new BellmanFordSP(G,0);

            if (spt.hasNegativeCycle())
            {
                stake = 1000;
                for (DirectedEdge e : spt.negativeCycle())
                {
                    //outputarbitrage.setText((Double.toString(stake) + name[e.from()]) + "  " + (Double.toString(stake) + name[e.to()]) + "\n");

                    outputarbitrage.setText("%10.5f %s " + stake + name[e.from()]);
                    stake = stake * Math.exp(-e.weight());
                    outputarbitrage.setText("= %10.5f %s\n" + stake + name[e.to()]);
                }
            }

            else
            {
                outputarbitrage.setText("No Arbitrage Opportunity Found");
            }
        }
    });

}
}
</code>```

Note : This code works perfectly in java IDE (I use netbeans) but crashes in android studio.

======================================================================================================================================================
EDIT 1

Added the log as below :

```<code>com.example.thispc.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: com.example.thispc.myapplication, PID: 4876
                                                                            java.lang.NumberFormatException: For input string: "USD 1 1.6 4
                                                                            CAD 2.3 1 1.3
                                                                            CHF 4 8 1"
                                                                                at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
                                                                                at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
                                                                                at java.lang.Double.parseDouble(Double.java:539)
                                                                                at com.example.thispc.myapplication.Arbitrage$1.onClick(Arbitrage.java:57)
                                                                                at android.view.View.performClick(View.java:6294)
                                                                                at android.view.View$PerformClick.run(View.java:24770)
                                                                                at android.os.Handler.handleCallback(Handler.java:790)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
</code>```

======================================================================================================================================================
EDIT 2

output

答:
Its getting crash because of the below line

```<code>rate = Double.parseDouble(inputdata.getText().toString());
</code>```

You are trying to parse the string and parseDoubel() expects the string value which only holds numeric value, but in your case inputdata.getText().toString() contains character other than numbers.

Try extracting digits form the inputdata before passing to parseDouble() method

```<code>str.replaceAll("[^0-9]", "");
</code>```

Body:
I am new to android programming and am trying to the program to run but the problem is that the app builds and runs successfully but crashes whenever I press the GO button. My professor gave me this to accomplish as something to get started with android programming as he thought it would be challenging task that will be motivational and interesting. I looked everywhere for the solution but could not find it. My professor himself is unable to debug the code and hence.

The code is as given below:

**CODE 1**

package com.example.thispc.myapplication;
import android.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;

import java.util.Scanner;

import edu.princeton.cs.algs4.EdgeWeightedDigraph;
import edu.princeton.cs.algs4.DirectedEdge;
import edu.princeton.cs.algs4.BellmanFordSP;

public class Arbitrage extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_arbitrage);

    Button Check_Arbitrage = findViewById(R.id.Check_Arbitrage);
    Check_Arbitrage.setOnClickListener(new View.OnClickListener() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onClick(View view) {

            EditText inputcurrencynumber;
            EditText inputdata;
            TextView outputarbitrage;
            inputcurrencynumber = findViewById(R.id.GetNoCurrencies);
            inputdata = findViewById(R.id.currency_table_input);
            outputarbitrage = findViewById(R.id.result);

            inputcurrencynumber = findViewById(R.id.GetNoCurrencies);
            int V;
            V = Integer.parseInt(inputcurrencynumber.getText().toString());
            outputarbitrage = findViewById(R.id.result);

            double rate,stake;

            inputdata = findViewById(R.id.currency_table_input);

            EdgeWeightedDigraph G = new EdgeWeightedDigraph(V);
            outputarbitrage.setText("Hello World");

            String [] name = new String[V];
            // The error occures here when i try to take an input
            for (int v = 0; v < V ; v++)
            {`enter code here`
                name[v] = inputdata.getText().toString();
                for (int w = 0; w < V ; w++)
                {
                    rate = Double.parseDouble(inputdata.getText().toString());
                    DirectedEdge e = new DirectedEdge(v, w, -Math.log(rate));
                    G.addEdge(e);

                }
           }

            BellmanFordSP spt = new BellmanFordSP(G,0);

            if (spt.hasNegativeCycle())
            {
                stake = 1000;
                for (DirectedEdge e : spt.negativeCycle())
                {
                    //outputarbitrage.setText((Double.toString(stake) + name[e.from()]) + "  " + (Double.toString(stake) + name[e.to()]) + "\n");

                    outputarbitrage.setText("%10.5f %s " + stake + name[e.from()]);
                    stake = stake * Math.exp(-e.weight());
                    outputarbitrage.setText("= %10.5f %s\n" + stake + name[e.to()]);
                }
            }

            else
            {
                outputarbitrage.setText("No Arbitrage Opportunity Found");
            }
        }
    });

}
}

Note : This code works perfectly in java IDE (I use netbeans) but crashes in android studio.

======================================================================================================================================================
EDIT 1

Added the log as below :

com.example.thispc.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: com.example.thispc.myapplication, PID: 4876
                                                                            java.lang.NumberFormatException: For input string: "USD 1 1.6 4
                                                                            CAD 2.3 1 1.3
                                                                            CHF 4 8 1"
                                                                                at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
                                                                                at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
                                                                                at java.lang.Double.parseDouble(Double.java:539)
                                                                                at com.example.thispc.myapplication.Arbitrage$1.onClick(Arbitrage.java:57)
                                                                                at android.view.View.performClick(View.java:6294)
                                                                                at android.view.View$PerformClick.run(View.java:24770)
                                                                                at android.os.Handler.handleCallback(Handler.java:790)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

======================================================================================================================================================
EDIT 2

output

Body:
Its getting crash because of the below line

rate = Double.parseDouble(inputdata.getText().toString());

You are trying to parse the string and parseDoubel() expects the string value which only holds numeric value, but in your case inputdata.getText().toString() contains character other than numbers.

Try extracting digits form the inputdata before passing to parseDouble() method

str.replaceAll("[^0-9]", "");


问:
How can I find the missing integer in a string of random non-repeating integers in a range
I'm having trouble even beginning to think of how to do this.

I need to find a missing number in a string of random numbers that don't have separators.

Here's an example: 14036587109. In this example, the missing number is 2, the range is 0-10 (inclusive).

How can I write a JavaScript/Node.JS program to solve this?

The part I can't figure out is how the program separates the numbers; In the example above, how would the program know that the number 10 (before the last number) isn't the numbers 1 and 0.

答:
This solution should work for any input string and any start/end range:

We can think about the numbers in the string as a pool of digits that we can choose from. We start at startRange and go through to endRange, looking for each number along the way in our pool of digits.

When we find a number that can be composed from our pool of digits, we delete those digits from our pool of digits, as those digits are already being used to form a number in our range.

As soon as we come across a number that cannot be composed from our pool of digits, that must be the missing number.

const str = "14036587109"; // input

const numsLeft = str.split("").map(num => parseInt(num)); // array of numbers

const startRange = 0;
const endRange = 10;

for(let i = startRange; i <= endRange ; i++) {

    // check if number can be formed given the numbers left in numsLeft
    const numFound = findNum(numsLeft, i);

    if(!numFound) {
        console.log("MISSING: " + i); // prints 2
        break;
    }
}

function findNum(numsLeft, i) {

    // array of digits
    const numsToFind = String(i).split("").map(num => parseInt(num));

    // default is true, if all digits are found in numsLeft
    let found = true;

    numsToFind.forEach(num => {

        // find digit in numsLeft
        const numFoundIndex = numsLeft.indexOf(num);

        if(numFoundIndex < 0) {

            // digit was not found in numsLeft
            found = false;
            return;

        } else {

            // digit was found; delete digit from numsLeft
            numsLeft.splice(numFoundIndex, 1);
        }

    });

    return found;
}```


问:
What are good ways to test a login page?
I get asked this question very frequently in my interviews. They draw username and password text fields and ask me what test cases I can come up with to ensure that this page works fine. My answers on this for some reason never seem to satisfy them. So what tests can we have to ensure that this page is working fine besides the ones mentioned below?

My answers normally include:

check whether the login works with correct credentials

check that it doesn't work with wrong credentials

check text field limits - whether the browser accepts more than the allowed database limits

check whether password text is hidden

答:
Check for invalid characters and correct escaping. What will happen if you try to login as Mugen'; drop database; -- (Don't test on a production server).

if for a website:

Check if the password is sent hashed or encrypted

and not (also) in plain text.

Check if it works without Javascript

ContentLicense: CC BY-SA 2.5


问:
Get static code analyzer messages only from 'git diff'?
In our build system (with sources under git version control), I'd like to get the static code analyzer (pylint, in this case) messages for every build. And I want them incremental: in the new build report, only the messages introduced by new commits are shown.

I can easily get the 'old' and 'new' commits. Then, the general path is to run the analyzer on the 'new' commit, and then, for each source code line with a message, find whether that line is new/modified, or if it is intact from the 'old' commit. Then, print only messages from new/modified lines.

Is there a simpler way of achieving this goal for pylint? Or is there an existing implementation of something similar?

答:
The git diff-tree command has a --diff-filter argument that can be used to filter for a specific type of modification:

From the git diff-tree documentation:

--diff-filter=[(A|C|D|M|R|T|U|X|B)…[*]]

  Select only files that are Added (A), Copied (C), Deleted (D), Modified (M), Renamed (R), have their type (i.e. regular file, symlink, submodule, …) changed (T), are Unmerged (U), are Unknown (X), or have had their pairing Broken (B). Any combination of the filter characters (including none) can be used.

If you want to get a list of the names of all added files you could use a command like this:

git diff-tree -r --name-only --diff-filter A <oldCommit>..<newCommit>

The -r option in this case means to diff the trees recursively. The --name-only option causes only the file names to be printed, without their status and prevents printing of the diff header.

Since this is one of the git diff commands, it also takes additional arguments that allow filtering the file list. If you are only interested in files ending in '.py' at a certain path you could add -- 'path/*.py' to the command.

If the list of files is sent further to a tool like xargs, it may make sense to add the -z option. This option causes the list of filenames to be delimited by a null byte instead of a newline. This makes the command robust against various special characters that may occur in file names (including spaces). The receiving end then needs to made aware of that. For xargs the option to use would be --null.

A complete command that runs pylint on added files with the '.py' extension between two commits could therefore look like this:

git diff-tree -r -z --name-only --diff-filter A <oldCommit>..<newCommit> -- '*.py' | xargs --null pylint


问:
Cannot push to Git repository on Bitbucket
I created a new repository and I'm running into a strange error. I've used Git before on Bitbucket but I just reformatted and now I can't seem to get Git to work.  After doing a commit, I had to add my email and name to the globals, but then it committed just fine.

When I try to use the command

```<code>git push origin master
</code>```

it doesn't work. I get this message:

```<code>$ git push origin master
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

I'm at a loss here.  My friend whom I'm sharing this repository with, accessed it fine and pushed to it just fine, but I can't seem to get it to work.

答:
I got this error

Connection to bitbucket.org closed by remote host.
  fatal: Could not read from remote repository.
  Please make sure you have the correct access rights.

Then i tried

git config --global user.email "you@example.com"

worked without quotes.

Body:
I created a new repository and I'm running into a strange error. I've used Git before on Bitbucket but I just reformatted and now I can't seem to get Git to work.  After doing a commit, I had to add my email and name to the globals, but then it committed just fine.

When I try to use the command

git push origin master

it doesn't work. I get this message:

$ git push origin master
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I'm at a loss here.  My friend whom I'm sharing this repository with, accessed it fine and pushed to it just fine, but I can't seem to get it to work.


问:
config-map kubernetes multiple environments
I am trying to deploy a Spring Boot application using configuration data from Kubernetes cluster. I have a simple RestController that prints a message by reading from a Kubernetes cluster.

```<code>    private String message = "Message not coming from Kubernetes config map";

@RequestMapping(value="/echo", method=GET)
public String printKubeConfig() {
    return message;
}
</code>```

Specified the name of the config map in my application.yml

```<code>spring:
  application:
    name: echo-configmap
</code>```

echo-configmap

```<code>apiVersion: v1
kind: ConfigMap
metadata:
  name: echo-configmap
data:
  application.properties: |-
    message=Hello from dev Kubernetes Configmap
  application_qa.properties: |-
    message=Hello from qa Kubernetes Configmap
</code>```

I have several environments like qa, int, test etc

What's the best way to specify environment specific properties in the config map? And how to access them in Spring boot application?

Ex: if the application is deployed in qa, my service should return the message "Hello from qa Kubernetes Configmap"

We also have plans to read these configuration files from GIT in future. How to handle that usecase?

答:
Typically you want that applications running on qa don't interfere with applications running on production. Using Kubernetes, you can get this kind of isolation using different namespaces for different environments.
That way, objects on the prod namespace are different from objects on the qa namespace. Another, more expensive approach would be to use different k8s clusters for different environments.

Having this setup, you would deploy your application in the namespace for the specific environment where you want to deploy to, creating the Deployment object on that namespace.
This Deployment would make use of a ConfigMap object containing your Spring Boot properties. Let's call this ConfigMap echo-properties for example.

That way, every namespace would have a unique copy of the echo-properties ConfigMap. Each containing the specific configuration for the environment where it belongs.

The Deployment object consumes the ConfigMap properties by either using environment variables or reading files. The important bit here is that if you change the echo-properties ConfigMap data, your application won't see those new values, by default. Kubernetes doesn't have this feature so far. You can't compare ConfigMaps to Spring Cloud Config, which is a dynamic configuration solution.

An approach that would get you a similar behaviour (but not quite the same) would be using the fabric8 ConfigMap Controller on your cluster. This controller is a process that runs on your cluster, and it would restart your application whenever the ConfigMap changes, so that it reads the new configuration values.

If you don't want to restart your application whenever a configuration changes, you should probably stick to Spring Cloud Config for values that will potentially change, and use ConfigMaps for other properties that won't change, like application name or port.

Body:
I am trying to deploy a Spring Boot application using configuration data from Kubernetes cluster. I have a simple RestController that prints a message by reading from a Kubernetes cluster.

    private String message = "Message not coming from Kubernetes config map";

@RequestMapping(value="/echo", method=GET)
public String printKubeConfig() {
    return message;
}

Specified the name of the config map in my application.yml

spring:
  application:
    name: echo-configmap

echo-configmap

apiVersion: v1
kind: ConfigMap
metadata:
  name: echo-configmap
data:
  application.properties: |-
    message=Hello from dev Kubernetes Configmap
  application_qa.properties: |-
    message=Hello from qa Kubernetes Configmap

I have several environments like qa, int, test etc

What's the best way to specify environment specific properties in the config map? And how to access them in Spring boot application?

Ex: if the application is deployed in qa, my service should return the message "Hello from qa Kubernetes Configmap"

We also have plans to read these configuration files from GIT in future. How to handle that usecase?


问:
How do i get the root, not the document root
I want to upload images outside the document root:

```<code>// on server:
/home1/myname/artist_gallery

// on localhost
c:/artist_gallery
</code>```

I use the following to create the DEFINE for both local and server:

```<code>define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT']);
define('GALLERY_FILE', DOCUMENT_ROOT . '/artist_gallery/');
</code>```

but, i get

```<code>/home1/myname/public_html/artist_gallery
C:/public_html/artist_gallery
</code>```

Notice the folder public_html... i dont want that folder...

So, how do I get the root (not the document root) in one DEFINE rule for both the localhost and server?

答:
you can get root by simply using a single / before the artist_gallery directory, like this:

```<code>define('GALLERY_FILE', '/artist_gallery/');
</code>```

Body:
I want to upload images outside the document root:

// on server:
/home1/myname/artist_gallery

// on localhost
c:/artist_gallery

I use the following to create the DEFINE for both local and server:

define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT']);
define('GALLERY_FILE', DOCUMENT_ROOT . '/artist_gallery/');

but, i get

/home1/myname/public_html/artist_gallery
C:/public_html/artist_gallery

Notice the folder public_html... i dont want that folder...

So, how do I get the root (not the document root) in one DEFINE rule for both the localhost and server?

Body:
you can get root by simply using a single / before the artist_gallery directory, like this:

define('GALLERY_FILE', '/artist_gallery/');


问:
Custom formatting of validation summary and errors

The problem

Summary

For the validation summary you usually have something like this:

```<code><div asp-validation-summary="ModelOnly" class="..."></div>
</code>```

which, in case there are errors with an empty string as field/attribute will be displayed inside that div within a
 list.

What if I want to display them using a sequence of divs with a specific class attribute? Or any other custom formatting?

Field validation

For field validation you usually do:

```<code><div class="form-group">
    <label asp-for="OldPassword"></label>
    <input asp-for="OldPassword" class="form-control" />
    <span asp-validation-for="OldPassword" class="text-danger"></span>
</div>
</code>```

and the error gets inserted as text within the span element.

I'm using a template that requires the has-errors class to be applied to the form-group div element in case there are errors because it needs to style both the label and the input.

It also requires the span to be a div (for some unknown reasons) and surprisingly enough changing the span to div prevents the div from inserting the text of the error; not to mention that wrapping the span inside a div yields that problem that the div has proper spacing applied to it so even if there are no errors the div shows an annoying space.

Question (tl; dr)

What is the most idiomatic way of handling custom form validation formatting (trying to DRY, since my application has many forms) with custom rules like the ones shown above?

答:
Using a custom tag helper i came up with a following solution:

```<code>[HtmlTargetElement("ul", Attributes = AttributeName)]
public class ValidationSummaryLiItemsTagHelper : TagHelper
{
    private const string AttributeName = "model-validation-summary-list";

    [HtmlAttributeNotBound]
    [ViewContext]
    public ViewContext ViewContext { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        var errors = ViewContext.ModelState.Where(x => x.Key == "").SelectMany(x => x.Value.Errors).ToList();
        foreach (var error in errors)
        {
            output.Content.AppendFormat("<li>{0}</li>", error.ErrorMessage);
        }

        if (errors.Any() == false)
            output.SuppressOutput();
    }
}
</code>```

Later i can use it like that:

```<code><ul class="some-css-class" id="some-id-name" model-validation-summary-list></ul>
</code>```

Then, for example, i can customize the ul container directly with bootstrap classes or add any html attribute.

Body:
The problem

Summary

For the validation summary you usually have something like this:

which, in case there are errors with an empty string as field/attribute will be displayed inside that div within a
 list.

What if I want to display them using a sequence of divs with a specific class attribute? Or any other custom formatting?

Field validation

For field validation you usually do:

    <input asp-for="OldPassword" class="form-control" />

and the error gets inserted as text within the span element.

I'm using a template that requires the has-errors class to be applied to the form-group div element in case there are errors because it needs to style both the label and the input.

It also requires the span to be a div (for some unknown reasons) and surprisingly enough changing the span to div prevents the div from inserting the text of the error; not to mention that wrapping the span inside a div yields that problem that the div has proper spacing applied to it so even if there are no errors the div shows an annoying space.

Question (tl; dr)

What is the most idiomatic way of handling custom form validation formatting (trying to DRY, since my application has many forms) with custom rules like the ones shown above?

Body:
Using a custom tag helper i came up with a following solution:

[HtmlTargetElement("ul", Attributes = AttributeName)]
public class ValidationSummaryLiItemsTagHelper : TagHelper
{
    private const string AttributeName = "model-validation-summary-list";

    [HtmlAttributeNotBound]
    [ViewContext]
    public ViewContext ViewContext { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        var errors = ViewContext.ModelState.Where(x => x.Key == "").SelectMany(x => x.Value.Errors).ToList();
        foreach (var error in errors)
        {
            output.Content.AppendFormat("<li>{0}</li>", error.ErrorMessage);
        }

        if (errors.Any() == false)
            output.SuppressOutput();
    }
}

Later i can use it like that:

<ul class="some-css-class" id="some-id-name" model-validation-summary-list></ul>

Then, for example, i can customize the ul container directly with bootstrap classes or add any html attribute.


问:
orb opencv variable inputs
I am new to opencv and am trying to extract keypoints of a gesture image by ORB algorithm in python interface. The image input is binary and has many curvatures. So ORB gives too many points as keypoints (which are actually not). I am trying to increase the threshold of ORB algorithm so that the unnesessary points dont get detected. I have searched for ORB algorithms and haven't found any use of threshold except for in c++ function description.
     So my question is what are the input parameters for ORB detection algorithm  and what is the actual syntax in python.
  Thanks in advance.</p>

答: After looking at the ORB() function in Opencv C++ description, I realized that the input parameters can be passed into function in Python as nfeatures=200,mask=img etc. (not sure about C++ though).

Title: orb opencv variable inputs

ContentLicense: CC BY-SA 4.0


问:
Adding external libs to the Phalcon project
Cannot add the Phalcon mailer and use it in the project. Doing same as instructions say. I have config linking to 'libraryDir' => APP_PATH . '/app/lib/', in the lib folder I have a Mailer folder where I put the composer.json.

I followed THIS but after using the lib in the Controller I've got

Fatal error: Uncaught Error: Class 'Phalcon\Ext\Mailer\Manager'

Code :

```<code>use Phalcon\Http\Response;
use Phalcon\Mvc\Model\Criteria;
use Phalcon\Mvc\Model\Query\BuilderInterface;
use Phalcon\Di\InjectionAwareInterface;
use Phalcon\Mvc\Model\Resultset; use Phalcon\Ext\Mailer\Manager;
use Phalcon\Ext\Mailer\Message;

class EmailController extends Phalcon\Mvc\Controller {
public function initialize() {
if ($this->request->isPost()) {
$this->view->disable();
}
}
public function indexAction() {

}

public function sendEmailAction(){
    if ($this->request->isPost()) {

        $config = [
            'driver'   => 'mail',
            'from'         => [
                'email' => 'manager@email.com',
                'name'    => 'Email'
            ]
        ];

        $email = new Phalcon\Ext\Mailer\Message($config);
        return "send";
    }
}
}
</code>```

答:
You have to follow Phalcon\Ext\Mailer installation instructions. There is no instructions about putting somewhere composer.json. Just install this library using typical for the Composer way:

```<code>composer require "phalcon-ext/mailer":"~2.0"
</code>```

The last thing you need: make sure that you are using Composer autoloader:

```<code>require_once 'vendor/autoload.php';
</code>```

Body:
Cannot add the Phalcon mailer and use it in the project. Doing same as instructions say. I have config linking to 'libraryDir' => APP_PATH . '/app/lib/', in the lib folder I have a Mailer folder where I put the composer.json.

I followed THIS but after using the lib in the Controller I've got

Fatal error: Uncaught Error: Class 'Phalcon\Ext\Mailer\Manager'

Code :

use Phalcon\Http\Response;
use Phalcon\Mvc\Model\Criteria;
use Phalcon\Mvc\Model\Query\BuilderInterface;
use Phalcon\Di\InjectionAwareInterface;
use Phalcon\Mvc\Model\Resultset; use Phalcon\Ext\Mailer\Manager;
use Phalcon\Ext\Mailer\Message;

class EmailController extends Phalcon\Mvc\Controller {
public function initialize() {
if ($this->request->isPost()) {
$this->view->disable();
}
}
public function indexAction() {

}

public function sendEmailAction(){
    if ($this->request->isPost()) {

        $config = [
            'driver'   => 'mail',
            'from'         => [
                'email' => 'manager@email.com',
                'name'    => 'Email'
            ]
        ];

        $email = new Phalcon\Ext\Mailer\Message($config);
        return "send";
    }
}
}

Body:
You have to follow Phalcon\Ext\Mailer installation instructions. There is no instructions about putting somewhere composer.json. Just install this library using typical for the Composer way:

composer require "phalcon-ext/mailer":"~2.0"

The last thing you need: make sure that you are using Composer autoloader:

require_once 'vendor/autoload.php';


问:
Perl 6 Grammar doesn't match like I think it should
I'm doing Advent of Code day 9:

You sit for a while and record part of the stream (your puzzle input). The characters represent groups - sequences that begin with { and end with }. Within a group, there are zero or more other things, separated by commas: either another group or garbage. Since groups can contain other groups, a } only closes the most-recently-opened unclosed group - that is, they are nestable. Your puzzle input represents a single, large group which itself contains many smaller ones.

Sometimes, instead of a group, you will find garbage. Garbage begins with < and ends with >. Between those angle brackets, almost any character can appear, including { and }. Within garbage, < has no special meaning.

In a futile attempt to clean up the garbage, some program has canceled some of the characters within it using !: inside garbage, any character that comes after ! should be ignored, including <, >, and even another !.

Of course, this screams out for a Perl 6 Grammar...

```<code>grammar Stream
{
    rule TOP { ^ <group> $ }

    rule group { '{' [ <group> || <garbage> ]* % ',' '}' }
    rule garbage { '<' [ <garbchar> | <garbignore> ]* '>' }

    token garbignore { '!' . }
    token garbchar { <-[ !> ]> }
}
</code>```

This seems to work fine on simple examples, but it goes wrong with two garbchars in a row:

```<code>say Stream.parse('{<aa>}');
</code>```

gives Nil.

Grammar::Tracer is no help:

```<code>TOP
|  group
|  |  group
|  |  * FAIL
|  |  garbage
|  |  |  garbchar
|  |  |  * MATCH "a"
|  |  * FAIL
|  * FAIL
* FAIL
Nil
</code>```

Multiple garbignores are no problem:

```<code>say Stream.parse('{<!!a!a>}');
</code>```

gives:

```<code>｢{<!!a!a>}｣
 group => ｢{<!!a!a>}｣
  garbage => ｢<!!a!a>｣
   garbignore => ｢!!｣
   garbchar => ｢a｣
   garbignore => ｢!a｣
</code>```

Any ideas?

答:
UPD Given that the Advent of code problem doesn't mention whitespace you shouldn't be using the rule construct at all. Just switch all the rules to tokens and you should be set. In general, follow Brad's advice -- use token unless you know you need a rule (discussed below) or a regex (if you need backtracking).

My original answer below explored why the rules didn't work. I'll leave it in for now.

TL;DR <garbchar> | contains a space. Whitespace that directly follows any atom in a rule indicates a tokenizing break. You can simply remove this inappropriate space, i.e. write <garbchar>| instead (or better still, <.garbchar>| if you don't need to capture the garbage) to get the result you seek.

As your original question allowed, this isn't a bug, it's just that your mental model is off.

Your answer correctly identifies the issue: tokenization.

So what we're left with is your follow up question, which is about your mental model of tokenization, or at least how Perl 6 tokenizes by default:

why ... my second example ... goes wrong with two garbchars in a row:

```<code>'{<aa>}'
</code>```

Simplifying, the issue is how to tokenize this:

```<code>aa
</code>```

The simple high level answer is that, in parsing vernacular, aa will ordinarily be treated as one token, not two, and, by default, Perl 6 assumes this ordinary definition. This is the issue you're encountering.

You can overrule this ordinary definition to get any tokenizing result you care to achieve. But it's seldom necessary to do so and it certainly isn't in simple cases like this.

I'll provide two redundant paths that I hope might lead folk to the correct mental model:

For those who prefer diving straight into nitty gritty detail, there's a reddit comment I wrote recently about tokenization in Perl 6.

The rest of this SO answer provides a high level discussion that complements the low level explanation in my reddit comment.

Excerpting from the "Obstacles" section of the wikipedia page on tokenization, and interleaving the excerpts with P6 specific discussion:

Typically, tokenization occurs at the word level. However, it is sometimes difficult to define what is meant by a "word". Often a tokenizer relies on simple heuristics, for example:

Punctuation and whitespace may or may not be included in the resulting list of tokens.

In Perl 6 you control what gets included or not in the parse tree using capturing features that are orthogonal to tokenizing.

All contiguous strings of alphabetic characters are part of one token; likewise with numbers.

Tokens are separated by whitespace characters, such as a space or line break, or by punctuation characters.

By default, the Perl 6 design embodies an equivalent of these two heuristics.

The key thing to get is that it's the rule construct that handles a string of tokens, plural. The token construct is used to define a single token per call.

I think I'll end my answer here because it's already getting pretty long. Please use the comments to help us improve this answer. I hope what I've written so far helps.

Body:
I'm doing Advent of Code day 9:

You sit for a while and record part of the stream (your puzzle input). The characters represent groups - sequences that begin with { and end with }. Within a group, there are zero or more other things, separated by commas: either another group or garbage. Since groups can contain other groups, a } only closes the most-recently-opened unclosed group - that is, they are nestable. Your puzzle input represents a single, large group which itself contains many smaller ones.

Sometimes, instead of a group, you will find garbage. Garbage begins with < and ends with >. Between those angle brackets, almost any character can appear, including { and }. Within garbage, < has no special meaning.

In a futile attempt to clean up the garbage, some program has canceled some of the characters within it using !: inside garbage, any character that comes after ! should be ignored, including <, >, and even another !.

Of course, this screams out for a Perl 6 Grammar...

grammar Stream
{
    rule TOP { ^ <group> $ }

    rule group { '{' [ <group> || <garbage> ]* % ',' '}' }
    rule garbage { '<' [ <garbchar> | <garbignore> ]* '>' }

    token garbignore { '!' . }
    token garbchar { <-[ !> ]> }
}

This seems to work fine on simple examples, but it goes wrong with two garbchars in a row:

say Stream.parse('{<aa>}');

gives Nil.

Grammar::Tracer is no help:

TOP
|  group
|  |  group
|  |  * FAIL
|  |  garbage
|  |  |  garbchar
|  |  |  * MATCH "a"
|  |  * FAIL
|  * FAIL
* FAIL
Nil

Multiple garbignores are no problem:

say Stream.parse('{<!!a!a>}');

gives:

｢{<!!a!a>}｣
 group => ｢{<!!a!a>}｣
  garbage => ｢<!!a!a>｣
   garbignore => ｢!!｣
   garbchar => ｢a｣
   garbignore => ｢!a｣

Any ideas?

Body:
UPD Given that the Advent of code problem doesn't mention whitespace you shouldn't be using the rule construct at all. Just switch all the rules to tokens and you should be set. In general, follow Brad's advice -- use token unless you know you need a rule (discussed below) or a regex (if you need backtracking).

My original answer below explored why the rules didn't work. I'll leave it in for now.

TL;DR <garbchar> | contains a space. Whitespace that directly follows any atom in a rule indicates a tokenizing break. You can simply remove this inappropriate space, i.e. write <garbchar>| instead (or better still, <.garbchar>| if you don't need to capture the garbage) to get the result you seek.

As your original question allowed, this isn't a bug, it's just that your mental model is off.

Your answer correctly identifies the issue: tokenization.

So what we're left with is your follow up question, which is about your mental model of tokenization, or at least how Perl 6 tokenizes by default:

why ... my second example ... goes wrong with two garbchars in a row:

'{<aa>}'

Simplifying, the issue is how to tokenize this:

aa

The simple high level answer is that, in parsing vernacular, aa will ordinarily be treated as one token, not two, and, by default, Perl 6 assumes this ordinary definition. This is the issue you're encountering.

You can overrule this ordinary definition to get any tokenizing result you care to achieve. But it's seldom necessary to do so and it certainly isn't in simple cases like this.

I'll provide two redundant paths that I hope might lead folk to the correct mental model:

For those who prefer diving straight into nitty gritty detail, there's a reddit comment I wrote recently about tokenization in Perl 6.

The rest of this SO answer provides a high level discussion that complements the low level explanation in my reddit comment.

Excerpting from the "Obstacles" section of the wikipedia page on tokenization, and interleaving the excerpts with P6 specific discussion:

Typically, tokenization occurs at the word level. However, it is sometimes difficult to define what is meant by a "word". Often a tokenizer relies on simple heuristics, for example:

Punctuation and whitespace may or may not be included in the resulting list of tokens.

In Perl 6 you control what gets included or not in the parse tree using capturing features that are orthogonal to tokenizing.

All contiguous strings of alphabetic characters are part of one token; likewise with numbers.

Tokens are separated by whitespace characters, such as a space or line break, or by punctuation characters.

By default, the Perl 6 design embodies an equivalent of these two heuristics.

The key thing to get is that it's the rule construct that handles a string of tokens, plural. The token construct is used to define a single token per call.

I think I'll end my answer here because it's already getting pretty long. Please use the comments to help us improve this answer. I hope what I've written so far helps.


问:
Internationalization with Angular 4
I need to Add multiple language support for my Angular 4 Application.I need to know the best approach to achieve this.</p>

答:
if you use angular-cli to create newApp it has a good infrastructure for translate, that use ngx-translate. and for translate your text use pipe: translate like:

```<code><span>{{ text | translate }}</span>
</code>```

translate files exist on the /src/assets/i18n/langCode.json (forEx: en.json). and an initializing require in the main layout constructor

```<code>constructor(public translate: TranslateService, zone: NgZone) {
  translate.use('en');
}
</code>```

Title: Internationalization with Angular 4

Body:
if you use angular-cli to create newApp it has a good infrastructure for translate, that use ngx-translate. and for translate your text use pipe: translate like:

<span>{{ text | translate }}</span>

translate files exist on the /src/assets/i18n/langCode.json (forEx: en.json). and an initializing require in the main layout constructor

constructor(public translate: TranslateService, zone: NgZone) {
  translate.use('en');
}


问:
What is the cost of calling jQuery and jQuery UI on every page?
I have an intranet site where half of the pages use jQuery, and ~20% use jQuery UI. Users who navigate the site will almost certainly open a page containing jQuery UI during their visit.

What I'd like to do is use for all pages a standard template that includes calls to jQuery and jQuery UI. It would make the site maintenance easier, but it also means that for 80% of my pages jQuery UI will be loaded for nothing.

What I have been told is that I should not worry too much about that. Calls to jQuery and jQuery UI will be cached by the browser, so anyway they'll only be called once during the user's visit.

Is this correct? Or are there other performance factors that could make the systematic call a bad idea?

答:
Including less Javascripts will Make fewer HTTP requests

which will Increase your site performance.

Yslow Performance Issue


问:
How to restrict Firebase data modification?
Firebase provides database back-end so that developers can focus on the client side code.

So if someone takes my firebase uri (for example, https://firebaseinstance.firebaseio.com) then develop on it locally.

Then, would they be able to create another app off my Firebase instance, signup and authenticate themselves to read all data of my Firebase app?

答:
Regarding the Auth white-listing for mobile apps, where the domain name is not applicable, Firebase has

SHA1 fingerprint for Android apps and

App Store ID and Bundle ID and Team ID (if necessary) for your iOS apps

which you will have to configure in the Firebase console.

With this protection, since validation is not just if someone has a valid API key, Auth domain, etc, but also, is it coming from our authorized apps and domain name/HTTP referrer in case of Web.

That said, we don't have to worry if these API keys and other connection params are exposed to others.

For more info, https://firebase.google.com/support/guides/launch-checklist


问:
Ensure data delivery in socket programming
How can I be sure that data is successfully delivered to the other end in socket programming?

outStream.write() doesn't guarantee that bytes are received on the other end. I can force server to send back some confirmation data, but how long should client wait for it? If I wait too short, maybe data is delivered to the server just when I throw timeout exception in client (which then shows error dialog, but server actually received data). On the other hand, I don't want to wait too much.

Should client wait some time and if confirmation is received, a third "commit" message is sent to server which then supplies data for further processing (so first client writes, then server replies and then client confirms). But then again, if the commit message is not received on server, client thinks that data is successfully sent but server will ignore it after some time, because it didn't receive commit message. And so on, bouncing never ends...

How is this situation generally handled?

Every tutorial that I read is just about creating/closing sockets, and sending data on client side and receiving it on server side.

If you have links to blogs which explain this problem (or even books), that would be good too.

[EDIT]

I should clarify some things. I'm using Java for client and server, and later I will create C# client. Everything is working perfectly for now. Both client and server are on the same LAN and I have never had any real problems. Scenario explained above is just theoretical, because I would like to cover as much as possible, including error handling.

I know TCP guarantees delivery, but in Java, out.write() doesn't block until underlying TCP delivers or fails and then continues execution or throws an exception. It just continues execution and I don't know if sending failed or not. There is no callback function. I'm starting with socket programming so maybe there is very simple solution which I don't know about. All I need to do is to make sure client knows that server received the message (if that is even possible).

答:
TCP:

TCP guarantees packet delivery at layer 4 of the OSI Model. TCP is based on a handshake in which the receiving party must confirm the packet's delivery. In that case there is either something wrong in your code or your network is malfunctioning. If you are talking about the packet not making it to its destination, make sure you have properly bound the TCP server to the port, and that the destination is correct. While waiting for a packets arrival, make sure you have a receive timeout in place in order to prevent you application from getting hung on the receive.


问:
Why is "this" NULL? C++ Segmentation fault

I'm building a Qt app and it's crashing because of a segmentation fault. After investigation, I found out that the cause of the segfault is that "this" is NULL and I try to access a member variable in the readInputFile(QString path) method.
In this line input += line;

I don't understand why this is happening. how can "this" be NULL ?

Here's where the object is created

```<code>void MainWindow::on_inpFileCheck_clicked()
{
    if (ui->inpFileCheck->isChecked()) {
        QString filePath = QFileDialog::getOpenFileName(this,tr("Open CSV file"), "/home", tr("CSV  (*.csv)"));
        myAlgo->readInputFile(filePath);
        ui->inputEdit->clear();
        ui->inputEdit->appendPlainText(myAlgo->getInput());
    }
}
</code>```

Here's the BaseAlgorithm header

```<code>#include "qstring.h"
#include "qmainwindow.h"

class BaseAlgorithm
{
public:
    BaseAlgorithm();
    QString readInputFile(QString);
    int lenArr;

private:
    QString input;
    QString output;
};
</code>```

And here's the implementation and where the problem happens

```<code>#include "basealgorithm.h"
#include "qfile.h"
#include "qtextstream.h"

BaseAlgorithm::BaseAlgorithm() {

    numComparisons = 0;
    input = "";
    output = "";
    intArr = NULL;
}

QString BaseAlgorithm::readInputFile(QString path) {

    QFile inpFile(path);
    if (inpFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&inpFile);

        while (!in.atEnd()) {
            QString line = in.readLine();
            input += line; // crash happens here
        }
        return input;
    }

    else {
         return "ERROR";
    }

}
</code>```

答: I fixed it. The object was being created late.</p>

Body:
I'm building a Qt app and it's crashing because of a segmentation fault. After investigation, I found out that the cause of the segfault is that "this" is NULL and I try to access a member variable in the readInputFile(QString path) method.
In this line input += line;

I don't understand why this is happening. how can "this" be NULL ?

Here's where the object is created

void MainWindow::on_inpFileCheck_clicked()
{
    if (ui->inpFileCheck->isChecked()) {
        QString filePath = QFileDialog::getOpenFileName(this,tr("Open CSV file"), "/home", tr("CSV  (*.csv)"));
        myAlgo->readInputFile(filePath);
        ui->inputEdit->clear();
        ui->inputEdit->appendPlainText(myAlgo->getInput());
    }
}

Here's the BaseAlgorithm header

#include "qstring.h"
#include "qmainwindow.h"

class BaseAlgorithm
{
public:
    BaseAlgorithm();
    QString readInputFile(QString);
    int lenArr;

private:
    QString input;
    QString output;
};

And here's the implementation and where the problem happens

#include "basealgorithm.h"
#include "qfile.h"
#include "qtextstream.h"

BaseAlgorithm::BaseAlgorithm() {

    numComparisons = 0;
    input = "";
    output = "";
    intArr = NULL;
}

QString BaseAlgorithm::readInputFile(QString path) {

    QFile inpFile(path);
    if (inpFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&inpFile);

        while (!in.atEnd()) {
            QString line = in.readLine();
            input += line; // crash happens here
        }
        return input;
    }

    else {
         return "ERROR";
    }

}


问:
RandomForestClassifier import
I've installed Anaconda Python distribution with scikit-learn.
While importing RandomForestClassifier:

from sklearn.ensemble import RandomForestClassifier

I have the following error:

File "C:\Anaconda\lib\site-packages\sklearn\tree\tree.py", line 36, in <module>
    from . import _tree
ImportError: cannot import name _tree

What the problem can be there?

答:
In sklearn version '0.18.1'</p>
```<code>from sklearn.ensemble.forest import RandomForestClassifier
</code>```

Title: RandomForestClassifier import

Body:
In sklearn version '0.18.1'

from sklearn.ensemble.forest import RandomForestClassifier


问:
Running time of a nested for loop
1a.)The loop is below and I want to find it's running time. Here is the loop

```<code>sum = 0
for (int i =0; i < N; i++){
    for(int j = i; j >= 0; j--)
          sum ++
</code>```

The first for loops runs in O(n) which is easy, however for the 2nd I think it also runs in O(n) time because whenever j = i, this loop will run i times.

So I wrote down this has a running time of O(n^2).

1b. )Moreover, can someone also explain what is meant, when a problems asks for a "theta bound"?

答:
Well, it's pretty simple to work out the exact number of loop iterations here. You get 1 + 2 + 3 + 4 + 5 + 6 + 7 + ... + N.

That sums to N(N+1) / 2, so yes, the algorithmic complexity is O(N2).

I can't say I've come across theta bounds... the Wikipedia page on big-O notation mentions it though, so that might be a reasonable starting point.

Title: Running time of a nested for loop

Body:
1a.)The loop is below and I want to find it's running time. Here is the loop

sum = 0
for (int i =0; i < N; i++){
    for(int j = i; j >= 0; j--)
          sum ++

The first for loops runs in O(n) which is easy, however for the 2nd I think it also runs in O(n) time because whenever j = i, this loop will run i times.

So I wrote down this has a running time of O(n^2).

1b. )Moreover, can someone also explain what is meant, when a problems asks for a "theta bound"?


问:
knitr, RwordPress quotations and ampersand changes
I followed this blog post and was 99% successful with accomplishing what I wanted to. Basically, create an R Notepad file (.Rmd), run it and save file. Then, run the code that is in the blog post and have my .Rmd file automatically upload to my WordPress site.

The problem is that it uploads and changes the single and double quotes to "&#39";, "&quot" with semicolons at the end, "&amp" respectively.

Example, my code looks like this: LoggerFile = 'SOLAR_LOGGER'

When uploaded to WordPress and I look at the post via text only, it shows up like this: "LoggerFile = &#39 ;SOLAR_LOGGER&#39 ;"
Only without the space between ";" and the 9.
When I publish, it still shows "LoggerFile = &#39 ;SOLAR_LOGGER&#39 ;" as well.

I know at one point I messed with my WordPress files to try and implement using pretty print for code which worked. I would normally manually enter "
Code Here" and it would prettify my code. This still works.

A side question: I was trying to post to another WordPress site to see if it was just that particular WordPress configuration but it doesn't seem to want to change sites. I stored site and password in the .Rprofile file. I tried to even put .Rprofile in same directory with no luck. The changes don't take effect, even after restarting R.

I am very new to R so I may be missing some key pieces of the puzzle. I am also new to MacOS and using terminals. Learning quickly and getting the hang of it (loving it as well!).

I'm using WordPress Version 4.9.1
Hosting under godaddy account (sorry!)
R Studio Version 1.0.153
R version 3.4.1 (2017-06-30)
macOS Sierra Version 10.12.6 (16G1036)

Any suggestions?

答:
So the answer ended up being a conflict between knit2wp and a Crayon add in for WordPress.

The solution is detailed in this post I found [here][1]. Essentially, the code will modify the contents to work well with the Syntax Highlighter built in.

They change knit2wp to knit2wpCrayon. I just tried it and it works perfect. This is good because I won't have to modify any of my old posts.


问:
Spring MVC Test: How to negate a content test
How can I negate a content test in Spring MVC / HamCrest, i.e. test for the negate of a matcher:</p>

```<code>.andExpect(content().string(containsString("StringToNOTExpect")))
</code>```

答:
found the answer by inspecting the hamcrest CoreMatchers class and searching for "not":</p>

```<code>import static org.hamcrest.CoreMatchers.not;

....

.andExpect(content().string(not(containsString("StringToNOTExpect"))))
</code>```

Body:
How can I negate a content test in Spring MVC / HamCrest, i.e. test for the negate of a matcher:

.andExpect(content().string(containsString("StringToNOTExpect")))

Body:
found the answer by inspecting the hamcrest CoreMatchers class and searching for "not":

import static org.hamcrest.CoreMatchers.not;

....

.andExpect(content().string(not(containsString("StringToNOTExpect"))))


问:
Presto configuration
As I set up a cluster of Presto and try to do some performance tuning, I wonder if there's a more comprehensive configuration guide of Presto, e.g. how can I control how many CPU cores a Presto worker can use. And is it good practice if I start multiple presto workers on a single server (in which case I don't need a dedicated server to run the coordinator)?

Besides, I don't quite understand the task.max-memory argument. Will the presto worker start multiple tasks for a single query? If yes, maybe I can use task.max-memory together with the -Xmx JVM argument to control the level of parallelism?

Thanks in advance.

答: For your question regarding "many CPU cores a Presto worker can use", I think it's controlled by the parameter task.concurrency, which by default is 16

Title: Presto configuration


问:
Python 3 inheritance AttributeError. How to solve it?
I've been reading a lot about Python inheritance, but I can't understand how to use it in the right way. I learnt about how inheritance works using Java, so I guess that's why I'm a little confused.

Here is my super class:

```<code>class MongoData:
    def __init__(self, db_name, coll_name):
        self.__config = configparser.ConfigParser()
        self.__config.read('conf.ini')
        self.__connect = self.__config.get('mongo', 'connect')
        self.__client = MongoClient(self.__connect)
        self.__db_name = db_name
        self.__coll_name = coll_name
        self.__db = None
        self.__coll = None

        if self.__db_name in self.__client.database_names(): # If DB already exists
            print('DB exist')
            self.__db = self.__client[self.__db_name]
            if self.__coll_name in self.__db.collection_names(): # If collection already exists
                print('Collection exists')
                self.__coll = self.__db[self.__coll_name]

            else: # If collection does not exist, create it
                self.__db = self.__db_name
                self.__coll = self.__db[self.__coll_name]
                print(self.__db.collection_names())

        else: # If DB does not exist, create it
            print('Creating database...')
            self.__db = self.__client[self.__db_name]
            self.__coll = self.__db[self.__coll_name]
            #print(self.__db.collection_names())
            print("Database {} and collection {} successfully created.".format(self.__db_name, self.__coll_name))

    def writeDB(self, wdict):
        """Method to implement"""
        raise NotImplementedError
</code>```

As you can see, I have a big init and I would like to inherit it in my subclass. Also I have a abstract method to be implemented in the subclass.

And here is the code of my subclass:

```<code>class AttackDB(MongoData):
    __metaclass__  = abc.ABCMeta

    def __init__(self, db_name, coll_name):
        MongoData.__init__(self, db_name, coll_name)

    @abc.abstractmethod
    def writeDB(self, wdict):
        doc_id = self.__coll.insert_one(attack).inserted_id
        print("Attack with id {} was inserted in the DB.".format(dic_id))
</code>```

As I supposed, I get a AttributeError

AttributeError: 'AttackDB' object has no attribute '_AttackDB__coll'

My question is, what can I do no to rewrite the hole init?

Thank you.

Edit:
How about in the super class returning self.__db and self.__coll? It works for me, but I'm not sure if it is a "good" solution.

答:
Welcome to Python, Elena!

As you have noticed already, Python is a bit different on handling inheritance than other languages. What you found is called a name mangling because of the nature of python.

So if you write:

```<code>class MongoData:
    def __init__(self, db_name, coll_name):
        self.__config = configparser.ConfigParser()
</code>```

What you get in child is variable called _MongoData__config, not the self.__config (remember _AttackDB__coll there? ) which might confuse you a bit, however as you understand better how Python works things finally starting to make sense.

Best practices for one language does not always work for others, so advice here is either use a different naming or use a composition over inheritance. Even Mixin pattern might be dangerous to some degree.

Hope that answers your question.

Body:
I've been reading a lot about Python inheritance, but I can't understand how to use it in the right way. I learnt about how inheritance works using Java, so I guess that's why I'm a little confused.

Here is my super class:

class MongoData:
    def __init__(self, db_name, coll_name):
        self.__config = configparser.ConfigParser()
        self.__config.read('conf.ini')
        self.__connect = self.__config.get('mongo', 'connect')
        self.__client = MongoClient(self.__connect)
        self.__db_name = db_name
        self.__coll_name = coll_name
        self.__db = None
        self.__coll = None

        if self.__db_name in self.__client.database_names(): # If DB already exists
            print('DB exist')
            self.__db = self.__client[self.__db_name]
            if self.__coll_name in self.__db.collection_names(): # If collection already exists
                print('Collection exists')
                self.__coll = self.__db[self.__coll_name]

            else: # If collection does not exist, create it
                self.__db = self.__db_name
                self.__coll = self.__db[self.__coll_name]
                print(self.__db.collection_names())

        else: # If DB does not exist, create it
            print('Creating database...')
            self.__db = self.__client[self.__db_name]
            self.__coll = self.__db[self.__coll_name]
            #print(self.__db.collection_names())
            print("Database {} and collection {} successfully created.".format(self.__db_name, self.__coll_name))

    def writeDB(self, wdict):
        """Method to implement"""
        raise NotImplementedError

As you can see, I have a big init and I would like to inherit it in my subclass. Also I have a abstract method to be implemented in the subclass.

And here is the code of my subclass:

class AttackDB(MongoData):
    __metaclass__  = abc.ABCMeta

    def __init__(self, db_name, coll_name):
        MongoData.__init__(self, db_name, coll_name)

    @abc.abstractmethod
    def writeDB(self, wdict):
        doc_id = self.__coll.insert_one(attack).inserted_id
        print("Attack with id {} was inserted in the DB.".format(dic_id))

As I supposed, I get a AttributeError

AttributeError: 'AttackDB' object has no attribute '_AttackDB__coll'

My question is, what can I do no to rewrite the hole init?

Thank you.

Edit:
How about in the super class returning self.__db and self.__coll? It works for me, but I'm not sure if it is a "good" solution.

Body:
Welcome to Python, Elena!

As you have noticed already, Python is a bit different on handling inheritance than other languages. What you found is called a name mangling because of the nature of python.

So if you write:

class MongoData:
    def __init__(self, db_name, coll_name):
        self.__config = configparser.ConfigParser()

What you get in child is variable called _MongoData__config, not the self.__config (remember _AttackDB__coll there? ) which might confuse you a bit, however as you understand better how Python works things finally starting to make sense.

Best practices for one language does not always work for others, so advice here is either use a different naming or use a composition over inheritance. Even Mixin pattern might be dangerous to some degree.

Hope that answers your question.


问:
JavaScript regex global flag doesn't return all occurences
I have a binary representation of a decimal:

```<code>1000010001
</code>```

I want to match a sequence of consecutive zeros that is surrounded by ones at both ends, 10001.

So in my string there are two such occurrences:

```<code>100001
10001
</code>```

But for some reason match with g returns only the first:

```<code>'1000010001'.match(/(?:10+1)+/ig)
> ["100001"]
</code>```

Why not both? How to make it return all occurrences?

答:
The matches consume characters, so after the first match, the string becomes 0001 and thus doesn't match the pattern anymore; You can turn the second 1 in the pattern into a look ahead assertion which doesn't consume characters, then add 1 to each match later:

var s = '1000010001';

console.log(
  s.match(/10+(?=1)/g).map(x => x + '1')
)```

Body:
I have a binary representation of a decimal:

1000010001

I want to match a sequence of consecutive zeros that is surrounded by ones at both ends, 10001.

So in my string there are two such occurrences:

100001
10001

But for some reason match with g returns only the first:

'1000010001'.match(/(?:10+1)+/ig)
> ["100001"]

Why not both? How to make it return all occurrences?


问:
When I start My SAP MMC EC6 server one service is not getting to wait mode

Can someone of you help me, how to make the following service selected in the image get into wait mode after starting the server.
Please let me know if developer trace is required to be posted for resolving this issue.

答:
that particular process is a BATCH process, a process that runs scheduled background tasks (maintained by transaction SM36/SM37). If the process is busy right after starting the server, that means there were scheduled tasks with status released waiting for execution, and as soon as the server was up, it started those tasks.

If you want to make sure the system doesn't immediately start released background tasks, you'll have to set the status back to scheduled (which, thanks to a bit of weird translation, means they won't be executed because they are not released).

if you want to start the server without having a chance to first change the job status in SM37, you would either have to reset the status on database level (likely not officially supported by SAP) or first start the server without any BATCH processes (which would give you a number of great big warning messages upon login) and change the job status before then restarting the server with the BATCH processes. You can set the number of processes for each type in the profile of your instance (parameter rdisp/wp_no_btc).


问:
Firebase: Uncaught SyntaxError: Unexpected identifier
I can't figure out why I recieve "Uncaught SyntaxError: Unexpected identifier" on line 16, when I have copied the script strait from firebase.

Here's what I'm working with:

```<code><!DOCTYPE html>
<html>
<head>
<title>23 Creative</title>

<script src="https://www.gstatic.com/firebasejs/4.8.0/firebase.js"></script>
<script>
var config = {
apiKey: "XXXXXXX",
authDomain: "XXXXXXXXX",
databaseURL: "XXXXXXXXXXXX",
projectId: "XXXXXXX",
storageBucket: "XXXXXXXXXX",
messagingSenderId: "XXXXXXXXXXXX"
}

firebase.auth().createUserWithEmailAndPassword(email,
password).catch(function(,error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  // ...
});
</script>
</code>```

答:
You forgot to add a semi-colon, add it at the end like this:</p>

```<code>var config = {
    apiKey: "XXXXXXX",
    authDomain: "XXXXXXXXX",
    databaseURL: "XXXXXXXXXXXX",
    projectId: "XXXXXXX",
    storageBucket: "XXXXXXXXXX",
    messagingSenderId: "XXXXXXXXXXXX"
     };
</code>```

Body:
I can't figure out why I recieve "Uncaught SyntaxError: Unexpected identifier" on line 16, when I have copied the script strait from firebase.

Here's what I'm working with:

<!DOCTYPE html>

<title>23 Creative</title>

Body:
You forgot to add a semi-colon, add it at the end like this:

var config = {
    apiKey: "XXXXXXX",
    authDomain: "XXXXXXXXX",
    databaseURL: "XXXXXXXXXXXX",
    projectId: "XXXXXXX",
    storageBucket: "XXXXXXXXXX",
    messagingSenderId: "XXXXXXXXXXXX"
     };


问:
Access by the pointer
I have problem with my program. I was looking for answer, but i did't find solution. I created struct and class:

```<code>struct Data
{
    Client* k;
    string msg;
};
class Client
{
public:
    string name;
    int _id;
}
</code>```

Then i created table of Data.

```<code>Data tab[100];
</code>```

And when i try get name from some fields in the table, like this:

```<code>tab[i].k->name;
</code>```

I get errors:

```<code>C2227 left of "->name" must point to class/struct/union/generic type
C2027 use of undefined type 'Client'
</code>```

答:
You got a ';' missing after the Client class declaration.

Either way, I slightly modified your code (Client before Data, add missing ';') and got it compiling and running fine:

```<code>#include <iostream>

using namespace std;

class Client
{
public:
    string name;
    int _id;
};
struct Data
{
    Client* k;
    string msg;
};

int main()
{
    Data tab[100];

    for (int i = 0; i < 100; i++)
    {
        tab[i].k = new Client();
        tab[i].k->name = "name" + to_string(i);
        cout << tab[i].k->name << endl;
    }
}
</code>```

Title: Access by the pointer

Body:
I have problem with my program. I was looking for answer, but i did't find solution. I created struct and class:

struct Data
{
    Client* k;
    string msg;
};
class Client
{
public:
    string name;
    int _id;
}

Then i created table of Data.

Data tab[100];

And when i try get name from some fields in the table, like this:

tab[i].k->name;

I get errors:

C2227 left of "->name" must point to class/struct/union/generic type
C2027 use of undefined type 'Client'

Body:
You got a ';' missing after the Client class declaration.

Either way, I slightly modified your code (Client before Data, add missing ';') and got it compiling and running fine:

#include <iostream>

using namespace std;

class Client
{
public:
    string name;
    int _id;
};
struct Data
{
    Client* k;
    string msg;
};

int main()
{
    Data tab[100];

    for (int i = 0; i < 100; i++)
    {
        tab[i].k = new Client();
        tab[i].k->name = "name" + to_string(i);
        cout << tab[i].k->name << endl;
    }
}