问:
Django Custom Model Field - formfield not working
I've been scratching my head for a while now over this one. I'm trying to build a custom model field to store postal address.

The general idea is to store all data after serializing in a models.TextField, and to use a form.MultiValueField to catch each value.

For some reason, even if migration works fine, in the admin, the field appear as a simple TextField. As if the MultiValueField part was completely ignored...

Here's my code:

```<code>from django.db import models
from django.forms import MultiValueField, CharField
from django.utils.translation import ugettext_lazy as _

class Address(object):
    """A postal address."""

    def __init__(self, street, postal_code, city,
                 country, complement=None, region=None):
        self.street = street
        self.complement = complement
        self.postal_code = postal_code
        self.city = city
        self.region = region
        self.country = country

    def print_address_inline(self):
        complement = ''
        region = ''
        if self.complement:
            complement = ', %s' % self.complement
        if self.region:
            region = ', %s' % self.region
        data = {
            'street': self.street,
            'complement': complement,
            'code': self.postal_code,
            'city': self.city,
            'region': region,
            'country': self.country
        }
        return '%(street)s%(complement)s, %(code)s %(city)s%(region)s' \
               ', %(country)s' % data

    def __str__(self):
        return self.print_address_inline()

class AddressFormField(MultiValueField):
    def __init__(self, *args, **kwargs):
        del kwargs['max_length']
        error_messages = {
            'incomplete': _('Enter a complete address: ' \
                            'street, postal code, city and country.'),
        }
        fields = (
            CharField(
                label='street', max_length=1024,
                error_messages={
                    'incomplete': _('Enter the number and street.')
                }
            ),
            CharField(
                label='complement', max_length=1024, required=False
            ),
            CharField(
                label='code', max_length=10,
                error_messages={'incomplete': _('Enter the postal code.')}
            ),
            CharField(
                label='city', max_length=255,
                error_messages={'incomplete': _('Enter the city.')}
            ),
            CharField(
                label='region', max_length=255, required=False
            ),
            CharField(
                label='country', max_length=255,
                error_messages={'incomplete': _('Enter the country.')}
            )
        )
        super(AddressFormField, self).__init__(
            error_messages=error_messages, fields=fields,
            require_all_fields=False, *args, **kwargs
        )

    def compress(self, data_list):
        if data_list:
            if data_list[0] in self.empty_values:
                raise ValidationError(
                    _('Enter the number and street.'),
                    code='incomplete'
                )
            if data_list[2] in self.empty_values:
                raise ValidationError(
                    _('Enter the postal code.'),
                    code='incomplete'
                )
            if data_list[3] in self.empty_values:
                raise ValidationError(
                    _('Enter the city.'),
                    code='incomplete'
                )
            if data_list[5] in self.empty_values:
                raise ValidationError(
                    _('Enter the country.'),
                    code='incomplete'
                )
            address = Address(
                street=data_list[0],
                complement=data_list[1],
                code=data_list[2],
                city=data_list[3].title(),
                region=data_list[4],
                country=data_list[5].upper()
            )
            return address
        return None

class AddressField(models.TextField):
    description = "A postal address."

    def __init__(self, *args, **kwargs):
        super(AddressField, self).__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super(AddressField, self).deconstruct()
        return name, path, args, kwargs

    def from_db_value(self, value, expression, connection, context):
        if value is None:
            return value
        data = value.split('@@')
        return Address(*data)

    def to_python(self, value):
        if isinstance(value, Address):
            return value
        if value is None:
            return value
        data = value.split('@@')
        return Address(*data)

    def get_prep_value(self, value):
        if isinstance(value, Address):
            data = []
            for v in [
                value.street,
                value.complement,
                value.postal_code,
                value.city,
                value.region,
                value.country,
            ]:
                if v is not None:
                    data.append(v)
                else:
                    data.append('')
            return '@@'.join(data)
        else:
            return value

    def formfield(self, **kwargs):
        defaults = {'form_class': AddressFormField}
        defaults.update(kwargs)
        return super(AddressField, self).formfield(**defaults)
</code>```

If you have any clue...

Thanks!

答:
I finally made it through with this piece of code.

```<code>from django.db import models
from django.forms import MultiValueField, CharField, TextInput
from django.forms.widgets import MultiWidget
from django.utils.translation import ugettext_lazy as _

class Address(object):
    """A postal address."""
    def __init__(self, street, complement, postal_code, city, region, country):
        self.street = street
        self.complement = complement
        self.postal_code = postal_code
        self.city = city
        self.region = region
        self.country = country

    def print_address_inline(self):
        complement = ''
        region = ''
        if self.complement != '':
            complement = ', %s' % self.complement
        if self.region != '':
            region = ', %s' % self.region
        data = {
            'street': self.street,
            'complement': complement,
            'code': self.postal_code,
            'city': self.city,
            'region': region,
            'country': self.country
        }
        return '%(street)s%(complement)s, %(code)s %(city)s%(region)s' \
               ', %(country)s' % data

    def get_values_list(self):
        data = [
            self.street,
            self.complement,
            self.postal_code,
            self.city,
            self.region,
            self.country,
        ]
        value_list = []
        for value in data:
            if value is not None:
                value_list.append(value)
            else:
                value_list.append('')
        return value_list

    def __str__(self):
        return self.print_address_inline()

class AddressWidget(MultiWidget):
    """A special widget to render Address form field."""
    def __init__(self, attrs=None):
        # TODO Look for django-localflavor to improve this custom field.
        # https://django-localflavor.readthedocs.io/en/latest/localflavor/fr/
        widgets = [
            TextInput(attrs={'placeholder':'street'}),
            TextInput(attrs={'placeholder':'complement'}),
            TextInput(attrs={'placeholder':'postal code'}),
            TextInput(attrs={'placeholder':'city'}),
            TextInput(attrs={'placeholder':'region'}),
            TextInput(attrs={'placeholder':'country'}),
        ]
        super(AddressWidget, self).__init__(widgets, attrs)

    def decompress(self, value):
        if value:
            return [
                value.street,
                value.complement,
                value.postal_code,
                value.city,
                value.region,
                value.country,
            ]
        return [None, None, None, None, None, None]

class AddressFormField(MultiValueField):
    """A special form field to handle Address model field."""
    widget = AddressWidget

    def __init__(self, *args, **kwargs):
        error_messages = {
            'incomplete': _('Enter a complete address: ' \
                            'street, postal code, city and country.'),
        }
        fields = (
            CharField(
                label='street', max_length=1024,
                error_messages={
                    'incomplete': _('Enter the number and street.')
                }
            ),
            CharField(
                label='complement', max_length=1024, required=False
            ),
            CharField(
                label='code', max_length=10,
                error_messages={'incomplete': _('Enter the postal code.')}
            ),
            CharField(
                label='city', max_length=255,
                error_messages={'incomplete': _('Enter the city.')}
            ),
            CharField(
                label='region', max_length=255, required=False
            ),
            CharField(
                label='country', max_length=255,
                error_messages={'incomplete': _('Enter the country.')}
            )
        )
        super(AddressFormField, self).__init__(
            error_messages=error_messages, fields=fields,
            require_all_fields=False, *args, **kwargs
        )

    def compress(self, data_list):
        if data_list:
            if data_list[0] in self.empty_values:
                raise ValidationError(
                    _('Enter the number and street.'),
                    code='incomplete'
                )
            if data_list[2] in self.empty_values:
                raise ValidationError(
                    _('Enter the postal code.'),
                    code='incomplete'
                )
            if data_list[3] in self.empty_values:
                raise ValidationError(
                    _('Enter the city.'),
                    code='incomplete'
                )
            if data_list[5] in self.empty_values:
                raise ValidationError(
                    _('Enter the country.'),
                    code='incomplete'
                )
            address = Address(
                street=data_list[0],
                complement=data_list[1],
                postal_code=data_list[2],
                city=data_list[3].title(),
                region=data_list[4],
                country=data_list[5].upper()
            )
            return address
        return None

class AddressField(models.Field):
    description = "A postal address."

    def __init__(self, *args, **kwargs):
        super(AddressField, self).__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super(AddressField, self).deconstruct()
        return name, path, args, kwargs

    def from_db_value(self, value, expression, connection, context):
        if value is None or value == '':
            return value
        data = value.split('@@')
        address = Address(*data)
        return address

    def to_python(self, value):
        if isinstance(value, Address):
            return value
        if value is None:
            return value
        data = value.split('@@')
        return Address(*data)

    def get_prep_value(self, value):
        if value:
            return '@@'.join(value.get_values_list())
        return ''

    def get_internal_type(self):
        return 'TextField'

    def formfield(self, **kwargs):
        defaults = {'form_class': AddressFormField}
        defaults.update(kwargs)
        return super(AddressField, self).formfield(**defaults)
</code>```

Feel free to comment or share your thoughts about it.
I made the choice of using double '@' as a separator. It is debatable, but it works in my case.

Body:
I've been scratching my head for a while now over this one. I'm trying to build a custom model field to store postal address.

The general idea is to store all data after serializing in a models.TextField, and to use a form.MultiValueField to catch each value.

For some reason, even if migration works fine, in the admin, the field appear as a simple TextField. As if the MultiValueField part was completely ignored...

Here's my code:

from django.db import models
from django.forms import MultiValueField, CharField
from django.utils.translation import ugettext_lazy as _

class Address(object):
    """A postal address."""

    def __init__(self, street, postal_code, city,
                 country, complement=None, region=None):
        self.street = street
        self.complement = complement
        self.postal_code = postal_code
        self.city = city
        self.region = region
        self.country = country

    def print_address_inline(self):
        complement = ''
        region = ''
        if self.complement:
            complement = ', %s' % self.complement
        if self.region:
            region = ', %s' % self.region
        data = {
            'street': self.street,
            'complement': complement,
            'code': self.postal_code,
            'city': self.city,
            'region': region,
            'country': self.country
        }
        return '%(street)s%(complement)s, %(code)s %(city)s%(region)s' \
               ', %(country)s' % data

    def __str__(self):
        return self.print_address_inline()

class AddressFormField(MultiValueField):
    def __init__(self, *args, **kwargs):
        del kwargs['max_length']
        error_messages = {
            'incomplete': _('Enter a complete address: ' \
                            'street, postal code, city and country.'),
        }
        fields = (
            CharField(
                label='street', max_length=1024,
                error_messages={
                    'incomplete': _('Enter the number and street.')
                }
            ),
            CharField(
                label='complement', max_length=1024, required=False
            ),
            CharField(
                label='code', max_length=10,
                error_messages={'incomplete': _('Enter the postal code.')}
            ),
            CharField(
                label='city', max_length=255,
                error_messages={'incomplete': _('Enter the city.')}
            ),
            CharField(
                label='region', max_length=255, required=False
            ),
            CharField(
                label='country', max_length=255,
                error_messages={'incomplete': _('Enter the country.')}
            )
        )
        super(AddressFormField, self).__init__(
            error_messages=error_messages, fields=fields,
            require_all_fields=False, *args, **kwargs
        )

    def compress(self, data_list):
        if data_list:
            if data_list[0] in self.empty_values:
                raise ValidationError(
                    _('Enter the number and street.'),
                    code='incomplete'
                )
            if data_list[2] in self.empty_values:
                raise ValidationError(
                    _('Enter the postal code.'),
                    code='incomplete'
                )
            if data_list[3] in self.empty_values:
                raise ValidationError(
                    _('Enter the city.'),
                    code='incomplete'
                )
            if data_list[5] in self.empty_values:
                raise ValidationError(
                    _('Enter the country.'),
                    code='incomplete'
                )
            address = Address(
                street=data_list[0],
                complement=data_list[1],
                code=data_list[2],
                city=data_list[3].title(),
                region=data_list[4],
                country=data_list[5].upper()
            )
            return address
        return None

class AddressField(models.TextField):
    description = "A postal address."

    def __init__(self, *args, **kwargs):
        super(AddressField, self).__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super(AddressField, self).deconstruct()
        return name, path, args, kwargs

    def from_db_value(self, value, expression, connection, context):
        if value is None:
            return value
        data = value.split('@@')
        return Address(*data)

    def to_python(self, value):
        if isinstance(value, Address):
            return value
        if value is None:
            return value
        data = value.split('@@')
        return Address(*data)

    def get_prep_value(self, value):
        if isinstance(value, Address):
            data = []
            for v in [
                value.street,
                value.complement,
                value.postal_code,
                value.city,
                value.region,
                value.country,
            ]:
                if v is not None:
                    data.append(v)
                else:
                    data.append('')
            return '@@'.join(data)
        else:
            return value

    def formfield(self, **kwargs):
        defaults = {'form_class': AddressFormField}
        defaults.update(kwargs)
        return super(AddressField, self).formfield(**defaults)

If you have any clue...

Thanks!

Body:
I finally made it through with this piece of code.

from django.db import models
from django.forms import MultiValueField, CharField, TextInput
from django.forms.widgets import MultiWidget
from django.utils.translation import ugettext_lazy as _

class Address(object):
    """A postal address."""
    def __init__(self, street, complement, postal_code, city, region, country):
        self.street = street
        self.complement = complement
        self.postal_code = postal_code
        self.city = city
        self.region = region
        self.country = country

    def print_address_inline(self):
        complement = ''
        region = ''
        if self.complement != '':
            complement = ', %s' % self.complement
        if self.region != '':
            region = ', %s' % self.region
        data = {
            'street': self.street,
            'complement': complement,
            'code': self.postal_code,
            'city': self.city,
            'region': region,
            'country': self.country
        }
        return '%(street)s%(complement)s, %(code)s %(city)s%(region)s' \
               ', %(country)s' % data

    def get_values_list(self):
        data = [
            self.street,
            self.complement,
            self.postal_code,
            self.city,
            self.region,
            self.country,
        ]
        value_list = []
        for value in data:
            if value is not None:
                value_list.append(value)
            else:
                value_list.append('')
        return value_list

    def __str__(self):
        return self.print_address_inline()

class AddressWidget(MultiWidget):
    """A special widget to render Address form field."""
    def __init__(self, attrs=None):
        # TODO Look for django-localflavor to improve this custom field.
        # https://django-localflavor.readthedocs.io/en/latest/localflavor/fr/
        widgets = [
            TextInput(attrs={'placeholder':'street'}),
            TextInput(attrs={'placeholder':'complement'}),
            TextInput(attrs={'placeholder':'postal code'}),
            TextInput(attrs={'placeholder':'city'}),
            TextInput(attrs={'placeholder':'region'}),
            TextInput(attrs={'placeholder':'country'}),
        ]
        super(AddressWidget, self).__init__(widgets, attrs)

    def decompress(self, value):
        if value:
            return [
                value.street,
                value.complement,
                value.postal_code,
                value.city,
                value.region,
                value.country,
            ]
        return [None, None, None, None, None, None]

class AddressFormField(MultiValueField):
    """A special form field to handle Address model field."""
    widget = AddressWidget

    def __init__(self, *args, **kwargs):
        error_messages = {
            'incomplete': _('Enter a complete address: ' \
                            'street, postal code, city and country.'),
        }
        fields = (
            CharField(
                label='street', max_length=1024,
                error_messages={
                    'incomplete': _('Enter the number and street.')
                }
            ),
            CharField(
                label='complement', max_length=1024, required=False
            ),
            CharField(
                label='code', max_length=10,
                error_messages={'incomplete': _('Enter the postal code.')}
            ),
            CharField(
                label='city', max_length=255,
                error_messages={'incomplete': _('Enter the city.')}
            ),
            CharField(
                label='region', max_length=255, required=False
            ),
            CharField(
                label='country', max_length=255,
                error_messages={'incomplete': _('Enter the country.')}
            )
        )
        super(AddressFormField, self).__init__(
            error_messages=error_messages, fields=fields,
            require_all_fields=False, *args, **kwargs
        )

    def compress(self, data_list):
        if data_list:
            if data_list[0] in self.empty_values:
                raise ValidationError(
                    _('Enter the number and street.'),
                    code='incomplete'
                )
            if data_list[2] in self.empty_values:
                raise ValidationError(
                    _('Enter the postal code.'),
                    code='incomplete'
                )
            if data_list[3] in self.empty_values:
                raise ValidationError(
                    _('Enter the city.'),
                    code='incomplete'
                )
            if data_list[5] in self.empty_values:
                raise ValidationError(
                    _('Enter the country.'),
                    code='incomplete'
                )
            address = Address(
                street=data_list[0],
                complement=data_list[1],
                postal_code=data_list[2],
                city=data_list[3].title(),
                region=data_list[4],
                country=data_list[5].upper()
            )
            return address
        return None

class AddressField(models.Field):
    description = "A postal address."

    def __init__(self, *args, **kwargs):
        super(AddressField, self).__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super(AddressField, self).deconstruct()
        return name, path, args, kwargs

    def from_db_value(self, value, expression, connection, context):
        if value is None or value == '':
            return value
        data = value.split('@@')
        address = Address(*data)
        return address

    def to_python(self, value):
        if isinstance(value, Address):
            return value
        if value is None:
            return value
        data = value.split('@@')
        return Address(*data)

    def get_prep_value(self, value):
        if value:
            return '@@'.join(value.get_values_list())
        return ''

    def get_internal_type(self):
        return 'TextField'

    def formfield(self, **kwargs):
        defaults = {'form_class': AddressFormField}
        defaults.update(kwargs)
        return super(AddressField, self).formfield(**defaults)

Feel free to comment or share your thoughts about it.
I made the choice of using double '@' as a separator. It is debatable, but it works in my case.


来源: stackexchange

问:
How to get value of IEnumerable using two parameters
I use the following code and it does not fail at compile time, but I do not seem to have entered correctly the input codes and parameters!

```<code>public IEnumerable<TimeWorkMonthly> Get(int id,int id1)
{
    using (EmployeeDbEntities Entities = new EmployeeDbEntities())
    {
        var result = Entities.TimeWorkMonthlies.Where(e => e.KartNo == id && e.TermID == id1).ToList();
        return result;
    }
}
</code>```

In my browser I type the address below:

```<code>http://localhost:49643/api/Employees/1461/9604
</code>```

But I get a 404 error.

While using an input value(id), I get the correct output from the program.

Where do you think the problem is?

答:
The problem is that the route http://localhost:49643/api/Employees/1461/9604 does not resolve the parameter id1 correctly.

The default route looks something like this (in WebApiConfig.cs):

```<code>routes.MapHttpRoute(
    name: "API Default",
    routeTemplate: "api/{controller}/{id}", // only "id" parameter is mapped from URL
    defaults: new { id = RouteParameter.Optional }
);
</code>```

Add another route that also maps the id1 from the URL:

```<code>routes.MapHttpRoute(
    name: "API with additional Id",
    routeTemplate: "api/{controller}/{id}/{id1}", // URL with TWO parameters
    defaults: new { id = UrlParameter.Optional, id1 = UrlParameter.Optional }
);
</code>```

Further reading: Routing in ASP.NET Web API.

ContentLicense: CC BY-SA 3.0

Body:
I use the following code and it does not fail at compile time, but I do not seem to have entered correctly the input codes and parameters!

public IEnumerable<TimeWorkMonthly> Get(int id,int id1)
{
    using (EmployeeDbEntities Entities = new EmployeeDbEntities())
    {
        var result = Entities.TimeWorkMonthlies.Where(e => e.KartNo == id && e.TermID == id1).ToList();
        return result;
    }
}

In my browser I type the address below:

http://localhost:49643/api/Employees/1461/9604

But I get a 404 error.

While using an input value(id), I get the correct output from the program.

Where do you think the problem is?

Body:
The problem is that the route http://localhost:49643/api/Employees/1461/9604 does not resolve the parameter id1 correctly.

The default route looks something like this (in WebApiConfig.cs):

routes.MapHttpRoute(
    name: "API Default",
    routeTemplate: "api/{controller}/{id}", // only "id" parameter is mapped from URL
    defaults: new { id = RouteParameter.Optional }
);

Add another route that also maps the id1 from the URL:

routes.MapHttpRoute(
    name: "API with additional Id",
    routeTemplate: "api/{controller}/{id}/{id1}", // URL with TWO parameters
    defaults: new { id = UrlParameter.Optional, id1 = UrlParameter.Optional }
);

Further reading: Routing in ASP.NET Web API.


问:
JavaScript | ColdFusion - Facebook pixel
I'm trying to trigger my Facebook pixel.

This is the problem:

I have my own image pixel installed in a client website, when my pixel is triggered in the client website it sends a request to my server which after some inserts in a db I redirect the request to CFML page (HTML for ColdFusion) which has the pixel code from Facebook like below:

```<code>  <script>
       // Facebok Pixel Init Code
       fbq('init', 'PIXEL_ID');
       fbq('trackCustom', 'myCustomEvent', {});
  </script>
  <noscript>
      <img src="THE_FB_URL/?id=PIXEL_ID&ev=myCustomEvent&noscript=1">
  </noscript>
</code>```

When I directly access the page via a browser it triggers the pixel successfully and I can see it in the Facebook pixel report. But when the request is redirected to the page after the insert to the db the pixel does not trigger.

I think its because the JavaScript and HTML is never added to the DOM so it never gets executed...

Do you know how can I achieve this?

I think if maybe I send an HTTP GET request to the  tag URL hopefully the Facebook accepts it..

UPDATE

So this is what happens, the request I send triggers the event, but @Jules is right. I can't find which ad led to a conversion using this method, the problem is that where pushing traffic to our clients website, in which we can't install any JavaScript code.

I tried to check what cookies Facebook stores so when I make the GET request I send those values too, but this happens:

1 - The ad sends the user to a link like this:

l.facebook.com/l.php?u=redirect_url&h=some_token_here

In this page I can check that there is some cookies (I assume these are the values Facebook needs to find which ad led to a conversion)

2 - Then the user is redirected to our clients form page

I tried to check the cookies here too but the cookies don't seem to exist..

I need help people!

答:
You should not write HTML/Javascript code.

The first conversion pixel is called via an img tag so you cannot respond with HTML/Javascript.

All you have to do is return a redirect (301) to your final image pixel. In this case:

```<code>Redirect 301 THE_FB_URL/?id=PIXEL_ID&ev=myCustomEvent&noscript=1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to trigger my Facebook pixel.

This is the problem:

I have my own image pixel installed in a client website, when my pixel is triggered in the client website it sends a request to my server which after some inserts in a db I redirect the request to CFML page (HTML for ColdFusion) which has the pixel code from Facebook like below:

When I directly access the page via a browser it triggers the pixel successfully and I can see it in the Facebook pixel report. But when the request is redirected to the page after the insert to the db the pixel does not trigger.

I think its because the JavaScript and HTML is never added to the DOM so it never gets executed...

Do you know how can I achieve this?

I think if maybe I send an HTTP GET request to the  tag URL hopefully the Facebook accepts it..

UPDATE

So this is what happens, the request I send triggers the event, but @Jules is right. I can't find which ad led to a conversion using this method, the problem is that where pushing traffic to our clients website, in which we can't install any JavaScript code.

I tried to check what cookies Facebook stores so when I make the GET request I send those values too, but this happens:

1 - The ad sends the user to a link like this:

l.facebook.com/l.php?u=redirect_url&h=some_token_here

In this page I can check that there is some cookies (I assume these are the values Facebook needs to find which ad led to a conversion)

2 - Then the user is redirected to our clients form page

I tried to check the cookies here too but the cookies don't seem to exist..

I need help people!

Body:
You should not write HTML/Javascript code.

The first conversion pixel is called via an img tag so you cannot respond with HTML/Javascript.

All you have to do is return a redirect (301) to your final image pixel. In this case:

Redirect 301 THE_FB_URL/?id=PIXEL_ID&ev=myCustomEvent&noscript=1


问:
Excel vba: Reassign collection member
I have a Collection that stores Date objects. I want to check if a month of a date object is different from 1 and if so, set it to 1.

```<code>Sub displayColl()
    Dim globals As Object
    Set globals = getGlobalVariables()

    Dim dates As Collection
    Set dates = getResultDates(globals("MIN_DATE"), globals("MAX_DATE"), False)

    Dim i As Integer
    For i = 1 To dates.Count
         Debug.Print dates(i)
    Next

    Debug.Print "After"

    For i = 1 To dates.Count
        Debug.Print dates(i)
        dates(i) = DateSerial(year(dates(i)), 1, Day(dates(i)))
    Next
End Sub
</code>```

However, this code doesn't work - I get Object requered error. Why is that? What is the right way to do it?

EDIT:

getResultDates function isn't important. It simply returns a Collection of Dates.

The same goes for getGlobalVariables - it returns a dictionary with information from user, including minimum and maximum dates a user wrote.

The error occurs on line Set dates(i) = DateSerial(year(dates(i)), 1, Day(dates(i))).

Removing Set doesn't accomplish anything.

I am sure the dates Collection contains dates.

The debug output:

```<code>01.01.2014
01.02.2014
01.03.2014
01.04.2014
01.05.2014
01.06.2014
01.07.2014
01.08.2014
01.09.2014
01.10.2014
01.11.2014
01.12.2014
01.01.2015
01.02.2015
01.03.2015
01.04.2015
01.05.2015
01.06.2015
01.07.2015
01.08.2015
01.09.2015
01.10.2015
01.11.2015
01.12.2015
01.01.2016
01.02.2016
01.03.2016
01.04.2016
01.05.2016
01.06.2016
01.07.2016
01.08.2016
01.09.2016
01.10.2016
01.11.2016
01.12.2016
01.01.2017
After
01.01.2014
</code>```

答:
According to Microsoft's VBA docs:
https://msdn.microsoft.com/en-us/library/f26wd2e5(v=vs.100).aspx
you can add, delete and retrieve items of a collection. It doesn't suggest you can replace items directly as you could with a Java List for instance.

You could add in the new date and remove the old one.

This is also discussed in
How to change value of an item of a collection

Title: Excel vba: Reassign collection member

Body:
I have a Collection that stores Date objects. I want to check if a month of a date object is different from 1 and if so, set it to 1.

Sub displayColl()
    Dim globals As Object
    Set globals = getGlobalVariables()

    Dim dates As Collection
    Set dates = getResultDates(globals("MIN_DATE"), globals("MAX_DATE"), False)

    Dim i As Integer
    For i = 1 To dates.Count
         Debug.Print dates(i)
    Next

    Debug.Print "After"

    For i = 1 To dates.Count
        Debug.Print dates(i)
        dates(i) = DateSerial(year(dates(i)), 1, Day(dates(i)))
    Next
End Sub

However, this code doesn't work - I get Object requered error. Why is that? What is the right way to do it?

EDIT:

getResultDates function isn't important. It simply returns a Collection of Dates.

The same goes for getGlobalVariables - it returns a dictionary with information from user, including minimum and maximum dates a user wrote.

The error occurs on line Set dates(i) = DateSerial(year(dates(i)), 1, Day(dates(i))).

Removing Set doesn't accomplish anything.

I am sure the dates Collection contains dates.

The debug output:

01.01.2014
01.02.2014
01.03.2014
01.04.2014
01.05.2014
01.06.2014
01.07.2014
01.08.2014
01.09.2014
01.10.2014
01.11.2014
01.12.2014
01.01.2015
01.02.2015
01.03.2015
01.04.2015
01.05.2015
01.06.2015
01.07.2015
01.08.2015
01.09.2015
01.10.2015
01.11.2015
01.12.2015
01.01.2016
01.02.2016
01.03.2016
01.04.2016
01.05.2016
01.06.2016
01.07.2016
01.08.2016
01.09.2016
01.10.2016
01.11.2016
01.12.2016
01.01.2017
After
01.01.2014


问:
Why doesn't my div inside a span work properly?
I'm writing the following HTML markup:

```<code><span> Some Text
    <div id="ch">татата</div>
</span>
</code>```

and styles:

```<code>span{
    border: 1px solid black;
    text-align:center;
    width: 300px;
    height: 300px;
    background: aqua;
}
#ch{
    width:100px;
    height:100px
    background: yellow;
}
</code>```

jsFiddle

Why is the height property not applied to a div element which inside the span, but width is applied?

Why is the right border of my span is missing?

答:
First answer: You forgot the semi-colon after height style, that's why it is not rendered.

Second answer: If you look closely, the border appears after the div. This is because you
are inserting block level element inside inline element. So, block level element takes it to the next line and then it takes the whole line. On the very next line you can see the right border for the span.

It is bad practice to put block level element inside inline element. In fact, I do not see any practical use of this kind of structure. Please, correct it if you are learning.

Body:
I'm writing the following HTML markup:

 Some Text

татата

and styles:

span{
    border: 1px solid black;
    text-align:center;
    width: 300px;
    height: 300px;
    background: aqua;
}
#ch{
    width:100px;
    height:100px
    background: yellow;
}

jsFiddle

Why is the height property not applied to a div element which inside the span, but width is applied?

Why is the right border of my span is missing?


问:
Autodesk Forge API createBucket not working
I'm trying to build an application by using the autodesk-forge-api's. To start with I created an App inside my Autodesk configuration to receive an "ClientID" and a "Client Secret" which are required to make API calls.

Somehow, when I try to use the createBucket-API call, which is documentet here I get an answer bad request 400 and I dont't know why.

here is my API call:

```<code>let oAuth2TwoLegged = new ForgeSDK.AuthClientTwoLegged(clientId,
  clientSecret, [
  'data:read',
  'data:write',
  'bucket:create',
  'bucket:read',
  'data:write',
  'data:read',
  'viewables:read'
], autoRefresh);

oAuth2TwoLegged.authenticate().then(function(credentials){

  var HubsApi = new ForgeSDK.HubsApi(); //Hubs Client
  var BucketsApi = new ForgeSDK.BucketsApi(); //Buckets Client

  BucketsApi.createBucket({bucketKey :"Test", policyKey: "transient"},{}, oAuth2TwoLegged, credentials).then((response) => {
    console.log(' new BUCKET: ', response)
  }).catch((err) => {
    console.log('ERROR BLA: ', err)
  });

}).catch((err) => {
  console.log('oauth error: ', err)
})
</code>```

Does anyone have a suggestion what I might doing wrong?

when I use a different call, for example this:

```<code>BucketsApi.getBuckets({}, oAuth2TwoLegged, credentials).then(function(response){
   console.log('buckets: ', response.body);
  }, function(err){
    console.error(err);
});
</code>```

it works...

EDIT

If I do the following:

```<code>BucketsApi.createBucket(xyda_select_rtl, {'bucketKey' :'xyda_select_rtl',
   'policyKey': 'transient'}, oAuth2TwoLegged, credentials).then((response) => {
    console.log(' new BUCKET: ', response)
  }).catch((err) => {
    console.log('ERROR BLA: ', err)
});
</code>```

I get xyda_select_rtl is not defined!?!

When I add:

```<code>var xyda_select_rtl;
</code>```

I get the error Missing the required parameter 'postBuckets' when calling createBucket

Ehhm.... yeah :-/

答:
You need to come up with a unique name for your buckets, sorry for that bad news. It's not so bad that you think. For example simply add your client_id to the bucket name:

```<code>"test-tAp1fqjjtcgqS4CKpCYDjAyNbKW4IVCC"
</code>```

Or use a random guid generated by code:

```<code>function guid() {

    var d = new Date().getTime();

    var guid = 'xxxx-xxxx-xxxx'.replace(
      /[xy]/g,
      function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
      });

    return guid;
  }
</code>```

Then use it to generate a bucket name:

```<code>var bucketKey = "test-" + guid()
</code>```

Body:
I'm trying to build an application by using the autodesk-forge-api's. To start with I created an App inside my Autodesk configuration to receive an "ClientID" and a "Client Secret" which are required to make API calls.

Somehow, when I try to use the createBucket-API call, which is documentet here I get an answer bad request 400 and I dont't know why.

here is my API call:

let oAuth2TwoLegged = new ForgeSDK.AuthClientTwoLegged(clientId,
  clientSecret, [
  'data:read',
  'data:write',
  'bucket:create',
  'bucket:read',
  'data:write',
  'data:read',
  'viewables:read'
], autoRefresh);

oAuth2TwoLegged.authenticate().then(function(credentials){

  var HubsApi = new ForgeSDK.HubsApi(); //Hubs Client
  var BucketsApi = new ForgeSDK.BucketsApi(); //Buckets Client

  BucketsApi.createBucket({bucketKey :"Test", policyKey: "transient"},{}, oAuth2TwoLegged, credentials).then((response) => {
    console.log(' new BUCKET: ', response)
  }).catch((err) => {
    console.log('ERROR BLA: ', err)
  });

}).catch((err) => {
  console.log('oauth error: ', err)
})

Does anyone have a suggestion what I might doing wrong?

when I use a different call, for example this:

BucketsApi.getBuckets({}, oAuth2TwoLegged, credentials).then(function(response){
   console.log('buckets: ', response.body);
  }, function(err){
    console.error(err);
});

it works...

EDIT

If I do the following:

BucketsApi.createBucket(xyda_select_rtl, {'bucketKey' :'xyda_select_rtl',
   'policyKey': 'transient'}, oAuth2TwoLegged, credentials).then((response) => {
    console.log(' new BUCKET: ', response)
  }).catch((err) => {
    console.log('ERROR BLA: ', err)
});

I get xyda_select_rtl is not defined!?!

When I add:

var xyda_select_rtl;

I get the error Missing the required parameter 'postBuckets' when calling createBucket

Ehhm.... yeah :-/

Body:
You need to come up with a unique name for your buckets, sorry for that bad news. It's not so bad that you think. For example simply add your client_id to the bucket name:

"test-tAp1fqjjtcgqS4CKpCYDjAyNbKW4IVCC"

Or use a random guid generated by code:

function guid() {

    var d = new Date().getTime();

    var guid = 'xxxx-xxxx-xxxx'.replace(
      /[xy]/g,
      function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
      });

    return guid;
  }

Then use it to generate a bucket name:

var bucketKey = "test-" + guid()


问:
How can I avoid GWT compilation by creating different modules?
We are using GWT for our application. Now as size of application grows, it is taking long time to compile, around 20-25 mins, which cause delay in development.

We have different modules, but currently all are in single application, as we have single entry point class.
So, is there any way that I divide those modules, and then import them in main module. So that compilation will happen only for module which has changes?

答:
Why do you need to recompile your application ?

Using SuperDevMode the recompilation is very fast. I almost never do a full compile of my GWT application. Only before release.

Why is your compilation taking so long ?
How many permutations do you have ?

Try to reduce the number of permutations.

You can do this by not using GWTs i18n system but enrolling your own.
And not compiling for all browsers.

I only compile for safari,gecko1_8 and ie10. I don't really want people using my app with IE9 and older so I don't compile for these browsers.

Some people even only compile safari and say that it works no problem on all browsers.

I never really understand people complaining about the compilation time as it is almost never needed. And can probably be reduced drasticly.


问:
Disable/Enable a textbox in bootstrap modal form based on radio button click
I have a bootsrap modal form.In that if i click on the radio button,'For All Subjects','Subject' textbox should be in disabled state.Similarly,if I click on radio button 'Specific Subject', 'Subject' textbox should be enabled.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

        <button type="button" class="btn  btn-lg"
         data-toggle="modal" data-target="#addMasterData" >Add Master</button>

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

          Add Master

        <form id="mastercreate" action="addConfig" method="post">

          Subjects:
           <input type="radio" name="roleSubjectRadio" id="forAllSubjects"
           value="Yes"  >For All Subjects
            <input type="radio"
           name="roleSubjectRadio" id="specificFlights"
         value="Specific"  checked>Specific Subject
           <input type="hidden" class="form-control" id="specs" name="specs"
           value="">

            Subject
             Name: <input type="text" class="form-control" id="subNo"
             name="subNo" >

          <button type="button" class="btn btn-primary"
           onclick="addMaster()">Submit</button>
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

        </form>

```

Please suggest how to do it from javascript.

答:
Using javascript you can do this. Give onclick="disableSubjectField()" to the radio buttons:

```<code><div class="form-group">
  <label for="text">Subjects:</label> <label class="radio-inline">
  <input type="radio" name="roleSubjectRadio" id="forAllSubjects" value="Yes" onclick="disableSubjectField()" >For All Subjects
  </label> <label class="radio-inline">
  <input type="radio" name="roleSubjectRadio" id="specificFlights" value="Specific"  onclick="disableSubjectField()" checked>Specific Subject
  </label> <input type="hidden" class="form-control" id="specs" name="specs" value="">
</div>
</code>```

Then write this javascript to disable the Subject input field.

```<code>function disableSubjectField() {
   if(document.getElementById('forAllSubjects').checked) {
        document.getElementById('subNo').disabled = true;

    }else if(document.getElementById('specificFlights').checked) {
        document.getElementById('subNo').disabled = false;
    }
}
</code>```

Body:
I have a bootsrap modal form.In that if i click on the radio button,'For All Subjects','Subject' textbox should be in disabled state.Similarly,if I click on radio button 'Specific Subject', 'Subject' textbox should be enabled.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

        <button type="button" class="btn  btn-lg"
         data-toggle="modal" data-target="#addMasterData" >Add Master</button>

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

          Add Master

        <form id="mastercreate" action="addConfig" method="post">

          Subjects:
           <input type="radio" name="roleSubjectRadio" id="forAllSubjects"
           value="Yes"  >For All Subjects
            <input type="radio"
           name="roleSubjectRadio" id="specificFlights"
         value="Specific"  checked>Specific Subject
           <input type="hidden" class="form-control" id="specs" name="specs"
           value="">

            Subject
             Name: <input type="text" class="form-control" id="subNo"
             name="subNo" >

          <button type="button" class="btn btn-primary"
           onclick="addMaster()">Submit</button>
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

        </form>

Please suggest how to do it from javascript.

Body:
Using javascript you can do this. Give onclick="disableSubjectField()" to the radio buttons:

<div class="form-group">
  <label for="text">Subjects:</label> <label class="radio-inline">
  <input type="radio" name="roleSubjectRadio" id="forAllSubjects" value="Yes" onclick="disableSubjectField()" >For All Subjects
  </label> <label class="radio-inline">
  <input type="radio" name="roleSubjectRadio" id="specificFlights" value="Specific"  onclick="disableSubjectField()" checked>Specific Subject
  </label> <input type="hidden" class="form-control" id="specs" name="specs" value="">
</div>

Then write this javascript to disable the Subject input field.

function disableSubjectField() {
   if(document.getElementById('forAllSubjects').checked) {
        document.getElementById('subNo').disabled = true;

    }else if(document.getElementById('specificFlights').checked) {
        document.getElementById('subNo').disabled = false;
    }
}


问:
Must issue a STARTTLS command first when sending email from jenkins on Windows
I have jenkins installed on my windows desktop and having issues configuring it to send emails from my outlook account as it uses TLS instead of SSL. I have done some research and some forums suggested adding the JENKINS_JAVA_OPTIONS to the jenkins.xml file and doing a restart however this didn't work for me.

JENKINS_JAVA_OPTIONS      -Djava.awt.headless=true -Dmail.smtp.starttls.enable=true

My SMTP settings are
SERVER smtp-mail.outlook.com
SMTP PORT 587
Use SSL unchecked
Username *****
Password ******

Error is below
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first

```<code>  at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2057)

  at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1580)

  at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1097)

  at javax.mail.Transport.send0(Transport.java:195)

  at javax.mail.Transport.send(Transport.java:124)

  at hudson.tasks.Mailer$DescriptorImpl.doSendTestMail(Mailer.java:581)

  at java.lang.invoke.MethodHandle.invokeWithArguments(Unknown Source)

  at org.kohsuke.stapler.Function$MethodFunction.invoke(Function.java:343)

  at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:184)
</code>```

答:
You can configure jenkins configuration file to enable TLS. For ubuntu it is in the path /etc/default/jenkins.
Use following statement to do so.

```<code>JAVA_ARGS = "-Djava.awt.headless=true -Dmail.smtp.starttls.enable=true"
</code>```

it worked for me. good luck.

Body:
I have jenkins installed on my windows desktop and having issues configuring it to send emails from my outlook account as it uses TLS instead of SSL. I have done some research and some forums suggested adding the JENKINS_JAVA_OPTIONS to the jenkins.xml file and doing a restart however this didn't work for me.

JENKINS_JAVA_OPTIONS      -Djava.awt.headless=true -Dmail.smtp.starttls.enable=true

My SMTP settings are
SERVER smtp-mail.outlook.com
SMTP PORT 587
Use SSL unchecked
Username *****
Password ******

Error is below
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first

  at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2057)

  at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1580)

  at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1097)

  at javax.mail.Transport.send0(Transport.java:195)

  at javax.mail.Transport.send(Transport.java:124)

  at hudson.tasks.Mailer$DescriptorImpl.doSendTestMail(Mailer.java:581)

  at java.lang.invoke.MethodHandle.invokeWithArguments(Unknown Source)

  at org.kohsuke.stapler.Function$MethodFunction.invoke(Function.java:343)

  at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:184)

Body:
You can configure jenkins configuration file to enable TLS. For ubuntu it is in the path /etc/default/jenkins.
Use following statement to do so.

JAVA_ARGS = "-Djava.awt.headless=true -Dmail.smtp.starttls.enable=true"

it worked for me. good luck.


问:
MSSQL 2008 Trigger - where variable = common value between two tables
new to Triggers, i created one that works when i hard code the value that i actually need to list as a variable. as in the code, table tbl_measure_stats has trigger StatsTrigger. When tbl_measure_stats changes, it sets tbl_activity.override = 0 WHERE tbl_activity.activityid is supposed to equal the tbl_measure_status.actid. The value in the trigger table is tbl_measures_stats.actid, which is supposed to equal the id of tbl_activity.activityid, whose value override i need to set to 0. How do I code the variable related to 54321? Code is actually simpler than my explanation:

```<code>USE [TestDB]
GO
/****** OBJECT: Trigger [dbo].[StatsTrigger]  ******/
/****** PURPOSE: detect any field changes in tbl_measure_stats ******/
/****** ... then set tbl_activity.override = 0 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
ALTER TRIGGER [dbo].[StatsTrigger] --resides in tbl_measure_stats>Triggers
ON  tbl_measure_stats --table which has the trigger
AFTER INSERT,DELETE,UPDATE --when something changes...
AS UPDATE tbl_activity set override = 0 where tbl_activity.activityid = 54321
</code>```

seems like this should be a straight forward solution but i am finding nothing actionable in all my searches. OLD, NEW, inserted for example... i am not getting those to work. Example when trying "inserted":

```<code>AS UPDATE cpy_activity set porc = 0 where cpy_activity.activityid = inserted.actid
</code>```

returns the error:

```<code>The multi-part identifier "inserted.actid" could not be bound.
</code>```

ideas?

答:
You probably need to include INSERTED in the FROM clause of the query.

```<code>ALTER TRIGGER [dbo].[StatsTrigger] --resides in tbl_measure_stats>Triggers
ON  tbl_measure_stats --table which has the trigger
AFTER INSERT,DELETE,UPDATE --when something changes...
AS
  UPDATE A SET override = 0
  FROM tbl_Activity A JOIN INSERTED I ON A.activityID = I.actid
</code>```

Note however that INSERTED won't have any rows when the trigger fires because of a DELETE action. You should check whether INSERTED or DELETED have rows and do the right thing accordingly.

Body:
new to Triggers, i created one that works when i hard code the value that i actually need to list as a variable. as in the code, table tbl_measure_stats has trigger StatsTrigger. When tbl_measure_stats changes, it sets tbl_activity.override = 0 WHERE tbl_activity.activityid is supposed to equal the tbl_measure_status.actid. The value in the trigger table is tbl_measures_stats.actid, which is supposed to equal the id of tbl_activity.activityid, whose value override i need to set to 0. How do I code the variable related to 54321? Code is actually simpler than my explanation:

USE [TestDB]
GO
/****** OBJECT: Trigger [dbo].[StatsTrigger]  ******/
/****** PURPOSE: detect any field changes in tbl_measure_stats ******/
/****** ... then set tbl_activity.override = 0 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
ALTER TRIGGER [dbo].[StatsTrigger] --resides in tbl_measure_stats>Triggers
ON  tbl_measure_stats --table which has the trigger
AFTER INSERT,DELETE,UPDATE --when something changes...
AS UPDATE tbl_activity set override = 0 where tbl_activity.activityid = 54321

seems like this should be a straight forward solution but i am finding nothing actionable in all my searches. OLD, NEW, inserted for example... i am not getting those to work. Example when trying "inserted":

AS UPDATE cpy_activity set porc = 0 where cpy_activity.activityid = inserted.actid

returns the error:

The multi-part identifier "inserted.actid" could not be bound.

ideas?

Body:
You probably need to include INSERTED in the FROM clause of the query.

ALTER TRIGGER [dbo].[StatsTrigger] --resides in tbl_measure_stats>Triggers
ON  tbl_measure_stats --table which has the trigger
AFTER INSERT,DELETE,UPDATE --when something changes...
AS
  UPDATE A SET override = 0
  FROM tbl_Activity A JOIN INSERTED I ON A.activityID = I.actid

Note however that INSERTED won't have any rows when the trigger fires because of a DELETE action. You should check whether INSERTED or DELETED have rows and do the right thing accordingly.


问:
SAS put data to Excel via DDE
I want to write some data to Excel via DDE and have the following code:

```<code>option noxwait noxsync;
x call "C:\Program Files (x86)\Microsoft Office\Office15\EXCEL.EXE";

%let delay=5;
data _null_;
    rc=sleep(&delay);
run;

filename random dde 'excel|Tabelle1!r1c1:r100c3';
data _null_;
    set sashelp.class;
    file random;
    put name sex age;
run;
</code>```

Excel opens successfully however the sheet remains empty. The log tells me that 19 records were written to the file RANDOM.

Any suggestions why the data is not written to my Excel sheet? Could it be connected with my language settings (German) in Excel?

答:
NOXSYNC is a mistake here.

Basically, what happens when I run this at least is it won't work if NOXSYNC is set, because it tries to write to the excel sheet before Excel is ready for it.  You need XSYNC to have SAS wait for the X command to complete.

If XSYNC is something you can't deal with, then you will need to add a manual delay.

I'd also verify that you don't have Excel open before running this, as if you do it may be writing to a different Excel workbook than the one it's opening.

Title: SAS put data to Excel via DDE

Body:
I want to write some data to Excel via DDE and have the following code:

option noxwait noxsync;
x call "C:\Program Files (x86)\Microsoft Office\Office15\EXCEL.EXE";

%let delay=5;
data _null_;
    rc=sleep(&delay);
run;

filename random dde 'excel|Tabelle1!r1c1:r100c3';
data _null_;
    set sashelp.class;
    file random;
    put name sex age;
run;

Excel opens successfully however the sheet remains empty. The log tells me that 19 records were written to the file RANDOM.

Any suggestions why the data is not written to my Excel sheet? Could it be connected with my language settings (German) in Excel?


问:
VBA code works fine in Excel 2013 but gives error in excel 2016 - Compile error
I am reaching out to everyone after searching a lot for the solution.
I have a code that works fine in Excel 2013 but when i try to run the same code in excel 2016 it gives me compile error.

This code was developed by someone else and i was just doing minor modification to it. Below is the code. The error is happening due to Environ$ variable. Because that what is highlighted when i press ok button in the given screenshot.

```<code>Function RangetoHTML(rng As Range)
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook

TempFile = Environ("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
    .Cells(1).PasteSpecial Paste:=8
    .Cells(1).PasteSpecial xlPasteValues, , False, False
    .Cells(1).PasteSpecial xlPasteFormats, , False, False
    .Cells(1).Select
    Application.CutCopyMode = False
    On Error Resume Next
    .DrawingObjects.Visible = True
    .DrawingObjects.Delete
    On Error GoTo 0
End With

'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
     SourceType:=xlSourceRange, _
     Filename:=TempFile, _
     Sheet:=TempWB.Sheets(1).Name, _
     Source:=TempWB.Sheets(1).UsedRange.Address, _
     HtmlType:=xlHtmlStatic)
    .Publish (True)
End With

'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.ReadAll
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                      "align=left x:publishsource=")

'Close TempWB
TempWB.Close savechanges:=False

'Delete the htm file we used in this function
Kill TempFile

Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
</code>```

I am also attaching error screen shot.

Environ$ variable compile error

Any quick help will be much appriciated.

答:
Just had the same error from Ron de Bruin rangetohtml(rng as range).

I have resolved.

If you go back to the code before
On Error Resume Next
and comment out.

run and you will see it can't find the drawingobjects.visible.

to fix.

go to file/options/formulas/

make sure it isn't R1C1  - uncheck this box.

Mine worked fine after this.

Body:
I am reaching out to everyone after searching a lot for the solution.
I have a code that works fine in Excel 2013 but when i try to run the same code in excel 2016 it gives me compile error.

This code was developed by someone else and i was just doing minor modification to it. Below is the code. The error is happening due to Environ$ variable. Because that what is highlighted when i press ok button in the given screenshot.

Function RangetoHTML(rng As Range)
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook

TempFile = Environ("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
    .Cells(1).PasteSpecial Paste:=8
    .Cells(1).PasteSpecial xlPasteValues, , False, False
    .Cells(1).PasteSpecial xlPasteFormats, , False, False
    .Cells(1).Select
    Application.CutCopyMode = False
    On Error Resume Next
    .DrawingObjects.Visible = True
    .DrawingObjects.Delete
    On Error GoTo 0
End With

'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
     SourceType:=xlSourceRange, _
     Filename:=TempFile, _
     Sheet:=TempWB.Sheets(1).Name, _
     Source:=TempWB.Sheets(1).UsedRange.Address, _
     HtmlType:=xlHtmlStatic)
    .Publish (True)
End With

'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.ReadAll
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                      "align=left x:publishsource=")

'Close TempWB
TempWB.Close savechanges:=False

'Delete the htm file we used in this function
Kill TempFile

Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function

I am also attaching error screen shot.

Environ$ variable compile error

Any quick help will be much appriciated.


问:
Create inherited class from base class
```<code>public class Car
{
    private string make;
    private string model;
    public Car(string make, string model)
    {
         this.make = make;
         this.model = model;
    }
    public virtual void Display()
    {
       Console.WriteLine("Make: {0}", make);
       Console.WriteLine("Model: {0}", model);
    }
    public string Make
    {
       get{return make;}
       set{make = value;}
    }
    public string Model
    {
       get{return model;}
       set{model = value;}
    }
}

public class SuperCar:Car
{
    private Car car;
    private int horsePower;
    public SuperCar(Car car)
    {
        this.car = car;
    }
    public int HorsePower
    {
       get{return horsePower;}
       set{horsepower = value;}
    }
    public override void Display()
    {
       base.Display();
       Console.WriteLine("I am a super car");
}
</code>```

When I do something like

```<code>Car myCar = new Car("Porsche", "911");
SuperCar mySupcar = new SuperCar(myCar);
mySupcar.Display();
</code>```

I only get "I am a supercar" but not the properties of my base class. Should I explicitly assign the properties of my base class in the SuperCar constructor? In fact I'm trying Decorator pattern where I want a class to add behaviour to a base class.

答:
Based on @JoshWheelock answer I wrote this method that I put in a shared file of my Xamarin project

It clones classes, so you can use to duplicate a base classe the heiress, you could adjust the T param

```<code>//...
#if WINDOWS_UWP
using System.Reflection;
#endif
//...

public void CloneIn<T>(T src, T dest)
{
#if WINDOWS_UWP
    var props = typeof(T).GetTypeInfo().DeclaredProperties.Where(p => !p.GetIndexParameters().Any());
#else
    var props = typeof(T).GetProperties().Where(p => !p.GetIndexParameters().Any());
#endif
    foreach (var prop in props)
    {
        if(prop.SetMethod!=null)
            prop.SetValue(dest, prop.GetValue(src));
    }
}
</code>```

Not yet tested in Android and iOS, concerning Android I have my emulator that soddenly stopped working properly since a week ...

ContentLicense: CC BY-SA 2.5

Title: Create inherited class from base class

Body:
public class Car
{
    private string make;
    private string model;
    public Car(string make, string model)
    {
         this.make = make;
         this.model = model;
    }
    public virtual void Display()
    {
       Console.WriteLine("Make: {0}", make);
       Console.WriteLine("Model: {0}", model);
    }
    public string Make
    {
       get{return make;}
       set{make = value;}
    }
    public string Model
    {
       get{return model;}
       set{model = value;}
    }
}

public class SuperCar:Car
{
    private Car car;
    private int horsePower;
    public SuperCar(Car car)
    {
        this.car = car;
    }
    public int HorsePower
    {
       get{return horsePower;}
       set{horsepower = value;}
    }
    public override void Display()
    {
       base.Display();
       Console.WriteLine("I am a super car");
}

When I do something like

Car myCar = new Car("Porsche", "911");
SuperCar mySupcar = new SuperCar(myCar);
mySupcar.Display();

I only get "I am a supercar" but not the properties of my base class. Should I explicitly assign the properties of my base class in the SuperCar constructor? In fact I'm trying Decorator pattern where I want a class to add behaviour to a base class.

Body:
Based on @JoshWheelock answer I wrote this method that I put in a shared file of my Xamarin project

It clones classes, so you can use to duplicate a base classe the heiress, you could adjust the T param

//...
#if WINDOWS_UWP
using System.Reflection;
#endif
//...

public void CloneIn<T>(T src, T dest)
{
#if WINDOWS_UWP
    var props = typeof(T).GetTypeInfo().DeclaredProperties.Where(p => !p.GetIndexParameters().Any());
#else
    var props = typeof(T).GetProperties().Where(p => !p.GetIndexParameters().Any());
#endif
    foreach (var prop in props)
    {
        if(prop.SetMethod!=null)
            prop.SetValue(dest, prop.GetValue(src));
    }
}

Not yet tested in Android and iOS, concerning Android I have my emulator that soddenly stopped working properly since a week ...


问:
What is the status of HTML5 Database?
This spec http://www.w3.org/TR/webdatabase/ says:

This document was on the W3C Recommendation track but specification work has stopped. The specification reached an impasse: all interested implementors have used the same SQL backend (Sqlite), but we need multiple independent implementations to proceed along a standardisation path.

Does this mean that HTML5 database is going away, and for some time we will have a de-facto standard using SQLite, possibly with browser differences? Or has the W3C published a plan of attack for finishing the standard?

答:
According to this article:

[...] we think it is worth explaining our design choices, and why we think IndexedDB is a better solution for the web than Web SQL Database.

In another article, we compare IndexedDB with Web SQL Database, and note that the former provides much syntactic simplicity over the latter. IndexedDB leaves room for a third-party JavaScript library to straddle the underlying primitives with a BTree API, and we look forward to seeing initiatives like BrowserCouch built on top of IndexedDB. Intrepid web developers can even build a SQL API on top of IndexedDB. We’d particularly welcome an implementation of the Web SQL Database API on top of IndexedDB, since we think that this is technically feasible. Starting with a SQL-based API for use with browser primitives wasn’t the right first step, but certainly there’s room for SQL-based APIs on top of IndexedDB.

I'm not personally swayed by the arguments put forth in the article, but it seems clear that (for the time being) Mozilla has decided that Web SQL Database is dead.

Further interesting comments about this article may be found on Hacker News.

Title: What is the status of HTML5 Database?


问:
How to find records that exist in all 4 tables? SQL Server 2008
I have to migrate records from one system to another. There is 4 different tables. First table contains all information about each user. Each row has unique ID that is primary key. So I need to grab primary key from table one and find matching record in other 3 tables. Those tables have foreign key that we should use to match users. Here is example:

```<code>SELECT *
FROM Users AS ur
WHERE EXISTS(
    SELECT *
    FROM TableA AS a
    WHERE ur.ur_id = a.a_urid
)

//Maybe second option can be to use INNER JOIN
SELECT *
FROM Users AS ur
    INNER JOIN TableA AS a
        ON ur.ur_id = a.a_urid
    INNER JOIN TableB AS b
        ON ur.ur_id = b.b_urid
    INNER JOIN TableC AS c
        ON ur.ur_id = c.c_urid
</code>```

Query above will return matching records only for Users and Table A. I'm wondering if I can match all records from Users table that have matching user ID in table A, B and C. How that can be achieved in SQL Server 2008? Or I would need to add/import each table individually? If anyone can help with this task please let me know. Thank you!

答:
You can use intersect:

```<code>select u.id
from users u
intersect
select a.a_urid
from a
intersect
select b.b_urid
from b
intersect
select c.c_urid
from c;
</code>```

Another way is to use exists:

```<code>SELECT ur.*
FROM Users ur
WHERE EXISTS (SELECT 1 FROM TableA AS a WHERE ur.ur_id = a.a_urid) AND
      EXISTS (SELECT 1 FROM TableB AS b WHERE ur.ur_id = b.b_urid) AND
      EXISTS (SELECT 1 FROM TableC AS c WHERE ur.ur_id = c.c_urid) ;
</code>```

Using a JOIN, you have to be careful.  The result set might contain duplicates.  And removing the duplicates could be very expensive.

Body:
I have to migrate records from one system to another. There is 4 different tables. First table contains all information about each user. Each row has unique ID that is primary key. So I need to grab primary key from table one and find matching record in other 3 tables. Those tables have foreign key that we should use to match users. Here is example:

SELECT *
FROM Users AS ur
WHERE EXISTS(
    SELECT *
    FROM TableA AS a
    WHERE ur.ur_id = a.a_urid
)

//Maybe second option can be to use INNER JOIN
SELECT *
FROM Users AS ur
    INNER JOIN TableA AS a
        ON ur.ur_id = a.a_urid
    INNER JOIN TableB AS b
        ON ur.ur_id = b.b_urid
    INNER JOIN TableC AS c
        ON ur.ur_id = c.c_urid

Query above will return matching records only for Users and Table A. I'm wondering if I can match all records from Users table that have matching user ID in table A, B and C. How that can be achieved in SQL Server 2008? Or I would need to add/import each table individually? If anyone can help with this task please let me know. Thank you!

Body:
You can use intersect:

select u.id
from users u
intersect
select a.a_urid
from a
intersect
select b.b_urid
from b
intersect
select c.c_urid
from c;

Another way is to use exists:

SELECT ur.*
FROM Users ur
WHERE EXISTS (SELECT 1 FROM TableA AS a WHERE ur.ur_id = a.a_urid) AND
      EXISTS (SELECT 1 FROM TableB AS b WHERE ur.ur_id = b.b_urid) AND
      EXISTS (SELECT 1 FROM TableC AS c WHERE ur.ur_id = c.c_urid) ;

Using a JOIN, you have to be careful.  The result set might contain duplicates.  And removing the duplicates could be very expensive.


问:
Django: how to stay DRY using custom querysets with Q object?
In the custom queryset example bellow, the displayable method uses a combination of permanent and scheduled method. It works, but as you can see, I'm repeating myself:

```<code>class ArticlesByCategoryQuerySet(models.QuerySet):
    def permanent(self):
        return self.filter(is_permanent=True)

    def scheduled(self, service):
        return self.filter(scheduled_services__in=[service])

    def displayable(self, service):
        complex_query = Q(is_permanent=True) | Q(scheduled_services__in=[service])
        return self.filter(complex_query)
</code>```

What is the correct syntax to use Q() and stay DRY? I didn't find such an example in Django documentation.
I tried something like that, but it raises a ValueError: too many values to unpack (expected 2):

```<code>def displayable(self, service):
    complex_query = Q(self.permanent()) | Q(self.scheduled(service))
    return self.filter(complex_query)
</code>```

Thanks for your help.

答:
You can use union() method of queryset New in Django 1.11, It uses SQL’s UNION operator to combine the results of two or more QuerySets.

```<code>def displayable(self, service):
    qs1 = self.permanent()
    qs2 = self.scheduled(service)
    return qs1.union(qs2)
</code>```

The UNION operator selects only distinct values by default. To allow duplicate values, use the all=True argument.

UPDATE

Both are used to merge/combine querysets, union() is New in Django 1.11

Major difference is *union(other_qs, all=False) return model instances of the type of the first QuerySet even if the arguments are QuerySets of other models.

The union operator for QuerySets is | the pipe symbol, only works on querysets from the same model and before slicing it.

Body:
In the custom queryset example bellow, the displayable method uses a combination of permanent and scheduled method. It works, but as you can see, I'm repeating myself:

class ArticlesByCategoryQuerySet(models.QuerySet):
    def permanent(self):
        return self.filter(is_permanent=True)

    def scheduled(self, service):
        return self.filter(scheduled_services__in=[service])

    def displayable(self, service):
        complex_query = Q(is_permanent=True) | Q(scheduled_services__in=[service])
        return self.filter(complex_query)

What is the correct syntax to use Q() and stay DRY? I didn't find such an example in Django documentation.
I tried something like that, but it raises a ValueError: too many values to unpack (expected 2):

def displayable(self, service):
    complex_query = Q(self.permanent()) | Q(self.scheduled(service))
    return self.filter(complex_query)

Thanks for your help.

Body:
You can use union() method of queryset New in Django 1.11, It uses SQL’s UNION operator to combine the results of two or more QuerySets.

def displayable(self, service):
    qs1 = self.permanent()
    qs2 = self.scheduled(service)
    return qs1.union(qs2)

The UNION operator selects only distinct values by default. To allow duplicate values, use the all=True argument.

UPDATE

Both are used to merge/combine querysets, union() is New in Django 1.11

Major difference is *union(other_qs, all=False) return model instances of the type of the first QuerySet even if the arguments are QuerySets of other models.

The union operator for QuerySets is | the pipe symbol, only works on querysets from the same model and before slicing it.


问:
Can GPS location be acquired in a phone without internet and SIM?
I'm trying to develop an android application which can acquire GPS location without using Internet and even network location using SIM. Actually, SIM will be inserted in phone and i know that location upto 500m accurate can be acquired through it. But in case of no SIM signals in the area, is it possible to acquire location?</p>

答:
Yes You can get the coordinates but for using map services you need internet.The only thing is your GPS will take a bit longer to lock your location on a cold start, and it might not be quite as accurate.

It's a aGPS (Assisted GPS), and get's part of the location information from the data network (If available) on cold start, then fine-tunes the location further than what a GPS alone can do.

Shouldn't be an issue however, really. Just turn your GPS on a little sooner (Like while getting ready to leave, not waiting until you are in your car).


问:
malloc : error double free with printf and a NULL wchar_t*
I'm trying to port an application from Linux to Mac Os X (leopard), but when I execute it, I have this error message : malloc: *** error for object 0x100160 : double free.

I've reproduced this issue with the code below :

```<code>//main.cpp
#include <stdio.h>
#include <wchar.h>

int main(int argc, char*argv[])
{
    wchar_t *b=NULL;
    printf("a=%ls, b=%ls \n", L"a", b);
}
</code>```

Compiled with gcc:

```<code>gcc main.cpp -o test
</code>```

The output of the execution:

```<code>a=a, b=(null)
test (5337) malloc: *** error for object 0x100160 : double free
*** set a breakpoint in malloc_error_break to debug
</code>```

It's strange because if I use this line : printf("a=%ls, b=%ls", b, b), no error are printed.
Furthermore, I can't use wprintf(L"a=%ls, b=%ls", a, b).
On Fedora 13, this program don't print any error.

Is it a printf bug?
How can I remove this error?

答:
Although it is not a good practice to pass a NULL pointer to printf, from generic point of view I cannot accept a situation when any function (including printf) reacts to an invalid input by destroying memory heap. So although you should not pass a NULL there I consider this behavior as a bug in library. If a function gets invalid arguments it can scream a lot but is not supposed to destroy memory heap.

Of course sometimes it is not possible to know if a parameter is valid, but here we have a NULL constant and it is simple to know that it cannot be dereferenced or something.

Body:
I'm trying to port an application from Linux to Mac Os X (leopard), but when I execute it, I have this error message : malloc: *** error for object 0x100160 : double free.

I've reproduced this issue with the code below :

//main.cpp
#include <stdio.h>
#include <wchar.h>

int main(int argc, char*argv[])
{
    wchar_t *b=NULL;
    printf("a=%ls, b=%ls \n", L"a", b);
}

Compiled with gcc:

gcc main.cpp -o test

The output of the execution:

a=a, b=(null)
test (5337) malloc: *** error for object 0x100160 : double free
*** set a breakpoint in malloc_error_break to debug

It's strange because if I use this line : printf("a=%ls, b=%ls", b, b), no error are printed.
Furthermore, I can't use wprintf(L"a=%ls, b=%ls", a, b).
On Fedora 13, this program don't print any error.

Is it a printf bug?
How can I remove this error?


问:
Why so much memory?
I have a 1000x1500 pixel bitmap of which I want to make a mutable copy in Android.

When I run the following code...

```<code>// int width = original.getWidth(); // 1000px
// int height = original.getHeight(); // 1500px
final Bitmap result = original.copy(original.getConfig(), true);
original.recycle();
</code>```

...I get an OutOfMemoryError on the copy line:

```<code>java.lang.OutOfMemoryError: bitmap size exceeds VM budget
ERROR/GraphicsJNI(419): VM won't let us allocate 6000000 bytes
</code>```

Why does the copy instruction need 6MB (!) for a 1000x1500 pixel bitmap?

How can I create a mutable bitmap from a non-mutable one in more memory-efficient way?

Edit

BitmapFactory returns inmutable bitmaps. Apparently, the only way of creating a mutable bitmap from an immutable one is to copy it into a new mutable bitmap. In the case of a 1000x1500 bitmap, this apparently requires 12MB (1000x1500x4x2), which causes an OutOfMemoryError in most Android devices.

Is this problem unsolvable in Android then?

答:
cdonner put me in the right direction.

Turns out that the original bitmap was using ARGB_8888, which requires 32 bits per pixel and is more than what was needed for this particular app.

Changing the bitmap config to RGB_565, which requires 16 bits per pixel, reduced memory consumption by half.

Title: Why so much memory?

Body:
I have a 1000x1500 pixel bitmap of which I want to make a mutable copy in Android.

When I run the following code...

// int width = original.getWidth(); // 1000px
// int height = original.getHeight(); // 1500px
final Bitmap result = original.copy(original.getConfig(), true);
original.recycle();

...I get an OutOfMemoryError on the copy line:

java.lang.OutOfMemoryError: bitmap size exceeds VM budget
ERROR/GraphicsJNI(419): VM won't let us allocate 6000000 bytes

Why does the copy instruction need 6MB (!) for a 1000x1500 pixel bitmap?

How can I create a mutable bitmap from a non-mutable one in more memory-efficient way?

Edit

BitmapFactory returns inmutable bitmaps. Apparently, the only way of creating a mutable bitmap from an immutable one is to copy it into a new mutable bitmap. In the case of a 1000x1500 bitmap, this apparently requires 12MB (1000x1500x4x2), which causes an OutOfMemoryError in most Android devices.

Is this problem unsolvable in Android then?


问:
local luarocks package install (luarepl) does not work
I'm new to luarocks and I just tried to install luarepl.
The installation apparently went fine:

```<code>$ luarocks install luarepl
Installing https://luarocks.org/luarepl-0.8-1.rockspec...
Using https://luarocks.org/luarepl-0.8-1.rockspec... switching to 'build' mode
Updating manifest for /Users/me/.luarocks/lib/luarocks/rocks-5.1
luarepl 0.8-1 is now built and installed in /Users/me/.luarocks (license: MIT/X11)
</code>```

but if I try to launch the executable, it seems that the installation is broken:

```<code>$ ~/.luarocks/bin/rep.lua
/usr/local/bin/lua5.1: ...cks/lib/luarocks/rocks-5.1/luarepl/0.8-1/bin/rep.lua:23: module 'repl.console' not found:
    no field package.preload['repl.console']
    no file './repl/console.lua'
    no file '/usr/local/share/lua/5.1/repl/console.lua'
    no file '/usr/local/share/lua/5.1/repl/console/init.lua'
    no file '/usr/local/lib/lua/5.1/repl/console.lua'
    no file '/usr/local/lib/lua/5.1/repl/console/init.lua'
    no file './repl/console.so'
    no file '/usr/local/lib/lua/5.1/repl/console.so'
    no file '/usr/local/lib/lua/5.1/loadall.so'
    no file './repl.so'
    no file '/usr/local/lib/lua/5.1/repl.so'
    no file '/usr/local/lib/lua/5.1/loadall.so'
stack traceback:
    [C]: in function 'require'
    ...cks/lib/luarocks/rocks-5.1/luarepl/0.8-1/bin/rep.lua:23: in main chunk
    [C]: ?
</code>```

I look into the ~/.luarocks dir:

```<code>$ cd ~ ; find .luarocks
.luarocks
.luarocks/bin
.luarocks/bin/rep.lua
.luarocks/config.lua
.luarocks/lib
.luarocks/lib/luarocks
.luarocks/lib/luarocks/rocks-5.1
.luarocks/lib/luarocks/rocks-5.1/luarepl
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1/bin
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1/bin/rep.lua
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1/doc
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1/doc/COPYING
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1/doc/IDEAS.md
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1/doc/plugins.md
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1/doc/README.md
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1/doc/Roadmap.md
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1/luarepl-0.8-1.rockspec
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1/rock_manifest
.luarocks/lib/luarocks/rocks-5.1/manifest
.luarocks/share
.luarocks/share/lua
.luarocks/share/lua/5.1
.luarocks/share/lua/5.1/repl
.luarocks/share/lua/5.1/repl/console.lua
.luarocks/share/lua/5.1/repl/init.lua
.luarocks/share/lua/5.1/repl/plugins
.luarocks/share/lua/5.1/repl/plugins/autoreturn.lua
.luarocks/share/lua/5.1/repl/plugins/completion.lua
.luarocks/share/lua/5.1/repl/plugins/example.lua
.luarocks/share/lua/5.1/repl/plugins/filename_completion.lua
.luarocks/share/lua/5.1/repl/plugins/history.lua
.luarocks/share/lua/5.1/repl/plugins/keep_last_eval.lua
.luarocks/share/lua/5.1/repl/plugins/linenoise.lua
.luarocks/share/lua/5.1/repl/plugins/pretty_print.lua
.luarocks/share/lua/5.1/repl/plugins/rcfile.lua
.luarocks/share/lua/5.1/repl/plugins/rlwrap.lua
.luarocks/share/lua/5.1/repl/plugins/semicolon_suppress_output.lua
.luarocks/share/lua/5.1/repl/sync.lua
.luarocks/share/lua/5.1/repl/utils.lua
</code>```

and I can find that stuff.
I tried adding a line to config.lua to load packages from local installation to no avail:

```<code>$ cat ~/.luarocks/config.lua
local_by_default=true
</code>```

(removing it has no effect)

did I miss some obvious step?

running luarocks with no arguments gives me:

```<code>CONFIGURATION
    Lua version: 5.1
    Configuration files:
        System: /usr/local/etc/luarocks51/config-5.1.lua (ok)
        User  : /Users/me/.luarocks/config.lua (ok)

    Rocks trees in use:
        /Users/me/.luarocks ("user")
        /usr/local ("system")
</code>```

it seems that the user rock tree is not in the package path:

```<code>$ lua
Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio
> print(package.path)
./?.lua;/usr/local/share/lua/5.1/?.lua;/usr/local/share/lua/5.1/?/init.lua;/usr/local/lib/lua/5.1/?.lua;/usr/local/lib/lua/5.1/?/init.lua
</code>```

why?

答:
From https://github.com/luarocks/luarocks/wiki/Using-LuaRocks:

Most LuaRocks installations will feature two rocks trees:

"system" rock tree (used by default)

"user" rock tree

To be able to use the module, we need to make sure that Lua can find that dkjson.lua file when we run require("dkjson"). You can check your Lua paths from the Lua environment, using

```<code>print(package.path)
print(package.cpath)
</code>```

These variables can be pre-configured from outside Lua, using the LUA_PATH and LUA_CPATH environment variables.

If you installed both Lua and LuaRocks in their default directories (/usr/local on Linux and Mac OSX), then the "system" tree is /usr/local and it will work by default. However, the "user" tree (for installing rocks without admin privileges) is not detected by Lua by default. For that we'll need to configure these environment variables.

LuaRocks offers a semi-automated way to do this. If you type the following command:

```<code>luarocks path --bin
</code>```

it will print commands suitable for your platform for setting up your environment. On typical Unix terminal environments, you can type this:

```<code>eval $(luarocks path --bin)
</code>```

and it apply the changes, temporarily, to your shell. To have these variables set permanently, you have to configure the environment variables to your shell configuration (for example, by adding the above line to your .bashrc file if your shell is Bash).

Body:
I'm new to luarocks and I just tried to install luarepl.
The installation apparently went fine:

$ luarocks install luarepl
Installing https://luarocks.org/luarepl-0.8-1.rockspec...
Using https://luarocks.org/luarepl-0.8-1.rockspec... switching to 'build' mode
Updating manifest for /Users/me/.luarocks/lib/luarocks/rocks-5.1
luarepl 0.8-1 is now built and installed in /Users/me/.luarocks (license: MIT/X11)

but if I try to launch the executable, it seems that the installation is broken:

$ ~/.luarocks/bin/rep.lua
/usr/local/bin/lua5.1: ...cks/lib/luarocks/rocks-5.1/luarepl/0.8-1/bin/rep.lua:23: module 'repl.console' not found:
    no field package.preload['repl.console']
    no file './repl/console.lua'
    no file '/usr/local/share/lua/5.1/repl/console.lua'
    no file '/usr/local/share/lua/5.1/repl/console/init.lua'
    no file '/usr/local/lib/lua/5.1/repl/console.lua'
    no file '/usr/local/lib/lua/5.1/repl/console/init.lua'
    no file './repl/console.so'
    no file '/usr/local/lib/lua/5.1/repl/console.so'
    no file '/usr/local/lib/lua/5.1/loadall.so'
    no file './repl.so'
    no file '/usr/local/lib/lua/5.1/repl.so'
    no file '/usr/local/lib/lua/5.1/loadall.so'
stack traceback:
    [C]: in function 'require'
    ...cks/lib/luarocks/rocks-5.1/luarepl/0.8-1/bin/rep.lua:23: in main chunk
    [C]: ?

I look into the ~/.luarocks dir:

$ cd ~ ; find .luarocks
.luarocks
.luarocks/bin
.luarocks/bin/rep.lua
.luarocks/config.lua
.luarocks/lib
.luarocks/lib/luarocks
.luarocks/lib/luarocks/rocks-5.1
.luarocks/lib/luarocks/rocks-5.1/luarepl
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1/bin
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1/bin/rep.lua
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1/doc
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1/doc/COPYING
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1/doc/IDEAS.md
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1/doc/plugins.md
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1/doc/README.md
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1/doc/Roadmap.md
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1/luarepl-0.8-1.rockspec
.luarocks/lib/luarocks/rocks-5.1/luarepl/0.8-1/rock_manifest
.luarocks/lib/luarocks/rocks-5.1/manifest
.luarocks/share
.luarocks/share/lua
.luarocks/share/lua/5.1
.luarocks/share/lua/5.1/repl
.luarocks/share/lua/5.1/repl/console.lua
.luarocks/share/lua/5.1/repl/init.lua
.luarocks/share/lua/5.1/repl/plugins
.luarocks/share/lua/5.1/repl/plugins/autoreturn.lua
.luarocks/share/lua/5.1/repl/plugins/completion.lua
.luarocks/share/lua/5.1/repl/plugins/example.lua
.luarocks/share/lua/5.1/repl/plugins/filename_completion.lua
.luarocks/share/lua/5.1/repl/plugins/history.lua
.luarocks/share/lua/5.1/repl/plugins/keep_last_eval.lua
.luarocks/share/lua/5.1/repl/plugins/linenoise.lua
.luarocks/share/lua/5.1/repl/plugins/pretty_print.lua
.luarocks/share/lua/5.1/repl/plugins/rcfile.lua
.luarocks/share/lua/5.1/repl/plugins/rlwrap.lua
.luarocks/share/lua/5.1/repl/plugins/semicolon_suppress_output.lua
.luarocks/share/lua/5.1/repl/sync.lua
.luarocks/share/lua/5.1/repl/utils.lua

and I can find that stuff.
I tried adding a line to config.lua to load packages from local installation to no avail:

$ cat ~/.luarocks/config.lua
local_by_default=true

(removing it has no effect)

did I miss some obvious step?

running luarocks with no arguments gives me:

CONFIGURATION
    Lua version: 5.1
    Configuration files:
        System: /usr/local/etc/luarocks51/config-5.1.lua (ok)
        User  : /Users/me/.luarocks/config.lua (ok)

    Rocks trees in use:
        /Users/me/.luarocks ("user")
        /usr/local ("system")

it seems that the user rock tree is not in the package path:

$ lua
Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio
> print(package.path)
./?.lua;/usr/local/share/lua/5.1/?.lua;/usr/local/share/lua/5.1/?/init.lua;/usr/local/lib/lua/5.1/?.lua;/usr/local/lib/lua/5.1/?/init.lua

why?

Body:
From https://github.com/luarocks/luarocks/wiki/Using-LuaRocks:

Most LuaRocks installations will feature two rocks trees:

"system" rock tree (used by default)

"user" rock tree

To be able to use the module, we need to make sure that Lua can find that dkjson.lua file when we run require("dkjson"). You can check your Lua paths from the Lua environment, using

print(package.path)
print(package.cpath)

These variables can be pre-configured from outside Lua, using the LUA_PATH and LUA_CPATH environment variables.

If you installed both Lua and LuaRocks in their default directories (/usr/local on Linux and Mac OSX), then the "system" tree is /usr/local and it will work by default. However, the "user" tree (for installing rocks without admin privileges) is not detected by Lua by default. For that we'll need to configure these environment variables.

LuaRocks offers a semi-automated way to do this. If you type the following command:

luarocks path --bin

it will print commands suitable for your platform for setting up your environment. On typical Unix terminal environments, you can type this:

eval $(luarocks path --bin)

and it apply the changes, temporarily, to your shell. To have these variables set permanently, you have to configure the environment variables to your shell configuration (for example, by adding the above line to your .bashrc file if your shell is Bash).


问:
Asp.net JavaScript OnClick not working
What I'm trying to do is, when I click on the button it should show an alert box.
Here is the code.

```<code>protected void btnAdd_Click(object sender, EventArgs e)
{
    string script = "<script type=\"text/javascript\">alert('abc 1');
    </script>";
    ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert 1",
    script);
    Response.Redirect("~/Index.aspx");

}
</code>```

It is working perfectly but when I put this same code in another page it does not work.

what are the things I have to look into? any suggestion please?

答:
move your js code to client side</p>

```<code><asp:Button ID="btnAdd" OnClientClick="alert('alert');" OnClick="btnAdd_Click" runat="server"/>

protected void btnAdd_Click(object sender, EventArgs e)
{
    Response.Redirect("~/Index.aspx");

}
</code>```

Title: Asp.net JavaScript OnClick not working

Body:
What I'm trying to do is, when I click on the button it should show an alert box.
Here is the code.

protected void btnAdd_Click(object sender, EventArgs e)
{
    string script = "";
    ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert 1",
    script);
    Response.Redirect("~/Index.aspx");

}

It is working perfectly but when I put this same code in another page it does not work.

what are the things I have to look into? any suggestion please?

Body:
move your js code to client side

<asp:Button ID="btnAdd" OnClientClick="alert('alert');" OnClick="btnAdd_Click" runat="server"/>

protected void btnAdd_Click(object sender, EventArgs e)
{
    Response.Redirect("~/Index.aspx");

}


问:
get memory address of java object in c/c++
Let's say I have a java class

```<code>class NativeInterface{
    public static native void access(Object obj);
}
</code>```

And all I want to do is access the 2nd byte (for example) of that object.

I.e. I want to do something like this:

```<code>#include<jni.h>
#include "NativeInterface.h"
#include <stdio.h>

using byte = unsigned char;

/*
* Class:     NativeInterface
* Method:    access
* Signature: (Ljava/lang/Object)V
*/
JNIEXPORT void JNICALL Java_NativeInterface_access(JNIEnv* env, jclass _obsolete, jobject obj){
    byte byte_array[] = obj;
    printf("%c",byte_array[2]);
}
</code>```

Now obviously, this doesn't work. obj may not even be the java object.
(jobject is defined in the jni.h and I haven't yet figured out what it does.)

So how do I do this?

(Trying this naive attempt will result in

```<code>error: initializer fails to determine size of ‘byte_array’
     byte byte_array[] = obj;
                         ^~~~
</code>```

, btw.)

答:
"obj may not even be the java object"

You almost figured it out yourself. It's just a bit stronger than that. Java has Garbage Collection. For that reason alone, you know that obj is not the java object, but merely a handle that refers to that object as it's shuffled around in memory by the Garbage Collector.

You now see the fundamental flaw in your question: "get memory address of java object" presumes that you get a useful value. But even if you could get an address, it would be unreliable from the first clocktick after you get it.

Body:
Let's say I have a java class

class NativeInterface{
    public static native void access(Object obj);
}

And all I want to do is access the 2nd byte (for example) of that object.

I.e. I want to do something like this:

#include<jni.h>
#include "NativeInterface.h"
#include <stdio.h>

using byte = unsigned char;

/*
* Class:     NativeInterface
* Method:    access
* Signature: (Ljava/lang/Object)V
*/
JNIEXPORT void JNICALL Java_NativeInterface_access(JNIEnv* env, jclass _obsolete, jobject obj){
    byte byte_array[] = obj;
    printf("%c",byte_array[2]);
}

Now obviously, this doesn't work. obj may not even be the java object.
(jobject is defined in the jni.h and I haven't yet figured out what it does.)

So how do I do this?

(Trying this naive attempt will result in

error: initializer fails to determine size of ‘byte_array’
     byte byte_array[] = obj;
                         ^~~~

, btw.)


问:
C programming, files, linked lists
The program will read your friends from the file and use a linked-list to store your friends’ details.
Please note that you cannot make any assumptions about the number of your friends and
there is no upper limit for the number of friends.

There is my code, it is not working. I used strtok ...

Content of file should be:

Name1; Surname1;M;01.06.1990;
Name2;Surname2;F;02.04.1992;
```

<p>And this is my code:</p>

```#include<stdio.h>

#include<stdlib.h>

#include<string.h>

struct Friend{
char  *name;
char  *sur;
char  *gen;
char  *date;
struct Friend *next;
};
struct Friend * initialize(char *);
void display(struct Friend *);
int main()
{
printf("\nsdasda\n");
struct Friend *head;
char fname[100];
printf("Enter the name of file .txt:  \t");
gets(fname);
head=initialize(fname);
display(head);

}
struct Friend * initialize(char *fname){
FILE* fpointer;
char ch;
fpointer = fopen(fname,"r");
if(fpointer == NULL){

    do
    {
        printf("\nFile not found, please enter the name of file again: \t");
        gets(fname);
        fpointer = fopen(fname,"r");
    }while(fpointer == NULL);
}
//FILE IS OPENED
struct Friend *head=(struct Friend*)malloc(sizeof(struct Friend));
struct Friend *t;
t=head;
char line[255];
char sent[2]=";";

while(!feof(fpointer)){
fgets(line,sizeof line,fpointer);
t->name=strtok(line,sent);
t->sur=strtok(NULL,sent);
t->gen=strtok(NULL,sent);
t->date=strtok(NULL,sent);
if(!feof(fpointer)){
t->next=(struct Friend*)malloc(sizeof(struct Friend));
t=t->next;
}
else if(feof(fpointer)){

t->next=NULL;

}

}

return head;

};

void display(struct Friend *head){
puts(head->name);
}
```

答:
There are plenty of problems here, not sure to be exhaustive:

gets is unsafe and should never be used. Learn how to use fgets which is a safer alternative

while(!feof(fpointer)) is almost always wrong. After reading last line, feof is still false, it will only be true after the first unsuccessful read operation. So the test for end of file must be between the read and the processing of data.

do not cast malloc in C! It is useless and can only hide compiler warnings if you have indirection level errors

NEVER, EVER assign char pointers inside a re-useable string. You only store an address and erase the content on next read. Allocate memory for each new string or use strdup that does it under the hood (BTW, that's probably what cause you program not to work).

always free what you allocate, be it with malloc of strdup or any other function internally using malloc

always return a sensible value to the environment from main. Real programs are not run from an IDE...

Title: C programming, files, linked lists

Body:
The program will read your friends from the file and use a linked-list to store your friends’ details.
Please note that you cannot make any assumptions about the number of your friends and
there is no upper limit for the number of friends.

There is my code, it is not working. I used strtok ...

Content of file should be:

Name1; Surname1;M;01.06.1990;
Name2;Surname2;F;02.04.1992;

And this is my code:

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

struct Friend{
char  *name;
char  *sur;
char  *gen;
char  *date;
struct Friend *next;
};
struct Friend * initialize(char *);
void display(struct Friend *);
int main()
{
printf("\nsdasda\n");
struct Friend *head;
char fname[100];
printf("Enter the name of file .txt:  \t");
gets(fname);
head=initialize(fname);
display(head);

}
struct Friend * initialize(char *fname){
FILE* fpointer;
char ch;
fpointer = fopen(fname,"r");
if(fpointer == NULL){

    do
    {
        printf("\nFile not found, please enter the name of file again: \t");
        gets(fname);
        fpointer = fopen(fname,"r");
    }while(fpointer == NULL);
}
//FILE IS OPENED
struct Friend *head=(struct Friend*)malloc(sizeof(struct Friend));
struct Friend *t;
t=head;
char line[255];
char sent[2]=";";

while(!feof(fpointer)){
fgets(line,sizeof line,fpointer);
t->name=strtok(line,sent);
t->sur=strtok(NULL,sent);
t->gen=strtok(NULL,sent);
t->date=strtok(NULL,sent);
if(!feof(fpointer)){
t->next=(struct Friend*)malloc(sizeof(struct Friend));
t=t->next;
}
else if(feof(fpointer)){

t->next=NULL;

}

}

return head;

};

void display(struct Friend *head){
puts(head->name);
}


问:
Remove minus sign from number in django tmplate
In my template I have this:

```<code>{{ gainer.total_progression }}
</code>```

Which produces -5664

I need 5664

I tried

```<code>{{ gainer.total_progression }}|slice:"1:"
</code>```

but it won't remove the -.

What is the proper way to handle this?

答:
If you're not against installing separate library for this, you can use django-mathfilters.</p>

```<code>{{ gainer.total_progression|abs }}
</code>```

Body:
In my template I have this:

{{ gainer.total_progression }}

Which produces -5664

I need 5664

I tried

{{ gainer.total_progression }}|slice:"1:"

but it won't remove the -.

What is the proper way to handle this?

Body:
If you're not against installing separate library for this, you can use django-mathfilters.

{{ gainer.total_progression|abs }}