答:
Supposing that your Consultation class is written in this way:

```<code>public class Consultation{
    private Integer id;
    private String adresse;
}
</code>```

You can extract the JSON you posted into ad ArrayList in this way:

```<code>ArrayList<Consultation> consultationList = gson.fromJson(json ,new TypeToken<List<Consultation>>(){}.getType());
</code>```

Title: GSON can't deserialize an array

Body:
I'm facing a problem with Gson. I'm fetching Json data formatted. Here is the syntax :

I/Reponse-Json: [{"consultation_id":281,"plageconsult_id":76,"patient_id":116,"heure":"11:04:00","duree":1,"motif":null,"secteur1":0,"secteur2":0,"rques":null,"chrono":"32","annule":"0","patient_date_reglement":null,"examen":null,"traitement":null,"histoire_maladie":null,"conclusion":null,"premiere":"0","derniere":"0","tarif":null,"patient_mode_reglement":null,"arrivee":"2017-11-22 11:04:00","codes_ccam":null,"banque_id":null,"categorie_id":null,"adresse":"0","valide":"0","total_amc":null,"total_amo":null,"total_assure":null,"du_patient":0,"sejour_id":252,"du_tiers":0,"tiers_mode_reglement":null,"tiers_date_reglement":null,"date_at":null,"concerne_ALD":"0","facture":"0","adresse_par_prat_id":null,"si_desistement":"0","fin_at":null,"pec_at":null,"reprise_at":null,"type":"classique","grossesse_id":null,"at_sans_arret":"0","arret_maladie":"0","factureconsult_id":null,"brancardage":null,"sianesthesique":0},{"consultation_id":282,"plageconsult_id":77,"patient_id":116,"heure":"16:31:00","duree":1,"motif":null,"secteur1":0,"secteur2":0,"rques":"RAS","chrono":"64","annule":"0","patient_date_reglement":null,"examen":null,"traitement":"HUILE DE PARAFINE FL DE 1 LITRE\n","histoire_maladie":null,"conclusion":null,"premiere":"0","derniere":"0","tarif":null,"patient_mode_reglement":null,"arrivee":"2017-11-22 16:31:00","codes_ccam":null,"banque_id":null,"categorie_id":null,"adresse":"0","valide":"0","total_amc":null,"total_amo":null,"total_assure":null,"du_patient":0,"sejour_id":252,"du_tiers":0,"tiers_mode_reglement":null,"tiers_date_reglement":null,"date_at":null,"concerne_ALD":"0","facture":"0","adresse_par_prat_id":null,"si_desistement":"0","fin_at":null,"pec_at":null,"reprise_at":null,"type":"classique","grossesse_id":null,"at_sans_arret":"0","arret_maladie":"0","factureconsult_id":null,"brancardage":null,"sianesthesique":0}]

And here is the code used to deserialized

    Log.i("Reponse-Json", response);
    List<Consultation> consultations = Arrays.asList(gson.fromJson(response, Consultation[].class));
    Log.i("ConsultActivity", consultations.size()+" consultations loaded");
    for (Consultation c : consultations) {
        Log.i("ConsultActivity", ""+c.getConsultationId());
    }

And here is the error:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 72
                                                                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
                                                                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
                                                                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
                                                                  at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
                                                                  at com.google.gson.internal.bind.ArrayTypeAdapter.read(ArrayTypeAdapter.java:72)
                                                                  at com.google.gson.Gson.fromJson(Gson.java:803)
                                                                  at com.google.gson.Gson.fromJson(Gson.java:768)
                                                                  at com.google.gson.Gson.fromJson(Gson.java:717)
                                                                  at com.google.gson.Gson.fromJson(Gson.java:689)
                                                                  at org.cfrtmbk.www.elaafi.ConsultActivity$1.onResponse(ConsultActivity.java:69)
                                                                  at org.cfrtmbk.www.elaafi.ConsultActivity$1.onResponse(ConsultActivity.java:65)
                                                                  at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
                                                                  at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
                                                                  at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                                                                  at android.os.Handler.handleCallback(Handler.java:751)
                                                                  at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                  at android.os.Looper.loop(Looper.java:154)
                                                                  at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                  at java.lang.reflect.Method.invoke(Native Method)
                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                               Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 72
                                                                  at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:374)
                                                                  at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory

I have try to use a solution similar to :

Type collectionType = new TypeToken<Collection<channelSearchEnum>>(){}.getType();
Collection<channelSearchEnum> enums = gson.fromJson(yourJson, collectionType);

but having the same issue
Please help me

Body:
Supposing that your Consultation class is written in this way:

public class Consultation{
    private Integer id;
    private String adresse;
}

You can extract the JSON you posted into ad ArrayList in this way:

ArrayList<Consultation> consultationList = gson.fromJson(json ,new TypeToken<List<Consultation>>(){}.getType());


来源: stackexchange

问:
Amazon Machine Learning and SageMaker algorithms
1) According to http://docs.aws.amazon.com/machine-learning/latest/dg/learning-algorithm.html Amazon ML uses SGD. However I can't find how many hidden layers are used in the neural network?

2) Can someone confirm that SageMaker would be able to do what Amazon ML does? i.e. SageMaker is more powerful than Amazon ML?

答:
I'm not sure about Amazon ML but SageMaker uses the docker containers listed here for the built-in training: https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-algo-docker-registry-paths.html

So, in general, anything you can do with Amazon ML you should be able to do with SageMaker (although Amazon ML has a pretty sweet schema editor).

You can check out each of those containers to dive deep on how it all works.

You can find an exhaustive list of available algorithms in SageMaker here:
https://docs.aws.amazon.com/sagemaker/latest/dg/algos.html

For now, as of December 2017, these algorithms are all available:

Linear Learner

Factorization Machines

XGBoost Algorithm

Image Classification Algorithm

Amazon SageMaker Sequence2Sequence

K-Means Algorithm

Principal Component Analysis (PCA)

Latent Dirichlet Allocation (LDA)

Neural Topic Model (NTM)

The general SageMaker SDK interface to these algorithms looks something like this:

```<code>from sagemaker import KMeans
kmeans = KMeans(role="SageMakerRole",
                train_instance_count=2,
                train_instance_type='ml.c4.8xlarge',
                data_location="s3://training_data/",
                output_path="s3://model_artifacts/",
                k=10)
</code>```

The libraries here: https://github.com/awslabs/amazon-sagemaker-examples
and here: https://github.com/aws/sagemaker-python-sdk are particularly useful for playing with SageMaker.

You can also make use of Spark with SageMaker the Spark library here: https://github.com/aws/sagemaker-spark

ContentLicense: CC BY-SA 3.0

Body:
I'm not sure about Amazon ML but SageMaker uses the docker containers listed here for the built-in training: https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-algo-docker-registry-paths.html

So, in general, anything you can do with Amazon ML you should be able to do with SageMaker (although Amazon ML has a pretty sweet schema editor).

You can check out each of those containers to dive deep on how it all works.

You can find an exhaustive list of available algorithms in SageMaker here:
https://docs.aws.amazon.com/sagemaker/latest/dg/algos.html

For now, as of December 2017, these algorithms are all available:

Linear Learner

Factorization Machines

XGBoost Algorithm

Image Classification Algorithm

Amazon SageMaker Sequence2Sequence

K-Means Algorithm

Principal Component Analysis (PCA)

Latent Dirichlet Allocation (LDA)

Neural Topic Model (NTM)

The general SageMaker SDK interface to these algorithms looks something like this:

from sagemaker import KMeans
kmeans = KMeans(role="SageMakerRole",
                train_instance_count=2,
                train_instance_type='ml.c4.8xlarge',
                data_location="s3://training_data/",
                output_path="s3://model_artifacts/",
                k=10)

The libraries here: https://github.com/awslabs/amazon-sagemaker-examples
and here: https://github.com/aws/sagemaker-python-sdk are particularly useful for playing with SageMaker.

You can also make use of Spark with SageMaker the Spark library here: https://github.com/aws/sagemaker-spark


问:
'half space' in matplotlib labels and legend
How can I insert a half space in the text of matplotlib labels or legends, e.g. between numbers and their units? A simple workaround would be to use latex rendering, but is there an other way, e.g. using unicode characters?</p>

答:
You don't need to use latex rendering. Normal MathText is sufficient. It still has most basic latex capabities, e.g. a small space as \, available.

```<code>import matplotlib.pyplot as plt

plt.plot([1,2], label='$100\,$s')
plt.plot([1,3], label='$100$ s')

plt.legend()

plt.show()
</code>```

Body:
You don't need to use latex rendering. Normal MathText is sufficient. It still has most basic latex capabities, e.g. a small space as \, available.

import matplotlib.pyplot as plt

plt.plot([1,2], label='$100\,$s')
plt.plot([1,3], label='$100$ s')

plt.legend()

plt.show()


问:
Rails: Virtual Association?
I have an Invoice model that has an status_id attribute, this model belongs to Status models.

The Invoice.status_id can be "0 => active" or "2 => closed" in the DB.

The thing is in my Status model i also have ":id => 1, :name => due", but this is only when the Invoice.payment_date is less than today.

So my question is how can i something like

```<code>i = Invoice.find(:first)
i.status.name # i need this to return due if the Invoice.status_id == 0 and
              # Invoice.payment_date < Date.today
</code>```

Obviously the above code is always returning the name based on the value Invoice.status_id, because the association is correct.

I hope it make sense and somebody can help me.

Thanks.

答:
Is there a reason Status has to be a model? If not, I would make it a method like this:

```<code>class Invoice < ActiveRecord::Base
  def status
    if closed?
      "closed"
    elsif payment_date < Date.today
      "due"
    else
      "active"
    end
  end
end
</code>```

Then add a boolean field closed to the invoices table.

ContentLicense: CC BY-SA 2.5

Title: Rails: Virtual Association?

Body:
I have an Invoice model that has an status_id attribute, this model belongs to Status models.

The Invoice.status_id can be "0 => active" or "2 => closed" in the DB.

The thing is in my Status model i also have ":id => 1, :name => due", but this is only when the Invoice.payment_date is less than today.

So my question is how can i something like

i = Invoice.find(:first)
i.status.name # i need this to return due if the Invoice.status_id == 0 and
              # Invoice.payment_date < Date.today

Obviously the above code is always returning the name based on the value Invoice.status_id, because the association is correct.

I hope it make sense and somebody can help me.

Thanks.

Body:
Is there a reason Status has to be a model? If not, I would make it a method like this:

class Invoice < ActiveRecord::Base
  def status
    if closed?
      "closed"
    elsif payment_date < Date.today
      "due"
    else
      "active"
    end
  end
end

Then add a boolean field closed to the invoices table.


问:
adding image src from mysql database
My question is why doesn't the image appear on my php page, i have image url in database under 'imageurl'. I want to echo url to image src and this will show the picture from the folder. The error is Parse error: syntax error, unexpected '<' in .... on line 95. I will put the line 95 in the sample code too.</p>

```<code><html>
   <body>
      <?php while($row = mysql_fetch_assoc($query)): ?>
         <div class="NewsItem">
            <div>
              <h1><?php echo $row['txt']; ?></a> <br>
              <span>posted on <?php echo $row['added']; ?></span><span> by <?php echo $row['adder'];?></span>

             </div>
             <div class="imgdiv"><?php if(($row['imageurl'] == 'NULL') or ($row['imageurl']== '')){
                 //No images
             }
             else{
            Line 95----  <img src="<?php echo $row['imageurl'];?>" width='300' height='300'/>
             }

             ?></div>
             <br>
             <div>
             <form action="comment.php"method="post" name="addComment"><input type="text" placeholder="kommentaar" name="commenttext" maxlenght="100"><input type="submit" name="addComment" value="Lisa kommentaar">
             <input id="prodId3" name="prodId3" type="hidden" value="<?php echo $row['id']; ?>">
             </form>
             </div>
          </div>

      <?php
      endwhile;
      ?>
</code>```

答:
You forget about printing the result after your elseif clause. Moreover, you should use alternative syntax in PHP template, it will make things easier to read/maintain (You did it for while/endwhile).</p>

```<code><?php while($row = mysql_fetch_assoc($query)): ?>
 <div class="NewsItem">
    <div>
      <h1><?php echo $row['txt']; ?></a> <br>
      <span>posted on <?php echo $row['added']; ?></span><span> by <?php echo $row['adder'];?></span>

     </div>
     <div class="imgdiv">
    <?php if(($row['imageurl'] == 'NULL') or ($row['imageurl']== '')): ?>
        No image
    <?php else: ?>
        <img src="<?php echo $row['imageurl'];?>" width='300' height='300'/>
    <?php endif; ?>
    </div>
     <br>
     <div>
     <form action="comment.php"method="post" name="addComment"><input type="text" placeholder="kommentaar" name="commenttext" maxlenght="100"><input type="submit" name="addComment" value="Lisa kommentaar">
     <input id="prodId3" name="prodId3" type="hidden" value="<?php echo $row['id']; ?>">
     </form>
     </div>
  </div>

<?php endwhile; ?>
</code>```

Title: adding image src from mysql database

Body:
My question is why doesn't the image appear on my php page, i have image url in database under 'imageurl'. I want to echo url to image src and this will show the picture from the folder. The error is Parse error: syntax error, unexpected '<' in .... on line 95. I will put the line 95 in the sample code too.

      <?php while($row = mysql_fetch_assoc($query)): ?>

<?php echo $row['txt']; ?>

              posted on <?php echo $row['added']; ?> by <?php echo $row['adder'];?>

<?php if(($row['imageurl'] == 'NULL') or ($row['imageurl']== '')){
                 //No images
             }
             else{
            Line 95----  <img src="<?php echo $row['imageurl'];?>" width='300' height='300'/>
             }

             ?>

             <form action="comment.php"method="post" name="addComment"><input type="text" placeholder="kommentaar" name="commenttext" maxlenght="100"><input type="submit" name="addComment" value="Lisa kommentaar">
             <input id="prodId3" name="prodId3" type="hidden" value="<?php echo $row['id']; ?>">
             </form>

      <?php
      endwhile;
      ?>

Body:
You forget about printing the result after your elseif clause. Moreover, you should use alternative syntax in PHP template, it will make things easier to read/maintain (You did it for while/endwhile).

<?php while($row = mysql_fetch_assoc($query)): ?>
 <div class="NewsItem">
    <div>
      <h1><?php echo $row['txt']; ?></a> <br>
      <span>posted on <?php echo $row['added']; ?></span><span> by <?php echo $row['adder'];?></span>

     </div>
     <div class="imgdiv">
    <?php if(($row['imageurl'] == 'NULL') or ($row['imageurl']== '')): ?>
        No image
    <?php else: ?>
        <img src="<?php echo $row['imageurl'];?>" width='300' height='300'/>
    <?php endif; ?>
    </div>
     <br>
     <div>
     <form action="comment.php"method="post" name="addComment"><input type="text" placeholder="kommentaar" name="commenttext" maxlenght="100"><input type="submit" name="addComment" value="Lisa kommentaar">
     <input id="prodId3" name="prodId3" type="hidden" value="<?php echo $row['id']; ?>">
     </form>
     </div>
  </div>

<?php endwhile; ?>


问:
Selecting from Datatable , Grouped by multiple Column with condition
I have a datatable which has 4 fields in it.

```<code> ptime, Substation, ColumnTitle, ValueAmount
</code>```

I want to have the row with the maximum ValueAmount , Grouped by Substation and ColumnTitle. So suppose this is my datatable

```<code> ptime,  Substation, ColumnTitle, ValueAmount
 --------------------------------------------
 '01:00'    'AA'       'A'          100
 '03:00'    'AA'       'A'          150
 '01:00'    'BB'       'A'          10
 '02:00'    'BB'       'A'          11
 '01:00'    'AA'       'C'          77
 '02:00'    'AA'       'C'          88
 '04:00'    'AA'       'C'          99
</code>```

So I want to have

```<code>   ptime,  Substation, ColumnTitle, ValueAmount
 --------------------------------------------
 '03:00'    'AA'       'A'          150
 '02:00'    'BB'       'A'          11
 '04:00'    'AA'       'C'          99
</code>```

what is the best linq command for this purpose?
I have programmed this:

```<code> var newSort = from row in dtFinal.AsEnumerable()
   group row by new  {Substation = row.Field<string>("Substation"),
            ColumnTitle= row.Field<string>("ColumnTitle")} into grp
   select new
   {
     Substation = grp.Key.Substation,
     ColumnTitle = grp.Key.ColumnTitle,
     ValueAmount = grp.Max(r => decimal.Parse(r.Field<string>("ValueAmount")))
   };
</code>```

but in this syntax I don't have ptime for that. How can I do that.

Thank you

答:
This can be achieved using 2 query as below:</p>

```<code>var dt = from cu in DtFinals
         group cu.ValueAmount by new
            {
                cu.Substation,
                cu.ColumnTitle,
            } into gs
            select new
            {
                Substation = gs.Key.Substation,
                ColumnTitle = gs.Key.ColumnTitle,
                ValueAmount = gs.Max()
            };

var final = from c in DtFinals
            join d in dt on
            new {c.Substation, c.ColumnTitle,c.ValueAmount} equals
            new {d.Substation, d.ColumnTitle, d.ValueAmount}
            select new
            {
                ptime = c.Ptime,
                Substation = d.Substation,
                ColumnTitle = d.ColumnTitle,
                ValueAmount = d.ValueAmount
            };
</code>```

Body:
I have a datatable which has 4 fields in it.

 ptime, Substation, ColumnTitle, ValueAmount

I want to have the row with the maximum ValueAmount , Grouped by Substation and ColumnTitle. So suppose this is my datatable

 ptime,  Substation, ColumnTitle, ValueAmount
 --------------------------------------------
 '01:00'    'AA'       'A'          100
 '03:00'    'AA'       'A'          150
 '01:00'    'BB'       'A'          10
 '02:00'    'BB'       'A'          11
 '01:00'    'AA'       'C'          77
 '02:00'    'AA'       'C'          88
 '04:00'    'AA'       'C'          99

So I want to have

   ptime,  Substation, ColumnTitle, ValueAmount
 --------------------------------------------
 '03:00'    'AA'       'A'          150
 '02:00'    'BB'       'A'          11
 '04:00'    'AA'       'C'          99

what is the best linq command for this purpose?
I have programmed this:

 var newSort = from row in dtFinal.AsEnumerable()
   group row by new  {Substation = row.Field<string>("Substation"),
            ColumnTitle= row.Field<string>("ColumnTitle")} into grp
   select new
   {
     Substation = grp.Key.Substation,
     ColumnTitle = grp.Key.ColumnTitle,
     ValueAmount = grp.Max(r => decimal.Parse(r.Field<string>("ValueAmount")))
   };

but in this syntax I don't have ptime for that. How can I do that.

Thank you

Body:
This can be achieved using 2 query as below:

var dt = from cu in DtFinals
         group cu.ValueAmount by new
            {
                cu.Substation,
                cu.ColumnTitle,
            } into gs
            select new
            {
                Substation = gs.Key.Substation,
                ColumnTitle = gs.Key.ColumnTitle,
                ValueAmount = gs.Max()
            };

var final = from c in DtFinals
            join d in dt on
            new {c.Substation, c.ColumnTitle,c.ValueAmount} equals
            new {d.Substation, d.ColumnTitle, d.ValueAmount}
            select new
            {
                ptime = c.Ptime,
                Substation = d.Substation,
                ColumnTitle = d.ColumnTitle,
                ValueAmount = d.ValueAmount
            };


问:
How to install Typesafe Activator for Netbeans?
I recently installed a plugin called "playnb" (Version: 1.4.1) for Netbeans Version 8.2. After the installation of said plugin, the options window of Netbeans opened in a Tab called Play Framework. I got following Errormessage in this Tab

Please, specify the typesafe activator installation directory. It is required.

The Problem with this is, that i can't find out where to get a typesafe activator.

Your help would be highly appreciated.

答:
It seems that Typesafe Activator is now Open Source and can be Downloaded at Link for Typesafe Activator Download.

After downloading it, it is possible to run the .bat file and let the Programm do the rest for you.


问:
What is the general idea behind the concept of "context" in programming?
Web programming in particular?   I am used to procedural programming, but I have been working with ( and understanding quite well ) some sophisticated object oriented php.  One thing they keep talking about is "passing the context" or "setting the context".  I would assume that this context concept would apply to more languages than php, and to more areas other than web programming, as I have also heard it used in discussions about other languages.  </p>

答:
I think it is about: Passing an array or passing a bicycle around. In OO languages, you will reflect to real life situations and check how something is created there.

I have an example of a game:

Shall we give the game character a
  movement controller? Or should there
  be some static manager that does it
  for us? We finally chose to implement
  the movement controller inside the
  game character. He is the one
  responsible for its own movement, or
  at least his brains are. There is no
  puppeteer in a corner somewhere. It
  reflects to humans with a real brain.

The context here is checking what is what and who is who. Why is it like this in real life? Why should we implement it in another way? Being sure of your sorts of objects makes a very clear distinction in what is needed and what not.

Last example:

If I have an array with numbers, it
  doesn't say a thing. So if we pass it
  to some method that does magic, it
  doesn't say a thing either. We can
  create all sorts of arrays and just
  pass it to the method.

But we could also assure the array,
  that there must be cars in there. So
  this context of car becomes very
  important in our method and we cannot
  just throw in an array with number.

I hope I explained it well. This is somewhat like how I have learned it at college.


问:
Xamarin build ERROR : error APT0000: In <declare-styleable> ..., unable to find attribute
I received a project from another developer. I setup my machine. VS-2017 with the required components was already configured.

Android SDK-Manager has the corresponding version installed. Project is configured to compile with Android 7.1 (Nougat).

Starting the build I get one error

```<code>1>ERROR : error APT0000: In <declare-styleable> AppBarLayout, unable to find attribute android:keyboardNavigationCluster
</code>```

It is unclear to me, were I need to set this information, or were this information is needed.

I rececked ERROR: In  MenuView, unable to find attribute android:preserveIconSpacing
 and Error:In  SherlockSpinner, unable to find attribute android:popupPromptView. Both articles don't help.

I rechecked the SDK-Tools, I deleted the folder C:\Users\<user>\AppData\Local\Xamarin.

As far as I understand the message there is an attribute missing, that needs to be set.

In a project file Resource.designer.cs I found

```<code>public const int AppBarLayout_android_keyboardNavigationCluster = 2;
</code>```

The name seams to match exactly.

Can someone explain me this error?

Can someone explain how I get rid of it and how to fix similar problems in future?

答: I fixed it by setting the Target Android Version to API Level 26.</p>

Body:
I received a project from another developer. I setup my machine. VS-2017 with the required components was already configured.

Android SDK-Manager has the corresponding version installed. Project is configured to compile with Android 7.1 (Nougat).

Starting the build I get one error

1>ERROR : error APT0000: In <declare-styleable> AppBarLayout, unable to find attribute android:keyboardNavigationCluster

It is unclear to me, were I need to set this information, or were this information is needed.

I rececked ERROR: In  MenuView, unable to find attribute android:preserveIconSpacing
 and Error:In  SherlockSpinner, unable to find attribute android:popupPromptView. Both articles don't help.

I rechecked the SDK-Tools, I deleted the folder C:\Users\<user>\AppData\Local\Xamarin.

As far as I understand the message there is an attribute missing, that needs to be set.

In a project file Resource.designer.cs I found

public const int AppBarLayout_android_keyboardNavigationCluster = 2;

The name seams to match exactly.

Can someone explain me this error?

Can someone explain how I get rid of it and how to fix similar problems in future?


问:
Caused by: org.postgresql.util.PSQLException: FATAL: remaining connection slots are reserved for non-replication superuser connections
I use c3p0-0.9.5.2.jar and mchange-commons-java-0.2.11.jar to manage the pool connection,
And I use postgreSql 9.3.

I get these messages at least once a day in my Prod environment :

```<code>Caused by: java.sql.SQLException: Connections could not be acquired from the underlying database!
    at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:118)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:692)
    at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:140)
    at org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider.getConnection(LocalDataSourceConnectionProvider.java:81)
    at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
    ... 212 more
Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
    at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1469)
    at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:644)
    at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:554)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse(C3P0PooledConnectionPool.java:758)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:685)
    ... 215 more
Caused by: org.postgresql.util.PSQLException: FATAL: remaining connection slots are reserved for non-replication superuser connections
    at org.postgresql.core.v3.ConnectionFactoryImpl.readStartupMessages(ConnectionFactoryImpl.java:712)
</code>```

I have this config in my aplication :

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
         <bean id="dataSource" class = "com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
       <property name="driverClass" value="org.postgresql.Driver"/>

        <property name="jdbcUrl" value="jdbc:postgresql://localhost:5432/Test"/>

        <property name="user" value="postgres"/>
        <property name="password" value="postgres"/>
           <!-- pool sizing -->
     <!-- pool sizing -->
        <property name="initialPoolSize" value="32" />
        <property name="minPoolSize" value="30" />
        <property name="maxPoolSize" value="300" />
        <property name="acquireIncrement" value="10" />
        <property name="maxStatements" value="0" />

        <!-- retries -->
        <property name="acquireRetryAttempts" value="30" />
        <property name="acquireRetryDelay" value="1000" /> <!-- 1s -->
        <property name="breakAfterAcquireFailure" value="false" />

        <!-- refreshing connections -->
        <property name="maxIdleTime" value="180" /> <!-- 3min -->
        <property name="maxConnectionAge" value="10" /> <!-- 1h -->

        <!-- timeouts and testing -->
        <property name="checkoutTimeout" value="0" /> <!-- 60s -->
        <property name="idleConnectionTestPeriod" value="60" /> <!-- 60 -->
        <property name="testConnectionOnCheckout" value="true" />
        <property name="preferredTestQuery" value="SELECT 1" />
        <property name="testConnectionOnCheckin" value="true" />

    </bean>
</beans>
</code>```

in postgresql.conf I have this config :

```<code>max_connections = 300
shared_buffers = 32GB
</code>```

my server has this performance: 24 cpu, 256 GB memory

the number of users using the application is around 1300

is there anyone who can help me to solve this problem

thank you in advance

答:
There are superuser_reserved_connections connections slots (3 by default) that are reserved for superusers so that they can connect even in a situation where all connection slots are taken.

So you effectively only have 297 slots available.

Either reduce the maximum number of connections of your connection pool or increase max_connections in PostgreSQL.

By the way, 300 is much too high. You should use a much lower setting with a connection pool (unless you have hundreds of cores in your database machine).

ContentLicense: CC BY-SA 4.0

Body:
I use c3p0-0.9.5.2.jar and mchange-commons-java-0.2.11.jar to manage the pool connection,
And I use postgreSql 9.3.

I get these messages at least once a day in my Prod environment :

Caused by: java.sql.SQLException: Connections could not be acquired from the underlying database!
    at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:118)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:692)
    at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:140)
    at org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider.getConnection(LocalDataSourceConnectionProvider.java:81)
    at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
    ... 212 more
Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
    at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1469)
    at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:644)
    at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:554)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse(C3P0PooledConnectionPool.java:758)
    at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:685)
    ... 215 more
Caused by: org.postgresql.util.PSQLException: FATAL: remaining connection slots are reserved for non-replication superuser connections
    at org.postgresql.core.v3.ConnectionFactoryImpl.readStartupMessages(ConnectionFactoryImpl.java:712)

I have this config in my aplication :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
         <bean id="dataSource" class = "com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
       <property name="driverClass" value="org.postgresql.Driver"/>

        <property name="jdbcUrl" value="jdbc:postgresql://localhost:5432/Test"/>

        <property name="user" value="postgres"/>
        <property name="password" value="postgres"/>

        <property name="initialPoolSize" value="32" />
        <property name="minPoolSize" value="30" />
        <property name="maxPoolSize" value="300" />
        <property name="acquireIncrement" value="10" />
        <property name="maxStatements" value="0" />

        <property name="acquireRetryAttempts" value="30" />
        <property name="acquireRetryDelay" value="1000" />
        <property name="breakAfterAcquireFailure" value="false" />

        <property name="maxIdleTime" value="180" />
        <property name="maxConnectionAge" value="10" />

        <property name="checkoutTimeout" value="0" />
        <property name="idleConnectionTestPeriod" value="60" />
        <property name="testConnectionOnCheckout" value="true" />
        <property name="preferredTestQuery" value="SELECT 1" />
        <property name="testConnectionOnCheckin" value="true" />

    </bean>
</beans>

in postgresql.conf I have this config :

max_connections = 300
shared_buffers = 32GB

my server has this performance: 24 cpu, 256 GB memory

the number of users using the application is around 1300

is there anyone who can help me to solve this problem

thank you in advance


问:
How to do C++ style destructors in C#?
I've got a C# class with a Dispose function via IDisposable. It's intended to be used inside a using block so the expensive resource it handles can be released right away.

The problem is that a bug occurred when an exception was thrown before Dispose was called, and the programmer neglected to use using or finally.

In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use using.

Is there any way to for a using block to be automatically used in C#?

Many thanks.

UPDATE:

I'd like to explain why I'm not accepting the finalizer answers. Those answers are technically correct in themselves, but they are not C++ style destructors.

Here's the bug I found, reduced to the essentials...

```<code>try
{
    PleaseDisposeMe a = new PleaseDisposeMe();
    throw new Exception();
    a.Dispose();
}
catch (Exception ex)
{
    Log(ex);
}

// This next call will throw a time-out exception unless the GC
// runs a.Dispose in time.
PleaseDisposeMe b = new PleaseDisposeMe();
</code>```

Using FXCop is an excellent suggestion, but if that's my only answer, my question would have to become a plea to the C# people, or use C++. Twenty nested using statements anyone?

答:
A better design is to make this class release the expensive resource on its own, before its disposed.

For example, If its a database connection, only connect when needed and release immediately, long before the actual class gets disposed.

OwnerDisplayName: billpg

Title: How to do C++ style destructors in C#?

Body:
I've got a C# class with a Dispose function via IDisposable. It's intended to be used inside a using block so the expensive resource it handles can be released right away.

The problem is that a bug occurred when an exception was thrown before Dispose was called, and the programmer neglected to use using or finally.

In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use using.

Is there any way to for a using block to be automatically used in C#?

Many thanks.

UPDATE:

I'd like to explain why I'm not accepting the finalizer answers. Those answers are technically correct in themselves, but they are not C++ style destructors.

Here's the bug I found, reduced to the essentials...

try
{
    PleaseDisposeMe a = new PleaseDisposeMe();
    throw new Exception();
    a.Dispose();
}
catch (Exception ex)
{
    Log(ex);
}

// This next call will throw a time-out exception unless the GC
// runs a.Dispose in time.
PleaseDisposeMe b = new PleaseDisposeMe();

Using FXCop is an excellent suggestion, but if that's my only answer, my question would have to become a plea to the C# people, or use C++. Twenty nested using statements anyone?

LastEditorDisplayName: billpg

OwnerDisplayName: Jonathan Holland


问:
Problem applying texture to square in OpenGL
I'm stuck at not being able to map texture to a square in openGLES. I'm trying to display a jpg image on the screen, and in order for me to do that, I draw a square that I want to then map image onto. However all I get as an output is a white square. I don't know what am I doing wrong. And this problem is preventing me from moving forward with my project. I'm using Managed OpenGL ES wrapper for Windows Mobile.
I verified that the texture is loading correctly, but I can't apply it to my object. I uploaded sample project that shows my problem here. You would need VS2008 with Windows Mobile 6 SDK to be able to run it. I'm also posting the code of the Form that renders and textures an object here. Any suggestions would be much appreciated, since I've been stuck on this problem for a while, and I can't figure out what am I doing wrong.</p>

```<code>    public partial class Form1 : Form
{
    [DllImport("coredll")]
    extern static IntPtr GetDC(IntPtr hwnd);

    EGLDisplay myDisplay;
    EGLSurface mySurface;
    EGLContext myContext;

    public Form1()
    {
        InitializeComponent();
        myDisplay = egl.GetDisplay(new EGLNativeDisplayType(this));

        int major, minor;
        egl.Initialize(myDisplay, out major, out minor);

        EGLConfig[] configs = new EGLConfig[10];
        int[] attribList = new int[]
        {
            egl.EGL_RED_SIZE, 5,
            egl.EGL_GREEN_SIZE, 6,
            egl.EGL_BLUE_SIZE, 5,
            egl.EGL_DEPTH_SIZE, 16 ,
            egl.EGL_SURFACE_TYPE, egl.EGL_WINDOW_BIT,
            egl.EGL_STENCIL_SIZE, egl.EGL_DONT_CARE,
            egl.EGL_NONE, egl.EGL_NONE
        };

        int numConfig;
        if (!egl.ChooseConfig(myDisplay, attribList, configs, configs.Length, out numConfig) || numConfig < 1)
            throw new InvalidOperationException("Unable to choose config.");

        EGLConfig config = configs[0];
        mySurface = egl.CreateWindowSurface(myDisplay, config, Handle, null);
        myContext = egl.CreateContext(myDisplay, config, EGLContext.None, null);

        egl.MakeCurrent(myDisplay, mySurface, mySurface, myContext);
        gl.ClearColor(0, 0, 0, 0);
        InitGL();
    }

    void InitGL()
    {
        gl.ShadeModel(gl.GL_SMOOTH);
        gl.ClearColor(0.0f, 0.0f, 0.0f, 0.5f);
        gl.BlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA);
        gl.Hint(gl.GL_PERSPECTIVE_CORRECTION_HINT, gl.GL_NICEST);
    }

    public unsafe void DrawGLScene()
    {
        gl.MatrixMode(gl.GL_PROJECTION);
        gl.LoadIdentity();
        gl.Orthof(0, ClientSize.Width, ClientSize.Height, 0, 0, 1);
        gl.Disable(gl.GL_DEPTH_TEST);

        gl.MatrixMode(gl.GL_MODELVIEW);
        gl.LoadIdentity();

        Texture myImage;
        Bitmap Image = new Bitmap(@"\Storage Card\Texture.jpg");
        using (MemoryStream ms = new MemoryStream())
        {
            Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            myImage = Texture.LoadStream(ms, false);
        }

        float[] rectangle = new float[] {
                0, 0,
                myImage.Width, 0,
                0,  myImage.Height,
                myImage.Width,  myImage.Height
            };

        float[] texturePosition = new float[] {
                0, 0,
                myImage.Width, 0,
                0,  myImage.Height,
                myImage.Width,  myImage.Height
            };

        //Bind texture
        gl.BindTexture(gl.GL_TEXTURE_2D, myImage.Name);
        gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR);
        gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR);
        gl.EnableClientState(gl.GL_TEXTURE_COORD_ARRAY);
        gl.EnableClientState(gl.GL_VERTEX_ARRAY);

        //draw square and texture it.
        fixed (float* rectanglePointer = &rectangle[0], positionPointer = &texturePosition[0])
        {
            gl.TexCoordPointer(2, gl.GL_FLOAT, 0, (IntPtr)positionPointer);
            gl.VertexPointer(2, gl.GL_FLOAT, 0, (IntPtr)rectanglePointer);
            gl.DrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4);
        }

        gl.DisableClientState(gl.GL_TEXTURE_COORD_ARRAY);
        gl.DisableClientState(gl.GL_VERTEX_ARRAY);

    }

    protected override void OnPaintBackground(PaintEventArgs e)
    {

    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        gl.Clear(gl.GL_COLOR_BUFFER_BIT);

        DrawGLScene();
        egl.SwapBuffers(myDisplay, mySurface);
        gl.Clear(gl.GL_COLOR_BUFFER_BIT);
    }

    protected override void OnClosing(CancelEventArgs e)
    {
        if (!egl.DestroySurface(myDisplay, mySurface))
            throw new Exception("Error while destroying surface.");
        if (!egl.DestroyContext(myDisplay, myContext))
            throw new Exception("Error while destroying context.");
        if (!egl.Terminate(myDisplay))
            throw new Exception("Error while terminating display.");
        base.OnClosing(e);
    }
}
</code>```

答:
You need to enable texturing:

```<code>glEnable( GL_TEXTURE_2D );
</code>```

before rendering the square.

OwnerDisplayName: Ilya Volodin

Body:
I'm stuck at not being able to map texture to a square in openGLES. I'm trying to display a jpg image on the screen, and in order for me to do that, I draw a square that I want to then map image onto. However all I get as an output is a white square. I don't know what am I doing wrong. And this problem is preventing me from moving forward with my project. I'm using Managed OpenGL ES wrapper for Windows Mobile.
I verified that the texture is loading correctly, but I can't apply it to my object. I uploaded sample project that shows my problem here. You would need VS2008 with Windows Mobile 6 SDK to be able to run it. I'm also posting the code of the Form that renders and textures an object here. Any suggestions would be much appreciated, since I've been stuck on this problem for a while, and I can't figure out what am I doing wrong.

    public partial class Form1 : Form
{
    [DllImport("coredll")]
    extern static IntPtr GetDC(IntPtr hwnd);

    EGLDisplay myDisplay;
    EGLSurface mySurface;
    EGLContext myContext;

    public Form1()
    {
        InitializeComponent();
        myDisplay = egl.GetDisplay(new EGLNativeDisplayType(this));

        int major, minor;
        egl.Initialize(myDisplay, out major, out minor);

        EGLConfig[] configs = new EGLConfig[10];
        int[] attribList = new int[]
        {
            egl.EGL_RED_SIZE, 5,
            egl.EGL_GREEN_SIZE, 6,
            egl.EGL_BLUE_SIZE, 5,
            egl.EGL_DEPTH_SIZE, 16 ,
            egl.EGL_SURFACE_TYPE, egl.EGL_WINDOW_BIT,
            egl.EGL_STENCIL_SIZE, egl.EGL_DONT_CARE,
            egl.EGL_NONE, egl.EGL_NONE
        };

        int numConfig;
        if (!egl.ChooseConfig(myDisplay, attribList, configs, configs.Length, out numConfig) || numConfig < 1)
            throw new InvalidOperationException("Unable to choose config.");

        EGLConfig config = configs[0];
        mySurface = egl.CreateWindowSurface(myDisplay, config, Handle, null);
        myContext = egl.CreateContext(myDisplay, config, EGLContext.None, null);

        egl.MakeCurrent(myDisplay, mySurface, mySurface, myContext);
        gl.ClearColor(0, 0, 0, 0);
        InitGL();
    }

    void InitGL()
    {
        gl.ShadeModel(gl.GL_SMOOTH);
        gl.ClearColor(0.0f, 0.0f, 0.0f, 0.5f);
        gl.BlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA);
        gl.Hint(gl.GL_PERSPECTIVE_CORRECTION_HINT, gl.GL_NICEST);
    }

    public unsafe void DrawGLScene()
    {
        gl.MatrixMode(gl.GL_PROJECTION);
        gl.LoadIdentity();
        gl.Orthof(0, ClientSize.Width, ClientSize.Height, 0, 0, 1);
        gl.Disable(gl.GL_DEPTH_TEST);

        gl.MatrixMode(gl.GL_MODELVIEW);
        gl.LoadIdentity();

        Texture myImage;
        Bitmap Image = new Bitmap(@"\Storage Card\Texture.jpg");
        using (MemoryStream ms = new MemoryStream())
        {
            Image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            myImage = Texture.LoadStream(ms, false);
        }

        float[] rectangle = new float[] {
                0, 0,
                myImage.Width, 0,
                0,  myImage.Height,
                myImage.Width,  myImage.Height
            };

        float[] texturePosition = new float[] {
                0, 0,
                myImage.Width, 0,
                0,  myImage.Height,
                myImage.Width,  myImage.Height
            };

        //Bind texture
        gl.BindTexture(gl.GL_TEXTURE_2D, myImage.Name);
        gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR);
        gl.TexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR);
        gl.EnableClientState(gl.GL_TEXTURE_COORD_ARRAY);
        gl.EnableClientState(gl.GL_VERTEX_ARRAY);

        //draw square and texture it.
        fixed (float* rectanglePointer = &rectangle[0], positionPointer = &texturePosition[0])
        {
            gl.TexCoordPointer(2, gl.GL_FLOAT, 0, (IntPtr)positionPointer);
            gl.VertexPointer(2, gl.GL_FLOAT, 0, (IntPtr)rectanglePointer);
            gl.DrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4);
        }

        gl.DisableClientState(gl.GL_TEXTURE_COORD_ARRAY);
        gl.DisableClientState(gl.GL_VERTEX_ARRAY);

    }

    protected override void OnPaintBackground(PaintEventArgs e)
    {

    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        gl.Clear(gl.GL_COLOR_BUFFER_BIT);

        DrawGLScene();
        egl.SwapBuffers(myDisplay, mySurface);
        gl.Clear(gl.GL_COLOR_BUFFER_BIT);
    }

    protected override void OnClosing(CancelEventArgs e)
    {
        if (!egl.DestroySurface(myDisplay, mySurface))
            throw new Exception("Error while destroying surface.");
        if (!egl.DestroyContext(myDisplay, myContext))
            throw new Exception("Error while destroying context.");
        if (!egl.Terminate(myDisplay))
            throw new Exception("Error while terminating display.");
        base.OnClosing(e);
    }
}

LastEditorDisplayName: aib

Body:
You need to enable texturing:

glEnable( GL_TEXTURE_2D );

before rendering the square.

OwnerDisplayName: codelogic


问:
test works with jasmine-node, but not and with jasmine
I have a object that is subscribed to the uncaught error event and I am trying to test its behaviour. First I tried with jasmine-node, but now when I am trying to go with jasmine I found trouble. Could anyone help me.

```<code>describe('Constructor tests', function () {
    it('error is passed to the callback', function (done) {
    const error = new Error("testError-0");

    let errorHandler = new AllErrorHandler((arg1) => {
        expect(arg1).toBe(error);
        errorHandler.dispose();
        done();
    });

    setTimeout(() => {
        throw error;
    }, 0)
});
</code>```

Thanks in advance.

答:
I got this working when executed directly via jasmine when the jasmine ./tests/alLErrorException.spec.js command is run. The following changes were required:

Always setup the listeners, even when the _callback should not be executed.

```<code>constructor(callback, startListening = true) {
  if (!callback) {
    throw new Error("Missing callback function");
  }

  this._callback = callback;
  this._listening = startListening;
  this._setupEvents();
}
</code>```

Add a function to intercept uncaughtException events and to call the _callback if we are _listening:

```<code>_handler() {
  if(this._listening) {
    this._callback.apply(null, arguments);
  }
}
</code>```

Remove all other uncaughtException event handlers in _setupEvents:

```<code>_setupEvents(attatch = true) {
    this._listening = attatch ? true : false;

    if (attatch) {
        if (typeof window !== "undefined") {
            window.addEventListener("error", this._callback);
        } else {
            // Added this line
            process.removeAllListeners('uncaughtException');
            process.addListener('uncaughtException', this._handler.bind(this));
        }
    } else {
        if (typeof window !== "undefined") {
            window.removeEventListener("error", this._callback);
        } else {
            process.removeListener('uncaughtException', this._callback);
        }
    }
}
</code>```

This is required because jasmine sets up it's own uncaughtException handler and reports an error even though the error was caught by the AllErrorHandler class.

Here is a paste of the full source for the AllErrorHandler class with the required changes.

Body:
I have a object that is subscribed to the uncaught error event and I am trying to test its behaviour. First I tried with jasmine-node, but now when I am trying to go with jasmine I found trouble. Could anyone help me.

describe('Constructor tests', function () {
    it('error is passed to the callback', function (done) {
    const error = new Error("testError-0");

    let errorHandler = new AllErrorHandler((arg1) => {
        expect(arg1).toBe(error);
        errorHandler.dispose();
        done();
    });

    setTimeout(() => {
        throw error;
    }, 0)
});

Thanks in advance.

Body:
I got this working when executed directly via jasmine when the jasmine ./tests/alLErrorException.spec.js command is run. The following changes were required:

Always setup the listeners, even when the _callback should not be executed.

constructor(callback, startListening = true) {
  if (!callback) {
    throw new Error("Missing callback function");
  }

  this._callback = callback;
  this._listening = startListening;
  this._setupEvents();
}

Add a function to intercept uncaughtException events and to call the _callback if we are _listening:

_handler() {
  if(this._listening) {
    this._callback.apply(null, arguments);
  }
}

Remove all other uncaughtException event handlers in _setupEvents:

_setupEvents(attatch = true) {
    this._listening = attatch ? true : false;

    if (attatch) {
        if (typeof window !== "undefined") {
            window.addEventListener("error", this._callback);
        } else {
            // Added this line
            process.removeAllListeners('uncaughtException');
            process.addListener('uncaughtException', this._handler.bind(this));
        }
    } else {
        if (typeof window !== "undefined") {
            window.removeEventListener("error", this._callback);
        } else {
            process.removeListener('uncaughtException', this._callback);
        }
    }
}

This is required because jasmine sets up it's own uncaughtException handler and reports an error even though the error was caught by the AllErrorHandler class.

Here is a paste of the full source for the AllErrorHandler class with the required changes.


问:
How to extract big text from Excel cell in a formatted text with Excel formulas?
I have below text in Excel cell:

```<code>$abcd.$efghijk.$lmn.$op.$qrst.
</code>```

I want above text in following format in Excel cell using Excel formula only:

```<code>abcd$abcd.efghijk$efghijk.lmn$lmn.op$op.qrst$qrst.
</code>```

答:
Here's what I will suggest based on discussion.

In a general module, insert following code.

```<code>Public Function RepeatCustom(strInput As String) As String
Dim varInput As Variant
Dim i As Long
If Len(strInput) = 0 Then
    RepeatCustom = ""
Else
    varInput = Split(strInput, ".")
    For i = LBound(varInput) To UBound(varInput)
        RepeatCustom = RepeatCustom & " " & Mid(varInput(i), 2, Len(varInput(i))) & varInput(i)
    Next
    RepeatCustom = Replace(Trim(RepeatCustom), " ", ".") & "."
End If
End Function
</code>```

And then assuming cell containing original data is A2, you can use above UDF:

=RepeatCustom(A2)

Just note that the code is minimum and is based on sample posted.

Body:
I have below text in Excel cell:

$abcd.$efghijk.$lmn.$op.$qrst.

I want above text in following format in Excel cell using Excel formula only:

abcd$abcd.efghijk$efghijk.lmn$lmn.op$op.qrst$qrst.

Body:
Here's what I will suggest based on discussion.

In a general module, insert following code.

Public Function RepeatCustom(strInput As String) As String
Dim varInput As Variant
Dim i As Long
If Len(strInput) = 0 Then
    RepeatCustom = ""
Else
    varInput = Split(strInput, ".")
    For i = LBound(varInput) To UBound(varInput)
        RepeatCustom = RepeatCustom & " " & Mid(varInput(i), 2, Len(varInput(i))) & varInput(i)
    Next
    RepeatCustom = Replace(Trim(RepeatCustom), " ", ".") & "."
End If
End Function

And then assuming cell containing original data is A2, you can use above UDF:

=RepeatCustom(A2)

Just note that the code is minimum and is based on sample posted.


答:
In your code there is missmatch of opening and closing php tag, also put full URL of image with site URL
Try the following code</p>

```<code>else{ ?>
      <img src="<?php echo "your site url".$row['imageurl'];?>" width='300' height='300'/>
<?php    }
</code>```

Title: adding image src from mysql database

Body:
In your code there is missmatch of opening and closing php tag, also put full URL of image with site URL
Try the following code

else{ ?>
      <img src="<?php echo "your site url".$row['imageurl'];?>" width='300' height='300'/>
<?php    }


问:
Angular outputting JSON
I want to output only the short_title from "id": 28 but I
am unusure how to just call the title from all the JSON and then output
it in Angular within a HTML page.

```<code>  {
    "content": [
    {
        "id": 29,
        "short_title": "Flow",
        "long_title": "Flow",
        "fields": {
            "images": [
                {
                    "src": "content/29/images/QMTQUZxTMCoJMGrjOeowwqChJmnIe4fmFFT7pSph.jpeg",
                    "title": "Flow_2560.jpg"
                }
            ]
        },
        "type_id": 4,
        "folder_id": 3,
        "created_at": "2017-11-28 16:40:12",
        "updated_at": "2017-11-28 16:40:12",
        "type": {
            "id": 4,
            "code": "image-only",
            "title": "Full screen image",
            "visible_fields": [
                "images"
            ],
            "created_at": "2017-08-31 14:22:59",
            "updated_at": "2017-08-31 14:22:59"
        }
    },
    {
        "id": 28,
        "short_title": "Navigation buttons",
</code>```

I want to just output this short title

```<code>        "long_title": "Nav buttons 21st November",
        "fields": {
            "links": [
                {
                    "icon": "1",
                    "link": "http://sportspecific.digitaltesting.net/",
                    "size": "full",
                    "title": "Button 1",
                    "bg_colour": "#a64343",
                    "link_type": "url"
                },
                {
                    "icon": "2",
                    "link": "http://sportspecific.digitaltesting.net/",
                    "size": "full",
                    "title": "Button 2",
                    "bg_colour": "#742d2d",
                    "link_type": "url"
                }
            ]
        },
</code>```

答:
try data.content[1].short_title

in HTML,

{{data.content[1].short_title}}

Title: Angular outputting JSON

Body:
I want to output only the short_title from "id": 28 but I
am unusure how to just call the title from all the JSON and then output
it in Angular within a HTML page.

  {
    "content": [
    {
        "id": 29,
        "short_title": "Flow",
        "long_title": "Flow",
        "fields": {
            "images": [
                {
                    "src": "content/29/images/QMTQUZxTMCoJMGrjOeowwqChJmnIe4fmFFT7pSph.jpeg",
                    "title": "Flow_2560.jpg"
                }
            ]
        },
        "type_id": 4,
        "folder_id": 3,
        "created_at": "2017-11-28 16:40:12",
        "updated_at": "2017-11-28 16:40:12",
        "type": {
            "id": 4,
            "code": "image-only",
            "title": "Full screen image",
            "visible_fields": [
                "images"
            ],
            "created_at": "2017-08-31 14:22:59",
            "updated_at": "2017-08-31 14:22:59"
        }
    },
    {
        "id": 28,
        "short_title": "Navigation buttons",

I want to just output this short title

        "long_title": "Nav buttons 21st November",
        "fields": {
            "links": [
                {
                    "icon": "1",
                    "link": "http://sportspecific.digitaltesting.net/",
                    "size": "full",
                    "title": "Button 1",
                    "bg_colour": "#a64343",
                    "link_type": "url"
                },
                {
                    "icon": "2",
                    "link": "http://sportspecific.digitaltesting.net/",
                    "size": "full",
                    "title": "Button 2",
                    "bg_colour": "#742d2d",
                    "link_type": "url"
                }
            ]
        },


问:
SSIS Script Task does not work on second iteration of ForEach Loop Container

This is my first post on Stack Overflow and it surely will not be the last one. I had a very rough week trying to fix a problem with my SSIS Script Task in SSDT for VS2015.

The problem is the following:

I have a ForEach Loop Container in the Control Flow. I map a variable USER::FileName. This Variable I do use to process an excel file (replace commas with dots) in a Script Task and afterwards save the processed file and convert it to a flat file in data flow task. So far so good. But on the second loop of the ForEach Loop Container the original excel file is not processed properly. The names are set correctly but the commas are not replaced. I don't know what to try anymore. Maybe someone has any suggestion?

Edit 2: This is how the Script Task Code looks like:

```<code>using Excel = Microsoft.Office.Interop.Excel;
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{

    public void Main()
    {
        Excel._Application oApp = new Excel.Application();
        Excel.Workbook oWorkbook = oApp.Workbooks.Open(Dts.Variables["User::SourcePath"].Value.ToString() + "\\" + Dts.Variables["User::FileName"].Value.ToString() + ".xls");
        Excel.Worksheet oWorksheet = oWorkbook.Worksheets[1];
        try
        {
            ChangeValues(oWorksheet);
            oWorkbook.SaveAs("C:\\TEMP\\" + Dts.Variables["User::FileName"].Value.ToString() + ".xls");
            oWorkbook.Close();
            oApp.Quit();
            oWorksheet = null;
            oWorkbook = null;
            oApp = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();

            Dts.TaskResult = (int)ScriptResults.Success;
        }
        catch (Exception e)
        {
            Dts.Events.FireError(0, "Script task", e.Message + "\r" + e.StackTrace, String.Empty, 0);
        }
    }

    private static void ChangeValues(Excel.Worksheet oWorksheet)
    {
        Excel.Range range = oWorksheet.UsedRange;
        int colNo = range.Columns.Count;
        int rowNo = range.Rows.Count;
        // read the values into an array.
        object[,] cells = range.Value;
            for (int j = 1; j <= colNo; j++)
            {
                for (int i = 1; i <= rowNo; i++)
                {
                    if (j > 3 && cells[i, j] != null)
                    {
                        cells[i, j] = cells[i, j].ToString().Replace(",", ".");
                    }
                }
            }
            // set the values back into the range.
            range.Value = cells;
            return;
        }
 }
</code>```

答: Ok, I know this Post is a bit old but I found a solution for the problem a few weeks later and wanted to share it realy quickly with you guys. To debug the code I had to install Windows 10 and VS2017 on a VM because the Visual Studio Tools for Application (VSTA) Debugger that runs Script Tasks in SSIS does not work on VS2015 and SSDT is not available for VS2017 on Windows 7. So I was able to debug the Script on Windows 10 in VS2017 and found out that my code didn't open the correct excel sheet. Hope it might help anyone else with problems debugging SSIS Script Tasks.</p>

Body:
This is my first post on Stack Overflow and it surely will not be the last one. I had a very rough week trying to fix a problem with my SSIS Script Task in SSDT for VS2015.

The problem is the following:

I have a ForEach Loop Container in the Control Flow. I map a variable USER::FileName. This Variable I do use to process an excel file (replace commas with dots) in a Script Task and afterwards save the processed file and convert it to a flat file in data flow task. So far so good. But on the second loop of the ForEach Loop Container the original excel file is not processed properly. The names are set correctly but the commas are not replaced. I don't know what to try anymore. Maybe someone has any suggestion?

Edit 2: This is how the Script Task Code looks like:

using Excel = Microsoft.Office.Interop.Excel;
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{

    public void Main()
    {
        Excel._Application oApp = new Excel.Application();
        Excel.Workbook oWorkbook = oApp.Workbooks.Open(Dts.Variables["User::SourcePath"].Value.ToString() + "\\" + Dts.Variables["User::FileName"].Value.ToString() + ".xls");
        Excel.Worksheet oWorksheet = oWorkbook.Worksheets[1];
        try
        {
            ChangeValues(oWorksheet);
            oWorkbook.SaveAs("C:\\TEMP\\" + Dts.Variables["User::FileName"].Value.ToString() + ".xls");
            oWorkbook.Close();
            oApp.Quit();
            oWorksheet = null;
            oWorkbook = null;
            oApp = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();

            Dts.TaskResult = (int)ScriptResults.Success;
        }
        catch (Exception e)
        {
            Dts.Events.FireError(0, "Script task", e.Message + "\r" + e.StackTrace, String.Empty, 0);
        }
    }

    private static void ChangeValues(Excel.Worksheet oWorksheet)
    {
        Excel.Range range = oWorksheet.UsedRange;
        int colNo = range.Columns.Count;
        int rowNo = range.Rows.Count;
        // read the values into an array.
        object[,] cells = range.Value;
            for (int j = 1; j <= colNo; j++)
            {
                for (int i = 1; i <= rowNo; i++)
                {
                    if (j > 3 && cells[i, j] != null)
                    {
                        cells[i, j] = cells[i, j].ToString().Replace(",", ".");
                    }
                }
            }
            // set the values back into the range.
            range.Value = cells;
            return;
        }
 }


问:
Suppress password change email when accepting invitation with Devise Invitable
I have enabled password change notifications using

config.send_password_change_notification = true

However, currently when a user accepts an invitation triggered by Devise Invitable they are receiving a password change email.
e.g.

```<code>Started PUT "/users/invitation" for 127.0.0.1 at 2017-10-20 16:14:41 +0100
Processing by UsersController::InvitationsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"9gDHF+Vm6oxGPILonaQe7NSnhytoQGsOBm0eVEMziSS6J93UFnoHSwouyV9NezleulmstfcNW8Axr/nJajBBYw==", "user"=>{"invitation_token"=>"98usw1XW4w31UuCd_DzQ", "full_name"=>"example", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Set my password"}
  User Load (1.0ms)  SELECT  "users".* FROM "users" WHERE "users"."invitation_token" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["invitation_token", "0a0787a3270a097c22a1272f49040c5c11d67b2cb222059d88d85f35e95c8d78"], ["LIMIT", 1]]
   (0.2ms)  BEGIN
  SQL (0.6ms)  UPDATE "users" SET "invitation_token" = $1, "encrypted_password" = $2, "full_name" = $3, "invitation_accepted_at" = $4, "updated_at" = $5 WHERE "users"."id" = $6  [["invitation_token", nil], ["encrypted_password", "$2a$11$qQKCx4FWQS2ARyiiGf8zdeAn7XLBa0clbWuv1cH1c1cXWbF65VMd6"], ["full_name", "example"], ["invitation_accepted_at", "2017-10-20 16:14:41.323768"], ["updated_at", "2017-10-20 16:14:41.324814"], ["id", 9]]
DeviseMailer#password_change: processed outbound mail in 1.7ms
Sent mail to example@example.com (195.9ms)
</code>```

Is it possible to suppress the notification if the user is accepting an invitation but continue to send it for other password change events?

Environment info:

```<code>Rails 5.1.4
devise (4.3.0, 4.2.1)
devise_invitable (1.7.2)
</code>```

答:
thank you for pointing me in the right direction, here is my take on this

def send_password_change_notification
    super unless accepting_invitation?
end
```

<p><code>accepting_invitation?</code> is a variable set on the beginning of the process</p>

<p>As a bonus, it bugged me that when you ask for a password recover it would prompt you with a success message and don't do anything, with this it would prompt with an error message. </p>

<p><strong>[:en, :errors, :messages, :invitation_active]</strong> on your locales or just use default <strong>:not_found</strong></p>

```def send_reset_password_instructions
    if invited_to_sign_up?
        self.errors.add :email, :invitation_active
    else
        super
    end
end
```

Body:
I have enabled password change notifications using

config.send_password_change_notification = true

However, currently when a user accepts an invitation triggered by Devise Invitable they are receiving a password change email.
e.g.

Started PUT "/users/invitation" for 127.0.0.1 at 2017-10-20 16:14:41 +0100
Processing by UsersController::InvitationsController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"9gDHF+Vm6oxGPILonaQe7NSnhytoQGsOBm0eVEMziSS6J93UFnoHSwouyV9NezleulmstfcNW8Axr/nJajBBYw==", "user"=>{"invitation_token"=>"98usw1XW4w31UuCd_DzQ", "full_name"=>"example", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Set my password"}
  User Load (1.0ms)  SELECT  "users".* FROM "users" WHERE "users"."invitation_token" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["invitation_token", "0a0787a3270a097c22a1272f49040c5c11d67b2cb222059d88d85f35e95c8d78"], ["LIMIT", 1]]
   (0.2ms)  BEGIN
  SQL (0.6ms)  UPDATE "users" SET "invitation_token" = $1, "encrypted_password" = $2, "full_name" = $3, "invitation_accepted_at" = $4, "updated_at" = $5 WHERE "users"."id" = $6  [["invitation_token", nil], ["encrypted_password", "$2a$11$qQKCx4FWQS2ARyiiGf8zdeAn7XLBa0clbWuv1cH1c1cXWbF65VMd6"], ["full_name", "example"], ["invitation_accepted_at", "2017-10-20 16:14:41.323768"], ["updated_at", "2017-10-20 16:14:41.324814"], ["id", 9]]
DeviseMailer#password_change: processed outbound mail in 1.7ms
Sent mail to example@example.com (195.9ms)

Is it possible to suppress the notification if the user is accepting an invitation but continue to send it for other password change events?

Environment info:

Rails 5.1.4
devise (4.3.0, 4.2.1)
devise_invitable (1.7.2)

Body:
thank you for pointing me in the right direction, here is my take on this

def send_password_change_notification
    super unless accepting_invitation?
end

accepting_invitation? is a variable set on the beginning of the process

As a bonus, it bugged me that when you ask for a password recover it would prompt you with a success message and don't do anything, with this it would prompt with an error message.

[:en, :errors, :messages, :invitation_active] on your locales or just use default :not_found

def send_reset_password_instructions
    if invited_to_sign_up?
        self.errors.add :email, :invitation_active
    else
        super
    end
end


问:
How to sort only last few lines of a .txt file
I am new to Linux and i am trying to sort my text file which is called test.txt  and sort it in an descending order and output only the last 10 name into a new file?

This is the content of my test.txt

```<code>Warchief
Bad Man
Skeleton
Grave
Bobby
Annie
Gourmet
Minions
Flame
Tessa
Miner
Worker
Pan
</code>```

I know that i need to use

```<code>sort -r test.txt > test2.txt
</code>```

But i do not know how to sort only the output of last 10 names into test2.txt

答:
use tail piped to sort:

```<code>tail -n 10 test.txt | sort -r > test2.txt
</code>```

if you want to sort first, just switch the commands

```<code>sort -r test.txt | tail -n 10 > test2.txt
</code>```

Body:
I am new to Linux and i am trying to sort my text file which is called test.txt  and sort it in an descending order and output only the last 10 name into a new file?

This is the content of my test.txt

Warchief
Bad Man
Skeleton
Grave
Bobby
Annie
Gourmet
Minions
Flame
Tessa
Miner
Worker
Pan

I know that i need to use

sort -r test.txt > test2.txt

But i do not know how to sort only the output of last 10 names into test2.txt

Body:
use tail piped to sort:

tail -n 10 test.txt | sort -r > test2.txt

if you want to sort first, just switch the commands

sort -r test.txt | tail -n 10 > test2.txt


问:
Could not resolve com.android.support.test.espresso:espressgit so-core:3.0.1
Hours ago the gradle sync works well, however a moment ago, the testing dependency failed to download

Could not GET 'http://oss.jfrog.org/artifactory/oss-snapshot-local/com/android/support/test/espresso/espressgit%20so-core/3.0.1/espressgit%20so-core-3.0.1.pom'. Received status code 409 from server: Conflict

```<code>{
   errors: [
   {
   status: 409,
   message: "The repository 'oss-snapshot-local' rejected the resolution of an artifact 'oss-snapshot-local:com/android/support/test/espresso/espressgit so-core/3.0.1/espressgit so-core-3.0.1.pom' due to conflict in the snapshot release handling policy."
   } ]
}
</code>```

Deleted them solved the issue but I would like to retain the espresso dependency.

```<code> androidTestImplementation 'com.android.support.test.espresso:espressgit so-core:3.0.1', {
        exclude group: 'com.android.support', module: 'support-annotations'
    }
    androidTestImplementation 'com.android.support.test.espresso:espresso-contrib:3.0.1', {
        exclude group: 'com.android.support', module: 'support-annotations'
        exclude group: 'com.android.support', module: 'support-v4'
        exclude group: 'com.android.support', module: 'design'
        exclude group: 'com.android.support', module: 'recyclerview-v7'
    }
</code>```

答:
I think you typed git s or sgit into your build script while you thought the focus is in your terminal.

Look closely at the dependency, it says espressgit so-core but should probably be espresso-core which would then resolve from the android support repository and not reach the jfrog repository which responds with 409 whyever.

Body:
Hours ago the gradle sync works well, however a moment ago, the testing dependency failed to download

Could not GET 'http://oss.jfrog.org/artifactory/oss-snapshot-local/com/android/support/test/espresso/espressgit%20so-core/3.0.1/espressgit%20so-core-3.0.1.pom'. Received status code 409 from server: Conflict

{
   errors: [
   {
   status: 409,
   message: "The repository 'oss-snapshot-local' rejected the resolution of an artifact 'oss-snapshot-local:com/android/support/test/espresso/espressgit so-core/3.0.1/espressgit so-core-3.0.1.pom' due to conflict in the snapshot release handling policy."
   } ]
}

Deleted them solved the issue but I would like to retain the espresso dependency.

 androidTestImplementation 'com.android.support.test.espresso:espressgit so-core:3.0.1', {
        exclude group: 'com.android.support', module: 'support-annotations'
    }
    androidTestImplementation 'com.android.support.test.espresso:espresso-contrib:3.0.1', {
        exclude group: 'com.android.support', module: 'support-annotations'
        exclude group: 'com.android.support', module: 'support-v4'
        exclude group: 'com.android.support', module: 'design'
        exclude group: 'com.android.support', module: 'recyclerview-v7'
    }


问:
NumberFormatException in GPS processing
I am having a weird problem.

I am developing a program to log GPS and sensor readings periodically. My friend runs the code on his machine using Eclipse Galileo 3.6 and it works perfectly fine for her.

When I run the code on my machine which has Eclipse Galileo 3.5.2 it shows service stopped unexpectedly.

We have the same JDK version. I am not able to figure out what may be the exact problem.

Please let me know what else information I need to give in order to fix the problem.

logcat

```<code>    I/ActivityManager( 1104): Start proc com.sensor.test for service com.sensor.test/.SensorReadings: pid=3539 uid=10057 gids={3003, 1015}
D/AndroidRuntime( 3539): Shutting down VM
W/dalvikvm( 3539): threadid=1: thread exiting with uncaught exception (group=0x4001d7e0)
E/AndroidRuntime( 3539): FATAL EXCEPTION: main
E/AndroidRuntime( 3539): java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.BATTERY_CHANGED flg=0x60000000 (has extras) } in com.sensor.test.SensorReadings$2@44770958
E/AndroidRuntime( 3539):    at android.app.ActivityThread$PackageInfo$ReceiverDispatcher$Args.run(ActivityThread.java:905)
E/AndroidRuntime( 3539):    at android.os.Handler.handleCallback(Handler.java:587)
E/AndroidRuntime( 3539):    at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime( 3539):    at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime( 3539):    at android.app.ActivityThread.main(ActivityThread.java:4627)
E/AndroidRuntime( 3539):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 3539):    at java.lang.reflect.Method.invoke(Method.java:521)
E/AndroidRuntime( 3539):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
E/AndroidRuntime( 3539):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
E/AndroidRuntime( 3539):    at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 3539): Caused by: java.lang.NullPointerException
E/AndroidRuntime( 3539):    at com.sensor.test.SensorReadings$2.onReceive(SensorReadings.java:327)
E/AndroidRuntime( 3539):    at android.app.ActivityThread$PackageInfo$ReceiverDispatcher$Args.run(ActivityThread.java:892)
E/AndroidRuntime( 3539):    ... 9 more
W/ActivityManager( 1104): Activity destroy timeout for HistoryRecord{44b38508 com.sensor.test/.MainScreen}
D/WifiService( 1104): acquireWifiLockLocked: WifiLock{NetworkLocationProvider type=2 binder=android.os.Binder@44963d80}
D/LocationMasfClient( 1104): getNetworkLocation(): Location not found in cache, making network request
D/LocationMasfClient( 1104): getNetworkLocation(): Number of prefetched entries 10
E/LocationMasfClient( 1104): getNetworkLocation(): Returning *server* computed location with accuracy 28
D/libgps  ( 1104): GpsInterface_inject_location( 35.772249, -78.673950, 28.000 )
D/WifiService( 1104): releaseWifiLockLocked: WifiLock{NetworkLocationProvider type=2 binder=android.os.Binder@44963d80}
D/WifiService( 1104): acquireWifiLockLocked: WifiLock{NetworkLocationProvider type=2 binder=android.os.Binder@44963d80}
D/WifiService( 1104): releaseWifiLockLocked: WifiLock{NetworkLocationProvider type=2 binder=android.os.Binder@44963d80}
D/NativeCrypto( 1104): Freeing OpenSSL session
D/dalvikvm( 1104): GC_FOR_MALLOC freed 22104 objects / 1169312 bytes in 128ms
D/NativeCrypto( 1104): Freeing OpenSSL session
I/Process ( 3539): Sending signal. PID: 3539 SIG: 9
W/InputManagerService( 1104): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@44b40dd0
I/ActivityManager( 1104): Process com.sensor.test (pid 3539) has died.
</code>```

The pertinent code for line 88 with parsing going on:

```<code>public void startService(){
        //startService(new Intent(MainScreen.this,SensorReadings.class));
        Intent intent = new Intent(MainScreen.this, SensorReadings.class);
        **intent.putExtra("lp", Integer.parseInt(""+longPeriod.getText()));// LINE 88**
        intent.putExtra("gp", Integer.parseInt(""+gpsPeriod.getText()));
        intent.putExtra("sp", Integer.parseInt(""+snrPeriod.getText()));
        //startActivity(intent);
        startService(intent);
    }
</code>```

Thanks.
AG

答:
I don't get why you are putting "".

So to be sure this is not the problem try either this:

intent.putExtra("lp", Integer.parseInt(longPeriod.getText()));
    intent.putExtra("gp", Integer.parseInt(gpsPeriod.getText()));
    intent.putExtra("sp", Integer.parseInt(snrPeriod.getText()));

or

String lp = longPeriod.getText();

String gp = gpsPeriod.getText();

String sp = snrPeriod.getText();

intent.putExtra("lp", Integer.parseInt(lp));
    intent.putExtra("gp", Integer.parseInt(gp));
    intent.putExtra("sp", Integer.parseInt(sp));

The second way is better for debugging... so you can see what is actually happening.

Title: NumberFormatException in GPS processing

Body:
I am having a weird problem.

I am developing a program to log GPS and sensor readings periodically. My friend runs the code on his machine using Eclipse Galileo 3.6 and it works perfectly fine for her.

When I run the code on my machine which has Eclipse Galileo 3.5.2 it shows service stopped unexpectedly.

We have the same JDK version. I am not able to figure out what may be the exact problem.

Please let me know what else information I need to give in order to fix the problem.

logcat

    I/ActivityManager( 1104): Start proc com.sensor.test for service com.sensor.test/.SensorReadings: pid=3539 uid=10057 gids={3003, 1015}
D/AndroidRuntime( 3539): Shutting down VM
W/dalvikvm( 3539): threadid=1: thread exiting with uncaught exception (group=0x4001d7e0)
E/AndroidRuntime( 3539): FATAL EXCEPTION: main
E/AndroidRuntime( 3539): java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.BATTERY_CHANGED flg=0x60000000 (has extras) } in com.sensor.test.SensorReadings$2@44770958
E/AndroidRuntime( 3539):    at android.app.ActivityThread$PackageInfo$ReceiverDispatcher$Args.run(ActivityThread.java:905)
E/AndroidRuntime( 3539):    at android.os.Handler.handleCallback(Handler.java:587)
E/AndroidRuntime( 3539):    at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime( 3539):    at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime( 3539):    at android.app.ActivityThread.main(ActivityThread.java:4627)
E/AndroidRuntime( 3539):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 3539):    at java.lang.reflect.Method.invoke(Method.java:521)
E/AndroidRuntime( 3539):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
E/AndroidRuntime( 3539):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
E/AndroidRuntime( 3539):    at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 3539): Caused by: java.lang.NullPointerException
E/AndroidRuntime( 3539):    at com.sensor.test.SensorReadings$2.onReceive(SensorReadings.java:327)
E/AndroidRuntime( 3539):    at android.app.ActivityThread$PackageInfo$ReceiverDispatcher$Args.run(ActivityThread.java:892)
E/AndroidRuntime( 3539):    ... 9 more
W/ActivityManager( 1104): Activity destroy timeout for HistoryRecord{44b38508 com.sensor.test/.MainScreen}
D/WifiService( 1104): acquireWifiLockLocked: WifiLock{NetworkLocationProvider type=2 binder=android.os.Binder@44963d80}
D/LocationMasfClient( 1104): getNetworkLocation(): Location not found in cache, making network request
D/LocationMasfClient( 1104): getNetworkLocation(): Number of prefetched entries 10
E/LocationMasfClient( 1104): getNetworkLocation(): Returning *server* computed location with accuracy 28
D/libgps  ( 1104): GpsInterface_inject_location( 35.772249, -78.673950, 28.000 )
D/WifiService( 1104): releaseWifiLockLocked: WifiLock{NetworkLocationProvider type=2 binder=android.os.Binder@44963d80}
D/WifiService( 1104): acquireWifiLockLocked: WifiLock{NetworkLocationProvider type=2 binder=android.os.Binder@44963d80}
D/WifiService( 1104): releaseWifiLockLocked: WifiLock{NetworkLocationProvider type=2 binder=android.os.Binder@44963d80}
D/NativeCrypto( 1104): Freeing OpenSSL session
D/dalvikvm( 1104): GC_FOR_MALLOC freed 22104 objects / 1169312 bytes in 128ms
D/NativeCrypto( 1104): Freeing OpenSSL session
I/Process ( 3539): Sending signal. PID: 3539 SIG: 9
W/InputManagerService( 1104): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@44b40dd0
I/ActivityManager( 1104): Process com.sensor.test (pid 3539) has died.

The pertinent code for line 88 with parsing going on:

public void startService(){
        //startService(new Intent(MainScreen.this,SensorReadings.class));
        Intent intent = new Intent(MainScreen.this, SensorReadings.class);
        **intent.putExtra("lp", Integer.parseInt(""+longPeriod.getText()));// LINE 88**
        intent.putExtra("gp", Integer.parseInt(""+gpsPeriod.getText()));
        intent.putExtra("sp", Integer.parseInt(""+snrPeriod.getText()));
        //startActivity(intent);
        startService(intent);
    }

Thanks.
AG


问:
Wordpress Split Menu
I'm coding my first WordPress Theme and trying to solve this problem:

On the desktop version of the website I’d like to split the menu into 2 sections. One would appear on the left of the logo and the other on the right of my logo (the logo is centered). The only way I know how to do this is to create 2 separate MENU objects in WP and then with CSS position each one accordingly.

This however causes a problem when I want to convert the menu into a mobile-friendly drop-down menu, because in the approach shown above  I end up with 2 separate lists of menu items (Left and Right) and I don’t know how would I merge them into one list for mobile-friendly drop-down menu.

I understand I can write custom CSS to add margin between menu item #2 and item #3, for example. But since I’m writing a theme this approach won't work, as it requires to know upfront how many menu items will be present. I need it to be something that would work regardless of the number of menu items and that would allow people to re-arrange menu items using WP Menu UI.

Is this the wrong way to tackle this? If you could suggest how to approach this better I’d be very appreciative.

答:
Possible with CSS:</p>

```<code>ul.2-columns {
  -moz-column-count: 2;
  -moz-column-gap: 60px;
  -webkit-column-count: 2;
  -webkit-column-gap: 60px;
  column-count: 2;
  column-gap: 60px;
}
</code>```

Title: Wordpress Split Menu

Body:
Possible with CSS:

ul.2-columns {
  -moz-column-count: 2;
  -moz-column-gap: 60px;
  -webkit-column-count: 2;
  -webkit-column-gap: 60px;
  column-count: 2;
  column-gap: 60px;
}


问:
Are export const statements visible inside the file they reside?
Are export const statements visible inside the file they reside?

```<code>export const MAX_NAME_LENGTH = 20;
console.log(MAX_NAME_LENGTH); // can I do this?
</code>```

答:
Yes, they are. The declaration is still a declaration in the scope in which it appears (e.g., the module's scope, since export can only appear there) and all the usual rules about the declaration apply; all export does is export it.

In that specific case, since it's a const declaration, the "usual rules" include the temporal dead zone above the declaration in which MAX_NAME_LENGTH cannot be used. If you'd exported a function declaration like this:

```<code>export function foo() {
}
</code>```

...the "usual rules" mean you could use foo anywhere in your module code, because it's still hoisted. (Same for export var x;.)

(You can also test things like this with an up-to-date version of Chrome, which now supports modules. :-) )

Body:
Are export const statements visible inside the file they reside?

export const MAX_NAME_LENGTH = 20;
console.log(MAX_NAME_LENGTH); // can I do this?

Body:
Yes, they are. The declaration is still a declaration in the scope in which it appears (e.g., the module's scope, since export can only appear there) and all the usual rules about the declaration apply; all export does is export it.

In that specific case, since it's a const declaration, the "usual rules" include the temporal dead zone above the declaration in which MAX_NAME_LENGTH cannot be used. If you'd exported a function declaration like this:

export function foo() {
}

...the "usual rules" mean you could use foo anywhere in your module code, because it's still hoisted. (Same for export var x;.)

(You can also test things like this with an up-to-date version of Chrome, which now supports modules. :-) )


问:
Rails - Globalize and Permanent_record dependent: :destroy callbacks
In a Rails 4.2 project I use gem 'permanent_records' to handle records soft-deletion and gem 'globalize' for translations.

Globalize sets the following relationships between the translated Model and the Translation Model (source):

```<code>has_many :translations, :class_name  => translation_class.name,
                                :foreign_key => options[:foreign_key],
                                :dependent   => :destroy,
                                :extend      => HasManyExtensions,
                                :autosave    => true,
                                :inverse_of  => :globalized_model
</code>```

The result is that calling :destroy on the translated Model, does not delete it (which is what permanent_records is used for), but I lose the related translations, which I'd like to keep alive.

Shall I override the dependent: :destroy callback only on some translated models (the translated models where I use permanent_records)? How to do it properly?

Is there any other way to get the desired result?

答: I finally solved the issue by adding a deleted_at attribute to GlobalizedModel::Translation Model (in my case Treatment::Translation) so that also translations are soft-deleted.

Body:
In a Rails 4.2 project I use gem 'permanent_records' to handle records soft-deletion and gem 'globalize' for translations.

Globalize sets the following relationships between the translated Model and the Translation Model (source):

has_many :translations, :class_name  => translation_class.name,
                                :foreign_key => options[:foreign_key],
                                :dependent   => :destroy,
                                :extend      => HasManyExtensions,
                                :autosave    => true,
                                :inverse_of  => :globalized_model

The result is that calling :destroy on the translated Model, does not delete it (which is what permanent_records is used for), but I lose the related translations, which I'd like to keep alive.

Shall I override the dependent: :destroy callback only on some translated models (the translated models where I use permanent_records)? How to do it properly?

Is there any other way to get the desired result?