问:
django-rest-swagger can't seem to work for me. I can't get it to document anything beyond a title
It seems like django-rest-swagger dropped support for the YAML documentation, and replaced it with a vague non-documented way to do things. I've spent the last 48 hours trying to understand how I can have it document the parameters that go into my post methods.

For instance: I have this:

```<code>class user_addresses(APIView):
    """
    get all addresses or post a new one
    """
    authentication_classes = ([JSONWebTokenAuthentication])

    def get(self, request, format=None):
        addresses = Address.objects.filter(owner_id=request.user.id)
        print (addresses)
        serializer = address_serializer(addresses, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = address_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({'success': True,
                            'result': serializer.validated_data},
                            status=status.HTTP_201_CREATED)
        return Response({'success': False,
                        'result': serializer.errors},
                        status=status.HTTP_400_BAD_REQUEST)
</code>```

But the django-rest-swagger will show it as:

Can someone point me in the direction of something that works where I can define all the rich data that swagger allows, like the post field names, if they're mandatory or not. etc. i'm just going crazy here running in circle and can't find anything but complaints that there's no way to do this.

答:
So the idea with the 2.0 update was to use CoreAPI, the "internal" rest framework schema generation, and from it generate the swagger spec.

CoreAPI uses serializer and view classes to do its thing. From serializers it knows what fields are required, what type are those fields and if you want to add your personal description you can do so with help_text parameter:

```<code>some_field = serializers.Field(help_text='Field description')
</code>```

In your case, the problem will be that it won't be able to understand the relationship between the APIView and your serializer. I suggest to take an extra step and move to generic views or viewsets, all of them support serializer_class attribute that can be used for the introspection. For your example something like this should work:

```<code># serializer
class AddressSerializer(serializers.ModelSerializer):

    line1 = serializers.CharField(help_text='Field documentation!')

    class Meta:
        model = Address
        fields = '__all__'
        read_only_fields = 'owner',

    def create(self, validated_data):
        validated_data['owner'] = self.context['request'].user
        return super().create(validated_data)

# api class-based view
class UserAddresses(generics.ListCreateAPIView):
    """
    General API documentation (not wisible in the swagger view)

    get:
    GET-specific documentation!

    Lorem ipsum

    post:
    POST-specific documentation!

    Dolor **sit amet**
    """
    authentication_classes = ([JSONWebTokenAuthentication])
    permission_classes = permissions.IsAuthenticated,
    serializer_class = AddressSerializer

    def get_queryset(self):
        return Address.objects.filter(owner_id=self.request.user.id)
</code>```

For views there is a specific docstirng format, it's very simple and hopefully, will improve overtime. In any way, you should have a bit more acceptable result now:

Body:
It seems like django-rest-swagger dropped support for the YAML documentation, and replaced it with a vague non-documented way to do things. I've spent the last 48 hours trying to understand how I can have it document the parameters that go into my post methods.

For instance: I have this:

class user_addresses(APIView):
    """
    get all addresses or post a new one
    """
    authentication_classes = ([JSONWebTokenAuthentication])

    def get(self, request, format=None):
        addresses = Address.objects.filter(owner_id=request.user.id)
        print (addresses)
        serializer = address_serializer(addresses, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = address_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({'success': True,
                            'result': serializer.validated_data},
                            status=status.HTTP_201_CREATED)
        return Response({'success': False,
                        'result': serializer.errors},
                        status=status.HTTP_400_BAD_REQUEST)

But the django-rest-swagger will show it as:

Can someone point me in the direction of something that works where I can define all the rich data that swagger allows, like the post field names, if they're mandatory or not. etc. i'm just going crazy here running in circle and can't find anything but complaints that there's no way to do this.

Body:
So the idea with the 2.0 update was to use CoreAPI, the "internal" rest framework schema generation, and from it generate the swagger spec.

CoreAPI uses serializer and view classes to do its thing. From serializers it knows what fields are required, what type are those fields and if you want to add your personal description you can do so with help_text parameter:

some_field = serializers.Field(help_text='Field description')

In your case, the problem will be that it won't be able to understand the relationship between the APIView and your serializer. I suggest to take an extra step and move to generic views or viewsets, all of them support serializer_class attribute that can be used for the introspection. For your example something like this should work:

# serializer
class AddressSerializer(serializers.ModelSerializer):

    line1 = serializers.CharField(help_text='Field documentation!')

    class Meta:
        model = Address
        fields = '__all__'
        read_only_fields = 'owner',

    def create(self, validated_data):
        validated_data['owner'] = self.context['request'].user
        return super().create(validated_data)

# api class-based view
class UserAddresses(generics.ListCreateAPIView):
    """
    General API documentation (not wisible in the swagger view)

    get:
    GET-specific documentation!

    Lorem ipsum

    post:
    POST-specific documentation!

    Dolor **sit amet**
    """
    authentication_classes = ([JSONWebTokenAuthentication])
    permission_classes = permissions.IsAuthenticated,
    serializer_class = AddressSerializer

    def get_queryset(self):
        return Address.objects.filter(owner_id=self.request.user.id)

For views there is a specific docstirng format, it's very simple and hopefully, will improve overtime. In any way, you should have a bit more acceptable result now:


来源: stackexchange

问:
Array number that are multiples of 3
I need to get all number that multiples of 3.
Can someone help me to write it?  Here is what I have so far:</p>

```<code>int[] myList = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };

public class Main {
public static void main(String[] args) {
    int[] myList = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };
    int share = myList[0];
    for (int i / 3; i / myList.length;) {

        }
    }
    System.out.println(i / 3 );

}

}
</code>```

答:
:) You are definitely new to this.

To begin with you need to disclose what the share variable is possibly used for.

Next you need learn how to properly iterate through your Integer Array.

You will also need to learn about the Modulus Operator (%) and how to utilize the IF statement within a FOR loop.

You will also need to learn how to display a Integer Array Element within the system Console. This would nomaly be done within your FOR loop.

Or if you're lucky....some clown will do your homework for you.

ContentLicense: CC BY-SA 3.0

Title: Array number that are multiples of 3

Body:
I need to get all number that multiples of 3.
Can someone help me to write it?  Here is what I have so far:

int[] myList = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };

public class Main {
public static void main(String[] args) {
    int[] myList = { 1, 2, 3, 4, 5, 6, 7, 8, 9, };
    int share = myList[0];
    for (int i / 3; i / myList.length;) {

        }
    }
    System.out.println(i / 3 );

}

}


问:
How to dynamically filter a select2 listing based on option class
I have a dropdown select of optional 'opportunities' (id="opportunities" in the example below) which I enhance using the select2 jquery plugin, and wish to dynamically filter this list in order to reduce the possible options presented to a user using a 2nd select dropdown (id="group-select" in the example below),

```<code><label>
  Select an opportunity<br>
  <select id="opportunities" style="width:300px;" multiple="multiple" name="selected-opps" value="">
    <optgroup label="Class A">
      <option class="group-1" value="1a">Opportunity 1a</option>
      <option class="group-2" value="2a">Opportunity 2a</option>
    </optgroup>
    <optgroup label="Class B">
      <option class="group-1" value="1b">Opportunity 1b</option>
      <option class="group-2" value="2b">Opportunity 2b</option>
    </optgroup>
    <optgroup label="Class C">
      <option class="group-1" value="1c">Opportunity 1c</option>
      <option class="group-2" value="2c">Opportunity 2c</option>
    </optgroup>
  </select>
</label>
<select id="group-select">
  <option value="">Select a group</option>
  <option value="group-1">group 1</option>
  <option value="group-2">group 2</option>
</select>
</div>
<div id="select-opportunity"></div>
<script type="text/javascript">
(function( $ ) {
  'use strict';

   var opportunities = $('select#opportunities').select2({
    dropdownParent: $('#select-opportunity')
  });
})( jQuery );
</script>
</code>```

I wish to be able to make a selection in the 2nd select, say 'group 1' and would like the select2 list to contain only 'group-1' items as per the option in the first select dropdown that have the grouo-1 class attribute.

答:
ّshort Example .

```<code>window.templateResult = function templateResult(state) {
            if (state.text.indexOf('ss') == -1)
                return null;///hide

            if (!state.id) { return state.text; }
            var $state = $(
              '<span>' + state.text + '</span>'
            );
            return $state;
        };

        //Init
        $("#select1").select2({
            templateResult: templateResult
        });
</code>```

ّFull Example below.

$(document).ready(function () {

            //general custom filter
            window.Select2FilterFunc = function (state) { return "Default" };

            //general custom templateResult
            window.templateResult = function templateResult(state) {

                //call custom filter
                var result = Select2FilterFunc(state);
                if (result != "Default")
                    return result;

                if (!state.id) { return state.text; }
                var $state = $(
                  '' + state.text + ''
                );
                return $state;
            };

            //Init
            $("#select1").select2({
                templateResult: templateResult
            });

            //Add Custom Filter when  opening
            $('#select1').on('select2:opening', function (evt) {

                //set your filter
                window.Select2FilterFunc = function (state) {
                    if (state.text.indexOf('ss') == -1)
                        return null;//hide item
                    else
                        return "Default";
                };

            }).on('select2:close', function (evt) {
                window.Select2FilterFunc = function (state) { return "Default" };
            });

        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<select id="select1" class="js-states form-control" style="width:300px" multiple="multiple ">
        <optgroup label="Alaskan/Hawaiian Time Zone">
            <option value="AK" title="11111111">Alaska</option>
            <option value="HI" title="2222">Hawaii </option>
        </optgroup>
        <optgroup label="Pacific Time Zone">
            <option value="CA">California</option>
            <option value="NV">Nevada</option>
            <option value="OR">Oregon</option>
            <option value="WA">Washington</option>
        </optgroup>
        <optgroup label="Mountain Time Zone">
            <option value="AZ">Arizona</option>
            <option value="CO">Colorado</option>
            <option value="ID">Idaho</option>
            <option value="MT">Montana</option>
            <option value="NE">Nebraska</option>
            <option value="NM">New Mexico</option>
            <option value="ND">North Dakota</option>
            <option value="UT">Utah</option>
            <option value="WY">Wyoming</option>
        </optgroup>
        <optgroup label="Central Time Zone">
            <option value="AL">Alabama</option>
            <option value="AR">Arkansas</option>
            <option value="IL">Illinois</option>
            <option value="IA">Iowa</option>
            <option value="KS">Kansas</option>
            <option value="KY">Kentucky</option>
            <option value="LA">Louisiana</option>
            <option value="MN">Minnesota</option>
            <option value="MS">Mississippi</option>
            <option value="MO">Missouri</option>
            <option value="OK">Oklahoma</option>
            <option value="SD">South Dakota</option>
            <option value="TX">Texas</option>
            <option value="TN">Tennessee</option>
            <option value="WI">Wisconsin</option>
        </optgroup>
        <optgroup label="Eastern Time Zone">
            <option value="CT">Connecticut</option>
            <option value="DE">Delaware</option>
            <option value="FL">Florida</option>
            <option value="GA">Georgia</option>
            <option value="IN">Indiana</option>
            <option value="ME">Maine</option>
            <option value="MD">Maryland</option>
            <option value="MA">Massachusetts</option>
            <option value="MI">Michigan</option>
            <option value="NH">New Hampshire</option>
            <option value="NJ">New Jersey</option>
            <option value="NY">New York</option>
            <option value="NC">North Carolina</option>
            <option value="OH">Ohio</option>
            <option value="PA">Pennsylvania</option>
            <option value="RI">Rhode Island</option>
            <option value="SC">South Carolina</option>
            <option value="VT">Vermont</option>
            <option value="VA">Virginia</option>
            <option value="WV">West Virginia</option>
        </optgroup>
    </select></code>```

Body:
I have a dropdown select of optional 'opportunities' (id="opportunities" in the example below) which I enhance using the select2 jquery plugin, and wish to dynamically filter this list in order to reduce the possible options presented to a user using a 2nd select dropdown (id="group-select" in the example below),

  Select an opportunity

  <select id="opportunities" style="width:300px;" multiple="multiple" name="selected-opps" value="">
    <optgroup label="Class A">
      <option class="group-1" value="1a">Opportunity 1a</option>
      <option class="group-2" value="2a">Opportunity 2a</option>
    </optgroup>
    <optgroup label="Class B">
      <option class="group-1" value="1b">Opportunity 1b</option>
      <option class="group-2" value="2b">Opportunity 2b</option>
    </optgroup>
    <optgroup label="Class C">
      <option class="group-1" value="1c">Opportunity 1c</option>
      <option class="group-2" value="2c">Opportunity 2c</option>
    </optgroup>
  </select>

<select id="group-select">
  <option value="">Select a group</option>
  <option value="group-1">group 1</option>
  <option value="group-2">group 2</option>
</select>

I wish to be able to make a selection in the 2nd select, say 'group 1' and would like the select2 list to contain only 'group-1' items as per the option in the first select dropdown that have the grouo-1 class attribute.

Body:
ّshort Example .

window.templateResult = function templateResult(state) {
            if (state.text.indexOf('ss') == -1)
                return null;///hide

            if (!state.id) { return state.text; }
            var $state = $(
              '<span>' + state.text + '</span>'
            );
            return $state;
        };

        //Init
        $("#select1").select2({
            templateResult: templateResult
        });

ّFull Example below.

$(document).ready(function () {

            //general custom filter
            window.Select2FilterFunc = function (state) { return "Default" };

            //general custom templateResult
            window.templateResult = function templateResult(state) {

                //call custom filter
                var result = Select2FilterFunc(state);
                if (result != "Default")
                    return result;

                if (!state.id) { return state.text; }
                var $state = $(
                  '<span>' + state.text + '</span>'
                );
                return $state;
            };

            //Init
            $("#select1").select2({
                templateResult: templateResult
            });

            //Add Custom Filter when  opening
            $('#select1').on('select2:opening', function (evt) {

                //set your filter
                window.Select2FilterFunc = function (state) {
                    if (state.text.indexOf('ss') == -1)
                        return null;//hide item
                    else
                        return "Default";
                };

            }).on('select2:close', function (evt) {
                window.Select2FilterFunc = function (state) { return "Default" };
            });

        });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<select id="select1" class="js-states form-control" style="width:300px" multiple="multiple ">
        <optgroup label="Alaskan/Hawaiian Time Zone">
            <option value="AK" title="11111111">Alaska</option>
            <option value="HI" title="2222">Hawaii </option>
        </optgroup>
        <optgroup label="Pacific Time Zone">
            <option value="CA">California</option>
            <option value="NV">Nevada</option>
            <option value="OR">Oregon</option>
            <option value="WA">Washington</option>
        </optgroup>
        <optgroup label="Mountain Time Zone">
            <option value="AZ">Arizona</option>
            <option value="CO">Colorado</option>
            <option value="ID">Idaho</option>
            <option value="MT">Montana</option>
            <option value="NE">Nebraska</option>
            <option value="NM">New Mexico</option>
            <option value="ND">North Dakota</option>
            <option value="UT">Utah</option>
            <option value="WY">Wyoming</option>
        </optgroup>
        <optgroup label="Central Time Zone">
            <option value="AL">Alabama</option>
            <option value="AR">Arkansas</option>
            <option value="IL">Illinois</option>
            <option value="IA">Iowa</option>
            <option value="KS">Kansas</option>
            <option value="KY">Kentucky</option>
            <option value="LA">Louisiana</option>
            <option value="MN">Minnesota</option>
            <option value="MS">Mississippi</option>
            <option value="MO">Missouri</option>
            <option value="OK">Oklahoma</option>
            <option value="SD">South Dakota</option>
            <option value="TX">Texas</option>
            <option value="TN">Tennessee</option>
            <option value="WI">Wisconsin</option>
        </optgroup>
        <optgroup label="Eastern Time Zone">
            <option value="CT">Connecticut</option>
            <option value="DE">Delaware</option>
            <option value="FL">Florida</option>
            <option value="GA">Georgia</option>
            <option value="IN">Indiana</option>
            <option value="ME">Maine</option>
            <option value="MD">Maryland</option>
            <option value="MA">Massachusetts</option>
            <option value="MI">Michigan</option>
            <option value="NH">New Hampshire</option>
            <option value="NJ">New Jersey</option>
            <option value="NY">New York</option>
            <option value="NC">North Carolina</option>
            <option value="OH">Ohio</option>
            <option value="PA">Pennsylvania</option>
            <option value="RI">Rhode Island</option>
            <option value="SC">South Carolina</option>
            <option value="VT">Vermont</option>
            <option value="VA">Virginia</option>
            <option value="WV">West Virginia</option>
        </optgroup>
    </select>


问:
Having issues using proper syntax for multidimensional arrays in PHP?
There are a multitude of similar questions like this one -- I've read nearly all of them on Stack and haven't been able to wrap my head around it.

I'm decoding a json file using CURL. The URL I'm retrieving contents from is https://api.mojang.com/user/profiles/e6e37a93864f496383ba362df30f4792/names.

After I convert the array to a PHP array correctly, I'm attempting to return the last item in the PHP array.

I've attempted to use array_pop but I couldn't get it to work. I resorted to counting the total rows in the array, and referencing that last row using the count.

```<code>    $data = json_decode($output);

    $count = count($data);

    return $data[$count]['name'];`
</code>```

I've even attempted to do

```<code>    return $data[$count]['name']->name; // OR...

    return $data[$count]->name;
</code>```

This is because

```<code>    return $data[0]->name;
</code>```

returns "Eli_Silveraxe", a value from the array, but not the last value. None of these options have worked for me, and it's only become more frustrating because I can return Eli_Silveraxe, but not "Malfunction", which is what SHOULD be returning.

Can you please help?

答:
try this please</p>

```<code>$data = json_decode($output, true);
$count = count($data) - 1;
return $data[$count]['name'];
</code>```

Body:
There are a multitude of similar questions like this one -- I've read nearly all of them on Stack and haven't been able to wrap my head around it.

I'm decoding a json file using CURL. The URL I'm retrieving contents from is https://api.mojang.com/user/profiles/e6e37a93864f496383ba362df30f4792/names.

After I convert the array to a PHP array correctly, I'm attempting to return the last item in the PHP array.

I've attempted to use array_pop but I couldn't get it to work. I resorted to counting the total rows in the array, and referencing that last row using the count.

    $data = json_decode($output);

    $count = count($data);

    return $data[$count]['name'];`

I've even attempted to do

    return $data[$count]['name']->name; // OR...

    return $data[$count]->name;

This is because

    return $data[0]->name;

returns "Eli_Silveraxe", a value from the array, but not the last value. None of these options have worked for me, and it's only become more frustrating because I can return Eli_Silveraxe, but not "Malfunction", which is what SHOULD be returning.

Can you please help?

Body:
try this please

$data = json_decode($output, true);
$count = count($data) - 1;
return $data[$count]['name'];


问:
Google Maps API Marker Clusterer Change Level Size
I'm trying to change level size of Google Maps API Marker Clusterer.
For default, the marker small size (blue icon/m1): 2-9 markers, medium level size (yellow icon/m2): 10-100 markers, big level (red icon/m3) size: 101-250 markers. (correct Me if I wrong).

I want to change the value of level size smaller than default. I have found another thread with same topic but I still didn't get clearly point.

This is the Google Maps API Marker Cluster icon I meant:

Google Maps API Marker Clusterer Icon

PS: I didn't mention about how to change clusterer icon, I meant how to change value of size. Ex: How I can change the level size of marker so it will be clustered to blue (m1), yellow (m2), and red(m3)? The default size like I mentioned before, for m1 it's contain of 2-9 markers, can I change the size value to 2-5 markers only?

答:
You need to create a custom Calculator function.  From the source (of the version referenced in Google's documentation, be sure to verify with the documentation of the version you are using, which you didn't provide).  The default calculator function:

```<code>/**
 *  The function for calculating the cluster icon image.
 *
 *  @param {Array.<google.maps.Marker>} markers The markers in the clusterer.
 *  @param {number} numStyles The number of styles available.
 *  @return {Object} A object properties: 'text' (string) and 'index' (number).
 *  @private
 */
MarkerClusterer.prototype.calculator_ = function(markers, numStyles) {
  var index = 0;
  var count = markers.length;
  var dv = count;
  while (dv !== 0) {
    dv = parseInt(dv / 10, 10);
    index++;
  }

  index = Math.min(index, numStyles);
  return {
    text: count,
    index: index
  };
};
</code>```

The function to set it (which describes its return value, the index is the index into the array of icons, the text is the text to display on the cluster):

```<code>/**
 * Set the calculator function.
 *
 * @param {function(Array, number)} calculator The function to set as the
 *     calculator. The function should return a object properties:
 *     'text' (string) and 'index' (number).
 *
 */
MarkerClusterer.prototype.setCalculator = function(calculator) {
  this.calculator_ = calculator;
};
</code>```

Body:
You need to create a custom Calculator function.  From the source (of the version referenced in Google's documentation, be sure to verify with the documentation of the version you are using, which you didn't provide).  The default calculator function:

/**
 *  The function for calculating the cluster icon image.
 *
 *  @param {Array.<google.maps.Marker>} markers The markers in the clusterer.
 *  @param {number} numStyles The number of styles available.
 *  @return {Object} A object properties: 'text' (string) and 'index' (number).
 *  @private
 */
MarkerClusterer.prototype.calculator_ = function(markers, numStyles) {
  var index = 0;
  var count = markers.length;
  var dv = count;
  while (dv !== 0) {
    dv = parseInt(dv / 10, 10);
    index++;
  }

  index = Math.min(index, numStyles);
  return {
    text: count,
    index: index
  };
};

The function to set it (which describes its return value, the index is the index into the array of icons, the text is the text to display on the cluster):

/**
 * Set the calculator function.
 *
 * @param {function(Array, number)} calculator The function to set as the
 *     calculator. The function should return a object properties:
 *     'text' (string) and 'index' (number).
 *
 */
MarkerClusterer.prototype.setCalculator = function(calculator) {
  this.calculator_ = calculator;
};


问:
Silent rewrite / redirect with subdomain .htaccess
I have structure:

```<code>public/test1
public/test1/a
public/test1/b

public/test2
public/test2/a
public/test2/b
</code>```

I want to rewrite / redirect as below:

```<code>test1.domain.com -> redirect to -> domain.com/test1 and user see -> test1.domain.com

test1.domain.com/a -> redirect to -> domain.com/test1/a and user see -> test1.domain.com/a

test2.domain.com -> redirect to -> domain.com/test2 and user see -> test2.domain.com

test2.domain.com/a -> redirect to -> domain.com/test2/a and user see -> test2.domain.com/a
</code>```

All redirect / rewrite is silent. How can i solve it?

答:
If the host names are served by the same http server, then you can use internal rewriting capturing the first token of the requested host name by means of a condition:

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.org$
RewriteRule ^/?(.*)$ /%1/$1 [END]
</code>```

If you operate a really old version of the apache http server then you may have to replace the END flag with the L flag which should also work in this case. Try that if you run into an http status 500 (server internal error). You also definitely should monitor your http servers error log file in such a case.

If instead those two host names are not served by the same http server that serves the shorter domain name, then probably the best approach is to use the builtin proxy module to internally relay the requests to that server.

And a general hint: you should always prefer to place such rules inside the http servers (virtual) host configuration instead of using dynamic configuration files (.htaccess style files). Those files are notoriously error prone, hard to debug and they really slow down the server. They are only provided as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).

Body:
I have structure:

public/test1
public/test1/a
public/test1/b

public/test2
public/test2/a
public/test2/b

I want to rewrite / redirect as below:

test1.domain.com -> redirect to -> domain.com/test1 and user see -> test1.domain.com

test1.domain.com/a -> redirect to -> domain.com/test1/a and user see -> test1.domain.com/a

test2.domain.com -> redirect to -> domain.com/test2 and user see -> test2.domain.com

test2.domain.com/a -> redirect to -> domain.com/test2/a and user see -> test2.domain.com/a

All redirect / rewrite is silent. How can i solve it?

Body:
If the host names are served by the same http server, then you can use internal rewriting capturing the first token of the requested host name by means of a condition:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.org$
RewriteRule ^/?(.*)$ /%1/$1 [END]

If you operate a really old version of the apache http server then you may have to replace the END flag with the L flag which should also work in this case. Try that if you run into an http status 500 (server internal error). You also definitely should monitor your http servers error log file in such a case.

If instead those two host names are not served by the same http server that serves the shorter domain name, then probably the best approach is to use the builtin proxy module to internally relay the requests to that server.

And a general hint: you should always prefer to place such rules inside the http servers (virtual) host configuration instead of using dynamic configuration files (.htaccess style files). Those files are notoriously error prone, hard to debug and they really slow down the server. They are only provided as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).


问:
What are the best keyboard macros for programming in windows?
I like putting shortcuts of the form "g - google.lnk" in my start menu so google is two keystrokes away. Win, g.

My eight or so most frequent applications go there.

I also make links to my solution files I am always opening "x - Popular Project.lnk"

Are there any better ways to automate opening frequently used applications?

答: Get a keyboard launcher program like Launchy</p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: EBGreen


问:
Setting SDK version fallback resource values in UWP
My application is compiling against Windows Creators Update (15063), but is supposed to run on a minimum version of 10586; however, some colour resources we used seem to be missing on old versions.

The exact whereabouts of failing resources are unknown (as the incompatible resources are), so temporarily, I want to give a global fallback value to eliminate crashes on old SDKs.

Is there any programmatic C# or automatic XAML way I can do it?

答: You could check whether certain features are available at runtime. There are many ways how to achieve that. You can read more about how to write version adaptive code for example here and here.</p>


问:
Why is EmojiCompat only available on Android 19+?
While many of the new support library 26 features are Android 14+, the EmojiCompat is only available on Android 19+. Does anyone know why (technically)?

It seems that EmojiCompat uses a downloadable fonts (which are available on 14+).

https://developer.android.com/preview/features/emoji-compat.html

答: Support for multicolor fonts (necessary for colored Emoji) was only added in Android 4.4 (API 19). EmojiCompat doesn't change the way Emoji are rendered. It merely provides the OS with a font containing Emoji images not shipped with the platform.</p>


问:
Associated Data Not Returned From Apollo to Client?
Here's relevant Apollo code. (Many database fields have been omitted to make it faster/easier to read this post.)

CONNECTORS

```<code>const userAccountsDataModel = db.define('userAccountsData', {
    id: {type: Sequelize.STRING, primaryKey: true},
    picture_medium: {type: Sequelize.STRING}
});

const associatesDataModel =  db.define('associatesData', {
    _id: {type: Sequelize.STRING, primaryKey: true},
    first_name: {type: Sequelize.STRING},
    last_name: {type: Sequelize.STRING},
    userID: {type: Sequelize.STRING},
});

associatesDataModel.belongsTo(userAccountsDataModel, {foreignKey: 'userID'});
</code>```

SCHEMA

```<code>type userAccountsData {
    id: String
    picture_medium: String
}

type associatesData {
    _id: String
    first_name: String
    last_name: String
    userID: String
    userAccountsData: [userAccountsData]
}
</code>```

QUERY

```<code>const GETONEASSOCIATE_QUERY = gql`
query getOneAssociate($_id: String!) {
  getOneAssociate(_id: $_id) {
    _id
    first_name
    last_name
    userID
    accountsData{
        id
        picture_medium
      }
  }
} `;
</code>```

RESOLVER

```<code>getOneAssociate(_, args)  {
    console.log('in getOneAssociate');
    var ret = connectors.associatesData.findAll({
        where: args,
        include: [connectors.userAccountsData],
        logging: console.log
    }).then((res) => res.map((item) => item.dataValues));

    return ret;
},
</code>```

Via Sequelize, the resolver generates the following SQL:

```<code>SELECT "associatesData"."_id",
       "associatesData"."first_name",
       "associatesData"."last_name",
       "associatesData"."userID",
       "userAccountsDatum"."id" AS "userAccountsDatum.id",
       "userAccountsDatum"."picture_medium" AS "userAccountsDatum.picture_medium"
FROM "associatesDatas" AS "associatesData"
   LEFT OUTER JOIN "userAccountsData" AS "userAccountsDatum"
                ON "associatesData"."userID" = "userAccountsDatum"."id"
WHERE "associatesData"."_id" = '35';
</code>```

When I run the above SQL in my SQL client, I can see that all the data sought is being returned, including the data from the related "userAccountsData" table.

However, when the data gets to my client code running in javascript the browser, the data from the related table is missing-- the object that should contain it is null.

What am I missing?

Thanks in advance to all for any info!

答:
This turned out to be an anomaly with Sequelize's automatic pluralizing of table names.

By default, Sequelize automatically pluralizes table names. It is supposed to be possible to turn this behavior off by using Sequelize's freezeTableName property. However, per this Sequelize issue post, there are cases in which Sequelize ignores the freezeTableName property and pluralizes (and sometimes singularizes) the table names anyway.

After discovering this I was able to resolve the anomaly by pluralizing the relevant table name and going through all my Apollo code to update the references to this table so that they would be pluralized as well.

Body:
Here's relevant Apollo code. (Many database fields have been omitted to make it faster/easier to read this post.)

CONNECTORS

const userAccountsDataModel = db.define('userAccountsData', {
    id: {type: Sequelize.STRING, primaryKey: true},
    picture_medium: {type: Sequelize.STRING}
});

const associatesDataModel =  db.define('associatesData', {
    _id: {type: Sequelize.STRING, primaryKey: true},
    first_name: {type: Sequelize.STRING},
    last_name: {type: Sequelize.STRING},
    userID: {type: Sequelize.STRING},
});

associatesDataModel.belongsTo(userAccountsDataModel, {foreignKey: 'userID'});

SCHEMA

type userAccountsData {
    id: String
    picture_medium: String
}

type associatesData {
    _id: String
    first_name: String
    last_name: String
    userID: String
    userAccountsData: [userAccountsData]
}

QUERY

const GETONEASSOCIATE_QUERY = gql`
query getOneAssociate($_id: String!) {
  getOneAssociate(_id: $_id) {
    _id
    first_name
    last_name
    userID
    accountsData{
        id
        picture_medium
      }
  }
} `;

RESOLVER

getOneAssociate(_, args)  {
    console.log('in getOneAssociate');
    var ret = connectors.associatesData.findAll({
        where: args,
        include: [connectors.userAccountsData],
        logging: console.log
    }).then((res) => res.map((item) => item.dataValues));

    return ret;
},

Via Sequelize, the resolver generates the following SQL:

SELECT "associatesData"."_id",
       "associatesData"."first_name",
       "associatesData"."last_name",
       "associatesData"."userID",
       "userAccountsDatum"."id" AS "userAccountsDatum.id",
       "userAccountsDatum"."picture_medium" AS "userAccountsDatum.picture_medium"
FROM "associatesDatas" AS "associatesData"
   LEFT OUTER JOIN "userAccountsData" AS "userAccountsDatum"
                ON "associatesData"."userID" = "userAccountsDatum"."id"
WHERE "associatesData"."_id" = '35';

When I run the above SQL in my SQL client, I can see that all the data sought is being returned, including the data from the related "userAccountsData" table.

However, when the data gets to my client code running in javascript the browser, the data from the related table is missing-- the object that should contain it is null.

What am I missing?

Thanks in advance to all for any info!


问:
Issue returning a Hashmap from a TestNg DataProvider
I am pretty new to Java and TestNg.  I have created the below DataProvider to return a hashmap to my test method but it seems to be failing and I can't work out where the issue is.  I am reading an excel file into a hashmap and storing this in the list.  I then want to return the hashmap in the object.

Any advice appreciated

```<code>@DataProvider(name = "DataProvider")
public Object[][] getTestData() throws Exception {
    LogUtil.error("in provider");
    ExcelUtils.setExcelFile("C://testData.xlsx", "Sheet1");

    int rowsUsed = ExcelUtils.getRowUsed();
    int colsUsed = ExcelUtils.getColumns();

    List<HashMap<String, String>> arrayMapList = new ArrayList<>();
    HashMap<String, String> map;

    for (int i = 0; i < rowsUsed; i++) {
        map = new HashMap<>();
        for (int j = 0; j < colsUsed; j++) {
            map.put(ExcelUtils.getCellData(0, j), ExcelUtils.getCellData(i +1, j));
        }

        arrayMapList.add(map);
    }

    Object[][] obj = new Object[rowsUsed][1];

    for (int i = 0; i <arrayMapList.size(); i++) {
        obj[i][0] = arrayMapList.get(i);
    }
    return obj;
}
</code>```

答: If you are saying that adding static property fixed your issue it means that you tried to use data provider from external class. For that case data provider method have to be static. If your test method and data provider are both in the same class static property could be omitted.</p>

Body:
I am pretty new to Java and TestNg.  I have created the below DataProvider to return a hashmap to my test method but it seems to be failing and I can't work out where the issue is.  I am reading an excel file into a hashmap and storing this in the list.  I then want to return the hashmap in the object.

Any advice appreciated

@DataProvider(name = "DataProvider")
public Object[][] getTestData() throws Exception {
    LogUtil.error("in provider");
    ExcelUtils.setExcelFile("C://testData.xlsx", "Sheet1");

    int rowsUsed = ExcelUtils.getRowUsed();
    int colsUsed = ExcelUtils.getColumns();

    List<HashMap<String, String>> arrayMapList = new ArrayList<>();
    HashMap<String, String> map;

    for (int i = 0; i < rowsUsed; i++) {
        map = new HashMap<>();
        for (int j = 0; j < colsUsed; j++) {
            map.put(ExcelUtils.getCellData(0, j), ExcelUtils.getCellData(i +1, j));
        }

        arrayMapList.add(map);
    }

    Object[][] obj = new Object[rowsUsed][1];

    for (int i = 0; i <arrayMapList.size(); i++) {
        obj[i][0] = arrayMapList.get(i);
    }
    return obj;
}


问:
How do I enable color when running RSpec through RStakeout?
When using topfunky's RStakeout, the color in the result of the spec command is lost. This happens even when adding the --color flag.

答: I was able to get it to work with --tty in my .rspec file (use Rails 3.0.3 and rspec 2.3). I think it's --autotest for older version of 2.0. After an hour of searching, found it here - https://github.com/tomas-stefano/infinity_test

OwnerDisplayName: Chris Lloyd


问:
Constructor overloads to accept any function
I am attempting to create a class template whose constructor(s) can take any kind of function as argument, that is, it takes a function pointer (which can be a member function pointer) and the corresponding function arguments. Additionally, there should be a static_assert that checks whether the function return type (taken from the function pointer) matches the class template parameter type. Thus, the code should look something like this:

```<code>template <class ReturnType>
struct Bar
{
    template <class RetType, class ... ParamType>
    Bar<ReturnType>(RetType (* func)(ParamType ...), ParamType && ... args) :
        package_(std::bind(func, std::forward<ParamType>(args) ...)),
        function_([this] { package_(); }),
        future_(package_.get_future())
    {
        static_assert(std::is_same<ReturnType, RetType>::value,
            "Type mismatch between class parameter type and constructor parameter type");
    }

    template <class RetType, class ObjType, class ... ParamType>
    Bar<ReturnType>(RetType (ObjType::* func)(ParamType ...), ObjType * obj, ParamType && ... args) :
        package_(std::bind(func, obj, std::forward<ParamType>(args) ...)),
        function_([this] { package_(); }),
        future_(package_.get_future())
    {
        static_assert(std::is_same<ReturnType, RetType>::value,
            "Type mismatch between class parameter type and constructor parameter type");
    }

    std::packaged_task<ReturnType()> package_;
    std::function<void()> function_;
    std::future<ReturnType> future_;
};
</code>```

The idea is that the code compiles for these situations, and allows for Bar::function_ to be called (through the function call operator) without errors:

```<code>struct Foo
{
    int foo(int i) {
        return i;
    }

    int foo() {
        return 1;
    }
};

int foo(int i)
{
    return i;
}

int foo()
{
    return 1;
}

int main()
{
    Foo f = Foo();

    Bar<int> b1(&Foo::foo, &f, 1);
    Bar<int> b2(&Foo::foo, &f);
    Bar<int> b3(foo, 1);
    Bar<int> b4(foo);

    return 0;
}
</code>```

Unfortunately, I have close to zero experience with template metaprogramming, and even though I have ran over several questions here in SO, and attempted several ways of solving my problem, such as using a more generalized approach to the constructor

```<code>template <class RetType, class ... ParamType>
Bar<ReturnType>(RetType func, ParamType && ... args)
</code>```

and combining it with type_traits to determine the return type), I have yet to find a way to make this work. What changes can I do to the constructor(s) that allow this functionality?

Edit:

max66's answer solved my original problem, however, a new one arose, which I hadn't considered in the previous question. I also want to be able to pass variables to the constructor, like so:

```<code>int main()
{
    Foo f = Foo();
    int i = 1;

    Bar<int> b1(&Foo::foo, &f, i); // Error
    Bar<int> b2(&Foo::foo, &f, 1); // Ok
    Bar<int> b3(&Foo::foo, &f); // Ok
    Bar<int> b4(foo, i); // Error
    Bar<int> b5(foo, 1); // Ok
    Bar<int> b6(foo); // Ok

    return 0;
}
</code>```

however, as it is, a compiler error shows up in the cases marked with Error. I am guessing this is because the parameter func in the constructor uses ParamType to determine its type (which doesn't match with the actual ParamTypes in the case of b1 and b4), but I have no idea how to solve this...

答:
Sorry but... if you want that the return type of the funtion is equal to the template parameter of the class... why don't you simply impose it?

I mean... you can use ReturnType instead of RetType, as follows

```<code>template <typename ReturnType>
struct Bar
{
    template <typename ... ParamType>
    Bar<ReturnType> (ReturnType (*func)(ParamType ...), ParamType && ... args)
      : package_(std::bind(func, std::forward<ParamType>(args) ...)),
        function_([this] { package_(); }),
        future_(package_.get_future())
     { }

    template <typename ObjType, typename ... ParamType>
    Bar<ReturnType> (ReturnType (ObjType::* func)(ParamType ...),
                     ObjType * obj, ParamType && ... args)
      : package_(std::bind(func, obj, std::forward<ParamType>(args) ...)),
        function_([this] { package_(); }),
        future_(package_.get_future())
     { }
</code>```

-- EDIT --

To solve the second problem, IF your not interested in moving parameters, you can throw away std::forward and &&, and simply write

```<code>template <typename ReturnType>
struct Bar
{
    template <typename ... ParamType>
    Bar<ReturnType> (ReturnType (*func)(ParamType ...),
                     ParamType const & ... args)
      : package_(std::bind(func, args...)),
        function_([this] { package_(); }),
        future_(package_.get_future())
     { }

    template <typename ObjType, typename ... ParamType>
    Bar<ReturnType> (ReturnType (ObjType::* func)(ParamType ...),
                     ObjType * obj, ParamType const & ... args)
      : package_(std::bind(func, obj, args...)),
        function_([this] { package_(); }),
        future_(package_.get_future())
     { }
</code>```

Body:
I am attempting to create a class template whose constructor(s) can take any kind of function as argument, that is, it takes a function pointer (which can be a member function pointer) and the corresponding function arguments. Additionally, there should be a static_assert that checks whether the function return type (taken from the function pointer) matches the class template parameter type. Thus, the code should look something like this:

template <class ReturnType>
struct Bar
{
    template <class RetType, class ... ParamType>
    Bar<ReturnType>(RetType (* func)(ParamType ...), ParamType && ... args) :
        package_(std::bind(func, std::forward<ParamType>(args) ...)),
        function_([this] { package_(); }),
        future_(package_.get_future())
    {
        static_assert(std::is_same<ReturnType, RetType>::value,
            "Type mismatch between class parameter type and constructor parameter type");
    }

    template <class RetType, class ObjType, class ... ParamType>
    Bar<ReturnType>(RetType (ObjType::* func)(ParamType ...), ObjType * obj, ParamType && ... args) :
        package_(std::bind(func, obj, std::forward<ParamType>(args) ...)),
        function_([this] { package_(); }),
        future_(package_.get_future())
    {
        static_assert(std::is_same<ReturnType, RetType>::value,
            "Type mismatch between class parameter type and constructor parameter type");
    }

    std::packaged_task<ReturnType()> package_;
    std::function<void()> function_;
    std::future<ReturnType> future_;
};

The idea is that the code compiles for these situations, and allows for Bar::function_ to be called (through the function call operator) without errors:

struct Foo
{
    int foo(int i) {
        return i;
    }

    int foo() {
        return 1;
    }
};

int foo(int i)
{
    return i;
}

int foo()
{
    return 1;
}

int main()
{
    Foo f = Foo();

    Bar<int> b1(&Foo::foo, &f, 1);
    Bar<int> b2(&Foo::foo, &f);
    Bar<int> b3(foo, 1);
    Bar<int> b4(foo);

    return 0;
}

Unfortunately, I have close to zero experience with template metaprogramming, and even though I have ran over several questions here in SO, and attempted several ways of solving my problem, such as using a more generalized approach to the constructor

template <class RetType, class ... ParamType>
Bar<ReturnType>(RetType func, ParamType && ... args)

and combining it with type_traits to determine the return type), I have yet to find a way to make this work. What changes can I do to the constructor(s) that allow this functionality?

Edit:

max66's answer solved my original problem, however, a new one arose, which I hadn't considered in the previous question. I also want to be able to pass variables to the constructor, like so:

int main()
{
    Foo f = Foo();
    int i = 1;

    Bar<int> b1(&Foo::foo, &f, i); // Error
    Bar<int> b2(&Foo::foo, &f, 1); // Ok
    Bar<int> b3(&Foo::foo, &f); // Ok
    Bar<int> b4(foo, i); // Error
    Bar<int> b5(foo, 1); // Ok
    Bar<int> b6(foo); // Ok

    return 0;
}

however, as it is, a compiler error shows up in the cases marked with Error. I am guessing this is because the parameter func in the constructor uses ParamType to determine its type (which doesn't match with the actual ParamTypes in the case of b1 and b4), but I have no idea how to solve this...

Body:
Sorry but... if you want that the return type of the funtion is equal to the template parameter of the class... why don't you simply impose it?

I mean... you can use ReturnType instead of RetType, as follows

template <typename ReturnType>
struct Bar
{
    template <typename ... ParamType>
    Bar<ReturnType> (ReturnType (*func)(ParamType ...), ParamType && ... args)
      : package_(std::bind(func, std::forward<ParamType>(args) ...)),
        function_([this] { package_(); }),
        future_(package_.get_future())
     { }

    template <typename ObjType, typename ... ParamType>
    Bar<ReturnType> (ReturnType (ObjType::* func)(ParamType ...),
                     ObjType * obj, ParamType && ... args)
      : package_(std::bind(func, obj, std::forward<ParamType>(args) ...)),
        function_([this] { package_(); }),
        future_(package_.get_future())
     { }

-- EDIT --

To solve the second problem, IF your not interested in moving parameters, you can throw away std::forward and &&, and simply write

template <typename ReturnType>
struct Bar
{
    template <typename ... ParamType>
    Bar<ReturnType> (ReturnType (*func)(ParamType ...),
                     ParamType const & ... args)
      : package_(std::bind(func, args...)),
        function_([this] { package_(); }),
        future_(package_.get_future())
     { }

    template <typename ObjType, typename ... ParamType>
    Bar<ReturnType> (ReturnType (ObjType::* func)(ParamType ...),
                     ObjType * obj, ParamType const & ... args)
      : package_(std::bind(func, obj, args...)),
        function_([this] { package_(); }),
        future_(package_.get_future())
     { }


问:
Android: Center an image
I've got a linear layout and an image...

```<code><?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">

<ImageView android:layout_width="wrap_content" android:id="@+id/imageView1"
 android:src="@drawable/icon" android:layout_height="wrap_content"
 android:scaleType="center"></ImageView>

</LinearLayout>
</code>```

How do I dynamically center my image so that it will appear in the center of the screen on all devices?

答:
Here are 2 ways you can center an image (or images) both vertically and horizontally in LinearLayout.

(1) Use the android:layout_gravity="center" attribute in ImageView

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        layout_height="wrap_content"
        android:src="@drawable/icon"
        android:layout_gravity="center"/>
</LinearLayout>
</code>```

How this works:
the android:layout_gravity="center" attribute in ImageView centers itself (i.e. the image) vertically and horizontally relative to its parent (LinearLayout).

-- OR --

(2) Alternatively, you can use the android:gravity="center" attribute in LinearLayout and omit the android:layout_gravity="center" attribute in ImageView :

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        layout_height="wrap_content"
        android:src="@drawable/icon"
        android:layout_gravity="center"/>
</LinearLayout>
</code>```

How this works: the android:gravity="center" attribute in LinearLayout centers its child/children (in this case, it's the image) vertically and horizontally.

Title: Android: Center an image

Body:
I've got a linear layout and an image...

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">

<ImageView android:layout_width="wrap_content" android:id="@+id/imageView1"
 android:src="@drawable/icon" android:layout_height="wrap_content"
 android:scaleType="center"></ImageView>

</LinearLayout>

How do I dynamically center my image so that it will appear in the center of the screen on all devices?

Body:
Here are 2 ways you can center an image (or images) both vertically and horizontally in LinearLayout.

(1) Use the android:layout_gravity="center" attribute in ImageView

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        layout_height="wrap_content"
        android:src="@drawable/icon"
        android:layout_gravity="center"/>
</LinearLayout>

How this works:
the android:layout_gravity="center" attribute in ImageView centers itself (i.e. the image) vertically and horizontally relative to its parent (LinearLayout).

-- OR --

(2) Alternatively, you can use the android:gravity="center" attribute in LinearLayout and omit the android:layout_gravity="center" attribute in ImageView :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        layout_height="wrap_content"
        android:src="@drawable/icon"
        android:layout_gravity="center"/>
</LinearLayout>

How this works: the android:gravity="center" attribute in LinearLayout centers its child/children (in this case, it's the image) vertically and horizontally.


问:
Trying to add cell value in web data connection url and got error 9
So I have this code in Excel VBA

```<code>Sub myquerie()
Dim mytable As QueryTable
Set mytable = Worksheets("Sheet5").QueryTables("MyQuery")
mytable.Connection = "URL;" & Worksheets("Converter").Cells(12, 4).Text
mytable.Refresh
End Sub
</code>```

And I get error "Subscript out of range" at

```<code>Set mytable = Worksheets("Sheet5").QueryTables("MyQuery")
</code>```

答:
You are getting Subscript Out of Range error because it cannot find that QueryTable. MyQuery is not a QueryTable. It is a ListObject

Any of the below methods can confirm that

```<code>'<~~ These both will give you Subscript out of Range error
?Worksheets("Sheet5").QueryTables(1).Name
?Worksheets("Sheet5").QueryTables.Count
</code>```

To confirm it is a ListObject

```<code>Sub WhatTheHellIsIt()
    Dim LS As ListObject
    Set LS = Sheet4.ListObjects(1)

    MsgBox LS.Name
End Sub
</code>```

EDIT

So what should I do to fix this. I'm not good in vba :/ – Venoox 8 hours ago

Declare it as a ListObject and then work with it. Something like this. Also SOMEVALIDCONNECTION below has to be a valid connection string.

```<code>Sub myquerie()
    Dim mytable As ListObject

    Set mytable = Worksheets("Sheet5").ListObjects("MyQuery")
    mytable.QueryTable.Connection = SOMEVALIDCONNECTION
    mytable.Refresh
End Sub
</code>```

Body:
So I have this code in Excel VBA

Sub myquerie()
Dim mytable As QueryTable
Set mytable = Worksheets("Sheet5").QueryTables("MyQuery")
mytable.Connection = "URL;" & Worksheets("Converter").Cells(12, 4).Text
mytable.Refresh
End Sub

And I get error "Subscript out of range" at

Set mytable = Worksheets("Sheet5").QueryTables("MyQuery")

Body:
You are getting Subscript Out of Range error because it cannot find that QueryTable. MyQuery is not a QueryTable. It is a ListObject

Any of the below methods can confirm that

'<~~ These both will give you Subscript out of Range error
?Worksheets("Sheet5").QueryTables(1).Name
?Worksheets("Sheet5").QueryTables.Count

To confirm it is a ListObject

Sub WhatTheHellIsIt()
    Dim LS As ListObject
    Set LS = Sheet4.ListObjects(1)

    MsgBox LS.Name
End Sub

EDIT

So what should I do to fix this. I'm not good in vba :/ – Venoox 8 hours ago

Declare it as a ListObject and then work with it. Something like this. Also SOMEVALIDCONNECTION below has to be a valid connection string.

Sub myquerie()
    Dim mytable As ListObject

    Set mytable = Worksheets("Sheet5").ListObjects("MyQuery")
    mytable.QueryTable.Connection = SOMEVALIDCONNECTION
    mytable.Refresh
End Sub


问:
Ruby Sinatra - connect to mongoDB on mongoHQ failed
This is just for my weekend project/study, I am very new to Sinatra and MongoDB.

I've installed the gems for mongoDB, such as: mongo, mongo_mapper and mongoid.

When I tried connecting to my database on MongoHQ from localhost, it encountered such an error:

```<code>Mongo::ConnectionFailure at /
failed to connect to any given host:port

    * file: connection.rb
    * location: connect
    * line: 489
</code>```

I found a similar thread on SO, but frankly speaking, I don't quite understand the answers...

Here is my code snippet:

```<code>require 'rubygems'
require 'sinatra'
require 'mongo'
require 'mongo_mapper'

get '/' do
  MongoMapper.connection = Mongo::Connection.new('flame.mongohq.com', 27044)
  MongoMapper.database = 'notes'
  MongoMapper.database.authenticate('foo', 'bar')
  erb :list
end
</code>```

I took the above code from here, but it seems not working...

Which part is wrong? Is there another way to do this? In the end this test web app will be deployed onto heroku, so I hope the solution can work with both localhost and my heroku server.

Updated:

```<code>I just created a minimal code snippet to test the mongodb connection:
require 'rubygems'
require 'mongo'

db = Mongo::Connection.new("flame.mongohq.com", 27044).db("notes")
</code>```

But still got the error, after timeout:

```<code>$ ruby mongodbtest.rb
/Library/Ruby/Gems/1.8/gems/mongo-1.0.8/lib/../lib/mongo/connection.rb:489:in
`connect': failed to connect to any given host:port (Mongo::ConnectionFailure)
from /Library/Ruby/Gems/1.8/gems/mongo-1.0.8/lib/../lib/mongo/connection.rb:137:in
`initialize'
from mongodbtest.rb:4:in `new'
from mongodbtest.rb:4
</code>```

The hostname and port are according to mongoHQ documentation, so they must be right.

Thanks for the help in advance.

2nd Update:

I just tested the mongodb connection string using terminal:

```<code>mongo mongodb://flame.mongohq.com:27044/notes -u foo -p bar
</code>```

Unfortunately this would get me an connection failed error, honestly, I don't know why...

答:
I use

```<code>uri =  URI.parse(ENV['MONGOHQ_URL'])
@mongo_connection = Mongo::Connection.from_uri( uri )
@mongo_db = @mongo_connection.db(uri.path.gsub(/^\//, ''))
@mongo_db.authenticate(uri.user, uri.password)
</code>```

You can look up your mongo url using the heroku config --long command

Body:
This is just for my weekend project/study, I am very new to Sinatra and MongoDB.

I've installed the gems for mongoDB, such as: mongo, mongo_mapper and mongoid.

When I tried connecting to my database on MongoHQ from localhost, it encountered such an error:

Mongo::ConnectionFailure at /
failed to connect to any given host:port

    * file: connection.rb
    * location: connect
    * line: 489

I found a similar thread on SO, but frankly speaking, I don't quite understand the answers...

Here is my code snippet:

require 'rubygems'
require 'sinatra'
require 'mongo'
require 'mongo_mapper'

get '/' do
  MongoMapper.connection = Mongo::Connection.new('flame.mongohq.com', 27044)
  MongoMapper.database = 'notes'
  MongoMapper.database.authenticate('foo', 'bar')
  erb :list
end

I took the above code from here, but it seems not working...

Which part is wrong? Is there another way to do this? In the end this test web app will be deployed onto heroku, so I hope the solution can work with both localhost and my heroku server.

Updated:

I just created a minimal code snippet to test the mongodb connection:
require 'rubygems'
require 'mongo'

db = Mongo::Connection.new("flame.mongohq.com", 27044).db("notes")

But still got the error, after timeout:

$ ruby mongodbtest.rb
/Library/Ruby/Gems/1.8/gems/mongo-1.0.8/lib/../lib/mongo/connection.rb:489:in
`connect': failed to connect to any given host:port (Mongo::ConnectionFailure)
from /Library/Ruby/Gems/1.8/gems/mongo-1.0.8/lib/../lib/mongo/connection.rb:137:in
`initialize'
from mongodbtest.rb:4:in `new'
from mongodbtest.rb:4

The hostname and port are according to mongoHQ documentation, so they must be right.

Thanks for the help in advance.

2nd Update:

I just tested the mongodb connection string using terminal:

mongo mongodb://flame.mongohq.com:27044/notes -u foo -p bar

Unfortunately this would get me an connection failed error, honestly, I don't know why...

Body:
I use

uri =  URI.parse(ENV['MONGOHQ_URL'])
@mongo_connection = Mongo::Connection.from_uri( uri )
@mongo_db = @mongo_connection.db(uri.path.gsub(/^\//, ''))
@mongo_db.authenticate(uri.user, uri.password)

You can look up your mongo url using the heroku config --long command


问:
Showing Month as Columns in SQL Server
I have a Users table that has a CARD_EXPIRY column of datatype DateTime. Now, I want to show my data like this:

```<code>Jan | Feb | Mar | So on.....
--------------------
 2  |  3  |  5  |
</code>```

The number shows number of card expired per month.

Here is what I tried:

```<code>DECLARE @Month TABLE
(
    Id INT,
    Name VARCHAR(10)
);

INSERT INTO @Month (Id, Name)
VALUES (1, 'Jan'), (2, 'Feb'), (3, 'Mar'), (4, 'Apr'), (5, 'May'),
       (6, 'Jun'), (7, 'Jul'), (8, 'Aug'), (9, 'Sep'), (10, 'Oct'),
       (11, 'Nov'), (12, 'Dec');

SELECT COUNT('t'), M.Name
FROM Users U
INNER JOIN @Month M ON M.Id = DATEPART(MONTH, U.CARD_EXPIRY)
WHERE MyCondition
GROUP BY M.Id, M.Name
ORDER BY M.Id
</code>```

But the data is being returned row-wise, like this:

```<code>C       Name
-------------
2764    Jan
3065    Feb
2849    mar
2158    Apr
2503    May
2925    Jun
2109    Jul
1399    Aug
1583    Sep
1820    Oct
1552    Nov
1912    Dec
</code>```

答:
You can use PIVOT, but you also can you group by, for axample:</p>

```<code> SELECT sum(case when DATEPART(MONTH, U.CARD_EXPIRY)=1 then 1 else 0) as Jan
       ,sum(case when DATEPART(MONTH, U.CARD_EXPIRY)=2 then 1 else 0) as Feb
       ,sum(case when DATEPART(MONTH, U.CARD_EXPIRY)=3 then 1 else 0) as mar
  ...................
       ,sum(case when DATEPART(MONTH, U.CARD_EXPIRY)=12 then 1 else 0) as Dec
 FROM Users U
 GROUP BY M.Id, M.Name
</code>```

Title: Showing Month as Columns in SQL Server

Body:
I have a Users table that has a CARD_EXPIRY column of datatype DateTime. Now, I want to show my data like this:

Jan | Feb | Mar | So on.....
--------------------
 2  |  3  |  5  |

The number shows number of card expired per month.

Here is what I tried:

DECLARE @Month TABLE
(
    Id INT,
    Name VARCHAR(10)
);

INSERT INTO @Month (Id, Name)
VALUES (1, 'Jan'), (2, 'Feb'), (3, 'Mar'), (4, 'Apr'), (5, 'May'),
       (6, 'Jun'), (7, 'Jul'), (8, 'Aug'), (9, 'Sep'), (10, 'Oct'),
       (11, 'Nov'), (12, 'Dec');

SELECT COUNT('t'), M.Name
FROM Users U
INNER JOIN @Month M ON M.Id = DATEPART(MONTH, U.CARD_EXPIRY)
WHERE MyCondition
GROUP BY M.Id, M.Name
ORDER BY M.Id

But the data is being returned row-wise, like this:

C       Name
-------------
2764    Jan
3065    Feb
2849    mar
2158    Apr
2503    May
2925    Jun
2109    Jul
1399    Aug
1583    Sep
1820    Oct
1552    Nov
1912    Dec

Body:
You can use PIVOT, but you also can you group by, for axample:

 SELECT sum(case when DATEPART(MONTH, U.CARD_EXPIRY)=1 then 1 else 0) as Jan
       ,sum(case when DATEPART(MONTH, U.CARD_EXPIRY)=2 then 1 else 0) as Feb
       ,sum(case when DATEPART(MONTH, U.CARD_EXPIRY)=3 then 1 else 0) as mar
  ...................
       ,sum(case when DATEPART(MONTH, U.CARD_EXPIRY)=12 then 1 else 0) as Dec
 FROM Users U
 GROUP BY M.Id, M.Name


问:
How to configure MongoDB and nodejs to use two different servers
I want to do the following structure for a website.

The idea is put web app on one server, and put MongoDB on another server. They are different machines.

In nodejs code, the only configuration for db is the following code:

```<code>var connectString = 'mongodb://localhost/myDataBase';
</code>```

Replace 'localhost' with '111.222.111.2', the ip address of the machine where MongoDB is running on, then it should work. Is this correct?

Will this make data retrieval slower comparing with putting the on one physical machine?

How the two machines communicate with each other to get the data? Through what protocol?

答:
Yes, replacing localhost with the IP address or domain name of your MongoDB server will work, providing that the remote server allows connections on the default port for Mongo (27017) and there are no firewalls in the middle blocking it.

It will be slower than the localhost connection, how much slower will depend entirely on the network infrastructure separating the two.

The protocol is a TCP/IP socket.

Body:
I want to do the following structure for a website.

The idea is put web app on one server, and put MongoDB on another server. They are different machines.

In nodejs code, the only configuration for db is the following code:

var connectString = 'mongodb://localhost/myDataBase';

Replace 'localhost' with '111.222.111.2', the ip address of the machine where MongoDB is running on, then it should work. Is this correct?

Will this make data retrieval slower comparing with putting the on one physical machine?

How the two machines communicate with each other to get the data? Through what protocol?


问:
Why is there Z-fighting when forward rendering lights?
In my OpenGL program I noticed black pixels appearing where lights were blended together in the forward rendering algorithm. At first I ignored it until I switch Window APIs (SDL to GLFW) when it became too visually problematic.

When I disable GL_DEPTH_TEST the blacks artifacts disappear but things become transparent to lights behind them so it's not a solution. (It's how I found the potential problem)

I'm not sure what the issue is it may be the depth buffer but switching window APIs enhances the artifacts, any help?

The pattern flickers as I move the camera

It seems the black lines/dots are isolated within each triangle

Here's where I blend lights

```<code>// Note: I wrapped OpenGL calls into wrapper functions but the naming convenction is still the same
gl::Clear(gl::e_ColorBufferBit | gl::e_DepthBufferBit);

mesh->Render(m_forward_ambient);
gl::Enable(gl::e_Blend);
gl::SetBlendFunc(gl::e_One, gl::e_One); // Additive blending
gl::SetDepthMask(false); // No need to write to depth buffer
gl::SetDepthFunc(gl::e_Equal); // Only draw fragments of equal depths (ignore fragments behind basically)
{
    for (word i = 0; i < m_lights.Length(); ++i)
    {
        m_active_light = m_lights[i];
        mesh->Render(m_active_light->shader); // Shaders use active light
    }
}
gl::SetDepthFunc(gl::e_Lequal); // Restore default state
gl::SetDepthMask(true);
gl::Disable(gl::e_Blend);
</code>```

Shader Code (the shader with all the code, others implement less)

```<code>// Vertex
void main()
{
    // pv_matrix is projection and camera, ml_matrix is model transform
    gl_Position = pv_matrix * ml_matrix * vec4(pos, 1);
    f_pos = (ml_matrix * vec4(pos, 1)).xyz;
    f_nrm = (ml_matrix * vec4(normalize(nrm), 0)).xyz;
    f_txc = txc;
}
// Fragment
struct Light
{
    vec3 color;
    float intensity;
};
struct Attenuation
{
    float constant;
    float linear;
    float exponent;
};
struct PointLight
{
    Light light;
    Attenuation atten;
    vec3 position;
    float range;
};
struct SpotLight
{
    PointLight plight;
    vec3 direction;
    float cutoff;
};
vec4 CalculateLight(Light light, vec3 direction, vec3 normal)
{
    float diffuse_factor = dot(normal, -direction);
    vec4 diffuse_color = vec4(0, 0, 0, 0);
    vec4 specular_color = vec4(0, 0, 0, 0);

    if (diffuse_factor > 0)
        diffuse_color = vec4(light.color, 1) * light.intensity * diffuse_factor;

    vec3 direction_to_eye = normalize(eye_pos - f_pos); // eye_pos is uniform for camera pos, f_pos is (position) attribute sent from vertex shader
    vec3 reflect_direction = normalize(reflect(direction, normal));
    float specular_factor = dot(reflect_direction, direction_to_eye); // specular calculations
    if (specular_factor > 0)
    {
        specular_factor = pow(specular_factor, specular_power);
        specular_color = vec4(light.color, 1) * specular_intensity * specular_factor;
    }

    return diffuse_color + specular_color;
}

vec4 CalculatePointLight(PointLight plight, vec3 normal)
{
    vec3 light_direction = f_pos - plight.position;
    float distance = length(light_direction);

    if (distance > plight.range)
        return vec4(0, 0, 0, 0);

    light_direction = normalize(light_direction);
    vec4 color = CalculateLight(plight.light, light_direction, normal);

    float a = plight.atten.constant + (plight.atten.linear * distance) + (plight.atten.exponent * (distance * distance)) + 0.0001;

    return color / a;
}

vec4 CalculateSpotLight(SpotLight slight, vec3 normal)
{
    vec3 light_direction = normalize(f_pos - slight.plight.position);
    float spot_factor = dot(light_direction, slight.direction);

    vec4 color = vec4(0, 0, 0, 0);
    if (spot_factor > slight.cutoff)
        color = CalculatePointLight(slight.plight, normal) * (1.0 - ((1.0 - spot_factor) / (1.0 - slight.cutoff)));

    return color;
}

uniform SpotLight spot_light;

void main()
{
    FragColor = CalculateSpotLight(spot_light, f_nrm); // f_nrm is a (normal) attribute sent from vertex shader
}
</code>```

答: You did not declare your gl_Position vertex shader output as invariant, so even if you use exactly the same formula, and bit-wise exact same inputs in both passes, your shaders aren't guaranteed to get to the exact same result. You should add proper invariance qualifiers to all of the shaders in all of the passes.

Body:
In my OpenGL program I noticed black pixels appearing where lights were blended together in the forward rendering algorithm. At first I ignored it until I switch Window APIs (SDL to GLFW) when it became too visually problematic.

When I disable GL_DEPTH_TEST the blacks artifacts disappear but things become transparent to lights behind them so it's not a solution. (It's how I found the potential problem)

I'm not sure what the issue is it may be the depth buffer but switching window APIs enhances the artifacts, any help?

The pattern flickers as I move the camera

It seems the black lines/dots are isolated within each triangle

Here's where I blend lights

// Note: I wrapped OpenGL calls into wrapper functions but the naming convenction is still the same
gl::Clear(gl::e_ColorBufferBit | gl::e_DepthBufferBit);

mesh->Render(m_forward_ambient);
gl::Enable(gl::e_Blend);
gl::SetBlendFunc(gl::e_One, gl::e_One); // Additive blending
gl::SetDepthMask(false); // No need to write to depth buffer
gl::SetDepthFunc(gl::e_Equal); // Only draw fragments of equal depths (ignore fragments behind basically)
{
    for (word i = 0; i < m_lights.Length(); ++i)
    {
        m_active_light = m_lights[i];
        mesh->Render(m_active_light->shader); // Shaders use active light
    }
}
gl::SetDepthFunc(gl::e_Lequal); // Restore default state
gl::SetDepthMask(true);
gl::Disable(gl::e_Blend);

Shader Code (the shader with all the code, others implement less)

// Vertex
void main()
{
    // pv_matrix is projection and camera, ml_matrix is model transform
    gl_Position = pv_matrix * ml_matrix * vec4(pos, 1);
    f_pos = (ml_matrix * vec4(pos, 1)).xyz;
    f_nrm = (ml_matrix * vec4(normalize(nrm), 0)).xyz;
    f_txc = txc;
}
// Fragment
struct Light
{
    vec3 color;
    float intensity;
};
struct Attenuation
{
    float constant;
    float linear;
    float exponent;
};
struct PointLight
{
    Light light;
    Attenuation atten;
    vec3 position;
    float range;
};
struct SpotLight
{
    PointLight plight;
    vec3 direction;
    float cutoff;
};
vec4 CalculateLight(Light light, vec3 direction, vec3 normal)
{
    float diffuse_factor = dot(normal, -direction);
    vec4 diffuse_color = vec4(0, 0, 0, 0);
    vec4 specular_color = vec4(0, 0, 0, 0);

    if (diffuse_factor > 0)
        diffuse_color = vec4(light.color, 1) * light.intensity * diffuse_factor;

    vec3 direction_to_eye = normalize(eye_pos - f_pos); // eye_pos is uniform for camera pos, f_pos is (position) attribute sent from vertex shader
    vec3 reflect_direction = normalize(reflect(direction, normal));
    float specular_factor = dot(reflect_direction, direction_to_eye); // specular calculations
    if (specular_factor > 0)
    {
        specular_factor = pow(specular_factor, specular_power);
        specular_color = vec4(light.color, 1) * specular_intensity * specular_factor;
    }

    return diffuse_color + specular_color;
}

vec4 CalculatePointLight(PointLight plight, vec3 normal)
{
    vec3 light_direction = f_pos - plight.position;
    float distance = length(light_direction);

    if (distance > plight.range)
        return vec4(0, 0, 0, 0);

    light_direction = normalize(light_direction);
    vec4 color = CalculateLight(plight.light, light_direction, normal);

    float a = plight.atten.constant + (plight.atten.linear * distance) + (plight.atten.exponent * (distance * distance)) + 0.0001;

    return color / a;
}

vec4 CalculateSpotLight(SpotLight slight, vec3 normal)
{
    vec3 light_direction = normalize(f_pos - slight.plight.position);
    float spot_factor = dot(light_direction, slight.direction);

    vec4 color = vec4(0, 0, 0, 0);
    if (spot_factor > slight.cutoff)
        color = CalculatePointLight(slight.plight, normal) * (1.0 - ((1.0 - spot_factor) / (1.0 - slight.cutoff)));

    return color;
}

uniform SpotLight spot_light;

void main()
{
    FragColor = CalculateSpotLight(spot_light, f_nrm); // f_nrm is a (normal) attribute sent from vertex shader
}


问:
Shell-Script Python call fails with Syntax Error
I am currently preparing a shell script which as part of it's functionality has to carry out some Python calls.

PY_OP=$(python -c 'import my_package as mp; print mp.some_operation()')
```

<p>However when I call my shell script in the bash I only receive a very strange syntax error:</p>

<pre class="lang-sh prettyprint-override"><code>$ ./my_script.sh
File "<string>", line 1
import my_package as mp; print mp.some_operation()
      ^
SyntaxError: invalid syntax
</code>```

Interestingly this error does not occur if I just execute the python -c ... command just from within the bash.

As additional information I can say the following:

I am using a virtualenv to contain all pip installed packages.

my Python version of use is 2.7.12

my operating system is elementaryOS 0.4.1 (which however fully bases on Ubuntu 16.04)

Any suggestions or hints on what I am doing wrong would be highly appreciated.

答:
Based on the comments @Cyrus gave in response to the initial question I was able to solve the problem using the cat -A {file-name}.sh command.

Executing it on the file revealed the following:

Expectation: import my_package as mp

Reality: importM-BM- my_packageM-BM- asM-BM- mp

The unfortunate thing is that these M-BM- are not visible in normal editors like Atom or Sublime, but appear to have an influence when the sh-file is exected. This also explains the weird placement of the error point which is pointing to a white space (which in fact appears to be some special, non-visible character).

Body:
I am currently preparing a shell script which as part of it's functionality has to carry out some Python calls.

PY_OP=$(python -c 'import my_package as mp; print mp.some_operation()')

However when I call my shell script in the bash I only receive a very strange syntax error:

$ ./my_script.sh
File "<string>", line 1
import my_package as mp; print mp.some_operation()
      ^
SyntaxError: invalid syntax

Interestingly this error does not occur if I just execute the python -c ... command just from within the bash.

As additional information I can say the following:

I am using a virtualenv to contain all pip installed packages.

my Python version of use is 2.7.12

my operating system is elementaryOS 0.4.1 (which however fully bases on Ubuntu 16.04)

Any suggestions or hints on what I am doing wrong would be highly appreciated.


问:
JQuery panel hiding
I'm having trouble getting a simple panel hide script to work. It works for MLAWebsite's panel, but when I click the MLAJournal button nothing happens? I've tried everything I can think of and looked at it for quite a bit now and can't seem to figure it out.

Relevant JQuery and HTML:

$(document).ready(function(){
    //var currentStep = 0;

    $("#MLAJournalpanel").hide();
    $("#MLAWebsitepanel").hide();

    $("btnMLAJournal").click(function(){
        $("#MLAWebsitepanel").hide();
        $("#MLAJournalpanel").show();

        //currentStep = 1;
    });

    $("#btnMLAWebsite").click(function(){
        $("#MLAJournalpanel").hide();
        $("#MLAWebsitepanel").show();

        //currentStep = 2;
    });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
   <head>
    <base target="_top">
     <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="Code.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

     <style>
     .branding-below {
        bottom: 56px;
        top: 0;
     }

     .branding-text {
        left: 7px;
        position: relative;
        top: 3px;
     }

     .col-contain {
        overflow: hidden;
     }

     .col-one {
        float: left;
        width: 50%;
     }

     .logo {
        vertical-align: middle;
     }

     .radio-spacer {
        height: 20px;
     }

     .width-100 {
        width: 100%;
     }
     </style>

   </head>

   <body>
     <div class="sidebar branding-below">
            <input id="btnMLAJournal" type="button" value="MLA Journal"></input>
            <input id="btnMLAWebsite" type="button" value="MLA Website"></input>

            <div id="MLAJournalpanel" class="panel">
                <div class="panel-body">
                    <h2>MLA Journal</h2>
                </div>
            </div>

            <div id="MLAWebsitepanel" class="panel">
                <div class="panel-body">
                    <h1>dadadda</h1>
                    <p>surprise!"</p>
                </div>
            </div>

        </div>
   </body>
</html></code>```

答:
You have given the id btnMLAJournal to your button and calling element from id in jquery requires # with id which in your case is missing.
just add # to your id in jquery and it will work fine

$(document).ready(function(){
    //var currentStep = 0;

    $("#MLAJournalpanel").hide();
    $("#MLAWebsitepanel").hide();

    //# is added here
    $("#btnMLAJournal").click(function(){
        $("#MLAWebsitepanel").hide();
        $("#MLAJournalpanel").show();

        //currentStep = 1;
    });

    $("#btnMLAWebsite").click(function(){
        $("#MLAJournalpanel").hide();
        $("#MLAWebsitepanel").show();

        //currentStep = 2;
    });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
   <head>
    <base target="_top">
     <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="Code.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

     <style>
     .branding-below {
        bottom: 56px;
        top: 0;
     }

     .branding-text {
        left: 7px;
        position: relative;
        top: 3px;
     }

     .col-contain {
        overflow: hidden;
     }

     .col-one {
        float: left;
        width: 50%;
     }

     .logo {
        vertical-align: middle;
     }

     .radio-spacer {
        height: 20px;
     }

     .width-100 {
        width: 100%;
     }
     </style>

   </head>

   <body>
     <div class="sidebar branding-below">
            <input id="btnMLAJournal" type="button" value="MLA Journal"></input>
            <input id="btnMLAWebsite" type="button" value="MLA Website"></input>

            <div id="MLAJournalpanel" class="panel">
                <div class="panel-body">
                    <h2>MLA Journal</h2>
                </div>
            </div>

            <div id="MLAWebsitepanel" class="panel">
                <div class="panel-body">
                    <h1>dadadda</h1>
                    <p>surprise!"</p>
                </div>
            </div>

        </div>
   </body>
</html></code>```

Title: JQuery panel hiding

Body:
I'm having trouble getting a simple panel hide script to work. It works for MLAWebsite's panel, but when I click the MLAJournal button nothing happens? I've tried everything I can think of and looked at it for quite a bit now and can't seem to figure it out.

Relevant JQuery and HTML:

$(document).ready(function(){
    //var currentStep = 0;

    $("#MLAJournalpanel").hide();
    $("#MLAWebsitepanel").hide();

    $("btnMLAJournal").click(function(){
        $("#MLAWebsitepanel").hide();
        $("#MLAJournalpanel").show();

        //currentStep = 1;
    });

    $("#btnMLAWebsite").click(function(){
        $("#MLAJournalpanel").hide();
        $("#MLAWebsitepanel").show();

        //currentStep = 2;
    });

});

<!DOCTYPE html>

    <base target="_top">
     <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

            <input id="btnMLAJournal" type="button" value="MLA Journal"></input>
            <input id="btnMLAWebsite" type="button" value="MLA Website"></input>

MLA Journal

dadadda

surprise!"

Body:
You have given the id btnMLAJournal to your button and calling element from id in jquery requires # with id which in your case is missing.
just add # to your id in jquery and it will work fine

$(document).ready(function(){
    //var currentStep = 0;

    $("#MLAJournalpanel").hide();
    $("#MLAWebsitepanel").hide();

    //# is added here
    $("#btnMLAJournal").click(function(){
        $("#MLAWebsitepanel").hide();
        $("#MLAJournalpanel").show();

        //currentStep = 1;
    });

    $("#btnMLAWebsite").click(function(){
        $("#MLAJournalpanel").hide();
        $("#MLAWebsitepanel").show();

        //currentStep = 2;
    });

});

<!DOCTYPE html>
<html>
   <head>
    <base target="_top">
     <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="Code.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

     <style>
     .branding-below {
        bottom: 56px;
        top: 0;
     }

     .branding-text {
        left: 7px;
        position: relative;
        top: 3px;
     }

     .col-contain {
        overflow: hidden;
     }

     .col-one {
        float: left;
        width: 50%;
     }

     .logo {
        vertical-align: middle;
     }

     .radio-spacer {
        height: 20px;
     }

     .width-100 {
        width: 100%;
     }
     </style>

   </head>

   <body>
     <div class="sidebar branding-below">
            <input id="btnMLAJournal" type="button" value="MLA Journal"></input>
            <input id="btnMLAWebsite" type="button" value="MLA Website"></input>

            <div id="MLAJournalpanel" class="panel">
                <div class="panel-body">
                    <h2>MLA Journal</h2>
                </div>
            </div>

            <div id="MLAWebsitepanel" class="panel">
                <div class="panel-body">
                    <h1>dadadda</h1>
                    <p>surprise!"</p>
                </div>
            </div>

        </div>
   </body>
</html>


问:
neural networks for missing features
I have a dataset wit A...F features for training. Now my prediction data set to predict the key feature does not have observations of 3 feature used in the training set. So I have only a subset of features for prediction whereas the neural newtork is trained for a broader range of features.

How can I handle such problem? Can you use a neural network for the missing features? In my mind came the following: First, I use a neural network on training set, but now to train on the missing features. So I can predict the 3 missing features from the prediction data set. Now, I use a neural network on this new prediction data set.

答:
Have you tried running the neural-network on your dataset even though features are missing? A neural-network does not need all features to be present.

You can simply set all missing features values to 0 for the neural network, as neural networks don't see a difference between 0 and feature is missing. Why not you ask? If you set an input value to 0, that means all the connections from that input node will have a 0 value a well: adding nothing to the hidden neurons that are connected to that input node.

But before you do that, try any of these:

source

As 1 seems the case for you!

Title: neural networks for missing features


问:
an error in integrating a function in R
The following code chunk is for defining and integrating a function f1 involving matrix exponentials.

```<code>library(expm)
Lambdahat=rbind(c(-0.57,0.21,0.36,0,0),
c(0,-7.02,7.02,0,0),
c(1,0,-37.02,29,7.02),
c(0.03,0,0,-0.25,0.22),
c(0,0,0,0,0));

B=rbind(c(-1,1,0,0,0),c(0,0,0,0,0),c(0,0,0,0,0),c(0,0,0,0,0),c(0,0,0,0,0))

f1<-function(tau1)
{
  A=(expm(Lambdahat*tau1)%*%B%*%expm(Lambdahat*(5-tau1)));
  return(A[1,5]);
}

out=integrate(f1,lower=0,upper=5)#integration of f1
</code>```

The integration in the above line gives the following error:

```<code>Error in integrate(f1, lower = 0, upper = 5) :
evaluation of function gave a result of wrong length
In addition: Warning messages:
1: In Lambdahat * tau1 :
longer object length is not a multiple of shorter object length
2: In Lambdahat * (t[i] - tau1) :
longer object length is not a multiple of shorter object length
</code>```

To check for if the function outputs and inputs are of function f1 different length, 10 evenly spaced inputs and corresponding outputs of f1 are reported below. Input and output length for all the test cases were recorded as equal to 1.

```<code>sapply(X=seq(from=0,to=5,by=0.5),FUN=f1)
[1] 2.107718e-01 1.441219e-01 0.000000e+00 2.023337e+06 1.709569e+14
[6] 1.452972e+22 1.243012e+30 1.071096e+38 9.302178e+45 8.146598e+53
[11] 7.197606e+61
</code>```

If anyone could share any hint or directions where the code may be going erroneous, it would be very helpful. Thanks very much!

答: The problem is that the function passed to integrate need to be vectorized, i.e. it should be able to receive a vector of input values and to return a vector of output values. I think f1 <- Vectorize(f1) could solve your problem.

Title: an error in integrating a function in R

Body:
The following code chunk is for defining and integrating a function f1 involving matrix exponentials.

library(expm)
Lambdahat=rbind(c(-0.57,0.21,0.36,0,0),
c(0,-7.02,7.02,0,0),
c(1,0,-37.02,29,7.02),
c(0.03,0,0,-0.25,0.22),
c(0,0,0,0,0));

B=rbind(c(-1,1,0,0,0),c(0,0,0,0,0),c(0,0,0,0,0),c(0,0,0,0,0),c(0,0,0,0,0))

f1<-function(tau1)
{
  A=(expm(Lambdahat*tau1)%*%B%*%expm(Lambdahat*(5-tau1)));
  return(A[1,5]);
}

out=integrate(f1,lower=0,upper=5)#integration of f1

The integration in the above line gives the following error:

Error in integrate(f1, lower = 0, upper = 5) :
evaluation of function gave a result of wrong length
In addition: Warning messages:
1: In Lambdahat * tau1 :
longer object length is not a multiple of shorter object length
2: In Lambdahat * (t[i] - tau1) :
longer object length is not a multiple of shorter object length

To check for if the function outputs and inputs are of function f1 different length, 10 evenly spaced inputs and corresponding outputs of f1 are reported below. Input and output length for all the test cases were recorded as equal to 1.

sapply(X=seq(from=0,to=5,by=0.5),FUN=f1)
[1] 2.107718e-01 1.441219e-01 0.000000e+00 2.023337e+06 1.709569e+14
[6] 1.452972e+22 1.243012e+30 1.071096e+38 9.302178e+45 8.146598e+53
[11] 7.197606e+61

If anyone could share any hint or directions where the code may be going erroneous, it would be very helpful. Thanks very much!


问:
While trying to copy data Next to variables from text to csv with python getting error:
I am trying to copy values of data seprated with: from text file.
 Text file having data like in this form:

I have 50+ text file contains data in this form:

```<code>Type: Assume
Number: 123456
Name: Assume
Phone Number: 000-000
Email Address: any@gmail.com
Mailing Address: Assume
</code>```

i am trying to get data values in this format in csv from multiple text files:

```<code>Type     Number  Name     Phone      email         Mailing Address
Assume   123456  Assume   000-000   any@gmail.com  Assume
</code>```

Here is the code:

```<code>import re
import csv

file_h = open("out.csv","a")
csv_writer = csv.writer(file_h)

def writeHeading(file_content):
    list_of_headings = []
    for row in file_content:
        key = str(row.split(":")[0]).strip()
        list_of_headings.append(key)

    csv_writer.writerow(tuple(list_of_headings))

def writeContents(file_content):
    list_of_data = ['Number']
    for row in file_content:
        value = str(row.split(":")[1]).strip()
        list_of_data.append(value)
    csv_writer.writerow(tuple(list_of_data))

def convert_txt_csv(filename):
    file_content = open(filename,"r").readlines()
    return file_content

list_of_files = ["10002.txt","10003.txt","10004.txt"]

# for writing heading once
file_content = convert_txt_csv(list_of_files[0])
writeHeading(file_content)

# for writing contents
for file in list_of_files:
    file_content = convert_txt_csv(file)
    writeContents(file_content)

file_h.close()
</code>```

Here is the following error:

```<code>Traceback (most recent call last):
  File "Magnet.py", line 37, in <module>
    writeContents(file_content)
  File "Magnet.py", line 20, in writeContents
    value = str(row.split(":")[1]).strip()
IndexError: list index out of range
</code>```

答:
Your code probably encounters a blank line at the end of the first file, or any line that doesn't have a : in it, so when you try to split it into key/values it complains as it didn't get a list of expected length. You can fix that easily by checking if there is a colon on the current line, i.e.:

```<code>for row in file_content:
    if ":" not in row:  # or you can do the split and check len() of the result
        continue
    key = row.split(":")[0].strip()
    list_of_headings.append(key)
</code>```

But... While the task you're attempting looks extremely simple, keep in mind that your approach assumes that all the files are equal, with equal number key: value combinations and in the same order.

You'd be much better off by storing your parsed data in a dict and then using csv.DictWriter() to do your bidding.

Body:
I am trying to copy values of data seprated with: from text file.
 Text file having data like in this form:

I have 50+ text file contains data in this form:

Type: Assume
Number: 123456
Name: Assume
Phone Number: 000-000
Email Address: any@gmail.com
Mailing Address: Assume

i am trying to get data values in this format in csv from multiple text files:

Type     Number  Name     Phone      email         Mailing Address
Assume   123456  Assume   000-000   any@gmail.com  Assume

Here is the code:

import re
import csv

file_h = open("out.csv","a")
csv_writer = csv.writer(file_h)

def writeHeading(file_content):
    list_of_headings = []
    for row in file_content:
        key = str(row.split(":")[0]).strip()
        list_of_headings.append(key)

    csv_writer.writerow(tuple(list_of_headings))

def writeContents(file_content):
    list_of_data = ['Number']
    for row in file_content:
        value = str(row.split(":")[1]).strip()
        list_of_data.append(value)
    csv_writer.writerow(tuple(list_of_data))

def convert_txt_csv(filename):
    file_content = open(filename,"r").readlines()
    return file_content

list_of_files = ["10002.txt","10003.txt","10004.txt"]

# for writing heading once
file_content = convert_txt_csv(list_of_files[0])
writeHeading(file_content)

# for writing contents
for file in list_of_files:
    file_content = convert_txt_csv(file)
    writeContents(file_content)

file_h.close()

Here is the following error:

Traceback (most recent call last):
  File "Magnet.py", line 37, in <module>
    writeContents(file_content)
  File "Magnet.py", line 20, in writeContents
    value = str(row.split(":")[1]).strip()
IndexError: list index out of range

Body:
Your code probably encounters a blank line at the end of the first file, or any line that doesn't have a : in it, so when you try to split it into key/values it complains as it didn't get a list of expected length. You can fix that easily by checking if there is a colon on the current line, i.e.:

for row in file_content:
    if ":" not in row:  # or you can do the split and check len() of the result
        continue
    key = row.split(":")[0].strip()
    list_of_headings.append(key)

But... While the task you're attempting looks extremely simple, keep in mind that your approach assumes that all the files are equal, with equal number key: value combinations and in the same order.

You'd be much better off by storing your parsed data in a dict and then using csv.DictWriter() to do your bidding.