问:
getView() is not called in custom list adapter?
This is my homepage.xml - where list view is placed:

```<code>  <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/background"
        android:orientation="vertical"
        tools:context="com.andapps.azaz.e_recommender.HomePage">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Select Category:"
        android:textStyle="bold|italic"
        android:layout_marginLeft="15sp"
        android:layout_marginRight="14sp"
        android:textColor="@color/textColor"
        />
    <Spinner
        android:id="@+id/spcategorieshomepage"
        android:layout_width="match_parent"
        android:layout_height="35sp"
        android:layout_marginRight="14sp"
        android:spinnerMode="dropdown"
        android:textColor="@color/textColor"
        >

   </Spinner>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:id="@+id/llhome"
        android:gravity="center"
        android:layout_marginLeft="15sp"
        android:layout_marginRight="14sp">

        <ListView
            android:id="@+id/listView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >

        </ListView>

    </LinearLayout>

</LinearLayout>
</code>```

And also my customlist.xml:

```<code> <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Product ID:"
        android:textStyle="bold|italic"
        android:layout_marginLeft="15sp"
        android:layout_marginRight="14sp"
        android:textColor="@color/textColor"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold|italic"
        android:layout_marginLeft="15sp"
        android:layout_marginRight="14sp"
        android:textColor="@color/textColor"
        android:id="@+id/tvproductid"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Product Name:"
        android:textStyle="bold|italic"
        android:layout_marginLeft="15sp"
        android:layout_marginRight="14sp"
        android:textColor="@color/textColor"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold|italic"
        android:layout_marginLeft="15sp"
        android:layout_marginRight="14sp"
        android:textColor="@color/textColor"
        android:id="@+id/tvproductname"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Product Rating:"
        android:textStyle="bold|italic"
        android:layout_marginLeft="15sp"
        android:layout_marginRight="14sp"
        android:textColor="@color/textColor"
        />

    <RatingBar
        android:id="@+id/ratingBar"
        style="?android:attr/ratingBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15sp"
        android:layout_marginRight="14sp"
        android:max="5"
        android:numStars="5" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold|italic"
        android:layout_marginLeft="15sp"
        android:layout_marginRight="14sp"
        android:textColor="@color/textColor"
        android:id="@+id/tvproductdesc"
        />
    <ImageView
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:id="@+id/imageView"
        android:layout_marginLeft="15sp"
        android:layout_marginRight="14sp"
        />

</LinearLayout>
</code>```

My homepage.java contains code which is using AsyncTask to consume REST API and fill arrays of data and send it to customAdapter.java

```<code>protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_page);
        lv=(ListView) findViewById(R.id.listView);

        Bundle emailbundle=getIntent().getExtras();
        email=emailbundle.get("email").toString();
        initializer();

        addingItemstoSpinner();

    }

protected void onPostExecute(String result) {

            try {
                jsonArray = new JSONArray(result);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            len= jsonArray.length();
            pdLoading.dismiss();
            if (len != 0) {
                try {

                    String [] productIDListArr= new String[len];
                    String [] productNameListArr= new String[len];
                    String [] productDescListArr= new String[len];
                    String [] productImagesArr= new String[len];
                    String [] productStarsArr= new String[len];
                    for (int i=0;i<len;i++)
                    {
                        objectInArray = jsonArray.getJSONObject(i);

                        productIDListArr[i]=(objectInArray.getString("productId"));
                        productNameListArr[i]=(objectInArray.getString("productName"));
                        productDescListArr[i]=(objectInArray.getString("stars"));
                        productImagesArr[i]=(objectInArray.getString("productId"));
                        productStarsArr[i]=(objectInArray.getString("stars")+" out of 5");

                        if(i==len-1)
                        {
                            createdAt=objectInArray.getString("createdAt");
                        }

                    }
                    lv.setAdapter(new CustomAdapter(HomePage.this, productIDListArr,productNameListArr,productDescListArr,productImagesArr,productStarsArr,email));

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(getApplicationContext(), "Server is down please try again later", Toast.LENGTH_LONG).show();
            }
</code>```

My customAdapter.java is

```<code>package com.andapps.azaz.e_recommender;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

/**
 * Created by M.Azaz on 30-Mar-17.
 */
public class CustomAdapter extends BaseAdapter {
    String [] productIDListArr,productNameListArr,productDescListArr,productImagesArr,productStarsArr;
    Context context;
    String email;
    private static LayoutInflater inflater=null;

    public CustomAdapter(HomePage homePage, String[] productIDList, String[] productNameList, String[] productDescList, String[] productImages, String[] productStars,String emailMain) {
        // TODO Auto-generated constructor stub
        productIDListArr=productIDList;
        productNameListArr=productNameList;
        productDescListArr=productDescList;
        productImagesArr=productImages;
        productStarsArr=productStars;
        context=homePage;
        email=emailMain;
        inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return productIDListArr.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return productIDListArr[position];
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public class Holder
    {
        TextView tvproductname, tvproductid, tvproductdesc;
        ImageView imageView;
        RatingBar ratingBar;
    }
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        Holder holder=new Holder();
        View rowView;
        rowView = inflater.inflate(R.layout.activity_custom_list, null);
        holder.tvproductname=(TextView) rowView.findViewById(R.id.tvproductname);
        holder.tvproductid=(TextView) rowView.findViewById(R.id.tvproductid);
        holder.tvproductdesc=(TextView) rowView.findViewById(R.id.tvproductdesc);
        holder.imageView=(ImageView) rowView.findViewById(R.id.imageView);
        holder.ratingBar=(RatingBar) rowView.findViewById(R.id.ratingBar);

        holder.tvproductname.setText(productNameListArr[position]);
        holder.tvproductid.setText(productIDListArr[position]);
        holder.tvproductdesc.setText(productDescListArr[position]);
        holder.ratingBar.setRating(Integer.parseInt(productStarsArr[position]));
        Picasso.with(context).load(context.getString(R.string.imageip) + productImagesArr[position]+".jpg").into(holder.imageView);
        rowView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(context, "You Clicked "+productIDListArr[position], Toast.LENGTH_LONG).show();
                Intent intent = new Intent("com.andapps.azaz.e_recommender.RATINGS");
                intent.putExtra("tag",productIDListArr[position]);
                intent.putExtra("email", email);
                context.startActivity(intent);
            }
        });
        return rowView;
    }

}
</code>```

But when I run the code, it actually calls customAdapter.java but right after calling getCount() from customAdapter Its not calling getView and the application terminates.

One more thing... how can I update more items into existing list?

答:
You app may crash in getCount method when productIDListArr is null. So add if condition in your getCount method before returning count.

For example :

```<code>  public int getCount(){
    if(productIDListArr==null){
     return 0;
     }else{
     return  productIDListArr.length;
      }
   }
</code>```

Tips : Create a class for holding your response data and pass the list of that model class to the adapter and each time when there is any change in your data update that list and call notify method of adapter.

For example :

```<code>     Class Item{
            public String productIDListArr;
            public String productNameListArr;
            public String productDescListArr;
            public String productImagesArr;
            public String productStarsArr;
         }

   ArrayList<Item> items=new ArrayList<Item>();
     for (int i=0;i<len;i++)
       {
        objectInArray = jsonArray.getJSONObject(i);
        Item item=new Item();
        item.productIDListArr=(objectInArray.getString("productId"));
        .......
       }

CustomAdapter extend BaseAdapter{
ArrayList<Item> items;
public CustomAdapter(ArrayList<Item> items){
 this.items=items;
 }
public int getCount(){
return items==null?0:items.size()
}
</code>```

Body:
This is my homepage.xml - where list view is placed:

  <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/background"
        android:orientation="vertical"
        tools:context="com.andapps.azaz.e_recommender.HomePage">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Select Category:"
        android:textStyle="bold|italic"
        android:layout_marginLeft="15sp"
        android:layout_marginRight="14sp"
        android:textColor="@color/textColor"
        />
    <Spinner
        android:id="@+id/spcategorieshomepage"
        android:layout_width="match_parent"
        android:layout_height="35sp"
        android:layout_marginRight="14sp"
        android:spinnerMode="dropdown"
        android:textColor="@color/textColor"
        >

   </Spinner>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:id="@+id/llhome"
        android:gravity="center"
        android:layout_marginLeft="15sp"
        android:layout_marginRight="14sp">

        <ListView
            android:id="@+id/listView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >

        </ListView>

    </LinearLayout>

</LinearLayout>

And also my customlist.xml:

 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Product ID:"
        android:textStyle="bold|italic"
        android:layout_marginLeft="15sp"
        android:layout_marginRight="14sp"
        android:textColor="@color/textColor"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold|italic"
        android:layout_marginLeft="15sp"
        android:layout_marginRight="14sp"
        android:textColor="@color/textColor"
        android:id="@+id/tvproductid"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Product Name:"
        android:textStyle="bold|italic"
        android:layout_marginLeft="15sp"
        android:layout_marginRight="14sp"
        android:textColor="@color/textColor"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold|italic"
        android:layout_marginLeft="15sp"
        android:layout_marginRight="14sp"
        android:textColor="@color/textColor"
        android:id="@+id/tvproductname"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Product Rating:"
        android:textStyle="bold|italic"
        android:layout_marginLeft="15sp"
        android:layout_marginRight="14sp"
        android:textColor="@color/textColor"
        />

    <RatingBar
        android:id="@+id/ratingBar"
        style="?android:attr/ratingBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15sp"
        android:layout_marginRight="14sp"
        android:max="5"
        android:numStars="5" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold|italic"
        android:layout_marginLeft="15sp"
        android:layout_marginRight="14sp"
        android:textColor="@color/textColor"
        android:id="@+id/tvproductdesc"
        />
    <ImageView
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:id="@+id/imageView"
        android:layout_marginLeft="15sp"
        android:layout_marginRight="14sp"
        />

</LinearLayout>

My homepage.java contains code which is using AsyncTask to consume REST API and fill arrays of data and send it to customAdapter.java

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_page);
        lv=(ListView) findViewById(R.id.listView);

        Bundle emailbundle=getIntent().getExtras();
        email=emailbundle.get("email").toString();
        initializer();

        addingItemstoSpinner();

    }

protected void onPostExecute(String result) {

            try {
                jsonArray = new JSONArray(result);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            len= jsonArray.length();
            pdLoading.dismiss();
            if (len != 0) {
                try {

                    String [] productIDListArr= new String[len];
                    String [] productNameListArr= new String[len];
                    String [] productDescListArr= new String[len];
                    String [] productImagesArr= new String[len];
                    String [] productStarsArr= new String[len];
                    for (int i=0;i<len;i++)
                    {
                        objectInArray = jsonArray.getJSONObject(i);

                        productIDListArr[i]=(objectInArray.getString("productId"));
                        productNameListArr[i]=(objectInArray.getString("productName"));
                        productDescListArr[i]=(objectInArray.getString("stars"));
                        productImagesArr[i]=(objectInArray.getString("productId"));
                        productStarsArr[i]=(objectInArray.getString("stars")+" out of 5");

                        if(i==len-1)
                        {
                            createdAt=objectInArray.getString("createdAt");
                        }

                    }
                    lv.setAdapter(new CustomAdapter(HomePage.this, productIDListArr,productNameListArr,productDescListArr,productImagesArr,productStarsArr,email));

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(getApplicationContext(), "Server is down please try again later", Toast.LENGTH_LONG).show();
            }

My customAdapter.java is

package com.andapps.azaz.e_recommender;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

/**
 * Created by M.Azaz on 30-Mar-17.
 */
public class CustomAdapter extends BaseAdapter {
    String [] productIDListArr,productNameListArr,productDescListArr,productImagesArr,productStarsArr;
    Context context;
    String email;
    private static LayoutInflater inflater=null;

    public CustomAdapter(HomePage homePage, String[] productIDList, String[] productNameList, String[] productDescList, String[] productImages, String[] productStars,String emailMain) {
        // TODO Auto-generated constructor stub
        productIDListArr=productIDList;
        productNameListArr=productNameList;
        productDescListArr=productDescList;
        productImagesArr=productImages;
        productStarsArr=productStars;
        context=homePage;
        email=emailMain;
        inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return productIDListArr.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return productIDListArr[position];
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public class Holder
    {
        TextView tvproductname, tvproductid, tvproductdesc;
        ImageView imageView;
        RatingBar ratingBar;
    }
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        Holder holder=new Holder();
        View rowView;
        rowView = inflater.inflate(R.layout.activity_custom_list, null);
        holder.tvproductname=(TextView) rowView.findViewById(R.id.tvproductname);
        holder.tvproductid=(TextView) rowView.findViewById(R.id.tvproductid);
        holder.tvproductdesc=(TextView) rowView.findViewById(R.id.tvproductdesc);
        holder.imageView=(ImageView) rowView.findViewById(R.id.imageView);
        holder.ratingBar=(RatingBar) rowView.findViewById(R.id.ratingBar);

        holder.tvproductname.setText(productNameListArr[position]);
        holder.tvproductid.setText(productIDListArr[position]);
        holder.tvproductdesc.setText(productDescListArr[position]);
        holder.ratingBar.setRating(Integer.parseInt(productStarsArr[position]));
        Picasso.with(context).load(context.getString(R.string.imageip) + productImagesArr[position]+".jpg").into(holder.imageView);
        rowView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(context, "You Clicked "+productIDListArr[position], Toast.LENGTH_LONG).show();
                Intent intent = new Intent("com.andapps.azaz.e_recommender.RATINGS");
                intent.putExtra("tag",productIDListArr[position]);
                intent.putExtra("email", email);
                context.startActivity(intent);
            }
        });
        return rowView;
    }

}

But when I run the code, it actually calls customAdapter.java but right after calling getCount() from customAdapter Its not calling getView and the application terminates.

One more thing... how can I update more items into existing list?

Body:
You app may crash in getCount method when productIDListArr is null. So add if condition in your getCount method before returning count.

For example :

  public int getCount(){
    if(productIDListArr==null){
     return 0;
     }else{
     return  productIDListArr.length;
      }
   }

Tips : Create a class for holding your response data and pass the list of that model class to the adapter and each time when there is any change in your data update that list and call notify method of adapter.

For example :

     Class Item{
            public String productIDListArr;
            public String productNameListArr;
            public String productDescListArr;
            public String productImagesArr;
            public String productStarsArr;
         }

   ArrayList<Item> items=new ArrayList<Item>();
     for (int i=0;i<len;i++)
       {
        objectInArray = jsonArray.getJSONObject(i);
        Item item=new Item();
        item.productIDListArr=(objectInArray.getString("productId"));
        .......
       }

CustomAdapter extend BaseAdapter{
ArrayList<Item> items;
public CustomAdapter(ArrayList<Item> items){
 this.items=items;
 }
public int getCount(){
return items==null?0:items.size()
}


来源: stackexchange

问:
Restcomm on Tomcat Click2CallAsync User Registration
I managed to start Restcomm on Tomcat and can see what supposed to be there at both 127.0.0.1:8080 and 127.0.0.1:8080/Click2CallAsync. At Click2CallAsync page, it asks me to register at least two users but I don't seem to be able to do that. I follow the steps exactly as it is told at Restcomm SIP Servlets User Guide
but I still can't see my users. I also tried two additional softphones other than Linphone but still the same. What am I supposed to do, how do I establish a SIP Servlet connection and make calls?</p>

答: Did you try reloading the page just in case ? This app has not been updated in a while. If that still doesn't work can you share DEBUG logs ?</p>

ContentLicense: CC BY-SA 3.0


问:
Can anyone tell me the Working of this scripts
matrix

1 2 3

4 5 6

1 8 9

awk '{for (i=1;i<=NF+1-NR;i++) printf "%s%s",$i,FS; print""}' matrix

1 2 3

4 5

7

awk '{for (i=1;i<=NF;i++) if (NR>=1 && NR==i) {for (j=1;j<=i-1;j++) printf " ";print $(i-0)}}' matrix

1

```<code> 2

   3

     4
</code>```

答:
NF , store the number of field in a record. From your matrix each line have 3 element, so NF is 3.

NR gives you the total number of records being processed or line number, it is a dynamic variable value change from 1-3 reference to your matrix.

You should have a look and research on awk command. http://www.thegeekstuff.com/2010/01/8-powerful-awk-built-in-variables-fs-ofs-rs-ors-nr-nf-filename-fnr/?ref=binfind.com/web

Body:
matrix

1 2 3

4 5 6

1 8 9

awk '{for (i=1;i<=NF+1-NR;i++) printf "%s%s",$i,FS; print""}' matrix

1 2 3

4 5

7

awk '{for (i=1;i<=NF;i++) if (NR>=1 && NR==i) {for (j=1;j<=i-1;j++) printf " ";print $(i-0)}}' matrix

1

 2

   3

     4


问:
Laravel middleware doesn't store the session value
I try to put my language in session(), but when I check session: dd(session()->get('locale')); - it's null. I have no idea why. I need to store that value in session.

my middleware:

```<code>class LangSwitch {
...
public function handle(Request $request, Closure $next)
        if(!session()->has('locale')){
            $locale = $request->segment(1);
            session()->put('locale', $locale);
        }
        else{
            $locale = session()->get('locale');
        }

        if (!array_key_exists($locale, Config::get('app.locales'))) {
            $segments = $request->segments();
            $segments[0] = Config::get('app.fallback_locale');

            return redirect()->to(implode('/', $segments));
        }

        App::setlocale($locale);

        return $next($request);
    }
}
</code>```

my kernel:

```<code>protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \App\Http\Middleware\LangSwitch::class,
    ],
</code>```

答:
let's try this

it will work

```<code>\Session::save();
</code>```

Whenever you want to save the modification so lets say I want to store the language of the user

```<code>\Session::put('lang','en');
\Session::save();
</code>```

Body:
I try to put my language in session(), but when I check session: dd(session()->get('locale')); - it's null. I have no idea why. I need to store that value in session.

my middleware:

class LangSwitch {
...
public function handle(Request $request, Closure $next)
        if(!session()->has('locale')){
            $locale = $request->segment(1);
            session()->put('locale', $locale);
        }
        else{
            $locale = session()->get('locale');
        }

        if (!array_key_exists($locale, Config::get('app.locales'))) {
            $segments = $request->segments();
            $segments[0] = Config::get('app.fallback_locale');

            return redirect()->to(implode('/', $segments));
        }

        App::setlocale($locale);

        return $next($request);
    }
}

my kernel:

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \App\Http\Middleware\LangSwitch::class,
    ],

Body:
let's try this

it will work

\Session::save();

Whenever you want to save the modification so lets say I want to store the language of the user

\Session::put('lang','en');
\Session::save();


问:
Is there a C# equivalent to access-modifier regions in C++
It's possible to declare variables with the below structure in C++

```<code>private:
public:
protected:
    float bla1;
    float bla2;
    float bla3;
</code>```

Is there an equivalent in C#? It seems rather tedious having to repeat yourself;

```<code>protected float bla1;
protected float bla2;
protected float bla3;
</code>```

答:
No there is no equivalent in C# (VB and F# as well).

Personally I love this difference.  I work in a very large C++ code base and there is no way to look at a particular method and know it's particular accessibility.  Some of the classes have gotten so large that it takes a significant amount of page scrolling just to see the modifier.

Some coders may think that's not to bad but consider what happens when people start mixing in #if defs in the middle of the class and adding modifiers within those #if's.  It makes determining the access modifier during a code review a non-trivial operation.

It's a small typing sacrifice to add the modifier inline but worth it in terms of long term readability.

OwnerDisplayName: Adam Naylor

Body:
It's possible to declare variables with the below structure in C++

private:
public:
protected:
    float bla1;
    float bla2;
    float bla3;

Is there an equivalent in C#? It seems rather tedious having to repeat yourself;

protected float bla1;
protected float bla2;
protected float bla3;

OwnerDisplayName: JaredPar

ContentLicense: CC BY-SA 2.5


问:
Is it ok to still use tables?

Possible Duplicate:

  Why not use tables for layout in HTML?

Just wondering, I thought I have read before that it is bad to use tables, so my question is, is it still acceptable to use tables in development?

答:
If you have a lot of tabular data, it makes sense to use tables.
Example: Suppose, you want to display a list of baseball players and their batting averages. </p>

Title: Is it ok to still use tables?


问:
error while running python command on ubuntu terminal
bash: /home/asif/anaconda/bin/python: No such file or directory

i am getting this error while running python command on ubuntu terminal

答:
try to check python is installed or not, and check which version of python you are using,</p>

```<code>$ which python
</code>```

Body:
try to check python is installed or not, and check which version of python you are using,

$ which python


问:
Task keeps waiting for activation
I trying to use an API using Microsoft.Http. I followed the samples giving here http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client, but my task does not complete, keeps in status WaitingForActivation

Login button:

```<code>    private void btnLogin_Click(object sender, EventArgs e) {
        try {
            var t = Api.LoginAsync( tbUsername.Text, tbPassword.Text);
            t.Wait();
            _Token = t.Result;
        }
        catch (Exception ex) {
            ShowError(ex.Message);
        }
    }
</code>```

Api class

```<code>static class Api {
    private const string URLBase = "http://localhost:28929/";

    public static async Task<string> LoginAsync(string Username, string Password ) {
        using (var client = new HttpClient()) {
            client.BaseAddress = new Uri(URLBase);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // HTTP POST
            var VM = new Usuario() { Username = Username, Password = Password};
            HttpResponseMessage response = await client.PostAsJsonAsync("api/login", VM);
            if (response.IsSuccessStatusCode) {
                return await response.Content.ReadAsAsync<string>();
            }
            else {
                throw new ApplicationException("No se pudo ingresar. Error: " + response.StatusCode.ToString());
            }
        }
    }
}
</code>```

答:
You can try bypass this using:

```<code>private void btnLogin_Click(object sender, EventArgs e) {
    try {
        var task= Task.Run(async () =>
                   {
                       return await Api.LoginAsync( tbUsername.Text, tbPassword.Text);
                   });
         _Token  = task.Result;
    }
    catch (Exception ex) {
        ShowError(ex.Message);
    }
}
</code>```

Im not recomend it, but in some cases can help.

Title: Task keeps waiting for activation

Body:
I trying to use an API using Microsoft.Http. I followed the samples giving here http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client, but my task does not complete, keeps in status WaitingForActivation

Login button:

    private void btnLogin_Click(object sender, EventArgs e) {
        try {
            var t = Api.LoginAsync( tbUsername.Text, tbPassword.Text);
            t.Wait();
            _Token = t.Result;
        }
        catch (Exception ex) {
            ShowError(ex.Message);
        }
    }

Api class

static class Api {
    private const string URLBase = "http://localhost:28929/";

    public static async Task<string> LoginAsync(string Username, string Password ) {
        using (var client = new HttpClient()) {
            client.BaseAddress = new Uri(URLBase);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // HTTP POST
            var VM = new Usuario() { Username = Username, Password = Password};
            HttpResponseMessage response = await client.PostAsJsonAsync("api/login", VM);
            if (response.IsSuccessStatusCode) {
                return await response.Content.ReadAsAsync<string>();
            }
            else {
                throw new ApplicationException("No se pudo ingresar. Error: " + response.StatusCode.ToString());
            }
        }
    }
}

Body:
You can try bypass this using:

private void btnLogin_Click(object sender, EventArgs e) {
    try {
        var task= Task.Run(async () =>
                   {
                       return await Api.LoginAsync( tbUsername.Text, tbPassword.Text);
                   });
         _Token  = task.Result;
    }
    catch (Exception ex) {
        ShowError(ex.Message);
    }
}

Im not recomend it, but in some cases can help.


问:
Find the words do not appear in the dictionary in linux platform
Here's the text maybe have some words ,each line has one word.and I accept it as a command line arguments. For example the textile a.txt is like:

```<code>about
catb
west
eastren
</code>```

And what I want to do is to find the words do not in the dictionary, if the words are dictionary words, delete it in the textfile.
I use the following commands:

```<code>word=$1
grep "$1$" /usr/share/dict/linux.words -q
for word in $(<a.txt)
do
  if [ $word -eq 0 ]
  then
    sed '/$word/d'
  fi
done
</code>```

Nothing Happened.

答:
grep alone is enough from what I understand

```<code>$ grep -xvFf /usr/share/dict/linux.words a.txt
catb
eastren
</code>```

catb and eastren are words not found in /usr/share/dict/linux.words. The options used are

```<code>   -x, --line-regexp
          Select only those matches that exactly match the whole line.  For a regular expression pattern, this is
          like parenthesizing the pattern and then surrounding it with ^ and $.

   -v, --invert-match
          Invert the sense of matching, to select non-matching lines.

   -F, --fixed-strings
          Interpret PATTERN as a list of fixed strings (instead of regular expressions), separated  by  newlines,
          any of which is to be matched.

   -f FILE, --file=FILE
          Obtain patterns from FILE, one per line.  If this option is used multiple times or is combined with the
          -e  (--regexp)  option,  search  for  all  patterns  given.  The empty file contains zero patterns, and
          therefore matches nothing.
</code>```

Body:
Here's the text maybe have some words ,each line has one word.and I accept it as a command line arguments. For example the textile a.txt is like:

about
catb
west
eastren

And what I want to do is to find the words do not in the dictionary, if the words are dictionary words, delete it in the textfile.
I use the following commands:

word=$1
grep "$1$" /usr/share/dict/linux.words -q
for word in $(<a.txt)
do
  if [ $word -eq 0 ]
  then
    sed '/$word/d'
  fi
done

Nothing Happened.

Body:
grep alone is enough from what I understand

$ grep -xvFf /usr/share/dict/linux.words a.txt
catb
eastren

catb and eastren are words not found in /usr/share/dict/linux.words. The options used are

   -x, --line-regexp
          Select only those matches that exactly match the whole line.  For a regular expression pattern, this is
          like parenthesizing the pattern and then surrounding it with ^ and $.

   -v, --invert-match
          Invert the sense of matching, to select non-matching lines.

   -F, --fixed-strings
          Interpret PATTERN as a list of fixed strings (instead of regular expressions), separated  by  newlines,
          any of which is to be matched.

   -f FILE, --file=FILE
          Obtain patterns from FILE, one per line.  If this option is used multiple times or is combined with the
          -e  (--regexp)  option,  search  for  all  patterns  given.  The empty file contains zero patterns, and
          therefore matches nothing.


问:
Spring Async is blocking and prevents nested async calls
Can anybody tell my is there a way of using the Spring Framework's @Async annotation without blocking / waiting on the result? Here is some code to clarify my question:

```<code>@Service
public class AsyncServiceA {

    @Autowired
    private AsyncServiceB asyncServiceB;

    @Async
    public CompletableFuture<String> a() {
        ThreadUtil.silentSleep(1000);
        return asyncServiceB.b();
    }
}

@Service
public class AsyncServiceB {

    @Async
    public CompletableFuture<String> b() {
        ThreadUtil.silentSleep(1000);
        return CompletableFuture.completedFuture("Yeah, I come from another thread.");
    }
}
</code>```

and the configuration:

```<code>@SpringBootApplication
@EnableAsync
public class Application implements AsyncConfigurer {

    private static final Log LOG = LogFactory.getLog(Application.class);

    private static final int THREAD_POOL_SIZE = 1;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return args -> {
            final AsyncServiceA bean = ctx.getBean(AsyncServiceA.class);
            bean.a().whenComplete(LOG::info);
        };
    }

    @Override
    @Bean(destroyMethod = "shutdown")
    public ThreadPoolTaskExecutor getAsyncExecutor() {
        final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(THREAD_POOL_SIZE);
        executor.setMaxPoolSize(THREAD_POOL_SIZE);
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        // omitted
    }
}
</code>```

When I run the application the executor goes through calling AsyncServiceA.a() and leaves, but it still holds the thread from the pool waiting on the CompletableFuture.get() method. Since there is just a single thread in the pool the AsyncServiceB.b() cannot be executed. What I'm expecting is that thread to be returned to the pool after it executes the AsyncServiceA.a() and then be available to execute the AsyncServiceB.b().

Is there a way to do that?

Note 1: I've tried with ListenableFuture also but the result is the same.

Note 2: I've successfully did it manually (without the @Async) by giving the executor to each method like so:

AsyncServiceA

```<code>public CompletableFuture<String> manualA(Executor executor) {
    return CompletableFuture.runAsync(() -> {
        LOG.info("manualA() working...");
        ThreadUtil.silentSleep(1000);
    }, executor)
            .thenCompose(x -> asyncServiceB.manualB(executor));
}
</code>```

AsyncServiceB

```<code>public CompletableFuture<String> manualB(Executor executor) {
    return CompletableFuture.runAsync(() -> {
        LOG.info("manualB() working...");
        ThreadUtil.silentSleep(1000);
    }, executor)
            .thenCompose(x -> CompletableFuture
                    .supplyAsync(() -> "Yeah, I come from another thread.", executor));
}
</code>```

Here is the ThreadUtil if someone was wondering.

```<code>public class ThreadUtil {

    public static void silentSleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
</code>```

Update: Added issue for non-blocking Async annotation https://jira.spring.io/browse/SPR-15401

答:
The @Async support has been part of Spring since Spring 3.0 which was way before the existence of Java8 (or 7 for that matter). Although support has been added for CompletableFutures in later versions it still is to be used for simple async execution of a method call. (The initial implementation reflects/shows the call).

For composing callbacks and operate non blocking the async support was never designed or intended to.

For non blocking support you would want to wait for Spring 5 with its reactive/non-blocking core, next to that you can always submit a ticket for non-blocking support in the async support.

Body:
Can anybody tell my is there a way of using the Spring Framework's @Async annotation without blocking / waiting on the result? Here is some code to clarify my question:

@Service
public class AsyncServiceA {

    @Autowired
    private AsyncServiceB asyncServiceB;

    @Async
    public CompletableFuture<String> a() {
        ThreadUtil.silentSleep(1000);
        return asyncServiceB.b();
    }
}

@Service
public class AsyncServiceB {

    @Async
    public CompletableFuture<String> b() {
        ThreadUtil.silentSleep(1000);
        return CompletableFuture.completedFuture("Yeah, I come from another thread.");
    }
}

and the configuration:

@SpringBootApplication
@EnableAsync
public class Application implements AsyncConfigurer {

    private static final Log LOG = LogFactory.getLog(Application.class);

    private static final int THREAD_POOL_SIZE = 1;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return args -> {
            final AsyncServiceA bean = ctx.getBean(AsyncServiceA.class);
            bean.a().whenComplete(LOG::info);
        };
    }

    @Override
    @Bean(destroyMethod = "shutdown")
    public ThreadPoolTaskExecutor getAsyncExecutor() {
        final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(THREAD_POOL_SIZE);
        executor.setMaxPoolSize(THREAD_POOL_SIZE);
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        // omitted
    }
}

When I run the application the executor goes through calling AsyncServiceA.a() and leaves, but it still holds the thread from the pool waiting on the CompletableFuture.get() method. Since there is just a single thread in the pool the AsyncServiceB.b() cannot be executed. What I'm expecting is that thread to be returned to the pool after it executes the AsyncServiceA.a() and then be available to execute the AsyncServiceB.b().

Is there a way to do that?

Note 1: I've tried with ListenableFuture also but the result is the same.

Note 2: I've successfully did it manually (without the @Async) by giving the executor to each method like so:

AsyncServiceA

public CompletableFuture<String> manualA(Executor executor) {
    return CompletableFuture.runAsync(() -> {
        LOG.info("manualA() working...");
        ThreadUtil.silentSleep(1000);
    }, executor)
            .thenCompose(x -> asyncServiceB.manualB(executor));
}

AsyncServiceB

public CompletableFuture<String> manualB(Executor executor) {
    return CompletableFuture.runAsync(() -> {
        LOG.info("manualB() working...");
        ThreadUtil.silentSleep(1000);
    }, executor)
            .thenCompose(x -> CompletableFuture
                    .supplyAsync(() -> "Yeah, I come from another thread.", executor));
}

Here is the ThreadUtil if someone was wondering.

public class ThreadUtil {

    public static void silentSleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

Update: Added issue for non-blocking Async annotation https://jira.spring.io/browse/SPR-15401


问:
COPY FROM says data violates unique constraint, but it doesn't
Using the COPY utility to import data into Postgres from a .txt file, and it fails and tells me the 2nd value violates the unique index.  But as you can see, it doesn't.

```<code>Re: "I'll just sue you. --Steve Jobs

Re: ?I?ll just sue you.? --Steve Jobs
</code>```

ERROR:  duplicate key value violates unique constraint "subject_subject_key"

  DETAIL:  Key (subject)=(Re: ?I?ll just sue you.? --Steve Jobs) already exists.

How can I get past this and still use COPY FROM (which is handy)?

答:
If your table was empty, then the mentionned key is repeated in a.txt.

You skipped nex line of error which should tell the line number of second occurance, look example:

```<code>t=# create table so38(i int,subject text primary key);
CREATE TABLE
t=# copy so38 from '/var/lib/pgsql93/a.txt';
ERROR:  duplicate key value violates unique constraint "so38_pkey"
DETAIL:  Key (subject)=(Re: ?I?ll just sue you.? --Steve Jobs) already exists.
CONTEXT:  COPY so38, line 2
t=# \! cat /var/lib/pgsql93/a.txt
1       Re: ?I?ll just sue you.? --Steve Jobs
12      Re: ?I?ll just sue you.? --Steve Jobs
9       Re: "I'll just sue you. --Steve Jobs
</code>```

here

CONTEXT:  COPY so38, line 2

would help identifying the problem. It does not tell you the line of first occurrence though. To check lines with duplicates, you can use:

```<code>t=# \! cat -n a.txt | grep 'Re: ?I?ll just sue you.? --Steve Jobs'
     1  1       Re: ?I?ll just sue you.? --Steve Jobs
     2  12      Re: ?I?ll just sue you.? --Steve Jobs
</code>```

here first number is a line number (1 and 2 in my example)

Body:
Using the COPY utility to import data into Postgres from a .txt file, and it fails and tells me the 2nd value violates the unique index.  But as you can see, it doesn't.

Re: "I'll just sue you. --Steve Jobs

Re: ?I?ll just sue you.? --Steve Jobs

ERROR:  duplicate key value violates unique constraint "subject_subject_key"

  DETAIL:  Key (subject)=(Re: ?I?ll just sue you.? --Steve Jobs) already exists.

How can I get past this and still use COPY FROM (which is handy)?

Body:
If your table was empty, then the mentionned key is repeated in a.txt.

You skipped nex line of error which should tell the line number of second occurance, look example:

t=# create table so38(i int,subject text primary key);
CREATE TABLE
t=# copy so38 from '/var/lib/pgsql93/a.txt';
ERROR:  duplicate key value violates unique constraint "so38_pkey"
DETAIL:  Key (subject)=(Re: ?I?ll just sue you.? --Steve Jobs) already exists.
CONTEXT:  COPY so38, line 2
t=# \! cat /var/lib/pgsql93/a.txt
1       Re: ?I?ll just sue you.? --Steve Jobs
12      Re: ?I?ll just sue you.? --Steve Jobs
9       Re: "I'll just sue you. --Steve Jobs

here

CONTEXT:  COPY so38, line 2

would help identifying the problem. It does not tell you the line of first occurrence though. To check lines with duplicates, you can use:

t=# \! cat -n a.txt | grep 'Re: ?I?ll just sue you.? --Steve Jobs'
     1  1       Re: ?I?ll just sue you.? --Steve Jobs
     2  12      Re: ?I?ll just sue you.? --Steve Jobs

here first number is a line number (1 and 2 in my example)


问:
How to handle overlapping button OnTouch Event in Android

I'm working on an android application which have multiple overlapping buttons and i want to perform some action on the touch event of each button(I'm adding these buttons through java code not XML).

Overlapping buttons

```<code>@Override
public boolean onTouchListener(View v, MotionEvent event)
{
    if(MotionEvent.ACTION_MOVE){
       //action to perform
    }
    return true;
}
</code>```

what i want to do is ,as i touch Button 1 and move towards Button 2 and Button 3 respectively without leaving the screen and when my finger comes overs the button 2 then button 2 touch Actions should perform and code should stop executing Button 1 actions.

Currently what happening is, as i touch button 1 and comes over button 2 still code is executing button 1 actions ,and once i leave the screen and touch button 2 or Button 3 actions associated with them starts executing.

i want to perform actions associated with buttons as i touch any button and move over any other button so code should identify the button i'm touching and perform actions associated to that button only.

Please reply if any confusion...

答:
You have to listen and intercept touch events that you are interested in from parent ViewGroup. See here for more details on that.

From documentation of ViewGroup#onInterceptTouchEvent(MotionEvent ev):

Implement this method to intercept all touch screen motion events. This allows you to watch events as they are dispatched to your children, and take ownership of the current gesture at any point.

Body:
I'm working on an android application which have multiple overlapping buttons and i want to perform some action on the touch event of each button(I'm adding these buttons through java code not XML).

Overlapping buttons

@Override
public boolean onTouchListener(View v, MotionEvent event)
{
    if(MotionEvent.ACTION_MOVE){
       //action to perform
    }
    return true;
}

what i want to do is ,as i touch Button 1 and move towards Button 2 and Button 3 respectively without leaving the screen and when my finger comes overs the button 2 then button 2 touch Actions should perform and code should stop executing Button 1 actions.

Currently what happening is, as i touch button 1 and comes over button 2 still code is executing button 1 actions ,and once i leave the screen and touch button 2 or Button 3 actions associated with them starts executing.

i want to perform actions associated with buttons as i touch any button and move over any other button so code should identify the button i'm touching and perform actions associated to that button only.

Please reply if any confusion...


问:
Comments on Overridden method in Java
Should we comment the overridden method or not? If yes, then whether the comment will be a Java Doc or simple comment?</p>

答:
@SimonC's answer explains how the javadoc utility generates "inherited" documentation for overridden methods.

You can also put explicit javadocs in an override method and they will take precedence over the inherited javadocs.  Furthermore, if you put the {@inheritDoc} tag in the override method's explicit javadocs, the inherited comments will be included at that point.

To answer this:

Should we comment the overridden method or not?  If yes, then whether the comment will be a Java Doc or simple comment?

In my opinion, if the override method refines the documented semantics (contract) of the overridden method (or ... heaven forbid ... breaks the contract), then this deserves to be documented in the override method's javadocs.  However, if the differences are merely "implementation details", then simple comments (or no comments) are more appropriate.

(However, the practice of including a "non-javadoc" comment that refers the reader back to the overridden method's javadoc is, IMO, a waste of screen real-estate ... when I am reading the source code.)

Title: Comments on Overridden method in Java


问:
Incorrect syntax near '.'. Sql Server 2008
I'm trying to do a SQL query Join with Function it gives me error this error:

```<code>SELECT *
  FROM Tbl a
  CROSS APPLY V_TBL_STR(a.Number)
</code>```

What can be the error?
Thanks

答:
Try this one</p>

```<code>SELECT *
  FROM Tbl a
  CROSS APPLY (SELECT V_TBL_STR(a.Number))
</code>```

Body:
I'm trying to do a SQL query Join with Function it gives me error this error:

SELECT *
  FROM Tbl a
  CROSS APPLY V_TBL_STR(a.Number)

What can be the error?
Thanks

Body:
Try this one

SELECT *
  FROM Tbl a
  CROSS APPLY (SELECT V_TBL_STR(a.Number))


问:
Find remaining outer rectangles from Rectangle.Intersection
I have an outer rectangle and a rectangle inside. How can I return all remaining rectangle after cut of intersecting rectangle?</p>

答:
The natural way to represent this would be to use the Region class, something like:

```<code>var result = new Region(outer);
result.Exclude(inner);
</code>```

If you really want a list of Rectangle structures, you can look at converting to RectangleFs using GetRegionScans using an identity matrix and then converting them to Rectangles using Ceiling or Floor.

Body:
The natural way to represent this would be to use the Region class, something like:

var result = new Region(outer);
result.Exclude(inner);

If you really want a list of Rectangle structures, you can look at converting to RectangleFs using GetRegionScans using an identity matrix and then converting them to Rectangles using Ceiling or Floor.


问:
Left-align items in a gridview
I can't seem to figure out how to left-align content of my GridView. Any suggestions?

```<code><GridView ItemsSource="{Binding HostedRooms}">
    <GridView.ItemsPanel>
        <ItemsPanelTemplate>
            <ItemsWrapGrid Orientation="Vertical" />
        </ItemsPanelTemplate>
    </GridView.ItemsPanel>

    <GridView.ItemTemplate>
        <DataTemplate>
            <Border BorderBrush="AliceBlue" BorderThickness="0">
                <StackPanel Orientation="Horizontal">
                    <StackPanel Margin="0, 20">
                        <TextBlock Text="{Binding RoomTitle}" TextAlignment="Left" />
                        <TextBlock>
                            <Run Text="Host: " />
                            <Run Text="{Binding Host}" />
                        </TextBlock>
                        <TextBlock>
                            <Run Text="Map: " />
                            <Run Text="{Binding Map}" />
                        </TextBlock>
                        <TextBlock>
                            <Run Text="Slots: " />
                            <Run Text="{Binding ClaimedSlots}" />
                            <Run Text="/" />
                            <Run Text="{Binding TotalSlots}" />
                            <Run Text="Players (" />
                            <Run Text="{Binding NonObservers}" />
                            <Run Text=") " />
                            <Run Text="Observers (" />
                            <Run Text="{Binding Observers}" />
                            <Run Text=") " />
                        </TextBlock>
                    </StackPanel>
                    <GridView ItemsSource="{Binding Players}">
                        <GridView.ItemsPanel>
                            <ItemsPanelTemplate>
                                <ItemsWrapGrid Orientation="Vertical" />
                            </ItemsPanelTemplate>
                        </GridView.ItemsPanel>
                    </GridView>
                </StackPanel>
            </Border>
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>
</code>```

And below is the result that's produced by the code. For whatever reason only the first item is left-aligned, with the remaining ones being centered.

答:
Why you are using a GridView instead of ListView if you have just one Column ?
This happens because your DataTemplate doesn't have a static width. So first GridViewItem has width equal all page width (from your screen), then other have lower grid and have aligment to center.

I suggest to use a ListView and use a ItemContainerStyle :

```<code> <Style TargetType="ListViewItem" x:Key="CustomCartItemsListview">
        <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}" />
        <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}" />
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseHighBrush}" />
        <Setter Property="TabNavigation" Value="Local"/>
        <Setter Property="IsHoldingEnabled" Value="True"/>
        <Setter Property="Padding" Value="12,0,12,0"/>
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="MinWidth" Value="{ThemeResource ListViewItemMinWidth}"/>
        <Setter Property="MinHeight" Value="{ThemeResource ListViewItemMinHeight}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListViewItem">
                    <ListViewItemPresenter
          ContentTransitions="{TemplateBinding ContentTransitions}"
          SelectionCheckMarkVisualEnabled="True"
          CheckBrush="{ThemeResource SystemControlForegroundBaseMediumHighBrush}"
          CheckBoxBrush="{ThemeResource SystemControlForegroundBaseMediumHighBrush}"
          DragBackground="{ThemeResource SystemControlHighlightListLowBrush}"
          DragForeground="{ThemeResource ListViewItemDragForegroundThemeBrush}"
          FocusBorderBrush="{ThemeResource SystemControlForegroundAltHighBrush}"
          FocusSecondaryBorderBrush="{ThemeResource SystemControlForegroundBaseHighBrush}"
          PlaceholderBackground="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}"
          PointerOverBackground="{ThemeResource SystemControlHighlightListLowBrush}"
          PointerOverForeground="{ThemeResource SystemControlHighlightAltBaseHighBrush}"
          SelectedBackground="{ThemeResource SystemControlHighlightListLowBrush}"
          SelectedForeground="{ThemeResource SystemControlHighlightAltBaseHighBrush}"
          SelectedPointerOverBackground="{ThemeResource SystemControlHighlightListLowBrush}"
          PressedBackground="{ThemeResource SystemControlHighlightListMediumBrush}"
          SelectedPressedBackground="{ThemeResource SystemControlHighlightListLowBrush}"
          DisabledOpacity="{ThemeResource ListViewItemDisabledThemeOpacity}"
          DragOpacity="{ThemeResource ListViewItemDragThemeOpacity}"
          ReorderHintOffset="{ThemeResource ListViewItemReorderHintThemeOffset}"
          HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
          VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
          ContentMargin="{TemplateBinding Padding}"
          CheckMode="Inline"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</code>```

Then you need to use it like this :

```<code> <ListView ItemContainerStyle="{StaticResource CustomCartItemsListview}">
  </ListView>
</code>```

Title: Left-align items in a gridview

Body:
I can't seem to figure out how to left-align content of my GridView. Any suggestions?

<GridView ItemsSource="{Binding HostedRooms}">
    <GridView.ItemsPanel>
        <ItemsPanelTemplate>
            <ItemsWrapGrid Orientation="Vertical" />
        </ItemsPanelTemplate>
    </GridView.ItemsPanel>

    <GridView.ItemTemplate>
        <DataTemplate>
            <Border BorderBrush="AliceBlue" BorderThickness="0">
                <StackPanel Orientation="Horizontal">
                    <StackPanel Margin="0, 20">
                        <TextBlock Text="{Binding RoomTitle}" TextAlignment="Left" />
                        <TextBlock>
                            <Run Text="Host: " />
                            <Run Text="{Binding Host}" />
                        </TextBlock>
                        <TextBlock>
                            <Run Text="Map: " />
                            <Run Text="{Binding Map}" />
                        </TextBlock>
                        <TextBlock>
                            <Run Text="Slots: " />
                            <Run Text="{Binding ClaimedSlots}" />
                            <Run Text="/" />
                            <Run Text="{Binding TotalSlots}" />
                            <Run Text="Players (" />
                            <Run Text="{Binding NonObservers}" />
                            <Run Text=") " />
                            <Run Text="Observers (" />
                            <Run Text="{Binding Observers}" />
                            <Run Text=") " />
                        </TextBlock>
                    </StackPanel>
                    <GridView ItemsSource="{Binding Players}">
                        <GridView.ItemsPanel>
                            <ItemsPanelTemplate>
                                <ItemsWrapGrid Orientation="Vertical" />
                            </ItemsPanelTemplate>
                        </GridView.ItemsPanel>
                    </GridView>
                </StackPanel>
            </Border>
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>

And below is the result that's produced by the code. For whatever reason only the first item is left-aligned, with the remaining ones being centered.

Body:
Why you are using a GridView instead of ListView if you have just one Column ?
This happens because your DataTemplate doesn't have a static width. So first GridViewItem has width equal all page width (from your screen), then other have lower grid and have aligment to center.

I suggest to use a ListView and use a ItemContainerStyle :

 <Style TargetType="ListViewItem" x:Key="CustomCartItemsListview">
        <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}" />
        <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}" />
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseHighBrush}" />
        <Setter Property="TabNavigation" Value="Local"/>
        <Setter Property="IsHoldingEnabled" Value="True"/>
        <Setter Property="Padding" Value="12,0,12,0"/>
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="MinWidth" Value="{ThemeResource ListViewItemMinWidth}"/>
        <Setter Property="MinHeight" Value="{ThemeResource ListViewItemMinHeight}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListViewItem">
                    <ListViewItemPresenter
          ContentTransitions="{TemplateBinding ContentTransitions}"
          SelectionCheckMarkVisualEnabled="True"
          CheckBrush="{ThemeResource SystemControlForegroundBaseMediumHighBrush}"
          CheckBoxBrush="{ThemeResource SystemControlForegroundBaseMediumHighBrush}"
          DragBackground="{ThemeResource SystemControlHighlightListLowBrush}"
          DragForeground="{ThemeResource ListViewItemDragForegroundThemeBrush}"
          FocusBorderBrush="{ThemeResource SystemControlForegroundAltHighBrush}"
          FocusSecondaryBorderBrush="{ThemeResource SystemControlForegroundBaseHighBrush}"
          PlaceholderBackground="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}"
          PointerOverBackground="{ThemeResource SystemControlHighlightListLowBrush}"
          PointerOverForeground="{ThemeResource SystemControlHighlightAltBaseHighBrush}"
          SelectedBackground="{ThemeResource SystemControlHighlightListLowBrush}"
          SelectedForeground="{ThemeResource SystemControlHighlightAltBaseHighBrush}"
          SelectedPointerOverBackground="{ThemeResource SystemControlHighlightListLowBrush}"
          PressedBackground="{ThemeResource SystemControlHighlightListMediumBrush}"
          SelectedPressedBackground="{ThemeResource SystemControlHighlightListLowBrush}"
          DisabledOpacity="{ThemeResource ListViewItemDisabledThemeOpacity}"
          DragOpacity="{ThemeResource ListViewItemDragThemeOpacity}"
          ReorderHintOffset="{ThemeResource ListViewItemReorderHintThemeOffset}"
          HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
          VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
          ContentMargin="{TemplateBinding Padding}"
          CheckMode="Inline"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Then you need to use it like this :

 <ListView ItemContainerStyle="{StaticResource CustomCartItemsListview}">
  </ListView>


问:
Restcomm GLMC diameter setup
I'm new to diameter protocol. All I want to do is provide a method to our developers to get mobile location using diameter protocol. We are still using map ati over sigtran to request location info, but it's no longer valid since LTE.

I have installed RestComm GLMC
https://github.com/RestComm/gmlc

and configured
jboss-5.1.0.GA/server/default/deploy/restcomm-diameter-mux-1.7.0.sar/config/jdiameter-config.xml as below since I want to connect to HSS.

```<code><?xml version="1.0"?>
<Configuration xmlns="http://www.jdiameter.org/jdiameter-server">

  <LocalPeer>
    <URI value=""aaa://uas.restcomm.org:3868"" />
    <!-- URI value="aaa://restcomm.open-ims.test:1812" /--> <!-- OpenIMS Example -->
    <IPAddresses>
      <IPAddress value="127.0.0.1" />
    </IPAddresses>
    <Realm value="MY_RELM_NAME" />
    <!-- Realm value="open-ims.test" / --> <!-- OpenIMS Example -->
    <VendorID value="193" />
    <ProductName value="jDiameter" />
    <FirmwareRevision value="1" />
    <OverloadMonitor>
      <Entry index="1" lowThreshold="0.5" highThreshold="0.6">
        <ApplicationID>
          <VendorId value="193" />
          <AuthApplId value="0" />
          <AcctApplId value="19302" />
        </ApplicationID>
      </Entry>
    </OverloadMonitor>
  </LocalPeer>

  <Parameters>
    <AcceptUndefinedPeer value="true" />
    <DuplicateProtection value="false" />
    <DuplicateTimer value="240000" />
    <DuplicateSize value="5000" />
    <UseUriAsFqdn value="false" /> <!-- Needed for Ericsson Emulator (set to true) -->
    <QueueSize value="10000" />
    <MessageTimeOut value="60000" />
    <StopTimeOut value="10000" />
    <CeaTimeOut value="10000" />
    <IacTimeOut value="30000" />
    <DwaTimeOut value="10000" />
    <DpaTimeOut value="5000" />
    <RecTimeOut value="10000" />

    <!-- Peer FSM Thread Count Configuration -->
    <PeerFSMThreadCount value="3" />

    <!-- Statistics Configuration -->
    <Statistics pause="30000" delay="30000" enabled="false" active_records="Concurrent,ScheduledExecService,Network,ScheduledExecService,AppGenRequestPerSecond,NetGenRequestPerSecond,Peer,Peer.local,PeerFSM"/>

    <Concurrent>
      <Entity name="ThreadGroup" size="64"/> <!-- Common Thread Pool -->
      <Entity name="ProcessingMessageTimer" size="1"/>
      <Entity name="DuplicationMessageTimer" size="1"/>
      <Entity name="RedirectMessageTimer" size="1"/>
      <Entity name="PeerOverloadTimer" size="1"/>
      <Entity name="ConnectionTimer" size="1"/>
      <Entity name="StatisticTimer" size="1"/>
    </Concurrent>

    <Dictionary enabled="false" sendLevel="MESSAGE" receiveLevel="OFF" />

    <!-- Router Request Table Cache Size and ClearSize -->
    <RequestTable size="10240" clear_size="2048" />

  </Parameters>

  <Network>
    <Peers>
      <!-- Testsuite -->
      <Peer name="aaa://HSS_IP:3868" attempt_connect="true" rating="1" />

      <!-- Ericsson SDK Client -->
      <!-- Peer name="aaa://127.0.0.1:11812" attempt_connect="false" rating="1"/-->

      <!-- Ericsson SDK Emulator -->
      <!-- Peer name="aaa://127.0.0.1:21812" attempt_connect="true" rating="1" /-->

      <!-- Sh / CCA / Cx/Dx -->
      <!-- Peer name="aaa://uac.restcomm.org" attempt_connect="false" rating="1" /-->

      <!-- Sh (OpenIMS) -->
      <!-- Peer name="aaa://hss.open-ims.test" attempt_connect="true" rating="1" /-->
    </Peers>
    <Realms>
      <!-- Ericsson SDK Client/Emulator and Testsuite -->
      <Realm name="MY_RELM_NAME" peers="HSS_IP_1,HSS_IP_2" local_action="LOCAL" dynamic="false" exp_time="1">
        <ApplicationID>
          <VendorId value="193" />
          <AuthApplId value="0" />
          <AcctApplId value="19302" />
        </ApplicationID>
      </Realm>

      <!-- Sh -->
      <!-- Realm name="restcomm.org" peers="127.0.0.1" local_action="LOCAL" dynamic="false" exp_time="1">
        <ApplicationID>
          <VendorId value="10415" />
          <AuthApplId value="16777217" />
          <AcctApplId value="0" />
        </ApplicationID>
      </Realm-->

      <!-- Sh (OpenIMS) -->
      <!-- Realm name="open-ims.test" peers="hss.open-ims.test,restcomm.open-ims.test" local_action="LOCAL" dynamic="false" exp_time="1">
        <ApplicationID>
          <VendorId value="10415" />
          <AuthApplId value="16777217" />
          <AcctApplId value="0" />
        </ApplicationID>
      </Realm-->

      <!--  CCA -->
      <!-- Realm name="restcomm.org" peers="127.0.0.1" local_action="LOCAL" dynamic="false" exp_time="1">
        <ApplicationID>
          <VendorId value="0" />
          <AuthApplId value="4" />
          <AcctApplId value="0" />
        </ApplicationID>
      </Realm -->

      <!-- Cx/Dx -->
      <!-- Realm name="restcomm.org" peers="127.0.0.1" local_action="LOCAL" dynamic="false" exp_time="1">
        <ApplicationID>
          <VendorId value="10415" />
          <AuthApplId value="16777216" />
          <AcctApplId value="0" />
        </ApplicationID>
      </Realm-->
    </Realms>
  </Network>

  <Extensions>
    <!-- To enable clustering uncomment the following lines
    <SessionDatasource value="org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource"/>
    <TimerFacility value="org.mobicents.diameter.impl.ha.timer.ReplicatedTimerFacilityImpl"/>
    -->
  </Extensions>

</Configuration>
</code>```

New I start the jboss server using below command
./run.sh -bMY_IP -Xdebug -Xrunjdwp:transport=dt_socket,address=52297,suspend=n,server=y

After it's started, when I do a curl request curl -X POST http://MY_IP:8080/restcomm/gmlc/rest?msisdn=MY_MSISDN to get location of a specific MSISDN I get below error as a return

<title>JBoss Web/2.1.3.GA - Error report</title>
HTTP Status 501 -

type Status report

message

description The server does not support the functionality needed to fulfill this request ().

JBoss Web/2.1.3.GA
[root@eir1apps ~]#

and below in jboss log

19:07:02,411 WARN  [SccpRoutingControl] (SLEE-EventRouterExecutor-4-thread-1) Received SccpMessage for Translation but no matching Rule found for local routing
SccpMessage=Sccp Msg [Type=-1 networkId=0 sls=1 incomingOpc=-1 incomingDpc=-1 outgoingDpc=-1 CallingAddress(pc=0,ssn=145,AI=18,gt=GlobalTitle0100Impl [digits=628184422892, natureOfAddress=INTERNATIONAL, numberingPlan=ISDN_TELEPHONY, translationType=0, encodingScheme=BCDEvenEncodingScheme[type=BCD_ODD, code=2]]) CalledParty(pc=0,ssn=6,AI=18,gt=GlobalTitle0100Impl [digits=MY_MSISDN, natureOfAddress=INTERNATIONAL, numberingPlan=ISDN_TELEPHONY, translationType=0, encodingScheme=BCDOddEncodingScheme[type=BCD_ODD, code=1]]) DataLen=78]
19:08:02,420 ERROR [MobileCoreNetworkInterfaceSbb] (SLEE-EventRouterExecutor-3-thread-1)
Rx :  onDialogTimeout DialogTimeout [org.mobicents.slee.resource.map.service.mobility.wrappers.MAPDialogMobilityWrapper@3999406a]
19:08:02,420 WARN  [MobileCoreNetworkInterfaceSbb] (SLEE-EventRouterExecutor-3-thread-1) When responding to HTTP no pending HTTP request is found, responseData=DialogTimeout
19:10:56,085 WARN  [SccpRoutingControl] (SLEE-EventRouterExecutor-6-thread-1) Received SccpMessage for Translation but no matching Rule found for local routing
SccpMessage=Sccp Msg [Type=-1 networkId=0 sls=2 incomingOpc=-1 incomingDpc=-1 outgoingDpc=-1 CallingAddress(pc=0,ssn=145,AI=18,gt=GlobalTitle0100Impl [digits=628184422892, natureOfAddress=INTERNATIONAL, numberingPlan=ISDN_TELEPHONY, translationType=0, encodingScheme=BCDEvenEncodingScheme[type=BCD_ODD, code=2]]) CalledParty(pc=0,ssn=6,AI=18,gt=GlobalTitle0100Impl [digits=MY_MSISDN, natureOfAddress=INTERNATIONAL, numberingPlan=ISDN_TELEPHONY, translationType=0, encodingScheme=BCDOddEncodingScheme[type=BCD_ODD, code=1]]) DataLen=78]

Now I'm stuck here. I have no idea if this is a configuration issue or not

答: @ivcode we don't support Diameter in GMLC yet. There is ongoing work on that happening. Would you like to help contribute to the effort ?</p>

Title: Restcomm GLMC diameter setup

Body:
I'm new to diameter protocol. All I want to do is provide a method to our developers to get mobile location using diameter protocol. We are still using map ati over sigtran to request location info, but it's no longer valid since LTE.

I have installed RestComm GLMC
https://github.com/RestComm/gmlc

and configured
jboss-5.1.0.GA/server/default/deploy/restcomm-diameter-mux-1.7.0.sar/config/jdiameter-config.xml as below since I want to connect to HSS.

<?xml version="1.0"?>
<Configuration xmlns="http://www.jdiameter.org/jdiameter-server">

  <LocalPeer>
    <URI value=""aaa://uas.restcomm.org:3868"" />

    <IPAddresses>
      <IPAddress value="127.0.0.1" />
    </IPAddresses>
    <Realm value="MY_RELM_NAME" />

    <VendorID value="193" />
    <ProductName value="jDiameter" />
    <FirmwareRevision value="1" />
    <OverloadMonitor>
      <Entry index="1" lowThreshold="0.5" highThreshold="0.6">
        <ApplicationID>
          <VendorId value="193" />
          <AuthApplId value="0" />
          <AcctApplId value="19302" />
        </ApplicationID>
      </Entry>
    </OverloadMonitor>
  </LocalPeer>

  <Parameters>
    <AcceptUndefinedPeer value="true" />
    <DuplicateProtection value="false" />
    <DuplicateTimer value="240000" />
    <DuplicateSize value="5000" />
    <UseUriAsFqdn value="false" />
    <QueueSize value="10000" />
    <MessageTimeOut value="60000" />
    <StopTimeOut value="10000" />
    <CeaTimeOut value="10000" />
    <IacTimeOut value="30000" />
    <DwaTimeOut value="10000" />
    <DpaTimeOut value="5000" />
    <RecTimeOut value="10000" />

    <PeerFSMThreadCount value="3" />

    <Statistics pause="30000" delay="30000" enabled="false" active_records="Concurrent,ScheduledExecService,Network,ScheduledExecService,AppGenRequestPerSecond,NetGenRequestPerSecond,Peer,Peer.local,PeerFSM"/>

    <Concurrent>
      <Entity name="ThreadGroup" size="64"/>
      <Entity name="ProcessingMessageTimer" size="1"/>
      <Entity name="DuplicationMessageTimer" size="1"/>
      <Entity name="RedirectMessageTimer" size="1"/>
      <Entity name="PeerOverloadTimer" size="1"/>
      <Entity name="ConnectionTimer" size="1"/>
      <Entity name="StatisticTimer" size="1"/>
    </Concurrent>

    <Dictionary enabled="false" sendLevel="MESSAGE" receiveLevel="OFF" />

    <RequestTable size="10240" clear_size="2048" />

  </Parameters>

  <Network>
    <Peers>

      <Peer name="aaa://HSS_IP:3868" attempt_connect="true" rating="1" />

    </Peers>
    <Realms>

      <Realm name="MY_RELM_NAME" peers="HSS_IP_1,HSS_IP_2" local_action="LOCAL" dynamic="false" exp_time="1">
        <ApplicationID>
          <VendorId value="193" />
          <AuthApplId value="0" />
          <AcctApplId value="19302" />
        </ApplicationID>
      </Realm>

    </Realms>
  </Network>

  <Extensions>

  </Extensions>

</Configuration>

New I start the jboss server using below command
./run.sh -bMY_IP -Xdebug -Xrunjdwp:transport=dt_socket,address=52297,suspend=n,server=y

After it's started, when I do a curl request curl -X POST http://MY_IP:8080/restcomm/gmlc/rest?msisdn=MY_MSISDN to get location of a specific MSISDN I get below error as a return

<title>JBoss Web/2.1.3.GA - Error report</title>
HTTP Status 501 -

type Status report

message

description The server does not support the functionality needed to fulfill this request ().

JBoss Web/2.1.3.GA
[root@eir1apps ~]#

and below in jboss log

19:07:02,411 WARN  [SccpRoutingControl] (SLEE-EventRouterExecutor-4-thread-1) Received SccpMessage for Translation but no matching Rule found for local routing
SccpMessage=Sccp Msg [Type=-1 networkId=0 sls=1 incomingOpc=-1 incomingDpc=-1 outgoingDpc=-1 CallingAddress(pc=0,ssn=145,AI=18,gt=GlobalTitle0100Impl [digits=628184422892, natureOfAddress=INTERNATIONAL, numberingPlan=ISDN_TELEPHONY, translationType=0, encodingScheme=BCDEvenEncodingScheme[type=BCD_ODD, code=2]]) CalledParty(pc=0,ssn=6,AI=18,gt=GlobalTitle0100Impl [digits=MY_MSISDN, natureOfAddress=INTERNATIONAL, numberingPlan=ISDN_TELEPHONY, translationType=0, encodingScheme=BCDOddEncodingScheme[type=BCD_ODD, code=1]]) DataLen=78]
19:08:02,420 ERROR [MobileCoreNetworkInterfaceSbb] (SLEE-EventRouterExecutor-3-thread-1)
Rx :  onDialogTimeout DialogTimeout [org.mobicents.slee.resource.map.service.mobility.wrappers.MAPDialogMobilityWrapper@3999406a]
19:08:02,420 WARN  [MobileCoreNetworkInterfaceSbb] (SLEE-EventRouterExecutor-3-thread-1) When responding to HTTP no pending HTTP request is found, responseData=DialogTimeout
19:10:56,085 WARN  [SccpRoutingControl] (SLEE-EventRouterExecutor-6-thread-1) Received SccpMessage for Translation but no matching Rule found for local routing
SccpMessage=Sccp Msg [Type=-1 networkId=0 sls=2 incomingOpc=-1 incomingDpc=-1 outgoingDpc=-1 CallingAddress(pc=0,ssn=145,AI=18,gt=GlobalTitle0100Impl [digits=628184422892, natureOfAddress=INTERNATIONAL, numberingPlan=ISDN_TELEPHONY, translationType=0, encodingScheme=BCDEvenEncodingScheme[type=BCD_ODD, code=2]]) CalledParty(pc=0,ssn=6,AI=18,gt=GlobalTitle0100Impl [digits=MY_MSISDN, natureOfAddress=INTERNATIONAL, numberingPlan=ISDN_TELEPHONY, translationType=0, encodingScheme=BCDOddEncodingScheme[type=BCD_ODD, code=1]]) DataLen=78]

Now I'm stuck here. I have no idea if this is a configuration issue or not


问:
Search a project in SonarQube based on the github Uri
I would like to search for a project's line coverage using the SonarQube Web API.

The entrypoint to my search is the github repository uri.

So something like this: git@github.com:user/my-project.git.

Currently, I am cutting out the repo name and try to find the project using /api/projects/index?search=my-project - assuming that the github repo name should be contained in the sonarqube project name.

I pick up the project key from the response and use it with /api/measures/component to retrieve the overall_line_coverage.

We are using the SonarQube gradle plugin to create the SonarQube project. We also set the sonar.branch property. So we end up with project keys like <groupId>:<artifactId>:<sonar.branch>.

Is there a better/more robust way to do this search - especially I would like to add the sonar.branch to the query the narrow down the search result.

答:
go to your project homepage to get the project key OR use the internal (made public in 6.3) WS api/components/search with the q parameter

use the WS api/measures/component to retrieve your project measure


问:
Delete comment link not working (acts_as_commentable)
In my Rails app, each post has a comment section where users can leave comments. I want each comment to have a delete link but I just can't get it to work. I am using the acts_as_commentable gem here.

posts/show.html.erb

```<code><% @comments.each do |comment| %>
  <p><strong><%= comment.user.username %></strong></p>
  <p class="comment"><%= comment.comment %><p>
  <%= link_to "Delete", [@post, comment], method: :delete %>
<% end %>
</code>```

I need help with this line

```<code><%= link_to("Delete", [@post, comment], method: :delete %>
</code>```

comments_controller.rb

```<code>def create
  @post = Post.find(params[:post_id])
  @comment = @post.comments.create(comment_params)
  @comment.user_id = current_user.id
end

def destroy
  @comment = Comment.find(params[:id])
  redirect_to :back
end
</code>```

Thanks for your help! :)

答:
You are not destroying it at all in the destroy action, you need to add @comment.destroy to delete the comment from database

```<code>def destroy
  @comment = Comment.find(params[:id]
  @comment.destroy # add this line
  redirect_to :back
end
</code>```

Hope that helps!

Body:
In my Rails app, each post has a comment section where users can leave comments. I want each comment to have a delete link but I just can't get it to work. I am using the acts_as_commentable gem here.

posts/show.html.erb

<% @comments.each do |comment| %>

<%= comment.user.username %>

<%= comment.comment %>

  <%= link_to "Delete", [@post, comment], method: :delete %>
<% end %>

I need help with this line

<%= link_to("Delete", [@post, comment], method: :delete %>

comments_controller.rb

def create
  @post = Post.find(params[:post_id])
  @comment = @post.comments.create(comment_params)
  @comment.user_id = current_user.id
end

def destroy
  @comment = Comment.find(params[:id])
  redirect_to :back
end

Thanks for your help! :)

Body:
You are not destroying it at all in the destroy action, you need to add @comment.destroy to delete the comment from database

def destroy
  @comment = Comment.find(params[:id]
  @comment.destroy # add this line
  redirect_to :back
end

Hope that helps!


问:
Reducing repeated information in database design
I am designing an application that when users create a new account, their account is populated with several hundred rows of data (predefined options, settings, etc). Most of the users will rarely, if ever, change the information contained in these tables. Are there any good design patterns to reduce the amount of duplicated data in the database tables?

Some ideas I had so far:

Keep the predefined options in their
own tables, and only save custom
options to the user tables. This
would seem to reduce the overhead,
but I can see the database calls
getting really tricky.

Create a new
database for every 100 users or so,
with a separate database for accounts
that points to the users database.
This is, well, not optimal.

Idea 3?

答:
Creating a new database for 100 users sounds like a crazy and inefficient idea.

How much data are we talking about and why do you want to reduce it? Even if you have millions of users, a few million rows is not a very large table - unless the data for each user is multiple megabytes in size. Well chosen indexing ought to be sufficient to optimise the user table. However, it could make it simpler to modify the default settings for all users if you only store user settings when they change the defaults.


问:
Undefined global variable but showing in view of Angular 2
I am confused with my codes in Angular 2. In my ts file I have:

```<code>    import { Test } from '../../../../models/test';
    import { TestService } from '../../../../services/test.service';
    import { Job} from '../../../../models/job';
    import { JobService } from '../../../../services/job.service';

    export class TestTakeMcComponent implements OnInit {
          company_name: string;
          test: Test;
          job: Job;

          constructor(
            private testService: TestService,
            private jobService: JobService
          ) { }
          ngOnInit() {
            this.getTest();
            this.getJob(this.test.id);
          }
          getTest(){
            this.testService.getById(40).subscribe(
              test => {
               if(test.data.data.length != 0){
                 this.test = test.data.data[0];
               }
              }
            );
          }
         getJob(id: number){
           this.jobService.getJobByTestId(id).subscribe();
         }
    }
</code>```

And in my HTML file I have:

```<code><h3 class="box-title">{{ test?.title }} </h3>
</code>```

Surely, the data binding {{ test?.title }} is working and showing the data. But during the call of another function getJob(this.test.id) on my ts file, it says an undefined parameter.
How this became undefined when it is showing perfectly in the view? I wanted to use the data inside this.test variable to other functions but I cannot since it is undefined.
Please someone has the same issue with me and how did you fix this problem. Thank you.

答:
This is because the console.log() is executed before this.test gets a value assigned. The execution is async, which means it scheduled to run later, while the execution of the sync code continues immediately.

{{ test?.title }} is undefined first but updated later, but the change happens too fast for a human too recognize.

If you move the console.log() you'll see the value

      getTest(){
        this.testService.getById(40).subscribe(
          test => {
           if(test.data.data.length != 0){
             this.test = test.data.data[0];
             console.log(this.test);
           }
          }
        );
      }
```

<p><strong>update</strong></p>

<pre class="lang-ts prettyprint-override"><code>export class TestTakeMcComponent implements OnInit {
      company_name: string;
      test: Test;
      job: Job;

      constructor(
        private testService: TestService,
        private jobService: JobService
      ) { }
      ngOnInit() {
        this.getTest().subscribe(val =>
            this.getJob(this.test.id));
      }
      getTest(){
        // add `return` and replace `subscribe` by `map`
        return this.testService.getById(40).map(
          test => {
           if(test.data.data.length != 0){
             this.test = test.data.data[0];
           }
          }
        );
      }
     getJob(id: number){
       this.jobService.getJobByTestId(id).subscribe();
     }
}
</code>```

Body:
I am confused with my codes in Angular 2. In my ts file I have:

    import { Test } from '../../../../models/test';
    import { TestService } from '../../../../services/test.service';
    import { Job} from '../../../../models/job';
    import { JobService } from '../../../../services/job.service';

    export class TestTakeMcComponent implements OnInit {
          company_name: string;
          test: Test;
          job: Job;

          constructor(
            private testService: TestService,
            private jobService: JobService
          ) { }
          ngOnInit() {
            this.getTest();
            this.getJob(this.test.id);
          }
          getTest(){
            this.testService.getById(40).subscribe(
              test => {
               if(test.data.data.length != 0){
                 this.test = test.data.data[0];
               }
              }
            );
          }
         getJob(id: number){
           this.jobService.getJobByTestId(id).subscribe();
         }
    }

And in my HTML file I have:

{{ test?.title }}

Surely, the data binding {{ test?.title }} is working and showing the data. But during the call of another function getJob(this.test.id) on my ts file, it says an undefined parameter.
How this became undefined when it is showing perfectly in the view? I wanted to use the data inside this.test variable to other functions but I cannot since it is undefined.
Please someone has the same issue with me and how did you fix this problem. Thank you.

Body:
This is because the console.log() is executed before this.test gets a value assigned. The execution is async, which means it scheduled to run later, while the execution of the sync code continues immediately.

{{ test?.title }} is undefined first but updated later, but the change happens too fast for a human too recognize.

If you move the console.log() you'll see the value

      getTest(){
        this.testService.getById(40).subscribe(
          test => {
           if(test.data.data.length != 0){
             this.test = test.data.data[0];
             console.log(this.test);
           }
          }
        );
      }

update

export class TestTakeMcComponent implements OnInit {
      company_name: string;
      test: Test;
      job: Job;

      constructor(
        private testService: TestService,
        private jobService: JobService
      ) { }
      ngOnInit() {
        this.getTest().subscribe(val =>
            this.getJob(this.test.id));
      }
      getTest(){
        // add `return` and replace `subscribe` by `map`
        return this.testService.getById(40).map(
          test => {
           if(test.data.data.length != 0){
             this.test = test.data.data[0];
           }
          }
        );
      }
     getJob(id: number){
       this.jobService.getJobByTestId(id).subscribe();
     }
}


问:
Chef: How to see how cookbook from chef supermarket looks like
I'm new to chef. I'm now learning to get a recipe from the chef supermarket and starting it in a local vagrant box. It works fine but I don't know how my recipe which I'v 'pulled' looks like.

So I've edited metadata.rb inside my cookbook and added:

```<code>depends 'selinux', '~> 0.9'
</code>```

I'm able to go to the chefsupermarket online and read the documentation. But is there wa way to see where the content of this 'pull' is?
In default.rb I set include_recipe 'selinux::permissive' to include it on my next kitchen converge. But I'm following a tutorial and practically everything is going fine. But it's more about the fact to understand it.

How do I know how the cookbook of selinux looks

How do I know how I have to describe the include_recipe statement in
metadata.rb

答: You can click the Download Cookbook button on the right to download an archive of the cookbook or the View Source button to view the code on GitHub (though beware that you are seeing the master branch by default which might not match the latest release).

Body:
I'm new to chef. I'm now learning to get a recipe from the chef supermarket and starting it in a local vagrant box. It works fine but I don't know how my recipe which I'v 'pulled' looks like.

So I've edited metadata.rb inside my cookbook and added:

depends 'selinux', '~> 0.9'

I'm able to go to the chefsupermarket online and read the documentation. But is there wa way to see where the content of this 'pull' is?
In default.rb I set include_recipe 'selinux::permissive' to include it on my next kitchen converge. But I'm following a tutorial and practically everything is going fine. But it's more about the fact to understand it.

How do I know how the cookbook of selinux looks

How do I know how I have to describe the include_recipe statement in
metadata.rb


问:
Angular UI Bootstrap Alert Closable Issue
I am using Angular UI Bootstrap to generate Alert boxes, using the following code:

```<code><alert data-ng-repeat="alert in alerts" type="{{alert.type}}" close="closeAlert($index)">{{alert.msg}}</alert>
</code>```

It renders as expected:

My question is: Is there some way of making some of the notifications closable and others not, depending on a variable?

I have written this mock code and want to display that closable x only when closeable is true.

```<code>$scope.alerts = [
    { type: 'danger', closeable: false, msg: 'Oh snap! Change a few things up and try submitting again.' },
    { type: 'success', closeable: true, msg: 'Well done! You successfully read this important alert message.' },
    { type: 'warning', closeable: false, msg: 'Be careful! Something may go wrong here.' },
    { type: 'info', closeable: true, msg: 'Attention! Here is some news for you.' }
];
</code>```

答:
Angular 2 (Typescript): with two way data bindings.

in template.component.ts

```<code>import {Component, OnInit} from '@angular/core';

@Component({
  selector: 'template-ditor',
  templateUrl: './template.component.html',
})
export class TemplateComponent implements OnInit {
  private content: string;
  // predefined parameters with initial values
  // make it private, invisible to other classes
  private isAlert: boolean = false;
  private alertMsg: string='Alert Message';
  private alertHeading: string = 'Error !'
  private alertTyp: string = 'danger'
  constructor() {}

  // when a form is submitted, display alert with alertHeading, alertMsg, alertTyp
  onSubmit() {
  // pass values and api response messages.
  // passing isAlert=true will show this alert.
    this.showAlert(true, "this is alert message", 'info', 'Info !');
  }
  // default values incase of no parameter is passed
  // passing isAlert=false will hide this alert.
  showAlert(isAlert: boolean=false, alertMsg:string='',
    alertTyp:string='danger', alertHeading:string='Error !'){
    // set
    this.alertMsg = alertMsg;
    this.isAlert = isAlert;
    this.alertTyp = alertTyp;
    this.alertHeading = alertHeading;
  }
  ngOnInit(): void {
  }
}
</code>```

in template.component.html

```<code><div *ngIf="isAlert" class="alert alert-{{ alertTyp? alertTyp : '-' }} alert-block">
  <a class="close" data-dismiss="alert" (click)="showAlert(false)" >×</a>
  <h4 class="alert-heading">{{ alertHeading? alertHeading : '-' }}</h4>
  {{ alertMsg? alertMsg : '-' }}
  <!-- will first check is variable is not empty -->
  <!-- if empty then replace with hyphen -->
  <!-- a good approach to avoid crashes -->
</div>
<div class="">
  <button class="btn btn-primary" type="button" (click)="onSubmit()" >
    Save
  </button>
</div>
</code>```

Body:
I am using Angular UI Bootstrap to generate Alert boxes, using the following code:

<alert data-ng-repeat="alert in alerts" type="{{alert.type}}" close="closeAlert($index)">{{alert.msg}}</alert>

It renders as expected:

My question is: Is there some way of making some of the notifications closable and others not, depending on a variable?

I have written this mock code and want to display that closable x only when closeable is true.

$scope.alerts = [
    { type: 'danger', closeable: false, msg: 'Oh snap! Change a few things up and try submitting again.' },
    { type: 'success', closeable: true, msg: 'Well done! You successfully read this important alert message.' },
    { type: 'warning', closeable: false, msg: 'Be careful! Something may go wrong here.' },
    { type: 'info', closeable: true, msg: 'Attention! Here is some news for you.' }
];

Body:
Angular 2 (Typescript): with two way data bindings.

in template.component.ts

import {Component, OnInit} from '@angular/core';

@Component({
  selector: 'template-ditor',
  templateUrl: './template.component.html',
})
export class TemplateComponent implements OnInit {
  private content: string;
  // predefined parameters with initial values
  // make it private, invisible to other classes
  private isAlert: boolean = false;
  private alertMsg: string='Alert Message';
  private alertHeading: string = 'Error !'
  private alertTyp: string = 'danger'
  constructor() {}

  // when a form is submitted, display alert with alertHeading, alertMsg, alertTyp
  onSubmit() {
  // pass values and api response messages.
  // passing isAlert=true will show this alert.
    this.showAlert(true, "this is alert message", 'info', 'Info !');
  }
  // default values incase of no parameter is passed
  // passing isAlert=false will hide this alert.
  showAlert(isAlert: boolean=false, alertMsg:string='',
    alertTyp:string='danger', alertHeading:string='Error !'){
    // set
    this.alertMsg = alertMsg;
    this.isAlert = isAlert;
    this.alertTyp = alertTyp;
    this.alertHeading = alertHeading;
  }
  ngOnInit(): void {
  }
}

in template.component.html

<div *ngIf="isAlert" class="alert alert-{{ alertTyp? alertTyp : '-' }} alert-block">
  <a class="close" data-dismiss="alert" (click)="showAlert(false)" >&#xD7;</a>
  <h4 class="alert-heading">{{ alertHeading? alertHeading : '-' }}</h4>
  {{ alertMsg? alertMsg : '-' }}
  <!-- will first check is variable is not empty -->
  <!-- if empty then replace with hyphen -->
  <!-- a good approach to avoid crashes -->
</div>
<div class="">
  <button class="btn btn-primary" type="button" (click)="onSubmit()" >
    Save
  </button>
</div>


问:
Quasar - Vertical scrollbar not working on more than 600px width
I'm working with quasar framework and i don't know why the vertical scroll bar in a .vue component is failing depending on the width of the window. It works for less than 600px of width.

home.vue Code:

```<code>    <template>
    <div class="layout-padding">
        <div class="user">
            <p>User Component</p>
            <router-view class="layout-view"></router-view>
        </div>
        <div>
            <i>account_circle</i>
            <p class="bg-red-1">Quasar framework</p>
            <button class="secondary" @click="toggleFullscreen()">
            <i class="on-left">zoom_out_map</i>
            Toggle Fullscreen
            </button>
        </div>

        <div>
            <p>-</p>
            <blockquote>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.</p>
            <small>Someone famous for <cite title="Quasar Framework">Quasar Framework</cite></small>
            </blockquote>
        </div>
    </div>
</template>
</code>```

答:
A root node is required for subroutes so I have to add a div that contains the "layout-padding" div

```<code><template>
    <div> <!-- root node -->
        <div class="layout-padding">
            [Content...]
        </div>
    </div>
</template>
</code>```

I got the solution from quasar documentation:
http://quasar-framework.org/components/layout-overview.html#Understanding-Layouts

Body:
I'm working with quasar framework and i don't know why the vertical scroll bar in a .vue component is failing depending on the width of the window. It works for less than 600px of width.

home.vue Code:

    <template>

User Component

            <router-view class="layout-view"></router-view>

            account_circle

Quasar framework

            <button class="secondary" @click="toggleFullscreen()">
            zoom_out_map
            Toggle Fullscreen
            </button>

-

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.

            Someone famous for Quasar Framework

</template>

Body:
A root node is required for subroutes so I have to add a div that contains the "layout-padding" div

<template>
    <div> <!-- root node -->
        <div class="layout-padding">
            [Content...]
        </div>
    </div>
</template>

I got the solution from quasar documentation:
http://quasar-framework.org/components/layout-overview.html#Understanding-Layouts