问:
C# Multi-threading, wait for all task to complete in a situation when new tasks are being constantly added
I have a situation where new tasks are being constantly generated and added to a ConcurrentBag<Tasks>.

I need to wait all tasks to complete.

Waiting for all the tasks in the ConcurrentBag via WaitAll is not enough as the number of tasks would have grown while the previous wait is completed.

At the moment I am waiting it in the following way:

```<code>private void WaitAllTasks()
{
    while (true)
    {
        int countAtStart = _tasks.Count();
        Task.WaitAll(_tasks.ToArray());

        int countAtEnd = _tasks.Count();
        if (countAtStart == countAtEnd)
        {
            break;
        }

        #if DEBUG
        if (_tasks.Count() > 100)
        {
            tokenSource.Cancel();
            break;
        }
        #endif
    }
}
</code>```

I am not very happy with the while(true) solution.

Can anyone suggest a better more efficient way to do this (without having to pool the processor constantly with a while(true))

Additional context information as requested in the comments. I don't think though this is relevant to the question.

This piece of code is used in a web crawler. The crawler scans page content and looks for two type of information. Data Pages and Link Pages. Data pages will be scanned and data will be collected, Link Pages will be scanned and more links will be collected from them.

As each of the tasks carry-on the activities and find more links, they add the links to an EventList. There is an event OnAdd on the list (code below) that is used to trigger other task to scan the newly added URLs. And so forth.

The job is complete when there are no more running tasks (so no more links will be added) and all items have been processed.

```<code>public IEventList<ISearchStatus> CurrentLinks { get; private set; }
public IEventList<IDataStatus> CurrentData { get; private set; }
public IEventList<System.Dynamic.ExpandoObject> ResultData { get; set; }
private readonly ConcurrentBag<Task> _tasks = new ConcurrentBag<Task>();

private readonly CancellationTokenSource tokenSource = new CancellationTokenSource();
private readonly CancellationToken token;

public void Search(ISearchDefinition search)
{
    CurrentLinks.OnAdd += UrlAdded;
    CurrentData.OnAdd += DataUrlAdded;

    var status = new SearchStatus(search);

    CurrentLinks.Add(status);

    WaitAllTasks();

    _exporter.Export(ResultData as IList<System.Dynamic.ExpandoObject>);
}

private void DataUrlAdded(object o, EventArgs e)
{
    var item = o as IDataStatus;
    if (item == null)
    {
        return;
    }

    _tasks.Add(Task.Factory.StartNew(() => ProcessObjectSearch(item), token));
}

private void UrlAdded(object o, EventArgs e)
{
    var item = o as ISearchStatus;
    if (item==null)
    {
        return;
    }

    _tasks.Add(Task.Factory.StartNew(() => ProcessFollow(item), token));
    _tasks.Add(Task.Factory.StartNew(() => ProcessData(item), token));
}

 public class EventList<T> : List<T>, IEventList<T>
{
    public EventHandler OnAdd { get; set; }
    private readonly object locker = new object();
    public new void Add(T item)
    {
        //lock (locker)
        {
            base.Add(item);
        }
        OnAdd?.Invoke(item, null);
    }

    public new bool Contains(T item)
    {
        //lock (locker)
        {
            return base.Contains(item);
        }
    }
}
</code>```

答:
I think that this task can be done with TPL Dataflow library with very basic setup. You'll need a TransformManyBlock<Task, IEnumerable<DataTask>> and an ActionBlock (may be more of them) for actual data processing, like this:

```<code>// queue for a new urls to parse
var buffer = new BufferBlock<ParseTask>();

// parser itself, returns many data tasks from one url
// similar to LINQ.SelectMany method
var transform = new TransformManyBlock<ParseTask, DataTask>(task =>
{
    // get all the additional urls to parse
    var parsedLinks = GetLinkTasks(task);
    // get all the data to parse
    var parsedData = GetDataTasks(task);

    // setup additional links to be parsed
    foreach (var parsedLink in parsedLinks)
    {
        buffer.Post(parsedLink);
    }

    // return all the data to be processed
    return parsedData;
});

// actual data processing
var consumer = new ActionBlock<DataTask>(s => ProcessData(s));
</code>```

After that you need to link the blocks between each over:

```<code>buffer.LinkTo(transform, new DataflowLinkOptions { PropagateCompletion = true });
transform.LinkTo(consumer, new DataflowLinkOptions { PropagateCompletion = true });
</code>```

Now you have a nice pipeline which will execute in background. At the moment you realize that everything you need is parsed, you simply call the Complete method for a block so it stops accepting news messages. After the buffer became empty, it will propagate the completion down the pipeline to transform block, which will propagate it down to consumer(s), and you need to wait for Completion task:

```<code>// no additional links would be accepted
buffer.Complete();
// after all the tasks are done, this will get fired
await consumer.Completion;
</code>```

You can check the moment for a completion, for example, if both buffer' Count property and transform' InputCount and transform' CurrentDegreeOfParallelism (this is internal property for the TransformManyBlock) are equal to 0.

However, I suggested you to implement some additional logic here to determine current transformers number, as using the internal logic isn't a great solution. As for cancelling the pipeline, you can create a TPL block with a CancellationToken, either the one for all, or a dedicated for each block, getting the cancellation out of box.

Body:
I have a situation where new tasks are being constantly generated and added to a ConcurrentBag<Tasks>.

I need to wait all tasks to complete.

Waiting for all the tasks in the ConcurrentBag via WaitAll is not enough as the number of tasks would have grown while the previous wait is completed.

At the moment I am waiting it in the following way:

private void WaitAllTasks()
{
    while (true)
    {
        int countAtStart = _tasks.Count();
        Task.WaitAll(_tasks.ToArray());

        int countAtEnd = _tasks.Count();
        if (countAtStart == countAtEnd)
        {
            break;
        }

        #if DEBUG
        if (_tasks.Count() > 100)
        {
            tokenSource.Cancel();
            break;
        }
        #endif
    }
}

I am not very happy with the while(true) solution.

Can anyone suggest a better more efficient way to do this (without having to pool the processor constantly with a while(true))

Additional context information as requested in the comments. I don't think though this is relevant to the question.

This piece of code is used in a web crawler. The crawler scans page content and looks for two type of information. Data Pages and Link Pages. Data pages will be scanned and data will be collected, Link Pages will be scanned and more links will be collected from them.

As each of the tasks carry-on the activities and find more links, they add the links to an EventList. There is an event OnAdd on the list (code below) that is used to trigger other task to scan the newly added URLs. And so forth.

The job is complete when there are no more running tasks (so no more links will be added) and all items have been processed.

public IEventList<ISearchStatus> CurrentLinks { get; private set; }
public IEventList<IDataStatus> CurrentData { get; private set; }
public IEventList<System.Dynamic.ExpandoObject> ResultData { get; set; }
private readonly ConcurrentBag<Task> _tasks = new ConcurrentBag<Task>();

private readonly CancellationTokenSource tokenSource = new CancellationTokenSource();
private readonly CancellationToken token;

public void Search(ISearchDefinition search)
{
    CurrentLinks.OnAdd += UrlAdded;
    CurrentData.OnAdd += DataUrlAdded;

    var status = new SearchStatus(search);

    CurrentLinks.Add(status);

    WaitAllTasks();

    _exporter.Export(ResultData as IList<System.Dynamic.ExpandoObject>);
}

private void DataUrlAdded(object o, EventArgs e)
{
    var item = o as IDataStatus;
    if (item == null)
    {
        return;
    }

    _tasks.Add(Task.Factory.StartNew(() => ProcessObjectSearch(item), token));
}

private void UrlAdded(object o, EventArgs e)
{
    var item = o as ISearchStatus;
    if (item==null)
    {
        return;
    }

    _tasks.Add(Task.Factory.StartNew(() => ProcessFollow(item), token));
    _tasks.Add(Task.Factory.StartNew(() => ProcessData(item), token));
}

 public class EventList<T> : List<T>, IEventList<T>
{
    public EventHandler OnAdd { get; set; }
    private readonly object locker = new object();
    public new void Add(T item)
    {
        //lock (locker)
        {
            base.Add(item);
        }
        OnAdd?.Invoke(item, null);
    }

    public new bool Contains(T item)
    {
        //lock (locker)
        {
            return base.Contains(item);
        }
    }
}

Body:
I think that this task can be done with TPL Dataflow library with very basic setup. You'll need a TransformManyBlock<Task, IEnumerable<DataTask>> and an ActionBlock (may be more of them) for actual data processing, like this:

// queue for a new urls to parse
var buffer = new BufferBlock<ParseTask>();

// parser itself, returns many data tasks from one url
// similar to LINQ.SelectMany method
var transform = new TransformManyBlock<ParseTask, DataTask>(task =>
{
    // get all the additional urls to parse
    var parsedLinks = GetLinkTasks(task);
    // get all the data to parse
    var parsedData = GetDataTasks(task);

    // setup additional links to be parsed
    foreach (var parsedLink in parsedLinks)
    {
        buffer.Post(parsedLink);
    }

    // return all the data to be processed
    return parsedData;
});

// actual data processing
var consumer = new ActionBlock<DataTask>(s => ProcessData(s));

After that you need to link the blocks between each over:

buffer.LinkTo(transform, new DataflowLinkOptions { PropagateCompletion = true });
transform.LinkTo(consumer, new DataflowLinkOptions { PropagateCompletion = true });

Now you have a nice pipeline which will execute in background. At the moment you realize that everything you need is parsed, you simply call the Complete method for a block so it stops accepting news messages. After the buffer became empty, it will propagate the completion down the pipeline to transform block, which will propagate it down to consumer(s), and you need to wait for Completion task:

// no additional links would be accepted
buffer.Complete();
// after all the tasks are done, this will get fired
await consumer.Completion;

You can check the moment for a completion, for example, if both buffer' Count property and transform' InputCount and transform' CurrentDegreeOfParallelism (this is internal property for the TransformManyBlock) are equal to 0.

However, I suggested you to implement some additional logic here to determine current transformers number, as using the internal logic isn't a great solution. As for cancelling the pipeline, you can create a TPL block with a CancellationToken, either the one for all, or a dedicated for each block, getting the cancellation out of box.


来源: stackexchange

问:
SailsJS remove bluebird
I want to remove the bluebird package installed in my sails app, in favor of the native Node promises.

But after I set npm remove bluebird --save, I get:

```<code>Error: Cannot find module 'bluebird'
    at Function.Module._resolveFilename (module.js:325:15)
    at Function.Module._load (module.js:276:25)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/candyvoice/node_modules/sails/node_modules/consolidate/lib/consolidate.js:22:15)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/candyvoice/node_modules/sails/node_modules/consolidate/index.js:1:80)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
</code>```

I don't use bluebird anywhere in my code so I'm guessing this is somehow a Sails dependency? The stacktrace doesn't refer to any of my files either.

Thanks

答:
Bluebird is a SailsJS dependency.

You can use native promises in your application alongside Sails' bluebird ones and it'll work seamlessly.

Bluebird has thousands of tests to ensure that its promises work seamlessly with native ones - and bluebird contributors are also NodeJS contributors that ensure it doesn't break from the other side either. (Full disclosure, I'm a bluebird contributor and a NodeJS collaborator).

Simply don't use bluebird in your own code - and things will work well :)

As a caveat, in NodeJS 8 there's a chance unhandled promise rejections will throw. You can fix this by setting process.on("unhandledRejection" which will set the same behavior to all promises.

ContentLicense: CC BY-SA 3.0

Title: SailsJS remove bluebird

Body:
I want to remove the bluebird package installed in my sails app, in favor of the native Node promises.

But after I set npm remove bluebird --save, I get:

Error: Cannot find module 'bluebird'
    at Function.Module._resolveFilename (module.js:325:15)
    at Function.Module._load (module.js:276:25)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/candyvoice/node_modules/sails/node_modules/consolidate/lib/consolidate.js:22:15)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/candyvoice/node_modules/sails/node_modules/consolidate/index.js:1:80)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)

I don't use bluebird anywhere in my code so I'm guessing this is somehow a Sails dependency? The stacktrace doesn't refer to any of my files either.

Thanks


问:
Castle Windsor: Set component dependencies on existing object
In MEF it's possible to set the dependencies for an existing object using something like:

```<code>container.SatisfyImportsOnce(instance);
</code>```

Is it possible to do the same with Castle Windsor?

I'm using (read: learning) Caliburn.Micro, and trying to update the template project from MEF to Windsor, which is where I've come across the issue.

答:
Sorry Neil, Windsor doesn't have that feature

Castle Windsor FAQ

Windsor will resolve a property dependency (which it considers an optional dependency) such as an ILogger property if there is a registered component for that service.  But this only happens during component activation...when the component is constructed the first time, there is no way to pass Windsor an existing instance and inject components into properties.

ContentLicense: CC BY-SA 2.5

Body:
In MEF it's possible to set the dependencies for an existing object using something like:

container.SatisfyImportsOnce(instance);

Is it possible to do the same with Castle Windsor?

I'm using (read: learning) Caliburn.Micro, and trying to update the template project from MEF to Windsor, which is where I've come across the issue.


问:
design ROM to save filter coefficients in verilog
I want to store filter coefficients(fixed values) in ROM using verilog.Below is the code for ROM using case.

```<code>module rom_using_case (
address , // Address input
data    , // Data output
read_en , // Read Enable
ce        // Chip Enable
);
input [3:0] address;
output [7:0] data;
input read_en;
input ce;

reg [7:0] data ;

always @ (ce or read_en or address)
begin
  case (address)
    0 : data = 10;
    1 : data = 55;
    2 : data = 244;
    3 : data = 0;
    4 : data = 1;
    5 : data = 8'hff;
    6 : data = 8'h11;
    7 : data = 8'h1;
    8 : data = 8'h10;
    9 : data = 8'h0;
    10 : data = 8'h10;
    11 : data = 8'h15;
    12 : data = 8'h60;
    13 : data = 8'h90;
    14 : data = 8'h70;
    15 : data = 8'h90;
  endcase
end

endmodule
</code>```

what does the case block do in the above code?
can i store filter coefficients in data variable in the case block?
can i access those filter coefficients?

答:
As you state the coefficients will be stored in a RAM LUT or in a ROM block.
The code is (somewhat) self-descriptive, the always  is sensitive to the address then each time the address changes its value the stored value will be assigned to data, case is the selector for which location of the memory block will be assinged to data.

Your implementation is enough for small filters, but if you need a lot of coefficients it will get hard to maintain.

For this purpose you can use the $readmemh or $readmemb. Those are verilog intrisic tasks.

From: https://www.csee.umbc.edu/~tinoosh/cmpe415/slides/Rom-LUT-verilog.pdf

The $readmemh system task expects the content of the named file to be
a sequence of hexadecimal numbers, separated by spaces or line breaks.
Similarly, $readmemb expects the file to contain a sequence of binary.

Here is a snippet which shows how to use it:

```<code>reg [19:0] data_ROM [0:511];
...
initial $readmemh("rom.data", data_ROM);
always @(address)
  if (ce & read_en)
    d_out = data_ROM[address];
</code>```

The "rom.data" contains the coefficients in text. For example, in your case:

```<code>8'hA
8'h37
8'hF4
8'h0
8'h1
8'hff
8'h11
8'h1
8'h10
8'h0
8'h10
8'h15
8'h60
8'h90
8'h70
8'h90
</code>```

Body:
I want to store filter coefficients(fixed values) in ROM using verilog.Below is the code for ROM using case.

module rom_using_case (
address , // Address input
data    , // Data output
read_en , // Read Enable
ce        // Chip Enable
);
input [3:0] address;
output [7:0] data;
input read_en;
input ce;

reg [7:0] data ;

always @ (ce or read_en or address)
begin
  case (address)
    0 : data = 10;
    1 : data = 55;
    2 : data = 244;
    3 : data = 0;
    4 : data = 1;
    5 : data = 8'hff;
    6 : data = 8'h11;
    7 : data = 8'h1;
    8 : data = 8'h10;
    9 : data = 8'h0;
    10 : data = 8'h10;
    11 : data = 8'h15;
    12 : data = 8'h60;
    13 : data = 8'h90;
    14 : data = 8'h70;
    15 : data = 8'h90;
  endcase
end

endmodule

what does the case block do in the above code?
can i store filter coefficients in data variable in the case block?
can i access those filter coefficients?

Body:
As you state the coefficients will be stored in a RAM LUT or in a ROM block.
The code is (somewhat) self-descriptive, the always  is sensitive to the address then each time the address changes its value the stored value will be assigned to data, case is the selector for which location of the memory block will be assinged to data.

Your implementation is enough for small filters, but if you need a lot of coefficients it will get hard to maintain.

For this purpose you can use the $readmemh or $readmemb. Those are verilog intrisic tasks.

From: https://www.csee.umbc.edu/~tinoosh/cmpe415/slides/Rom-LUT-verilog.pdf

The $readmemh system task expects the content of the named file to be
a sequence of hexadecimal numbers, separated by spaces or line breaks.
Similarly, $readmemb expects the file to contain a sequence of binary.

Here is a snippet which shows how to use it:

reg [19:0] data_ROM [0:511];
...
initial $readmemh("rom.data", data_ROM);
always @(address)
  if (ce & read_en)
    d_out = data_ROM[address];

The "rom.data" contains the coefficients in text. For example, in your case:

8'hA
8'h37
8'hF4
8'h0
8'h1
8'hff
8'h11
8'h1
8'h10
8'h0
8'h10
8'h15
8'h60
8'h90
8'h70
8'h90


问:
scala what does this mean? "{ /* compiled code */ }"
I came across this thing multiple times: { /* compiled code */ } but I can't find what it does in scala.

example:

```<code>object autoImport extends scala.AnyRef {
    ...
    val destination : sbt.SettingKey[java.io.File] = { /* compiled code */ }
    ...

}
</code>```

答:
It doesn't do anything. It's your IDE telling you that it can't find the source code for the given method and thus can't show it to you.

That's assuming you're looking at a class file in your IDE. If you're looking at actual Scala code, it's just an empty method with a severely misleading comment.

Body:
I came across this thing multiple times: { /* compiled code */ } but I can't find what it does in scala.

example:

object autoImport extends scala.AnyRef {
    ...
    val destination : sbt.SettingKey[java.io.File] = { /* compiled code */ }
    ...

}


问:
How to import specified classes from CSS file instead of everything
I'm trying to import some classes from a CSS file like bootstrap.css to my site.scss SASS file, not all of them. The problem with following code is that I get all bootstrap classes in my compiled site.css file:

site.scss

```<code>@import "bootstrap";

.my-div-md-6
{
    /*some other styles*/
    @extend .col-md-6;
}
</code>```

On the other hand, It is possible to do this with LESS by importing bootstrap.css as reference using this code:

site.less

```<code>@import (less, reference) "bootstrap.css";

.my-div-md-6{
     /*some other styles*/
    &:extend(.col-md-6);
}
</code>```

The compiled output of LESS is very light as below:

site.css

```<code>.my-div-md-6 {
  position: relative;
  min-height: 1px;
  padding-right: 15px;
  padding-left: 15px;
}
@media (min-width: 992px) {
  .my-div-md-6 {
    float: left;
  }
  .my-div-md-6 {
    width: 50%;
  }
}
.my-div-md-6 {
  /*some other styles*/
}
</code>```

Is it possible to achieve this with SASS? If yes, giving a quick example would help.

答:
Unfortunately, there is not simple answer and at the time of writing this, Ruby Sass does not natively support the LESS import (reference) feature.

TLDR; Suggestions:

use uncss or postcss to remove the compiled css from file before finalising stylesheet.

if you can, use mixins and placeholder classes as a rewrite of the scss file, but this is the MOST time consuming.

<s>import "file" as partial such that file="_file.scss" and @extend .class if you absolutely have to, (manual method but suppose it'll work)</s>

UNCSS

You can use uncss as a package from npm to remove the compiled css (I know this isn't efficient, but if you had to use SASS), then you'd remove the chaff that's generated from the example bootstrap import.

HOW?

QUOTE: SO-Answer-Joesph

How? The process by which UnCSS removes the unused rules is as follows:

The HTML files are loaded by PhantomJS and JavaScript is executed.

Used stylesheets are extracted from the resulting HTML.

The stylesheets are concatenated and the rules are parsed by css-parse.

document.querySelector filters out selectors that are not found in the HTML files.

The remaining rules are converted back to CSS.

So yes, it removes selectors not in the DOM at runtime. If you have dynamically added selectors, you can make uncss ignore them by commenting: /* uncss:ignore */ before them, e.g...

MAKE SURE YOU ADD THE MEDIA OPTION IN UNCSS

REF: SO-Answer-Deksden

SASS Background research:

Summarising above:

nex3: one of the core leads for sass, has been at google and working on dart. They released dart-sass (unstable release) as a rewrite in favour to replace and improve upon ruby sass. This is interesting as this rewrite also explains the lack of feature development in Ruby Sass as well as the need for a rewrite. Since a core contributor of a ruby sass port: i.e. libsass (C++ implementation of ruby-sass) left the libsass team, it brings a further impetus to improve on sass performance.

Credit:

Joesph

Deksden

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to import some classes from a CSS file like bootstrap.css to my site.scss SASS file, not all of them. The problem with following code is that I get all bootstrap classes in my compiled site.css file:

site.scss

@import "bootstrap";

.my-div-md-6
{
    /*some other styles*/
    @extend .col-md-6;
}

On the other hand, It is possible to do this with LESS by importing bootstrap.css as reference using this code:

site.less

@import (less, reference) "bootstrap.css";

.my-div-md-6{
     /*some other styles*/
    &:extend(.col-md-6);
}

The compiled output of LESS is very light as below:

site.css

.my-div-md-6 {
  position: relative;
  min-height: 1px;
  padding-right: 15px;
  padding-left: 15px;
}
@media (min-width: 992px) {
  .my-div-md-6 {
    float: left;
  }
  .my-div-md-6 {
    width: 50%;
  }
}
.my-div-md-6 {
  /*some other styles*/
}

Is it possible to achieve this with SASS? If yes, giving a quick example would help.


问:
Assignment, about 2d arrays
I would like some assistance with a problem.

I have this text file:

I input the contents of the text into a string 2d array and converted it to a integer 2d array. When i converted to the int array the nan's were replaced with a zero. I now proceeded to find the max and min of each line in the 2d array and find the average of both, which I successfully achieved. My problem is I want to assign the average value found for each line to the zero. I tried using two for loops but it replacing all the zero's with the average of the first line. Can anyone please assist me.

My code:

```<code>int min = 200;

int main() {

    fstream imagefile;
    imagefile.open("Text.txt");

    if (imagefile.fail()) { // checking for errors in file
        cerr << "Error opening file" << endl;
        exit(1);

    std::string data[3][11];
    int integer[3][11];
    for (int k = 0; k < 3; k++) {

        for (int i = 0; i < 11; i++) {
            imagefile >> data[k][i]; // read from file

        }
    }

    cin.get();

    for (int k = 0; k < 3; k++) {

        for (int i = 0; i < 11; i++)
        {
            integer[k][i] = atoi(data[k][i].c_str()); // converts string to int
        }
    }
    cin.get();

    for (int k = 0; k < 3; k++) { //k is the row  and i is the column

        for (int i = 0; i < 11; i++) {
            cout << integer[k][i] << "  ";

        }
        cout << endl;
    }

    int row, col;
    for (row = 0; row < 3; row++) { //k is the row  and i is the column

        max = integer[row][0];
        min = integer[row][0];

        for (col = 0; col < 11; col++) {
            if (integer[row][col] > max) { max = integer[row][col]; }
            if ((integer[row][col] < min) && (integer[row][col] != 0)) { min = integer[row][col]; }
            //if (integer[row][col] == 0) { avg == integer[row][col]; }

            sum = max + min;
            avg = sum / 2;
        }
            for (int k = 0; k < integer[k][i]; k++) {  //k is the row  and i is the column
                for (int i = 0; i < 11; i++) {
                    if (integer[k][i] == 0) {

                        integer[k][i] = avg;

                    }
                    cout << integer[k][i] << "  ";

                }
                cout << endl;
            }

        cout << max << " ";
        cout << min << " ";
        cout << avg << " " << endl;
    }

    imagefile.close();
    system("pause");
    return 0;
}
</code>```

答:
Here is your code will work perfectly if you will have this file.

Note: Your Text.txt should be exactly this format. Not with a blank line.

```<code>#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
    ifstream in("Text.txt");
    char ch = '\0'; int count = 1; //Ac counter to count number of rows
    while (!in.eof())
    {
        in.get(ch);
        if (ch == '\n') //counting lines
            count++;
    }
    in.close();
    double *avgArray = new double[count]; //array to store avg of min/max of every row
    int arraySize = count;
    in.open("Text.txt");
    count = 0;
    string strTemp = "";
    int temp = 0; //temp to get int values
    int sum = 0; //calculate sum of avery row
    int i = 0; //index number
    int max = 0;
    int min = 99999;
    while (!in.eof())
    {
        in >> strTemp;
        if (strTemp == "NaN")
            temp = 0;
        else
            temp = atoi(strTemp.c_str());
        if (temp > max)
            max = temp;
        if (temp < min && temp!=0)
            min = temp;
        in.get(ch);
        if (ch == '\n' || in.eof()) //if new line occured
        {
            avgArray[i] = double(max + min) / 2.0; //store avg in abg array
            max = 0;
            min = 99999;
            i++; //counter of avg array
        }
    }
    in.close();
    //for (int i = 0; i < arraySize; i++) //printing
        //cout << avgArray[i]<<endl; //avg of all rows
    in.open("Text.txt");
    i = 0;
    int col = 0; //counter for cols
    int SizeCol = 0;
    temp = 0;
    strTemp = "";
    double **DataArray = new double*[arraySize]; //2D array to store file data
    while (!in.eof())
    {
        in >> strTemp;
        if (strTemp == "NaN")
            temp = 0;
        else
            temp = atoi(strTemp.c_str());
        in.get(ch);
        col++; //counting columns
        if (ch == '\n')
        {
            DataArray[i] = new double[col]; //making dynmically cols
            i++;
            SizeCol = col;
            col = 0;
        }
        if (in.eof())
            DataArray[i] = new double[col]; //for last line of file
    }
    in.close();
    in.open("Text.txt");

    for (int i = 0; i < arraySize; i++)
    {
        for (int j = 0; j < SizeCol; j++)
        {
            in >> strTemp;
            if (strTemp == "NaN")
                temp = 0;
            else
                temp = atoi(strTemp.c_str());
            DataArray[i][j]=temp;
            if (DataArray[i][j] == 0)
                DataArray[i][j] = avgArray[i]; //Assigning avg of row at row's 0 place
        }
    }
    in.close();

    //Printing the final array
    for (int i = 0; i < arraySize; i++)
    {
        for (int j = 0; j < SizeCol; j++)
        {
            cout<< DataArray[i][j]<<" "; //printing
        }
        cout << endl;
    }
    cout << endl << endl;
    ofstream out("Text.txt");
    //Wrting the final array into Text.txt
    for (int i = 0; i < arraySize; i++)
    {
        for (int j = 0; j < SizeCol; j++)
        {
            out << DataArray[i][j] << " "; //Writing
        }
        out << endl;
    }
    delete[] avgArray;
    for (int i = 0; i < arraySize; i++)
        delete DataArray[i];
    delete[] DataArray;
    system("pause");
    return 0;
}
</code>```

Title: Assignment, about 2d arrays

Body:
I would like some assistance with a problem.

I have this text file:

I input the contents of the text into a string 2d array and converted it to a integer 2d array. When i converted to the int array the nan's were replaced with a zero. I now proceeded to find the max and min of each line in the 2d array and find the average of both, which I successfully achieved. My problem is I want to assign the average value found for each line to the zero. I tried using two for loops but it replacing all the zero's with the average of the first line. Can anyone please assist me.

My code:

int min = 200;

int main() {

    fstream imagefile;
    imagefile.open("Text.txt");

    if (imagefile.fail()) { // checking for errors in file
        cerr << "Error opening file" << endl;
        exit(1);

    std::string data[3][11];
    int integer[3][11];
    for (int k = 0; k < 3; k++) {

        for (int i = 0; i < 11; i++) {
            imagefile >> data[k][i]; // read from file

        }
    }

    cin.get();

    for (int k = 0; k < 3; k++) {

        for (int i = 0; i < 11; i++)
        {
            integer[k][i] = atoi(data[k][i].c_str()); // converts string to int
        }
    }
    cin.get();

    for (int k = 0; k < 3; k++) { //k is the row  and i is the column

        for (int i = 0; i < 11; i++) {
            cout << integer[k][i] << "  ";

        }
        cout << endl;
    }

    int row, col;
    for (row = 0; row < 3; row++) { //k is the row  and i is the column

        max = integer[row][0];
        min = integer[row][0];

        for (col = 0; col < 11; col++) {
            if (integer[row][col] > max) { max = integer[row][col]; }
            if ((integer[row][col] < min) && (integer[row][col] != 0)) { min = integer[row][col]; }
            //if (integer[row][col] == 0) { avg == integer[row][col]; }

            sum = max + min;
            avg = sum / 2;
        }
            for (int k = 0; k < integer[k][i]; k++) {  //k is the row  and i is the column
                for (int i = 0; i < 11; i++) {
                    if (integer[k][i] == 0) {

                        integer[k][i] = avg;

                    }
                    cout << integer[k][i] << "  ";

                }
                cout << endl;
            }

        cout << max << " ";
        cout << min << " ";
        cout << avg << " " << endl;
    }

    imagefile.close();
    system("pause");
    return 0;
}

Body:
Here is your code will work perfectly if you will have this file.

Note: Your Text.txt should be exactly this format. Not with a blank line.

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
    ifstream in("Text.txt");
    char ch = '\0'; int count = 1; //Ac counter to count number of rows
    while (!in.eof())
    {
        in.get(ch);
        if (ch == '\n') //counting lines
            count++;
    }
    in.close();
    double *avgArray = new double[count]; //array to store avg of min/max of every row
    int arraySize = count;
    in.open("Text.txt");
    count = 0;
    string strTemp = "";
    int temp = 0; //temp to get int values
    int sum = 0; //calculate sum of avery row
    int i = 0; //index number
    int max = 0;
    int min = 99999;
    while (!in.eof())
    {
        in >> strTemp;
        if (strTemp == "NaN")
            temp = 0;
        else
            temp = atoi(strTemp.c_str());
        if (temp > max)
            max = temp;
        if (temp < min && temp!=0)
            min = temp;
        in.get(ch);
        if (ch == '\n' || in.eof()) //if new line occured
        {
            avgArray[i] = double(max + min) / 2.0; //store avg in abg array
            max = 0;
            min = 99999;
            i++; //counter of avg array
        }
    }
    in.close();
    //for (int i = 0; i < arraySize; i++) //printing
        //cout << avgArray[i]<<endl; //avg of all rows
    in.open("Text.txt");
    i = 0;
    int col = 0; //counter for cols
    int SizeCol = 0;
    temp = 0;
    strTemp = "";
    double **DataArray = new double*[arraySize]; //2D array to store file data
    while (!in.eof())
    {
        in >> strTemp;
        if (strTemp == "NaN")
            temp = 0;
        else
            temp = atoi(strTemp.c_str());
        in.get(ch);
        col++; //counting columns
        if (ch == '\n')
        {
            DataArray[i] = new double[col]; //making dynmically cols
            i++;
            SizeCol = col;
            col = 0;
        }
        if (in.eof())
            DataArray[i] = new double[col]; //for last line of file
    }
    in.close();
    in.open("Text.txt");

    for (int i = 0; i < arraySize; i++)
    {
        for (int j = 0; j < SizeCol; j++)
        {
            in >> strTemp;
            if (strTemp == "NaN")
                temp = 0;
            else
                temp = atoi(strTemp.c_str());
            DataArray[i][j]=temp;
            if (DataArray[i][j] == 0)
                DataArray[i][j] = avgArray[i]; //Assigning avg of row at row's 0 place
        }
    }
    in.close();

    //Printing the final array
    for (int i = 0; i < arraySize; i++)
    {
        for (int j = 0; j < SizeCol; j++)
        {
            cout<< DataArray[i][j]<<" "; //printing
        }
        cout << endl;
    }
    cout << endl << endl;
    ofstream out("Text.txt");
    //Wrting the final array into Text.txt
    for (int i = 0; i < arraySize; i++)
    {
        for (int j = 0; j < SizeCol; j++)
        {
            out << DataArray[i][j] << " "; //Writing
        }
        out << endl;
    }
    delete[] avgArray;
    for (int i = 0; i < arraySize; i++)
        delete DataArray[i];
    delete[] DataArray;
    system("pause");
    return 0;
}


问:
Generating a single Entity from existing database using symfony2 and doctrine
Is it possible to generate a single entity from database using the Symfony2 console tool?

In the middle of coding I had to add a table and there are modifications made to the existing entity classes. So I don't want all my entities regenerated.

Any suggestions will be appreciated!

答:
Works great with Symfony 3 too.

If you are getting "No Metadata Classes to process." message try convert your tablename to Doctrine camel casing in the filter parameter.

"my_table_name" needs to be write as "MyTableName".


问:
Can we conclude a set might not be random by checking its subset?
Set A includes 1000 numbers. I checked that half of the numbers in this set are even.

I extracted subset B from set A as follow: any number in set A which starts with 1 is also in set B. (All numbers in B start with 1).

I checked that more than half of the numbers in set B are even.

Half of the numbers in A are even so should we expect the same for B? But more than half of B are even. So can conclude that set A is not random?

If 60% of B are even, can we still conclude A is not generated random?

How if 70% of B are odd?

答:
That depends entirely on how large the sample is.

From basic probability, if p is the probability of getting a "success" (the outcome you're focused on) from a binary trial, q = (1-p) is the probability of getting a "failure" (the alternative outcome).  Let n be the number of trials.  If the trials are independent, the number of outcomes X has a binomial distribution with parameters n and p, and p-hat = X/n is an unbiased estimator for p.  The mean and variance of p-hat are p and pq/n, respectively, and for sufficiently large sample sizes the distribution converges to Gaussian (the bell-shaped curve).  Based on that, as long as p and q are sufficiently bigger than 0 we can say that in repeated experiments about 95% of them should fall within a distance of 1.96*sqrt(pq/n) of the true mean.  That distance is called the margin of error (ME).

You're conjecturing that p = 1/2.  Consequently, your margin of error is ME = 1.96*sqrt(pq/n) = 0.98/sqrt(n).  You can invert to find out how much of a sample size you need to obtain a particular ME:  n = ceiling((0.98/ME)2).

Plugging in some particular margins of error:

ME = 0.20 ==> n = 25 (borderline to believe Gaussian convergence)

ME = 0.10 ==> n = 97

ME = 0.05 ==> n = 385

ME = 0.03 ==> n = 1068

ME = 0.01 ==> n = 9604

In other words, the smaller you want your margin of error to be, the larger the sample size required, and the sampling requirement grows quadratically.

Those last two are relevant to political polling.  It's common to take sample sizes around 1000 and report the estimates as having a margin of error of ±3%.  People would intuitively like ±1%, but it would take 9 times the sampling and is deemed to not be cost-effective.

Bringing this back around to your question, based on the size of your subset you can make a probabilistic statement about how plausible you find your conjecture that p = 1/2, but it's going to take hundreds or thousands of values to make that a tight bound.

Also, please note that non-uniform or non-independent are not the same thing as non-random.  The test you're trying to perform is for uniformity of select bits, and tells you nothing about the other bits nor about the independence of the data.


问:
How to guarantee the transmission of data over the network?
Imagine 2 machines A and B. A wants to make sure B receives a packet P even if there are network failures, how can that be achieved?

Scenario 1:

1) A sends P over the network to B.

Problem: if the network fails at step 1, B won't receive P and A won't know about it.

Scenario 2 with acknowledgement:

1) A sends P over the network to B.

2) B sends back ACK if it receives P.

Problem: If the network fails at step 2, A won't receive the ACK, so A can't reliably know whether B received P or not.

Having ACKs of ACKs would in turn push the problem 1 step further.

答:
This is a huge problem which has been studied for years.   Read about the TCP protocol which guarantees that either the data will be delivered or the sender will (eventually) know that delivery may have failed.

You can start reading here: https://en.wikipedia.org/wiki/Transmission_Control_Protocol
but there are many more helpful and interesting pages about TCP on the web.

Or you could just use TCP and take advantage of the work that has already been done.


问:
Pass parameter from one Powershell function to another
I’m new to powershell and development in general.  I’m trying to write a script that will email a contact once a file exceeds a certain size.  I have two individual functions both working separately (one to check the file size and one to generate a file for sendmail to use) but I can’t get them to interact.

I want to execute the function CheckSize and if the variable $ExceedsSize gets set to 1 then call function SendMail otherwise the script should finish with no other action.

I’ve searched through the forums but couldn’t find anything to apply to what I’m doing.

```<code>   ##Check file to see if it is over a particular size and then send email once threshold is reached.

param(
    [string]$SiteName = "TestSite",                                                 #Name of Site (No Spaces)
    [string]$Path = "\\NetworkPath\Directory",                                      #Path of directory to check
    [int]$FileSizeThreshold = 10,                                                   #Size in MB that will trigger a notification email
    [string]$Contacts = "MyEmail@email.com"
    )

CLS

##Creates variable $ExceedsSize based on newest file in folder.
Function CheckSize {
IF ((GCI $Path -Filter *.txt | Sort LastWriteTime -Descending | Select-Object -first 1 | Measure-Object -property Length -sum).sum / 1000000 -gt $FileSizeThreshold) {$ExceedsSize = 1}
ELSE {$ExceedsSize = 0}

Write-Host $ExceedsSize
}

Function SendMail {
    Param([string]$Template, [string]$Contacts, [string]$WarnTime)

    $EmailLocation = "\\NetworkPath\Scripts\File_$SiteName.txt"

    #Will Generate email from params
        New-Item $EmailLocation -type file -force -value "From: JMSIssue@emails.com`r
To: $Contacts`r
Subject: $SiteName file has exceeded the maximum file size threshold of $FileSizeThreshold MB`r`n"

    #Send Email
    #CMD /C "$SendMail\sendmail.exe -t < $EmailLocation"

    }
</code>```

答:
Per the other answer, you need to return $ExceedsSize instead of using Write-Host (see here for why Write-Host is considered harmful: http://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful/).

You could alternatively call the SendMail function from within the CheckSize function, e.g:

```<code> if ($ExceedsSize -eq 1){SendMail}
</code>```

You will still need to call the CheckSize function somewhere also:

```<code>CheckSize
</code>```

You might also want to give consideration to naming your functions in the verb-noun style of the built in cmdlets. This really helps make their use more explicit to you and others. When choosing a verb, its best to stick to the approved list: https://msdn.microsoft.com/en-us/library/ms714428(v=vs.85).aspx

And also to use names that are fairly unique to avoid possible conflicts.

I'd suggest something along the lines of:

```<code>Get-NewestFileSize
</code>```

(although that's what it should then return)

and

```<code>Send-CCSMail
</code>```

Body:
I’m new to powershell and development in general.  I’m trying to write a script that will email a contact once a file exceeds a certain size.  I have two individual functions both working separately (one to check the file size and one to generate a file for sendmail to use) but I can’t get them to interact.

I want to execute the function CheckSize and if the variable $ExceedsSize gets set to 1 then call function SendMail otherwise the script should finish with no other action.

I’ve searched through the forums but couldn’t find anything to apply to what I’m doing.

   ##Check file to see if it is over a particular size and then send email once threshold is reached.

param(
    [string]$SiteName = "TestSite",                                                 #Name of Site (No Spaces)
    [string]$Path = "\\NetworkPath\Directory",                                      #Path of directory to check
    [int]$FileSizeThreshold = 10,                                                   #Size in MB that will trigger a notification email
    [string]$Contacts = "MyEmail@email.com"
    )

CLS

##Creates variable $ExceedsSize based on newest file in folder.
Function CheckSize {
IF ((GCI $Path -Filter *.txt | Sort LastWriteTime -Descending | Select-Object -first 1 | Measure-Object -property Length -sum).sum / 1000000 -gt $FileSizeThreshold) {$ExceedsSize = 1}
ELSE {$ExceedsSize = 0}

Write-Host $ExceedsSize
}

Function SendMail {
    Param([string]$Template, [string]$Contacts, [string]$WarnTime)

    $EmailLocation = "\\NetworkPath\Scripts\File_$SiteName.txt"

    #Will Generate email from params
        New-Item $EmailLocation -type file -force -value "From: JMSIssue@emails.com`r
To: $Contacts`r
Subject: $SiteName file has exceeded the maximum file size threshold of $FileSizeThreshold MB`r`n"

    #Send Email
    #CMD /C "$SendMail\sendmail.exe -t < $EmailLocation"

    }

Body:
Per the other answer, you need to return $ExceedsSize instead of using Write-Host (see here for why Write-Host is considered harmful: http://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful/).

You could alternatively call the SendMail function from within the CheckSize function, e.g:

 if ($ExceedsSize -eq 1){SendMail}

You will still need to call the CheckSize function somewhere also:

CheckSize

You might also want to give consideration to naming your functions in the verb-noun style of the built in cmdlets. This really helps make their use more explicit to you and others. When choosing a verb, its best to stick to the approved list: https://msdn.microsoft.com/en-us/library/ms714428(v=vs.85).aspx

And also to use names that are fairly unique to avoid possible conflicts.

I'd suggest something along the lines of:

Get-NewestFileSize

(although that's what it should then return)

and

Send-CCSMail


问:
iOS - Terminated due to memory issue
I'm having a memory issue with one specific ViewController and memory. When I launch my app in debug mode, it launches with 40mb memory usage. (I have no idea if this is already a lot or not -- what is common?). Then, when I open this specific view, it spikes up to about 120mb. The issue is, when I pop this view (with the navigationController popViewController), the memory stays up at 120mb. And then, when I re-open it, it spikes to 200mb (a 80mb increase every time).
With other similar ViewController it spikes up to 120mb too, but when I close the view, it goes back down to more or less 40mb.

The problem is that this specific view contains quite a bit of code (about 1000 lines...) and it's impossible for me to post everything here.

What methods should I use to specifically locate the issue in xCode?

答:
For anyone I might be able to help with this:

use the tools in xCode as recommended. There are some great tutorials online.

In my case it was an issue with an [NSTimer] which kept a strong reference to my view, so it never got released afterwards, thus stacking up memory. Make sure to stop your time when you pop a view.

Title: iOS - Terminated due to memory issue


问:
Combining ifelse and any to create new column - R 3.3.2 Windows 7
I have a data.table and I'm trying to create a new column by checking to see if a row has particular values in any of a given set of columns.

```<code>head(d1)

   MEDREC_KEY   pat_key           drug1          drug2          drug3       drug4        drug5       drug6      drug7     drug8 drug9 drug10 drug11 drug12
1: -140665983 669723105 Anti-infectives Cephalosporins     Ethambutol   Isoniazid   Macrolides Penicillins Quinolones Rifamycin    NA     NA     NA     NA
2: -606290573  85924804 Anti-infectives   Beta-lactams Cephalosporins Penicillins   Quinolones          NA         NA        NA    NA     NA     NA     NA
3: -615873176 161009395  Cephalosporins    Penicillins             NA          NA           NA          NA         NA        NA    NA     NA     NA     NA
4: -616819481  36280536 Anti-infectives Cephalosporins     Macrolides  Quinolones           NA          NA         NA        NA    NA     NA     NA     NA
5: -625709819 720290063 Anti-infectives Cephalosporins     Ethambutol   Isoniazid Pyrazinamide  Quinolones  Rifamycin        NA    NA     NA     NA     NA
6: -637094857 720918635 Anti-infectives    Penicillins     Quinolones          NA           NA          NA         NA        NA    NA     NA     NA     NA
</code>```

What I want to happen is if any of the "drug" columns == "Macrolides" AND any of the same columns == "Cephalosporins" then my new column, "correct" == 1 otherwise "correct" == 0 (or it could be logical), like so:

```<code>head(d1)
   MEDREC_KEY   pat_key           drug1          drug2          drug3       drug4        drug5       drug6      drug7     drug8 drug9 drug10 drug11 drug12 correct
1: -140665983 669723105 Anti-infectives Cephalosporins     Ethambutol   Isoniazid   Macrolides Penicillins Quinolones Rifamycin    NA     NA     NA     NA   1
2: -606290573  85924804 Anti-infectives   Beta-lactams Cephalosporins Penicillins   Quinolones          NA         NA        NA    NA     NA     NA     NA   0
3: -615873176 161009395  Cephalosporins    Penicillins             NA          NA           NA          NA         NA        NA    NA     NA     NA     NA   0
4: -616819481  36280536 Anti-infectives Cephalosporins     Macrolides  Quinolones           NA          NA         NA        NA    NA     NA     NA     NA   1
5: -625709819 720290063 Anti-infectives Cephalosporins     Ethambutol   Isoniazid Pyrazinamide  Quinolones  Rifamycin        NA    NA     NA     NA     NA   0
6: -637094857 720918635 Anti-infectives    Penicillins     Quinolones          NA           NA          NA         NA        NA    NA     NA     NA     NA   0
</code>```

I've tried both of these (but am still learning how to decipher warning messages so those don't help much, especially as I am new to data.table):

```<code>> d1$correct<-ifelse(d1[,c(3:14)]=="Macrolides" | d1[,c(3:14)]=="Cephalosporins", 1, 0)
Warning messages:
1: In `[<-.data.table`(x, j = name, value = value) :
  12 column matrix RHS of := will be treated as one vector
2: In `[<-.data.table`(x, j = name, value = value) :
  Supplied 56868 items to be assigned to 4739 items of column 'correct' (52129 unused)
>
>
> selected_cols<-c("drug1", "drug2", "drug3", "drug4", "drug5", "drug6", "drug7", "drug8", "drug9", "drug10", "drug11", "drug12")
> d1$correct<-ifelse(d1 %in% selected_cols=="Macrolides" | d1 %in% selected_cols=="Cephalosporins", 1, 0)
Warning message:
In `[<-.data.table`(x, j = name, value = value) :
  Supplied 16 items to be assigned to 4739 items of column 'correct' (recycled leaving remainder of 3 items).
</code>```

The closest I've gotten is this:

```<code>d1$correct<-apply(d1, 1, function(r) any(r %in% c("Macrolides", "Cephalosporins")))
</code>```

Which will give TRUE if either of those is true across columns, but I can't figure out how to do it if both of those is true across columns. I'd prefer to not have to use a stunningly massive ifelse statement, since I have 12 columns and more combinations I'll need to make, and the NA's throw it off anyway.

I'd love a dplyr or data.table solution since those are so elegant, but at this point I'm desperate.

答:
This should work:</p>

```<code>d1$correct<-apply(d1, 1, function(r) { any(r =="Macrolides") & any(r == "Cephalosporins") })
</code>```

Body:
I have a data.table and I'm trying to create a new column by checking to see if a row has particular values in any of a given set of columns.

head(d1)

   MEDREC_KEY   pat_key           drug1          drug2          drug3       drug4        drug5       drug6      drug7     drug8 drug9 drug10 drug11 drug12
1: -140665983 669723105 Anti-infectives Cephalosporins     Ethambutol   Isoniazid   Macrolides Penicillins Quinolones Rifamycin    NA     NA     NA     NA
2: -606290573  85924804 Anti-infectives   Beta-lactams Cephalosporins Penicillins   Quinolones          NA         NA        NA    NA     NA     NA     NA
3: -615873176 161009395  Cephalosporins    Penicillins             NA          NA           NA          NA         NA        NA    NA     NA     NA     NA
4: -616819481  36280536 Anti-infectives Cephalosporins     Macrolides  Quinolones           NA          NA         NA        NA    NA     NA     NA     NA
5: -625709819 720290063 Anti-infectives Cephalosporins     Ethambutol   Isoniazid Pyrazinamide  Quinolones  Rifamycin        NA    NA     NA     NA     NA
6: -637094857 720918635 Anti-infectives    Penicillins     Quinolones          NA           NA          NA         NA        NA    NA     NA     NA     NA

What I want to happen is if any of the "drug" columns == "Macrolides" AND any of the same columns == "Cephalosporins" then my new column, "correct" == 1 otherwise "correct" == 0 (or it could be logical), like so:

head(d1)
   MEDREC_KEY   pat_key           drug1          drug2          drug3       drug4        drug5       drug6      drug7     drug8 drug9 drug10 drug11 drug12 correct
1: -140665983 669723105 Anti-infectives Cephalosporins     Ethambutol   Isoniazid   Macrolides Penicillins Quinolones Rifamycin    NA     NA     NA     NA   1
2: -606290573  85924804 Anti-infectives   Beta-lactams Cephalosporins Penicillins   Quinolones          NA         NA        NA    NA     NA     NA     NA   0
3: -615873176 161009395  Cephalosporins    Penicillins             NA          NA           NA          NA         NA        NA    NA     NA     NA     NA   0
4: -616819481  36280536 Anti-infectives Cephalosporins     Macrolides  Quinolones           NA          NA         NA        NA    NA     NA     NA     NA   1
5: -625709819 720290063 Anti-infectives Cephalosporins     Ethambutol   Isoniazid Pyrazinamide  Quinolones  Rifamycin        NA    NA     NA     NA     NA   0
6: -637094857 720918635 Anti-infectives    Penicillins     Quinolones          NA           NA          NA         NA        NA    NA     NA     NA     NA   0

I've tried both of these (but am still learning how to decipher warning messages so those don't help much, especially as I am new to data.table):

> d1$correct<-ifelse(d1[,c(3:14)]=="Macrolides" | d1[,c(3:14)]=="Cephalosporins", 1, 0)
Warning messages:
1: In `[<-.data.table`(x, j = name, value = value) :
  12 column matrix RHS of := will be treated as one vector
2: In `[<-.data.table`(x, j = name, value = value) :
  Supplied 56868 items to be assigned to 4739 items of column 'correct' (52129 unused)
>
>
> selected_cols<-c("drug1", "drug2", "drug3", "drug4", "drug5", "drug6", "drug7", "drug8", "drug9", "drug10", "drug11", "drug12")
> d1$correct<-ifelse(d1 %in% selected_cols=="Macrolides" | d1 %in% selected_cols=="Cephalosporins", 1, 0)
Warning message:
In `[<-.data.table`(x, j = name, value = value) :
  Supplied 16 items to be assigned to 4739 items of column 'correct' (recycled leaving remainder of 3 items).

The closest I've gotten is this:

d1$correct<-apply(d1, 1, function(r) any(r %in% c("Macrolides", "Cephalosporins")))

Which will give TRUE if either of those is true across columns, but I can't figure out how to do it if both of those is true across columns. I'd prefer to not have to use a stunningly massive ifelse statement, since I have 12 columns and more combinations I'll need to make, and the NA's throw it off anyway.

I'd love a dplyr or data.table solution since those are so elegant, but at this point I'm desperate.

Body:
This should work:

d1$correct<-apply(d1, 1, function(r) { any(r =="Macrolides") & any(r == "Cephalosporins") })


问:
Proper way to store shared class variables?
A somewhat simple question, but I'd like some help understanding exactly how classes work in Python. Specifically, when are class variables set, and are they overwritten every time an instance of that class is created?

Here is the general situation. I have a table of data that I would like all instances of a certain class to be able to access. The problem is that this table sits on a database server. I want to connect to the database automatically and retrieve this table into memory the first time a instance of this class is created, but not any time after that.

It seems like a class variable would work, but I just wanted to verify that this would be the case. My program is going to be creating hundreds of instances of this class so I definitely don't want to be accidentally making hundreds of database calls for the same table or storing hundreds of copies of the same table in memory.

Would I be able to write something like the following? Assume that "get_table_from_db" is a function that connects to a database and returns a pandas dataframe with the relevant table.

```<code>class ExampleClass:
    table1 = get_table_from_db(arguments)
    def __init__(self, x, y):
        self.value = self.table1.iloc[x, y]

obj1 = ExampleClass(0, 0)
obj2 = ExampleClass(0, 1)
</code>```

Basically, when I run this script, I want to run "get_table_from_db" once, either before or when obj1 is created and store the relevant dataframe to table1. When obj2 is created, I do not want to call "get_table_from_db" again because table1 already exists. However, I still want it to have access to table1 for some of its methods because it will need that data available to it (as an example, I assigned self.value equal to a specific cell in the table, but my actual code is going to be more complicated than that).

Also, a similar question. If the above method works, can I then reset a class variable from within the class? For example, will something like the following allow me to modify (and by modify I mean redownload) the class variable for all instances of the class?

```<code>class ExampleClass:
    table1 = get_table_from_db(arguments)
    def __init__(self, x, y):
        self.value = self.table1.iloc[x, y]
    def reset_table(self):
        ExampleClass.table1 = get_table_from_db(arguments)
</code>```

答:
The class variable will be initialized once, when the class is declared (so before either obj1 or obj2 are created), so your code will work the way you think.

With regards to your second question, you should do it like this:

```<code>class ExampleClass:
    @classmethod
    def reset_table(cls):
        cls.table1 = get_table_from_db(arguments)
</code>```

That way you can call either obj.reset_table() or ExampleClass.reset_table() without needing an instance of ExampleClass.

Body:
A somewhat simple question, but I'd like some help understanding exactly how classes work in Python. Specifically, when are class variables set, and are they overwritten every time an instance of that class is created?

Here is the general situation. I have a table of data that I would like all instances of a certain class to be able to access. The problem is that this table sits on a database server. I want to connect to the database automatically and retrieve this table into memory the first time a instance of this class is created, but not any time after that.

It seems like a class variable would work, but I just wanted to verify that this would be the case. My program is going to be creating hundreds of instances of this class so I definitely don't want to be accidentally making hundreds of database calls for the same table or storing hundreds of copies of the same table in memory.

Would I be able to write something like the following? Assume that "get_table_from_db" is a function that connects to a database and returns a pandas dataframe with the relevant table.

class ExampleClass:
    table1 = get_table_from_db(arguments)
    def __init__(self, x, y):
        self.value = self.table1.iloc[x, y]

obj1 = ExampleClass(0, 0)
obj2 = ExampleClass(0, 1)

Basically, when I run this script, I want to run "get_table_from_db" once, either before or when obj1 is created and store the relevant dataframe to table1. When obj2 is created, I do not want to call "get_table_from_db" again because table1 already exists. However, I still want it to have access to table1 for some of its methods because it will need that data available to it (as an example, I assigned self.value equal to a specific cell in the table, but my actual code is going to be more complicated than that).

Also, a similar question. If the above method works, can I then reset a class variable from within the class? For example, will something like the following allow me to modify (and by modify I mean redownload) the class variable for all instances of the class?

class ExampleClass:
    table1 = get_table_from_db(arguments)
    def __init__(self, x, y):
        self.value = self.table1.iloc[x, y]
    def reset_table(self):
        ExampleClass.table1 = get_table_from_db(arguments)

Body:
The class variable will be initialized once, when the class is declared (so before either obj1 or obj2 are created), so your code will work the way you think.

With regards to your second question, you should do it like this:

class ExampleClass:
    @classmethod
    def reset_table(cls):
        cls.table1 = get_table_from_db(arguments)

That way you can call either obj.reset_table() or ExampleClass.reset_table() without needing an instance of ExampleClass.


问:
Laravel Eloquent limit results for relationship
I have a simple set-up of Albums and Images, each album has many images. I can get all the data fine but I want to limit the returned number of images to 3. I have tried passing a closure like so:

```<code>Album::with(['images' =>  function($query) { $query->take(3);}])->get();
</code>```

This does limit the number of images to 3 but it limits the total count of images to 3 but I want to limit each album to 3 images. So the first album will show 3 images as expected but all the other albums have no images.

I have tried adding a new method to my model like so:

```<code>public function limitImages()
{
    return $this->hasMany('App\Image')->limit(3);
}
</code>```

And I call this in my controller:

```<code>Album::with('limitImages')->get();
</code>```

But this doesn't limit the image count returned at all

答:
I feel you'd quickly run into an N+1 issue trying to accomplish this.  Just do it in the collection that it returns:</p>

```<code>Album::with('images')->get()->map(function($album) {
    $album->setRelation('images', $album->images->take(3));
    return $album;
});
</code>```

Body:
I have a simple set-up of Albums and Images, each album has many images. I can get all the data fine but I want to limit the returned number of images to 3. I have tried passing a closure like so:

Album::with(['images' =>  function($query) { $query->take(3);}])->get();

This does limit the number of images to 3 but it limits the total count of images to 3 but I want to limit each album to 3 images. So the first album will show 3 images as expected but all the other albums have no images.

I have tried adding a new method to my model like so:

public function limitImages()
{
    return $this->hasMany('App\Image')->limit(3);
}

And I call this in my controller:

Album::with('limitImages')->get();

But this doesn't limit the image count returned at all

Body:
I feel you'd quickly run into an N+1 issue trying to accomplish this.  Just do it in the collection that it returns:

Album::with('images')->get()->map(function($album) {
    $album->setRelation('images', $album->images->take(3));
    return $album;
});


问:
Click other element same as click this element
Sorry for the title may seem confusing.

i have 2 element. with no relation like parent or child.

```<code><div class="alpha"></div>
<div class="beta"></div>
</code>```

The class=alpha have event, if we click it's, there is will be a fade in or fade out element (which is done by jQuery).

now i want to make simulation like. if we click class="beta" it will be the same as we click class="beta".

more details is like if we click beta the alpha will show it's fadein fadeout effect :)

how we can make it?

many thanks

答:
now i want to make simulation like. if we click class="beta" it will be the same as we click class="beta".

Not 100% sure what you mean with that. My guess is what you want is...

```<code>$('.alpha').click(function() { $('.beta').click(); });
</code>```

Body:
Sorry for the title may seem confusing.

i have 2 element. with no relation like parent or child.

The class=alpha have event, if we click it's, there is will be a fade in or fade out element (which is done by jQuery).

now i want to make simulation like. if we click class="beta" it will be the same as we click class="beta".

more details is like if we click beta the alpha will show it's fadein fadeout effect :)

how we can make it?

many thanks

Body:
now i want to make simulation like. if we click class="beta" it will be the same as we click class="beta".

Not 100% sure what you mean with that. My guess is what you want is...

$('.alpha').click(function() { $('.beta').click(); });


问:
Require program to run as admin
How can I check if my program is running as an administrator on a Windows 7 system, using C?

In batch I could do something along the lines of:

```<code>whoami /groups | findstr /b /c:"Mandatory Label\High Mandatory Level" | findstr /c:"Enabled group" > nul: && set IS_ELEVATED=1
    if %IS_ELEVATED%==0 (
        set /p _="You need to run Utilis as administrator, run with admin cmd. Press enter to exit..
    )
</code>```

This will check if the current user is an administrator or not. How can I achieve the same concept in C?

答: I suggest that if you set the executable's properties and permissions, so that it can only be run by administrator, that could solve the problem.

Title: Require program to run as admin

Body:
How can I check if my program is running as an administrator on a Windows 7 system, using C?

In batch I could do something along the lines of:

whoami /groups | findstr /b /c:"Mandatory Label\High Mandatory Level" | findstr /c:"Enabled group" > nul: && set IS_ELEVATED=1
    if %IS_ELEVATED%==0 (
        set /p _="You need to run Utilis as administrator, run with admin cmd. Press enter to exit..
    )

This will check if the current user is an administrator or not. How can I achieve the same concept in C?


问:
Converting several files with Multiprocessing in python
I have seeked for an answer on this site but didn't find out. My problem is that I want to convert several files from a format to another in python. I would like to convert 4 files simultaneously. I have already made a code with process keyword from the multiprocessing library, it works, but it uses several processes to convert files one by one, which is not what I want. I tried to convert them simultaneously with this code:

```<code>def convert_all_files (directoryName):
  directoryName = r'Here I set my directory name C:\...'
  files2=[]
  pool=mp.Pool(4)
  for path, dirs, files in os.walk(directoryName):
    for f in files:
      f1=f
      path1=path
      files2.append((path1,f1))
  for j in range(0, len(files2)):
    pool.apply_async(convert, (files2[j][0],files2[j][1]))
  pool.close()
  pool.join()
</code>```

My problem is that the code runs, but the function convert is not executed, and the code freezes at the line pool.join() (I use this technique to gain a lot of time because conversion is very long, and when I run this code, the conversion is instantaneous and doesn't work.)

I use the function defined above in another file. I import my module and call the function.

Does anyone has an Idea?
thanks

答:
Here is a working solution, without the limitations of 4 conversion at the same time.

```<code>def convert_all_files(directoryName):
    for folder, subs, files in os.walk(directoryName):
        for filename in files:
            p = Process(target=convert, args=(folder, filename))
            p.start()
</code>```

If you need the limitation, here is a solution, but I am not sure this is the best:

```<code>def convert_all_files(directoryName):
    process_count = 0
    for folder, subs, files in os.walk(directoryName):
        for filename in files:
            p = Process(target=convert, args=(folder, filename))
            p.start()

            # Maybe not the better way to handle it
            process_count = process_count + 1
            if process_count % 4 == 0:
                p.join()
</code>```

Body:
I have seeked for an answer on this site but didn't find out. My problem is that I want to convert several files from a format to another in python. I would like to convert 4 files simultaneously. I have already made a code with process keyword from the multiprocessing library, it works, but it uses several processes to convert files one by one, which is not what I want. I tried to convert them simultaneously with this code:

def convert_all_files (directoryName):
  directoryName = r'Here I set my directory name C:\...'
  files2=[]
  pool=mp.Pool(4)
  for path, dirs, files in os.walk(directoryName):
    for f in files:
      f1=f
      path1=path
      files2.append((path1,f1))
  for j in range(0, len(files2)):
    pool.apply_async(convert, (files2[j][0],files2[j][1]))
  pool.close()
  pool.join()

My problem is that the code runs, but the function convert is not executed, and the code freezes at the line pool.join() (I use this technique to gain a lot of time because conversion is very long, and when I run this code, the conversion is instantaneous and doesn't work.)

I use the function defined above in another file. I import my module and call the function.

Does anyone has an Idea?
thanks

Body:
Here is a working solution, without the limitations of 4 conversion at the same time.

def convert_all_files(directoryName):
    for folder, subs, files in os.walk(directoryName):
        for filename in files:
            p = Process(target=convert, args=(folder, filename))
            p.start()

If you need the limitation, here is a solution, but I am not sure this is the best:

def convert_all_files(directoryName):
    process_count = 0
    for folder, subs, files in os.walk(directoryName):
        for filename in files:
            p = Process(target=convert, args=(folder, filename))
            p.start()

            # Maybe not the better way to handle it
            process_count = process_count + 1
            if process_count % 4 == 0:
                p.join()


问:
Using async/await + Bluebird to promisifyAll
I'm constructing a library that uses async/await, and I would like to know if it is possible to use native modules like fs with the async/await. I know that async/await it's just Promises in the background, so is there a native way to promisify a method or function? Currently I'm using the Bluebird, but I don't know if it's a bad pattern.

Example:

    const Bluebird = require("bluebird");
    const { access } = require("fs");

    const accessAsync = Bluebird.promisify(access);

    async function checkInput(options) {
      await accessAsync(options.file);
      /// etc
      return options;
    }

    module.exports = (options) => {
      Promise.resolve(options)
        .then(checkInput)
    };
```

I'm combining both native Promises and Bluebird. Should I only use Bluebird?

答:
By all means, Bluebird is designed to work with native promises. The use case you describe is not only supported - but is a design goal of Bluebird.

Bluebird's promises implement then according to the Promises/A+ specification, which is guaranteed to work with await. Moreover, you can pass native promises to Bluebird and it'll work just fine.

Body:
I'm constructing a library that uses async/await, and I would like to know if it is possible to use native modules like fs with the async/await. I know that async/await it's just Promises in the background, so is there a native way to promisify a method or function? Currently I'm using the Bluebird, but I don't know if it's a bad pattern.

Example:

    const Bluebird = require("bluebird");
    const { access } = require("fs");

    const accessAsync = Bluebird.promisify(access);

    async function checkInput(options) {
      await accessAsync(options.file);
      /// etc
      return options;
    }

    module.exports = (options) => {
      Promise.resolve(options)
        .then(checkInput)
    };

I'm combining both native Promises and Bluebird. Should I only use Bluebird?


问:
extjs 4 - set horizontal scrolling to tbar in grid panel
I need to set horizontal scrolling to an ExtJS tbar which contains buttons in a row that are not visible in the end. Following is the code.

```<code>Ext.define('myProject.view.accounts.user.UserGrid', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.usergrid',
    minHeight: 400,
    margin: '0,5,0,5',
    title: 'User Accounts',
    region: 'center',
    cls: 'grid-with-footer',
    scroll: 'vertical',
    bind: {
        ...
    },
    initComponent: function() {
        ...
        Ext.applyIf(me, {
            columns: [{
                ...
            }],

            features: [{
                ...
            }],

            tbar: [{ // <-- this should be horizontally scrollable.
                ...
            }],

            bbar: {
                ...
            }
        });
        this.callParent();
    }
});
</code>```

(I'm using ExtJS 4.2.1)

答:
Instead of using tbar, you can add it as a dockedItem, which allows for more configs

```<code>dockedItems: [{
        xtype: 'toolbar',
        dock: 'top',
        overflowX: 'scroll', // <---- This allows horizontal scroll
        items: [
             .....
        ]
    }]
</code>```

You can view this in a fiddle here

(edit: fiddle was in ExtJS 6.2 instead of 4.2, whoops)

Body:
I need to set horizontal scrolling to an ExtJS tbar which contains buttons in a row that are not visible in the end. Following is the code.

Ext.define('myProject.view.accounts.user.UserGrid', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.usergrid',
    minHeight: 400,
    margin: '0,5,0,5',
    title: 'User Accounts',
    region: 'center',
    cls: 'grid-with-footer',
    scroll: 'vertical',
    bind: {
        ...
    },
    initComponent: function() {
        ...
        Ext.applyIf(me, {
            columns: [{
                ...
            }],

            features: [{
                ...
            }],

            tbar: [{ // <-- this should be horizontally scrollable.
                ...
            }],

            bbar: {
                ...
            }
        });
        this.callParent();
    }
});

(I'm using ExtJS 4.2.1)

Body:
Instead of using tbar, you can add it as a dockedItem, which allows for more configs

dockedItems: [{
        xtype: 'toolbar',
        dock: 'top',
        overflowX: 'scroll', // <---- This allows horizontal scroll
        items: [
             .....
        ]
    }]

You can view this in a fiddle here

(edit: fiddle was in ExtJS 6.2 instead of 4.2, whoops)


问:
How to center vertically an absolutely positioned scaled element?
Without scale code works fine, but I need to center vertically an already scaled element. I am looking for solution using CSS or JS approaches.
Also I can not use transform-origin CSS property because it's unsupported in some browsers that  I need to support...

https://jsfiddle.net/o62ja9r6/17/

.container {
  position: fixed;
  border: 2px dashed blue;
  width: 400px;
  height: 300px;
}

.slide {
  position: absolute;
  width: 76px;
  height: 169px;
  background-color: red;
}

.vertical-center {
  top: 50%;
  transform: scale(0.4) translateY(-50%);
  /* transform: translateY(-50%);  // <--- it works */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="slide vertical-center">
  </div>
</div></code>```

答:
Instead of translate you can use simple CSS for this

```<code>.vertical-center {
  top: 0;
  left:0px;
  bottom:0px;
  right:0px;
  margin: auto;
  transform:  scale(0.4);
}
</code>```

for working demo click here

Body:
Instead of translate you can use simple CSS for this

.vertical-center {
  top: 0;
  left:0px;
  bottom:0px;
  right:0px;
  margin: auto;
  transform:  scale(0.4);
}

for working demo click here


问:
C++ behaviour when const
Here's a basic struct (I hope)

```<code>struct SomeType {
    float a;
    float b;
    float c;
    float d;

    SomeType(float, float, float, float);
};
</code>```

And source

```<code>SomeType::SomeType(float na, float nb, float nc, float nd) : a(na), b(nb), c(nc), d(nd) {}
</code>```

The I have a class

```<code>struct SomeClass {
    static const SomeType v;

    SomeClass();
};
</code>```

When I then initialise it

```<code>const SomeType SomeClass::v(0,0,0,0);
</code>```

My vales become inf or nan or -nan. Anyone seen this before, or know how to fix it?

Edit: Fixed type

Edit: This is quite close to my original example. I multiple classes with similar structure to SomeClass.

答:
Though I didn’t reproduce that exact behavior, the initialization doesn’t specify the type. It should be:

```<code>const SomeType SomeClass::v(0, 0, 0, 0);
</code>```

After doing this, it works fine.

Title: C++ behaviour when const

Body:
Here's a basic struct (I hope)

struct SomeType {
    float a;
    float b;
    float c;
    float d;

    SomeType(float, float, float, float);
};

And source

SomeType::SomeType(float na, float nb, float nc, float nd) : a(na), b(nb), c(nc), d(nd) {}

The I have a class

struct SomeClass {
    static const SomeType v;

    SomeClass();
};

When I then initialise it

const SomeType SomeClass::v(0,0,0,0);

My vales become inf or nan or -nan. Anyone seen this before, or know how to fix it?

Edit: Fixed type

Edit: This is quite close to my original example. I multiple classes with similar structure to SomeClass.

Body:
Though I didn’t reproduce that exact behavior, the initialization doesn’t specify the type. It should be:

const SomeType SomeClass::v(0, 0, 0, 0);

After doing this, it works fine.


问:
Multiple procedures in Oracle SQL Excel VBA
Excel version: 2013

SQL Oracle with ADODB

I am rather new to ADODB and SQL. I have the following code:

```<code>objMyCmd.CommandText = "begin " & Chr(10) & _
"scheme1.function1(to_date('2017.01.01','YYYY-MM-DD'), to_date('2017.03.01','YYYY-MM-DD'),'ALEX'); " & Chr(10) & "commit; " & Chr(10) & "end; "

objMyCmd.CommandType = adCmdText

objMyCmd.Execute

objMyCmd.CommandText = "SELECT * from table1"

objMyCmd.CommandType = adCmdText

objMyCmd.Execute
</code>```

The code in SQL interpretator would look like this:

```<code>begin
scheme1.function1(to_date('2017.01.01','YYYY-MM-DD'),to_date('2017.03.01','YYYY-MM-DD'),'ALEX');
commit;
end;

SELECT * from table1
</code>```

When running the 2nd objMyCmd.Execute I get:

[Oracle][ODBC][Ora]ORA-00903: invalid table name

I guess the problem arises from combining the first and the second procedures in a single objMyCmd.CommandText.

Please, help me solve this problem and make a VBA script work correctly.

答:
Is this table in your schema?
If no - is there a public synonym ?
Try schema.table1
Maybe there is no public synonym.</p>

Body:
Excel version: 2013

SQL Oracle with ADODB

I am rather new to ADODB and SQL. I have the following code:

objMyCmd.CommandText = "begin " & Chr(10) & _
"scheme1.function1(to_date('2017.01.01','YYYY-MM-DD'), to_date('2017.03.01','YYYY-MM-DD'),'ALEX'); " & Chr(10) & "commit; " & Chr(10) & "end; "

objMyCmd.CommandType = adCmdText

objMyCmd.Execute

objMyCmd.CommandText = "SELECT * from table1"

objMyCmd.CommandType = adCmdText

objMyCmd.Execute

The code in SQL interpretator would look like this:

begin
scheme1.function1(to_date('2017.01.01','YYYY-MM-DD'),to_date('2017.03.01','YYYY-MM-DD'),'ALEX');
commit;
end;

SELECT * from table1

When running the 2nd objMyCmd.Execute I get:

[Oracle][ODBC][Ora]ORA-00903: invalid table name

I guess the problem arises from combining the first and the second procedures in a single objMyCmd.CommandText.

Please, help me solve this problem and make a VBA script work correctly.


问:
Rest API security for mobile apps
I'm in the process of designing a mobile application that will need to connect to a server-side process for its business logic and data transactions.  I'm writing my server-side code in Java using Spring Boot and I intend to create a Rest API in order for the mobile app to connect to the server.

I'm just doing some research at the moment for the best way to secure the connection between mobile app and server.  What I'd like to do is allow the user on the mobile app to log in once they open the app and for them to use the app for as long as they like and for their access to time out after a period of inactivity.

Can anyone recommend any very simple reading on this?  I've looked at OAuth2 but that appears to be for logging into web services using another account (like Google, GitHub, etc).

Would it be acceptable to login over https (SSL) by passing username and password to a rest endpoint and returning some sort of token (a GUID?).  Then have the client (mobile app) pass that GUID with each subsequent call so the server can verify the call?  Is it better to just do everything over SSL in this scenario?

I have done a fair bit of research but I don't seem to be able to find anything that quite matches what I'm trying to do.

Hope someone can help

Thanks

答:
Thanks again for these replies.  I've been implementing my service to run under https by using server.ssl.key-store parameters and it looks like it's working okay.  I have used keytool.exe to create a trust store and I run my SpringBoot app (with Tomcat embedded) using that trust store. I can open a browser to my REST endpoint (using https this time, not http), the browser asks for authentication and when I enter my user details, it matches them against my db user and allows me to see the response from the server.

One question though, what's the point of having a trust store on the server side (Java) if I can just access the REST endpoint using any old browser and just enter my user name and password?  Eventually, this REST endpoint won't be accessed via a browser, it'll be accessed using a mobile app programmatically, so I assume I'll be logging on using that with username and password over https.  I thought I'd need to have a certificate of some sort on the client side in order to communicate or does it not work like this?

Thanks again

Title: Rest API security for mobile apps


问:
Preprocessing categorical data already converted into numbers
I'm fairly new to machine learning, so I don't know the correct terminology, but I converted two categorical columns into numbers the following way. These columns are part of my features inputs, akin to the  sex column in the titanic database.
(They are not the target data y which I have already created)

```<code>                           changed  p_changed
Date
2010-02-17   0.477182        0          0
2010-02-18   0.395813        0          0
2010-02-19   0.252179        1          1
2010-02-22   0.401321        0          1
2010-02-23   0.519375        1          1
</code>```

Now the rest of my data Xlooks something like this

```<code>          Open  High   Low  Close    Volume  Adj Close  log_return  \
Date
2010-02-17  2.07  2.07  1.99   2.03  219700.0       2.03   -0.019513
2010-02-18  2.03  2.03  1.99   2.03  181700.0       2.03    0.000000
2010-02-19  2.03  2.03  2.00   2.02  116400.0       2.02   -0.004938
2010-02-22  2.05  2.05  2.02   2.04  188300.0       2.04    0.009852
2010-02-23  2.05  2.07  2.01   2.05  255400.0       2.05    0.004890

            close_open  Daily_Change  30_Avg_Vol  20_Avg_Vol  15_Avg_Vol  \
Date
2010-02-17        0.00         -0.04    0.909517    0.779299    0.668242
2010-02-18        0.00          0.00    0.747470    0.635404    0.543015
2010-02-19        0.00         -0.01    0.508860    0.417706    0.348761
2010-02-22        0.03         -0.01    0.817274    0.666903    0.562414
2010-02-23        0.01          0.00    1.078411    0.879007    0.742730
</code>```

As you can see the rest of my data is continuous (containing many variables) as opposed to the two categorical columns which only have two values (0 and 1).

I was planning to preprocess all this data in one shot via this simple preprocess method

```<code>X_scaled = preprocessing.scale(X)
</code>```

I was wondering if this is mistake? Is there something else I need to do to the categorical values before using this simple preprocessing?

EDIT: I tried two ways; First I  tried scaling the full data, including the categorical data converted to 1's and 0's.

```<code>Full_X = OPK_df.iloc[:-5, 0:-5]
Full_X_scaled = preprocessing.scale( Full_X)   # First way, which scales everything in one shot.
</code>```

Then I tried dropping the last two columns, scaling, then adding the dropped columns via this code.

```<code>X =OPK_df.iloc[:-5, 0:-7]   # Here I'm dropping both -7 while originally the offset was only till -5, which means two extra columns were dropped.
</code>```

I created another dataframe which has those two columns I dropped

```<code> x2 =OPK_df.iloc[:-5, -7:-5]
 x2 = np.array(x2)   # convert it to an array

 # preprocessing the data without last two columns
   from sklearn import preprocessing
   X_scaled = preprocessing.scale(X)

# Then concact the X_scaled with x2(originally dropped columns)

   X =np.concatenate((X_scaled, x2), axis =1)

    #Creating a classifier

from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=5)
knn2 = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_scaled, y)
knn2.fit(X,y)

knn.score(Full_X_scaled, y)

0.71396522714526078

knn2.score(X, y)

0.71789119461581608
</code>```

So there is a higher score when I do indeed drop the two columns during standarization.

答:
You're doing pretty well so far.  Do not scale your classification data.  Since those appear to be binary classifications, think of this as "Yes" and "No".  What does it mean to scale these?

Even worse, consider that you might have classifications such as flower types: you've coded Zinnia=0, Rose=1, Orchid=2, etc.  What does it meant to scale those?  It doesn't make any sense to re-code these as Zinnia=-0.257, Rose=+0.448, etc.

Scaling your input data is the necessary part: it keeps the values within comparable ranges (mathematical influence), allowing you to readily use a single treatment for your loss function.  Otherwise, the feature with the largest spread of values would have the greatest influence on training, until your model's weights learned how to properly discount the large values.

For your beginning explorations, don't do any other preprocessing: just scale the input data and start your fitting exercises.

Body:
I'm fairly new to machine learning, so I don't know the correct terminology, but I converted two categorical columns into numbers the following way. These columns are part of my features inputs, akin to the  sex column in the titanic database.
(They are not the target data y which I have already created)

                           changed  p_changed
Date
2010-02-17   0.477182        0          0
2010-02-18   0.395813        0          0
2010-02-19   0.252179        1          1
2010-02-22   0.401321        0          1
2010-02-23   0.519375        1          1

Now the rest of my data Xlooks something like this

          Open  High   Low  Close    Volume  Adj Close  log_return  \
Date
2010-02-17  2.07  2.07  1.99   2.03  219700.0       2.03   -0.019513
2010-02-18  2.03  2.03  1.99   2.03  181700.0       2.03    0.000000
2010-02-19  2.03  2.03  2.00   2.02  116400.0       2.02   -0.004938
2010-02-22  2.05  2.05  2.02   2.04  188300.0       2.04    0.009852
2010-02-23  2.05  2.07  2.01   2.05  255400.0       2.05    0.004890

            close_open  Daily_Change  30_Avg_Vol  20_Avg_Vol  15_Avg_Vol  \
Date
2010-02-17        0.00         -0.04    0.909517    0.779299    0.668242
2010-02-18        0.00          0.00    0.747470    0.635404    0.543015
2010-02-19        0.00         -0.01    0.508860    0.417706    0.348761
2010-02-22        0.03         -0.01    0.817274    0.666903    0.562414
2010-02-23        0.01          0.00    1.078411    0.879007    0.742730

As you can see the rest of my data is continuous (containing many variables) as opposed to the two categorical columns which only have two values (0 and 1).

I was planning to preprocess all this data in one shot via this simple preprocess method

X_scaled = preprocessing.scale(X)

I was wondering if this is mistake? Is there something else I need to do to the categorical values before using this simple preprocessing?

EDIT: I tried two ways; First I  tried scaling the full data, including the categorical data converted to 1's and 0's.

Full_X = OPK_df.iloc[:-5, 0:-5]
Full_X_scaled = preprocessing.scale( Full_X)   # First way, which scales everything in one shot.

Then I tried dropping the last two columns, scaling, then adding the dropped columns via this code.

X =OPK_df.iloc[:-5, 0:-7]   # Here I'm dropping both -7 while originally the offset was only till -5, which means two extra columns were dropped.

I created another dataframe which has those two columns I dropped

 x2 =OPK_df.iloc[:-5, -7:-5]
 x2 = np.array(x2)   # convert it to an array

 # preprocessing the data without last two columns
   from sklearn import preprocessing
   X_scaled = preprocessing.scale(X)

# Then concact the X_scaled with x2(originally dropped columns)

   X =np.concatenate((X_scaled, x2), axis =1)

    #Creating a classifier

from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=5)
knn2 = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_scaled, y)
knn2.fit(X,y)

knn.score(Full_X_scaled, y)

0.71396522714526078

knn2.score(X, y)

0.71789119461581608

So there is a higher score when I do indeed drop the two columns during standarization.


问:
Object-oriented programming (python)
```<code>class Ammo(Thing):
    def __init__(self, name, weapon, quantity):
        self.name=name
        self.weapon=weapon
        self.quantity=quantity
    def get_quantity(self):
        return self.quantity
    def weapon_type(self):
        return self.weapon
    def remove_all():
        self.quantity=0

bow = Weapon('bow', 10, 20)
arrows = Ammo('arrow', bow, 5)
print(arrows.weapon_type())
</code>```

output of print(arrows.weapon_type()) is supposed to be bow but I got <__main__.Weapon object at 0x10441f0b8> instead. How can I modify my code so that it returns bow?

Below is class Weapon:

```<code>import random
class Weapon(Thing):
    def __init__(self, name, min_dmg, max_dmg):
        self.name=name
        self.min_dmg=min_dmg
        self.max_dmg=max_dmg
    def min_damage(self):
        return self.min_dmg
    def max_damage(self):
        return self.max_dmg
    def damage(self):
        return random.randint(self.min_dmg,self.max_dmg)
</code>```

答:
I think the best way to do it would be overriding the str function in Weapon.

adding:

```<code>def __str__(self):
    return self.name
</code>```

to your weapon class should fix it.

Title: Object-oriented programming (python)

Body:
class Ammo(Thing):
    def __init__(self, name, weapon, quantity):
        self.name=name
        self.weapon=weapon
        self.quantity=quantity
    def get_quantity(self):
        return self.quantity
    def weapon_type(self):
        return self.weapon
    def remove_all():
        self.quantity=0

bow = Weapon('bow', 10, 20)
arrows = Ammo('arrow', bow, 5)
print(arrows.weapon_type())

output of print(arrows.weapon_type()) is supposed to be bow but I got <__main__.Weapon object at 0x10441f0b8> instead. How can I modify my code so that it returns bow?

Below is class Weapon:

import random
class Weapon(Thing):
    def __init__(self, name, min_dmg, max_dmg):
        self.name=name
        self.min_dmg=min_dmg
        self.max_dmg=max_dmg
    def min_damage(self):
        return self.min_dmg
    def max_damage(self):
        return self.max_dmg
    def damage(self):
        return random.randint(self.min_dmg,self.max_dmg)

Body:
I think the best way to do it would be overriding the str function in Weapon.

adding:

def __str__(self):
    return self.name

to your weapon class should fix it.


问:
How to install a package from a download zip file
I have download this package as a zip file.

Is it possible to install it from R console using this zip or unzip version to a specific path?

```<code>install.packages("C:/Users/Desktop/rvest-master.zip', lib='C:/R/R-3.2.1',repos = NULL)
</code>```

I type the previous command but is not working

```<code>> setwd("C:/Users/Desktop/")
> unzip("rvest-master.zip")
> file.rename("rvest-master", "rvest")
[1] TRUE
> shell("R CMD build rvest")
Warning messages:
1: running command ' /c R CMD build rvest' had status 127
2: In shell("R CMD build rvest") :
  'R CMD build rvest' execution failed with error code 127
> install.packages("rvest_0.2.0.9000.tar.gz", repos = NULL)
Installing package into ‘C:/Users/Documents/R/win-library/3.2’
(as ‘lib’ is unspecified)
Warning: invalid package 'rvest_0.2.0.9000.tar.gz'
Error: ERROR: no packages specified
Warning messages:
1: running command '"C:/R/R-3.2.1/bin/x64/R" CMD INSTALL -l "C:\Users\Documents\R\win-library\3.2" "rvest_0.2.0.9000.tar.gz"' had status 1
2: In install.packages("rvest_0.2.0.9000.tar.gz", repos = NULL) :
  installation of package ‘rvest_0.2.0.9000.tar.gz’ had non-zero exit status
</code>```

In the previous line are the results from the answer

答:
Download the package.tar.gz

Then from command line :

```<code>R CMD INSTALL package.tar.gz
</code>```

Body:
I have download this package as a zip file.

Is it possible to install it from R console using this zip or unzip version to a specific path?

install.packages("C:/Users/Desktop/rvest-master.zip', lib='C:/R/R-3.2.1',repos = NULL)

I type the previous command but is not working

> setwd("C:/Users/Desktop/")
> unzip("rvest-master.zip")
> file.rename("rvest-master", "rvest")
[1] TRUE
> shell("R CMD build rvest")
Warning messages:
1: running command ' /c R CMD build rvest' had status 127
2: In shell("R CMD build rvest") :
  'R CMD build rvest' execution failed with error code 127
> install.packages("rvest_0.2.0.9000.tar.gz", repos = NULL)
Installing package into ‘C:/Users/Documents/R/win-library/3.2’
(as ‘lib’ is unspecified)
Warning: invalid package 'rvest_0.2.0.9000.tar.gz'
Error: ERROR: no packages specified
Warning messages:
1: running command '"C:/R/R-3.2.1/bin/x64/R" CMD INSTALL -l "C:\Users\Documents\R\win-library\3.2" "rvest_0.2.0.9000.tar.gz"' had status 1
2: In install.packages("rvest_0.2.0.9000.tar.gz", repos = NULL) :
  installation of package ‘rvest_0.2.0.9000.tar.gz’ had non-zero exit status

In the previous line are the results from the answer

Body:
Download the package.tar.gz

Then from command line :

R CMD INSTALL package.tar.gz


问:
AdMob interstitial not showing What is wrong?
I am trying to add admob interstitial ads to my app but when I run my app no ad shows up. I just get a message in the logs saying :

<Google> To get test ads on this device, call: request.testDevices = @[ @« deviceID » ];

I'm pretty sure it knows im trying to show an add because of a previous error but it just won't appear.

here is my code( I added a print statement to the first part but it doesn't seem to take it into considiration ):

```<code>if interstitialad != nil {
            if interstitialad!.isReady {
                interstitialad?.present(fromRootViewController: self)

            }
        }
</code>```

here is the second part of the code ( note both are in ViewDidLoad )

```<code>if interstitialad != nil {
            if interstitialad!.isReady {
                interstitialad?.present(fromRootViewController: self)
            }
        }

        func createAndLoadInterstitial() -> GADInterstitial {
            let request = GADRequest()
            let interstitial = GADInterstitial(adUnitID: "unit id")
            //request.testDevices = ["iPhone test device ID"]
            //request.testDevices = ["simulator ID"]
            interstitial.delegate = self
            interstitial.load(request)
            return interstitial
        }
        interstitialad = createAndLoadInterstitial()
</code>```

What is wrong with this?
Thanks !

答:
You said you're trying to present your GADInterstitial in your viewDidLoad. This is not when you should be presenting your GADInterstitial. You need to give the GADInterstitial time to load the ad. Presenting an ad in your viewDidLoad is also against the AdMob TOS. You should be presenting the GADInterstitial during a transition/action in your application. You should also implement the GADInterstitial delegate methods so you know why the ad is failing to load, when it has actually loaded, and when the user has dismissed the ad so you can continue to transition them in your application.

Disallowed interstitial implementations

GADInterstitial Ad Events

Body:
I am trying to add admob interstitial ads to my app but when I run my app no ad shows up. I just get a message in the logs saying :

<Google> To get test ads on this device, call: request.testDevices = @[ @« deviceID » ];

I'm pretty sure it knows im trying to show an add because of a previous error but it just won't appear.

here is my code( I added a print statement to the first part but it doesn't seem to take it into considiration ):

if interstitialad != nil {
            if interstitialad!.isReady {
                interstitialad?.present(fromRootViewController: self)

            }
        }

here is the second part of the code ( note both are in ViewDidLoad )

if interstitialad != nil {
            if interstitialad!.isReady {
                interstitialad?.present(fromRootViewController: self)
            }
        }

        func createAndLoadInterstitial() -> GADInterstitial {
            let request = GADRequest()
            let interstitial = GADInterstitial(adUnitID: "unit id")
            //request.testDevices = ["iPhone test device ID"]
            //request.testDevices = ["simulator ID"]
            interstitial.delegate = self
            interstitial.load(request)
            return interstitial
        }
        interstitialad = createAndLoadInterstitial()

What is wrong with this?
Thanks !