问:
How to know if lazy loading worked via hibernate mapping?
I have a Person object with 5 columns and i used following properties:

```<code> property name="firstName" column="FirstName" type="string" lazy="false"
 property name="lastName" column="LastName" type="string" lazy="true"
 property name="city" column="City" type="string" lazy="true"
 property name="country" column="Country" type="string" lazy="true"
 property name="phone" column="Phone" type="string" lazy="true"
</code>```

Now how do i find out if the object i get back using "From Person" contains only rows of data with the FIRSTNAME within it - assuming the other 4 are lazy loaded. I tried debugger but when i dive in i see all values has already been there... is there something missing? thanks

答:
To find out if it's lazy loaded or not without checking the generated sqls you can simply close the session and then access the property.

However, you need further bytecode enhancement to enable this type of behavior. http://docs.jboss.org/hibernate/orm/5.0/manual/en-US/html_single/#performance-fetching-lazyproperties

For instance, after enhancing the bytecode to enable lazy loading of horse (string property) inside Note and running.

```<code>    Criteria criteria = session.createCriteria(Note.class);
    List<Note> list1 = criteria.list();
    session.close();
    String horse = list1.get(0).getHorse();
</code>```

I get

```<code>Caused by: org.hibernate.LazyInitializationException: Unable to perform requested lazy initialization [stackoverflow.Note.horse] - no session and settings disallow loading outside the Session
    at org.hibernate.bytecode.enhance.spi.interceptor.Helper.throwLazyInitializationException(Helper.java:165)
</code>```

Body:
I have a Person object with 5 columns and i used following properties:

 property name="firstName" column="FirstName" type="string" lazy="false"
 property name="lastName" column="LastName" type="string" lazy="true"
 property name="city" column="City" type="string" lazy="true"
 property name="country" column="Country" type="string" lazy="true"
 property name="phone" column="Phone" type="string" lazy="true"

Now how do i find out if the object i get back using "From Person" contains only rows of data with the FIRSTNAME within it - assuming the other 4 are lazy loaded. I tried debugger but when i dive in i see all values has already been there... is there something missing? thanks

Body:
To find out if it's lazy loaded or not without checking the generated sqls you can simply close the session and then access the property.

However, you need further bytecode enhancement to enable this type of behavior. http://docs.jboss.org/hibernate/orm/5.0/manual/en-US/html_single/#performance-fetching-lazyproperties

For instance, after enhancing the bytecode to enable lazy loading of horse (string property) inside Note and running.

    Criteria criteria = session.createCriteria(Note.class);
    List<Note> list1 = criteria.list();
    session.close();
    String horse = list1.get(0).getHorse();

I get

Caused by: org.hibernate.LazyInitializationException: Unable to perform requested lazy initialization [stackoverflow.Note.horse] - no session and settings disallow loading outside the Session
    at org.hibernate.bytecode.enhance.spi.interceptor.Helper.throwLazyInitializationException(Helper.java:165)


来源: stackexchange

问:
What's wrong with this MySQL query and PHP foreach
Please help me learn what is wrong with this PHP / MySQL query.

This is my channels table:

name    url              id      key
BBC2    http://url.com/2 BBC2   2
BBC1    http://url.com/1 BBC1   1
```

<p>This works:</p>

<pre class="lang-PHP prettyprint-override"><code>$getchans = "SELECT * FROM channels";
$channels = mysqli_query($db,$getchans);
foreach ($channels as $channel)
{
    // do stuff
}
</code>```

This does not work:

```<code>$getchans = "SELECT * FROM channels ORDER BY key ASC";
$channels = mysqli_query($db,$getchans);
foreach ($channels as $channel)
{
    // do stuff
}
</code>```

and gives error Warning: Invalid argument supplied for foreach()

Can anyone please tell me why it doesn't work when MySQL query/result  is ordered?

Thank you.

答:
esacepe Key Keyword, refer</p>

```<code>$getchans="SELECT * FROM channels ORDER BY `key` ASC";
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Please help me learn what is wrong with this PHP / MySQL query.

This is my channels table:

name    url              id      key
BBC2    http://url.com/2 BBC2   2
BBC1    http://url.com/1 BBC1   1

This works:

$getchans = "SELECT * FROM channels";
$channels = mysqli_query($db,$getchans);
foreach ($channels as $channel)
{
    // do stuff
}

This does not work:

$getchans = "SELECT * FROM channels ORDER BY key ASC";
$channels = mysqli_query($db,$getchans);
foreach ($channels as $channel)
{
    // do stuff
}

and gives error Warning: Invalid argument supplied for foreach()

Can anyone please tell me why it doesn't work when MySQL query/result  is ordered?

Thank you.

Body:
esacepe Key Keyword, refer

$getchans="SELECT * FROM channels ORDER BY `key` ASC";


问:
Ruby loops style/convention
I'm wondering how I would create the following psuedo-esque code's conventional equivalent in Ruby. I've read quite a bit regarding standard practices but I'm just curious what the generally accepted/cleanest approach to this specific loop structure might be. I haven't come across a direct example.

```<code>for(i = 0, j = 10; i < 10 && j > 0; i++, j--){
  //do something
}
</code>```

Side note:
The intended purpose for this loop structure is to iterate through an array of arrays diagonally, the loop will contain a number of break-ing conditions.

答:
The intended purpose for this loop structure is to iterate through an array of arrays diagonally.

Given a square array of arrays:

```<code>array = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
</code>```

You can traverse it diagonally (from top right to bottom left) via:

```<code>array.each.with_index(1) do |row, i|
  puts row[-i]
end
</code>```

Output:

```<code>3
5
7
</code>```

Or, if you prefer (or need) an index-based approach:

```<code>0.upto(2).zip(2.downto(0)).each do |i, j|
  p i: i, j: j, element: array[i][j]
end
</code>```

Output:

```<code>{:i=>0, :j=>2, :element=>3}
{:i=>1, :j=>1, :element=>5}
{:i=>2, :j=>0, :element=>7}
</code>```

You could also use array.each_index.zip(array.each_index.reverse_each)

Title: Ruby loops style/convention

Body:
I'm wondering how I would create the following psuedo-esque code's conventional equivalent in Ruby. I've read quite a bit regarding standard practices but I'm just curious what the generally accepted/cleanest approach to this specific loop structure might be. I haven't come across a direct example.

for(i = 0, j = 10; i < 10 && j > 0; i++, j--){
  //do something
}

Side note:
The intended purpose for this loop structure is to iterate through an array of arrays diagonally, the loop will contain a number of break-ing conditions.

Body:
The intended purpose for this loop structure is to iterate through an array of arrays diagonally.

Given a square array of arrays:

array = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]

You can traverse it diagonally (from top right to bottom left) via:

array.each.with_index(1) do |row, i|
  puts row[-i]
end

Output:

3
5
7

Or, if you prefer (or need) an index-based approach:

0.upto(2).zip(2.downto(0)).each do |i, j|
  p i: i, j: j, element: array[i][j]
end

Output:

{:i=>0, :j=>2, :element=>3}
{:i=>1, :j=>1, :element=>5}
{:i=>2, :j=>0, :element=>7}

You could also use array.each_index.zip(array.each_index.reverse_each)


问:
Java ';' expected error
I'm struggling for some days with some code. Many tries, see my other questions.  Now they expect a ";" but I don't know why.

```<code>holder.valueLabel.setOnClickListener(view -> {
            if (item.value.equals(""))
                try {
                    String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
                    holder.valueLabel.setText(date);
                    mItems.get(position).value = date;
                    showDatePickerDialog(holder.valueLabel.getText().toString(), (datePicker, year, month, day) -> {
                        String dateInFormat = getDateInFormat(year, month, day);
                        holder.valueLabel.setText(dateInFormat);
                        mItems.get(position).value = dateInFormat;

                        (DialogInterface.BUTTON_NEGATIVE), "cancel", (DialogInterface.OnClickListener) (dialog, which) -> {
                            if (which == DialogInterface.BUTTON_NEGATIVE) {
                                mItems.get(position).value = "";
                            } else {
                                mItems.get(position).value = dateInFormat;
                            }
                            ----->}); <--------------

                    }).show();
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            else {
                try {
                    showDatePickerDialog(holder.valueLabel.getText().toString(), (datePicker, year, month, day) -> {
                        String dateInFormat = getDateInFormat(year, month, day);
                        holder.valueLabel.setText(dateInFormat);
                        mItems.get(position).value = dateInFormat;
                    }).show();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
});
</code>```

ShowDatePickerDialog

```<code>private DatePickerDialog showDatePickerDialog(String date, DatePickerDialog.OnDateSetListener listener) throws ParseException {
    Calendar myCalendar = getDateFromFormat(date);
    return new DatePickerDialog(getContext(), R.style.AppTheme_DialogTheme, listener,
            myCalendar.get(Calendar.YEAR),
            myCalendar.get(Calendar.MONTH),
            myCalendar.get(Calendar.DAY_OF_MONTH)
    );

}
</code>```

答:
You have not properly implement DatePickerDialog methods try below way resolve error what you are getting :</p>

```<code>holder.valueLabel.setOnClickListener(view -> {
            if (item.value.equals(""))
                try {
                    String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
                    holder.valueLabel.setText(date);
                    mItems.get(position).value = date;
                    DatePickerDialog datePickerDialog = showDatePickerDialog(holder.valueLabel.getText().toString(), new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            String dateInFormat = getDateInFormat(year, month, day);
                            holder.valueLabel.setText(dateInFormat);
                            mItems.get(position).value = dateInFormat;
                        }

                    });
                    datePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "cancel", (dialog, which) -> {
                        holder.valueLabel.setText("");
                        mItems.get(position).value = "";
                    });
                    datePickerDialog.show();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            else {
                try {
                    showDatePickerDialog(holder.valueLabel.getText().toString(), (datePicker, year, month, day) -> {
                        String dateInFormat = getDateInFormat(year, month, day);
                        holder.valueLabel.setText(dateInFormat);
                        mItems.get(position).value = dateInFormat;
                    }).show();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        });
</code>```

Title: Java ';' expected error

Body:
I'm struggling for some days with some code. Many tries, see my other questions.  Now they expect a ";" but I don't know why.

holder.valueLabel.setOnClickListener(view -> {
            if (item.value.equals(""))
                try {
                    String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
                    holder.valueLabel.setText(date);
                    mItems.get(position).value = date;
                    showDatePickerDialog(holder.valueLabel.getText().toString(), (datePicker, year, month, day) -> {
                        String dateInFormat = getDateInFormat(year, month, day);
                        holder.valueLabel.setText(dateInFormat);
                        mItems.get(position).value = dateInFormat;

                        (DialogInterface.BUTTON_NEGATIVE), "cancel", (DialogInterface.OnClickListener) (dialog, which) -> {
                            if (which == DialogInterface.BUTTON_NEGATIVE) {
                                mItems.get(position).value = "";
                            } else {
                                mItems.get(position).value = dateInFormat;
                            }
                            ----->}); <--------------

                    }).show();
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            else {
                try {
                    showDatePickerDialog(holder.valueLabel.getText().toString(), (datePicker, year, month, day) -> {
                        String dateInFormat = getDateInFormat(year, month, day);
                        holder.valueLabel.setText(dateInFormat);
                        mItems.get(position).value = dateInFormat;
                    }).show();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
});

ShowDatePickerDialog

private DatePickerDialog showDatePickerDialog(String date, DatePickerDialog.OnDateSetListener listener) throws ParseException {
    Calendar myCalendar = getDateFromFormat(date);
    return new DatePickerDialog(getContext(), R.style.AppTheme_DialogTheme, listener,
            myCalendar.get(Calendar.YEAR),
            myCalendar.get(Calendar.MONTH),
            myCalendar.get(Calendar.DAY_OF_MONTH)
    );

}

Body:
You have not properly implement DatePickerDialog methods try below way resolve error what you are getting :

holder.valueLabel.setOnClickListener(view -> {
            if (item.value.equals(""))
                try {
                    String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
                    holder.valueLabel.setText(date);
                    mItems.get(position).value = date;
                    DatePickerDialog datePickerDialog = showDatePickerDialog(holder.valueLabel.getText().toString(), new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            String dateInFormat = getDateInFormat(year, month, day);
                            holder.valueLabel.setText(dateInFormat);
                            mItems.get(position).value = dateInFormat;
                        }

                    });
                    datePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "cancel", (dialog, which) -> {
                        holder.valueLabel.setText("");
                        mItems.get(position).value = "";
                    });
                    datePickerDialog.show();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            else {
                try {
                    showDatePickerDialog(holder.valueLabel.getText().toString(), (datePicker, year, month, day) -> {
                        String dateInFormat = getDateInFormat(year, month, day);
                        holder.valueLabel.setText(dateInFormat);
                        mItems.get(position).value = dateInFormat;
                    }).show();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        });


问:
Converting string to byte array in C# (CSV)
I wrote a function to convert byte[] to string, and I add ";" after each byte. Now I want to convert this string to byte[] by splitting the string (similar to a CSV string).

```<code>public string ByteArrayToString(byte[] byteArray,string s)
{
    for (int i = 0; i < byteArray.Length; i++)
    {
        s += byteArray[i].ToString() + ";";
    }
    s = s.Substring(0, s.Length - 1);
    return s;
}
</code>```

How could I write a function to convert this string to that byte array again?

答:
try this</p>

```<code>var byteArray = new byte[] {123, 11, 111};
var stringBytes = string.Join(";", byteArray.Select(b => b.ToString()));
var newByteArray = stringBytes.Split(';').Select(s => byte.Parse(s)).ToArray();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I wrote a function to convert byte[] to string, and I add ";" after each byte. Now I want to convert this string to byte[] by splitting the string (similar to a CSV string).

public string ByteArrayToString(byte[] byteArray,string s)
{
    for (int i = 0; i < byteArray.Length; i++)
    {
        s += byteArray[i].ToString() + ";";
    }
    s = s.Substring(0, s.Length - 1);
    return s;
}

How could I write a function to convert this string to that byte array again?

Body:
try this

var byteArray = new byte[] {123, 11, 111};
var stringBytes = string.Join(";", byteArray.Select(b => b.ToString()));
var newByteArray = stringBytes.Split(';').Select(s => byte.Parse(s)).ToArray();


问:
Can't access Google Maps library in script tag from React component
I've been trying to embed a Google Map on my page via React. In my index.html html, I the followng scipr tag in between my  tag

```<code><script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&callback=initMap" async defer></script>
</code>```

I need to create the initMap callback function. I want this callback function to be inside my Map component.

1) How would I connect this callback such that the maps API knows where to find it?

2) To actually create the map, I do it through the google object.

```<code>var map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: -34.397, lng: 150.644},
      scrollwheel: false,
      zoom: 8
    });
</code>```

However, my React component won't compile because it's complaining that the 'google' object doesn't exist -- meaning it's not being exposed to me as it should. Of course when I go to the console, I can access it. It seems like the component either doesn't have access to it (although it should since the objects from script tags become global, right?) or its accessing it before the library is loaded (which I don't know how to fix even though it says "defer" in the script tag).

Any help would be appreciated. My problem is similar to this, but the accepted answer did not work for me.

I also tried this tutorial to no avail...I'm not sure if I'm missing something.

答:
Quick Example

If u want ignore the error, try add global variable in your eslint config

"globals": {
    "google": true
    }

In my example, I remove the callback argument in script tag, I did it in my component.

Hope this can help.

Body:
I've been trying to embed a Google Map on my page via React. In my index.html html, I the followng scipr tag in between my  tag

I need to create the initMap callback function. I want this callback function to be inside my Map component.

1) How would I connect this callback such that the maps API knows where to find it?

2) To actually create the map, I do it through the google object.

var map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: -34.397, lng: 150.644},
      scrollwheel: false,
      zoom: 8
    });

However, my React component won't compile because it's complaining that the 'google' object doesn't exist -- meaning it's not being exposed to me as it should. Of course when I go to the console, I can access it. It seems like the component either doesn't have access to it (although it should since the objects from script tags become global, right?) or its accessing it before the library is loaded (which I don't know how to fix even though it says "defer" in the script tag).

Any help would be appreciated. My problem is similar to this, but the accepted answer did not work for me.

I also tried this tutorial to no avail...I'm not sure if I'm missing something.


问:
Calculate sum of dynamically adding input fields with jquery
I've a form where i am calculating sum of amounts. Rows are dynamically generated with jquery clone();

This code is calculating sum of rendered rows not the new created rows

```<code> $(document).ready(function(){

        $('.datepicker').datepicker();

        var $inst = $('.inst_amount');
            $inst_form = $('.inst_form');
            $total_amount = $('#total_amount');
            $total_price = $('#total_price');
            total = 0;

        $.each($inst, function(index, val) {
            var val = ($(this).val() == "") ? 0 : $(this).val();
            total = total + parseFloat(val);
        });
         $total_price.html(Math.round(total));
         $total_amount.val(Math.round(total));

        $(document).on('blur','.inst_amount', function(){
            var total = 0;
            $.each($inst, function(index, val) {
                var val = ($(this).val() == "") ? 0 : $(this).val();
                total = total + parseFloat(val);
            });
            console.log(total);
            $total_price.html(Math.round(total));
            $total_amount.val(Math.round(total));
        });
});
</code>```

答: This code will only calculate total of all the rows which were available when page was loaded. You need to call the same code to make the total again when you are adding a new row. Basically on click of add row you need to re-calculate.</p>

Body:
I've a form where i am calculating sum of amounts. Rows are dynamically generated with jquery clone();

This code is calculating sum of rendered rows not the new created rows

 $(document).ready(function(){

        $('.datepicker').datepicker();

        var $inst = $('.inst_amount');
            $inst_form = $('.inst_form');
            $total_amount = $('#total_amount');
            $total_price = $('#total_price');
            total = 0;

        $.each($inst, function(index, val) {
            var val = ($(this).val() == "") ? 0 : $(this).val();
            total = total + parseFloat(val);
        });
         $total_price.html(Math.round(total));
         $total_amount.val(Math.round(total));

        $(document).on('blur','.inst_amount', function(){
            var total = 0;
            $.each($inst, function(index, val) {
                var val = ($(this).val() == "") ? 0 : $(this).val();
                total = total + parseFloat(val);
            });
            console.log(total);
            $total_price.html(Math.round(total));
            $total_amount.val(Math.round(total));
        });
});


问:
How would you secure text in iPhone app made in Swift?
Could you tell me how would you secure a text file in iPhone app? Let's say you write a text in the app. I would like it to be secured, so even if you have access to the device you still need to enter a specific pin to be able to display the text. I don't want the text to be available on iCloud, only in the specific app itself. Are there any easy and secure ways to do it? I'm total newbie and I will really appreciate any answer :) Have a nice one!</p>

答:
Encrypt the file before saving it to local file system using single key encryption algorithms. Ask the user to enter the key while decrypting, use the key to decrypt and show it :)

How to do it ?

So when user creates/edits a file, create it in temp folder of your app bundle. Content in this folder is not backed up by iCloud and kept temporarily hence the name temp folder :)

Once he is done with editing it, save it in document directory of your app bundle. But because the content in this file can be viewed using third party apps or can be backed up by iCloud, encrypt it before saving it to local document directory.

Which algorithm to use ?

Depends on your requirement. I don't think you need Private and Public Key encryptions looking at your requirement. You can make use of any single key encryption algorithms. I have used https://github.com/RNCryptor/RNCryptor
and it works pretty well. Try it

Happy coding


问:
Passing Array (not Object) for Auth in Laravel
I've some problem with passing array, please give me some advice so I can solve this matter.

Here is My Controller:

```<code>$keluhan_list=DB::table('keluhans')
->select(DB::raw('id,produk,username,masalah,id_departemen'))
->where('status','=','Proses')->get();
return view('layanankonsumen.lihattindaklanjut',compact('keluhan_list');
</code>```

And this is part of my Blade view:

```<code>@if (Auth::check() && (Auth::user()->level == 'MR' || Auth::user()->level == 'PDD' || Auth::user()->id_departemen ==' @foreach ($keluhan_list as $keluhan) {{$keluhan->id_departemen}} @endforeach' ))
</code>```

It's not error but it's not pass the auth. When I try to replace with Auth::user()->id_departemen == '10' it's working.

答:
One mistake in return view line

```<code>$keluhan_list=DB::table('keluhans')
->select(DB::raw('id,produk,username,masalah,id_departemen'))
->where('status','=','Proses')->get();
return view('layanankonsumen.lihattindaklanjut',compact('keluhan_list'));// add one more braces before semicolon
</code>```

First add this line in your blade

```<code>@foreach ($keluhan_list as $keluhan)
   <?php $id_dept[] = $keluhan->id_departemen; ?>
@endforeach
</code>```

then

```<code>@if (Auth::check() && (Auth::user()->level == 'MR' || Auth::user()->level == 'PDD' || in_array(Auth::user()->id_departemen,$id_dept) ))
</code>```

Body:
I've some problem with passing array, please give me some advice so I can solve this matter.

Here is My Controller:

$keluhan_list=DB::table('keluhans')
->select(DB::raw('id,produk,username,masalah,id_departemen'))
->where('status','=','Proses')->get();
return view('layanankonsumen.lihattindaklanjut',compact('keluhan_list');

And this is part of my Blade view:

@if (Auth::check() && (Auth::user()->level == 'MR' || Auth::user()->level == 'PDD' || Auth::user()->id_departemen ==' @foreach ($keluhan_list as $keluhan) {{$keluhan->id_departemen}} @endforeach' ))

It's not error but it's not pass the auth. When I try to replace with Auth::user()->id_departemen == '10' it's working.

Body:
One mistake in return view line

$keluhan_list=DB::table('keluhans')
->select(DB::raw('id,produk,username,masalah,id_departemen'))
->where('status','=','Proses')->get();
return view('layanankonsumen.lihattindaklanjut',compact('keluhan_list'));// add one more braces before semicolon

First add this line in your blade

@foreach ($keluhan_list as $keluhan)
   <?php $id_dept[] = $keluhan->id_departemen; ?>
@endforeach

then

@if (Auth::check() && (Auth::user()->level == 'MR' || Auth::user()->level == 'PDD' || in_array(Auth::user()->id_departemen,$id_dept) ))


问:
Google Analytics Bloated Data
I manage an internal website and we recently implemented campaign tracking for our emails and homepage links to see where traffic comes from.

I set up the URLs using the Google URL builder.

The data we're receiving is very bloated. We ran a test URL with 8 people, and we received 129 "views", with an average of 9 views per day for over a month. No one clicked this link after the first day.

Our average session times were about 30 minutes, which is very strange.

My questions are:

how does google track campaigns? If you use a tracking URL, does the cookie track views for any organic views after that?

Is there a tool we can use to only track first time visits using a campaign URL?

Admittedly, I'm fairly new to Google Analytics, but no one on our marketing analytics team was able to help.

答:
Since you used the Google URL builder I don't think you have made any mistakes there. However I strongly think that the bloated data is due to Bot traffic in your account. And yes, the bot traffic does increase average session duration.

So here's a set of steps I'll suggest:

1) Create 3 views in Google Analytics (It is a best practice):
 Unfiltered, Master, Test

2) Check for Langauage spam and weird referrals in your report.

3) Add filters to "Test" view to remove these bots & spam referrals. You'll need to write a regular expression for each of these filters. Also make sure you have enabled "bot filtering" in view settings for master & test view. (I am leaving Unfiltered view as it is our data backup in case if anything goes wrong.)

4) Check your traffic for next few days and try doing the URL test again and see the results.

5) If the results in Test View are correct, then apply the same filters to "Master" view.

I hope this helps.

Title: Google Analytics Bloated Data


问:
Load readonly database tables into memory
In one of my applications I have a 1gb database table that is used for reference data. It has a huge amounts of reads coming off that table but there are no writes ever. I was wondering if there's any way that data could be loaded into RAM so that it doesn't have to be accessed from disk?

I'm using SQL Server 2005

答:
If you have enough RAM, SQL will do an outstanding job determining what to load into RAM and what to seek on disk.

This question is asked a lot and it reminds me of people trying to manually set which "core" their process will run on -- let the OS (or in this case the DB) do what it was designed for.

If you want to verify that SQL is in fact reading your look-up data out of cache, then you can initiate a load test and use Sysinternals FileMon, Process Explorer and Process Monitor to verify that the 1GB table is not being read from. For this reason, we sometimes put our "lookup" data onto a separate filegroup so that it is very easy to monitor when it is being accessed on disk.

Hope this helps.

OwnerDisplayName: lomaxx

LastEditorDisplayName: Kevin Fairchild

OwnerDisplayName: Portman


问:
C# Multiple Indexers
Is it possible to have something like the following:

```<code>class C
{
    public Foo Foos[int i]
    {
        ...
    }

    public Bar Bars[int i]
    {
        ...
    }
}
</code>```

If not, then are what are some of the ways I can achieve this? I know I could make functions called getFoo(int i) and getBar(int i) but I was hoping to do this with properties.

答:
If you're trying to do something like this:

```<code>var myClass = new MyClass();

Console.WriteLine(myClass.Foos[0]);
Console.WriteLine(myClass.Bars[0]);
</code>```

then you need to define the indexers on the Foo and Bar classes themselves - i.e. put all the Foo objects inside Foos, and make Foos a type instance that supports indexing directly.

To demonstrate using arrays for the member properties (since they already support indexers):

```<code>public class C {
    private string[] foos = new string[] { "foo1", "foo2", "foo3" };
    private string[] bars = new string[] { "bar1", "bar2", "bar3" };
    public string[] Foos { get { return foos; } }
    public string[] Bars { get { return bars; } }
}
</code>```

would allow you to say:

```<code> C myThing = new C();
 Console.WriteLine(myThing.Foos[1]);
 Console.WriteLine(myThing.Bars[2]);
</code>```

Title: C# Multiple Indexers

Body:
Is it possible to have something like the following:

class C
{
    public Foo Foos[int i]
    {
        ...
    }

    public Bar Bars[int i]
    {
        ...
    }
}

If not, then are what are some of the ways I can achieve this? I know I could make functions called getFoo(int i) and getBar(int i) but I was hoping to do this with properties.

Body:
If you're trying to do something like this:

var myClass = new MyClass();

Console.WriteLine(myClass.Foos[0]);
Console.WriteLine(myClass.Bars[0]);

then you need to define the indexers on the Foo and Bar classes themselves - i.e. put all the Foo objects inside Foos, and make Foos a type instance that supports indexing directly.

To demonstrate using arrays for the member properties (since they already support indexers):

public class C {
    private string[] foos = new string[] { "foo1", "foo2", "foo3" };
    private string[] bars = new string[] { "bar1", "bar2", "bar3" };
    public string[] Foos { get { return foos; } }
    public string[] Bars { get { return bars; } }
}

would allow you to say:

 C myThing = new C();
 Console.WriteLine(myThing.Foos[1]);
 Console.WriteLine(myThing.Bars[2]);

OwnerDisplayName: Dylan Beattie


问:
didSelectItemAt not working from SCLAlertView
I am using SCLAlertView to create custom alert view. My alert view contains one text field and collection view of coloured cells

Problem is that UICollectionView's didSelectItemAt method is not working. I think problem is because it is like subview. But I can't fix it.
I have one collection view at UIViewController and that method is working. Here's my code

```<code>    var collectionViewAlert: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
        layout.itemSize = CGSize(width: 25, height: 25)

        collectionViewAlert = UICollectionView(frame: CGRect(x: 18, y: 10, width: 250, height: 25), collectionViewLayout: layout)
        collectionViewAlert.dataSource = self
        collectionViewAlert.delegate = self
        collectionViewAlert.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "CollCell")
        collectionViewAlert.backgroundColor = UIColor.white

    }

    @IBAction func addCategory(_ sender: Any) {
        let alertView = SCLAlertView()
        alertView.addTextField("Enter category name")

        let subview = UIView(frame: CGRect(x:0,y:0,width:216,height:70))
        subview.addSubview(self.collectionViewAlert)
        alertView.customSubview = subview
        alertView.showEdit("Choose color", subTitle: "This alert view has buttons")

    }

    let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
    var colors = [UIColor.red, UIColor.yellow, UIColor.green, UIColor.blue, UIColor.cyan]

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.colors.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        // get a reference to our storyboard cell
        if (collectionView == self.collectionViewAlert) {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollCell", for: indexPath as IndexPath)
            cell.backgroundColor = self.colors[indexPath.item]
            return cell
        }
        else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath)

            cell.backgroundColor = self.colors[indexPath.item]// make cell more visible in our example project
            return cell
        }

    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("You selected cell #\(indexPath.item)!")
    }

}
</code>```

More screens here: screens

EDIT:

I still not found answer how to solve this problem. I think problem is subview interaction, because delegate method cellForItemAt is invoked on alert show. Someone know how to figure this out? screen from view hierarchy
Thanks for any help.

答:
I have looked into SCLAlertView code. It seems it uses a tap recognizer for dismissing the keyboard.

Tap recognizer can conflict with the tap recognizer used by collection view.

To disable the recognizer in SCLAlertView you can use an appearance object:

```<code>let appearance = SCLAlertView.SCLAppearance(
    disableTapGesture: true
)
let alertView = SCLAlertView(appearance: appearance)
</code>```

Body:
I am using SCLAlertView to create custom alert view. My alert view contains one text field and collection view of coloured cells

Problem is that UICollectionView's didSelectItemAt method is not working. I think problem is because it is like subview. But I can't fix it.
I have one collection view at UIViewController and that method is working. Here's my code

    var collectionViewAlert: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
        layout.itemSize = CGSize(width: 25, height: 25)

        collectionViewAlert = UICollectionView(frame: CGRect(x: 18, y: 10, width: 250, height: 25), collectionViewLayout: layout)
        collectionViewAlert.dataSource = self
        collectionViewAlert.delegate = self
        collectionViewAlert.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "CollCell")
        collectionViewAlert.backgroundColor = UIColor.white

    }

    @IBAction func addCategory(_ sender: Any) {
        let alertView = SCLAlertView()
        alertView.addTextField("Enter category name")

        let subview = UIView(frame: CGRect(x:0,y:0,width:216,height:70))
        subview.addSubview(self.collectionViewAlert)
        alertView.customSubview = subview
        alertView.showEdit("Choose color", subTitle: "This alert view has buttons")

    }

    let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
    var colors = [UIColor.red, UIColor.yellow, UIColor.green, UIColor.blue, UIColor.cyan]

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.colors.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        // get a reference to our storyboard cell
        if (collectionView == self.collectionViewAlert) {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollCell", for: indexPath as IndexPath)
            cell.backgroundColor = self.colors[indexPath.item]
            return cell
        }
        else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath)

            cell.backgroundColor = self.colors[indexPath.item]// make cell more visible in our example project
            return cell
        }

    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("You selected cell #\(indexPath.item)!")
    }

}

More screens here: screens

EDIT:

I still not found answer how to solve this problem. I think problem is subview interaction, because delegate method cellForItemAt is invoked on alert show. Someone know how to figure this out? screen from view hierarchy
Thanks for any help.

Body:
I have looked into SCLAlertView code. It seems it uses a tap recognizer for dismissing the keyboard.

Tap recognizer can conflict with the tap recognizer used by collection view.

To disable the recognizer in SCLAlertView you can use an appearance object:

let appearance = SCLAlertView.SCLAppearance(
    disableTapGesture: true
)
let alertView = SCLAlertView(appearance: appearance)


问:
Get joined reulst from 2 table and when value not exist any of them, fill with empty value
I have tables clients and partners

Table clients

```<code>company_id | name
------------------
11         | UA prods.
12         | CI corp.
13         | UAC
</code>```

Table partners

```<code>company_id | name
------------------
11         | UA prods.
12         | CI corp.
20         | BDP Group
30         | UFF
</code>```

I need get all company names from both table. When company exists in both tables, then theyr names, when doesn't exist, just leave it empty.

I tried left joins, inner joins but it gives me not what I want.

I want result like this

```<code>clients    | partners
--------------------
UA prods.  | UA prods.
CI corp.   | CI corp.
UAC        |
           | BDP Group
           | UFF
</code>```

答:
you will get this with the combination of two joins with the help of union like below

```<code>SELECT t1.c_name,t2.p_name
FROM clients t1
LEFT JOIN partners t2 ON t1.c_id = t2.p_id

UNION

SELECT t4.c_name,t3.p_name
FROM partners t3
LEFT JOIN clients t4 ON t3.p_id = t4.c_id
where t4.c_name is null
</code>```

let me know if you got any issue...

Body:
I have tables clients and partners

Table clients

company_id | name
------------------
11         | UA prods.
12         | CI corp.
13         | UAC

Table partners

company_id | name
------------------
11         | UA prods.
12         | CI corp.
20         | BDP Group
30         | UFF

I need get all company names from both table. When company exists in both tables, then theyr names, when doesn't exist, just leave it empty.

I tried left joins, inner joins but it gives me not what I want.

I want result like this

clients    | partners
--------------------
UA prods.  | UA prods.
CI corp.   | CI corp.
UAC        |
           | BDP Group
           | UFF

Body:
you will get this with the combination of two joins with the help of union like below

SELECT t1.c_name,t2.p_name
FROM clients t1
LEFT JOIN partners t2 ON t1.c_id = t2.p_id

UNION

SELECT t4.c_name,t3.p_name
FROM partners t3
LEFT JOIN clients t4 ON t3.p_id = t4.c_id
where t4.c_name is null

let me know if you got any issue...


问:
linq query issues multiple tables
Here is what I have guys/girls...I have 3 tables as follows (only included important columns):

ITEMS:

```<code>ItemId  Name            ItemLocationId
20      Portal Orange   12
21      Portal Blue     13
</code>```

ITEMLOCATIONS:

```<code>ItemLocationid  ItemId  CreateDate              LocationIf
13              21      3/26/2017 2:19:15 AM    5
14              20      3/27/2017 6:25:45 PM    6
15              21      3/31/2017 12:17:25 AM   6
16              21      3/31/2017 12:18:42 AM   5
17              21      3/31/2017 12:20:23 AM   6
</code>```

LOCATIONS

```<code>LocationId  Name
5           Storage Room
6           Boss Room
</code>```

My issue lies in the itemlocations table...I only need the most recent ItemLocation in the table...The others are for historical value...here is the query I am running now

```<code>Dim i = From r In mydb.Items
        Join il In mydb.ItemLocations On r.ItemLocationId Equals il.ItemLocationId
        Join l In mydb.Locations On il.LocationId Equals l.LocationId
        Where r.CompanyId = UserPro.CompanyId
        Select r.ItemId, r.Name, Location = l.Name
</code>```

this is returning the first itemlocation in the table for that item...how do I get only the one with then most recent

答:
What about this one</p>

```<code>Dim groupQuery=from il mydb.ItemLocations
  .group il by il.ItemId into gl
               select gl.orderByDescending(g=>g.CreateDate).First();

Dim i = From r In mydb.Items
        Join il In groupQuery On r.ItemLocationId Equals il.ItemLocationId
        Join l In mydb.Locations On il.LocationId Equals l.LocationId
        Where r.CompanyId = UserPro.CompanyId
        Select r.ItemId, r.Name, Location = l.Name
</code>```

Title: linq query issues multiple tables

Body:
Here is what I have guys/girls...I have 3 tables as follows (only included important columns):

ITEMS:

ItemId  Name            ItemLocationId
20      Portal Orange   12
21      Portal Blue     13

ITEMLOCATIONS:

ItemLocationid  ItemId  CreateDate              LocationIf
13              21      3/26/2017 2:19:15 AM    5
14              20      3/27/2017 6:25:45 PM    6
15              21      3/31/2017 12:17:25 AM   6
16              21      3/31/2017 12:18:42 AM   5
17              21      3/31/2017 12:20:23 AM   6

LOCATIONS

LocationId  Name
5           Storage Room
6           Boss Room

My issue lies in the itemlocations table...I only need the most recent ItemLocation in the table...The others are for historical value...here is the query I am running now

Dim i = From r In mydb.Items
        Join il In mydb.ItemLocations On r.ItemLocationId Equals il.ItemLocationId
        Join l In mydb.Locations On il.LocationId Equals l.LocationId
        Where r.CompanyId = UserPro.CompanyId
        Select r.ItemId, r.Name, Location = l.Name

this is returning the first itemlocation in the table for that item...how do I get only the one with then most recent

Body:
What about this one

Dim groupQuery=from il mydb.ItemLocations
  .group il by il.ItemId into gl
               select gl.orderByDescending(g=>g.CreateDate).First();

Dim i = From r In mydb.Items
        Join il In groupQuery On r.ItemLocationId Equals il.ItemLocationId
        Join l In mydb.Locations On il.LocationId Equals l.LocationId
        Where r.CompanyId = UserPro.CompanyId
        Select r.ItemId, r.Name, Location = l.Name


问:
Placing two (or more) multi-line variables next to each other bash
Lets say I have 3 variables, each with a multi-line output, like so:

```<code>IPs="10.0.0.1
10.0.0.2
10.0.0.3
10.0.0.4"

MACs="08:16:E9:3D:12:D5
C6:70:A5:25:FF:58
42:96:ED:C8:D5:80
05:89:C6:37:68:9B"

Vendors="Apple
Intel
Sagemcom
HP"
</code>```

and I want to put them next to each other, like so:

```<code>10.0.0.1 08:16:E9:3D:12:D5 Apple
10.0.0.2 C6:70:A5:25:FF:58 Intel
10.0.0.3 42:96:ED:C8:D5:80 Sagemcom
10.0.0.4 05:89:C6:37:68:9B HP
</code>```

How would I do so?

Body:
Lets say I have 3 variables, each with a multi-line output, like so:

IPs="10.0.0.1
10.0.0.2
10.0.0.3
10.0.0.4"

MACs="08:16:E9:3D:12:D5
C6:70:A5:25:FF:58
42:96:ED:C8:D5:80
05:89:C6:37:68:9B"

Vendors="Apple
Intel
Sagemcom
HP"

and I want to put them next to each other, like so:

10.0.0.1 08:16:E9:3D:12:D5 Apple
10.0.0.2 C6:70:A5:25:FF:58 Intel
10.0.0.3 42:96:ED:C8:D5:80 Sagemcom
10.0.0.4 05:89:C6:37:68:9B HP

How would I do so?

Body:
We on macOS (BSD) also:

rs 3 <<<"$IPs $MACs $Vendors" | rs -C' ' -T

10.0.0.1 08:16:E9:3D:12:D5 Apple
10.0.0.2 C6:70:A5:25:FF:58 Intel
10.0.0.3 42:96:ED:C8:D5:80 Sagemcom
10.0.0.4 05:89:C6:37:68:9B HP


问:
System.Data.Entity.Infrastructure.DbUpdateException error even when i am not updating the id column
I am working on a project where I am using Entity framework to manipulate a DB on sql server 2014.
My code is the following:

```<code>private void BtnAddUser(object sender, EventArgs e)
    {
        var u = new User();
        u.username = txtBoxNewUser.Text;
        u.password = txtBoxNewPass.Text;
        u.rank = cmbBoxRank.GetItemText(this.cmbBoxRank.SelectedItem);
        using (var db = new ProjetPooEntities2())
        {
            db.Users.Add(u);
            db.SaveChanges();
        }

    }
</code>```

Please note that the code runs perfectly but it when i press the Add button to add the created user to the db an error shows on "db.saveChanges()" and it says:

System.Data.Entity.Infrastructure.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.'
  And the inner exception is:
  SqlException: Cannot insert explicit value for identity column in table 'User' when IDENTITY_INSERT is set to OFF.

I have set the identity column in the db to "id" and it is set to auto-increment by 1 starting from 1.
I have tried searching a lot for a solution but i found nothing.
Any help will be appreciated!!

答:
Suppose the User entity has this structure:

```<code>public class User
{
    public int id { get; set; }
    public string username { get; set; }
    public string password { get; set; }
    public string rank { get; set; }
}
</code>```

If Code First is used, add DatabaseGeneratedAttribute with option DatabaseGeneratedOption.Identity as this to set id as identity autoincrement property:

```<code>public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int id { get; set; }
    ... // other properties
}
</code>```

However if Database First is used, open EDMX model designer, use "Properties" context menu on id field and set StoreGeneratedPattern to Identity:

Then, open EDMX file with XML editor and ensure it has StoreGeneratedPattern="Identity" on id property as shown below:

```<code><EntityType Name="User">
    <Key>
        <PropertyRef Name="id" />
    </Key>
    <Property Name="id" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
</EntityType>
</code>```

If those ways above still won't work thereafter, you can execute SET IDENTITY_INSERT query in DbContext as this (must be reverting with StoreGeneratedPattern="None" in EDMX or DatabaseGenerated(DatabaseGeneratedOption.None) in Code First to work properly):

```<code>using (var db = new ProjetPooEntities2())
{
    // taken from /a/31856991
    db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[User] ON");
    db.Users.Add(u);
    db.SaveChanges();
    db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[User] OFF");
}
</code>```

Note that this bottom-most approach here considered not a good practice, since it is possible to allow insertion of duplicate values in certain cases.

Related issues:

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF

How can I force entity framework to insert identity columns?

Body:
I am working on a project where I am using Entity framework to manipulate a DB on sql server 2014.
My code is the following:

private void BtnAddUser(object sender, EventArgs e)
    {
        var u = new User();
        u.username = txtBoxNewUser.Text;
        u.password = txtBoxNewPass.Text;
        u.rank = cmbBoxRank.GetItemText(this.cmbBoxRank.SelectedItem);
        using (var db = new ProjetPooEntities2())
        {
            db.Users.Add(u);
            db.SaveChanges();
        }

    }

Please note that the code runs perfectly but it when i press the Add button to add the created user to the db an error shows on "db.saveChanges()" and it says:

System.Data.Entity.Infrastructure.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.'
  And the inner exception is:
  SqlException: Cannot insert explicit value for identity column in table 'User' when IDENTITY_INSERT is set to OFF.

I have set the identity column in the db to "id" and it is set to auto-increment by 1 starting from 1.
I have tried searching a lot for a solution but i found nothing.
Any help will be appreciated!!

Body:
Suppose the User entity has this structure:

public class User
{
    public int id { get; set; }
    public string username { get; set; }
    public string password { get; set; }
    public string rank { get; set; }
}

If Code First is used, add DatabaseGeneratedAttribute with option DatabaseGeneratedOption.Identity as this to set id as identity autoincrement property:

public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int id { get; set; }
    ... // other properties
}

However if Database First is used, open EDMX model designer, use "Properties" context menu on id field and set StoreGeneratedPattern to Identity:

Then, open EDMX file with XML editor and ensure it has StoreGeneratedPattern="Identity" on id property as shown below:

<EntityType Name="User">
    <Key>
        <PropertyRef Name="id" />
    </Key>
    <Property Name="id" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
</EntityType>

If those ways above still won't work thereafter, you can execute SET IDENTITY_INSERT query in DbContext as this (must be reverting with StoreGeneratedPattern="None" in EDMX or DatabaseGenerated(DatabaseGeneratedOption.None) in Code First to work properly):

using (var db = new ProjetPooEntities2())
{
    // taken from /a/31856991
    db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[User] ON");
    db.Users.Add(u);
    db.SaveChanges();
    db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[User] OFF");
}

Note that this bottom-most approach here considered not a good practice, since it is possible to allow insertion of duplicate values in certain cases.

Related issues:

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF

How can I force entity framework to insert identity columns?


问:
Django - serving a SPA from static folder
Our django server is our API as well as an operations backend. I'm working on improving our ops backend by writing a Vue SPA that slowly replaces the existing ops backend.

I'm frontend and a little lost in intricacies of Django configs. Could someone suggest a sane solution for this problem?

I would like for the app to be served out of static folder, and have set:

```<code>STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
    os.path.join(BASE_DIR, '../console/dist'),
)
</code>```

This works and I can see my code when I view source, but only at http://localhost:8000/static/console/index.html

1) this won't work because as a SPA, Vue needs control of routing. From the Django side how can I have /static/console/* use my Vue app? On the Vue end, what do I have to configure in Webpack and Vue-router?

2) despite the fact that I can see my compiled app source, I get errors:

```<code>Creating Application Cache with manifest http://localhost:8000/static/appcache/manifest.appcache
index.html:1 Application Cache Checking event
index.html:1 Application Cache Downloading event
index.html:1 Application Cache Progress event (0 of 7) http://localhost:8000/favicon.ico
index.html:1 Application Cache Error event: Resource fetch failed (4) http://localhost:8000/favicon.ico
index.html:1 Uncaught (in promise) TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.
</code>```

which is weird because http://localhost:8000/favicon.ico is a working URL. I have a feeling this is also a Webpack problem.

What are my options?

答:
I made it like this for Angular2 app with Django(it works without problems) - I think it can help you.

urls.py:

```<code># catch-all pattern for compatibility with the Angular routes
url(r'^$', views.index),
url(r'^(?P<path>.*)/$', views.index),
</code>```

views.py

```<code>def index(request, path=''):
    """
    Renders the Angular2 SPA
    """
    return render(request, 'index.html')
</code>```

index.html

```<code>{% load staticfiles %}
...some other stuff...
<app-root>Loading... </app-root>
<script src="{% static 'js/jquery-3.1.1.min.js' %}"></script>
<script src="{% static  'js/materialize.min.js'%}"></script>

<!-- Angular app -->
<script type="text/javascript" src="{% static 'js/app/inline.bundle.js' %}"></script>
<script type="text/javascript" src="{% static 'js/app/vendor.bundle.js' %}"></script>
<script type="text/javascript" src="{% static 'js/app/main.bundle.js' %}"></script>
<script type="text/javascript" src="{% static 'js/app/scripts.bundle.js' %}"></script>¸
</code>```

settings.py

```<code>TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
</code>```

My index.html is stored in templates directory, my js app files are stored in static/js/app.

Body:
Our django server is our API as well as an operations backend. I'm working on improving our ops backend by writing a Vue SPA that slowly replaces the existing ops backend.

I'm frontend and a little lost in intricacies of Django configs. Could someone suggest a sane solution for this problem?

I would like for the app to be served out of static folder, and have set:

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
    os.path.join(BASE_DIR, '../console/dist'),
)

This works and I can see my code when I view source, but only at http://localhost:8000/static/console/index.html

1) this won't work because as a SPA, Vue needs control of routing. From the Django side how can I have /static/console/* use my Vue app? On the Vue end, what do I have to configure in Webpack and Vue-router?

2) despite the fact that I can see my compiled app source, I get errors:

Creating Application Cache with manifest http://localhost:8000/static/appcache/manifest.appcache
index.html:1 Application Cache Checking event
index.html:1 Application Cache Downloading event
index.html:1 Application Cache Progress event (0 of 7) http://localhost:8000/favicon.ico
index.html:1 Application Cache Error event: Resource fetch failed (4) http://localhost:8000/favicon.ico
index.html:1 Uncaught (in promise) TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script.

which is weird because http://localhost:8000/favicon.ico is a working URL. I have a feeling this is also a Webpack problem.

What are my options?

Body:
I made it like this for Angular2 app with Django(it works without problems) - I think it can help you.

urls.py:

# catch-all pattern for compatibility with the Angular routes
url(r'^$', views.index),
url(r'^(?P<path>.*)/$', views.index),

views.py

def index(request, path=''):
    """
    Renders the Angular2 SPA
    """
    return render(request, 'index.html')

index.html

{% load staticfiles %}
...some other stuff...
<app-root>Loading... </app-root>
<script src="{% static 'js/jquery-3.1.1.min.js' %}"></script>
<script src="{% static  'js/materialize.min.js'%}"></script>

<!-- Angular app -->
<script type="text/javascript" src="{% static 'js/app/inline.bundle.js' %}"></script>
<script type="text/javascript" src="{% static 'js/app/vendor.bundle.js' %}"></script>
<script type="text/javascript" src="{% static 'js/app/main.bundle.js' %}"></script>
<script type="text/javascript" src="{% static 'js/app/scripts.bundle.js' %}"></script>¸

settings.py

TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

My index.html is stored in templates directory, my js app files are stored in static/js/app.

ContentLicense: CC BY-SA 4.0


问:
Printing statements in thenReturn of mockito
I am using Mockito to mock a certain class while writing my test cases.

Is there a way to print some statements before returning a value? Like:

```<code>when(x.callFunction(10).thenReturn(new String("Hello"));
</code>```

The above statement works, however I am not able to do the following:

```<code>when(x.callFunction(10).thenReturn({
   System.out.println("Mock called---going to return hello");
   return new String("Hello");});
</code>```

答:
I like the other answers, but given your latest comment:

I will be using thenReturn in my final code. This is more to test my testing code and check if my mocking function is being called or not!

I have another idea for you: do not return/print on that call; use thenThrow() instead!

The point is: print statements in the console are sometimes helpful; but they are easy to be overlooked. If the whole purpose is to be sure that a certain call happens on a certain mock; then just throw an exception instead of returning a value. As JUnit will give you direct and hard-to-ignore feedback on that; by failing the testcase.

You could even go one step further and put up @expected on that test - in that way you have a method to test this aspect automatically - if the mock isn't called; no exception; test will fail.

Body:
I am using Mockito to mock a certain class while writing my test cases.

Is there a way to print some statements before returning a value? Like:

when(x.callFunction(10).thenReturn(new String("Hello"));

The above statement works, however I am not able to do the following:

when(x.callFunction(10).thenReturn({
   System.out.println("Mock called---going to return hello");
   return new String("Hello");});


问:
how to send location data (latitude, longitude) periodically to web server
I am developing real time application so i need to send continuous or some periodic (in seconds) location data as latitude and longitude to web service using rest API. so what can i use to send continuous or periodic data to server? do i need to use back ground service or anything else? i don't know how background service work and how to use it? so can anyone help me for this? thanks in advance.</p>

```<code>protected void startLocationUpdates() {

        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);

    }

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
                + result.getErrorCode());
    }

    @Override
    public void onConnected(Bundle arg0) {

        displayLocation();

        if (mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }

    @Override
    public void onConnectionSuspended(int arg0) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        mLastLocation = location;

        Toast.makeText(getApplicationContext(), "Location changed!",
                Toast.LENGTH_SHORT).show();

        displayLocation();
    }
</code>```

答:
you need to make a service for that if you want to send data continuous to the server even after your application is closed.

Here is how i made my service.

```<code> public class FeatureService extends Service
{

@Nullable
@Override
public IBinder onBind(Intent intent)
{
    return null;
}

@Override
public void onCreate()
{
  // make your api call here and other implementations according to your requirement.
    super.onCreate();

}

@Override
public void onDestroy()
{
   // what you want when service is destroyed
}
</code>```

Declare your service in Manifest

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name="Your Serive"
        android:enabled="true">
    </service>
</application>
</code>```

And Finally call your service like this in onCreate of your relevant activity.

```<code>Intent i= new Intent(this,FeatureService.class);
startService(i);
</code>```

Body:
I am developing real time application so i need to send continuous or some periodic (in seconds) location data as latitude and longitude to web service using rest API. so what can i use to send continuous or periodic data to server? do i need to use back ground service or anything else? i don't know how background service work and how to use it? so can anyone help me for this? thanks in advance.

protected void startLocationUpdates() {

        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);

    }

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
                + result.getErrorCode());
    }

    @Override
    public void onConnected(Bundle arg0) {

        displayLocation();

        if (mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }

    @Override
    public void onConnectionSuspended(int arg0) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        mLastLocation = location;

        Toast.makeText(getApplicationContext(), "Location changed!",
                Toast.LENGTH_SHORT).show();

        displayLocation();
    }

Body:
you need to make a service for that if you want to send data continuous to the server even after your application is closed.

Here is how i made my service.

 public class FeatureService extends Service
{

@Nullable
@Override
public IBinder onBind(Intent intent)
{
    return null;
}

@Override
public void onCreate()
{
  // make your api call here and other implementations according to your requirement.
    super.onCreate();

}

@Override
public void onDestroy()
{
   // what you want when service is destroyed
}

Declare your service in Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name="Your Serive"
        android:enabled="true">
    </service>
</application>

And Finally call your service like this in onCreate of your relevant activity.

Intent i= new Intent(this,FeatureService.class);
startService(i);


问:
VBScript writing to file error
I've coded a script that has the basic function of creating a .txt file and then writing some text into it. But whenever I run it I get;

Script: F\Known.vbs
    Line: 17
    Char:1
    Error: Permission denied
    Code: 800A0046
    Source: Microsoft VBScript runtime error

My code goes as such;

Option Explicit
    Dim objFSO, objFSOText, objFolder, r, objFile
    Dim strDirectory, strFile
    Dim objNetwork
    do
    randomize
    r = int(rnd*91372183) + 1
    strDirectory = "C:\Users\" & CreateObject("Wscript.Network").UserName & "\Desktop"
    strFile = "\" & r & ".txt"
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
    Const ReadOnly = 1
    Set objFile = objFSO.GetFile(strDirectory & strFile)
    objFile.Attributes = objFile.Attributes XOR ReadOnly
    Const ForWriting = 2
    Set objNetwork = CreateObject("Wscript.Network")
    Set objFile = objFSO.OpenTextFile(strDirectory & strFile, ForWriting)
    objFile.Write "f672f7fd12d6wf6df26df6f26dfs6f6qf67wqqf6dfw6f16fw76df61f62fd"
    objFile.WriteBlankLines(1)
    loop

I have looked at other questions of a similar nature, trying to add read-write attributes, etc. but none have worked.

答:
You can't open the 'strDirectory & strFile'-file a second time with

```<code>Set objFile = objFSO.OpenTextFile(strDirectory & strFile, ForWriting)
</code>```

in line 17 after you opened it in line 11 with

```<code>Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
</code>```

Evidence:

```<code>>> Set f = oFS.CreateTextFile("x")
>> Set f = oFS.OpenTextFile("x", 2)
>>
Error Number:       70
Error Description:  Erlaubnis verweigert.
>>
</code>```

The other parts of your script are a mess (Randomize and Const in a loop, variables not used, bad attempts to roll your own versions of standard methods), so you should read the docs and plan before you write your next lines of code.

Title: VBScript writing to file error

Body:
You can't open the 'strDirectory & strFile'-file a second time with

Set objFile = objFSO.OpenTextFile(strDirectory & strFile, ForWriting)

in line 17 after you opened it in line 11 with

Set objFile = objFSO.CreateTextFile(strDirectory & strFile)

Evidence:

>> Set f = oFS.CreateTextFile("x")
>> Set f = oFS.OpenTextFile("x", 2)
>>
Error Number:       70
Error Description:  Erlaubnis verweigert.
>>

The other parts of your script are a mess (Randomize and Const in a loop, variables not used, bad attempts to roll your own versions of standard methods), so you should read the docs and plan before you write your next lines of code.


问:
Mysql doesn't work after installing both through brew and the package from the official website
```<code>Shans-Macbook:~ Shanshan$  sudo cp /usr/local/mysql/support-files/my-small.cnf /etc/my.cnf

Password:

cp: /usr/local/mysql/support-files/my-small.cnf: No such file or directory

Shans-Macbook:~ Shanshan$  sudo cd /usr/local/mysql/support-files/my-small.cnf /etc/my.cnf

/usr/bin/cd: line 4: cd: /usr/local/mysql/support-files/my-small.cnf: No such file or directory

Shans-Macbook:~ Shanshan$ sudo /usr/local/mysql/support-files/mysql.server start

Starting MySQL
.................................................................................................... ERROR! The server quit without updating PID file (/usr/local/mysql/data/Shans-Macbook.pid).

Shans-Macbook:~ Shanshan$ mysqld_safe --skip-grant-tables &

[1] 15852

Shans-Macbook:~ Shanshan$ 2017-03-31T07:16:22.6NZ mysqld_safe Logging to '/usr/local/var/mysql/Shans-Macbook.err'.

2017-03-31T07:16:22.6NZ mysqld_safe Logging to '/usr/local/var/mysql/Shans-Macbook.err'.

/usr/local/bin/mysqld_safe: line 139: /usr/local/var/mysql/Shans-Macbook.err: Permission denied

2017-03-31T07:16:22.6NZ mysqld_safe Starting mysqld daemon with databases from /usr/local/var/mysql

/usr/local/bin/mysqld_safe: line 139: /usr/local/var/mysql/Shans-Macbook.err: Permission denied

/usr/local/bin/mysqld_safe: line 193: /usr/local/var/mysql/Shans-Macbook.err: Permission denied

2017-03-31T07:16:22.6NZ mysqld_safe mysqld from pid file /usr/local/var/mysql/Shans-Macbook.pid ended
/usr/local/bin/mysqld_safe: line 139: /usr/local/var/mysql/Shans-Macbook.err: Permission denied

Shans-Macbook:~ Shanshan$ mysql -u root

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
[1]+  Done                    mysqld_safe --skip-grant-tables

Shans-Macbook:~ Shanshan$ mysql.server start
Starting MySQL

./usr/local/Cellar/mysql/5.7.17/bin/mysqld_safe: line 139:

/usr/local/var/mysql/Shans-Macbook.err: Permission denied

/usr/local/Cellar/mysql/5.7.17/bin/mysqld_safe: line 139:

/usr/local/var/mysql/Shans-Macbook.err: Permission denied

/usr/local/Cellar/mysql/5.7.17/bin/mysqld_safe: line 193:

/usr/local/var/mysql/Shans-Macbook.err: Permission denied

/usr/local/Cellar/mysql/5.7.17/bin/mysqld_safe: line 139:

/usr/local/var/mysql/Shans-Macbook.err: Permission denied

 ERROR! The server quit without updating PID file (/usr/local/var/mysql/Shans-Macbook.pid).
</code>```

I have spend 2 days searching and trying every post online, and it is still not working.

My mac's system is macOS Sierra.

```<code>Shans-Macbook:~ Shanshan$ mysql -V

mysql  Ver 14.14 Distrib 5.7.17, for osx10.12 (x86_64) using  EditLine wrapper
</code>```

答:
I think you wan't the MySQL workbench.
If you download the DMG File: https://dev.mysql.com/downloads/workbench/

Then you probably need the Server as well:
https://dev.mysql.com/downloads/mysql/

Check it out, there are a lot of forums, wich provide this problem.

Body:
Shans-Macbook:~ Shanshan$  sudo cp /usr/local/mysql/support-files/my-small.cnf /etc/my.cnf

Password:

cp: /usr/local/mysql/support-files/my-small.cnf: No such file or directory

Shans-Macbook:~ Shanshan$  sudo cd /usr/local/mysql/support-files/my-small.cnf /etc/my.cnf

/usr/bin/cd: line 4: cd: /usr/local/mysql/support-files/my-small.cnf: No such file or directory

Shans-Macbook:~ Shanshan$ sudo /usr/local/mysql/support-files/mysql.server start

Starting MySQL
.................................................................................................... ERROR! The server quit without updating PID file (/usr/local/mysql/data/Shans-Macbook.pid).

Shans-Macbook:~ Shanshan$ mysqld_safe --skip-grant-tables &

[1] 15852

Shans-Macbook:~ Shanshan$ 2017-03-31T07:16:22.6NZ mysqld_safe Logging to '/usr/local/var/mysql/Shans-Macbook.err'.

2017-03-31T07:16:22.6NZ mysqld_safe Logging to '/usr/local/var/mysql/Shans-Macbook.err'.

/usr/local/bin/mysqld_safe: line 139: /usr/local/var/mysql/Shans-Macbook.err: Permission denied

2017-03-31T07:16:22.6NZ mysqld_safe Starting mysqld daemon with databases from /usr/local/var/mysql

/usr/local/bin/mysqld_safe: line 139: /usr/local/var/mysql/Shans-Macbook.err: Permission denied

/usr/local/bin/mysqld_safe: line 193: /usr/local/var/mysql/Shans-Macbook.err: Permission denied

2017-03-31T07:16:22.6NZ mysqld_safe mysqld from pid file /usr/local/var/mysql/Shans-Macbook.pid ended
/usr/local/bin/mysqld_safe: line 139: /usr/local/var/mysql/Shans-Macbook.err: Permission denied

Shans-Macbook:~ Shanshan$ mysql -u root

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
[1]+  Done                    mysqld_safe --skip-grant-tables

Shans-Macbook:~ Shanshan$ mysql.server start
Starting MySQL

./usr/local/Cellar/mysql/5.7.17/bin/mysqld_safe: line 139:

/usr/local/var/mysql/Shans-Macbook.err: Permission denied

/usr/local/Cellar/mysql/5.7.17/bin/mysqld_safe: line 139:

/usr/local/var/mysql/Shans-Macbook.err: Permission denied

/usr/local/Cellar/mysql/5.7.17/bin/mysqld_safe: line 193:

/usr/local/var/mysql/Shans-Macbook.err: Permission denied

/usr/local/Cellar/mysql/5.7.17/bin/mysqld_safe: line 139:

/usr/local/var/mysql/Shans-Macbook.err: Permission denied

 ERROR! The server quit without updating PID file (/usr/local/var/mysql/Shans-Macbook.pid).

I have spend 2 days searching and trying every post online, and it is still not working.

My mac's system is macOS Sierra.

Shans-Macbook:~ Shanshan$ mysql -V

mysql  Ver 14.14 Distrib 5.7.17, for osx10.12 (x86_64) using  EditLine wrapper


问:
Retrofit,onResponse method doesnt execute code in its body
Retrofit2, onResponse method doesn't execute code in its body. The app doesn't crash but the list is not showing up with data in the activity.
I created log.e() to see where my code was executing and not executing.the code in the on response didn't execute at all but the one in the onFailure did execute.

I see :

```<code>"java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $ " in the logcat.
</code>```

My interface

```<code>    public interface RadioApiClient {
        String BASE_URL = "https://api.broadcastify.com/audio/";
        String API_KEY = "1234567890";//dummy key
        String JSON_RESPONSE = "json";
        String XML_RESPONSE = "XML";

        //api.broadcastify.com/audio/?a=feeds&type=json&key=1234567890
        @GET(".")
        Call<List<Feeds>> getFeeds(@Query("a") String action,
                                   @Query("type") String reponseType,
                                   @Query("key") String key);

        @GET("api.broadcastify.com/audio/?a=feeds&type=json&key=1234567890")
        Call<List<Feeds>> getFeeds();

    }
</code>```

My main activity

```<code>        public class MainActivity extends AppCompatActivity {

        private ListView listView;

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

            listView = (ListView) findViewById(R.id.listView);

            final Retrofit.Builder builder = new Retrofit.Builder()
                    .baseUrl(RadioApiClient.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create());
            Retrofit retrofit = builder.build();

            RadioApiClient client = retrofit.create(RadioApiClient.class);

    //I checked if internet was connected

            if (isNetworkConnected()) {
                Log.e("success", "" + "Has internet");
            } else {
                Log.e("No success", "" + "no internet");

            }
            Call<List<Feeds>> call = client.getFeeds("feeds",
                    RadioApiClient.JSON_RESPONSE,
                    RadioApiClient.API_KEY);
            isNetworkConnected();
            Log.e("Accessing url", client.getFeeds("feeds",
                    RadioApiClient.JSON_RESPONSE,
                    RadioApiClient.API_KEY).request().url().toString());

   //all log.e excecuted apart from the one in the onResponse method

            call.enqueue(new Callback<List<Feeds>>() {
                @Override
                public void onResponse(Call<List<Feeds>> call, Response<List<Feeds>> response) {

                    Log.e("success", "" + "3");
                    List<Feeds> feeds = response.body();
                    Context context = getApplicationContext();
                    Log.e("success", "" + "4");
                    Log.e("Feedsize", "" + feeds.size());

                    Toast toast = Toast.makeText(context, feeds.size(), Toast.LENGTH_LONG);
                    toast.show();
                    listView.setAdapter(new ArrayAdapter<Feeds>(MainActivity.this, android.R.layout.simple_list_item_1, feeds));
                }

                @Override
                public void onFailure(Call<List<Feeds>> call, Throwable t) {
                    Log.e("no success", "" + "onfailure");
                    t.printStackTrace();
                }
            });
        }

        private boolean isNetworkConnected() {
            ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

            return cm.getActiveNetworkInfo() != null;
        }

    }
</code>```

My Model

```<code>public class Radio {

    @SerializedName("Feeds")
    @Expose
    private List<Feeds> feeds = null;

    public List<Feeds> getFeeds() {
        return feeds;
    }

    public void setFeeds(List<Feeds> feeds) {
        this.feeds = feeds;
    }

}

      public class Feeds {

        @SerializedName("id")
        @Expose
        private int id;
        @SerializedName("status")
        @Expose
        private int status;
        @SerializedName("listeners")
        @Expose
        private int listeners;
        @SerializedName("descr")
        @Expose
        private String descr;
        @SerializedName("genre")
        @Expose
        private String genre;
        @SerializedName("mount")
        @Expose
        private String mount;
        @SerializedName("bitrate")
        @Expose
        private int bitrate;
        @SerializedName("Counties")
        @Expose
        private List<County> counties = null;
        @SerializedName("Relays")
        @Expose
        private List<Relay> relays = null;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public int getListeners() {
            return listeners;
        }

        public void setListeners(int listeners) {
            this.listeners = listeners;
        }

        public String getDescr() {
            return descr;
        }

        public void setDescr(String descr) {
            this.descr = descr;
        }

        public String getGenre() {
            return genre;
        }

        public void setGenre(String genre) {
            this.genre = genre;
        }

        public String getMount() {
            return mount;
        }

        public void setMount(String mount) {
            this.mount = mount;
        }

        public int getBitrate() {
            return bitrate;
        }

        public void setBitrate(int bitrate) {
            this.bitrate = bitrate;
        }

        public List<County> getCounties() {
            return counties;
        }

        public void setCounties(List<County> counties) {
            this.counties = counties;
        }

        public List<Relay> getRelays() {
            return relays;
        }

        public void setRelays(List<Relay> relays) {
            this.relays = relays;
        }

    }
</code>```

答:
Change Your code in RadioApiClient  to this  </p>

```<code>public interface RadioApiClient {

String BASE_URL = "https://api.broadcastify.com/";
String API_KEY = "1234567890";//dummy key
String JSON_RESPONSE = "json";
String XML_RESPONSE = "XML";

@GET("audio/?")
Call<List<Feeds>> getFeeds(
        @Query("a") String action,
        @Query("type") String responseType,
        @Query("key") String key);
</code>```

<p>}</p>

Body:
Retrofit2, onResponse method doesn't execute code in its body. The app doesn't crash but the list is not showing up with data in the activity.
I created log.e() to see where my code was executing and not executing.the code in the on response didn't execute at all but the one in the onFailure did execute.

I see :

"java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $ " in the logcat.

My interface

    public interface RadioApiClient {
        String BASE_URL = "https://api.broadcastify.com/audio/";
        String API_KEY = "1234567890";//dummy key
        String JSON_RESPONSE = "json";
        String XML_RESPONSE = "XML";

        //api.broadcastify.com/audio/?a=feeds&type=json&key=1234567890
        @GET(".")
        Call<List<Feeds>> getFeeds(@Query("a") String action,
                                   @Query("type") String reponseType,
                                   @Query("key") String key);

        @GET("api.broadcastify.com/audio/?a=feeds&type=json&key=1234567890")
        Call<List<Feeds>> getFeeds();

    }

My main activity

        public class MainActivity extends AppCompatActivity {

        private ListView listView;

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

            listView = (ListView) findViewById(R.id.listView);

            final Retrofit.Builder builder = new Retrofit.Builder()
                    .baseUrl(RadioApiClient.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create());
            Retrofit retrofit = builder.build();

            RadioApiClient client = retrofit.create(RadioApiClient.class);

    //I checked if internet was connected

            if (isNetworkConnected()) {
                Log.e("success", "" + "Has internet");
            } else {
                Log.e("No success", "" + "no internet");

            }
            Call<List<Feeds>> call = client.getFeeds("feeds",
                    RadioApiClient.JSON_RESPONSE,
                    RadioApiClient.API_KEY);
            isNetworkConnected();
            Log.e("Accessing url", client.getFeeds("feeds",
                    RadioApiClient.JSON_RESPONSE,
                    RadioApiClient.API_KEY).request().url().toString());

   //all log.e excecuted apart from the one in the onResponse method

            call.enqueue(new Callback<List<Feeds>>() {
                @Override
                public void onResponse(Call<List<Feeds>> call, Response<List<Feeds>> response) {

                    Log.e("success", "" + "3");
                    List<Feeds> feeds = response.body();
                    Context context = getApplicationContext();
                    Log.e("success", "" + "4");
                    Log.e("Feedsize", "" + feeds.size());

                    Toast toast = Toast.makeText(context, feeds.size(), Toast.LENGTH_LONG);
                    toast.show();
                    listView.setAdapter(new ArrayAdapter<Feeds>(MainActivity.this, android.R.layout.simple_list_item_1, feeds));
                }

                @Override
                public void onFailure(Call<List<Feeds>> call, Throwable t) {
                    Log.e("no success", "" + "onfailure");
                    t.printStackTrace();
                }
            });
        }

        private boolean isNetworkConnected() {
            ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

            return cm.getActiveNetworkInfo() != null;
        }

    }

My Model

public class Radio {

    @SerializedName("Feeds")
    @Expose
    private List<Feeds> feeds = null;

    public List<Feeds> getFeeds() {
        return feeds;
    }

    public void setFeeds(List<Feeds> feeds) {
        this.feeds = feeds;
    }

}

      public class Feeds {

        @SerializedName("id")
        @Expose
        private int id;
        @SerializedName("status")
        @Expose
        private int status;
        @SerializedName("listeners")
        @Expose
        private int listeners;
        @SerializedName("descr")
        @Expose
        private String descr;
        @SerializedName("genre")
        @Expose
        private String genre;
        @SerializedName("mount")
        @Expose
        private String mount;
        @SerializedName("bitrate")
        @Expose
        private int bitrate;
        @SerializedName("Counties")
        @Expose
        private List<County> counties = null;
        @SerializedName("Relays")
        @Expose
        private List<Relay> relays = null;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public int getListeners() {
            return listeners;
        }

        public void setListeners(int listeners) {
            this.listeners = listeners;
        }

        public String getDescr() {
            return descr;
        }

        public void setDescr(String descr) {
            this.descr = descr;
        }

        public String getGenre() {
            return genre;
        }

        public void setGenre(String genre) {
            this.genre = genre;
        }

        public String getMount() {
            return mount;
        }

        public void setMount(String mount) {
            this.mount = mount;
        }

        public int getBitrate() {
            return bitrate;
        }

        public void setBitrate(int bitrate) {
            this.bitrate = bitrate;
        }

        public List<County> getCounties() {
            return counties;
        }

        public void setCounties(List<County> counties) {
            this.counties = counties;
        }

        public List<Relay> getRelays() {
            return relays;
        }

        public void setRelays(List<Relay> relays) {
            this.relays = relays;
        }

    }

Body:
Change Your code in RadioApiClient  to this

public interface RadioApiClient {

String BASE_URL = "https://api.broadcastify.com/";
String API_KEY = "1234567890";//dummy key
String JSON_RESPONSE = "json";
String XML_RESPONSE = "XML";

@GET("audio/?")
Call<List<Feeds>> getFeeds(
        @Query("a") String action,
        @Query("type") String responseType,
        @Query("key") String key);

}


问:
Removing a specific Row in TableLayoutPanel
I have TableLayoutPanel that I programatically add Rows to. The User basically choses a Property and that is then displayed in the table along with some controls. I think I have a general understanding problem here and I will try to explain it.

One of the Controls in every row is a 'delete'-Button. That button should delete the row it is in. What I did is add an eventhandler to the button and set the current rowcount.

```<code>deleteTalent.Click += (sender, e) => buttonClickHandler(numberOfRows);
</code>```

Code of the handler:

```<code>private void buttonClickHandler(int rowCount)
{
    int count = rowCount - 1;
    for (int i = count; i < (count + 5); i++)
    {
        balanceTable.Controls.RemoveAt(count);
    }
    balanceTable.RowStyles.RemoveAt(count);
    balanceTable.RowCount--;

}
</code>```

I looked at it for hours and played around. But I can't find a working clean solution. I'm also pretty new to C#

Here's the complete Function that creates a new row:

```<code>private void addBalanceItems(ToolStripMenuItem item)
{
    int numberOfRows = balanceTable.RowCount;
    if (numberOfRows > 1)
    {
        balanceTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.AutoSize));

    }
    balanceTable.Height = numberOfRows * 45;
    Steigerungsrechner rechner = new Steigerungsrechner();
    string tag = item.Tag.ToString();

    //change that asap :(
    if (tag == "A") { rechner.column = 1; }
    if (tag == "B") { rechner.column = 2; }
    if (tag == "C") { rechner.column = 3; }
    if (tag == "D") { rechner.column = 4; }
    if (tag == "E") { rechner.column = 5; }
    if (tag == "F") { rechner.column = 6; }
    if (tag == "G") { rechner.column = 7; }
    if (tag == "H") { rechner.column = 8; }

    Label talentName = new Label();
    talentName.Text = item.Text;
    talentName.Height = standardHeight;
    talentName.TextAlign = ContentAlignment.MiddleLeft;
    talentName.AutoSize = true;
    Label cost = new Label();
    cost.TextChanged += (sender, e) => costChangeHandler(cost);
    cost.Height = standardHeight;
    cost.TextAlign = ContentAlignment.MiddleLeft;
    TextBox startValue = new TextBox();
    startValue.TextChanged += (sender, e) => startValueChangeHandler(rechner, startValue, cost);
    startValue.Height = standardHeight;
    startValue.TextAlign = HorizontalAlignment.Center;
    TextBox endValue = new TextBox();
    endValue.TextChanged += (sender, e) => endValueChangeHandler(rechner, endValue, cost);
    endValue.Height = standardHeight;
    endValue.TextAlign = HorizontalAlignment.Center;
    Button deleteTalent = new Button();
    deleteTalent.Text = "x";
    deleteTalent.Click += (sender, e) => buttonClickHandler(numberOfRows);
    deleteTalent.Height = standardHeight;

    balanceTable.Controls.Add(talentName);
    balanceTable.Controls.Add(startValue);
    balanceTable.Controls.Add(endValue);
    balanceTable.Controls.Add(cost);
    balanceTable.Controls.Add(deleteTalent);
    balanceTable.Visible = true;
    balanceTable.RowCount++;
}
</code>```

Any help would be greatly appreciated! :)

答:
Removing complete Table -

```<code>tableLayoutPanel1.Controls.Clear();
tableLayoutPanel1.RowStyles.Clear();
</code>```

Set your Headline of the Table again -

```<code>            tableLayoutPanel.RowCount = 1;
            tableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 20F));
            tableLayoutPanel.Controls.Add(new Label() { Text = "MONTH", Font = new Font("Century Gothic", 12, FontStyle.Bold), ForeColor = Color.LightGray }, 0, tableLayoutPanel.RowCount - 1);
            tableLayoutPanel.Controls.Add(new Label() { Text = "YEAR", Font = new Font("Century Gothic", 12, FontStyle.Bold), ForeColor = Color.LightGray }, 1, tableLayoutPanel.RowCount - 1);
            tableLayoutPanel.Controls.Add(new Label() { Text = "MEASURED WAFERS", Font = new Font("Century Gothic", 12, FontStyle.Bold), ForeColor = Color.LightGray }, 2, tableLayoutPanel.RowCount - 1);
</code>```

3 Columns - 1 Row

Maybe someone can use my codesnipped, works proper good...

Body:
I have TableLayoutPanel that I programatically add Rows to. The User basically choses a Property and that is then displayed in the table along with some controls. I think I have a general understanding problem here and I will try to explain it.

One of the Controls in every row is a 'delete'-Button. That button should delete the row it is in. What I did is add an eventhandler to the button and set the current rowcount.

deleteTalent.Click += (sender, e) => buttonClickHandler(numberOfRows);

Code of the handler:

private void buttonClickHandler(int rowCount)
{
    int count = rowCount - 1;
    for (int i = count; i < (count + 5); i++)
    {
        balanceTable.Controls.RemoveAt(count);
    }
    balanceTable.RowStyles.RemoveAt(count);
    balanceTable.RowCount--;

}

I looked at it for hours and played around. But I can't find a working clean solution. I'm also pretty new to C#

Here's the complete Function that creates a new row:

private void addBalanceItems(ToolStripMenuItem item)
{
    int numberOfRows = balanceTable.RowCount;
    if (numberOfRows > 1)
    {
        balanceTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.AutoSize));

    }
    balanceTable.Height = numberOfRows * 45;
    Steigerungsrechner rechner = new Steigerungsrechner();
    string tag = item.Tag.ToString();

    //change that asap :(
    if (tag == "A") { rechner.column = 1; }
    if (tag == "B") { rechner.column = 2; }
    if (tag == "C") { rechner.column = 3; }
    if (tag == "D") { rechner.column = 4; }
    if (tag == "E") { rechner.column = 5; }
    if (tag == "F") { rechner.column = 6; }
    if (tag == "G") { rechner.column = 7; }
    if (tag == "H") { rechner.column = 8; }

    Label talentName = new Label();
    talentName.Text = item.Text;
    talentName.Height = standardHeight;
    talentName.TextAlign = ContentAlignment.MiddleLeft;
    talentName.AutoSize = true;
    Label cost = new Label();
    cost.TextChanged += (sender, e) => costChangeHandler(cost);
    cost.Height = standardHeight;
    cost.TextAlign = ContentAlignment.MiddleLeft;
    TextBox startValue = new TextBox();
    startValue.TextChanged += (sender, e) => startValueChangeHandler(rechner, startValue, cost);
    startValue.Height = standardHeight;
    startValue.TextAlign = HorizontalAlignment.Center;
    TextBox endValue = new TextBox();
    endValue.TextChanged += (sender, e) => endValueChangeHandler(rechner, endValue, cost);
    endValue.Height = standardHeight;
    endValue.TextAlign = HorizontalAlignment.Center;
    Button deleteTalent = new Button();
    deleteTalent.Text = "x";
    deleteTalent.Click += (sender, e) => buttonClickHandler(numberOfRows);
    deleteTalent.Height = standardHeight;

    balanceTable.Controls.Add(talentName);
    balanceTable.Controls.Add(startValue);
    balanceTable.Controls.Add(endValue);
    balanceTable.Controls.Add(cost);
    balanceTable.Controls.Add(deleteTalent);
    balanceTable.Visible = true;
    balanceTable.RowCount++;
}

Any help would be greatly appreciated! :)

Body:
Removing complete Table -

tableLayoutPanel1.Controls.Clear();
tableLayoutPanel1.RowStyles.Clear();

Set your Headline of the Table again -

            tableLayoutPanel.RowCount = 1;
            tableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 20F));
            tableLayoutPanel.Controls.Add(new Label() { Text = "MONTH", Font = new Font("Century Gothic", 12, FontStyle.Bold), ForeColor = Color.LightGray }, 0, tableLayoutPanel.RowCount - 1);
            tableLayoutPanel.Controls.Add(new Label() { Text = "YEAR", Font = new Font("Century Gothic", 12, FontStyle.Bold), ForeColor = Color.LightGray }, 1, tableLayoutPanel.RowCount - 1);
            tableLayoutPanel.Controls.Add(new Label() { Text = "MEASURED WAFERS", Font = new Font("Century Gothic", 12, FontStyle.Bold), ForeColor = Color.LightGray }, 2, tableLayoutPanel.RowCount - 1);

3 Columns - 1 Row

Maybe someone can use my codesnipped, works proper good...