问:
How do I display an image corresponding to a string value in a list item in android?
I am developing an Android application with a list view and I want to diplay two textviews and an imageview in each listitem.

The text required for the textviews are stored in a server and is displayed on the listview. But I further want to add a corresponding image to each list item from the drawables folder, stored within the mobile app.

I access the text values using the link http://alvideobackend.azurewebsites.net/lesson/Physics
and receive the lesson number, name and subname. The images stored in the drawables folder are in correspondance with the lesson number. For example, lesson Number = 1, Image = 1.png

Please help me out in displaying the images in the list items.

SecondActivity.java

```<code>package com.example.acer.videoapp;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;

public class SecondActivity extends AppCompatActivity {

    private String TAG = MainActivity.class.getSimpleName();
    private ProgressDialog pDialog;
    private ListView listView1;
    Toolbar toolbar1;
    String subjectName;

    ArrayList<HashMap<String, String>> lessonList;

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

        //setting title to toolbar
        toolbar1 = (Toolbar) findViewById(R.id.toolbar1);
        toolbar1.setTitleTextColor(getColor(R.color.white));

        Bundle bundle = getIntent().getExtras();
        if(bundle!=null) {
            toolbar1.setTitle(bundle.getString("description"));
            subjectName=bundle.getString("engdescription");
        }

        lessonList = new ArrayList<>();
        listView1 = (ListView) findViewById(R.id.list);
        new GetLessons().execute();

        listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
                HashMap<String, String> lesson = lessonList.get(i);
                intent.putExtra("number", lesson.get("number"));
                intent.putExtra("name", lesson.get("name"));
                startActivity(intent);
            }
        });

        //set back button on toolbar
        toolbar1.setNavigationIcon(R.drawable.back);
        toolbar1.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

    }

    /* Async task class to get json by making HTTP call */
    private class GetLessons extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(SecondActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String url = getResources().getString(R.string.lessons_url, subjectName);
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    // Getting JSON Array
                    JSONArray lessons = new JSONArray(jsonStr);

                    // looping through All lessons
                    for (int i = 0; i < lessons.length(); i++) {
                        JSONObject c = lessons.getJSONObject(i);

                        String number = c.getString("lessonNo");
                        String name = c.getString("lessonName");
                        String engname = c.getString("lessonEngName");

                        // tmp hash map for single lesson
                        HashMap<String, String> lesson = new HashMap<>();

                        // adding each child node to HashMap key => value
                        lesson.put("number", number);
                        lesson.put("name", name);
                        lesson.put("engname", engname);

                        // adding lesson to lesson list
                        lessonList.add(lesson);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),"Json parsing error: " + e.getMessage(),Toast.LENGTH_LONG).show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Please check your Internet Connection");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),"Couldn't get json from server. Check LogCat for possible errors!",Toast.LENGTH_LONG).show();
                    }
                });

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    SecondActivity.this, lessonList,R.layout.list_item1, new String[]{"name","engname",}, new int[]{R.id.lname,R.id.lname1});
            listView1.setAdapter(adapter);

        }

    }

}
</code>```

list_item1.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/img"
        android:layout_gravity="center"
        android:scaleType="fitXY"
        android:editable="true"
        android:layout_width="50dp"
        android:layout_height="50dp" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/lname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="0dip"
            android:paddingTop="20dip"
            android:paddingLeft="10dip"
            android:layout_marginLeft="0dp"
            android:layout_marginRight="5dp"
            android:textSize="17sp"
            android:textColor="@android:color/black"/>

        <TextView
            android:id="@+id/lname1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="20dip"
            android:paddingTop="0dip"
            android:paddingLeft="10dip"
            android:layout_marginLeft="0dp"
            android:layout_marginRight="5dp"
            android:textSize="13sp"/>

    </LinearLayout>
</LinearLayout>
</code>```

答:
A general method could be to build a data model for your list items, then when selecting a new item in the list, update the image from the data model.

A specific way of doing it could be to have your image filenames loaded into an array in the same order as they appear in the list, then, when an item is selected in the list, display the image from that index of the array.

Body:
I am developing an Android application with a list view and I want to diplay two textviews and an imageview in each listitem.

The text required for the textviews are stored in a server and is displayed on the listview. But I further want to add a corresponding image to each list item from the drawables folder, stored within the mobile app.

I access the text values using the link http://alvideobackend.azurewebsites.net/lesson/Physics
and receive the lesson number, name and subname. The images stored in the drawables folder are in correspondance with the lesson number. For example, lesson Number = 1, Image = 1.png

Please help me out in displaying the images in the list items.

SecondActivity.java

package com.example.acer.videoapp;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;

public class SecondActivity extends AppCompatActivity {

    private String TAG = MainActivity.class.getSimpleName();
    private ProgressDialog pDialog;
    private ListView listView1;
    Toolbar toolbar1;
    String subjectName;

    ArrayList<HashMap<String, String>> lessonList;

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

        //setting title to toolbar
        toolbar1 = (Toolbar) findViewById(R.id.toolbar1);
        toolbar1.setTitleTextColor(getColor(R.color.white));

        Bundle bundle = getIntent().getExtras();
        if(bundle!=null) {
            toolbar1.setTitle(bundle.getString("description"));
            subjectName=bundle.getString("engdescription");
        }

        lessonList = new ArrayList<>();
        listView1 = (ListView) findViewById(R.id.list);
        new GetLessons().execute();

        listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
                HashMap<String, String> lesson = lessonList.get(i);
                intent.putExtra("number", lesson.get("number"));
                intent.putExtra("name", lesson.get("name"));
                startActivity(intent);
            }
        });

        //set back button on toolbar
        toolbar1.setNavigationIcon(R.drawable.back);
        toolbar1.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

    }

    /* Async task class to get json by making HTTP call */
    private class GetLessons extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(SecondActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String url = getResources().getString(R.string.lessons_url, subjectName);
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    // Getting JSON Array
                    JSONArray lessons = new JSONArray(jsonStr);

                    // looping through All lessons
                    for (int i = 0; i < lessons.length(); i++) {
                        JSONObject c = lessons.getJSONObject(i);

                        String number = c.getString("lessonNo");
                        String name = c.getString("lessonName");
                        String engname = c.getString("lessonEngName");

                        // tmp hash map for single lesson
                        HashMap<String, String> lesson = new HashMap<>();

                        // adding each child node to HashMap key => value
                        lesson.put("number", number);
                        lesson.put("name", name);
                        lesson.put("engname", engname);

                        // adding lesson to lesson list
                        lessonList.add(lesson);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),"Json parsing error: " + e.getMessage(),Toast.LENGTH_LONG).show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Please check your Internet Connection");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),"Couldn't get json from server. Check LogCat for possible errors!",Toast.LENGTH_LONG).show();
                    }
                });

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    SecondActivity.this, lessonList,R.layout.list_item1, new String[]{"name","engname",}, new int[]{R.id.lname,R.id.lname1});
            listView1.setAdapter(adapter);

        }

    }

}

list_item1.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/img"
        android:layout_gravity="center"
        android:scaleType="fitXY"
        android:editable="true"
        android:layout_width="50dp"
        android:layout_height="50dp" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/lname"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="0dip"
            android:paddingTop="20dip"
            android:paddingLeft="10dip"
            android:layout_marginLeft="0dp"
            android:layout_marginRight="5dp"
            android:textSize="17sp"
            android:textColor="@android:color/black"/>

        <TextView
            android:id="@+id/lname1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="20dip"
            android:paddingTop="0dip"
            android:paddingLeft="10dip"
            android:layout_marginLeft="0dp"
            android:layout_marginRight="5dp"
            android:textSize="13sp"/>

    </LinearLayout>
</LinearLayout>


来源: stackexchange

问:
reversing an array using pointer c
I am trying to write a code that receives the number of input numbers and integers, then reverses those order and prints them out. When I run this code it freezes from the for loop in input_integer function. What am I doing wrong?</p>

```<code># include <stdio.h>
# include <stdlib.h>

void input_integer (int *arr, int *arrSize);
void inverse_reorder (int *arr, int *arrSize);

int main (void){
    int* arrSize;
    int* arr;
    int i;

    input_integer(arr, arrSize);
    printf("inputted data : ");
    for ( i = 0; i < *arrSize ; i++ ){
        printf("%d, ", *(arr + i));
    }
    inverse_reorder(arr, arrSize);
    printf("reversed data : ");
    for ( i = 0; i < *arrSize ; i++ ){
        printf("%d, ", *(arr + i));
    }

    return 0;
}

void input_integer (int* arr, int *arrSize){
    printf("Array size = ? ");
    scanf("%d", arrSize);
    int i;
    for( i = 0; i < *arrSize ; i++ ){
        scanf("%d", *(arr + i));
    }
}

void inverse_reorder (int * arr, int *arrSize){
    int i;
    int temp = 0;
    for ( i = 0; i < *arrSize ; i++ ){
        temp = *(arr+i);
        *(arr+i) = *(arr + *arrSize - i);
        *(arr + *arrSize - i) = temp;
    }
}
</code>```

答:
arrSize is not a pointer it should be a value for the program to run.
You can't compare the incremented i in the loop to the reference value of arrSize otherwise it will be looping for long and long as the loop's limit would be the pointer address.
You should access the pointers only when writing , never on reading (unless it's intended).</p>

ContentLicense: CC BY-SA 3.0

Title: reversing an array using pointer c

Body:
I am trying to write a code that receives the number of input numbers and integers, then reverses those order and prints them out. When I run this code it freezes from the for loop in input_integer function. What am I doing wrong?

# include <stdio.h>
# include <stdlib.h>

void input_integer (int *arr, int *arrSize);
void inverse_reorder (int *arr, int *arrSize);

int main (void){
    int* arrSize;
    int* arr;
    int i;

    input_integer(arr, arrSize);
    printf("inputted data : ");
    for ( i = 0; i < *arrSize ; i++ ){
        printf("%d, ", *(arr + i));
    }
    inverse_reorder(arr, arrSize);
    printf("reversed data : ");
    for ( i = 0; i < *arrSize ; i++ ){
        printf("%d, ", *(arr + i));
    }

    return 0;
}

void input_integer (int* arr, int *arrSize){
    printf("Array size = ? ");
    scanf("%d", arrSize);
    int i;
    for( i = 0; i < *arrSize ; i++ ){
        scanf("%d", *(arr + i));
    }
}

void inverse_reorder (int * arr, int *arrSize){
    int i;
    int temp = 0;
    for ( i = 0; i < *arrSize ; i++ ){
        temp = *(arr+i);
        *(arr+i) = *(arr + *arrSize - i);
        *(arr + *arrSize - i) = temp;
    }
}


问:
Trading algorithm - actions in Q-learning/DQN
The following has completed using MATLAB.

I am trying to build a trading algorithm using Deep Q learning. I have just taken a years worth of daily stock prices and am using that as the training set.

My state space is my [money, stock, price]

money is the amount of cash I have,

stock is the number of stocks I have, and

price is the price of the stock at that time step.

The issue I am having is with the actions; looking online, people only have three actions, { buy | sell | hold }.

My reward function is the difference between the value of portfolio value in the current time step and the previous time step.

But using just three actions, I am unsure how to choose to buy, lets say 67 stocks at the price?

I am using a neural network to approximate the q-values. It has three inputs
[money, stock, price] and 202 outputs, i.e. I can sell between 0 and 100 number of stock, 0, I can hold the stock, or I can buy 1-100 stock.

Can anyone shed some light on the how can I reduce this to 3 actions?

My code is  :

```<code>%  p is the stock price
% sp is the stock price at the next time interval
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

hidden_layers =   1;
actions       = 202;
net           = newff( [-1000000 1000000;-1000000 1000000;0 1000;],
                       [hidden_layers, actions],
                       {'tansig','purelin'},
                       'trainlm'
                       );

net           = init( net );

net.trainParam.showWindow = false;

% neural network training parameters -----------------------------------
net.trainParam.lr     =   0.01;
net.trainParam.mc     =   0.1;
net.trainParam.epochs = 100;

% parameters for q learning --------------------------------------------
epsilon        =    0.8;
gamma          =    0.95;
max_episodes   = 1000;
max_iterations = length( p ) - 1;

reset          =    false;
inital_money   = 1000;
inital_stock   =    0;

%These will be where I save the outputs
save_s        = zeros( max_iterations, max_episodes );
save_pt       = zeros( max_iterations, max_episodes );
save_Q_target = zeros( max_iterations, max_episodes );
save_a        = zeros( max_iterations, max_episodes );

% construct the inital state -------------------------------------------
% a           = randi( [1 3], 1, 1 );
s             = [inital_money;inital_stock;p( 1, 1 )];

% construct initial q matrix -------------------------------------------
Qs            = zeros( 1, actions );
Qs_prime      = zeros( 1, actions );

for     i = 1:max_episodes
    for j = 1:max_iterations             % max_iterations --------------

        Qs = net( s );

        %% here we will choose an action based on epsilon-greedy strategy

        if ( rand() <= epsilon )
            [Qs_value  a] = max(Qs);
        else
            a = randi( [1 202], 1, 1 );
        end

        a2                 = a - 101;
        save_a(j,i)        = a2;
        sp                 = p( j+1, 1 ) ;
        pt                 = s( 1 ) + s( 2 ) * p( j, 1 );
        save_pt(j,i)       = pt;
        [s_prime,reward]   = simulateStock( s, a2, pt, sp );

        Qs_prime           = net( s_prime );

        Q_target           = reward + gamma * max( Qs_prime );
        save_Q_target(j,i) = Q_target;
        Targets            = Qs;

        Targets( a )       =  Q_target;

        save_s( j, i )     = s( 1 );
        s                  = s_prime;
    end

    epsilon = epsilon * 0.99 ;
    reset   = false;
    s       = [inital_money;inital_stock;p(1,1)];
end

% ----------------------------------------------------------------------
function[s_prime,reward] = simulateStock( s, a, pt, sp )
                           money   = s(1);
                           stock   = s(2);
                           price   = s(3);

                           money   = money - a * price ;
                           money   = max( money, 0 );
                           stock   = s(2) + a;
                           stock   = max( stock, 0 );

                           s_prime = [money;stock;sp];
                           reward  = ( money + stock * price ) - pt;
end
</code>```

答:
Actions: ill-defined
 ( if not giving an ultimate reason for so flattened, decaffeinated & knowingly short-cut model )

You may be right, that using a range of just { buy | hold | sell } actions is a frequent habit for academic papers, where authors sometimes decide to illustrate their demonstrated academic efforts on improving learning / statistical methods and opt to pick an exemplary application in a trading domain. The pity is, this could be done in academic papers, but not in the reality of trading.

Why?

Even with an elementary view on trading, the problem is much more complex. As a brief reference, there are more than five principal domains of such model-space. Given a trading is to be modelled, one cannot remain without a fully described strategy --

```<code>Tru-Strategy := {    SelectPOLICY,
                     DetectPOLICY,
                        ActPOLICY,
                   AllocatePOLICY,
                  TerminatePOLICY
                  }
</code>```

Any whatever motivated simplification, that would opt to omit any single one domain of these five principal domains will become whatever but a truly Trading Strategy.

One can easily figure out, what comes out of just training ( the worse from later harnessing such model in doing real trades with ) an ill-defined model, that is not coherent with the reality.

Sure, it can reach ( and will ( again, unless ill-formulated minimiser's criterion function ) ) some mathematical function's minimum, but that does not ensure the reality to immediately change it's so far natural behaviours and to start "obey" the ill-defined model and to "dance" according to such oversimplified or otherwise skewed ( ill-modelled )-opinions about the reality.

Rewards: ill-defined
 ( if not giving a reason for ignoring the fact or delayed rewards )

If in doubts what this means, try to follow an example:

Today, the Strategy-Model decides to A:Buy(AAPL,67).

Tomorrow, AAPL goes down, some 0.1% and thus the immediate reward ( as was proposed above ) is negative, thus punishing such decision. The Model is stimulated not to do it ( do not buy AAPL ).

The point is, that after some period of time, AAPL rises much higher, producing much higher reward compared to initial fluctuations in D2D Close, which is known, but the proposed Strategy-Model Q-fun simply principally erroneously did not reflect at all.

Beware WYTIWYG -- What You Train Is What You Get ...

This means an as-is-Model could be trained to act according to the such defined stimuli, but it's actual behaviour will favour NOTHING but such extremely naive intraday "quasi-scalping" shots with limited ( if any at all ) support from actual Market State & Market Dynamics as are available by many industry-wide accepted quantitative models.

So, sure, one can train a reality-blind model, that was kept blind & deaf ( ignoring the reality of the Problem Domain ), but for what sake?

Epilogue:

There is nothing like a "Data Science"
even when MarCom & HR beat their drums & whistles, as they indeed do a lot nowadays

Why?

Exactly because the above observed rationale. Having data-points is nothing. Sure, it is better than standing clueless in front of the customer without a single observation of the reality, but the Data-points do not save the game.

It is the domain-knowledge, that starts to make some sense from the Data-points, not the Data-points per se.

If still in doubts, if one has a few terabytes of numbers, there is no Data Science to tell you, what the data-points represent.

On the other hand, if one knows, from the domain-specific context, these data-points ought be temperature readings, there is still no Data-Science God to tell you, whether there are all ( just by coincidence ) in [°K] or [°C]  ( if there are just positive readings >= 0.00001 ).

Body:
The following has completed using MATLAB.

I am trying to build a trading algorithm using Deep Q learning. I have just taken a years worth of daily stock prices and am using that as the training set.

My state space is my [money, stock, price]

money is the amount of cash I have,

stock is the number of stocks I have, and

price is the price of the stock at that time step.

The issue I am having is with the actions; looking online, people only have three actions, { buy | sell | hold }.

My reward function is the difference between the value of portfolio value in the current time step and the previous time step.

But using just three actions, I am unsure how to choose to buy, lets say 67 stocks at the price?

I am using a neural network to approximate the q-values. It has three inputs
[money, stock, price] and 202 outputs, i.e. I can sell between 0 and 100 number of stock, 0, I can hold the stock, or I can buy 1-100 stock.

Can anyone shed some light on the how can I reduce this to 3 actions?

My code is  :

%  p is the stock price
% sp is the stock price at the next time interval
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

hidden_layers =   1;
actions       = 202;
net           = newff( [-1000000 1000000;-1000000 1000000;0 1000;],
                       [hidden_layers, actions],
                       {'tansig','purelin'},
                       'trainlm'
                       );

net           = init( net );

net.trainParam.showWindow = false;

% neural network training parameters -----------------------------------
net.trainParam.lr     =   0.01;
net.trainParam.mc     =   0.1;
net.trainParam.epochs = 100;

% parameters for q learning --------------------------------------------
epsilon        =    0.8;
gamma          =    0.95;
max_episodes   = 1000;
max_iterations = length( p ) - 1;

reset          =    false;
inital_money   = 1000;
inital_stock   =    0;

%These will be where I save the outputs
save_s        = zeros( max_iterations, max_episodes );
save_pt       = zeros( max_iterations, max_episodes );
save_Q_target = zeros( max_iterations, max_episodes );
save_a        = zeros( max_iterations, max_episodes );

% construct the inital state -------------------------------------------
% a           = randi( [1 3], 1, 1 );
s             = [inital_money;inital_stock;p( 1, 1 )];

% construct initial q matrix -------------------------------------------
Qs            = zeros( 1, actions );
Qs_prime      = zeros( 1, actions );

for     i = 1:max_episodes
    for j = 1:max_iterations             % max_iterations --------------

        Qs = net( s );

        %% here we will choose an action based on epsilon-greedy strategy

        if ( rand() <= epsilon )
            [Qs_value  a] = max(Qs);
        else
            a = randi( [1 202], 1, 1 );
        end

        a2                 = a - 101;
        save_a(j,i)        = a2;
        sp                 = p( j+1, 1 ) ;
        pt                 = s( 1 ) + s( 2 ) * p( j, 1 );
        save_pt(j,i)       = pt;
        [s_prime,reward]   = simulateStock( s, a2, pt, sp );

        Qs_prime           = net( s_prime );

        Q_target           = reward + gamma * max( Qs_prime );
        save_Q_target(j,i) = Q_target;
        Targets            = Qs;

        Targets( a )       =  Q_target;

        save_s( j, i )     = s( 1 );
        s                  = s_prime;
    end

    epsilon = epsilon * 0.99 ;
    reset   = false;
    s       = [inital_money;inital_stock;p(1,1)];
end

% ----------------------------------------------------------------------
function[s_prime,reward] = simulateStock( s, a, pt, sp )
                           money   = s(1);
                           stock   = s(2);
                           price   = s(3);

                           money   = money - a * price ;
                           money   = max( money, 0 );
                           stock   = s(2) + a;
                           stock   = max( stock, 0 );

                           s_prime = [money;stock;sp];
                           reward  = ( money + stock * price ) - pt;
end

Body:
Actions: ill-defined
 ( if not giving an ultimate reason for so flattened, decaffeinated & knowingly short-cut model )

You may be right, that using a range of just { buy | hold | sell } actions is a frequent habit for academic papers, where authors sometimes decide to illustrate their demonstrated academic efforts on improving learning / statistical methods and opt to pick an exemplary application in a trading domain. The pity is, this could be done in academic papers, but not in the reality of trading.

Why?

Even with an elementary view on trading, the problem is much more complex. As a brief reference, there are more than five principal domains of such model-space. Given a trading is to be modelled, one cannot remain without a fully described strategy --

Tru-Strategy := {    SelectPOLICY,
                     DetectPOLICY,
                        ActPOLICY,
                   AllocatePOLICY,
                  TerminatePOLICY
                  }

Any whatever motivated simplification, that would opt to omit any single one domain of these five principal domains will become whatever but a truly Trading Strategy.

One can easily figure out, what comes out of just training ( the worse from later harnessing such model in doing real trades with ) an ill-defined model, that is not coherent with the reality.

Sure, it can reach ( and will ( again, unless ill-formulated minimiser's criterion function ) ) some mathematical function's minimum, but that does not ensure the reality to immediately change it's so far natural behaviours and to start "obey" the ill-defined model and to "dance" according to such oversimplified or otherwise skewed ( ill-modelled )-opinions about the reality.

Rewards: ill-defined
 ( if not giving a reason for ignoring the fact or delayed rewards )

If in doubts what this means, try to follow an example:

Today, the Strategy-Model decides to A:Buy(AAPL,67).

Tomorrow, AAPL goes down, some 0.1% and thus the immediate reward ( as was proposed above ) is negative, thus punishing such decision. The Model is stimulated not to do it ( do not buy AAPL ).

The point is, that after some period of time, AAPL rises much higher, producing much higher reward compared to initial fluctuations in D2D Close, which is known, but the proposed Strategy-Model Q-fun simply principally erroneously did not reflect at all.

Beware WYTIWYG -- What You Train Is What You Get ...

This means an as-is-Model could be trained to act according to the such defined stimuli, but it's actual behaviour will favour NOTHING but such extremely naive intraday "quasi-scalping" shots with limited ( if any at all ) support from actual Market State & Market Dynamics as are available by many industry-wide accepted quantitative models.

So, sure, one can train a reality-blind model, that was kept blind & deaf ( ignoring the reality of the Problem Domain ), but for what sake?

Epilogue:

There is nothing like a "Data Science"
even when MarCom & HR beat their drums & whistles, as they indeed do a lot nowadays

Why?

Exactly because the above observed rationale. Having data-points is nothing. Sure, it is better than standing clueless in front of the customer without a single observation of the reality, but the Data-points do not save the game.

It is the domain-knowledge, that starts to make some sense from the Data-points, not the Data-points per se.

If still in doubts, if one has a few terabytes of numbers, there is no Data Science to tell you, what the data-points represent.

On the other hand, if one knows, from the domain-specific context, these data-points ought be temperature readings, there is still no Data-Science God to tell you, whether there are all ( just by coincidence ) in [°K] or [°C]  ( if there are just positive readings >= 0.00001 ).

ContentLicense: CC BY-SA 4.0


问:
Defined a custom action in controllers and added routes but still get no route matches error. Rails 5 app
I have a links controller and I have defined two custom actions called upvote and downvote. The action definitions:-

```<code>  def upvote
    @link = Link.find_by(id: params[:id])
    @link.vote_count += 1
    flash[:message]="Vote successfully registered"
    redirect_to root_path
  end

  def downvote
    @link = Link.find_by(id: params[:id])
    @link.vote_count -= 1
    flash[:message]="Vote successfully registered"
    redirect_to root_path
  end
</code>```

I have added the routes for these actions in the routes.rb file:-

```<code>  post '/links/:id', to: 'links#upvote', as: 'upvote'
  post '/links/:id', to: 'links#downvote', as: 'downvote'
</code>```

rails routes shows:-

```<code>upvote POST   /links/:id(.:format)     links#upvote
downvote POST   /links/:id(.:format)     links#downvote
</code>```

I'm calling the actions from the view as below:-

```<code><% if link.user != current_user %>
  <span class="vote-buttons">
    <div class="btn-group-vertical" role="group" aria-label="vote-buttons">
      <%= button_to 'Up', 'upvote_path', type:"button", class:"btn btn-xs btn-success" %>
      <%= button_to 'Down', 'downvote_path', type:"button", class:"btn btn-xs btn-danger" %>
    </div>
  </span>
<% end %>
</code>```

But I keep getting this error:-

```<code>No route matches [POST] "/upvote_path"
</code>```

Why am I seeing this even though rails routes shows that the route exists?

I tried restarting the server too.

答:
No route matches [POST] "/upvote_path"

As per your routes, you are missing an :id which should be sent inside the route.

```<code><%= button_to 'Up', upvote_path(link), type:"button", class:"btn btn-xs btn-success" %>
</code>```

Same applies for downvote

```<code><%= button_to 'Down', downvote_path(link), type:"button", class:"btn btn-xs btn-danger" %>
</code>```

Addition to the above problem, you are not saving @link after a upvote or a downvote

```<code>def upvote
  @link = Link.find_by(id: params[:id])
  @link.vote_count += 1
  @link.save!
  flash[:message]="Vote successfully registered"
  redirect_to root_path
end

def downvote
  @link = Link.find_by(id: params[:id])
  @link.vote_count -= 1
  @link.save!
  flash[:message]="Vote successfully registered"
  redirect_to root_path
end
</code>```

Body:
I have a links controller and I have defined two custom actions called upvote and downvote. The action definitions:-

  def upvote
    @link = Link.find_by(id: params[:id])
    @link.vote_count += 1
    flash[:message]="Vote successfully registered"
    redirect_to root_path
  end

  def downvote
    @link = Link.find_by(id: params[:id])
    @link.vote_count -= 1
    flash[:message]="Vote successfully registered"
    redirect_to root_path
  end

I have added the routes for these actions in the routes.rb file:-

  post '/links/:id', to: 'links#upvote', as: 'upvote'
  post '/links/:id', to: 'links#downvote', as: 'downvote'

rails routes shows:-

upvote POST   /links/:id(.:format)     links#upvote
downvote POST   /links/:id(.:format)     links#downvote

I'm calling the actions from the view as below:-

<% if link.user != current_user %>

      <%= button_to 'Up', 'upvote_path', type:"button", class:"btn btn-xs btn-success" %>
      <%= button_to 'Down', 'downvote_path', type:"button", class:"btn btn-xs btn-danger" %>

<% end %>

But I keep getting this error:-

No route matches [POST] "/upvote_path"

Why am I seeing this even though rails routes shows that the route exists?

I tried restarting the server too.

Body:
No route matches [POST] "/upvote_path"

As per your routes, you are missing an :id which should be sent inside the route.

<%= button_to 'Up', upvote_path(link), type:"button", class:"btn btn-xs btn-success" %>

Same applies for downvote

<%= button_to 'Down', downvote_path(link), type:"button", class:"btn btn-xs btn-danger" %>

Addition to the above problem, you are not saving @link after a upvote or a downvote

def upvote
  @link = Link.find_by(id: params[:id])
  @link.vote_count += 1
  @link.save!
  flash[:message]="Vote successfully registered"
  redirect_to root_path
end

def downvote
  @link = Link.find_by(id: params[:id])
  @link.vote_count -= 1
  @link.save!
  flash[:message]="Vote successfully registered"
  redirect_to root_path
end


问:
Clojure + stomp + websockets
I have followed a couple of tutorials about interactive/real-time applications using STOMP over WebSockets with the Spring framework using the messaging layer.

Example in Spring

I would like to implement the same functionality in clojure. Has anybody experience in implementing a similar application? I have been looking for documentation/examples about using these technologies, but there is nothing like the examples in clojure.

That it makes sense? Is it necessary to have an external message broker to connect the backend app and the browser clients?

答:
I have some experience using a broker to pass messages along.  However, I think it's still best to write your own http frontend for the browser to talk to.  That frontend in turn can post messages to a broker (using Stomp or any other protocol).  That way, you have more control and you're not tied to a message broker.  For instance you can have the frontend do more than just websockets, like serve static files, or a regular HTTP interface.

But that's up to you, if the broker supports websockets, you can use that too (see for instance ActiveMQ).  My advice is: try the simplest possible way first :-).

Take a look at Http-kit for a good Clojure webserver.  It also has good websocket support.

Title: Clojure + stomp + websockets


问:
Split lines using tags that appear multiple times in file
I have a file that has the contents as below:

```<code>this is test line 1
this is testing purpose
<public>
am inside of public
doing lot of stuffs and priting result here
</public>
<public>
am inside of another public
doing another set of stuffs and priting here
</public>
</code>```

I want to split this file into three different sections:

The lines which are not inside any of the   section

The lines which are inside of first   section

The lines which are inside of second   section

I tried with take_while and drop_while,

```<code>File.open(filename).each_line.take_while do |l|
  !l.include?('</public>')
end.drop_while do |l|
  !l.include?('<public>')
end.drop(1))
</code>```

but it extracts only the first <public>...</public> section.

I am looking for a better solution. Any suggestion would be appreciated.

答:
```<code>File.read(filename).split(/<\/?public>/)
                   .map(&:strip)
                   .reject(&:empty?) # [0..2] if the file has a tail
#⇒ [
#   [0] "this is test line 1 \nthis is testing purpose",
#   [1] "am inside of public\ndoing lot of stuffs and priting result here",
#   [2] "am inside of another public\ndoing another set of stuffs and priting here"
# ]
</code>```

Body:
I have a file that has the contents as below:

this is test line 1
this is testing purpose
<public>
am inside of public
doing lot of stuffs and priting result here
</public>
<public>
am inside of another public
doing another set of stuffs and priting here
</public>

I want to split this file into three different sections:

The lines which are not inside any of the   section

The lines which are inside of first   section

The lines which are inside of second   section

I tried with take_while and drop_while,

File.open(filename).each_line.take_while do |l|
  !l.include?('</public>')
end.drop_while do |l|
  !l.include?('<public>')
end.drop(1))

but it extracts only the first <public>...</public> section.

I am looking for a better solution. Any suggestion would be appreciated.


答:
The %d format specifier in scanf expects an int* as its parameter. However, you are dereferencing the pointer when you do this: *(arr + i). You don't need the *.

However, in your main function, you declare two pointers that don't point anywhere. You need to allocate some storage e.g.

```<code>int main (void){
    int arrSize;
    int i;

    int* arr = input_integer(&arrSize);
</code>```

I changed input_integer to return the int pointer of the array.

And input_integer will allocate storage based on the input array size:

```<code>int* input_integer (int *arrSize){
    printf("Array size = ? ");
    scanf("%d", arrSize);
    // Should really validate the size here
    int *arr = calloc(*arrSize, sizof *arr);
    int i;
    for( i = 0; i < *arrSize ; i++ ){
        scanf("%d", arr + i);
    }
    return arr;
}
</code>```

Then your main function should always use arrSize without dereferencing it and also free the pointer at the end.

Title: reversing an array using pointer c

Body:
The %d format specifier in scanf expects an int* as its parameter. However, you are dereferencing the pointer when you do this: *(arr + i). You don't need the *.

However, in your main function, you declare two pointers that don't point anywhere. You need to allocate some storage e.g.

int main (void){
    int arrSize;
    int i;

    int* arr = input_integer(&arrSize);

I changed input_integer to return the int pointer of the array.

And input_integer will allocate storage based on the input array size:

int* input_integer (int *arrSize){
    printf("Array size = ? ");
    scanf("%d", arrSize);
    // Should really validate the size here
    int *arr = calloc(*arrSize, sizof *arr);
    int i;
    for( i = 0; i < *arrSize ; i++ ){
        scanf("%d", arr + i);
    }
    return arr;
}

Then your main function should always use arrSize without dereferencing it and also free the pointer at the end.


问:
Adding Boost Library to a C++ project in OS X Eclipse
I am have been attempting to get a C++ project setup using boost file system library using eclipse. I followed these directions to install boost on my system. The directions where pretty much

download

extract

run bootstrap.sh

run ./bjam architecture=combined

That seemed to go fine, no errors. I then fired up eclipse and created a new test project called test with a single file called test.cpp. The code in it is:

```<code>#include <stdio.h>
#include <boost/filesystem.hpp>

int main() {
    boost::filesystem::path path("/Users/schoen"); // random pathname
    bool result = boost::filesystem::is_directory(path);
    printf("Path is a directory : %d\n", result);
    return 0;
}
</code>```

This is just something simple to make sure it is all set up correctly. Of course I tried to compile at this point and it failed. Did some googling and found this site. It said to add the boost library to the linker by going to project properties and adding "boost_filesystem". I tried this, and well it didn't work.

Can someone point me in the right direction or give me a hint to how to set up Boost in an Eclipse project?

I am new to C++ and Eclipse, and most my experience is in Java with Netbeans. So I am pretty lost at the moment.

UPDATE

I just wanted to update on what I have tried based on the answers given.

Based on Alex's suggestion I added boost_system and boost_filesystem to the linker list. I was still getting the same compiler errors.

Following the suggestion from rve I added the path to the boost libraries to the Library search path. When this did not work. I cleared out the linker list and tried it with just the library search path. This also did not work.

I then cleared the Library search path. I then manually edited the command on the linker window to be 'g++ -L/Users/jacobschoen/Library/boost_1_45_0/stage/lib -lboost -lboost_filesystem'. This also did not work.

In all of these I tried setting the path to boost to be '/Users/jacobschoen/Library/boost_1_45_0' and '/Users/jacobschoen/Library/boost_1_45_0/stage/lib'. Neither worked.

As requested the comiler error for the above code is:

```<code>**** Build of configuration Debug for project test ****

make all
Building file: ../src/test.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/test.d" -MT"src/test.d" -o"src/test.o" "../src/test.cpp"
../src/test.cpp:10:32: warning: boost/filesystem.hpp: No such file or directory
../src/test.cpp: In function 'int main()':
../src/test.cpp:13: error: 'boost' has not been declared
../src/test.cpp:13: error: expected `;' before 'path'
../src/test.cpp:14: error: 'boost' has not been declared
../src/test.cpp:14: error: 'path' was not declared in this scope
make: *** [src/test.o] Error 1
</code>```

If any one has any further suggestions I am still trying.

Second Update
On a suggestion by rholmes I added an include library along with the linker list and library search path. So now the compile error is:

```<code>**** Build of configuration Debug for project test ****

make all
Building target: test
Invoking: MacOS X C++ Linker
g++ -L/Users/jacobschoen/Library/boost_1_45_0 -o "test"  ./src/test.o   -lboost_system -lboost_filesystem
ld: library not found for -lboost_system
collect2: ld returned 1 exit status
make: *** [test] Error 1
</code>```

Any ideas?

答: Add boost_system to the linker list, together with boost_filesystem.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am have been attempting to get a C++ project setup using boost file system library using eclipse. I followed these directions to install boost on my system. The directions where pretty much

download

extract

run bootstrap.sh

run ./bjam architecture=combined

That seemed to go fine, no errors. I then fired up eclipse and created a new test project called test with a single file called test.cpp. The code in it is:

#include <stdio.h>
#include <boost/filesystem.hpp>

int main() {
    boost::filesystem::path path("/Users/schoen"); // random pathname
    bool result = boost::filesystem::is_directory(path);
    printf("Path is a directory : %d\n", result);
    return 0;
}

This is just something simple to make sure it is all set up correctly. Of course I tried to compile at this point and it failed. Did some googling and found this site. It said to add the boost library to the linker by going to project properties and adding "boost_filesystem". I tried this, and well it didn't work.

Can someone point me in the right direction or give me a hint to how to set up Boost in an Eclipse project?

I am new to C++ and Eclipse, and most my experience is in Java with Netbeans. So I am pretty lost at the moment.

UPDATE

I just wanted to update on what I have tried based on the answers given.

Based on Alex's suggestion I added boost_system and boost_filesystem to the linker list. I was still getting the same compiler errors.

Following the suggestion from rve I added the path to the boost libraries to the Library search path. When this did not work. I cleared out the linker list and tried it with just the library search path. This also did not work.

I then cleared the Library search path. I then manually edited the command on the linker window to be 'g++ -L/Users/jacobschoen/Library/boost_1_45_0/stage/lib -lboost -lboost_filesystem'. This also did not work.

In all of these I tried setting the path to boost to be '/Users/jacobschoen/Library/boost_1_45_0' and '/Users/jacobschoen/Library/boost_1_45_0/stage/lib'. Neither worked.

As requested the comiler error for the above code is:

**** Build of configuration Debug for project test ****

make all
Building file: ../src/test.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/test.d" -MT"src/test.d" -o"src/test.o" "../src/test.cpp"
../src/test.cpp:10:32: warning: boost/filesystem.hpp: No such file or directory
../src/test.cpp: In function 'int main()':
../src/test.cpp:13: error: 'boost' has not been declared
../src/test.cpp:13: error: expected `;' before 'path'
../src/test.cpp:14: error: 'boost' has not been declared
../src/test.cpp:14: error: 'path' was not declared in this scope
make: *** [src/test.o] Error 1

If any one has any further suggestions I am still trying.

Second Update
On a suggestion by rholmes I added an include library along with the linker list and library search path. So now the compile error is:

**** Build of configuration Debug for project test ****

make all
Building target: test
Invoking: MacOS X C++ Linker
g++ -L/Users/jacobschoen/Library/boost_1_45_0 -o "test"  ./src/test.o   -lboost_system -lboost_filesystem
ld: library not found for -lboost_system
collect2: ld returned 1 exit status
make: *** [test] Error 1

Any ideas?


问:
How can a weak map be implemented in ES5?
There is another question that asks the same, but I cannot grok the accepted answer.

The library in question appears to use Object.defineProperty to add a reference to the object to be stored (albeit indirectly via another object).

But... surely that would then mean the object cannot be garbage collected because of this link?

What am I missing?

Is it really possible to create an object and store it somewhere without maintaining a reference noticeable by the garbage collector? (Prior to ES2015)

The accepted answer:

It took me a while to grok the code, but then it hit me: the key
  itself is used to store a reference to the value.

For example, several layers into set it does

defProp(obj, globalID, { value: store }); where defProp has been
  defined to be Object.defineProperty, obj is the key, globalID is a
  guid and store is a storage object that contains the value.

Then down in get it looks up the value with

obj[globalID];

This is very clever. The WeakMap doesn't actually contain a reference
  to anything (weak or otherwise)-- it just sets up a policy of where to
  secretly store the value. The use of Object.defineProperty means that
  you won't accidentally discover the value storage-- you have to know
  the magic guid to look it up.

Since the key directly refers to the value (and the WeakMap doesn't
  refer to it), when all references to the key are gone, it gets GCed
  like normal.

The library in question.

答:
surely that would then mean the object cannot be garbage collected because of this link?

Yes.

What am I missing?

Nothing. Maybe that this is exactly the desired behaviour.

As the answer explains, "the WeakMap doesn't actually contain a reference to anything (weak or otherwise)" and "when all references to the key are gone, it gets GCed like normal."


问:
How to use a dropdown value as a if function
i have a html code as following

tfa_78 is a dropdown list, but build in formassembly, so not able to put it in the code
the value "Test" is just to show myself, that the code in general is running ;)

```<code><script>

var tfa78 = document.getElementById("tfa_78").selvalue;

if( tfa78 == "karte" )
{
document.getElementById('tfa_2448').innerHTML ='<b>Bei karte anrufen.</b> <br>';
} else {
document.getElementById('tfa_2448').innerHTML ='Test';
}
</code>```

my question: it is not working, i do not get the first result, what might be wrong? is the selvalue the right thing to select the dropdown value? before, i used this code with a textfield, that was working, so i guess it is anyhow related to the wrong "get" value argument?

Thanks a lot in advance for your support.

I updated my code already due to few comments as below:

```<code> <script>
 var tfa78 = document.getElementById("tfa_78").value;
 if( tfa78 == 'tfa_2438' ) {
 document.getElementById('tfa_2448').innerHTML ='<b> anrufen.</b> <br>';
 }else {
 document.getElementById('tfa_2448').innerHTML ='Test'+ tfa78;
 }</script>
</code>```

and this is the dropdown code, but i can not change that.

```<code><select id="tfa_78" name="tfa_78" title="Quelle?" class="required"><option
value="">Bitte auswählen:</option>
<option value="tfa_2438" id="tfa_2438" data-conditionals="#tfa_93"
class="">karte</option>
<option value="tfa_2437" id="tfa_2437" data-conditionals="#tfa_93"
class="">Test</option>
</select>
</code>```

答:
To get the selected value you should use the property value.
The selvalue I don't in which language exists. See following:

function change(){
  var tfa78 = document.getElementById("tfa_78").value;

  if( tfa78 == "karte" )
  {
  document.getElementById('tfa_2448').innerHTML ='Bei karte anrufen.
';
  } else {
  document.getElementById('tfa_2448').innerHTML ='Test';
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="tfa_78" onchange="change()">
  <option/>
  <option value="karte">karte</option>
  <option value="diem">diem</option>
</select>

<div id="tfa_2448"/></code>```

Body:
i have a html code as following

tfa_78 is a dropdown list, but build in formassembly, so not able to put it in the code
the value "Test" is just to show myself, that the code in general is running ;)

and this is the dropdown code, but i can not change that.

<select id="tfa_78" name="tfa_78" title="Quelle?" class="required"><option
value="">Bitte auswählen:</option>
<option value="tfa_2438" id="tfa_2438" data-conditionals="#tfa_93"
class="">karte</option>
<option value="tfa_2437" id="tfa_2437" data-conditionals="#tfa_93"
class="">Test</option>
</select>

Body:
To get the selected value you should use the property value.
The selvalue I don't in which language exists. See following:

function change(){
  var tfa78 = document.getElementById("tfa_78").value;

  if( tfa78 == "karte" )
  {
  document.getElementById('tfa_2448').innerHTML ='<b>Bei karte anrufen.</b> <br>';
  } else {
  document.getElementById('tfa_2448').innerHTML ='Test';
  }
}

<select id="tfa_78" onchange="change()">
  <option/>
  <option value="karte">karte</option>
  <option value="diem">diem</option>
</select>

<div id="tfa_2448"/>


问:
When downloading image using XmlHttpRequest, I getting this error
This is the code I'm following.

```<code> storageRef.child('images/stars.jpg').getDownloadURL().then(function(url) {
      // `url` is the download URL for 'images/stars.jpg'

  // This can be downloaded directly:
  var xhr = new XMLHttpRequest();
  xhr.responseType = 'blob';
  xhr.onload = function(event) {
    var blob = xhr.response;
  };
  xhr.open('GET', url);
  xhr.setRequestHeader('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  xhr.setRequestHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
  xhr.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type');
  xhr.send();

  // Or inserted into an <img> element:
  var img = document.getElementById('myimg');
  img.src = url;
}).catch(function(error) {
  // Handle any errors
});
</code>```

But I can't download image file as it says:

No 'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost:8000' is therefore not allowed
  access.

However, I'm successful in displaying the image in my img tag. It would be good if I could download it also.

I using localhost to run this.

Updated:
This is the new error:

Request header field Access-Control-Allow-Origin is not allowed by
  Access-Control-Allow-Headers in preflight response.

答:
You must add headers in your server:

```<code>header('Access-Control-Allow-Origin', '*');
header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
header('Access-Control-Allow-Headers', 'Content-Type');
</code>```

For example, this will allow all domains for the methods specified and headers.

Body:
This is the code I'm following.

 storageRef.child('images/stars.jpg').getDownloadURL().then(function(url) {
      // `url` is the download URL for 'images/stars.jpg'

  // This can be downloaded directly:
  var xhr = new XMLHttpRequest();
  xhr.responseType = 'blob';
  xhr.onload = function(event) {
    var blob = xhr.response;
  };
  xhr.open('GET', url);
  xhr.setRequestHeader('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  xhr.setRequestHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
  xhr.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type');
  xhr.send();

  // Or inserted into an  element:
  var img = document.getElementById('myimg');
  img.src = url;
}).catch(function(error) {
  // Handle any errors
});

But I can't download image file as it says:

No 'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost:8000' is therefore not allowed
  access.

However, I'm successful in displaying the image in my img tag. It would be good if I could download it also.

I using localhost to run this.

Updated:
This is the new error:

Request header field Access-Control-Allow-Origin is not allowed by
  Access-Control-Allow-Headers in preflight response.

Body:
You must add headers in your server:

header('Access-Control-Allow-Origin', '*');
header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
header('Access-Control-Allow-Headers', 'Content-Type');

For example, this will allow all domains for the methods specified and headers.


问:
Download and install apk (without publishing in playstore) from the Instant App
I have uploaded .apk file to the dropbox. I want to download and launch app when user clicks an install button in the Instant App. But the following exception occurs after call to startActivity():

Caused by: java.lang.SecurityException: Permission Denial: opening provider android.support.v4.content.FileProvider from ProcessRecord{8593d11 2399:com.google.android.packageinstaller/u0a26} (pid=2399, uid=10026) that is not exported from uid 10298

```<code>Intent intent = new Intent(Intent.ACTION_VIEW);
if (intent.resolveActivity(getPackageManager()) == null) {
    Log.e("No Packate Manager", intent.getPackage() + "");
    return;
}

Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {  //BuildConfig.APPLICATION_ID
    // File file = new File(File folder, "app-debug.apk");
    //uri = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".fileprovider", file);
    uri = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".fileprovider", new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "app-debug.apk"));
    List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resInfoList) {
        String packageName = resolveInfo.activityInfo.packageName;
        grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }
} else {
    // uri = Uri.fromFile(new File("/mnt/sdcard/Download/app-debug.apk"));
    File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    File outputFile = new File(folder, "app-debug.apk");
    uri = Uri.fromFile(outputFile);
}

intent.setDataAndType(uri, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// install.setDataAndType(myuri, manager.getMimeTypeForDownloadedFile(downloadId));

startActivity(intent);
</code>```

答:
It's not possible to initiate an install of an APK file that is hosted outside of Play Store from an Instant App (nor is it recommended).

The error you are receiving is because Instant Apps cannot read (or write) to external disk storage. For more info on restricted features in Instant Apps, please see the docs. Instant Apps can read/write to their own internal storage though, however they cannot expose or share that data to other apps.

The recommended approach is to publish a regular APK to Google Play and then use the provided showInstallPrompt() helper method to initiate an install. This will direct the user to Google Play to install your app.

You should also review our UX guidelines for presenting such an install button (called an "explicit install prompt").

Body:
I have uploaded .apk file to the dropbox. I want to download and launch app when user clicks an install button in the Instant App. But the following exception occurs after call to startActivity():

Caused by: java.lang.SecurityException: Permission Denial: opening provider android.support.v4.content.FileProvider from ProcessRecord{8593d11 2399:com.google.android.packageinstaller/u0a26} (pid=2399, uid=10026) that is not exported from uid 10298

Intent intent = new Intent(Intent.ACTION_VIEW);
if (intent.resolveActivity(getPackageManager()) == null) {
    Log.e("No Packate Manager", intent.getPackage() + "");
    return;
}

Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {  //BuildConfig.APPLICATION_ID
    // File file = new File(File folder, "app-debug.apk");
    //uri = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".fileprovider", file);
    uri = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".fileprovider", new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "app-debug.apk"));
    List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resInfoList) {
        String packageName = resolveInfo.activityInfo.packageName;
        grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }
} else {
    // uri = Uri.fromFile(new File("/mnt/sdcard/Download/app-debug.apk"));
    File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    File outputFile = new File(folder, "app-debug.apk");
    uri = Uri.fromFile(outputFile);
}

intent.setDataAndType(uri, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// install.setDataAndType(myuri, manager.getMimeTypeForDownloadedFile(downloadId));

startActivity(intent);


问:
Slack API: `groups.list` not returning private channels I am part of
I am trying to get a list of all channels (public and private) to which I can post messages.

I am getting a list of public channels using channels.list and it is working well. It is returning me all the public channels to which I can post.

I am trying to get a list of private channels by using groups.list. The call is returning an OK response, but I am not getting any results.

I have created a private channel. I am the only member. This channel is not being returned by the group.list API call.

I have groups:read and channels:read oauth scopes.

This is being done using the Slacker python library.

Even the following curl call does not return me any private channels:

```<code> curl --data "token=xoxb-REDACTED"  'https://slack.com/api/groups.list'
</code>```

How can I get a list of private channels I am part of using the Slack API?

UPDATE:

If I use the dev token in the above curl call, it does correctly return me my private channels.

When I look inside of Slack at the integrations, I see the integration with my dev app. It says that the dev app can Access information about user’s private channels, granted by 1 team member (among others). Something is amiss and I don't know where. It seems that the oauth token has an issue, but I don't know what.

答: The problem is that I was also requesting the bot oauth scope. When Slack finished authorizing my app, it was issuing a personal token and a bot token. The bot token does not have access to the private channels, while the personal one does.

Body:
I am trying to get a list of all channels (public and private) to which I can post messages.

I am getting a list of public channels using channels.list and it is working well. It is returning me all the public channels to which I can post.

I am trying to get a list of private channels by using groups.list. The call is returning an OK response, but I am not getting any results.

I have created a private channel. I am the only member. This channel is not being returned by the group.list API call.

I have groups:read and channels:read oauth scopes.

This is being done using the Slacker python library.

Even the following curl call does not return me any private channels:

 curl --data "token=xoxb-REDACTED"  'https://slack.com/api/groups.list'

How can I get a list of private channels I am part of using the Slack API?

UPDATE:

If I use the dev token in the above curl call, it does correctly return me my private channels.

When I look inside of Slack at the integrations, I see the integration with my dev app. It says that the dev app can Access information about user’s private channels, granted by 1 team member (among others). Something is amiss and I don't know where. It seems that the oauth token has an issue, but I don't know what.


问:
indexpath of cells in grouped tableview
i have a table view, split into alphabetical sections, populated from array that has been filtered

how can i track the "true" indexpath of cells in a grouped tableview.
instead of the count starting at 0 for each section.

i need to get this so i can access the right bit of data from an array

at the moment it works like this(just in case im not clear)

(section 0)
row 0
row 1
row 2
(section 1)
row 0
row 1
etc...........

i need to get it so i can get

section 0)
row 0
row 1
row 2
(section 1)
row 3
row 4

thanks in advance

答:
Use this code to get correct row,</p>

```<code>NSUInteger row = 0;
for (NSUInteger i = 0; i < noofsectionsinTableView; i++)
   row += [self.tableView numberOfRowsInSection:i];
return row;
</code>```

Title: indexpath of cells in grouped tableview

Body:
Use this code to get correct row,

NSUInteger row = 0;
for (NSUInteger i = 0; i < noofsectionsinTableView; i++)
   row += [self.tableView numberOfRowsInSection:i];
return row;


问:
Extracting a laser line in an image (using OpenCV)
i have a picture from a laser line and i would like to extract that line out of the image.

As the laser line is red, i take the red channel of the image and then searching for the highest intensity in every row:

The problem now is, that there are also some points which doesnt belong to the laser line (if you zoom into the second picture, you can see these points).

Does anyone have an idea for the next steps (to remove the single points and also to extract the lines)?

That was another approach to detect the line:
First i blurred out that "black-white" line with a kernel, then i thinned(skeleton) that blurred line to a thin line, then i applied an OpenCV function to detect the line.. the result is in the below image:

NEW:

Now i have another harder situation.
I have to extract a green laser light.

  The problem here is that the colour range of the laser line is wider and changing.

On some parts of the laser line the pixel just have high green component, while on other parts the pixel have high blue component as well.

答:
I'm really sorry for the short answer without any code, but I suggest you take contours and process them.

I dont know exact what you need, so here are two approaches for you:

just collect as much as possible contours on single line (use centers and try find straight line with smallest mean)

as first way, but trying heuristically combine separated lines.... it's much harder, but this may give you almost full laser line from image.

--

Some example for yours picture:

```<code>import cv2
import numpy as np
import math

img = cv2.imread('image.png')
hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
# filtering red area of hue
redHueArea = 15
redRange = ((hsv[:, :, 0] + 360 + redHueArea) % 360)
hsv[np.where((2 * redHueArea) > redRange)] = [0, 0, 0]
# filtering by saturation
hsv[np.where(hsv[:, :, 1] < 95)] = [0, 0, 0]
# convert to rgb
rgb = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
# select only red grayscaled channel with low threshold
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
gray = cv2.threshold(gray, 15, 255, cv2.THRESH_BINARY)[1]
# contours processing
(_, contours, _) = cv2.findContours(gray.copy(), cv2.RETR_LIST, 1)
for c in contours:
    area = cv2.contourArea(c)
    if area < 8: continue
    epsilon = 0.1 * cv2.arcLength(c, True) # tricky smoothing to a single line
    approx = cv2.approxPolyDP(c, epsilon, True)
    cv2.drawContours(img, [approx], -1, [255, 255, 255], -1)

cv2.imshow('result', img)
cv2.waitKey(0)
</code>```

In your case it's work perfectly, but, as i already said, you will need to do much more work with contours.

Body:
I'm really sorry for the short answer without any code, but I suggest you take contours and process them.

I dont know exact what you need, so here are two approaches for you:

just collect as much as possible contours on single line (use centers and try find straight line with smallest mean)

as first way, but trying heuristically combine separated lines.... it's much harder, but this may give you almost full laser line from image.

--

Some example for yours picture:

import cv2
import numpy as np
import math

img = cv2.imread('image.png')
hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
# filtering red area of hue
redHueArea = 15
redRange = ((hsv[:, :, 0] + 360 + redHueArea) % 360)
hsv[np.where((2 * redHueArea) > redRange)] = [0, 0, 0]
# filtering by saturation
hsv[np.where(hsv[:, :, 1] < 95)] = [0, 0, 0]
# convert to rgb
rgb = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
# select only red grayscaled channel with low threshold
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
gray = cv2.threshold(gray, 15, 255, cv2.THRESH_BINARY)[1]
# contours processing
(_, contours, _) = cv2.findContours(gray.copy(), cv2.RETR_LIST, 1)
for c in contours:
    area = cv2.contourArea(c)
    if area < 8: continue
    epsilon = 0.1 * cv2.arcLength(c, True) # tricky smoothing to a single line
    approx = cv2.approxPolyDP(c, epsilon, True)
    cv2.drawContours(img, [approx], -1, [255, 255, 255], -1)

cv2.imshow('result', img)
cv2.waitKey(0)

In your case it's work perfectly, but, as i already said, you will need to do much more work with contours.


问:
Unable to push my Angular code into Github
I am new person for github,i try to upload angular project into github but only angular-cli code is created,i can not push my entire worked code,Thanks in advance.
After complete push operation it shows "untracked files: nothing added to commit but untracked files present" error</p>

答:
you need to do these steps</p>

```<code>1. git add .
2. git commit -m "your commit name"
3. git push origin master
</code>```

Body:
you need to do these steps

1. git add .
2. git commit -m "your commit name"
3. git push origin master


问:
Difference between {$_GET['id']} and '".$_GET['id']."'?
Is the any difference between writing

```
{$_GET['id']}
```

and

'".$_GET['id']."'

in a sql statement? both works the same

答:
If you use a variable - especially an associative array - in a string, you can be quite sure that it will lead to errors. It's just bad style.
I - personally - don't like the second alternative either.

```<code>sprintf( '... %d ...', $_GET[ 'id' ] );
</code>```

That's my favorite way of putting a variable into a string.

OwnerDisplayName: Bartek

LastEditorDisplayName: Ross

Body:
Is the any difference between writing

{$_GET['id']}

and

'".$_GET['id']."'

in a sql statement? both works the same

Body:
If you use a variable - especially an associative array - in a string, you can be quite sure that it will lead to errors. It's just bad style.
I - personally - don't like the second alternative either.

sprintf( '... %d ...', $_GET[ 'id' ] );

That's my favorite way of putting a variable into a string.

OwnerDisplayName: okoman


问:
How to draw a line with repeated shapes/markers in canvas?
I'm looking for a way to lines with markers in a <canvas> element, like the picture bellow.

In SVG we can do that thanks the markers but I haven't found a similar way to do that with canvas. I know that we can create patterns in canvas thanks to the createPattern function but I doubt it could help to solve the issue.

EDIT: This is not a duplicate of this question since I'm looking for a way to repeat a shape/marker on a path. It's not about placing marker at a specific given point.

As I've commented bellow, I've discovered the svg-path-properties which is almost perfect for my solution.

答:
There is unfortunately no native way to add markers to strokes in the canvas API. Even if we are able to set strokeStyle to a CanvasPattern, there is no way to make this pattern follow our path's direction.

This means that you'll have to make the calculations of the direction and position of your markers yourself...

For this, you can refer to many posts, like this one proposed by Tomàs Antunes in comments.

However, to do the exact triangle shape you shown to us, I've got an non-mathy hack, which doesn't work very well, but that I'd like to share anyway.

Strokes can have dash-arrays, which will create gaps in the stroke.

By offsetting multiple times this dash-array, and decreasing the lineWidth of our stroke, we can sort-of create these arrow shapes :

var ctx = c.getContext('2d');
// our default path
ctx.beginPath();
ctx.moveTo(50, 20);
ctx.bezierCurveTo(230, 30, 150, 60, 50, 100);
ctx.bezierCurveTo(250, 50, 150, 60, 150, 150);
ctx.stroke();
// the hack
for (var i = 0; i < 9; i += .5) {
  // set an dasharray of 1px visible, then 40 invisible
  ctx.setLineDash([1, 49]);
  // offset the dash-array by one px
  ctx.lineDashOffset = i;
  // reduce the width of our stroke
  ctx.lineWidth = i;
  ctx.stroke();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="c"></canvas></code>```

But the main caveat of this method (apart from requiring to redraw the same path 20 times) is that it will really follow the path, and that in angles, it may not completely look like our triangle shape anymore.

var ctx = c.getContext('2d');
// our default path
ctx.beginPath();
ctx.moveTo(50, 20);
ctx.bezierCurveTo(230, 30, 150, 60, 50, 100);
ctx.stroke();
// the hack
for (var i = 0; i < 9; i += .5) {
  // set an dasharray of 1px visible, then 20 invisible
  ctx.setLineDash([1, 14]);
  // offset the dash-array by one px
  ctx.lineDashOffset = i;
  // reduce the width of our stroke
  ctx.lineWidth = i*2;
  ctx.stroke();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="c"></canvas></code>```

Body:
There is unfortunately no native way to add markers to strokes in the canvas API. Even if we are able to set strokeStyle to a CanvasPattern, there is no way to make this pattern follow our path's direction.

This means that you'll have to make the calculations of the direction and position of your markers yourself...

For this, you can refer to many posts, like this one proposed by Tomàs Antunes in comments.

However, to do the exact triangle shape you shown to us, I've got an non-mathy hack, which doesn't work very well, but that I'd like to share anyway.

Strokes can have dash-arrays, which will create gaps in the stroke.

By offsetting multiple times this dash-array, and decreasing the lineWidth of our stroke, we can sort-of create these arrow shapes :

var ctx = c.getContext('2d');
// our default path
ctx.beginPath();
ctx.moveTo(50, 20);
ctx.bezierCurveTo(230, 30, 150, 60, 50, 100);
ctx.bezierCurveTo(250, 50, 150, 60, 150, 150);
ctx.stroke();
// the hack
for (var i = 0; i < 9; i += .5) {
  // set an dasharray of 1px visible, then 40 invisible
  ctx.setLineDash([1, 49]);
  // offset the dash-array by one px
  ctx.lineDashOffset = i;
  // reduce the width of our stroke
  ctx.lineWidth = i;
  ctx.stroke();
}

<canvas id="c"></canvas>

But the main caveat of this method (apart from requiring to redraw the same path 20 times) is that it will really follow the path, and that in angles, it may not completely look like our triangle shape anymore.

var ctx = c.getContext('2d');
// our default path
ctx.beginPath();
ctx.moveTo(50, 20);
ctx.bezierCurveTo(230, 30, 150, 60, 50, 100);
ctx.stroke();
// the hack
for (var i = 0; i < 9; i += .5) {
  // set an dasharray of 1px visible, then 20 invisible
  ctx.setLineDash([1, 14]);
  // offset the dash-array by one px
  ctx.lineDashOffset = i;
  // reduce the width of our stroke
  ctx.lineWidth = i*2;
  ctx.stroke();
}

<canvas id="c"></canvas>


问:
Remove increment and decrement icon from input field
I have a input as follows:

```<code><input id="phone_area_code" maxlength="3" type="number" class="ember-view ember-text-field">
</code>```

Upon rendering, it automatically adds the increment and decrement buttons as shown below. And because of this, the maxLength doesn't work (eg: if input is 999 and I click increment, it allows 1000)

I tried the following answer:

https://stackoverflow.com/a/22306944

But, no use. How to get rid of these buttons?

答:
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
  -webkit-appearance: none;
}

input[type=number] {
  -moz-appearance: textfield;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" min="1" max="10" value="1"></code>```

Body:
I have a input as follows:

<input id="phone_area_code" maxlength="3" type="number" class="ember-view ember-text-field">

Upon rendering, it automatically adds the increment and decrement buttons as shown below. And because of this, the maxLength doesn't work (eg: if input is 999 and I click increment, it allows 1000)

I tried the following answer:

https://stackoverflow.com/a/22306944

But, no use. How to get rid of these buttons?

Body:
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
  -webkit-appearance: none;
}

input[type=number] {
  -moz-appearance: textfield;
}

<input type="number" min="1" max="10" value="1">


问:
Way to get all alphabetic chars in an array in PHP?
Is there a way to get all alphabetic chars (A-Z) in an array in PHP so I can loop through them and display them?</p>

答:
Lower Case Letters

```<code>for ($x = 97; $x < 122; $x++) {
    $y = chr($x);
    echo $y;
    echo "<br>";
}
</code>```

Upper Case Letters

```<code>for ($x = 65; $x < 90; $x++) {
    $y = chr($x);
    echo $y;
    echo "<br>";
}
</code>```

OwnerDisplayName: Click Upvote

LastEditorDisplayName: Paul Dixon

Body:
Lower Case Letters

for ($x = 97; $x < 122; $x++) {
    $y = chr($x);
    echo $y;
    echo "<br>";
}

Upper Case Letters

for ($x = 65; $x < 90; $x++) {
    $y = chr($x);
    echo $y;
    echo "<br>";
}


问:
Find the area of a rectangle using OpenCV
I have 8 points of a polygon that are given in image below:

I want to find out the area of this shape using OpenCV Java

Here is the current code I'm trying:

```<code>Mat temp_mat=new Mat();
List<MatOfPoint> temp_contour=new ArrayList();
temp_contour.add(new MatOfPoint(new Point(w1,w2),new Point(x1,x2),new Point(y1,y2),new Point(z1,z2)));
Imgproc.drawContours(temp_mat,temp_contour,0,new Scalar(255,0,0));
double contourArea = Imgproc.contourArea(temp_contour.get(0));
</code>```

But the contourArea value is returned as empty

I found some reference code for OpenCV Python, as follows:

```<code>import numpy
import cv2

contours = [numpy.array([[1,1],[10,50],[50,50]], dtype=numpy.int32) , numpy.array([[99,99],[99,60],[60,99]], dtype=numpy.int32)]

drawing = numpy.zeros([100, 100],numpy.uint8)
for cnt in contours:
    cv2.drawContours(drawing,[cnt],0,(255,255,255),2)

cv2.imshow('output',drawing)
cv2.waitKey(0)
</code>```

Unfortunately, I was unable to convert it into Java. How would I go about finding the area of this shape?

答:
Calculating the area of the polygon has nothing to do with OpenCV and can in fact be done without the library...

Assuming you have a polygon of 4 points P1 until P4

then the area can be calculated as

Body:
I have 8 points of a polygon that are given in image below:

I want to find out the area of this shape using OpenCV Java

Here is the current code I'm trying:

Mat temp_mat=new Mat();
List<MatOfPoint> temp_contour=new ArrayList();
temp_contour.add(new MatOfPoint(new Point(w1,w2),new Point(x1,x2),new Point(y1,y2),new Point(z1,z2)));
Imgproc.drawContours(temp_mat,temp_contour,0,new Scalar(255,0,0));
double contourArea = Imgproc.contourArea(temp_contour.get(0));

But the contourArea value is returned as empty

I found some reference code for OpenCV Python, as follows:

import numpy
import cv2

contours = [numpy.array([[1,1],[10,50],[50,50]], dtype=numpy.int32) , numpy.array([[99,99],[99,60],[60,99]], dtype=numpy.int32)]

drawing = numpy.zeros([100, 100],numpy.uint8)
for cnt in contours:
    cv2.drawContours(drawing,[cnt],0,(255,255,255),2)

cv2.imshow('output',drawing)
cv2.waitKey(0)

Unfortunately, I was unable to convert it into Java. How would I go about finding the area of this shape?


答:
```<code> <script>
    var elem = document.getElementById("tfa_78");
    var tfa78 = elem.options[elem.selectedIndex].value;
    if (tfa78 == "karte") {
        document.getElementById('tfa_2448').innerHTML = '<b>Bei karte anrufen.</b> <br>';
    } else {
        document.getElementById('tfa_2448').innerHTML = 'Test';
    }

    </script>
</code>```

Title: How to use a dropdown value as a if function


问:
limit imput length to max 10 chars
I try to limit a form of input to 10 chars

var max_chars = 10;

$('input#ctl00$bc$custom_element_44').keydown( function(e){
    if ($(this).val().length >= max_chars) {
        $(this).val($(this).val().substr(0, max_chars));
    }
});

$('input#ctl00$bc$custom_element_44').keyup( function(e){
    if ($(this).val().length >= max_chars) {
        $(this).val($(this).val().substr(0, max_chars));
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input name="ctl00$bc$custom_element_44" type="text" id="ctl00_bc_custom_element_44"></code>```

But it does not seem to work, advice is sought;)

Regards Pete

答:
Simplest approach, vanilla JavaScript. JSFiddle.

JS:

```<code>let name = document.getElementById('name');

name.addEventListener('keyup', () => {
    if (name.value.length > 10) {
        name.value = name.value.slice(0, 10);
    }
})
</code>```

HTML:

```<code><input type="text" id="name">
</code>```

Title: limit imput length to max 10 chars

Body:
I try to limit a form of input to 10 chars

var max_chars = 10;

$('input#ctl00$bc$custom_element_44').keydown( function(e){
    if ($(this).val().length >= max_chars) {
        $(this).val($(this).val().substr(0, max_chars));
    }
});

$('input#ctl00$bc$custom_element_44').keyup( function(e){
    if ($(this).val().length >= max_chars) {
        $(this).val($(this).val().substr(0, max_chars));
    }
});

<input name="ctl00$bc$custom_element_44" type="text" id="ctl00_bc_custom_element_44">

But it does not seem to work, advice is sought;)

Regards Pete

Body:
Simplest approach, vanilla JavaScript. JSFiddle.

JS:

let name = document.getElementById('name');

name.addEventListener('keyup', () => {
    if (name.value.length > 10) {
        name.value = name.value.slice(0, 10);
    }
})

HTML:

<input type="text" id="name">


问:
Pass PDF result to another web api in ASP.NET Core
I have a web api which retrieves PDF file stored in database.

```<code>[HttpGet("file/{id}")]
public IActionResult GetFile(int id)
{
    var file = dataAccess.GetFileFromDB(id);

    HttpContext.Response.ContentType = "application/pdf";
    FileContentResult result = new FileContentResult(file, "application/pdf")
    {
        FileDownloadName = "test.pdf"
    };

    return result;
}
</code>```

I need to write a wrapper web api which will pass result from the above web api to the client.

What is the best way to achieve this using .NET Core? should I return byte array from the above web api and  convert byte array to FileContentResult in the wrapper api?

Any code sample would be very helpful.

Thanks.

答:
You may try to just reroute the response from an HttpClient to the user:

```<code>using System.Net.Http;
using Microsoft.AspNetCore.Mvc;

public class TestController : Controller
{
    public async Task<IActionResult> Get()
    {
        using (var client = new HttpClient())
        {
            var response = await client.GetAsync("http://apiaddress", HttpCompletionOption.ResponseHeadersRead); // this ensures the response body is not buffered

            using (var stream = await response.Content.ReadAsStreamAsync())
            {
                return File(stream, "application/pdf");
            }
        }
    }
}
</code>```

Body:
I have a web api which retrieves PDF file stored in database.

[HttpGet("file/{id}")]
public IActionResult GetFile(int id)
{
    var file = dataAccess.GetFileFromDB(id);

    HttpContext.Response.ContentType = "application/pdf";
    FileContentResult result = new FileContentResult(file, "application/pdf")
    {
        FileDownloadName = "test.pdf"
    };

    return result;
}

I need to write a wrapper web api which will pass result from the above web api to the client.

What is the best way to achieve this using .NET Core? should I return byte array from the above web api and  convert byte array to FileContentResult in the wrapper api?

Any code sample would be very helpful.

Thanks.

Body:
You may try to just reroute the response from an HttpClient to the user:

using System.Net.Http;
using Microsoft.AspNetCore.Mvc;

public class TestController : Controller
{
    public async Task<IActionResult> Get()
    {
        using (var client = new HttpClient())
        {
            var response = await client.GetAsync("http://apiaddress", HttpCompletionOption.ResponseHeadersRead); // this ensures the response body is not buffered

            using (var stream = await response.Content.ReadAsStreamAsync())
            {
                return File(stream, "application/pdf");
            }
        }
    }
}


问:
Generate back stack for deep linking from an email URL
I basically try to mix these two tutorials:

deep linking from notification with back stack

deep linking from url

What I want to do is to launch a specific activity of my app when the user click on a url in an email. When the activity is launched I want the user to be able to press back and to go to the parent activity like if the user had land on this page following the normal journey throw the app.

I know how to open the specific activity but I don't know how to generate the backstack. In the example they are able to manage the backstack as the deep linking comes from a notification generated by the app itself, so they can create a pending intent. In my case the link is from an email so I can't do that.

Any idea?

答:
Create activity without content view for handling incoming intents. This RouterActivity handles intents and decides what activities should be started with startActivities (TaskStackBuilder) after that it finishes itself with finish().

RouterActivity should use theme: @android:style/Theme.NoDisplay (use Activity instead of AppCompatActivity) and should not set any content view
 so user will have no clue that there was any activity started before desired one.


问:
Can't restore SQL Server database to another server
I'm trying to migrate databases from an old, dying server, to the new one.

All over the internet, I found two handy scripts by Andrew Morgan, for saving and restoring databases. The backup part works well; I get my db.bak on my local pc by sharing the folder over the network and having the script backup the db to the unc path.

Unfortunately, the restoring part won't work, and I don't know why (and my senior DEV doesn't know either, and he's the one knowing SQL aorund here).

I'm calling it this way:

```<code>Restore-SQLdatabase -SQLServer "NEWSERVER\MSSQLSERVER" -SQLDatabase "DBToMigrate" -Path "C:\Backup\DBToMigrate.bak" -SQLusername "sa" -SQLpassword "IMAPLAINTEXTPASSWORD"
</code>```

sa has complete power over the database.

It fails with the following message:

Attempting to connect to the Specified SQL server: Success

  WARNUNG: An Exception was caught while restoring the database!

  WARNUNG: Ausnahme beim Aufrufen von "ExecuteNonQuery" mit 0 Argument(en):  "Incorrect syntax near '‘'.

  Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon."

  WARNUNG: attempting to recover the database

The part in question is:

```<code>ALTER DATABASE $SQLDatabase
SET SINGLE_USER WITH ROLLBACK IMMEDIATE

RESTORE DATABASE $SQLDatabase
FROM DISK = '$path'
WITH REPLACE
</code>```

When it gets executed, the scipt gets the exception.

I tried putting a CREATE DATABASE $SQLDatabase in front of the ALTER part, but then it says something along the lines of "that database name already exists", after creating that db.

Also, when omitting the altering part and changing that part to

```<code>RESTORE DATABASE $SQLDatabase FROM DISK = '$path' WITH REPLACE
</code>```

It says something about the database files, giving me the path on the old server (which I'd like to be completely irrelevant, but it seems there may be my next problem), cannot be found (of course, since I'm on my local machine now, which doesn't have those).

I'm doing it with a script, because there are around 15 databases we need to migrate, and also because I want to learn how to do this stuff without just using the SSMS wizard.

Update: I changed the apostrophes to normal ones, that was indeed the mistake. Now I just need to get the file name of the db files so I can MOVE them to the new server.

答:
All you need is to write a new destinations to your files, you can check the syntax of RESTORE here: RESTORE Statements (Transact-SQL)

And your code will be like this:

```<code>RESTORE DATABASE AdventureWorks2012
   FROM AdventureWorksBackups
   WITH MOVE 'AdventureWorks2012_Data' TO
'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Data\NewAdvWorks.mdf',
      MOVE 'AdventureWorks2012_Log'
TO 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Data\NewAdvWorks.ldf';
</code>```

Body:
I'm trying to migrate databases from an old, dying server, to the new one.

All over the internet, I found two handy scripts by Andrew Morgan, for saving and restoring databases. The backup part works well; I get my db.bak on my local pc by sharing the folder over the network and having the script backup the db to the unc path.

Unfortunately, the restoring part won't work, and I don't know why (and my senior DEV doesn't know either, and he's the one knowing SQL aorund here).

I'm calling it this way:

Restore-SQLdatabase -SQLServer "NEWSERVER\MSSQLSERVER" -SQLDatabase "DBToMigrate" -Path "C:\Backup\DBToMigrate.bak" -SQLusername "sa" -SQLpassword "IMAPLAINTEXTPASSWORD"

sa has complete power over the database.

It fails with the following message:

Attempting to connect to the Specified SQL server: Success

  WARNUNG: An Exception was caught while restoring the database!

  WARNUNG: Ausnahme beim Aufrufen von "ExecuteNonQuery" mit 0 Argument(en):  "Incorrect syntax near '‘'.

  Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon."

  WARNUNG: attempting to recover the database

The part in question is:

ALTER DATABASE $SQLDatabase
SET SINGLE_USER WITH ROLLBACK IMMEDIATE

RESTORE DATABASE $SQLDatabase
FROM DISK = '$path'
WITH REPLACE

When it gets executed, the scipt gets the exception.

I tried putting a CREATE DATABASE $SQLDatabase in front of the ALTER part, but then it says something along the lines of "that database name already exists", after creating that db.

Also, when omitting the altering part and changing that part to

RESTORE DATABASE $SQLDatabase FROM DISK = '$path' WITH REPLACE

It says something about the database files, giving me the path on the old server (which I'd like to be completely irrelevant, but it seems there may be my next problem), cannot be found (of course, since I'm on my local machine now, which doesn't have those).

I'm doing it with a script, because there are around 15 databases we need to migrate, and also because I want to learn how to do this stuff without just using the SSMS wizard.

Update: I changed the apostrophes to normal ones, that was indeed the mistake. Now I just need to get the file name of the db files so I can MOVE them to the new server.

Body:
All you need is to write a new destinations to your files, you can check the syntax of RESTORE here: RESTORE Statements (Transact-SQL)

And your code will be like this:

RESTORE DATABASE AdventureWorks2012
   FROM AdventureWorksBackups
   WITH MOVE 'AdventureWorks2012_Data' TO
'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Data\NewAdvWorks.mdf',
      MOVE 'AdventureWorks2012_Log'
TO 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Data\NewAdvWorks.ldf';