问:
Exception Value: column home_profile.goal does not exist
I'm really stuck here and i'm a little confused as to why this error is being thrown. I'm running Django 1.10 and the live database is a postgresql DB. I'm not that familiar with postgres. I've been doing all of my development work with sqlite for flexibility.

I've recently added two new fields to my model. They are both IntegerFields I've not had any issues with them locally. I've not deployed my changes to my live environment and i'm getting the above error.

```<code>goal = models.IntegerField(default=1, choices=weight_goal, null=True, blank=True)
</code>```

I have tried removing the fields, deleting all the migration files and even removing the model itself. However, when i add the field back in it throws the same error.

I've done some research and all i can see is 'Drop the DB and create it again". Well this isn't possible as i'll lose all of the data inside the live DB.

I don't really feel comfortable diving into a live database and trying to add the column manually. I mean, this seems a little OTT anyway?

Note: I'm deploying the box via Heroku

Profile Model:

```<code>class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    image = CloudinaryField('image', default="thumbnail_mqe6ne")
    weight = models.DecimalField(help_text="KG", max_digits=5, default=0, decimal_places=2, validators=[
        MinValueValidator(30),
        MaxValueValidator(600)
        ])
    height = models.DecimalField(help_text="CM", max_digits=8, default=0, decimal_places=2, validators=[
        MinValueValidator(20),
        MaxValueValidator(600),
        ])

    gender_option = (
        ('Male', 'Male'),
        ('Female', 'Female'),
    )

    profile_status = (
        ('Public', 'Public'),
        ('Private', 'Private'),
    )

    birth_date = models.DateField(blank=True, verbose_name="Date of Birth")

    gender = models.CharField(choices=gender_option, max_length=10)
    bio = models.TextField(max_length=300, blank=True)
    location = models.CharField(max_length=30, blank=True)

    weight_goal = (
        (1, 'Weight Loss'),
        (2, 'Weight / Muscle weight gain'),
    )

    goal = models.IntegerField(default=1, choices=weight_goal, null=True, blank=True)

    activity = (
        (1, 'Mostly inactive or sedentary'),
        (2, 'Fairly active'),
        (3, 'Moderately active'),
        (4, 'Active'),
        (5, 'Very active'),
    )

    activity_level = models.IntegerField(default=1, choices=activity, null=True, blank=True)

    intensity = (
        (1, 'Very light training'),
        (2, 'Moderate intensity'),
        (3, 'Moderate to high intensity (1 - 3 hours)'),
        (4, 'Very high intensity training (4+ Hours Daily)'),

    )

    training_intensity = models.IntegerField(default=1, choices=intensity)

    status = models.CharField(default="Public", max_length=10, choices=profile_status)
</code>```

Any help would be much apprecited. Full traceback below:

```<code>Environment:

Request Method: GET
Request URL: /

Django Version: 1.10
Python Version: 2.7.13
Installed Applications:
['djangocms_admin_style',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.sites',
 'stats',
 'home',
 'blog',
 'haystack',
 'ckeditor_uploader',
 'ckeditor',
 'django_social_share',
 'post_office',
 'sorl.thumbnail',
 'storages',
 'cloudinary',
 'django.contrib.staticfiles',
 'cloudinary_storage',
 'django_cleanup',
 'django_instagram',
 'embed_video',
 'easy_thumbnails',
 'filer',
 'reversion',
 'allauth',
 'allauth.account',
 'allauth.socialaccount',
 'allauth.socialaccount.providers.facebook']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'solid_i18n.middleware.SolidLocaleMiddleware',
 'whitenoise.middleware.WhiteNoiseMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware',
 'django.middleware.locale.LocaleMiddleware']

Traceback:

File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in _legacy_get_response
  249.             response = self._get_response(request)

File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "/app/home/views.py" in get_user_profile
  42.     profile = Profile.objects.get(user=request.user.id)

File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py" in get
  379.         num = len(clone)

File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py" in __len__
  238.         self._fetch_all()

File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py" in _fetch_all
  1085.             self._result_cache = list(self.iterator())

File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py" in __iter__
  54.         results = compiler.execute_sql()

File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
  835.             cursor.execute(sql, params)

File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  79.             return super(CursorDebugWrapper, self).execute(sql, params)

File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

File "/app/.heroku/python/lib/python2.7/site-packages/django/db/utils.py" in __exit__
  94.                 six.reraise(dj_exc_type, dj_exc_value, traceback)

File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

Exception Type: ProgrammingError at /profile/
Exception Value: column home_profile.goal does not exist
LINE 1: ... "home_profile"."bio", "home_profile"."location", "home_prof...
                                                         ^
</code>```

答:
The first thing to do, if you haven't done already is to create a backup of your database.

database is a postgresql DB. I'm not that familiar with postgres. I've been doing all of my development work with sqlite for flexibility.

For non trivial projects, it's best to have the same RDBMS at both ends.

I've done some research and all i can see is 'Drop the DB and create it again"

You are right not to go down this path. That's very poor advice.

I have tried removing the fields, deleting all the migration files and even removing the model itself. However, when i add the field back in it throws the same error.

But this is also a pretty lonely and dangerous path that you have taken full of pitfalls. Let's see if we can put things right.

The fact that postgresql complaining about the column being missing clearly indicates that you have a rogue, migration. Go through your backups and see if you have a version of the db, with that column. If you don't, you are going to lose some data.

If you have such a backup, restore it after visually checking through psql or pgadmin that the column is indeed missing on the db.

Now that you have cleared up the migrations, completely empty that folder. Make sure that there aren't any .pyc files hanging about.

Next inspect your django_migrations table. Delete the the migrations related to the current app (home I think).

Next do

```<code>./manage.py makemigrations home
</code>```

This should create exactly one migration in your migrations folder. After confirmation do

```<code>./manage.py migrate --fake-initial home
</code>```

now everything should be ok.

Body:
I'm really stuck here and i'm a little confused as to why this error is being thrown. I'm running Django 1.10 and the live database is a postgresql DB. I'm not that familiar with postgres. I've been doing all of my development work with sqlite for flexibility.

I've recently added two new fields to my model. They are both IntegerFields I've not had any issues with them locally. I've not deployed my changes to my live environment and i'm getting the above error.

goal = models.IntegerField(default=1, choices=weight_goal, null=True, blank=True)

I have tried removing the fields, deleting all the migration files and even removing the model itself. However, when i add the field back in it throws the same error.

I've done some research and all i can see is 'Drop the DB and create it again". Well this isn't possible as i'll lose all of the data inside the live DB.

I don't really feel comfortable diving into a live database and trying to add the column manually. I mean, this seems a little OTT anyway?

Note: I'm deploying the box via Heroku

Profile Model:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    image = CloudinaryField('image', default="thumbnail_mqe6ne")
    weight = models.DecimalField(help_text="KG", max_digits=5, default=0, decimal_places=2, validators=[
        MinValueValidator(30),
        MaxValueValidator(600)
        ])
    height = models.DecimalField(help_text="CM", max_digits=8, default=0, decimal_places=2, validators=[
        MinValueValidator(20),
        MaxValueValidator(600),
        ])

    gender_option = (
        ('Male', 'Male'),
        ('Female', 'Female'),
    )

    profile_status = (
        ('Public', 'Public'),
        ('Private', 'Private'),
    )

    birth_date = models.DateField(blank=True, verbose_name="Date of Birth")

    gender = models.CharField(choices=gender_option, max_length=10)
    bio = models.TextField(max_length=300, blank=True)
    location = models.CharField(max_length=30, blank=True)

    weight_goal = (
        (1, 'Weight Loss'),
        (2, 'Weight / Muscle weight gain'),
    )

    goal = models.IntegerField(default=1, choices=weight_goal, null=True, blank=True)

    activity = (
        (1, 'Mostly inactive or sedentary'),
        (2, 'Fairly active'),
        (3, 'Moderately active'),
        (4, 'Active'),
        (5, 'Very active'),
    )

    activity_level = models.IntegerField(default=1, choices=activity, null=True, blank=True)

    intensity = (
        (1, 'Very light training'),
        (2, 'Moderate intensity'),
        (3, 'Moderate to high intensity (1 - 3 hours)'),
        (4, 'Very high intensity training (4+ Hours Daily)'),

    )

    training_intensity = models.IntegerField(default=1, choices=intensity)

    status = models.CharField(default="Public", max_length=10, choices=profile_status)

Any help would be much apprecited. Full traceback below:

Environment:

Request Method: GET
Request URL: /

Django Version: 1.10
Python Version: 2.7.13
Installed Applications:
['djangocms_admin_style',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.sites',
 'stats',
 'home',
 'blog',
 'haystack',
 'ckeditor_uploader',
 'ckeditor',
 'django_social_share',
 'post_office',
 'sorl.thumbnail',
 'storages',
 'cloudinary',
 'django.contrib.staticfiles',
 'cloudinary_storage',
 'django_cleanup',
 'django_instagram',
 'embed_video',
 'easy_thumbnails',
 'filer',
 'reversion',
 'allauth',
 'allauth.account',
 'allauth.socialaccount',
 'allauth.socialaccount.providers.facebook']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'solid_i18n.middleware.SolidLocaleMiddleware',
 'whitenoise.middleware.WhiteNoiseMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware',
 'django.middleware.locale.LocaleMiddleware']

Traceback:

File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in _legacy_get_response
  249.             response = self._get_response(request)

File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "/app/home/views.py" in get_user_profile
  42.     profile = Profile.objects.get(user=request.user.id)

File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py" in get
  379.         num = len(clone)

File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py" in __len__
  238.         self._fetch_all()

File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py" in _fetch_all
  1085.             self._result_cache = list(self.iterator())

File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/query.py" in __iter__
  54.         results = compiler.execute_sql()

File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
  835.             cursor.execute(sql, params)

File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  79.             return super(CursorDebugWrapper, self).execute(sql, params)

File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

File "/app/.heroku/python/lib/python2.7/site-packages/django/db/utils.py" in __exit__
  94.                 six.reraise(dj_exc_type, dj_exc_value, traceback)

File "/app/.heroku/python/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

Exception Type: ProgrammingError at /profile/
Exception Value: column home_profile.goal does not exist
LINE 1: ... "home_profile"."bio", "home_profile"."location", "home_prof...
                                                         ^

Body:
The first thing to do, if you haven't done already is to create a backup of your database.

database is a postgresql DB. I'm not that familiar with postgres. I've been doing all of my development work with sqlite for flexibility.

For non trivial projects, it's best to have the same RDBMS at both ends.

I've done some research and all i can see is 'Drop the DB and create it again"

You are right not to go down this path. That's very poor advice.

I have tried removing the fields, deleting all the migration files and even removing the model itself. However, when i add the field back in it throws the same error.

But this is also a pretty lonely and dangerous path that you have taken full of pitfalls. Let's see if we can put things right.

The fact that postgresql complaining about the column being missing clearly indicates that you have a rogue, migration. Go through your backups and see if you have a version of the db, with that column. If you don't, you are going to lose some data.

If you have such a backup, restore it after visually checking through psql or pgadmin that the column is indeed missing on the db.

Now that you have cleared up the migrations, completely empty that folder. Make sure that there aren't any .pyc files hanging about.

Next inspect your django_migrations table. Delete the the migrations related to the current app (home I think).

Next do

./manage.py makemigrations home

This should create exactly one migration in your migrations folder. After confirmation do

./manage.py migrate --fake-initial home

now everything should be ok.


来源: stackexchange

问:
Schema design for review with rating and optional items
I am by no means a SQL/DB expert. Currently working on an evaluation/rating app and having doubts with the design.

The context is as follows: There are a number of organisations in the system that could deliver services. Every organisation can have multiple services and services can be delivered by multiple orgnisations. Users are able to evaluate/rate the organisations. Optionally, with every evaluation, they can also specify whether or not a service is present.

This is what I am thinking about in terms of design (I cannot post images yet):DB Diagram

Many to many relationship between Organisations and Services

Many to many relationship between Evaluations and Services

One to many relationship between Organisations and Evaluations

My questions would be whether this is a good approach to follow? Or should the evaluation/rating be threated separately from the actual setting of the services?

答:
I think you are on the right track. You can have the Organisations and the Services table, together with the linking table OrganisationServices.

And for the evaluation part, you can have another table Evaluations(id, userId, organisationId, serviceId, score), as I think you really want to rate the specific service of an organisation (really big organisations cand have services in multiple domains of activity). Be careful to have a unique constraint for user, organisation and service.

This way, if you want to have an overall score for an organisation, you can just do a simple query to do a mean of the scores for all the services of that organisation.

Hope this helped you in some way.

ContentLicense: CC BY-SA 3.0


问:
Tidy up PHP echo code
Apologies in advance though I've tried and failed several different things and obviously I'm not a php pro just yet.
I'm looking for a way to tidy up my code here, I'm pretty certain I don't need to continually type "echo" for each line but can't work out how to combine my code to achieve the same result, any ideas?

<?php
$values = get_field('bothscoreno');
$url    = "$values";
$arr    = str_split("$url, PHP_URL_QUERY");
if ($url) {
    echo $arr[11];
    echo $arr[12];
    echo $arr[13];
    echo $arr[14];
    echo $arr[15];
    echo $arr[16];
} else {
    echo 'No';
}
?>```

Thanks in advance.

答:
Use the point as concatenation operator</p>

```<code>echo $arr[11].$arr[12]
</code>```

Title: Tidy up PHP echo code

Body:
Apologies in advance though I've tried and failed several different things and obviously I'm not a php pro just yet.
I'm looking for a way to tidy up my code here, I'm pretty certain I don't need to continually type "echo" for each line but can't work out how to combine my code to achieve the same result, any ideas?

<?php
$values = get_field('bothscoreno');
$url    = "$values";
$arr    = str_split("$url, PHP_URL_QUERY");
if ($url) {
    echo $arr[11];
    echo $arr[12];
    echo $arr[13];
    echo $arr[14];
    echo $arr[15];
    echo $arr[16];
} else {
    echo 'No';
}
?>

Thanks in advance.

Body:
Use the point as concatenation operator

echo $arr[11].$arr[12]


问:
Spring: Accessing field from final method returning null
So I came across a very weird bug in my project. I had the following two classes

```<code>@Component
@Scope("prototype")
public abstract class World {
    String name;

    public World(String name) {
          this.name = name;
    }

    final void print() {
          System.out.println(name);
    }
}

@Component
@Scope("prototype")
public class Hello extends World {

    public Hello(String name) {
          super(name);
    }
}
</code>```

When I instantiate an object using context.getBean(Hello.class, "foo"), I get back a Hello class bean. But when I hello.print(), it printed null.

Removing the final modifier resolved the issue. Whats going on here? Is spring having any limitations with final methods?

答:
My assumption is that you use CGLIB proxying. You can check that by

```<code>context.getBean(Hello.class, "foo").getClass()
</code>```

In that case Spring asks CGLIB to create a subclass of the Hello. That subclass gets the real instance of Hello class. This allows to override all the methods and then eventually call the target, here is how it looks approximately:

```<code>class Proxy extends Hello {
  Hello target;

  void print() {
     target.print();
  }
}
</code>```

Because you marked your method as final Java doesn't allow overriding. And proxy itself (while is a subclass of Hello) doesn't get the name field initialized - it's null.

So your real Hello#print() method is not invoked - only Proxy#print() is called and Proxy#name is null, which results in null showing up in console.

Body:
So I came across a very weird bug in my project. I had the following two classes

@Component
@Scope("prototype")
public abstract class World {
    String name;

    public World(String name) {
          this.name = name;
    }

    final void print() {
          System.out.println(name);
    }
}

@Component
@Scope("prototype")
public class Hello extends World {

    public Hello(String name) {
          super(name);
    }
}

When I instantiate an object using context.getBean(Hello.class, "foo"), I get back a Hello class bean. But when I hello.print(), it printed null.

Removing the final modifier resolved the issue. Whats going on here? Is spring having any limitations with final methods?

Body:
My assumption is that you use CGLIB proxying. You can check that by

context.getBean(Hello.class, "foo").getClass()

In that case Spring asks CGLIB to create a subclass of the Hello. That subclass gets the real instance of Hello class. This allows to override all the methods and then eventually call the target, here is how it looks approximately:

class Proxy extends Hello {
  Hello target;

  void print() {
     target.print();
  }
}

Because you marked your method as final Java doesn't allow overriding. And proxy itself (while is a subclass of Hello) doesn't get the name field initialized - it's null.

So your real Hello#print() method is not invoked - only Proxy#print() is called and Proxy#name is null, which results in null showing up in console.


问:
Export documents to either JSON or CSV
I know this might be a basic question, but I believe everybody has to learn from some point.

I am trying hard to learn Elasticsearch and as I was going through the documentation at this page

https://www.elastic.co/guide/en/elasticsearch/reference/current/_exploring_your_data.html

I learned how to load a JSON data and form an index. But later an question arose in my head, how would I be able to export the whole index that I created (here the bank) to CSV or a JSON. Since I couldn't find a solution in Kibana, I searched Github and came across this python script 'es2csv'.

https://pypi.python.org/pypi/es2csv/2.4.11

I installed it, but I can't make an output to a format that it should appear in a CSV file. Please, could you help me understand what should I do and clarify the steps i should take because it is vital for me to learn.

Many thanks!

答:
This appears to be the most high level option - it would download all indices from elasticsearch, not just one (from the docs).

```<code>es2csv -q 'host: localhost' -o database.csv
</code>```

or to specify an index, use -i and your index name:

```<code>es2csv -i indexname -q 'host: localhost' -o database.csv
</code>```

A better way might be to use kibana to build visualisations. You can then export the data as Raw or Formatted using the buttons below the visualisation in kibana.

This might work better especially if you build a data table, as the data will be 'flattened' - rather than nested in a json structure which might not be much use when you convert directly to csv.

Title: Export documents to either JSON or CSV

Body:
This appears to be the most high level option - it would download all indices from elasticsearch, not just one (from the docs).

es2csv -q 'host: localhost' -o database.csv

or to specify an index, use -i and your index name:

es2csv -i indexname -q 'host: localhost' -o database.csv

A better way might be to use kibana to build visualisations. You can then export the data as Raw or Formatted using the buttons below the visualisation in kibana.

This might work better especially if you build a data table, as the data will be 'flattened' - rather than nested in a json structure which might not be much use when you convert directly to csv.


问:
C: Separate HEX String into Char Aarray with RegEx
I want to convert hexadecimal strings like:

FE2A8D0000CA372D4F461B1D9A1883A32F018823FFFF60D30000484200000D0A0F270300030006000000B0040307000356A3

Into this format:

```<code>const char msg[] = {0xFE, 0x2A, 0x8D, 0x00, 0x00, 0xCA, 0x37, 0x2D, 0x4F,
0x46, 0x1B, 0x1D, 0x9A, 0x18, 0x83, 0xA3, 0x2F, 0x01, 0x88, 0x23, 0xFF,
0xFF, 0x60, 0xD3, 0x00, 0x00, 0x48, 0x42, 0x00, 0x00, 0x0D, 0x0A, 0x0F,
0x27, 0x03, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00, 0xB0, 0x04, 0x03,
0x07, 0x00, 0x03, 0x56, 0xA3};
</code>```

At the moment, I use regex in Notepad++, and works well.
This is the regex:

```<code>find: ([a-z0-9]{2})
replace with: \, 0x\1
(then I remove the first ',')
</code>```

I'm coding in C, I have tried using regex but I can't get it working. How should I use regex for this?

A solution without regex is also fine.

答:
May be following code will fulfill the requirement:</p>

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

 void printHex(char data[])
 {
     int i,j;
     char temp[] = "0x00";
     int count = strlen(data)/2;

     for(i=0, j=0; i<count;i++, j+=2)
     {
         temp[2] = data[j];
         temp[3] = data[j+1];
         printf("%s, ",temp);
     }
 }

 int main()
 {
     char data[]="FE2A8D0000CA372D4F461B1D9A1883A32F018823FFFF60D30000484200000D0A0F270300030006000000B0040307000356A3";
     printHex(data);
     return 0;
 }
</code>```

Body:
I want to convert hexadecimal strings like:

FE2A8D0000CA372D4F461B1D9A1883A32F018823FFFF60D30000484200000D0A0F270300030006000000B0040307000356A3

Into this format:

const char msg[] = {0xFE, 0x2A, 0x8D, 0x00, 0x00, 0xCA, 0x37, 0x2D, 0x4F,
0x46, 0x1B, 0x1D, 0x9A, 0x18, 0x83, 0xA3, 0x2F, 0x01, 0x88, 0x23, 0xFF,
0xFF, 0x60, 0xD3, 0x00, 0x00, 0x48, 0x42, 0x00, 0x00, 0x0D, 0x0A, 0x0F,
0x27, 0x03, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00, 0xB0, 0x04, 0x03,
0x07, 0x00, 0x03, 0x56, 0xA3};

At the moment, I use regex in Notepad++, and works well.
This is the regex:

find: ([a-z0-9]{2})
replace with: \, 0x\1
(then I remove the first ',')

I'm coding in C, I have tried using regex but I can't get it working. How should I use regex for this?

A solution without regex is also fine.

Body:
May be following code will fulfill the requirement:

 #include <stdio.h>
 #include <string.h>

 void printHex(char data[])
 {
     int i,j;
     char temp[] = "0x00";
     int count = strlen(data)/2;

     for(i=0, j=0; i<count;i++, j+=2)
     {
         temp[2] = data[j];
         temp[3] = data[j+1];
         printf("%s, ",temp);
     }
 }

 int main()
 {
     char data[]="FE2A8D0000CA372D4F461B1D9A1883A32F018823FFFF60D30000484200000D0A0F270300030006000000B0040307000356A3";
     printHex(data);
     return 0;
 }


问:
Reading several files into multiple lists
I have just been brought in on a project where we have several huge text files (each close to a gigabyte) of data that we want to put into tables and analyse. Each text file consists of data from a single year, and each data point is from one of three categories, and the end result we want is one list for each of the categories, containing observations from each year as columns.

The way it is done now is to read each of the files into a list, then split those lists according to the categories and make three new lists for each year, then rbind all lists of a given category from different years into the final lists. See below for the R file I was presented (anonymised):

```<code>Year1 <- read.table(YearOneFilePath)
table(Year1$category)
Year1A <- Year1[Year1$category == "A",]
Year1B <- Year1[Year1$category == "B",]
Year1C <- Year1[Year1$category == "C",]
rm(Year1)
Year2 <- read.table(YeartwoFilePath)
table(Year2$category)
Year2A <- Year2[Year2$category == "A",]
Year2B <- Year2[Year2$category == "B",]
Year2C <- Year2[Year2$category == "C",]
rm(Year2)
Year3 <- read.table(YearThreeFilePath)
table(Year3$category)
Year3A <- Year3[Year3$category == "A",]
Year3B <- Year3[Year3$category == "B",]
Year3C <- Year3[Year3$category == "C",]
rm(Year3)

A <- rbind(Year1A, Year2A, Year3A)
B <- rbind(Year1B, Year2B, Year3B)
C <- rbind(Year1C, Year2C, Year3C)

rm(Year1A)
rm(Year2A)
rm(Year3A)
rm(Year1B)
rm(Year2B)
rm(Year3B)
rm(Year1C)
rm(Year2C)
rm(Year3C)
</code>```

This seems to me like it reads all the data form the files, and copies it twice while moving it around, which with large amounts of data like this takes a long time and a lot of memory. Obviously I can get around the YearXY lists by putting YearX[YearX$Category == "Y",] directly into the rbind function, but that still means that I at some point in the execution have two full copies of everything. Is there a way to make the final A, B and C lists from the files on only one readthrough of each file and without copying all the data an additional time?

答:
```<code> library(data.table)

Year1 <- fread(YearOneFilePath)
Year1[, .N ,by = category]
Year1A <- Year1[Year1$category == "A",,]
Year1B <- Year1[Year1$category == "B",,]
Year1C <- Year1[Year1$category == "C",,]
rm(Year1)
gc()
#YES garbage collection may help ;)
A <- rbind(Year1A, Year2A, Year3A)
rm(Year1A)
rm(Year2A)
rm(Year3A)
gc()
</code>```

For splitting here is one more method,

```<code>split_list1=split(Year1 ,Year1$category)
Year1A <-split_list1[[1]]
Year1B <-split_list1[[2]]
Year1C <-split_list1[[3]]
</code>```

also see split data table to small tables R

Body:
I have just been brought in on a project where we have several huge text files (each close to a gigabyte) of data that we want to put into tables and analyse. Each text file consists of data from a single year, and each data point is from one of three categories, and the end result we want is one list for each of the categories, containing observations from each year as columns.

The way it is done now is to read each of the files into a list, then split those lists according to the categories and make three new lists for each year, then rbind all lists of a given category from different years into the final lists. See below for the R file I was presented (anonymised):

Year1 <- read.table(YearOneFilePath)
table(Year1$category)
Year1A <- Year1[Year1$category == "A",]
Year1B <- Year1[Year1$category == "B",]
Year1C <- Year1[Year1$category == "C",]
rm(Year1)
Year2 <- read.table(YeartwoFilePath)
table(Year2$category)
Year2A <- Year2[Year2$category == "A",]
Year2B <- Year2[Year2$category == "B",]
Year2C <- Year2[Year2$category == "C",]
rm(Year2)
Year3 <- read.table(YearThreeFilePath)
table(Year3$category)
Year3A <- Year3[Year3$category == "A",]
Year3B <- Year3[Year3$category == "B",]
Year3C <- Year3[Year3$category == "C",]
rm(Year3)

A <- rbind(Year1A, Year2A, Year3A)
B <- rbind(Year1B, Year2B, Year3B)
C <- rbind(Year1C, Year2C, Year3C)

rm(Year1A)
rm(Year2A)
rm(Year3A)
rm(Year1B)
rm(Year2B)
rm(Year3B)
rm(Year1C)
rm(Year2C)
rm(Year3C)

This seems to me like it reads all the data form the files, and copies it twice while moving it around, which with large amounts of data like this takes a long time and a lot of memory. Obviously I can get around the YearXY lists by putting YearX[YearX$Category == "Y",] directly into the rbind function, but that still means that I at some point in the execution have two full copies of everything. Is there a way to make the final A, B and C lists from the files on only one readthrough of each file and without copying all the data an additional time?

Body:
 library(data.table)

Year1 <- fread(YearOneFilePath)
Year1[, .N ,by = category]
Year1A <- Year1[Year1$category == "A",,]
Year1B <- Year1[Year1$category == "B",,]
Year1C <- Year1[Year1$category == "C",,]
rm(Year1)
gc()
#YES garbage collection may help ;)
A <- rbind(Year1A, Year2A, Year3A)
rm(Year1A)
rm(Year2A)
rm(Year3A)
gc()

For splitting here is one more method,

split_list1=split(Year1 ,Year1$category)
Year1A <-split_list1[[1]]
Year1B <-split_list1[[2]]
Year1C <-split_list1[[3]]

also see split data table to small tables R


问:
How to add new utterance to LUIS intent?
Please help me in LUIS training. I want to add new utterances to intent using LUIS API. But I can't find any examples in the documentation.</p>

答: You might want to try the Add Label operation from the LUIS Programatic API.</p>


问:
How do I delete files programmatically on Android?
I'm on 4.4.2, trying to delete a file (image) via uri. Here's my code:

```<code>File file = new File(uri.getPath());
boolean deleted = file.delete();
if(!deleted){
      boolean deleted2 = file.getCanonicalFile().delete();
      if(!deleted2){
           boolean deleted3 = getApplicationContext().deleteFile(file.getName());
      }
}
</code>```

Right now, none of these delete functions is actually deleting the file. I also have this in my AndroidManifest.xml:

```<code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
</code>```

答:
I tested this code on Nougat emulator and it worked:

In manifest add:

```<code><application...

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
</application>
</code>```

Create empty xml folder in res folder and past in the provider_paths.xml:

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

Then put the next snippet into your code (for instance fragment):

```<code>File photoLcl = new File(homeDirectory + "/" + fileNameLcl);
Uri imageUriLcl = FileProvider.getUriForFile(getActivity(),
  getActivity().getApplicationContext().getPackageName() +
    ".provider", photoLcl);
ContentResolver contentResolver = getActivity().getContentResolver();
contentResolver.delete(imageUriLcl, null, null);
</code>```

Body:
I'm on 4.4.2, trying to delete a file (image) via uri. Here's my code:

File file = new File(uri.getPath());
boolean deleted = file.delete();
if(!deleted){
      boolean deleted2 = file.getCanonicalFile().delete();
      if(!deleted2){
           boolean deleted3 = getApplicationContext().deleteFile(file.getName());
      }
}

Right now, none of these delete functions is actually deleting the file. I also have this in my AndroidManifest.xml:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />

Body:
I tested this code on Nougat emulator and it worked:

In manifest add:

<application...

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
</application>

Create empty xml folder in res folder and past in the provider_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
 <paths xmlns:android="http://schemas.android.com/apk/res/android">
   <external-path name="external_files" path="."/>
  </paths>

Then put the next snippet into your code (for instance fragment):

File photoLcl = new File(homeDirectory + "/" + fileNameLcl);
Uri imageUriLcl = FileProvider.getUriForFile(getActivity(),
  getActivity().getApplicationContext().getPackageName() +
    ".provider", photoLcl);
ContentResolver contentResolver = getActivity().getContentResolver();
contentResolver.delete(imageUriLcl, null, null);


问:
Problems with getting a node out of JSON with jsoncpp
Im trying to use jsoncpp to parse a set of json. The json has been generated from a webpage with simplejson from a django object. I get it from a particular URL using libcurl. WHen I use the toStyledString() function on the root I get this printed out.

```<code>[
   {
      "fields" : {
         "desc" : "Carol King test",
         "format" : "1",
         "genre" : "Pop",
         "mount" : "CarolKing",
         "name" : "Carol King",
         "protocol" : "0",
         "songs" : [ 27, 28, 29, 30, 31, 32, 33, 34 ],
         "url" : "http://192.168.0.5:8000/CarolKing"
      },
      "model" : "music.playlist",
      "pk" : 2
   }
]
</code>```

So it seems like I am getting the data right and its in a Json::Value class.

The problem is that im unable to get a particular node out of the json structure. This is the code im using.

```<code>#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
#include <curl/curl.h>
#include <string>
#include "Parameter.h"
#include "lib_json/json.h"

using namespace std;

static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
    cout << "-->write_data " << endl;
    string buf = string(static_cast<char *>(ptr), size *nmemb);
    stringstream * response = static_cast<stringstream *>(stream);
    response->write(buf.c_str(), (streamsize)buf.size());
    return size * nmemb;

}

int main(int sys_argc, char ** sys_argv) {
    CURL *curl;
    CURLcode res;
    stringstream response;
    string error;

    char ** argv = sys_argv;

    string file = argv[1];
    Parameter *parms = new Parameter(file);
    parms->ReadParameters();

    cout << "URL: " << parms->GetParameter("URL");

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if(curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, parms->GetParameter("URL").c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
        res = curl_easy_perform(curl);

        cout << "Playlists-JSON: " << response.str() << endl;
        curl_easy_cleanup(curl);
    }

    Json::Value root;
    Json::Reader reader;

    bool parsingSuccessful = reader.parse(response.str(), root);

    if(!parsingSuccessful)
    {
        cout << "Failed to parse configuration. " << reader.getFormatedErrorMessages();
        return 16;
    }

    cout << "Pretty-Print: " << root.toStyledString() << endl;
    const Json::Value fields = root["fields"]["songs"];

    return 0;
}
</code>```

because of another issue I'm not using the actual libjson.so shared library, im just pulling in the files and compiling them in with my source (I'm guessing this is bad, but that problem is not the point of this question). Below is how my src folder is structured.

```<code>.:
bird  Bird.cpp  fopen.cpp  fopen.h  lib_json  Parameter.cpp  Parameter.h

./lib_json:
autolink.h  features.h  json_batchallocator.h  json_internalarray.inl  json_reader.cpp  json_valueiterator.inl  reader.h    value.h
config.h    forwards.h  json.h                 json_internalmap.inl    json_value.cpp   json_writer.cpp         sconscript  writer.h
</code>```

and this is the output of make.

```<code>    munderwo@bertha:/local/Documents/inthebackground/Box/Bird/bird/Debug$ make
Building file: ../src/lib_json/json_reader.cpp
Invoking: GCC C++ Compiler
g++ -I"/local/Documents/inthebackground/Box/Bird/bird/Libraries/i386/include" -I"/local/Documents/inthebackground/Box/Bird/bird/src" -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/lib_json/json_reader.d" -MT"src/lib_json/json_reader.d" -o"src/lib_json/json_reader.o" "../src/lib_json/json_reader.cpp"
Finished building: ../src/lib_json/json_reader.cpp

Building file: ../src/lib_json/json_value.cpp
Invoking: GCC C++ Compiler
g++ -I"/local/Documents/inthebackground/Box/Bird/bird/Libraries/i386/include" -I"/local/Documents/inthebackground/Box/Bird/bird/src" -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/lib_json/json_value.d" -MT"src/lib_json/json_value.d" -o"src/lib_json/json_value.o" "../src/lib_json/json_value.cpp"
Finished building: ../src/lib_json/json_value.cpp

Building file: ../src/lib_json/json_writer.cpp
Invoking: GCC C++ Compiler
g++ -I"/local/Documents/inthebackground/Box/Bird/bird/Libraries/i386/include" -I"/local/Documents/inthebackground/Box/Bird/bird/src" -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/lib_json/json_writer.d" -MT"src/lib_json/json_writer.d" -o"src/lib_json/json_writer.o" "../src/lib_json/json_writer.cpp"
Finished building: ../src/lib_json/json_writer.cpp

Building file: ../src/Bird.cpp
Invoking: GCC C++ Compiler
g++ -I"/local/Documents/inthebackground/Box/Bird/bird/Libraries/i386/include" -I"/local/Documents/inthebackground/Box/Bird/bird/src" -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/Bird.d" -MT"src/Bird.d" -o"src/Bird.o" "../src/Bird.cpp"
Finished building: ../src/Bird.cpp

Building file: ../src/Parameter.cpp
Invoking: GCC C++ Compiler
g++ -I"/local/Documents/inthebackground/Box/Bird/bird/Libraries/i386/include" -I"/local/Documents/inthebackground/Box/Bird/bird/src" -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/Parameter.d" -MT"src/Parameter.d" -o"src/Parameter.o" "../src/Parameter.cpp"
../src/Parameter.cpp: In member function ‘int Parameter::ReadParameters()’:
../src/Parameter.cpp:47: warning: comparison between signed and unsigned integer expressions
Finished building: ../src/Parameter.cpp

Building file: ../src/fopen.cpp
Invoking: GCC C++ Compiler
g++ -I"/local/Documents/inthebackground/Box/Bird/bird/Libraries/i386/include" -I"/local/Documents/inthebackground/Box/Bird/bird/src" -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/fopen.d" -MT"src/fopen.d" -o"src/fopen.o" "../src/fopen.cpp"
Finished building: ../src/fopen.cpp

Building target: Bird
Invoking: GCC C++ Linker
g++ -L"/local/Documents/inthebackground/Box/Bird/bird/Libraries/i386/lib" -o"Bird"  ./src/lib_json/json_reader.o ./src/lib_json/json_value.o ./src/lib_json/json_writer.o  ./src/Bird.o ./src/Parameter.o ./src/fopen.o   -lcurl
Finished building target: Bird
</code>```

and from all of that I get the following output when I execute Bird

```<code>*Bird: ../src/lib_json/json_value.cpp:1025: Json::Value& Json::Value::resolveReference(const char*, bool): Assertion `type_ == nullValue || type_ == objectValue' failed.*
URL: 127.0.0.1:8000/playlist-->write_data
Playlists-JSON: [{"pk": 2, "model": "music.playlist", "fields": {"protocol": "0", "name": "Carol King", "format": "1", "url": "http://192.168.0.5:8000/CarolKing", "mount": "CarolKing", "genre": "Pop", "songs": [27, 28, 29, 30, 31, 32, 33, 34], "desc": "Carol King test"}}]
Pretty-Print: [
   {
      "fields" : {
         "desc" : "Carol King test",
         "format" : "1",
         "genre" : "Pop",
         "mount" : "CarolKing",
         "name" : "Carol King",
         "protocol" : "0",
         "songs" : [ 27, 28, 29, 30, 31, 32, 33, 34 ],
         "url" : "http://192.168.0.5:8000/CarolKing"
      },
      "model" : "music.playlist",
      "pk" : 2
   }
]
</code>```

I dont get the problem if I comment out this line

```<code>const Json::Value fields = root["songs"];
</code>```

Im totally open to the fact that im doing something wrong here. But I just dont know what it is. So what is causing the error:

```<code>Bird: ../src/lib_json/json_value.cpp:1025: Json::Value& Json::Value::resolveReference(const char*, bool): Assertion `type_ == nullValue || type_ == objectValue' failed.
</code>```

thanks for any help you can give.

Cheers

Mark

答:
Sorry,

But

```<code>const Json::Value fields = root["songs"];
</code>```

Shouldn't be

```<code>const Json::Value fields = root["fields"];
</code>```

songs is nested into fields, so to get the songs you should access it like this:

```<code>const Json::Value songs = root["fields"]["songs"];
</code>```

No?

ContentLicense: CC BY-SA 2.5

Body:
Im trying to use jsoncpp to parse a set of json. The json has been generated from a webpage with simplejson from a django object. I get it from a particular URL using libcurl. WHen I use the toStyledString() function on the root I get this printed out.

[
   {
      "fields" : {
         "desc" : "Carol King test",
         "format" : "1",
         "genre" : "Pop",
         "mount" : "CarolKing",
         "name" : "Carol King",
         "protocol" : "0",
         "songs" : [ 27, 28, 29, 30, 31, 32, 33, 34 ],
         "url" : "http://192.168.0.5:8000/CarolKing"
      },
      "model" : "music.playlist",
      "pk" : 2
   }
]

So it seems like I am getting the data right and its in a Json::Value class.

The problem is that im unable to get a particular node out of the json structure. This is the code im using.

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
#include <curl/curl.h>
#include <string>
#include "Parameter.h"
#include "lib_json/json.h"

using namespace std;

static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
    cout << "-->write_data " << endl;
    string buf = string(static_cast<char *>(ptr), size *nmemb);
    stringstream * response = static_cast<stringstream *>(stream);
    response->write(buf.c_str(), (streamsize)buf.size());
    return size * nmemb;

}

int main(int sys_argc, char ** sys_argv) {
    CURL *curl;
    CURLcode res;
    stringstream response;
    string error;

    char ** argv = sys_argv;

    string file = argv[1];
    Parameter *parms = new Parameter(file);
    parms->ReadParameters();

    cout << "URL: " << parms->GetParameter("URL");

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if(curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, parms->GetParameter("URL").c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
        res = curl_easy_perform(curl);

        cout << "Playlists-JSON: " << response.str() << endl;
        curl_easy_cleanup(curl);
    }

    Json::Value root;
    Json::Reader reader;

    bool parsingSuccessful = reader.parse(response.str(), root);

    if(!parsingSuccessful)
    {
        cout << "Failed to parse configuration. " << reader.getFormatedErrorMessages();
        return 16;
    }

    cout << "Pretty-Print: " << root.toStyledString() << endl;
    const Json::Value fields = root["fields"]["songs"];

    return 0;
}

because of another issue I'm not using the actual libjson.so shared library, im just pulling in the files and compiling them in with my source (I'm guessing this is bad, but that problem is not the point of this question). Below is how my src folder is structured.

.:
bird  Bird.cpp  fopen.cpp  fopen.h  lib_json  Parameter.cpp  Parameter.h

./lib_json:
autolink.h  features.h  json_batchallocator.h  json_internalarray.inl  json_reader.cpp  json_valueiterator.inl  reader.h    value.h
config.h    forwards.h  json.h                 json_internalmap.inl    json_value.cpp   json_writer.cpp         sconscript  writer.h

and this is the output of make.

    munderwo@bertha:/local/Documents/inthebackground/Box/Bird/bird/Debug$ make
Building file: ../src/lib_json/json_reader.cpp
Invoking: GCC C++ Compiler
g++ -I"/local/Documents/inthebackground/Box/Bird/bird/Libraries/i386/include" -I"/local/Documents/inthebackground/Box/Bird/bird/src" -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/lib_json/json_reader.d" -MT"src/lib_json/json_reader.d" -o"src/lib_json/json_reader.o" "../src/lib_json/json_reader.cpp"
Finished building: ../src/lib_json/json_reader.cpp

Building file: ../src/lib_json/json_value.cpp
Invoking: GCC C++ Compiler
g++ -I"/local/Documents/inthebackground/Box/Bird/bird/Libraries/i386/include" -I"/local/Documents/inthebackground/Box/Bird/bird/src" -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/lib_json/json_value.d" -MT"src/lib_json/json_value.d" -o"src/lib_json/json_value.o" "../src/lib_json/json_value.cpp"
Finished building: ../src/lib_json/json_value.cpp

Building file: ../src/lib_json/json_writer.cpp
Invoking: GCC C++ Compiler
g++ -I"/local/Documents/inthebackground/Box/Bird/bird/Libraries/i386/include" -I"/local/Documents/inthebackground/Box/Bird/bird/src" -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/lib_json/json_writer.d" -MT"src/lib_json/json_writer.d" -o"src/lib_json/json_writer.o" "../src/lib_json/json_writer.cpp"
Finished building: ../src/lib_json/json_writer.cpp

Building file: ../src/Bird.cpp
Invoking: GCC C++ Compiler
g++ -I"/local/Documents/inthebackground/Box/Bird/bird/Libraries/i386/include" -I"/local/Documents/inthebackground/Box/Bird/bird/src" -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/Bird.d" -MT"src/Bird.d" -o"src/Bird.o" "../src/Bird.cpp"
Finished building: ../src/Bird.cpp

Building file: ../src/Parameter.cpp
Invoking: GCC C++ Compiler
g++ -I"/local/Documents/inthebackground/Box/Bird/bird/Libraries/i386/include" -I"/local/Documents/inthebackground/Box/Bird/bird/src" -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/Parameter.d" -MT"src/Parameter.d" -o"src/Parameter.o" "../src/Parameter.cpp"
../src/Parameter.cpp: In member function ‘int Parameter::ReadParameters()’:
../src/Parameter.cpp:47: warning: comparison between signed and unsigned integer expressions
Finished building: ../src/Parameter.cpp

Building file: ../src/fopen.cpp
Invoking: GCC C++ Compiler
g++ -I"/local/Documents/inthebackground/Box/Bird/bird/Libraries/i386/include" -I"/local/Documents/inthebackground/Box/Bird/bird/src" -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/fopen.d" -MT"src/fopen.d" -o"src/fopen.o" "../src/fopen.cpp"
Finished building: ../src/fopen.cpp

Building target: Bird
Invoking: GCC C++ Linker
g++ -L"/local/Documents/inthebackground/Box/Bird/bird/Libraries/i386/lib" -o"Bird"  ./src/lib_json/json_reader.o ./src/lib_json/json_value.o ./src/lib_json/json_writer.o  ./src/Bird.o ./src/Parameter.o ./src/fopen.o   -lcurl
Finished building target: Bird

and from all of that I get the following output when I execute Bird

*Bird: ../src/lib_json/json_value.cpp:1025: Json::Value& Json::Value::resolveReference(const char*, bool): Assertion `type_ == nullValue || type_ == objectValue' failed.*
URL: 127.0.0.1:8000/playlist-->write_data
Playlists-JSON: [{"pk": 2, "model": "music.playlist", "fields": {"protocol": "0", "name": "Carol King", "format": "1", "url": "http://192.168.0.5:8000/CarolKing", "mount": "CarolKing", "genre": "Pop", "songs": [27, 28, 29, 30, 31, 32, 33, 34], "desc": "Carol King test"}}]
Pretty-Print: [
   {
      "fields" : {
         "desc" : "Carol King test",
         "format" : "1",
         "genre" : "Pop",
         "mount" : "CarolKing",
         "name" : "Carol King",
         "protocol" : "0",
         "songs" : [ 27, 28, 29, 30, 31, 32, 33, 34 ],
         "url" : "http://192.168.0.5:8000/CarolKing"
      },
      "model" : "music.playlist",
      "pk" : 2
   }
]

I dont get the problem if I comment out this line

const Json::Value fields = root["songs"];

Im totally open to the fact that im doing something wrong here. But I just dont know what it is. So what is causing the error:

Bird: ../src/lib_json/json_value.cpp:1025: Json::Value& Json::Value::resolveReference(const char*, bool): Assertion `type_ == nullValue || type_ == objectValue' failed.

thanks for any help you can give.

Cheers

Mark

Body:
Sorry,

But

const Json::Value fields = root["songs"];

Shouldn't be

const Json::Value fields = root["fields"];

songs is nested into fields, so to get the songs you should access it like this:

const Json::Value songs = root["fields"]["songs"];

No?


问:
Connecting to Postgres Database via Python
I am trying to connect to my database via Python 2.7 with this code:

```<code>import csv
import psycopg2

try:
    conn = psycopg2.connect("dbname='student', user='postgres',password='password', host='localhost'")
    cursor = conn_cursor()
    reader = csv.reader(open('last_file.csv', 'rb'))
    print "connected"
except:
    print "not Connected"
</code>```

It did work last week and we don't think we've changed anything, but now it won't connect.
We've tried using it with the database open and closed, nothing worked.
The database does exist in Postgres.

答:
```<code>import psycopg2

try:
    conn = psycopg2.connect("dbname='database_name' user='postgres_user_name' host='localhost' password='user_passwd'")
except:
    print "I am unable to connect to the database"

cur = conn.cursor()
cur.execute("""SELECT * from table_name""")
rows = cur.fetchall()
print "\nShow me the data:\n"
for row in rows:
    print "   ", row[0]
    print "   ", row[1]
</code>```

Body:
I am trying to connect to my database via Python 2.7 with this code:

import csv
import psycopg2

try:
    conn = psycopg2.connect("dbname='student', user='postgres',password='password', host='localhost'")
    cursor = conn_cursor()
    reader = csv.reader(open('last_file.csv', 'rb'))
    print "connected"
except:
    print "not Connected"

It did work last week and we don't think we've changed anything, but now it won't connect.
We've tried using it with the database open and closed, nothing worked.
The database does exist in Postgres.


答:
use for loop and start index from 14 to echo your result</p>

```<code>$values = get_field('bothscoreno');
$url    = $values;
$arr    = str_split("$url, PHP_URL_QUERY");
$string = '';
if ($url) {
  for($i = 11;$i <= 16;$i++){
    $string .= $arr[$i];
  }
} else {
    $string = 'No';
}

echo $string;
</code>```

Title: Tidy up PHP echo code

Body:
use for loop and start index from 14 to echo your result

$values = get_field('bothscoreno');
$url    = $values;
$arr    = str_split("$url, PHP_URL_QUERY");
$string = '';
if ($url) {
  for($i = 11;$i <= 16;$i++){
    $string .= $arr[$i];
  }
} else {
    $string = 'No';
}

echo $string;


问:
Unexpected behavior in ES6 const assignment
Given the following:

```<code>const foo = foo; // Uncaught ReferenceError: foo is not defined
</code>```

Trying to follow up with:

```<code>const foo = 123; // Uncaught SyntaxError: Identifier 'foo' has already been declared
</code>```

foo is never set, and similar behavior is seen in both Chrome and Firefox.

What is happening here?

答:
What you are experiencing here is the temporal dead zone. The variable foo has been declared, but not yet initialised. In fact you tried to initialise it as proper, but the evaluation of that expression threw an exception before foo could be set to a value. Now it is forever uninitialised - you had only that one chance.

This is a known problem. From es-discuss (by Jason Orendorff):

I just realized this has an unfortunate implication for REPLs. Suppose
  you make this typo:

```<code>js> let x = Math.cso(a)    // oops, TypeError, should be Math.cos
</code>```

Now x is irreparably hosed in your REPL. That seems bad.

I guess we can fix this by making the REPL bend the rules of the
  language. But this is rather hard to do for REPLs implemented in JS.
  Maybe the rules should just be a little more forgiving.

Body:
Given the following:

const foo = foo; // Uncaught ReferenceError: foo is not defined

Trying to follow up with:

const foo = 123; // Uncaught SyntaxError: Identifier 'foo' has already been declared

foo is never set, and similar behavior is seen in both Chrome and Firefox.

What is happening here?

Body:
What you are experiencing here is the temporal dead zone. The variable foo has been declared, but not yet initialised. In fact you tried to initialise it as proper, but the evaluation of that expression threw an exception before foo could be set to a value. Now it is forever uninitialised - you had only that one chance.

This is a known problem. From es-discuss (by Jason Orendorff):

I just realized this has an unfortunate implication for REPLs. Suppose
  you make this typo:

js> let x = Math.cso(a)    // oops, TypeError, should be Math.cos

Now x is irreparably hosed in your REPL. That seems bad.

I guess we can fix this by making the REPL bend the rules of the
  language. But this is rather hard to do for REPLs implemented in JS.
  Maybe the rules should just be a little more forgiving.


问:
How to select the Angular grid-controller row in selenium with webdriver?
I am working on automation test framework in selenium java.
In my test application we have used angular grid-controller.

How to access grid row to perform few operations?

答:
Finally I got the answer myself,
For every angular grid , angular generates the column index(hex number) , which is appended to the class attribute of the tag.
So we can access the cell value with same class attribute and  and iterate through all the rows for the host name column as shown in image please find the code snippet in selenium for same:

```<code>[![List<WebElement> rows = driver.findElements(By.xpath("//*[contains(@class,'ui-grid-cell ng-scope ui-grid-disable-selection ui-grid-coluiGrid-0006')]//div"));
    int iSize = rows.size();
for (int i = 0; i < iSize; i++) {
                String sValue =  "192.168.30.70";
                if (sValue.equalsIgnoreCase(inputtext)) {
                    rows.get(i).click();
                    break;
                }
            }
</code>```

so in this way we can search the particular grid column for the matching value.

Body:
Finally I got the answer myself,
For every angular grid , angular generates the column index(hex number) , which is appended to the class attribute of the tag.
So we can access the cell value with same class attribute and  and iterate through all the rows for the host name column as shown in image please find the code snippet in selenium for same:

[![List<WebElement> rows = driver.findElements(By.xpath("//*[contains(@class,'ui-grid-cell ng-scope ui-grid-disable-selection ui-grid-coluiGrid-0006')]//div"));
    int iSize = rows.size();
for (int i = 0; i < iSize; i++) {
                String sValue =  "192.168.30.70";
                if (sValue.equalsIgnoreCase(inputtext)) {
                    rows.get(i).click();
                    break;
                }
            }

so in this way we can search the particular grid column for the matching value.


问:
About the screen on in android application
I have an Android application and I want to keep the screen on. But sometimes I don't want to keep the screen on. What can I do to that?

EDIT: I have already used this code to set my screen on:

```<code>getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
</code>```

答:
You should use this:

```<code><uses-permission android:name="android.permission.WAKE_LOCK" />
</code>```

and then :

```<code>PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
wakeLock.acquire();
</code>```

Hope this helps.

Body:
I have an Android application and I want to keep the screen on. But sometimes I don't want to keep the screen on. What can I do to that?

EDIT: I have already used this code to set my screen on:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

Body:
You should use this:

<uses-permission android:name="android.permission.WAKE_LOCK" />

and then :

PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
wakeLock.acquire();

Hope this helps.


问:
Exception on aws configure in android studio
This error I get
     Error:Execution failed for task':app:transformClassesWithJarMergingForDebug'.

com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/amazonaws/services/cognitosync/AmazonCognitoSync.class

```<code>THIS IS MY BUILD.GREDLE FILE
//
// Copyright 2016 Amazon.com, Inc. or its affiliates (Amazon). All Rights Reserved.
//
// Code generated by AWS Mobile Hub. Amazon gives unlimited permission to
// copy, distribute and modify it.
//
// Source code generated from template: aws-my-sample-app-android v0.9
//
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "25.0.2"

    defaultConfig {
        applicationId "com.amazon.mysampleapp"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled = true
    }
    dexOptions {
        javaMaxHeapSize "4g"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            debuggable true
        }
    }

    lintOptions {
        abortOnError false
    }

    sourceCompatibility = 1.7
    targetCompatibility = 1.7
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.android.support:support-v4:23.0.1'
    compile 'com.amazonaws:aws-android-sdk-core:2.2.18'
    compile 'com.amazonaws:aws-android-sdk-cognito:2.2.18'
    compile 'com.amazonaws:aws-android-sdk-s3:2.2.18'
    compile 'com.amazonaws:aws-android-sdk-ddb:2.2.18'
    compile 'com.amazonaws:aws-android-sdk-ddb-mapper:2.2.18'
    compile 'com.amazonaws:aws-android-sdk-mobileanalytics:2.2.18'
    compile 'com.amazonaws:aws-android-sdk-lambda:2.2.18'
    compile 'com.amazonaws:aws-android-sdk-sns:2.2.18'
    compile 'com.google.android.gms:play-services:8.4.0'
    compile 'com.facebook.android:facebook-android-sdk:4.6.0'
    compile 'com.google.android.gms:play-services-plus:8.4.0'
    compile 'com.android.support:multidex:1.0.1'
    compile files('libs/aws-java-sdk-1.10.62.jar')
    compile files('libs/aws-java-sdk-1.10.62-sources.jar')

}
</code>```

答:
Execute the below code in the root project folder using terminal</p>

```<code>./gradlew clean
</code>```

Body:
This error I get
     Error:Execution failed for task':app:transformClassesWithJarMergingForDebug'.

com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/amazonaws/services/cognitosync/AmazonCognitoSync.class

THIS IS MY BUILD.GREDLE FILE
//
// Copyright 2016 Amazon.com, Inc. or its affiliates (Amazon). All Rights Reserved.
//
// Code generated by AWS Mobile Hub. Amazon gives unlimited permission to
// copy, distribute and modify it.
//
// Source code generated from template: aws-my-sample-app-android v0.9
//
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "25.0.2"

    defaultConfig {
        applicationId "com.amazon.mysampleapp"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled = true
    }
    dexOptions {
        javaMaxHeapSize "4g"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            debuggable true
        }
    }

    lintOptions {
        abortOnError false
    }

    sourceCompatibility = 1.7
    targetCompatibility = 1.7
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.android.support:support-v4:23.0.1'
    compile 'com.amazonaws:aws-android-sdk-core:2.2.18'
    compile 'com.amazonaws:aws-android-sdk-cognito:2.2.18'
    compile 'com.amazonaws:aws-android-sdk-s3:2.2.18'
    compile 'com.amazonaws:aws-android-sdk-ddb:2.2.18'
    compile 'com.amazonaws:aws-android-sdk-ddb-mapper:2.2.18'
    compile 'com.amazonaws:aws-android-sdk-mobileanalytics:2.2.18'
    compile 'com.amazonaws:aws-android-sdk-lambda:2.2.18'
    compile 'com.amazonaws:aws-android-sdk-sns:2.2.18'
    compile 'com.google.android.gms:play-services:8.4.0'
    compile 'com.facebook.android:facebook-android-sdk:4.6.0'
    compile 'com.google.android.gms:play-services-plus:8.4.0'
    compile 'com.android.support:multidex:1.0.1'
    compile files('libs/aws-java-sdk-1.10.62.jar')
    compile files('libs/aws-java-sdk-1.10.62-sources.jar')

}

Body:
Execute the below code in the root project folder using terminal

./gradlew clean


问:
Confused about ACF import/export workflow
After spending time browsing forum threads I'm still confused about Advanced Custom Fields' PHP/JSON import/export functionality (docs here, here and here). For instance between PHP and JSON export methods:

Which one saves field definition and which one saves field data?

Which one writes into the database and which one doesn't?

More importantly, why do imported fields (created on a different server) show up in the dashboard in some cases, but frustratingly not in others?

I saw in certain threads that there are people who are confused about at least one of these aspects too. Could someone sum up exactly how this works?

For the record, my team wants total sync on every developer's machine, that is, we want to see the same thing in ACF settings and in the admin pages, everywhere.

答:
None of the methods export DATA. They're exporting FIELDS. To export data you have to use Export under Tools menu in WordPress dashboard (that place where you can export your posts or pages)

As above, none.

PHP exported fields are not showing in dashboard (ACF dashboard, so you can't edit them).


问:
Kolmogorov-Smirnov test for normality in MATLAB - data normalisation?
I'm using the Kolmogorov-Smirnov test in MATLAB to determine the normality of each column of a data matrix prior to performing generalised linear regression. An example data vector is:

```<code>data = [8126,3163,9129,5399,8682,1126,1053,7805,2989,2758,3277,1152,6994,6833];
</code>```

The test runs and gives me a result. However, when I plot the empirical cumulative distribution function (cdf) (blue) and the standard normal cdf (red) for a visual comparison, the scale of such a data vector is such that the graph is not useful:

The code used to plot this figure is:

```<code>[h,p,ksstat,cv] = kstest(data);
[f,x_values] = ecdf(data);
figure()
F = plot(x_values,f);
set(F,'LineWidth',2);
hold on
G = plot(x_values,normcdf(x_values,0,1),'r-');
set(G,'LineWidth',2);
legend([F G],...
    'Empirical CDF','Standard Normal CDF',...
    'Location','SE');
</code>```

Does this mean the result of my test is not valid? If yes, can I just normalise the data e.g.

```<code>dataN=(data-min(data))./(max(data)-min(data));
</code>```

while maintaining test validity?

Thank you for your time,

Laura

答:
Thanks to Luis Mendo I solved this problem. normcdf requires the mean and standard deviation of the data vector as inputs, which I had not changed from the example code I was working from. The edited code is:

```<code>[h,p,ksstat,cv] = kstest(data);
[f,x_values] = ecdf(data);
figure()
F = plot(x_values,f);
set(F,'LineWidth',2);
hold on
variableMean = mean(data);
variableSD = std(data);
G = plot(x_values,normcdf(x_values,variableMean,variableSD),'r-');
set(G,'LineWidth',2);
legend([F G],...
    'Empirical CDF','Standard Normal CDF',...
    'Location','SE');
</code>```

Body:
I'm using the Kolmogorov-Smirnov test in MATLAB to determine the normality of each column of a data matrix prior to performing generalised linear regression. An example data vector is:

data = [8126,3163,9129,5399,8682,1126,1053,7805,2989,2758,3277,1152,6994,6833];

The test runs and gives me a result. However, when I plot the empirical cumulative distribution function (cdf) (blue) and the standard normal cdf (red) for a visual comparison, the scale of such a data vector is such that the graph is not useful:

The code used to plot this figure is:

[h,p,ksstat,cv] = kstest(data);
[f,x_values] = ecdf(data);
figure()
F = plot(x_values,f);
set(F,'LineWidth',2);
hold on
G = plot(x_values,normcdf(x_values,0,1),'r-');
set(G,'LineWidth',2);
legend([F G],...
    'Empirical CDF','Standard Normal CDF',...
    'Location','SE');

Does this mean the result of my test is not valid? If yes, can I just normalise the data e.g.

dataN=(data-min(data))./(max(data)-min(data));

while maintaining test validity?

Thank you for your time,

Laura

Body:
Thanks to Luis Mendo I solved this problem. normcdf requires the mean and standard deviation of the data vector as inputs, which I had not changed from the example code I was working from. The edited code is:

[h,p,ksstat,cv] = kstest(data);
[f,x_values] = ecdf(data);
figure()
F = plot(x_values,f);
set(F,'LineWidth',2);
hold on
variableMean = mean(data);
variableSD = std(data);
G = plot(x_values,normcdf(x_values,variableMean,variableSD),'r-');
set(G,'LineWidth',2);
legend([F G],...
    'Empirical CDF','Standard Normal CDF',...
    'Location','SE');


问:
Javascript timer to use multiple times in a page
I have this Javascript count down timer that works perfectly. Only problem is i can use it for only one time in one page. I want to use it multiple times.

I think script use id ="timer" that is why i am not able to use it multiple times.

Below  is the JS code:

```<code><script>
var startTime = 60; //in Minutes
var doneClass = "done"; //optional styling applied to text when timer is done
var space = '       ';

function startTimer(duration, display) {
  var timer = duration,
    minutes, seconds;
  var intervalLoop = setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    display.textContent = "00" + space + minutes + space + seconds;
    if (--timer < 0) {
      document.querySelector("#timer").classList.add(doneClass);
      clearInterval(intervalLoop);
    }
  }, 1000);
}

window.onload = function() {
  var now = new Date();
  var hrs = now.getHours();
  var setMinutes = 60 * (startTime - now.getMinutes() - (now.getSeconds() / 100)),
    display = document.querySelector("#timer");

  startTimer(setMinutes, display);
};
</script>
</code>```

答:
I think something like this could be helpful:

Timer object declaration

var timerObject = function(){
 this.startTime = 60; //in Minutes
 this.doneClass = "done"; //optional styling applied to text when timer is done
 this.space = '       ';

  return this;
};

timerObject.prototype.startTimer = function(duration, display) {
  var me = this,
    timer = duration,
    minutes, seconds;
  var intervalLoop = setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    display.textContent = "00" + me.space + minutes + me.space + seconds;
    if (--timer < 0) {
      // not sure about this part, because of selectors
      document.querySelector("#timer").classList.add(me.doneClass);
      clearInterval(intervalLoop);
    }
  }, 1000);
}```
</div>
</div>
</p>

<p>Use it like </p>

```var t1 = new timerObject();
var t2 = new timerObject();
t1.startTimer(a,b);
t2.startTimer(a,b);
```

JS Fiddle example:

UPD1 commented part so the the timer could be stopped

https://jsfiddle.net/9fjwsath/1/

Body:
I think something like this could be helpful:

Timer object declaration

var timerObject = function(){
 this.startTime = 60; //in Minutes
 this.doneClass = "done"; //optional styling applied to text when timer is done
 this.space = '       ';

  return this;
};

timerObject.prototype.startTimer = function(duration, display) {
  var me = this,
    timer = duration,
    minutes, seconds;
  var intervalLoop = setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    display.textContent = "00" + me.space + minutes + me.space + seconds;
    if (--timer < 0) {
      // not sure about this part, because of selectors
      document.querySelector("#timer").classList.add(me.doneClass);
      clearInterval(intervalLoop);
    }
  }, 1000);
}

Use it like

var t1 = new timerObject();
var t2 = new timerObject();
t1.startTimer(a,b);
t2.startTimer(a,b);

JS Fiddle example:

UPD1 commented part so the the timer could be stopped

https://jsfiddle.net/9fjwsath/1/


问:
How can I disable lazy loading of active record queries?
I want to query some objects from the database using a WHERE clause similar to the following:

```<code>@monuments =  Monument.where("... lots of SQL ...").limit(6)
</code>```

Later on, in my view I use methods like @monuments.first, then I loop through @monuments, then I display @monuments.count.

When I look at the Rails console, I see that Rails queries the database multiple times, first with a limit of 1 (for @monuments.first), then with a limit of 6 (for looping through all of them), and finally it issues a count() query.

How can I tell ActiveRecord to only execute the query once? Just executing the query once with a limit of 6 should be enough to get all the data I need. Since the query is slow (80ms), repeating it costs a lot of time.

答:
AFAIK, @monuments.first should not hit the db, I confirmed it on my console, maybe you have multiple instance with same variable or you are doing something else(which you haven't shared here), share the exact code and query and we might debug.

Since, ActiveRecord Collections acts as array, you can use array analogies to avoid querying the db.

Regarding first you can do,

```<code>@monuments[0]
</code>```

Regarding the count, yes, it is a different query which hits the db, to avoid it you can use length as..

```<code>@monuments.length
</code>```

Body:
I want to query some objects from the database using a WHERE clause similar to the following:

@monuments =  Monument.where("... lots of SQL ...").limit(6)

Later on, in my view I use methods like @monuments.first, then I loop through @monuments, then I display @monuments.count.

When I look at the Rails console, I see that Rails queries the database multiple times, first with a limit of 1 (for @monuments.first), then with a limit of 6 (for looping through all of them), and finally it issues a count() query.

How can I tell ActiveRecord to only execute the query once? Just executing the query once with a limit of 6 should be enough to get all the data I need. Since the query is slow (80ms), repeating it costs a lot of time.

Body:
AFAIK, @monuments.first should not hit the db, I confirmed it on my console, maybe you have multiple instance with same variable or you are doing something else(which you haven't shared here), share the exact code and query and we might debug.

Since, ActiveRecord Collections acts as array, you can use array analogies to avoid querying the db.

Regarding first you can do,

@monuments[0]

Regarding the count, yes, it is a different query which hits the db, to avoid it you can use length as..

@monuments.length


问:
Relationships with Lithium models
Can't find any documentation on relationships with Lithum models (using MongoDB). Could anyone point me to some info or show me an example?</p>

答:
You can use Doctrine 2 or another ORM for using relationships in Lithium with a relational database, but since Lithium is very much Mongo/Couch DB slanted in its approach, the question you have is less about Lithium and more about the NoSql approach that it is encouraging.

BTW I think relationships are not yet officially supported in Lithium, but NoSql have their own methods for mostly not needing them - or not needing them as much by nesting data in JSON like syntax. But I think this is one feature that looks like it will be coming in 1.0, expect a blog post on it fairly soon.

Title: Relationships with Lithium models


问:
C# Generic Error GDI+ on SaveAdd
I'm trying to create a small program to take a set of multi-page TIFF files from a folder, remove the front page and save the remaining pages using the same name to a separate output folder.

The files can save to the output folder without issue but I get "A Generic Error Occurred in GDI+" when it gets to the SaveAdd function on the second document. The first document(7 pages on output) adds all pages correctly. The second document fails when trying to add additional pages/frames after the initial page. I've tried different documents as first and second with varying number of pages. Can anyone shed any light on the issue?

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace FrontPageRemover
{
    class Program
    {
        static void Main(string[] args)
        {
            Image frame;
            int pages;
            string fileName;

            string folderPath = @"TIFF\Tiff Files";
            string[] files = Directory.GetFiles(folderPath);
            Image image;

            Encoder encoder = Encoder.SaveFlag;
            ImageCodecInfo encoderInfo = ImageCodecInfo.GetImageEncoders().First(i => i.MimeType == "image/tiff");
            EncoderParameters encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.MultiFrame);

            foreach (string file in files)
            {
                image = Image.FromFile(file);
                pages = image.GetFrameCount(FrameDimension.Page);
                image.SelectActiveFrame(FrameDimension.Page, 1);

                fileName = Path.GetFileName(file);
                image.Save(@"TIFF\Files Out\" + fileName, encoderInfo, encoderParams);

                for (int index = 2; index < pages; index++)
                {
                    image.SelectActiveFrame(FrameDimension.Page, index);
                    encoderParams.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.FrameDimensionPage);
                    image.SaveAdd(encoderParams);
                }

                encoderParams.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.Flush);
                image.SaveAdd(encoderParams);
                image.Dispose();
            }

        }
    }
}
</code>```

答:
Comments pointed me in the right direction with regards to the EncoderParameters not updating/being disposed of correctly.

The issue was with

```<code>encoderParams.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.MultiFrame);
</code>```

being outside of the loop. Hence the first document working correctly but the second document failing.

Title: C# Generic Error GDI+ on SaveAdd

Body:
I'm trying to create a small program to take a set of multi-page TIFF files from a folder, remove the front page and save the remaining pages using the same name to a separate output folder.

The files can save to the output folder without issue but I get "A Generic Error Occurred in GDI+" when it gets to the SaveAdd function on the second document. The first document(7 pages on output) adds all pages correctly. The second document fails when trying to add additional pages/frames after the initial page. I've tried different documents as first and second with varying number of pages. Can anyone shed any light on the issue?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace FrontPageRemover
{
    class Program
    {
        static void Main(string[] args)
        {
            Image frame;
            int pages;
            string fileName;

            string folderPath = @"TIFF\Tiff Files";
            string[] files = Directory.GetFiles(folderPath);
            Image image;

            Encoder encoder = Encoder.SaveFlag;
            ImageCodecInfo encoderInfo = ImageCodecInfo.GetImageEncoders().First(i => i.MimeType == "image/tiff");
            EncoderParameters encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.MultiFrame);

            foreach (string file in files)
            {
                image = Image.FromFile(file);
                pages = image.GetFrameCount(FrameDimension.Page);
                image.SelectActiveFrame(FrameDimension.Page, 1);

                fileName = Path.GetFileName(file);
                image.Save(@"TIFF\Files Out\" + fileName, encoderInfo, encoderParams);

                for (int index = 2; index < pages; index++)
                {
                    image.SelectActiveFrame(FrameDimension.Page, index);
                    encoderParams.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.FrameDimensionPage);
                    image.SaveAdd(encoderParams);
                }

                encoderParams.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.Flush);
                image.SaveAdd(encoderParams);
                image.Dispose();
            }

        }
    }
}

Body:
Comments pointed me in the right direction with regards to the EncoderParameters not updating/being disposed of correctly.

The issue was with

encoderParams.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.MultiFrame);

being outside of the loop. Hence the first document working correctly but the second document failing.


问:
use wildcard to copy folders using maven-assembly-plugin
I am using maven-assembly-plugin to collect some files and folders in a .tar.gz file. In my target directory, I have some folders with these names (for example):

lib-oracle
lib-mysql
lib-sqlserver
.
.

and each folder contains some jar files.

I want to copy these folders (and also contents of them) into a final .tar.gz file. I know I can copy them separately like this:

```<code><fileSet>
    <directory>target/lib-oracle</directory>
    <outputDirectory>lib-oracle</outputDirectory>
</fileSet>
</code>```

but I'm interested to know if there is any way to copy them all together?

maybe something like this:

```<code><fileSet>
    <directory>target/lib*</directory>
</fileSet>
</code>```

答:
You can use:

```<code><fileSet>
    <directory>target</directory>
    <includes>
        <include>lib-oracle/**</include>
        <outputDirectory>/</outputDirectory>
    </includes>
</fileSet>
</code>```

'**' indicates all the files in the current folder and all the files in the subfolders of the current folder.

Body:
I am using maven-assembly-plugin to collect some files and folders in a .tar.gz file. In my target directory, I have some folders with these names (for example):

lib-oracle
lib-mysql
lib-sqlserver
.
.

and each folder contains some jar files.

I want to copy these folders (and also contents of them) into a final .tar.gz file. I know I can copy them separately like this:

<fileSet>
    <directory>target/lib-oracle</directory>
    <outputDirectory>lib-oracle</outputDirectory>
</fileSet>

but I'm interested to know if there is any way to copy them all together?

maybe something like this:

<fileSet>
    <directory>target/lib*</directory>
</fileSet>

Body:
You can use:

<fileSet>
    <directory>target</directory>
    <includes>
        <include>lib-oracle/**</include>
        <outputDirectory>/</outputDirectory>
    </includes>
</fileSet>

'**' indicates all the files in the current folder and all the files in the subfolders of the current folder.