问:
how can i resize imageButton?
I want to resize my ImageButton using mouse on graphic layout or using code by
android:layout_width , android:layout_height. But whenever I do this, the ImageButton isn't resized, in fact and it's not smaller but it is cut at the edges.

thanks in advance

答:
The way I solved this problem is to create a bitmap from the drawing resource in question then transform it into a scaled bitmap with the desired size. I also set the background to transparent to only show the image.

```<code>    int height = 300;
    int width = 500
    Bitmap bmp;
    bmp = BitmapFactory.decodeResource(getResources(), R.drawable.myresourcename);
    bmp = Bitmap.createScaledBitmap(bmp, width, height, true);
    ImageButton imageButton = new ImageButton(this.getActivity());
    imageButton.setImageBitmap(bmp);
    imageButton.setBackgroundColor(Color.TRANSPARENT);
</code>```

Then add it to a layout.

Title: how can i resize imageButton?

Body:
The way I solved this problem is to create a bitmap from the drawing resource in question then transform it into a scaled bitmap with the desired size. I also set the background to transparent to only show the image.

    int height = 300;
    int width = 500
    Bitmap bmp;
    bmp = BitmapFactory.decodeResource(getResources(), R.drawable.myresourcename);
    bmp = Bitmap.createScaledBitmap(bmp, width, height, true);
    ImageButton imageButton = new ImageButton(this.getActivity());
    imageButton.setImageBitmap(bmp);
    imageButton.setBackgroundColor(Color.TRANSPARENT);

Then add it to a layout.


来源: stackexchange

问:
How do you mock ActivatedRoute
I'm learning Angular and I want to do tests, but I'm stuck. I've got a function:

```<code>ngOnInit(): void {
    this.route.paramMap
    .switchMap((params: ParamMap) =>
        this.SomethingService.getSomething(params.get('id')))
        .subscribe(something => {
            this.something = something;
            this.doSomethingElse();
    });
}
</code>```

where

```<code>route: ActivatedRoute
</code>```

and I want to test it but I don't know how to mock ActivatedRoute

答:
I was facing the same problem using paramMap instead of params.  This got it working for me, at least for the simplest case:

```<code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Observable } from 'rxjs';
import 'rxjs/add/observable/of';
import { ComponentToTest } from './component-to-test.component';
import { ActivatedRoute } from '@angular/router';

TestBed.configureTestingModule({
  declarations: [ComponentToTest],
  providers: [
    {
        provide: ActivatedRoute,
        useValue: {
            paramMap: Observable.of({ get: (key) => 'value' })
        }
    }
  ]
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: How do you mock ActivatedRoute

Body:
I'm learning Angular and I want to do tests, but I'm stuck. I've got a function:

ngOnInit(): void {
    this.route.paramMap
    .switchMap((params: ParamMap) =>
        this.SomethingService.getSomething(params.get('id')))
        .subscribe(something => {
            this.something = something;
            this.doSomethingElse();
    });
}

where

route: ActivatedRoute

and I want to test it but I don't know how to mock ActivatedRoute

Body:
I was facing the same problem using paramMap instead of params.  This got it working for me, at least for the simplest case:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Observable } from 'rxjs';
import 'rxjs/add/observable/of';
import { ComponentToTest } from './component-to-test.component';
import { ActivatedRoute } from '@angular/router';

TestBed.configureTestingModule({
  declarations: [ComponentToTest],
  providers: [
    {
        provide: ActivatedRoute,
        useValue: {
            paramMap: Observable.of({ get: (key) => 'value' })
        }
    }
  ]
});

ContentLicense: CC BY-SA 4.0


Title: Classifying items in a panel dataframe based on their average value over time

Body:
I have a multi-index dataframe of panel data that shows historical prices over time. What I basically want to do is group them by their average forecast over time- high (above 0.4), medium (between 0.2 and 0.4), and low (below 0.2).

                      price   yield   forecast

 date       assetid
 1/1/2017   4200      96.44    0.23       0.64
 1/1/2017   408        46.3     0.6        0.4
 1/1/2017   413       50.68    0.47       0.73
 1/1/2017   3911      82.48    0.33       0.84
 1/1/2017   7392      97.24     0.4       0.62
 1/1/2017   7144      31.86    0.18       0.54
 1/1/2017   8793      59.66    0.65        0.9
 1/2/2017   4200       57.1    0.21       0.69
 1/2/2017   408        4.76    0.86       0.16
 1/2/2017   413       70.79    0.24       0.12
 1/2/2017   3911       5.43    0.91       0.44
 1/2/2017   7392      47.33    0.51       0.18
 1/2/2017   7144      17.85    0.79       0.59
 1/2/2017   8793      98.08     0.2       0.24

So the first step I need to figure out is how to create a table that returns the mean value of each asset.

  assetid   Average of forecast
     408               0.73
     413              0.355
    3911               0.62
    4200               0.22
    7144              0.485
    7392              0.455
    8793              0.425

Then, I have to just join this newly created table and match on the assetid, with the same classification over time.

                      price   yield   forecast   type
 date       assetid
 1/1/2017   4200      96.44    0.23       0.64   med
 1/1/2017   408        46.3     0.6        0.4   high
 1/1/2017   413       50.68    0.47       0.73   med
 1/1/2017   3911      82.48    0.33       0.84   med
 1/1/2017   7392      97.24     0.4       0.62   high
 1/1/2017   7144      31.86    0.18       0.54   low
 1/1/2017   8793      59.66    0.65        0.9   high
 1/2/2017   4200       57.1    0.21       0.69   med
 1/2/2017   408        4.76    0.86       0.16   high
 1/2/2017   413       70.79    0.24       0.12   med
 1/2/2017   3911       5.43    0.91       0.44   med
 1/2/2017   7392      47.33    0.51       0.18   high
 1/2/2017   7144      17.85    0.79       0.59   low
 1/2/2017   8793      98.08     0.2       0.24   high

Body:
Let's use pd.cut:

s = pd.cut(df.groupby('assetid')['forecast'].mean(),[0,.2,.4,np.inf], labels=['low','med','high'])
df['type'] = df.assetid.map(s)
print(df)

Output:

        date  assetid  price  yield  forecast  type
0   1/1/2017     4200  96.44   0.23      0.64  high
1   1/1/2017      408  46.30   0.60      0.40   med
2   1/1/2017      413  50.68   0.47      0.73  high
3   1/1/2017     3911  82.48   0.33      0.84  high
4   1/1/2017     7392  97.24   0.40      0.62   med
5   1/1/2017     7144  31.86   0.18      0.54  high
6   1/1/2017     8793  59.66   0.65      0.90  high
7   1/2/2017     4200  57.10   0.21      0.69  high
8   1/2/2017      408   4.76   0.86      0.16   med
9   1/2/2017      413  70.79   0.24      0.12  high
10  1/2/2017     3911   5.43   0.91      0.44  high
11  1/2/2017     7392  47.33   0.51      0.18   med
12  1/2/2017     7144  17.85   0.79      0.59  high
13  1/2/2017     8793  98.08   0.20      0.24  high


问:
Parsing xml containing character reference
The XML im trying to parse contains a control character 0x2 inside CDATA. I tried to replace it with character reference which led to CDATA looking like:

```<code>CDATA section----charcter reference----CDATA section
</code>```

Now if i try to parse it i get an error message saying:
org.xml.sax.SAXParseException: Content is not allowed in prolog.

The original xml looked like:

```<code><?xml version="1.1" encoding="UTF-16"?><CELL><![CDATA[ABCDEFGH]]></CELL>
</code>```

I modified it to:

```<code><?xml version="1.1" encoding="UTF-16"?><CELL><![CDATA[ABCD]]><![CDATA[EFGH]]></CELL>
</code>```

答:
Entity definitions are not resolved in CDATA sections, that is why your original example does not work. That the modified example does not work seems to be a SAX parser error in my opinion. Maybe the SAX parser does not allow an invisible byte order mark (BOM) before the XML prolog that starts with <?, but the SAX parser should.

To help the SAX parser the following workaround would eventually do. Namely consuming the BOM before you feed the parser. You could use a markable stream for this purpose, i.e. marking the stream, reading the BOM, reseting the stream to its mark if there was no BOM. I didn't try, its just a guess.

BTW: Your question would be perceived better if you would fix the typo in the intro: Write "character reference" instead of "charcter reference". I first thought that the missing a is related to your question.

ContentLicense: CC BY-SA 2.5

Body:
The XML im trying to parse contains a control character 0x2 inside CDATA. I tried to replace it with character reference which led to CDATA looking like:

CDATA section----charcter reference----CDATA section

Now if i try to parse it i get an error message saying:
org.xml.sax.SAXParseException: Content is not allowed in prolog.

The original xml looked like:

<?xml version="1.1" encoding="UTF-16"?><CELL><![CDATA[ABCDEFGH]]></CELL>

I modified it to:

<?xml version="1.1" encoding="UTF-16"?><CELL><![CDATA[ABCD]]><![CDATA[EFGH]]></CELL>


问:
Does Parallel.ForEach limit the number of active threads?
Given this code:

```<code>var arrayStrings = new string[1000];
Parallel.ForEach<string>(arrayStrings, someString =>
{
    DoSomething(someString);
});
</code>```

Will all 1000 threads spawn almost simultaneously?

答:
Great question. In your example, the level of parallelization is pretty low even on a quad core processor, but with some waiting the level of parallelization can get quite high.

```<code>// Max concurrency: 5
[Test]
public void Memory_Operations()
{
    ConcurrentBag<int> monitor = new ConcurrentBag<int>();
    ConcurrentBag<int> monitorOut = new ConcurrentBag<int>();
    var arrayStrings = new string[1000];
    Parallel.ForEach<string>(arrayStrings, someString =>
    {
        monitor.Add(monitor.Count);
        monitor.TryTake(out int result);
        monitorOut.Add(result);
    });

    Console.WriteLine("Max concurrency: " + monitorOut.OrderByDescending(x => x).First());
}
</code>```

Now look what happens when a waiting operation is added to simulate an HTTP request.

```<code>// Max concurrency: 34
[Test]
public void Waiting_Operations()
{
    ConcurrentBag<int> monitor = new ConcurrentBag<int>();
    ConcurrentBag<int> monitorOut = new ConcurrentBag<int>();
    var arrayStrings = new string[1000];
    Parallel.ForEach<string>(arrayStrings, someString =>
    {
        monitor.Add(monitor.Count);

        System.Threading.Thread.Sleep(1000);

        monitor.TryTake(out int result);
        monitorOut.Add(result);
    });

    Console.WriteLine("Max concurrency: " + monitorOut.OrderByDescending(x => x).First());
}
</code>```

I haven't made any changes yet and the level of concurrency/parallelization has jumped drammatically. Concurrency can have its limit increased with ParallelOptions.MaxDegreeOfParallelism.

```<code>// Max concurrency: 43
[Test]
public void Test()
{
    ConcurrentBag<int> monitor = new ConcurrentBag<int>();
    ConcurrentBag<int> monitorOut = new ConcurrentBag<int>();
    var arrayStrings = new string[1000];
    var options = new ParallelOptions {MaxDegreeOfParallelism = int.MaxValue};
    Parallel.ForEach<string>(arrayStrings, options, someString =>
    {
        monitor.Add(monitor.Count);

        System.Threading.Thread.Sleep(1000);

        monitor.TryTake(out int result);
        monitorOut.Add(result);
    });

    Console.WriteLine("Max concurrency: " + monitorOut.OrderByDescending(x => x).First());
}

// Max concurrency: 391
[Test]
public void Test()
{
    ConcurrentBag<int> monitor = new ConcurrentBag<int>();
    ConcurrentBag<int> monitorOut = new ConcurrentBag<int>();
    var arrayStrings = new string[1000];
    var options = new ParallelOptions {MaxDegreeOfParallelism = int.MaxValue};
    Parallel.ForEach<string>(arrayStrings, options, someString =>
    {
        monitor.Add(monitor.Count);

        System.Threading.Thread.Sleep(100000);

        monitor.TryTake(out int result);
        monitorOut.Add(result);
    });

    Console.WriteLine("Max concurrency: " + monitorOut.OrderByDescending(x => x).First());
}
</code>```

I reccommend setting ParallelOptions.MaxDegreeOfParallelism. It will not necessarily increase the number of threads in use, but it will ensure you only start a sane number of threads, which seems to be your concern.

Lastly to answer your question, no you will not get all threads to start at once. Use Parallel.Invoke if you are looking to invoke in parallel perfectly e.g. testing race conditions.

```<code>// 636462943623363344
// 636462943623363344
// 636462943623363344
// 636462943623363344
// 636462943623363344
// 636462943623368346
// 636462943623368346
// 636462943623373351
// 636462943623393364
// 636462943623393364
[Test]
public void Test()
{
    ConcurrentBag<string> monitor = new ConcurrentBag<string>();
    ConcurrentBag<string> monitorOut = new ConcurrentBag<string>();
    var arrayStrings = new string[1000];
    var options = new ParallelOptions {MaxDegreeOfParallelism = int.MaxValue};
    Parallel.ForEach<string>(arrayStrings, options, someString =>
    {
        monitor.Add(DateTime.UtcNow.Ticks.ToString());
        monitor.TryTake(out string result);
        monitorOut.Add(result);
    });

    var startTimes = monitorOut.OrderBy(x => x.ToString()).ToList();
    Console.WriteLine(string.Join(Environment.NewLine, startTimes.Take(10)));
}
</code>```

Body:
Given this code:

var arrayStrings = new string[1000];
Parallel.ForEach<string>(arrayStrings, someString =>
{
    DoSomething(someString);
});

Will all 1000 threads spawn almost simultaneously?

Body:
Great question. In your example, the level of parallelization is pretty low even on a quad core processor, but with some waiting the level of parallelization can get quite high.

// Max concurrency: 5
[Test]
public void Memory_Operations()
{
    ConcurrentBag<int> monitor = new ConcurrentBag<int>();
    ConcurrentBag<int> monitorOut = new ConcurrentBag<int>();
    var arrayStrings = new string[1000];
    Parallel.ForEach<string>(arrayStrings, someString =>
    {
        monitor.Add(monitor.Count);
        monitor.TryTake(out int result);
        monitorOut.Add(result);
    });

    Console.WriteLine("Max concurrency: " + monitorOut.OrderByDescending(x => x).First());
}

Now look what happens when a waiting operation is added to simulate an HTTP request.

// Max concurrency: 34
[Test]
public void Waiting_Operations()
{
    ConcurrentBag<int> monitor = new ConcurrentBag<int>();
    ConcurrentBag<int> monitorOut = new ConcurrentBag<int>();
    var arrayStrings = new string[1000];
    Parallel.ForEach<string>(arrayStrings, someString =>
    {
        monitor.Add(monitor.Count);

        System.Threading.Thread.Sleep(1000);

        monitor.TryTake(out int result);
        monitorOut.Add(result);
    });

    Console.WriteLine("Max concurrency: " + monitorOut.OrderByDescending(x => x).First());
}

I haven't made any changes yet and the level of concurrency/parallelization has jumped drammatically. Concurrency can have its limit increased with ParallelOptions.MaxDegreeOfParallelism.

// Max concurrency: 43
[Test]
public void Test()
{
    ConcurrentBag<int> monitor = new ConcurrentBag<int>();
    ConcurrentBag<int> monitorOut = new ConcurrentBag<int>();
    var arrayStrings = new string[1000];
    var options = new ParallelOptions {MaxDegreeOfParallelism = int.MaxValue};
    Parallel.ForEach<string>(arrayStrings, options, someString =>
    {
        monitor.Add(monitor.Count);

        System.Threading.Thread.Sleep(1000);

        monitor.TryTake(out int result);
        monitorOut.Add(result);
    });

    Console.WriteLine("Max concurrency: " + monitorOut.OrderByDescending(x => x).First());
}

// Max concurrency: 391
[Test]
public void Test()
{
    ConcurrentBag<int> monitor = new ConcurrentBag<int>();
    ConcurrentBag<int> monitorOut = new ConcurrentBag<int>();
    var arrayStrings = new string[1000];
    var options = new ParallelOptions {MaxDegreeOfParallelism = int.MaxValue};
    Parallel.ForEach<string>(arrayStrings, options, someString =>
    {
        monitor.Add(monitor.Count);

        System.Threading.Thread.Sleep(100000);

        monitor.TryTake(out int result);
        monitorOut.Add(result);
    });

    Console.WriteLine("Max concurrency: " + monitorOut.OrderByDescending(x => x).First());
}

I reccommend setting ParallelOptions.MaxDegreeOfParallelism. It will not necessarily increase the number of threads in use, but it will ensure you only start a sane number of threads, which seems to be your concern.

Lastly to answer your question, no you will not get all threads to start at once. Use Parallel.Invoke if you are looking to invoke in parallel perfectly e.g. testing race conditions.

// 636462943623363344
// 636462943623363344
// 636462943623363344
// 636462943623363344
// 636462943623363344
// 636462943623368346
// 636462943623368346
// 636462943623373351
// 636462943623393364
// 636462943623393364
[Test]
public void Test()
{
    ConcurrentBag<string> monitor = new ConcurrentBag<string>();
    ConcurrentBag<string> monitorOut = new ConcurrentBag<string>();
    var arrayStrings = new string[1000];
    var options = new ParallelOptions {MaxDegreeOfParallelism = int.MaxValue};
    Parallel.ForEach<string>(arrayStrings, options, someString =>
    {
        monitor.Add(DateTime.UtcNow.Ticks.ToString());
        monitor.TryTake(out string result);
        monitorOut.Add(result);
    });

    var startTimes = monitorOut.OrderBy(x => x.ToString()).ToList();
    Console.WriteLine(string.Join(Environment.NewLine, startTimes.Take(10)));
}


问:
How can I know/set the HTML that will be rendered with ReactJS?
So normally we have these codes as the entry point for ReactJS.

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('container')
);
</code>```

For the ReactDOM.render() how and where I can specify the HTML file? Let say, I want to have the output HTML to be "not_index.html". How can I achieve that? I still don't understand how can ReactJS feels suddenly connected to a HTML file.

答: You just have a html file that loads this javascript. Somewhere in the html file you have an element with an id of container. You don't specify a html file anywhere, you just load that html file with the relevant javascript.

Body:
So normally we have these codes as the entry point for ReactJS.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <App />,
  document.getElementById('container')
);

For the ReactDOM.render() how and where I can specify the HTML file? Let say, I want to have the output HTML to be "not_index.html". How can I achieve that? I still don't understand how can ReactJS feels suddenly connected to a HTML file.


问:
Stackexchange Redis Sentinel Client
i m working with Redis distributed cache with failover pattern merged with hashing data distribution. My configuration is :

```<code>          Sentinel1                   Sentinel4
Master1                     Master2
          Sentinel2                   Sentinel5
Slave1                      Slave2
          Sentinel3                   Sentinel6
</code>```

In my code i need to access  master cache using sentinel.

Which one have i to point?

I suppose i have to register all the sentinel enpoints inside the configuration of the ConnectionMultiplexer.

I m able to connect my client to sentinel using this code:

```<code>  var options = new ConfigurationOptions()
    {
        CommandMap = CommandMap.Sentinel,
        EndPoints = { { IP, Port } },
        AllowAdmin = true,
        TieBreaker = "",
        ServiceName = ServiceName,
        SyncTimeout = 5000,
        AbortOnConnectFail = true,
        Ssl = false
    };
    var connection = ConnectionMultiplexer.Connect(options, Console.Out);
    return connection;
</code>```

Once got the connection i need to access the cache database using the standard redis methods like SetString and getString... so

```<code>db = conn.getDatabase();
db.getString(key);
db.setString(key, value);
</code>```

at this point i get an error stating "This operation has been disabled in the command-map and cannot be used: SETEX" or GET.

I suppose there should be a way to ask the sentinel the connection to the current master, but i m not finding many useful code example around.
Can anyone help me please?

答:
I believe if you connect to the Sentinel you can only issue Sentinel-specific commands. Try connecting to Redis instances instead, as explained here.

As for having the Redis client know, via Sentinel, that there was a change in Redis config (something I'm researching now and that's how I found your question) I think that part isn't implemented in Stackexchange.Redis yet - have a look at this.

Title: Stackexchange Redis Sentinel Client

Body:
i m working with Redis distributed cache with failover pattern merged with hashing data distribution. My configuration is :

          Sentinel1                   Sentinel4
Master1                     Master2
          Sentinel2                   Sentinel5
Slave1                      Slave2
          Sentinel3                   Sentinel6

In my code i need to access  master cache using sentinel.

Which one have i to point?

I suppose i have to register all the sentinel enpoints inside the configuration of the ConnectionMultiplexer.

I m able to connect my client to sentinel using this code:

  var options = new ConfigurationOptions()
    {
        CommandMap = CommandMap.Sentinel,
        EndPoints = { { IP, Port } },
        AllowAdmin = true,
        TieBreaker = "",
        ServiceName = ServiceName,
        SyncTimeout = 5000,
        AbortOnConnectFail = true,
        Ssl = false
    };
    var connection = ConnectionMultiplexer.Connect(options, Console.Out);
    return connection;

Once got the connection i need to access the cache database using the standard redis methods like SetString and getString... so

db = conn.getDatabase();
db.getString(key);
db.setString(key, value);

at this point i get an error stating "This operation has been disabled in the command-map and cannot be used: SETEX" or GET.

I suppose there should be a way to ask the sentinel the connection to the current master, but i m not finding many useful code example around.
Can anyone help me please?


问:
Can I call Java from Node.js via JNI and how?
can I call Java from Node.js via JNI? Are there any examples?

答:
I wonder if it is possible at all. but even if it is possible I imagine it is hard to implement and I am certain that nobody has done that yet.

how about using a named pipe to communicate between processes(java and node.js) ?


问:
Select Column, Count(Column) but order by a third column value
I tryed to do what was on this thread: SELECT COUNT messes with ORDER BY

But It seemed that I can't use the solution in ASP cshtml (or don't know how).

Here is the code I have right now

```<code>var selectCommand3 = "SELECT Ident, COUNT(Ident) As Column1 FROM ToolDor_AppMagDor AS NumberOfOrders GROUP BY Ident";
var selectedData3 = db.Query(selectCommand3);
</code>```

What I would like to do is order By DateCR. A third column where the DateCR column value is the same for each Ident column value. Like if there is 10 rows with the same Ident, the DateCR will also be the same.

I can't just Select DateCR instead because there can be more than one different Ident value for one DateCR...

I tryed a substring index but I dont seem to be able to make it works.

Basicaly I would like the system to accept this (but it won't =P) :

```<code>var selectCommand3 = "SELECT Ident, COUNT(Ident) As Column1 FROM ToolDor_AppMagDor AS NumberOfOrders GROUP BY Ident ORDER By DateCR DESC";
var selectedData3 = db.Query(selectCommand3);
</code>```

Thank you for your help and sorry for my english

答:
You need an aggregation function on the column, because the ORDER BY is processed after the aggregation.

This probably does what you want:

```<code>SELECT Ident, COUNT(Ident) As Column1
FROM ToolDor_AppMagDor NumberOfOrders
GROUP BY Ident
ORDER By MAX(DateCR) DESC;
</code>```

Body:
I tryed to do what was on this thread: SELECT COUNT messes with ORDER BY

But It seemed that I can't use the solution in ASP cshtml (or don't know how).

Here is the code I have right now

var selectCommand3 = "SELECT Ident, COUNT(Ident) As Column1 FROM ToolDor_AppMagDor AS NumberOfOrders GROUP BY Ident";
var selectedData3 = db.Query(selectCommand3);

What I would like to do is order By DateCR. A third column where the DateCR column value is the same for each Ident column value. Like if there is 10 rows with the same Ident, the DateCR will also be the same.

I can't just Select DateCR instead because there can be more than one different Ident value for one DateCR...

I tryed a substring index but I dont seem to be able to make it works.

Basicaly I would like the system to accept this (but it won't =P) :

var selectCommand3 = "SELECT Ident, COUNT(Ident) As Column1 FROM ToolDor_AppMagDor AS NumberOfOrders GROUP BY Ident ORDER By DateCR DESC";
var selectedData3 = db.Query(selectCommand3);

Thank you for your help and sorry for my english

Body:
You need an aggregation function on the column, because the ORDER BY is processed after the aggregation.

This probably does what you want:

SELECT Ident, COUNT(Ident) As Column1
FROM ToolDor_AppMagDor NumberOfOrders
GROUP BY Ident
ORDER By MAX(DateCR) DESC;


问:
Writing Spark Dataframe directly to HIVE is taking too much time
I am writing 2 dataframes from Spark directly to Hive using PySpark. The first df has only one row and 7 columns. The second df has 20M rows and 20 columns. It took 10 mins to write the 1 df(1row) and around 30Mins to write 1M rows in the second DF. I dont know how long it will take to write the entire 20M, I killed the code before it can complete.

I have tried two approaches to write the df. I also cached the df to see if it would make the write faster but didn't seem to have any effect:

```<code>df_log.write.mode("append").insertInto("project_alpha.sends_log_test")
</code>```

2nd Method

```<code>#df_log.registerTempTable("temp2")
#df_log.createOrReplaceTempView("temp2")
sqlContext.sql("insert into table project_alpha.sends_log_test select * from temp2")
</code>```

In the 2nd approach I tried using both registerTempTable() as well as createOrReplaceTempView() but there was no difference in the run time.

Is there a way to write it faster or more efficiently. Thanks.

答:
Its bad idea(or design) to do insert into hive table. You have to save it as file and create a table on top of it or add as a  partition to existing table.

Can you please try that route.

Body:
I am writing 2 dataframes from Spark directly to Hive using PySpark. The first df has only one row and 7 columns. The second df has 20M rows and 20 columns. It took 10 mins to write the 1 df(1row) and around 30Mins to write 1M rows in the second DF. I dont know how long it will take to write the entire 20M, I killed the code before it can complete.

I have tried two approaches to write the df. I also cached the df to see if it would make the write faster but didn't seem to have any effect:

df_log.write.mode("append").insertInto("project_alpha.sends_log_test")

2nd Method

#df_log.registerTempTable("temp2")
#df_log.createOrReplaceTempView("temp2")
sqlContext.sql("insert into table project_alpha.sends_log_test select * from temp2")

In the 2nd approach I tried using both registerTempTable() as well as createOrReplaceTempView() but there was no difference in the run time.

Is there a way to write it faster or more efficiently. Thanks.


问:
iOS push notifications feedback service
I can send to my swift 2 app push notifications via PHP.
now I would like to have a script for the feedback service.

I found this:

```<code>$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'xxx.pem');
stream_context_set_option($ctx, 'ssl', 'verify_peer', false);

$fp = stream_socket_client('ssl://feedback.push.apple.com:2196', $error, $errorString, 60, STREAM_CLIENT_CONNECT, $ctx);

if (!$fp) {
 echo "Failed to connect feedback server:".$err.". ".$errstr."<br />";
 exit();
}
else {
 echo "Connection to feedback server OK<br />";
}

 echo "APNS feedback results<br />";
 while ($devcon = fread($fp, 38))
 {
 $arr = unpack("H*", $devcon);
 $rawhex = trim(implode("", $arr));
 $feedbackTime = hexdec(substr($rawhex, 0, 8));
 $feedbackDate = date('Y-m-d H:i', $feedbackTime);
 $feedbackLen = hexdec(substr($rawhex, 8, 4));
 $feedbackDeviceToken = substr($rawhex, 12, 64);
 echo "TIMESTAMP:" . $feedbackDate . "<br />";
 echo "DEVICE ID:" . $feedbackDeviceToken. "<br /><br />";
 }
fclose($fp);
</code>```

This code shows me that:

```<code>Connection to feedback server OK
APNS feedback results
</code>```

But no result. I sent a few minutes ago and push notification to a token 0. this is an invalid token.

But why I didn't get this invalid token via feedback service?

答: You only get results when there is something to show. Results are shown one time, after that it is deleted so you should handle it immediatly when received</p>

Title: iOS push notifications feedback service

Body:
I can send to my swift 2 app push notifications via PHP.
now I would like to have a script for the feedback service.

I found this:

$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'xxx.pem');
stream_context_set_option($ctx, 'ssl', 'verify_peer', false);

$fp = stream_socket_client('ssl://feedback.push.apple.com:2196', $error, $errorString, 60, STREAM_CLIENT_CONNECT, $ctx);

if (!$fp) {
 echo "Failed to connect feedback server:".$err.". ".$errstr."
";
 exit();
}
else {
 echo "Connection to feedback server OK
";
}

 echo "APNS feedback results
";
 while ($devcon = fread($fp, 38))
 {
 $arr = unpack("H*", $devcon);
 $rawhex = trim(implode("", $arr));
 $feedbackTime = hexdec(substr($rawhex, 0, 8));
 $feedbackDate = date('Y-m-d H:i', $feedbackTime);
 $feedbackLen = hexdec(substr($rawhex, 8, 4));
 $feedbackDeviceToken = substr($rawhex, 12, 64);
 echo "TIMESTAMP:" . $feedbackDate . "
";
 echo "DEVICE ID:" . $feedbackDeviceToken. "

";
 }
fclose($fp);

This code shows me that:

Connection to feedback server OK
APNS feedback results

But no result. I sent a few minutes ago and push notification to a token 0. this is an invalid token.

But why I didn't get this invalid token via feedback service?


问:
Transfer LocalStorage When Installing cordova-plugin-wkwebview-engine Plugin
Is there a way to transfer a user's LocalStorage data to the wkwebview browser when adding the cordova-plugin-wkwebview-engine plugin into an existing cordova/ionic project?

WKWebView is essentially a different browser and has no knowledge of any previous data saved within the UIWebView browser.

Crosswalk for Android handles this process automatically by migrating data to the new browser when the plugin is installed and first run on an existing user's device.

答:
This Cordova plugin seems to be doing exactly what you describe, it migrates the localStorage from UIWebView over to be used in WKWebview: https://github.com/MaKleSoft/cordova-plugin-migrate-localstorage

Someone even forked it to add more functionality, such as migrating IndexedDB: https://github.com/jairemix/cordova-plugin-migrate-localstorage

Hope this helps!


Body:
pd.cut + transform

df['type']=pd.cut(df.groupby(level='assetid')
               .forecast
                  .transform('mean'),[0,0.2,0.4,np.inf],labels=['low','med','high'])
df
Out[663]:
                  price  yield  forecast  type
date     assetid
1/1/2017 4200     96.44   0.23      0.64  high
         408      46.30   0.60      0.40   med
         413      50.68   0.47      0.73  high
         3911     82.48   0.33      0.84  high
         7392     97.24   0.40      0.62   med
         7144     31.86   0.18      0.54  high
         8793     59.66   0.65      0.90  high
1/2/2017 4200     57.10   0.21      0.69  high
         408       4.76   0.86      0.16   med
         413      70.79   0.24      0.12  high
         3911      5.43   0.91      0.44  high
         7392     47.33   0.51      0.18   med
         7144     17.85   0.79      0.59  high
         8793     98.08   0.20      0.24  high


问:
reading appSettings from asp.net core webapi
I have an asp.net core 2 webapi service. I want to read appsettings.json but I cannot figure it out. As usual, when I search the internet I get a dozen completely different answers based on various versions of the framework that ultimately don't seem to work.

As an example appsettings.json:

```<code>"AppSettings": {
  "Domain": "http://localhost"
}
</code>```

Firstly I tried this:

Added via nuget Microsoft.Extensions.Configuration and Microsoft.Extensions.Configuration.Json

In my ConfigureServices method I added:

```<code>services.AddSingleton<IConfiguration>(Configuration);
</code>```

In my Controller I injected the config:

```<code>IConfiguration iconfig;
public ValuesController(IConfiguration iConfig)
{
    iconfig = iConfig;
}
</code>```

To retrieve it:

```<code>return "value: " + iconfig.GetValue<string>("AppSettings:Domain");
</code>```

I can see the controller constructor being called and passing in a config, but the value is always null.

I did notice that Startup already passes in an IConfiguration. Is it a case of yet another change in implementation and i need to do something different?

[edit]
I've now read
https://joonasw.net/view/aspnet-core-2-configuration-changes

Which says it's all change again and it's auto injected, but after following the code it doesn't actually say how you get your hands on the data in your controller.

答:
You can take a look at my answer here:　https://stackoverflow.com/a/46940811/2410655

Basically you create a class that matches the properties you define in appsettings.json file (In the answer it's the AppSettings class).

And then in ConfigureServices(), you inject that class using services.Configure<>. That class will be available in all Controllers by DI.

To access its data, you can take a look at @aman's original question post from the link above.

```<code>public class HomeController : Controller
{
    private readonly AppSettings _mySettings;

    public HomeController(IOptions<AppSettings> appSettingsAccessor)
    {
        _mySettings = appSettingsAccessor.Value;
    }
}
</code>```

Body:
I have an asp.net core 2 webapi service. I want to read appsettings.json but I cannot figure it out. As usual, when I search the internet I get a dozen completely different answers based on various versions of the framework that ultimately don't seem to work.

As an example appsettings.json:

"AppSettings": {
  "Domain": "http://localhost"
}

Firstly I tried this:

Added via nuget Microsoft.Extensions.Configuration and Microsoft.Extensions.Configuration.Json

In my ConfigureServices method I added:

services.AddSingleton<IConfiguration>(Configuration);

In my Controller I injected the config:

IConfiguration iconfig;
public ValuesController(IConfiguration iConfig)
{
    iconfig = iConfig;
}

To retrieve it:

return "value: " + iconfig.GetValue<string>("AppSettings:Domain");

I can see the controller constructor being called and passing in a config, but the value is always null.

I did notice that Startup already passes in an IConfiguration. Is it a case of yet another change in implementation and i need to do something different?

[edit]
I've now read
https://joonasw.net/view/aspnet-core-2-configuration-changes

Which says it's all change again and it's auto injected, but after following the code it doesn't actually say how you get your hands on the data in your controller.

Body:
You can take a look at my answer here:　https://stackoverflow.com/a/46940811/2410655

Basically you create a class that matches the properties you define in appsettings.json file (In the answer it's the AppSettings class).

And then in ConfigureServices(), you inject that class using services.Configure<>. That class will be available in all Controllers by DI.

To access its data, you can take a look at @aman's original question post from the link above.

public class HomeController : Controller
{
    private readonly AppSettings _mySettings;

    public HomeController(IOptions<AppSettings> appSettingsAccessor)
    {
        _mySettings = appSettingsAccessor.Value;
    }
}


问:
Subversion - Async development cycle... two trunks?
Currently in our enterprise we have a situation that i think it's not very common, or at least i haven't found a similar case in Internet. My problem is that we have software that can evolve by more than one requirement, and both not necessarily will coincide in their release date.

We have a development cycle where all software is developed in a "DEV" environment, and then it's handled to SQA so it can be tested on "LAB" environment; if all works OK then this software is moved to "PROD" environment. The problem i am facing here is that i cant use a single trunk and i don't see how a single branch could work either.

For example, lets say i have requirements A and B, one to be released today and the other a week from today. Both have reached LAB environment but today's release to PROD environment only has to contain A, since B is not yet needed by our business users (and it cannot be released early because it would introduce some error's to others systems). Both requirements where developed in different branches (they respond to different needs). In this case my problem is that i can't have a single trunk where developers can merge to see both changes in "DEV" environment, and then use the same trunk to feed "LAB" environment since it would have source code not yet scheduled for release.

I think i should also mention that having a separate development environment for each branch is not possible because this software is based on PL/SQL (Oracle) and our current test database is about 350Mb in size, so having a different one for each requirement would be quite expensive and hard to manage.

Any suggestion or similar experience would be appreciated.

Regards

答:
In most cases what you need is to test the resultant application with features enabled AND disabled so that you can choose what to enable or disable at release time.

The point is that if you create a testing release that contains both and then go and completely remove one part, regardless of your versionning system, you could end up creating an integration problem, which you wont know about and you'll have already pushed it to the production server.

Regardless of what you do, you still need to test the exact product you will give to the client.

A release should then be what is going to be tested, not what is going to production. What will be going to production is the tested release. At that point it simply a question of creating a branch for each release or feature and merge what is needed.

A merge operation doesn't need to be for everything. If the commits are well done, you should be able to merge just the features (comits and/or files) you need between branches easily. Also to note that SVN only has the ability to keep the history of merged branches since 1.5/

OwnerDisplayName: Patricio Téllez

LastEditorDisplayName: Adam Lassek

OwnerDisplayName: Loki

LastEditorDisplayName: Loki


问:
"Invalid Host header" when running Angular/cli development server c9.io
Current command: ng serve --host --public $IP:$PORT

Results on my website:

Invalid Host header

答:
I was getting this error when trying to access our app using the localtunnel utility.

@tarn 's suggestion (from a comment on the accepted answer) of adding --disableHostCheck true to the ng serve command did the trick.


问:
pg-promise upsert on postgresql 9.4.11
I've searched extensively and I've not been able to solve this simple issue.
I'm programming in nodejs, and using pg-promise to store my JSON file dynamically into a postgres 9.4.11 database (I'm not allowed to upgrade the DB).
My JSON contains about a hundred columns each, and I've parsed it properly into three objects.
1. fields
2. columns
3. tables
Pg-promise works PERFECTLY when I do this:

```<code>//-- connection details would be up here  const db = pgp (conn);--
//Insert statement is below

 for (var i=0; i<Object.keys(fields).length; i++){

    const data = [fields[i]];
    const cs = new pgp.helpers.ColumnSet(columns[i]);
    const table = new pgp.helpers.TableName(tables[i],"public");
    const insert = pgp.helpers.insert(data,cs,table);

       db.none(insert)
        .then(data => {
            console.log("Success! Record inserted for " + table);
        })
        .catch(error => {
            //error
            console.log("ALERT!!! Something went wrong with Record in table " + table);
        });
    }
</code>```

But of course, I'm on postgresql 9.4.11 and I can't use the simple:

```<code>const insert = pgp.helpers.insert(data,cs,table) + " ON CONFLICT (id1, uid2, xid3) DO NOTHING";
</code>```

to perform an insert of ONLY new items because UPSERTS are only available starting at 9.5.

My query performs about 2,000 row inserts per run and I'm comfortable with that.

I'm pretty new at this, and I hope maybe in my hours of googling I overlooked the straight forward solution.

The closest resolution I've seen is a stored procedure, but I'm not sure how I'd implement that.

Please, stackoverflow, you might be my only hope!

I simply want to make sure each row that matches on id1, uid2, and xid3 does not get inserted into my postgres db.

答:
So I learned a couple of things about postgres.  But first, this is the code that finally worked for me:

```<code> for (var i=0; i<Object.keys(fields).length; i++){

    const data = [fields[i]];
    const cs = new pgp.helpers.ColumnSet(columns[i]);
    const table = new pgp.helpers.TableName(tables[i],"public");
    const insert = pgp.helpers.insert(data,cs,table);
         db.none( 'BEGIN WORK; LOCK TABLE public.'
        + tables[i] + ' IN SHARE ROW EXCLUSIVE MODE; '
        + 'INSERT INTO public.'+tables[i]+ ' ('+ columns[i]+')'
        + 'SELECT 'google.com','another value', 'etc...' WHERE NOT EXISTS(SELECT 1 FROM public.'
        +tables[i] +' WHERE id1 ='+fields[i].id1
        +' AND uid2 ='+fields[i].uid2
        +' AND xid3 ='+fields[i].xid3 +');'
        + 'COMMIT WORK;' )
    }
</code>```

So what I learned was that postgres does not see items inside double quotes as values, but as columns.
So I had to take my values array and strip the double quotes and replace with single quotes, which allowed postgres to accept the query.

This use of pg-promise to stitch together a postgres query might seem hacky, but it's the best way I found to work with my data using a for loop to load hundreds of rows that are hundreds of columns wide.

Note, I have a values array, but I wrote them out as 'google.com','another value', 'etc...' just so you'd see the double quotes vs single quotes.

Title: pg-promise upsert on postgresql 9.4.11

Body:
I've searched extensively and I've not been able to solve this simple issue.
I'm programming in nodejs, and using pg-promise to store my JSON file dynamically into a postgres 9.4.11 database (I'm not allowed to upgrade the DB).
My JSON contains about a hundred columns each, and I've parsed it properly into three objects.
1. fields
2. columns
3. tables
Pg-promise works PERFECTLY when I do this:

//-- connection details would be up here  const db = pgp (conn);--
//Insert statement is below

 for (var i=0; i<Object.keys(fields).length; i++){

    const data = [fields[i]];
    const cs = new pgp.helpers.ColumnSet(columns[i]);
    const table = new pgp.helpers.TableName(tables[i],"public");
    const insert = pgp.helpers.insert(data,cs,table);

       db.none(insert)
        .then(data => {
            console.log("Success! Record inserted for " + table);
        })
        .catch(error => {
            //error
            console.log("ALERT!!! Something went wrong with Record in table " + table);
        });
    }

But of course, I'm on postgresql 9.4.11 and I can't use the simple:

const insert = pgp.helpers.insert(data,cs,table) + " ON CONFLICT (id1, uid2, xid3) DO NOTHING";

to perform an insert of ONLY new items because UPSERTS are only available starting at 9.5.

My query performs about 2,000 row inserts per run and I'm comfortable with that.

I'm pretty new at this, and I hope maybe in my hours of googling I overlooked the straight forward solution.

The closest resolution I've seen is a stored procedure, but I'm not sure how I'd implement that.

Please, stackoverflow, you might be my only hope!

I simply want to make sure each row that matches on id1, uid2, and xid3 does not get inserted into my postgres db.

Body:
So I learned a couple of things about postgres.  But first, this is the code that finally worked for me:

 for (var i=0; i<Object.keys(fields).length; i++){

    const data = [fields[i]];
    const cs = new pgp.helpers.ColumnSet(columns[i]);
    const table = new pgp.helpers.TableName(tables[i],"public");
    const insert = pgp.helpers.insert(data,cs,table);
         db.none( 'BEGIN WORK; LOCK TABLE public.'
        + tables[i] + ' IN SHARE ROW EXCLUSIVE MODE; '
        + 'INSERT INTO public.'+tables[i]+ ' ('+ columns[i]+')'
        + 'SELECT 'google.com','another value', 'etc...' WHERE NOT EXISTS(SELECT 1 FROM public.'
        +tables[i] +' WHERE id1 ='+fields[i].id1
        +' AND uid2 ='+fields[i].uid2
        +' AND xid3 ='+fields[i].xid3 +');'
        + 'COMMIT WORK;' )
    }

So what I learned was that postgres does not see items inside double quotes as values, but as columns.
So I had to take my values array and strip the double quotes and replace with single quotes, which allowed postgres to accept the query.

This use of pg-promise to stitch together a postgres query might seem hacky, but it's the best way I found to work with my data using a for loop to load hundreds of rows that are hundreds of columns wide.

Note, I have a values array, but I wrote them out as 'google.com','another value', 'etc...' just so you'd see the double quotes vs single quotes.


问:
ember Error: Compile Error: is not a helper
I got the following error while developing our front-end with Ember.js:

ember Error: Compile Error: '...' is not a helper

What is the meaning of this error?

答:
From the documentation:

Helpers allow you to add additional functionality to your templates beyond what is included out-of-the-box in Ember. Helpers are most useful for transforming raw values from models and components into a format more appropriate for your users.

It looks like you are using a non-defined helper. So please look through (and maybe provide) some more of your log output. You are probably using an undefined helper in one (or multiple) of your .hbs-files.


问:
Angular 4 apply attributes upon declaration to component template (do not render wrapping element)
Let's say I want to make a custom button.
So I create a component

import { Component, Input } from '@angular/core';
@Component({
  selector: '[extended-button]',
  template: `<button (click)="onClick($event)"></button>`,
  styles: []
})
export class ExtendedButtonComponent {
  @Input() disabled: boolean;
}
```

<p>And when I use an instance of this button I want the attibutes I type when declaring it in the HTML to apply to the button inside the template:</p>

<pre class="lang-html prettyprint-override"><code><div extended-button class="some-nice-button"></div>
</code>```

So the results of this would be:

<button class="some-nice-button" (click)="onClick($event)"></button>
```

I really don't want the
 tag to be rendered. Any ideas how to achieve that?

答:
I'm not sure if this is what you want to achieve but i think you should use your selector as a html tag, like this:</p>

```<code><div>
<extended-button></extended-button>
</div>
</code>```

Body:
Let's say I want to make a custom button.
So I create a component

import { Component, Input } from '@angular/core';
@Component({
  selector: '[extended-button]',
  template: `<button (click)="onClick($event)"></button>`,
  styles: []
})
export class ExtendedButtonComponent {
  @Input() disabled: boolean;
}

And when I use an instance of this button I want the attibutes I type when declaring it in the HTML to apply to the button inside the template:

So the results of this would be:

<button class="some-nice-button" (click)="onClick($event)"></button>

I really don't want the
 tag to be rendered. Any ideas how to achieve that?

Body:
I'm not sure if this is what you want to achieve but i think you should use your selector as a html tag, like this:

<div>
<extended-button></extended-button>
</div>


问:
NPM install -> but only add appropriate line to package.json
I have been wondering this for years, but never bothered to ask. There are many cases where I just want to add the appropriate line for the latest version of a package to package.json, without actually touching node_modules.

Say I want to add the latest version of lodash to my project w/o actually installing it to node_modules. Is there an NPM command to do that?

Let me know if there is a better way to phrase the question.

答:
A simple sh function to fetch and format the data might help

```<code>npmvp(){
  npmvp_version=$(npm view $1 version)
  echo " \"$1\": \"$npmvp_version\""
}
</code>```

jq might be another quick shell way

```<code>npmvp(){
  npmvp_name=$1
  npmvp_version=$(npm view $npmvp_name version)
  cat package.json | jq --arg name "$npmvp_name" --arg version "$npmvp_version" \
    '.dependencies[$name] = $version' > package.json.tmp
  #mv package.json.tmp package.json
}
</code>```

Otherwise you could dig into the npm code and make something do the steps up to the actuall installation, rather than implementing something completely new yourself.

Body:
A simple sh function to fetch and format the data might help

npmvp(){
  npmvp_version=$(npm view $1 version)
  echo " \"$1\": \"$npmvp_version\""
}

jq might be another quick shell way

npmvp(){
  npmvp_name=$1
  npmvp_version=$(npm view $npmvp_name version)
  cat package.json | jq --arg name "$npmvp_name" --arg version "$npmvp_version" \
    '.dependencies[$name] = $version' > package.json.tmp
  #mv package.json.tmp package.json
}

Otherwise you could dig into the npm code and make something do the steps up to the actuall installation, rather than implementing something completely new yourself.


问:
How can I get a link to a Facebook or Twitter avatar by username?
How can I get a link to a Facebook or Twitter avatar by username?</p>

答:
For Facebook the image is publically availible and can be seen at: http://graph.facebook.com/username/picture

For example, here is mine: http://graph.facebook.com/totten/picture

You will notice that the url above actually gets forwarded to another caching url. Don't save the long url (http://profile.ak.fbcdn.net/....) save the short http://graph.facebook.com/ one. The other, longer url, could change and break.

If you want to display that url in a web page you just need to do the following:

```

Which gets you: http://graph.facebook.com/totten/picture

Thats it, no complicated API or authentication is needed.

For twitter you need to use the api: http://apiwiki.twitter.com/w/page/22554755/Twitter-REST-API-Method:-users%C2%A0show

Body:
For Facebook the image is publically availible and can be seen at: http://graph.facebook.com/username/picture

For example, here is mine: http://graph.facebook.com/totten/picture

You will notice that the url above actually gets forwarded to another caching url. Don't save the long url (http://profile.ak.fbcdn.net/....) save the short http://graph.facebook.com/ one. The other, longer url, could change and break.

If you want to display that url in a web page you just need to do the following:

<img src="//graph.facebook.com/totten/picture" />

Which gets you: http://graph.facebook.com/totten/picture

Thats it, no complicated API or authentication is needed.

For twitter you need to use the api: http://apiwiki.twitter.com/w/page/22554755/Twitter-REST-API-Method:-users%C2%A0show


问:
There is an error in XML document (1, 1)
I have been trying to read data from XML. When I try to deserialize it, I get the following error:

"There is an error in XML document (1, 1)."

For your reference, I am attaching my entire code as well as my xml file.

C# Code:

```<code>CarCollection cars = null;
string path = @"C:\Users\harsha\Desktop\Doc.xml";
XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
var reader = XmlReader.Create(path);
cars = (CarCollection)serializer.Deserialize(reader);
reader.Close();
</code>```

Also,the data structure is as follows:

```<code>namespace XMLDataReader
{
   [Serializable()]
   public class Car
   {
       [System.Xml.Serialization.XmlElement("StockNumber")]
       public string StockNumber { get; set; }

       [System.Xml.Serialization.XmlElement("Make")]
       public string Make { get; set; }

       [System.Xml.Serialization.XmlElement("Model")]
       public string Model { get; set; }
   }

   [Serializable()]
   [System.Xml.Serialization.XmlRoot("CarCollection")]
   public class CarCollection
   {
       [XmlArray("Cars")]
       [XmlArrayItem("Car", typeof(Car))]
       public Car[] Car { get; set; }
   }
</code>```

XML File:

```<code>   <CarCollection>
<Cars>
  <Car>
    <StockNumber>1020</StockNumber>
    <Make>Nissan</Make>
    <Model>Sentra</Model>
  </Car>
  <Car>
    <StockNumber>1010</StockNumber>
    <Make>Toyota</Make>
    <Model>Corolla</Model>
  </Car>
  <Car>
    <StockNumber>1111</StockNumber>
    <Make>Honda</Make>
    <Model>Accord</Model>
  </Car>
</Cars>
</CarCollection>
</code>```

Waiting for some help. Thanks in advance!

答:
Can you open it with notepad and verify the content is what you expect?  You will see that error if:

there is nothing in the document

the xml in the file is not valid or well-formed

the schema of the xml is different than what is specified

It could also be because you don't have the Xml Declaration header defined (depending on the version of xml spec you're using):

For example:

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

See Does a valid XML file require an XML declaration?

Body:
I have been trying to read data from XML. When I try to deserialize it, I get the following error:

"There is an error in XML document (1, 1)."

For your reference, I am attaching my entire code as well as my xml file.

C# Code:

CarCollection cars = null;
string path = @"C:\Users\harsha\Desktop\Doc.xml";
XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
var reader = XmlReader.Create(path);
cars = (CarCollection)serializer.Deserialize(reader);
reader.Close();

Also,the data structure is as follows:

namespace XMLDataReader
{
   [Serializable()]
   public class Car
   {
       [System.Xml.Serialization.XmlElement("StockNumber")]
       public string StockNumber { get; set; }

       [System.Xml.Serialization.XmlElement("Make")]
       public string Make { get; set; }

       [System.Xml.Serialization.XmlElement("Model")]
       public string Model { get; set; }
   }

   [Serializable()]
   [System.Xml.Serialization.XmlRoot("CarCollection")]
   public class CarCollection
   {
       [XmlArray("Cars")]
       [XmlArrayItem("Car", typeof(Car))]
       public Car[] Car { get; set; }
   }

XML File:

   <CarCollection>
<Cars>
  <Car>
    <StockNumber>1020</StockNumber>
    <Make>Nissan</Make>
    <Model>Sentra</Model>
  </Car>
  <Car>
    <StockNumber>1010</StockNumber>
    <Make>Toyota</Make>
    <Model>Corolla</Model>
  </Car>
  <Car>
    <StockNumber>1111</StockNumber>
    <Make>Honda</Make>
    <Model>Accord</Model>
  </Car>
</Cars>
</CarCollection>

Waiting for some help. Thanks in advance!

Body:
Can you open it with notepad and verify the content is what you expect?  You will see that error if:

there is nothing in the document

the xml in the file is not valid or well-formed

the schema of the xml is different than what is specified

It could also be because you don't have the Xml Declaration header defined (depending on the version of xml spec you're using):

For example:

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

See Does a valid XML file require an XML declaration?


问:
Clear screen in shell
Just a quick question:

How do you clear the screen in shell?
I've seen ways like:

```<code>import os
os.system('cls')
</code>```

This just opens the windows cmd, clears the screen and closes but
I want the shell window to be cleared

(PS: I don't know this helps, but I'm using version 3.3.2 of Python)

Thank you :)

答:
In addition to being an all-around great CLI library, click also provides a platform-agnostic clear() function:

import click
click.clear()
```

Title: Clear screen in shell

Body:
Just a quick question:

How do you clear the screen in shell?
I've seen ways like:

import os
os.system('cls')

This just opens the windows cmd, clears the screen and closes but
I want the shell window to be cleared

(PS: I don't know this helps, but I'm using version 3.3.2 of Python)

Thank you :)


问:
Recursive string reversal function in javascript?
I'm a pretty experienced frontend engineer with a weak CS background. I'm trying to get my head around the concept of recursion. Most of the examples and purported explanations I can find just aren't explaining it in a way I find easy to understand.

I set myself a task of writing a function that will reverse a string recursively. I know there has to be a base condition (i.e. the solution is found), but I can't figure out how to actually write something like this and could use a demo to study.

Could someone provide a sample function?

答:
A 25% faster function: jsperf.com

function Reverse(str) {
  if (str === null) {
    return null;
  }
  if (str.length <= 1) {
    return str;
  }
  var first = str[0];
  var last = str[str.length - 1];
  var str1 = Reverse(str.substring(1, str.length - 1));
  return last + str1 + first;
}

var result = Reverse("a really serious string of nothingness making call stack to explode");```


问:
awk to convert unix time without strftime or date command(-d & -r option isn't supported in AIX)
I have current output as

```<code>file | awk '$1=="IMAGE" {print $2","$7","$14","$17","$19/1000}'

ABC,POL1,1510009167,1510009677,20.5
DEF,POL2,1510009667,1510009887,20.5
XYZ,POL3,1510007867,1510009887,20.5
PQR,POL4,1510009267,1510009997,20.5
</code>```

Expected output should have these unix time converted into human readable format, I can't use strftime or date -d option as they are not supported in AIX.
I do have a user defined command which i can use to convert but i can't use it in awk.I tried creating function and then use it in awk which didn't help

With Ed's Code I am getting this output as the user defined command gives output like this, However I want it to give me only day/Mon/Year. I can use awk to print this in user command, But i do i use it in this function?

```<code>ABC POL1 1510009167 = Mon Nov  6 17:59:27 EST 2017 1510009677 = Tue Nov  7 04:37:57 IST 2017 20.5
DEF POL2 1510009667 = Mon Nov  6 18:07:47 EST 2017 1510009887 = Tue Nov  7 04:41:27 IST 2017 20.5
XYZ POL3 1510007867 = Mon Nov  6 17:37:47 EST 2017 1510009887 = Tue Nov  7 04:41:27 IST 2017 20.5
PQR POL4 1510009267 = Mon Nov  6 18:01:07 EST 2017 1510009997 = Tue Nov  7 04:43:17 IST 2017 20.5
</code>```

答:
Assuming your user defined command that you mention is in an executable named "command" that's in your PATH which you today call as:

```<code>command -ctime $14 | awk '{print $4"/"$5"/"$6"/"}
</code>```

to get the format you want (per your comments) then all you need is to write an awk function to call it:

```<code>awk '
function secs2time(secs,     cmd, line, flds, time) {
    cmd = "command -ctime \"" secs "\""
    if ( (cmd | getline line) > 0  ) {
        split(line,flds," ")
        time = flds[4] "/" flds[5] "/" flds[6] "/"
    }
    else {
        time = "error:" secs
    }
    close(cmd)
    return time
}
BEGIN { FS=OFS="," }
$1=="IMAGE" {print $2, $7, secs2time($14), secs2time($17), $19/1000}
'
</code>```

Body:
I have current output as

file | awk '$1=="IMAGE" {print $2","$7","$14","$17","$19/1000}'

ABC,POL1,1510009167,1510009677,20.5
DEF,POL2,1510009667,1510009887,20.5
XYZ,POL3,1510007867,1510009887,20.5
PQR,POL4,1510009267,1510009997,20.5

Expected output should have these unix time converted into human readable format, I can't use strftime or date -d option as they are not supported in AIX.
I do have a user defined command which i can use to convert but i can't use it in awk.I tried creating function and then use it in awk which didn't help

With Ed's Code I am getting this output as the user defined command gives output like this, However I want it to give me only day/Mon/Year. I can use awk to print this in user command, But i do i use it in this function?

ABC POL1 1510009167 = Mon Nov  6 17:59:27 EST 2017 1510009677 = Tue Nov  7 04:37:57 IST 2017 20.5
DEF POL2 1510009667 = Mon Nov  6 18:07:47 EST 2017 1510009887 = Tue Nov  7 04:41:27 IST 2017 20.5
XYZ POL3 1510007867 = Mon Nov  6 17:37:47 EST 2017 1510009887 = Tue Nov  7 04:41:27 IST 2017 20.5
PQR POL4 1510009267 = Mon Nov  6 18:01:07 EST 2017 1510009997 = Tue Nov  7 04:43:17 IST 2017 20.5

Body:
Assuming your user defined command that you mention is in an executable named "command" that's in your PATH which you today call as:

command -ctime $14 | awk '{print $4"/"$5"/"$6"/"}

to get the format you want (per your comments) then all you need is to write an awk function to call it:

awk '
function secs2time(secs,     cmd, line, flds, time) {
    cmd = "command -ctime \"" secs "\""
    if ( (cmd | getline line) > 0  ) {
        split(line,flds," ")
        time = flds[4] "/" flds[5] "/" flds[6] "/"
    }
    else {
        time = "error:" secs
    }
    close(cmd)
    return time
}
BEGIN { FS=OFS="," }
$1=="IMAGE" {print $2, $7, secs2time($14), secs2time($17), $19/1000}
'


问:
When writing a test for Flutter, what happens when similar aspects appear more than one time? How to filter for the right one?
I'm writing unit and integration tests for Flutter. If many widgets, with similar aspects (e.g. text), appear more than one time, how to filter for the right one?</p>

答:
There are several options:

Finder.first finds the first occurrence of the widget

Finder.last finds the last occurrence of the widget

Finder.hitTestable finds only the widgets that can be reached by a hit test (e.g. by a tap)

Finder.skipOffstage finds only widgets considered to be "on-stage" (see Offstage widget)

find.descendant finds only widgets that are descendants of another widget

Finally you can use find.byPredicate or even extend the Finder class and get much more flexibility.


问:
How to access app Module Classes from Library Classes in Android?
I created two modules in single android project.

app module(which is default my app module)

and another added library module.

Now app module have many java classes.  i want to access .Java class of app module in library module.

Module app has a class DatabaseHelper in package xyz

Now I want to import class DatabaseHelper in Library module.

DatabaseHelper is not recognized by android.

Questions,

Is it possible to import Class from a app module to another module?

any other way.

MyFiles

build.gradle(app)

```<code>compile project(':materialList')
</code>```

setting.gradle

```<code>include ':app', ':Library'
</code>```

答:
Is it possible to import Class from a app module to another module?

This won't be possible as this will be creating a circular dependency.

However there is a pattern that can be utilized in this scenario:

Define the data type : DatabaseHelperContent in the library module

Define an interface DatabaseHelperI in the library module the implementer of which is supposed to provide the data.

Create a DatabaseHelperImpl class implementing the DatabaseHelperI interface, providing the data (this class is in the app module)

Initialize the interface as the instance of class ABC while referring to it in the Application class, so that the data from the class can be dynamically passed to the sub-module.

This would become even simpler with some dependency-injection framework
  like Dagger where you can just specify provider of the interface in
  the @Module class and use the injected data from the common provider everywhere.

Body:
I created two modules in single android project.

app module(which is default my app module)

and another added library module.

Now app module have many java classes.  i want to access .Java class of app module in library module.

Module app has a class DatabaseHelper in package xyz

Now I want to import class DatabaseHelper in Library module.

DatabaseHelper is not recognized by android.

Questions,

Is it possible to import Class from a app module to another module?

any other way.

MyFiles

build.gradle(app)

compile project(':materialList')

setting.gradle

include ':app', ':Library'


问:
How to get sorted paged map by couple conditions using java 8 streams
I have some model object Account with list of fields, in simple case with two fields String name and double margin

And I need to get exact page of this accounts which is over some margin limit, sorted by margin & name. Each record should have margin as key, and Account as value.

I made this minimal example of code, but seems like sorting doesn't works well for me. So I wrap it in TreeMap, but it will cost extra memory and I hate it.
Probably should be wait to fix this inside of streams and add losted sort by name in case of equals margin

```<code>@Data
class Account {
    private final String name;
    private final double margin;

    private final static double MARGIN_LIMIT = 100;
    private final static int PAGE_SIZE = 3;

    private static Set<Account> accounts = new HashSet<>();

    public static void main(String[] args) {
        accounts.add(new Account("user1", 200));
        accounts.add(new Account("user2", 100));
        accounts.add(new Account("user3", 150));
        accounts.add(new Account("user4", 175));
        accounts.add(new Account("user5", 75));
        accounts.add(new Account("user6", 110));

        Map<Double,Account> val = new TreeMap<Double,Account>(Comparator.reverseOrder());
        val.putAll(getClientsForClosing(2));
        System.out.println(val);
    }

    private static Map<Double, Account> getClientsForClosing(int page) {
        return accounts.stream()
                .filter(account -> account.getMargin() >= MARGIN_LIMIT)
                .sorted(Comparator.comparingDouble(Account::getMargin).reversed())
                .skip(PAGE_SIZE * (page - 1))
                .limit(PAGE_SIZE)
                .collect(Collectors.toMap(Account::getMargin, o -> o));
    }
}
</code>```

答:
Your question and solution somehow are contradictory, on one hand you show code that sorts your entries by margin - which is a double; in this case there is a simpler way:

```<code>accounts.stream()
        .filter(account -> account.getMargin() >= MARGIN_LIMIT)
        .skip(PAGE_SIZE * (page - 1))
        .limit(PAGE_SIZE)
        .collect(Collectors.groupingBy(
               Account::getMargin,
               () -> new TreeMap<Double, List<Account>>(Comparator.reverseOrder()),
               Collectors.toList()));
</code>```

If you want to sort by both margin and name and still keep the definition as Map<Double, List<Account>>, you will have to stick with a LinkedHashMap:

```<code>accounts.stream()
        .filter(account -> account.getMargin() >= MARGIN_LIMIT)
        .sorted(Comparator.comparingDouble(Account::getMargin)
                          .reversed()
                          .thenComparing(Comparator.comparing(Account::getName)))
        .skip(PAGE_SIZE * (page - 1))
        .limit(PAGE_SIZE)
        .collect(Collectors.toMap(
              Account::getMargin,
              x -> {
                 List<Account> list = new ArrayList<>();
                 list.add(x);
                 return list;
              },
              (left, right) -> {
                  left.addAll(right);
                  return left;
              },
              LinkedHashMap::new));
</code>```

Body:
I have some model object Account with list of fields, in simple case with two fields String name and double margin

And I need to get exact page of this accounts which is over some margin limit, sorted by margin & name. Each record should have margin as key, and Account as value.

I made this minimal example of code, but seems like sorting doesn't works well for me. So I wrap it in TreeMap, but it will cost extra memory and I hate it.
Probably should be wait to fix this inside of streams and add losted sort by name in case of equals margin

@Data
class Account {
    private final String name;
    private final double margin;

    private final static double MARGIN_LIMIT = 100;
    private final static int PAGE_SIZE = 3;

    private static Set<Account> accounts = new HashSet<>();

    public static void main(String[] args) {
        accounts.add(new Account("user1", 200));
        accounts.add(new Account("user2", 100));
        accounts.add(new Account("user3", 150));
        accounts.add(new Account("user4", 175));
        accounts.add(new Account("user5", 75));
        accounts.add(new Account("user6", 110));

        Map<Double,Account> val = new TreeMap<Double,Account>(Comparator.reverseOrder());
        val.putAll(getClientsForClosing(2));
        System.out.println(val);
    }

    private static Map<Double, Account> getClientsForClosing(int page) {
        return accounts.stream()
                .filter(account -> account.getMargin() >= MARGIN_LIMIT)
                .sorted(Comparator.comparingDouble(Account::getMargin).reversed())
                .skip(PAGE_SIZE * (page - 1))
                .limit(PAGE_SIZE)
                .collect(Collectors.toMap(Account::getMargin, o -> o));
    }
}

Body:
Your question and solution somehow are contradictory, on one hand you show code that sorts your entries by margin - which is a double; in this case there is a simpler way:

accounts.stream()
        .filter(account -> account.getMargin() >= MARGIN_LIMIT)
        .skip(PAGE_SIZE * (page - 1))
        .limit(PAGE_SIZE)
        .collect(Collectors.groupingBy(
               Account::getMargin,
               () -> new TreeMap<Double, List<Account>>(Comparator.reverseOrder()),
               Collectors.toList()));

If you want to sort by both margin and name and still keep the definition as Map<Double, List<Account>>, you will have to stick with a LinkedHashMap:

accounts.stream()
        .filter(account -> account.getMargin() >= MARGIN_LIMIT)
        .sorted(Comparator.comparingDouble(Account::getMargin)
                          .reversed()
                          .thenComparing(Comparator.comparing(Account::getName)))
        .skip(PAGE_SIZE * (page - 1))
        .limit(PAGE_SIZE)
        .collect(Collectors.toMap(
              Account::getMargin,
              x -> {
                 List<Account> list = new ArrayList<>();
                 list.add(x);
                 return list;
              },
              (left, right) -> {
                  left.addAll(right);
                  return left;
              },
              LinkedHashMap::new));


问:
How to properly upgrade node using nvm
Is it possible to upgrade node right in place, instead of manually installing the latest stable version?

I have installed node.js version 5.0 with nvm, but now I want to update it to 5.4. I'm trying to avoid having to manually reinstall all of my global packages (e.g. by running npm install -g grunt-cli bower yo yoman-angular-generator blabla blablablabla...).

答:
⚡ TWO Simple Solutions:

To install the latest version of node and reinstall the old version packages just run the following command.

```<code>nvm install node --reinstall-packages-from=node
</code>```

To install the latest lts (long term support) version of node and reinstall the old version packages just run the following command.

```<code>nvm install --lts /* --reinstall-packages-from=node
</code>```

Here's a GIF animation to support this answer:

Title: How to properly upgrade node using nvm

Body:
⚡ TWO Simple Solutions:

To install the latest version of node and reinstall the old version packages just run the following command.

nvm install node --reinstall-packages-from=node

To install the latest lts (long term support) version of node and reinstall the old version packages just run the following command.

nvm install --lts /* --reinstall-packages-from=node

Here's a GIF animation to support this answer:


问:
How to tag services in Symfony 3.3 and construct a mini container from it?
I am writing a component in which multiple services have to be injected. However only a few services are required to process a request. As the services are heavy to instantiate. I would like them to be lazy instantiated.
Is it some how possible to build a mini container using only the services that have the appropriate tags?

Right now I simply inject the entire service container but from what I understand this should not be done.

答:
Starting in Symfony 3.3, if you enable autoconfigure, then some tags are automatically applied for you like twig.extension.

Enable autoconfigure does not work for all tags. Many tags have required attributes, like event listeners, where you also need to specify the event name and method in your tag. Autoconfigure works only for tags without any required tag attributes


问:
Splitting a form(tastic) into a three-column layout
I'm quite new to Rails, so please excuse any wildly inaccurate terminology. First, some context: I'm building a sample tracking web app for a small analytical lab. It would be particularly slick to be able to split up a batch submission form into three columns. A batch is associated with several tests in column 1, batch information is entered into column 2, and individual samples are named in column 3. Ideally, there'd be a nice big submit button at the bottom of column 3 that pushes the whole mess through.

I am using 960 (12 column) for CSS and formtastic for form generation. My first inclination is to set up the columns by way of three divs and to split the form discretely into each div, however, I'm unsure how to split up a form into divs while maintaining what I'll hackishly call a persistence of data across all columns. Should I even be using divs? Here's some code show my general gist:

```<code>
.grid_4
  # Test associating stuff

.grid_4
  = semantic_form_for @batch do |f|
    = f.inputs :name => "Batch Info" do
      = f.input :sampling_date, :required => false
      = f.input :experiment_name, :required => false
      = f.input :notes, :as => :text

.grid_4
  # The page obviously breaks without this line, but it makes the form only
  # pertain to the inputs in this column.
  = semantic_form_for @batch do |f|
    # The sample and test association stuff will be nested forms
    = f.semantic_fields_for :samples do |sample_form|
      = sample_form.input :sample_name
    = f.buttons do
      = f.commit_button :label => "Submit batch"
</code>```

Thanks in advance for any help!

答:
Turns out I was in some crazy haze when I posted this question and didn't think to grid inside of the formtastic helper. For example:

```<code>
= semantic_form_for @something do |f|
  .grid_4
    # Part 1 of form
  .grid_4
    # Part 2 of form
  .grid_4
    # Part 3 of form
</code>```

Which gives me a nicely split up big nested form.

Body:
I'm quite new to Rails, so please excuse any wildly inaccurate terminology. First, some context: I'm building a sample tracking web app for a small analytical lab. It would be particularly slick to be able to split up a batch submission form into three columns. A batch is associated with several tests in column 1, batch information is entered into column 2, and individual samples are named in column 3. Ideally, there'd be a nice big submit button at the bottom of column 3 that pushes the whole mess through.

I am using 960 (12 column) for CSS and formtastic for form generation. My first inclination is to set up the columns by way of three divs and to split the form discretely into each div, however, I'm unsure how to split up a form into divs while maintaining what I'll hackishly call a persistence of data across all columns. Should I even be using divs? Here's some code show my general gist:

.grid_4
  # Test associating stuff

.grid_4
  = semantic_form_for @batch do |f|
    = f.inputs :name => "Batch Info" do
      = f.input :sampling_date, :required => false
      = f.input :experiment_name, :required => false
      = f.input :notes, :as => :text

.grid_4
  # The page obviously breaks without this line, but it makes the form only
  # pertain to the inputs in this column.
  = semantic_form_for @batch do |f|
    # The sample and test association stuff will be nested forms
    = f.semantic_fields_for :samples do |sample_form|
      = sample_form.input :sample_name
    = f.buttons do
      = f.commit_button :label => "Submit batch"

Thanks in advance for any help!

Body:
Turns out I was in some crazy haze when I posted this question and didn't think to grid inside of the formtastic helper. For example:

= semantic_form_for @something do |f|
  .grid_4
    # Part 1 of form
  .grid_4
    # Part 2 of form
  .grid_4
    # Part 3 of form

Which gives me a nicely split up big nested form.


问:
Get detailed error message when BGSAVE fails
Context

We have a backup script which backs up several redis-server instances.

We chose the following way to backup a redis-server instance :

start a BGSAVE

regularly poll INFO Persistence (and rdb_bgsave_in_progress) to see if BGSAVE has completed

check rdb_last_bgsave_status to see if all has gone well

Yesterday, something went wrong (the disk was full).

This error was adequately reported in redis logs, so with a human intervention, we were able to quickly find the cause.

Looking at the redis api however, I only see the generic  :

```<code># Persitence
...
rdb_last_bgsave_status:err
</code>```

line which indicates a generic kind of error, and I do not see how the automated script can report a more detailed error.

Question

When a BGSAVE has gone wrong, is there a way to access some kind of error code or error description through the redis api ?

答: Nope - if the error is detailed, it will be in the logs. The Redis API doesn't feature an error log, although that could be a nice to have feature.</p>

Body:
Context

We have a backup script which backs up several redis-server instances.

We chose the following way to backup a redis-server instance :

start a BGSAVE

regularly poll INFO Persistence (and rdb_bgsave_in_progress) to see if BGSAVE has completed

check rdb_last_bgsave_status to see if all has gone well

Yesterday, something went wrong (the disk was full).

This error was adequately reported in redis logs, so with a human intervention, we were able to quickly find the cause.

Looking at the redis api however, I only see the generic  :

# Persitence
...
rdb_last_bgsave_status:err

line which indicates a generic kind of error, and I do not see how the automated script can report a more detailed error.

Question

When a BGSAVE has gone wrong, is there a way to access some kind of error code or error description through the redis api ?


问:
Android KeyStore get raw bytes/string of stored key
I can generate a key to be stored in the Android Keystore like so:

```<code>private static final String AndroidKeyStore = "AndroidKeyStore";
private static final String AES_MODE = "AES/GCM/NoPadding";
keyStore = KeyStore.getInstance(AndroidKeyStore);
keyStore.load(null);

if (!keyStore.containsAlias(KEY_ALIAS)) {
    KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, AndroidKeyStore);
    keyGenerator.init(
            new KeyGenParameterSpec.Builder(KEY_ALIAS,
                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(KeyProperties.BLOCK_MODE_GCM)                   .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                    .setRandomizedEncryptionRequired(false)
                    .build());
    keyGenerator.generateKey();
}
</code>```

Similarly, I can retrieve it like so:

```<code>keyStore.getKey(KEY_ALIAS, null);
</code>```

I know that the getKey() function returns a Key object, but I haven't found a way to reveal the key itself. It does not seem to have a toString() or getBytes() or something like that.

How can I get the bytes of the key, or at least print out the string version of it? Is it even possible?

答:
The Key object returned has methods:

```<code>getAlgorithm()
getEncoded()
getFormat()
</code>```

They return String, byte[], and String, respectively.

Click here for more info.

Body:
I can generate a key to be stored in the Android Keystore like so:

private static final String AndroidKeyStore = "AndroidKeyStore";
private static final String AES_MODE = "AES/GCM/NoPadding";
keyStore = KeyStore.getInstance(AndroidKeyStore);
keyStore.load(null);

if (!keyStore.containsAlias(KEY_ALIAS)) {
    KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, AndroidKeyStore);
    keyGenerator.init(
            new KeyGenParameterSpec.Builder(KEY_ALIAS,
                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(KeyProperties.BLOCK_MODE_GCM)                   .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                    .setRandomizedEncryptionRequired(false)
                    .build());
    keyGenerator.generateKey();
}

Similarly, I can retrieve it like so:

keyStore.getKey(KEY_ALIAS, null);

I know that the getKey() function returns a Key object, but I haven't found a way to reveal the key itself. It does not seem to have a toString() or getBytes() or something like that.

How can I get the bytes of the key, or at least print out the string version of it? Is it even possible?

Body:
The Key object returned has methods:

getAlgorithm()
getEncoded()
getFormat()

They return String, byte[], and String, respectively.

Click here for more info.


问:
Convert a 64 bits floating point number into two integer numbers < 2^32 and back in Lua 5.1
I want to convert a number (64 bit double precision) into two integer numbers (unsigned 32 bits) and back. Is that possible to do without precision loss? The 64 bit number should fit into two 32 bit numbers, I just can't figure out how to do it in Lua.

My experiments with the bitop library in LuaJIT did not result in anything useful. Is it possible to cast the number to unsigned long long and split that one up, in pure Lua code using the ffi API?

Maybe it's not possible without precision loss. What is a reasonable way to do it, even if I lose precision?

答:
Using LuaJIT:</p>

```<code>local ffi = require"ffi"
local u = ffi.new"union{uint32_t i[2]; double d;}"
-- convert double into pair of int32
u.d = 1/3
print(("%x %x"):format(u.i[0], u.i[1]))  --> 55555555 3fd55555
</code>```

Body:
Using LuaJIT:

local ffi = require"ffi"
local u = ffi.new"union{uint32_t i[2]; double d;}"
-- convert double into pair of int32
u.d = 1/3
print(("%x %x"):format(u.i[0], u.i[1]))  --> 55555555 3fd55555


问:
how to create postgreSQL database using EF code first
I have two classes Class1 and Class2

```<code>[Table("CLASS1", Schema = "public")]
    public class Class1
    {
        public int Class1Id { get; set; }
        public string Name1 { get; set; }
    }

[Table("CLASS2", Schema = "public")]
    public class Class2
    {
        public int Class2Id { get; set; }
        public string Name2 { get; set; }

        public int Class1Id { get; set; }
        public virtual Class1 c1 { get; set; }
</code>```

I defined the DatabaseContext :

```<code>public sealed class     DatabaseContext : DbContext
    {
        private static readonly DatabaseContext instance = new DatabaseContext();

        public static DatabaseContext Instance
        {
            get
            {
                return instance;
            }
        }

        private DatabaseContext()
            : base("maconnexion")
        {
            Database.SetInitializer<DatabaseContext>(null);

        }

        public DbSet<Class1> table1{ get; set; }
        public DbSet<Class2> table2{ get; set; }

    }
</code>```

and i have added those lines to my App.config

```<code><DbProviderFactories>
      <add name="Npgsql Data Provider" invariant="Npgsql" description="Data Provider for PostgreSQL" type="Npgsql.NpgsqlFactory, Npgsql" />
    </DbProviderFactories>

 <connectionStrings>
    <add name="maconnexion"
 connectionString="Server=127.0.0.1;Port=5432;Database=DB_Ticketing;UserId=postgres;Password=slots2013;" providerName="Npgsql" />
  </connectionStrings>
</code>```

and I have created a database in PostgreSQL with the name DB_Ticketing. But when I execute my code the tables table1 and table2 are not added to my data base.

答:
I know has been a long time, but for the people still gets in this post.
this is the most simple info to do it.
basic, how to configure. Entity Framework 6 with PostgreSQL: http://lvasquez.github.io/2014-11-24/EntityFramework-PostgreSql/

how to init code-first. very graphic. Entity Framework Code First For PostgreSQL: https://dotblogs.com.tw/wuanunet/2016/02/26/entity-framework-code-first-postgresql

Optional. Avoid pluralize:
How turn off pluralize table creation for Entity Framework 5?

Note: if you decide not to use code-first, remember PostgreSQL by default sets lowercase, so define if decorate with lower case or create tables case sensitive (create table public."XyZa")

Body:
I have two classes Class1 and Class2

[Table("CLASS1", Schema = "public")]
    public class Class1
    {
        public int Class1Id { get; set; }
        public string Name1 { get; set; }
    }

[Table("CLASS2", Schema = "public")]
    public class Class2
    {
        public int Class2Id { get; set; }
        public string Name2 { get; set; }

        public int Class1Id { get; set; }
        public virtual Class1 c1 { get; set; }

I defined the DatabaseContext :

public sealed class     DatabaseContext : DbContext
    {
        private static readonly DatabaseContext instance = new DatabaseContext();

        public static DatabaseContext Instance
        {
            get
            {
                return instance;
            }
        }

        private DatabaseContext()
            : base("maconnexion")
        {
            Database.SetInitializer<DatabaseContext>(null);

        }

        public DbSet<Class1> table1{ get; set; }
        public DbSet<Class2> table2{ get; set; }

    }

and i have added those lines to my App.config

<DbProviderFactories>
      <add name="Npgsql Data Provider" invariant="Npgsql" description="Data Provider for PostgreSQL" type="Npgsql.NpgsqlFactory, Npgsql" />
    </DbProviderFactories>

 <connectionStrings>
    <add name="maconnexion"
 connectionString="Server=127.0.0.1;Port=5432;Database=DB_Ticketing;UserId=postgres;Password=slots2013;" providerName="Npgsql" />
  </connectionStrings>

and I have created a database in PostgreSQL with the name DB_Ticketing. But when I execute my code the tables table1 and table2 are not added to my data base.


问:
Check all numbers are equal
What is the best way to check that all numbers in the array (or list) are equal?

I think the solution as a loop that seek for the first unequal element ist maybe efficient, but not so elegant or readable. Any solutions in one line?

答:
Some sort of C pseudocode</p>

```<code>i = len(list) - 1;
while (list[i] == list[i+1] && i) i--;
return i == 0;
</code>```

Title: Check all numbers are equal

Body:
Some sort of C pseudocode

i = len(list) - 1;
while (list[i] == list[i+1] && i) i--;
return i == 0;


答:
If it succeeds on one node and not another while the query will work with 1 less 'in' clause I would guess this is a memory pressure issue.  To eliminate the 'query parsing problem' you can re-write your query as:

SELECT * FROM myTable WHERE id = 'x' AND ts >= '2017-10-15' AND ts <= '2017-11-07';

The in clause is only truly useful if you start bucketing your data.  This is a good approach if you have hotspots or if you see 1 node with much higher load than the others.

To bucket your data you would want to do something like:

CREATE TABLE table (
  id text,
  ts text,
  score decimal,
  type text,
  values text,
  PRIMARY KEY ((id, ts), type)
) WITH CLUSTERING ORDER BY (type DESC)

Your data would now be partitioned by id AND day.  Your query would then become what you have now:

SELECT * FROM myTable WHERE id='x' AND ts in ('2017-01-01')

This will better distribute data on the HDDs and allow better parallelization from cassandra.  This WILL NOT fix the memory pressure issue.  To fix that you would want to move the aggregation of data from the coordinator to your application layer.

This means running N SELECT ... WHERE id='x' and ts = '2017-01-01'; queries.

Title: Cassandra read timeout because of some response size limit reached?

Body:
I encountered a strange behavior on cassandra 3.0:

I have the following table:

CREATE TABLE table (
  id text,
  ts text,
  score decimal,
  type text,
  values text,
  PRIMARY KEY (id, ts)
) WITH CLUSTERING ORDER BY (ts DESC)

and the following query (which returns instantly):

SELECT * FROM keyspace.table WHERE id='someId' AND ts IN ('2017-10-15','2017-10-16','2017-10-17','2017-10-18','2017-10-19','2017-10-20','2017-10-21','2017-10-22','2017-10-23','2017-10-24','2017-10-25','2017-10-26','2017-10-27','2017-10-28','2017-10-29','2017-10-30','2017-10-31','2017-11-01','2017-11-02','2017-11-03','2017-11-04','2017-11-05','2017-11-06');

If I add another day in the IN clause, the response never comes (even after 10 minutes!!!):

SELECT * FROM keyspace.table WHERE id='someId' AND ts IN ('2017-10-15','2017-10-16','2017-10-17','2017-10-18','2017-10-19','2017-10-20','2017-10-21','2017-10-22','2017-10-23','2017-10-24','2017-10-25','2017-10-26','2017-10-27','2017-10-28','2017-10-29','2017-10-30','2017-10-31','2017-11-01','2017-11-02','2017-11-03','2017-11-04','2017-11-05','2017-11-06', '2017-11-07');

The 'values' column may have large json data. There is some flag in cassandra.yaml with some size threshold or something like this? I guess adding another day in the query reaches some limit somewhere...in cassandra system.log I didn't see anything relevant to this.


问:
EmberJS - user signin - what's the best way to approach?
I have a layout for user to signin, with the usual "user firstname", "lastname", "email" and a few more fields.
I'm using "component" to show this content to the user.
I also need to validate this data locally.

Now I need to tie the UI to the data.
I have two options:
1. Use model
2. Use member variables in component

And when everything is okay, when user clicks on the "register" button,
I need to send this data to the back-end.

What do you suggest is the best way to do this?

答:
I would probably take a look at the ember-simple-auth project:

Ember Simple Auth is a lightweight library for implementing authentication/ authorization with Ember.js applications. It has minimal requirements with respect to application structure, routes etc. With its pluggable strategies it can support all kinds of authentication and authorization mechanisms.


问:
Why EPSILON is used in comparing two floating point numbers
I'm googling about how to find if a number y is power of x and came across this link

Java

```<code>public class Solution {
public boolean isPowerOfThree(int n) {
    return (Math.log10(n) / Math.log10(3)) % 1 == 0;
} }
</code>```

Common pitfalls

This solution is problematic because we start using doubles, which
  means we are subject to precision errors. This means, we should never
  use == when comparing doubles. That is because the result of
  Math.log10(n) / Math.log10(3) could be 5.0000001 or 4.9999999. This
  effect can be observed by using the function Math.log() instead of
  Math.log10().

In order to fix that, we need to compare the result against an
  epsilon.

Java

return (Math.log(n) / Math.log(3) + epsilon) % 1 <= 2 * epsilon;

There I didn't understand return (Math.log(n) / Math.log(3) + epsilon) % 1 <= 2 * epsilon;

What is the meaning of that line?

Why EPSILON is used while comparing floating points?

答:
Because natural logarithm calculates using simple series. https://en.wikipedia.org/wiki/Natural_logarithm
Such series may be implemented in math-coprocessor in CPU. You may express any logarithm from natural using simple proportion without big computation time.</p>

Body:
I'm googling about how to find if a number y is power of x and came across this link

Java

public class Solution {
public boolean isPowerOfThree(int n) {
    return (Math.log10(n) / Math.log10(3)) % 1 == 0;
} }

Common pitfalls

This solution is problematic because we start using doubles, which
  means we are subject to precision errors. This means, we should never
  use == when comparing doubles. That is because the result of
  Math.log10(n) / Math.log10(3) could be 5.0000001 or 4.9999999. This
  effect can be observed by using the function Math.log() instead of
  Math.log10().

In order to fix that, we need to compare the result against an
  epsilon.

Java

return (Math.log(n) / Math.log(3) + epsilon) % 1 <= 2 * epsilon;

There I didn't understand return (Math.log(n) / Math.log(3) + epsilon) % 1 <= 2 * epsilon;

What is the meaning of that line?

Why EPSILON is used while comparing floating points?


问:
Run-time error '5': Invalid procedure call or argument while running macro
I am using a V.B.A Code to Dynamically Change a Pivot Table's Data Source Range. The sheet containing the pivot table is in a different sheet(Sheet7) (in the same excel file) and the data source is in Sheet2 and the macro runs in the Sheet9 i.e a different sheet that the data source and the pivot table. Upon running the code throws error : Run-time error '5': Invalid procedure call or argument
(Note : All the sheets are of the same excel file)

The code is as follows:

```<code>Sub UPDATE_BUTTON()
'PURPOSE: Automatically readjust a Pivot Table's data source range
'SOURCE: www.TheSpreadsheetGuru.com/The-Code-Vault

Dim Data_sht As Worksheet
Dim Pivot_sht As Worksheet
Dim StartPoint As Range
Dim DataRange As Range
Dim PivotName As String
Dim NewRange As String

'Set Variables Equal to Data Sheet and Pivot Sheet
  Set Data_sht = ThisWorkbook.Worksheets("Sheet2")
  Set Pivot_sht = ThisWorkbook.Worksheets("Sheet7")

'Enter in Pivot Table Name
  PivotName = "A"

'Dynamically Retrieve Range Address of Data
  Set StartPoint = Data_sht.Range("A1")
  Set DataRange = Data_sht.Range(StartPoint, StartPoint.SpecialCells(xlLastCell))

  NewRange = Data_sht.Name & "!" & _
    DataRange.Address(ReferenceStyle:=xlR1C1)

'Make sure every column in data set has a heading and is not blank (error prevention)
  If WorksheetFunction.CountBlank(DataRange.Rows(1)) > 0 Then
    MsgBox "One of your data columns has a blank heading." & vbNewLine _
      & "Please fix and re-run!.", vbCritical, "Column Heading Missing!"
    Exit Sub
  End If
'DataArea = "Sheet7!R1C1:R" & Selection.Rows.Count & "C" & Selection.Columns.Count
'Change Pivot Table Data Source Range Address
  Pivot_sht.PivotTables(PivotName).ChangePivotCache _
    ThisWorkbook.PivotCaches.Create( _
    SourceType:=xlDatabase, _
    SourceData:=NewRange)

'Ensure Pivot Table is Refreshed
  Pivot_sht.PivotTables(PivotName).RefreshTable

'Complete Message
  MsgBox PivotName & "'s data source range has been successfully updated!"

End Sub
</code>```

The same is throwing an error in the line :

```<code>Pivot_sht.PivotTables(PivotName).ChangePivotCache _
    ThisWorkbook.PivotCaches.Create( _
    SourceType:=xlDatabase, _
    SourceData:=NewRange)
</code>```

If I change the same to :

```<code>ThisWorkbook.Worksheets("Sheet7").PivotCaches.Create( _
</code>```

It gives Run-time error '438': Object doesnt support this property or method

答:
PivotCaches is tied to workbook, not worksheet.
https://msdn.microsoft.com/en-us/vba/excel-vba/articles/pivotcaches-object-excel

Body:
I am using a V.B.A Code to Dynamically Change a Pivot Table's Data Source Range. The sheet containing the pivot table is in a different sheet(Sheet7) (in the same excel file) and the data source is in Sheet2 and the macro runs in the Sheet9 i.e a different sheet that the data source and the pivot table. Upon running the code throws error : Run-time error '5': Invalid procedure call or argument
(Note : All the sheets are of the same excel file)

The code is as follows:

Sub UPDATE_BUTTON()
'PURPOSE: Automatically readjust a Pivot Table's data source range
'SOURCE: www.TheSpreadsheetGuru.com/The-Code-Vault

Dim Data_sht As Worksheet
Dim Pivot_sht As Worksheet
Dim StartPoint As Range
Dim DataRange As Range
Dim PivotName As String
Dim NewRange As String

'Set Variables Equal to Data Sheet and Pivot Sheet
  Set Data_sht = ThisWorkbook.Worksheets("Sheet2")
  Set Pivot_sht = ThisWorkbook.Worksheets("Sheet7")

'Enter in Pivot Table Name
  PivotName = "A"

'Dynamically Retrieve Range Address of Data
  Set StartPoint = Data_sht.Range("A1")
  Set DataRange = Data_sht.Range(StartPoint, StartPoint.SpecialCells(xlLastCell))

  NewRange = Data_sht.Name & "!" & _
    DataRange.Address(ReferenceStyle:=xlR1C1)

'Make sure every column in data set has a heading and is not blank (error prevention)
  If WorksheetFunction.CountBlank(DataRange.Rows(1)) > 0 Then
    MsgBox "One of your data columns has a blank heading." & vbNewLine _
      & "Please fix and re-run!.", vbCritical, "Column Heading Missing!"
    Exit Sub
  End If
'DataArea = "Sheet7!R1C1:R" & Selection.Rows.Count & "C" & Selection.Columns.Count
'Change Pivot Table Data Source Range Address
  Pivot_sht.PivotTables(PivotName).ChangePivotCache _
    ThisWorkbook.PivotCaches.Create( _
    SourceType:=xlDatabase, _
    SourceData:=NewRange)

'Ensure Pivot Table is Refreshed
  Pivot_sht.PivotTables(PivotName).RefreshTable

'Complete Message
  MsgBox PivotName & "'s data source range has been successfully updated!"

End Sub

The same is throwing an error in the line :

Pivot_sht.PivotTables(PivotName).ChangePivotCache _
    ThisWorkbook.PivotCaches.Create( _
    SourceType:=xlDatabase, _
    SourceData:=NewRange)

If I change the same to :

ThisWorkbook.Worksheets("Sheet7").PivotCaches.Create( _

It gives Run-time error '438': Object doesnt support this property or method