问:
How to run scenarios of a feature file instead of feature files using testng
I have the testng file as below

```<code><test thread-count="5" name="Test" parallel="classes">
    <classes>
        <class name="com.cucumber.runners.smoketestcasesRunner1" />
        <class name="com.cucumber.runners.HRSmokeTestCasesRunner2" />
    </classes>
</test>
</code>```

and the runner file is as below

```<code>import org.testng.annotations.Test;
import cucumber.api.CucumberOptions;
import cucumber.api.testng.TestNGCucumberRunner;

@CucumberOptions(features = "smoketestcases.feature",glue = "com.cucumber.steps")

public class smoketestcasesRunner1 {
@Test
public void runCukes() {

    new TestNGCucumberRunner(getClass()).runCukes();

}

}
</code>```

which will run the feature files in parallel.  But i want to run the scenarios in parallel using testng not the feature files how to achieve it using testng

答:
Make sure you upgrade to the latest version of Cucumber.

Quoting the official documentation

Add a cucumber runner by extending the AbstractTestNGCucumberTests
  class and overriding the scenarios method in the parallel package
  (same name as step definition package) in src/test/java folder. Set
  the parallel option value to true for the DataProvider annotation.

package parallel;

import org.testng.annotations.DataProvider;
import io.cucumber.testng.AbstractTestNGCucumberTests;

public class RunCucumberTest extends AbstractTestNGCucumberTests{

    @Override
    @DataProvider(parallel = true)
    public Object[][] scenarios() {
        return super.scenarios();
    }
}
```

Read more from the documentation here

Body:
I have the testng file as below

<test thread-count="5" name="Test" parallel="classes">
    <classes>
        <class name="com.cucumber.runners.smoketestcasesRunner1" />
        <class name="com.cucumber.runners.HRSmokeTestCasesRunner2" />
    </classes>
</test>

and the runner file is as below

import org.testng.annotations.Test;
import cucumber.api.CucumberOptions;
import cucumber.api.testng.TestNGCucumberRunner;

@CucumberOptions(features = "smoketestcases.feature",glue = "com.cucumber.steps")

public class smoketestcasesRunner1 {
@Test
public void runCukes() {

    new TestNGCucumberRunner(getClass()).runCukes();

}

}

which will run the feature files in parallel.  But i want to run the scenarios in parallel using testng not the feature files how to achieve it using testng

Body:
Make sure you upgrade to the latest version of Cucumber.

Quoting the official documentation

Add a cucumber runner by extending the AbstractTestNGCucumberTests
  class and overriding the scenarios method in the parallel package
  (same name as step definition package) in src/test/java folder. Set
  the parallel option value to true for the DataProvider annotation.

package parallel;

import org.testng.annotations.DataProvider;
import io.cucumber.testng.AbstractTestNGCucumberTests;

public class RunCucumberTest extends AbstractTestNGCucumberTests{

    @Override
    @DataProvider(parallel = true)
    public Object[][] scenarios() {
        return super.scenarios();
    }
}

Read more from the documentation here


来源: stackexchange

问:
Learning WPF without success
Hello developers and designers,

I am very willing to learn WPF in which i use C# as the logic code.
Or i 'try' to anyway.

I have written a 2-page long code-behind in Forms-style though, so i know some syntaxes.
But that was a really cumbersome way of doing it.

The problem is that i am still lingering around the area of understanding at least the basic concept of object oriented programming. But 9 out of 10 times i am not getting the example-codes entirely because of that '1 little thing of which i don't even know what it's called'.
How do you even know if there is a command for the function you want to express and more importantly.... how it's called and where it located in what namespace?

Even the best video-examples aren't doing it for me, because when any code is typed, they never explain how the code exactly works. And most of the times it just doesn't even add up to what i know of logic code (of course i'm wrong).

In the early days i learned the Commodore64's Basic no problem.
Learning and writing Actionscript (Flash), within 2 months creating a 2D-shoot'em up
Learning and writing CMD, within 3 months writing 5000+ lines of code for all sorts of functions.

Why in Merlin's beard is WPF so hard?
Watching the "simplest" tutorial-video's are becoming more and more de-motivational.

Anyone recognizes this?

Thanks for reading,
Danny

答:
I don't think that WPF is actually that hard. I think it's just that WPF definitely requires a slightly different way of thinking. You can tell that it was built with certain principles in mind (like MVVM, as another poster mentioned), and it's very different from most other frameworks. If you try to do it like you did Windows Forms or MFC or ASP.NET or whatever... you'll struggle. You need to be willing to change your mind on how things work.

Frankly, I think the only way to learn it is with experimentation. Come up with some side project to work on using WPF and try your hand at it. Learn a bit and refactor it. Get a good book, read the WPF disciples list, read anything that Sacha Barber writes, read the WPF section here on SO.

When you have your first "ah ha!" moment where you decide to write an Attached Property to solve some obscure problem you're having, you'll know you've finally understood it :)

ContentLicense: CC BY-SA 3.0

Title: Learning WPF without success


问:
Angular5 - TypeError: Cannot read property 'template' of undefined
I have added EDIT, DELETE and DETAILS buttons to each row in mat-table using Angular material@5.0.0-rc.2.
All buttons are working but,
  * I am getting an error "Cannot read property 'template' of undefined" and
  * for each button click, everything is displaying on the same page

itemlist.component.html

```<code><mat-table #table [dataSource]="dataSource">
  <ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
    <mat-cell *matCellDef="let row"> {{row.name}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="description">
    <mat-header-cell *matHeaderCellDef> Description </mat-header-cell>
    <mat-cell *matCellDef="let row"> {{row.description}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="actions">
    <mat-cell *matCellDef="let row">
      <button mat-button (click)="showDetails(row)">DETAILS</button>
      <button mat-button (click)="editItem(row)">EDIT</button>
      <button mat-button (click)="deleteItem(row)">DELETE</button>
    </mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns:displayedColumns"></mat-row>
</mat-table>
</code>```

itemlist.component.ts

```<code>export class ItemListComponent {
  @Input() dataSource;
  displayedColumns = ['name', 'description', 'actions'];

  @Input() items: Item[];
  @Output() onEdit = new EventEmitter<Item>();
  @Output() onShow = new EventEmitter<Item>();
  @Output() onDelete = new EventEmitter<Item>();

  itemsTrackByFn = (index: string, item: Item) => item.id;

  showDetails(item: Item) {
    this.onShow.emit(item);
  }
  editItem(item: Item) {
    this.onEdit.emit(item)
  }
  deleteItem(item: Item) {
    this.onDelete.emit(item)
  }
}
</code>```

itemindex.component.html

```<code><app-item-list [dataSource]="dataSource"
              (onShow)="showItem($event)"
              (onDelete)="deleteItem($event)"
              (onEdit)="editItem($event)"
></app-item-list>
</code>```

itemindex.component.ts

```<code>export class ItemIndexComponent implements OnInit {
  items$: Observable<Item[]>;
  public dataSource: ItemsDatasource;

  constructor(public store: Store<fromRoot.State>, private router: Router){}

  ngOnInit() {
    this.items$ = this.store.select(fromItems.getAllItems);
    this.store.dispatch(new itemsActions.LoadAll());
    this.dataSource = new ItemsDatasource(this.items$);
  }

  editItem(item: Item) {
    this.store.dispatch(new itemsActions.SetCurrentItemId(item.id));
    this.router.navigate(['/items', item.id, 'edit'])
  }
  showItem(item: Item) {
    this.store.dispatch(new itemsActions.SetCurrentItemId(item.id));
    this.router.navigate(['/items', item.id])
  }
  deleteItem(item: Item) {
     this.store.dispatch(new itemsActions.Delete(item.id));
   }
 }
}

export class ItemsDatasource extends DataSource<Item> {

  public constructor(private items$: Observable<Item[]>) {
    super()
  }

  public connect(collectionViewer: CollectionViewer): Observable<Item[]> {
    return this.items$;
  }

  public disconnect(collectionViewer: CollectionViewer): void {}
}
</code>```

Any suggestion would be helpful

答:
I faced this error because, I forget to add th and td in
  ng-container

```<code><ng-container matColumnDef="actions">

</ng-container>
</code>```

Body:
I have added EDIT, DELETE and DETAILS buttons to each row in mat-table using Angular material@5.0.0-rc.2.
All buttons are working but,
  * I am getting an error "Cannot read property 'template' of undefined" and
  * for each button click, everything is displaying on the same page

itemlist.component.html

<mat-table #table [dataSource]="dataSource">
  <ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
    <mat-cell *matCellDef="let row"> {{row.name}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="description">
    <mat-header-cell *matHeaderCellDef> Description </mat-header-cell>
    <mat-cell *matCellDef="let row"> {{row.description}} </mat-cell>
  </ng-container>

  <ng-container matColumnDef="actions">
    <mat-cell *matCellDef="let row">
      <button mat-button (click)="showDetails(row)">DETAILS</button>
      <button mat-button (click)="editItem(row)">EDIT</button>
      <button mat-button (click)="deleteItem(row)">DELETE</button>
    </mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns:displayedColumns"></mat-row>
</mat-table>

itemlist.component.ts

export class ItemListComponent {
  @Input() dataSource;
  displayedColumns = ['name', 'description', 'actions'];

  @Input() items: Item[];
  @Output() onEdit = new EventEmitter<Item>();
  @Output() onShow = new EventEmitter<Item>();
  @Output() onDelete = new EventEmitter<Item>();

  itemsTrackByFn = (index: string, item: Item) => item.id;

  showDetails(item: Item) {
    this.onShow.emit(item);
  }
  editItem(item: Item) {
    this.onEdit.emit(item)
  }
  deleteItem(item: Item) {
    this.onDelete.emit(item)
  }
}

itemindex.component.html

<app-item-list [dataSource]="dataSource"
              (onShow)="showItem($event)"
              (onDelete)="deleteItem($event)"
              (onEdit)="editItem($event)"
></app-item-list>

itemindex.component.ts

export class ItemIndexComponent implements OnInit {
  items$: Observable<Item[]>;
  public dataSource: ItemsDatasource;

  constructor(public store: Store<fromRoot.State>, private router: Router){}

  ngOnInit() {
    this.items$ = this.store.select(fromItems.getAllItems);
    this.store.dispatch(new itemsActions.LoadAll());
    this.dataSource = new ItemsDatasource(this.items$);
  }

  editItem(item: Item) {
    this.store.dispatch(new itemsActions.SetCurrentItemId(item.id));
    this.router.navigate(['/items', item.id, 'edit'])
  }
  showItem(item: Item) {
    this.store.dispatch(new itemsActions.SetCurrentItemId(item.id));
    this.router.navigate(['/items', item.id])
  }
  deleteItem(item: Item) {
     this.store.dispatch(new itemsActions.Delete(item.id));
   }
 }
}

export class ItemsDatasource extends DataSource<Item> {

  public constructor(private items$: Observable<Item[]>) {
    super()
  }

  public connect(collectionViewer: CollectionViewer): Observable<Item[]> {
    return this.items$;
  }

  public disconnect(collectionViewer: CollectionViewer): void {}
}

Any suggestion would be helpful

Body:
I faced this error because, I forget to add th and td in
  ng-container

<ng-container matColumnDef="actions">

</ng-container>

ContentLicense: CC BY-SA 4.0


问:
Python 3 equivalent of Python 2 urllib.urlencode
I'm making a POST request to a remote server using Python 2.7 and Python 3 and getting different responses in each scenario. Could the issue be how the data in each request is being encoded? What's the Python 3 equivalent of what I'm doing in 2.7?

```<code>// Python 2.7
data = {'username':'test'}
data = urllib.urlencode(data)
print(data)

req = urllib2.Request(base_link + 'inf.cgi', data, headers)
response = urllib2.urlopen(req)
mypage = response.read()
</code>```

user=test

```<code>// Python 3
data = {'username':'test'}
data = urllib.parse.urlencode(data).encode("utf-8")
print(data)
base_link = 'http://tax1.co.monmouth.nj.us/cgi-bin/'

# Make HTTP request
request = urllib.request.Request(url, data, headers)
mypage = urllib.request.urlopen(request).read()
</code>```

b'user=test'

Trying this without encoding the data:

```<code>data = urllib.parse.urlencode(data)
</code>```

gives a similar output to that in 2.7:

user=test

but results in an error when making the POST request: 'TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.'

答:
You are looking for urllib.parse. This is an example of a code that I use.

```<code>address = urllib.parse.quote(address, safe='/:=?&', encoding="utf-8", errors="strict")
address = urllib.request.urlopen(address).read().decode('utf8')
</code>```

Body:
I'm making a POST request to a remote server using Python 2.7 and Python 3 and getting different responses in each scenario. Could the issue be how the data in each request is being encoded? What's the Python 3 equivalent of what I'm doing in 2.7?

// Python 2.7
data = {'username':'test'}
data = urllib.urlencode(data)
print(data)

req = urllib2.Request(base_link + 'inf.cgi', data, headers)
response = urllib2.urlopen(req)
mypage = response.read()

user=test

// Python 3
data = {'username':'test'}
data = urllib.parse.urlencode(data).encode("utf-8")
print(data)
base_link = 'http://tax1.co.monmouth.nj.us/cgi-bin/'

# Make HTTP request
request = urllib.request.Request(url, data, headers)
mypage = urllib.request.urlopen(request).read()

b'user=test'

Trying this without encoding the data:

data = urllib.parse.urlencode(data)

gives a similar output to that in 2.7:

user=test

but results in an error when making the POST request: 'TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.'

Body:
You are looking for urllib.parse. This is an example of a code that I use.

address = urllib.parse.quote(address, safe='/:=?&', encoding="utf-8", errors="strict")
address = urllib.request.urlopen(address).read().decode('utf8')


问:
Can I have an enum with unlabelled values in C++?
Basically I want to restrict variables to the values 0, 1 or 2.

I have tried doing this with the following:

```<code>enum Value
{
    0,
    1,
    2
};
Value var;
</code>```

But this is a compile error because the enum values are unlabelled. It just makes the code less readable to assign names like "ZERO", "ONE" and "TWO" rather than referring to the values as 0, 1 and 2. Is there any way around this or should I just get rid of the enum and enforce the rule elsewhere?

答:
Just because you add identifiers for the values doesn't mean you have to use them... you can use Value(0), Value(2) etc. if that's more convenient, but there is a danger: enum doesn't restrict the value stored to those listed... e.g. it won't protect you against Value(3).

Inside structs/classes you can use bit fields to restrict the storage used for numbers, but even then:
 - the range has to correspond to either the signed or unsigned values possible in the number of bits requested
 - attempts to assign other values will result in high order bits being removed rather than any kind of compile- or run-time error

If your intention is to create a distinct type that enforces a restricted values 0 through 2, then you need a class with specialised constructor and assignment operators:

```<code>template <int MIN, int MAX>
class Bound
{
  public:
    explicit Bound(int n) { *this = n; }

    Bound& operator=(int n)
    {
        if (n < MIN or n > MAX)
            throw std::runtime_error("out of bounds");
        n_ = n;
        return *this;
    }
    Bound& operator+=(int n) { *this = n_ + n; }

    // should "+" return int or Bound?  entirely usage dependent...
    Bound operator+(int n) { return Bound(n_ + n); }

    // -=, -, *=, *, /=, /, %=, %, bitwise ops, pre/post ++/-- etc...

    operator int() const { return n_; }

  private:
    int n_;
};
</code>```

Body:
Basically I want to restrict variables to the values 0, 1 or 2.

I have tried doing this with the following:

enum Value
{
    0,
    1,
    2
};
Value var;

But this is a compile error because the enum values are unlabelled. It just makes the code less readable to assign names like "ZERO", "ONE" and "TWO" rather than referring to the values as 0, 1 and 2. Is there any way around this or should I just get rid of the enum and enforce the rule elsewhere?

Body:
Just because you add identifiers for the values doesn't mean you have to use them... you can use Value(0), Value(2) etc. if that's more convenient, but there is a danger: enum doesn't restrict the value stored to those listed... e.g. it won't protect you against Value(3).

Inside structs/classes you can use bit fields to restrict the storage used for numbers, but even then:
 - the range has to correspond to either the signed or unsigned values possible in the number of bits requested
 - attempts to assign other values will result in high order bits being removed rather than any kind of compile- or run-time error

If your intention is to create a distinct type that enforces a restricted values 0 through 2, then you need a class with specialised constructor and assignment operators:

template <int MIN, int MAX>
class Bound
{
  public:
    explicit Bound(int n) { *this = n; }

    Bound& operator=(int n)
    {
        if (n < MIN or n > MAX)
            throw std::runtime_error("out of bounds");
        n_ = n;
        return *this;
    }
    Bound& operator+=(int n) { *this = n_ + n; }

    // should "+" return int or Bound?  entirely usage dependent...
    Bound operator+(int n) { return Bound(n_ + n); }

    // -=, -, *=, *, /=, /, %=, %, bitwise ops, pre/post ++/-- etc...

    operator int() const { return n_; }

  private:
    int n_;
};


问:
Are JOIN conditions better than WHERE clauses in T-SQL?
I have come to see that you can do the same thing with either one much of the time. Is any way of doing it more performant in certain circumstances? Is one considered better than the other in terms of readability? Does SQL Server compile them into the same thing anyway?

An example:

```<code>SELECT c.customer_name
,      o.order_id
FROM customers AS c
JOIN orders AS o ON c.customer_id = o.customer_id AND o.order_total > 50.00
</code>```

VS

```<code>SELECT c.customer_name
,      o.order_id
FROM customers AS c
JOIN orders AS o ON c.customer_id = o.customer_id
WHERE o.order_total > 50.00
</code>```

Please excuse me if I am severely misunderstanding something about this or my syntax is incorrect.

I'm pretty new to SQL and much of the logic in the application I work on at my new job is in dynamic SQL (I just started my first development job 2 weeks ago)

This is my first Stack Overflow question

I had to adapt a fake query from the ones I see at work, so what I gave as an example might not even be correct syntax. Every time I think I understand how things work I soon realize that no, it's not that simple.

答:
It depends on JOIN type.

For INNER JOINS there is no difference, optimizer will treat them the same.

For OUTER JOINS there is a key difference.

For following query:

```<code>SELECT * FROM employee AS e
LEFT OUTER JOIN department AS d ON e.depId=d.depId AND d.location = 'USA'
</code>```

It will return all employees and join USA departments.

```<code>SELECT * FROM employee AS e
LEFT OUTER JOIN department AS d ON e.depId=d.depId
WHERE d.location = 'USA'
</code>```

This one will return only employees in USA departments (in other words it will convert the join to INNER JOIN).

Body:
I have come to see that you can do the same thing with either one much of the time. Is any way of doing it more performant in certain circumstances? Is one considered better than the other in terms of readability? Does SQL Server compile them into the same thing anyway?

An example:

SELECT c.customer_name
,      o.order_id
FROM customers AS c
JOIN orders AS o ON c.customer_id = o.customer_id AND o.order_total > 50.00

VS

SELECT c.customer_name
,      o.order_id
FROM customers AS c
JOIN orders AS o ON c.customer_id = o.customer_id
WHERE o.order_total > 50.00

Please excuse me if I am severely misunderstanding something about this or my syntax is incorrect.

I'm pretty new to SQL and much of the logic in the application I work on at my new job is in dynamic SQL (I just started my first development job 2 weeks ago)

This is my first Stack Overflow question

I had to adapt a fake query from the ones I see at work, so what I gave as an example might not even be correct syntax. Every time I think I understand how things work I soon realize that no, it's not that simple.

Body:
It depends on JOIN type.

For INNER JOINS there is no difference, optimizer will treat them the same.

For OUTER JOINS there is a key difference.

For following query:

SELECT * FROM employee AS e
LEFT OUTER JOIN department AS d ON e.depId=d.depId AND d.location = 'USA'

It will return all employees and join USA departments.

SELECT * FROM employee AS e
LEFT OUTER JOIN department AS d ON e.depId=d.depId
WHERE d.location = 'USA'

This one will return only employees in USA departments (in other words it will convert the join to INNER JOIN).


问:
Flask Application not returning javascript contents in html
I have a little problem here with my  flask application

i have this html file that i have linked to some javascript files and if i open the html file with a browser it works fine with  the javascript codes.
Now if i use python flask and return the html file,only the html file is popped up while the JS part is not reflecting on the Web page?

I have linked my JS files to the html page and they are  in the same folder

any solutions?

```<code>head>
  <script src="jquery-1.11.3.min.js"></script>
  <script src="video.js"></script>
  <script src="zxing.js"></script>
</head>
</code>```

答: You should create a new folder titled "Static". Inside that folder is where you store all your CSS files, JavaScript files, etc. So move your video.js, zxing.js and any other JavaScript file to the "Static" folder. Hope this helps, feel free to ask any questions!</p>

Body:
I have a little problem here with my  flask application

i have this html file that i have linked to some javascript files and if i open the html file with a browser it works fine with  the javascript codes.
Now if i use python flask and return the html file,only the html file is popped up while the JS part is not reflecting on the Web page?

I have linked my JS files to the html page and they are  in the same folder

any solutions?

head>


问:
How could I upload an icon I made in Adobe Illustrator to my HTML document?
I can export the file as an SVG, but how would I actually customize it with a hover effect afterwards? I use FontAwesome for most of my icons, but I'm not sure how I'd get my own icon to carry the  tag so that I could modify it the same way as the others.

Body:
You can convert it to a PNG or JPEG, and then place it into your HTML document.

 <!-- Use it as an image  ╌>
<img src="/image.png>`
 <!-- or as a website favicon  ╌>
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico"/>

To convert the file types you can use an online converter or the command line.


问:
Add click event to datatable cell
I'm trying to add a click event to a dynamically created a datatabe. So this is my js :

```<code>   $('#report-table').dataTable({
        "proccessing": true,
        "serverSide": true,
        "ajax": {
            url: '@Url.Action("Get","Controller")',
            type: 'GET'

        },
       "columns": [
           { "data": "Name" },
                { "data": "Date" }, //lest say I want to add a click event here ???
                { "data": "sName", render: myRender }// I tried render but this is rendered without waiting on click function
        ]

    });
</code>```

and this is my table for example :

```<code><tr role="row" class="odd">
<td class="sorting_1">A Test</td>
<td class="aaaa">2/13/2020 3:34:40 PM</td> //lets say I want to fire a click event when I click the .aaaa class
<td>
    <a  asp-route-fileid="55555555" asp-action="Download5"><img src="img/download.svg" height="30" width="30"></a>
</td>
</code>```

Let's say I want to fire a click event when I click the .aaaa class.

Can anyone please give me an idea? Can I do this?
I'm stucked right here. Any idea would be apprecciated very very much :)

Title: Add click event to datatable cell

Body:
I'm trying to add a click event to a dynamically created a datatabe. So this is my js :

   $('#report-table').dataTable({
        "proccessing": true,
        "serverSide": true,
        "ajax": {
            url: '@Url.Action("Get","Controller")',
            type: 'GET'

        },
       "columns": [
           { "data": "Name" },
                { "data": "Date" }, //lest say I want to add a click event here ???
                { "data": "sName", render: myRender }// I tried render but this is rendered without waiting on click function
        ]

    });

and this is my table for example :

A Test
2/13/2020 3:34:40 PM	 //lets say I want to fire a click event when I click the .aaaa class

Let's say I want to fire a click event when I click the .aaaa class.

Can anyone please give me an idea? Can I do this?
I'm stucked right here. Any idea would be apprecciated very very much :)

Body:
$("tr[role='row']").on('click',()=> {
    alert($(this).find('td.aaaa').text());
});


问:
How to override in Kotiln Volley JsonObjectRequest class?
I'm writing a Kotlin app that has a class. I need that class to extend JsonObjectRequest, since I need to override the function

```<code>override fun parseNetworkResponse(response: NetworkResponse?): Response<T>
</code>```

That's because I need to interpret in Kotlin the HTTP response code the server is sending.

However, I admit to being new to Kotlin and haven't managed to figure out how to extend the JsonObjectRequest class. I keep running into silly compiler issues.

Can someone provide a quick example of that?

答:
After a bit of iteration, i managed to finally figure it out. Posting it here since it may be useful to others - </p>

```<code>class DataRequest(
    method: Int,
    uri: String,
    jsonObject: JSONObject,
    listener: Response.Listener<JSONObject>,
    errorListener: Response.ErrorListener
) :
    JsonObjectRequest(method, uri, jsonObject, listener, errorListener)
{
    override fun parseNetworkResponse(response: NetworkResponse): Response<JSONObject>
    {
        try
        {
            val jsonString = String(
                response.data,
                Charset.forName(HttpHeaderParser.parseCharset(response.headers))
            )
            return Response.success(
                JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response)
            )
        } catch (e: UnsupportedEncodingException)
        {
            return Response.error(ParseError(e))
        } catch (je: JSONException)
        {
            return Response.error(ParseError(je))
        }

    }
}
</code>```

Body:
I'm writing a Kotlin app that has a class. I need that class to extend JsonObjectRequest, since I need to override the function

override fun parseNetworkResponse(response: NetworkResponse?): Response<T>

That's because I need to interpret in Kotlin the HTTP response code the server is sending.

However, I admit to being new to Kotlin and haven't managed to figure out how to extend the JsonObjectRequest class. I keep running into silly compiler issues.

Can someone provide a quick example of that?

Body:
After a bit of iteration, i managed to finally figure it out. Posting it here since it may be useful to others -

class DataRequest(
    method: Int,
    uri: String,
    jsonObject: JSONObject,
    listener: Response.Listener<JSONObject>,
    errorListener: Response.ErrorListener
) :
    JsonObjectRequest(method, uri, jsonObject, listener, errorListener)
{
    override fun parseNetworkResponse(response: NetworkResponse): Response<JSONObject>
    {
        try
        {
            val jsonString = String(
                response.data,
                Charset.forName(HttpHeaderParser.parseCharset(response.headers))
            )
            return Response.success(
                JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response)
            )
        } catch (e: UnsupportedEncodingException)
        {
            return Response.error(ParseError(e))
        } catch (je: JSONException)
        {
            return Response.error(ParseError(je))
        }

    }
}


问:
I am trying to download file using res.download(). I get the following error

 const path = require('path')
const fs = require('fs');

 const filePath1 = path.join
(
__dirname,
 "..",
 "public",
"exports",
"csv-"+ req.user.ecode + " history"  + ".csv"
)
  fs.writeFile(filePath1,csv,function(err){
            if(err){
              console.log('fs writeFile error:' + err)
              return res.status(500).json({ err })
            }else{
              setTimeout(function()
             {
             fs.unlinkSync(filePath1)
             },40000)
             res.download(filePath1, function(err){
                console.log(err);
              })
            }
          })```
</div>
</div>
</p>

<p>am getting the following output in my console with csv and error as follows..
Date :,Feb-14-2020
Strategy,Corporate Goal,Project Name,Weightage,Responsibility,Target Date
Financial,EBIDTA@582%= 46.77cr INR,Project A,10,EM00875,Jul-25-2020
Financial,EBIDTA@582%= 46.77cr INR,Project C,90,EM00875,Feb-16-2020</p>

```Error: Request aborted
    at onaborted (E:\KRA_5\abc_5_final - Copy\node_modules\express\lib\response.js:1025:15)
    at Immediate._onImmediate (E:\KRA_5\abc_5_final - Copy\node_modules\express\lib\response.js:1067:9)
    at processImmediate (internal/timers.js:439:21) {
  code: 'ECONNABORTED'
}
```

答:
Download your file using Express.js instead of Node.js.
How to download a file using Express in Node.js

Hopefully the problem will be fixed. Let me know.

Besides, you can check the following links to have more clear idea that can be helpful related to your problem.

https://stackoverflow.com/a/20177012/10427807

https://stackoverflow.com/a/7288883/10427807

Body:
 const path = require('path')
const fs = require('fs');

 const filePath1 = path.join
(
__dirname,
 "..",
 "public",
"exports",
"csv-"+ req.user.ecode + " history"  + ".csv"
)
  fs.writeFile(filePath1,csv,function(err){
            if(err){
              console.log('fs writeFile error:' + err)
              return res.status(500).json({ err })
            }else{
              setTimeout(function()
             {
             fs.unlinkSync(filePath1)
             },40000)
             res.download(filePath1, function(err){
                console.log(err);
              })
            }
          })

am getting the following output in my console with csv and error as follows..
Date :,Feb-14-2020
Strategy,Corporate Goal,Project Name,Weightage,Responsibility,Target Date
Financial,EBIDTA@582%= 46.77cr INR,Project A,10,EM00875,Jul-25-2020
Financial,EBIDTA@582%= 46.77cr INR,Project C,90,EM00875,Feb-16-2020

Error: Request aborted
    at onaborted (E:\KRA_5\abc_5_final - Copy\node_modules\express\lib\response.js:1025:15)
    at Immediate._onImmediate (E:\KRA_5\abc_5_final - Copy\node_modules\express\lib\response.js:1067:9)
    at processImmediate (internal/timers.js:439:21) {
  code: 'ECONNABORTED'
}


问:
Stop people uploading malicious PHP files via forms
I have an upload form created in php on my website where people are able to upload a zip file. The zip file is then extracted and all file locations are added to a database. The upload form is for people to upload pictures only, obviously, with the files being inside the zip folder I cant check what files are being uploaded until the file has been extracted. I need a piece of code which will delete all the files which aren't image formats (.png, .jpeg, etc). I'm really worried about people being able to upload malicious php files, big security risk! I also need to be aware of people changing the extensions of php files trying to get around this security feature.

This is the original script I used http://net.tutsplus.com/videos/screencasts/how-to-open-zip-files-with-php/

This is the code which actually extracts the .zip file:

```<code>function openZip($file_to_open) {
    global $target;

    $zip = new ZipArchive();
    $x = $zip->open($file_to_open);
    if($x === true) {
        $zip->extractTo($target);
        $zip->close();

        unlink($file_to_open);
    } else {
        die("There was a problem. Please try again!");
    }
}
</code>```

Thanks, Ben.

答:
I don't see the risk in having renamed php files in your DB...
As long as you're not evaluating them as PHP files (or at all, for that matter), they can't do too much harm, and since there's no .php extension the php engine won't touch them.

I guess you could also search the files for <?php...

Also: assume the worst about the files uploaded to your machine. Renamed the folder into which you're saving them "viruses" and treat it accordingly. Don't make it public, don't give any file launch permissions (especially the php user), etc.

OwnerDisplayName: Ben McRae

Body:
I have an upload form created in php on my website where people are able to upload a zip file. The zip file is then extracted and all file locations are added to a database. The upload form is for people to upload pictures only, obviously, with the files being inside the zip folder I cant check what files are being uploaded until the file has been extracted. I need a piece of code which will delete all the files which aren't image formats (.png, .jpeg, etc). I'm really worried about people being able to upload malicious php files, big security risk! I also need to be aware of people changing the extensions of php files trying to get around this security feature.

This is the original script I used http://net.tutsplus.com/videos/screencasts/how-to-open-zip-files-with-php/

This is the code which actually extracts the .zip file:

function openZip($file_to_open) {
    global $target;

    $zip = new ZipArchive();
    $x = $zip->open($file_to_open);
    if($x === true) {
        $zip->extractTo($target);
        $zip->close();

        unlink($file_to_open);
    } else {
        die("There was a problem. Please try again!");
    }
}

Thanks, Ben.

LastEditorDisplayName: gs

OwnerDisplayName: Assaf

ContentLicense: CC BY-SA 2.5


问:
Android application loses state after launching another intent
So I have the following:

A Common class that many of my Activities access in my android application, via setting the class in my manifest:

```<code><application android:name="com.dev.games.phraseparty.Common"... />
</code>```

Now, within this class I have several objects that are constructed to preserve application state and common services to perform applications that are constructed in the Common constructor

ie

```<code>GameStateVO gameState;

public Common()
{
    gameState = new GameStateVO();
}
</code>```

My problem is that my Activity has an Admob ad. When the user clicks on the ad, it calls the webbrowser intent to open the ad URL in a webbrowser.

Now, when I click back from the webbrowser launched by admob, it takes me back to the caling activity and the OnCreate method is called.

This activity then gets a null pointer exception because it will do something like:

```<code>public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Common common = this.getApplication();

//null pointer here since the game state VO is null since the Common has lost its state.
int score = common.getGameState().getScore();

}
</code>```

答: If you have no active foreground activity, then your process is ripe for shutdown by the OS to obtain more resources. The browser app in particular i've noticed uses a lot of resources and can quickly lead to background activities and later processes being killed off. Having a service can help keep your process around, but even then it can still be killed off if needed. I think you'll need to use the activity lifetime cycle method to save & restore your state. See the process lifecycle section of the docs for more info</p>

Body:
So I have the following:

A Common class that many of my Activities access in my android application, via setting the class in my manifest:

<application android:name="com.dev.games.phraseparty.Common"... />

Now, within this class I have several objects that are constructed to preserve application state and common services to perform applications that are constructed in the Common constructor

ie

GameStateVO gameState;

public Common()
{
    gameState = new GameStateVO();
}

My problem is that my Activity has an Admob ad. When the user clicks on the ad, it calls the webbrowser intent to open the ad URL in a webbrowser.

Now, when I click back from the webbrowser launched by admob, it takes me back to the caling activity and the OnCreate method is called.

This activity then gets a null pointer exception because it will do something like:

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Common common = this.getApplication();

//null pointer here since the game state VO is null since the Common has lost its state.
int score = common.getGameState().getScore();

}


问:
Is there a way to fix " Umbraco.Core.pdb not loaded " error UMBRACO

I don't know what happened but when I build the project, this error showed up.

Does anyone know?

答:
In my case, I have missed connection string details in web.config file.

I had  <connectionStrings configSource=".\UmbracoConnectionDetails.config" /> in my web.config file but UmbracoConnectionDetails.config was missing in my root folder. Just has added file and working fine.


问:
Why Select * Only return the first record in a group?
I am studying the Group by and Having clauses in a SQL statement. In the following page, what I want are all customers whose country contain more than 5 customers in the database.

So I use

```<code>SELECT *
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
</code>```

in https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_having

But this select only returns the first record in the group, not all records in the group. Why?

答:
But select only returns the first record in the group, not all records in the group. Why?

Because one row per group is what GROUP BY does.

The way to do what you want to do is to figure out which countries have more that 5 customers, then return all records from those countries:

```<code>SELECT * FROM Customers WHERE Country IN
(SELECT Country FROM Customers GROUP BY Country HAVING COUNT(CustomerID) > 5)
</code>```

Body:
I am studying the Group by and Having clauses in a SQL statement. In the following page, what I want are all customers whose country contain more than 5 customers in the database.

So I use

SELECT *
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5

in https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_having

But this select only returns the first record in the group, not all records in the group. Why?

Body:
But select only returns the first record in the group, not all records in the group. Why?

Because one row per group is what GROUP BY does.

The way to do what you want to do is to figure out which countries have more that 5 customers, then return all records from those countries:

SELECT * FROM Customers WHERE Country IN
(SELECT Country FROM Customers GROUP BY Country HAVING COUNT(CustomerID) > 5)


问:
Why can you set multiple accessModes on a persistent volume?
For example in the following example:

```<code>apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: exmaple-pvc
spec:
  accessModes:
    - ReadOnlyMany
    - ReadWriteMany
  storageClassName: standard
  volumeMode: Filesystem
  resources:
    requests:
      storage: 1Gi
</code>```

Why is this allowed? What is the actual behavior of the volume in this case? Read only? Read and write?

答:
A persistent volume can be mounted by multiple pods on the different node at the same. One pod can mount a persistent volume with only one access mode at a time and other pods can mount the same persistent volume with different access mode. But a pod can mount the persistent volume with only one access mode.

Documentation reference for those who didn't understand the question: persistent volume access modes

Body:
For example in the following example:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: exmaple-pvc
spec:
  accessModes:
    - ReadOnlyMany
    - ReadWriteMany
  storageClassName: standard
  volumeMode: Filesystem
  resources:
    requests:
      storage: 1Gi

Why is this allowed? What is the actual behavior of the volume in this case? Read only? Read and write?


问:
Java try-catch input validation with do-while loop
I've been sitting here (embarrassingly) for hours trying to get a do-while loop to to accept user input until it's valid, but I seem to be messing up when it comes to the boolean that I'm using to try and exit the loop.  Whenever I can get the program to partially work the catch exception just ends up repeating itself infinitely.</p>

```<code>Scanner scnr = new Scanner(System.in);

double wallHeight = 0.0;
boolean valid = false;

// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's height
do {
    try {
        System.out.println("Enter wall height (feet): ");
        wallHeight = scnr.nextDouble();
        valid = false;

        if (wallHeight <=0) {
            throw new Exception ("Invalid Input");
        }
    }
    catch (Exception e) {
        System.out.println("Invalid Input");
    }
} while (!valid);
</code>```

答:
Start by assuming the input is valid (and set valid to true on every iteration of the loop). Only set valid to false when you encounter an exception (hopefully the one you raised).

```<code>do {
    valid = true;
    try {
        System.out.println("Enter wall height (feet): ");
        wallHeight = scnr.nextDouble();
        if (wallHeight <= 0) {
            throw new Exception("Invalid Input");
        }
    } catch (Exception e) {
        valid = false;
        System.out.println("Invalid Input");
    }
} while (!valid);
</code>```

Note that you do not appear to need an exception here, as

```<code>do {
    valid = true;
    System.out.println("Enter wall height (feet): ");
    wallHeight = scnr.nextDouble();
    if (wallHeight <= 0) {
        System.out.println("Invalid Input");
        valid = false;
    }
} while (!valid);
</code>```

would also work. Of course, that assumes the user only inputs valid double(s). If you need handle arbitrary input, you should check that there is a double before you attempt to consume it (and you must consume anything that isn't a double or you have an infinite loop). Like,

```<code>do {
    valid = true;
    System.out.println("Enter wall height (feet): ");
    if (scnr.hasNextDouble()) {
        wallHeight = scnr.nextDouble();
        if (wallHeight <= 0) {
            System.out.println("Invalid Input");
            valid = false;
        }
    } else {
        System.out.println("Invalid Input " + scnr.nextLine());
        valid = false;
    }
} while (!valid);
</code>```

Body:
I've been sitting here (embarrassingly) for hours trying to get a do-while loop to to accept user input until it's valid, but I seem to be messing up when it comes to the boolean that I'm using to try and exit the loop.  Whenever I can get the program to partially work the catch exception just ends up repeating itself infinitely.

Scanner scnr = new Scanner(System.in);

double wallHeight = 0.0;
boolean valid = false;

// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's height
do {
    try {
        System.out.println("Enter wall height (feet): ");
        wallHeight = scnr.nextDouble();
        valid = false;

        if (wallHeight <=0) {
            throw new Exception ("Invalid Input");
        }
    }
    catch (Exception e) {
        System.out.println("Invalid Input");
    }
} while (!valid);

Body:
Start by assuming the input is valid (and set valid to true on every iteration of the loop). Only set valid to false when you encounter an exception (hopefully the one you raised).

do {
    valid = true;
    try {
        System.out.println("Enter wall height (feet): ");
        wallHeight = scnr.nextDouble();
        if (wallHeight <= 0) {
            throw new Exception("Invalid Input");
        }
    } catch (Exception e) {
        valid = false;
        System.out.println("Invalid Input");
    }
} while (!valid);

Note that you do not appear to need an exception here, as

do {
    valid = true;
    System.out.println("Enter wall height (feet): ");
    wallHeight = scnr.nextDouble();
    if (wallHeight <= 0) {
        System.out.println("Invalid Input");
        valid = false;
    }
} while (!valid);

would also work. Of course, that assumes the user only inputs valid double(s). If you need handle arbitrary input, you should check that there is a double before you attempt to consume it (and you must consume anything that isn't a double or you have an infinite loop). Like,

do {
    valid = true;
    System.out.println("Enter wall height (feet): ");
    if (scnr.hasNextDouble()) {
        wallHeight = scnr.nextDouble();
        if (wallHeight <= 0) {
            System.out.println("Invalid Input");
            valid = false;
        }
    } else {
        System.out.println("Invalid Input " + scnr.nextLine());
        valid = false;
    }
} while (!valid);


问:
Is there any way to use notepad++ run command to execute it from current directory?
When using Notepad++, i used run.. command to run a .bat file in a folder but when i am running it, the bat file goes to notepad++ directory and then runs itself.
'''C:/Program Files/Notepad++'''
Is There Any way so that i can run it from current directory where it is saved.
Update 1:I Created A Batch File That Inspects all java Files present in the folder where the batch file is kept And Compiles Them, it uses %cd% as locating the folder so when i want it to run from notepad++ v7.8.4. It Takse that batch file and keeps it in C:/Program Files/Notepad++   and then runs the batch file but i want notepad ++ to run it from the current directory where i have kept the batch file.
run in notepad++ can be opened by pressing F5.
thanks</p>

答:
Sir, @AdrianHHH I Got It , the problem was i was editing the wrong xml file. the file which was responsible was is%APPDATA%/Roaming/Notepad++/shortcuts.xml. There is the exact copy of shortcuts.xml which works fine.

<Command name="CD and run file" Ctrl="no" Alt="no" Shift="no" Key="0">cmd /C "cd /d $(CURRENT_DIRECTORY) && $(FULL_CURRENT_PATH)"</Command>```

Sir Can You Please Edit The Above Code SO I Can Run My Executor Java.bat from It.
Thanks
Assuming my Bat File IS In :D:\Projects\Java\Java Executor

Body:
Sir, @AdrianHHH I Got It , the problem was i was editing the wrong xml file. the file which was responsible was is%APPDATA%/Roaming/Notepad++/shortcuts.xml. There is the exact copy of shortcuts.xml which works fine.

<Command name="CD and run file" Ctrl="no" Alt="no" Shift="no" Key="0">cmd /C &quot;cd /d $(CURRENT_DIRECTORY) &amp;&amp; $(FULL_CURRENT_PATH)&quot;</Command>

Sir Can You Please Edit The Above Code SO I Can Run My Executor Java.bat from It.
Thanks
Assuming my Bat File IS In :D:\Projects\Java\Java Executor


问:
There was a problem setting up codemirror indentUnit,
I changed the indentUnit of codemirror by the following code

  $('#form').on('submit', function(e){
    e.preventDefault()
    $.ajax({
      type: 'PUT',
      url: $(this).attr('action'),
      data: $(this).serialize(),
      success: function(data){
        if(data.success){
          let editor_mode = $("#editor_mode option:selected").val()
          let tab_size = $("#tab_size option:selected").val()
          editor.setTabSize(tab_size)
          if (editor_mode == 'vim'){
            editor.setVimMode()
          }else{
            editor.setEmacsPrefix()
          }
          editor.fit()
          editor.autoFormatRange()
          $('#settingModal').modal('hide')
        }
      }
    })
  })
```

<pre class="lang-js prettyprint-override"><code>  setTabSize(tabSize){
    this.cm.setOption('tabSize', tabSize)
    this.cm.setOption('indentUnit', tabSize)
  }
</code>```

But after I changed, indented multiplied by 10

答:
Not sure why, i set

this.cm.setOption('tabSize',2)
this.cm.setOption('indentUnit',2)
```

<p>Indent effect becomes 20.
If set</p>

<pre class="lang-js prettyprint-override"><code>this.cm.setOption('tabSize',4)
this.cm.setOption('indentUnit',4)
</code>```

Indent effect becomes 40.

Body:
I changed the indentUnit of codemirror by the following code

  $('#form').on('submit', function(e){
    e.preventDefault()
    $.ajax({
      type: 'PUT',
      url: $(this).attr('action'),
      data: $(this).serialize(),
      success: function(data){
        if(data.success){
          let editor_mode = $("#editor_mode option:selected").val()
          let tab_size = $("#tab_size option:selected").val()
          editor.setTabSize(tab_size)
          if (editor_mode == 'vim'){
            editor.setVimMode()
          }else{
            editor.setEmacsPrefix()
          }
          editor.fit()
          editor.autoFormatRange()
          $('#settingModal').modal('hide')
        }
      }
    })
  })

  setTabSize(tabSize){
    this.cm.setOption('tabSize', tabSize)
    this.cm.setOption('indentUnit', tabSize)
  }

But after I changed, indented multiplied by 10

Body:
Not sure why, i set

this.cm.setOption('tabSize',2)
this.cm.setOption('indentUnit',2)

Indent effect becomes 20.
If set

this.cm.setOption('tabSize',4)
this.cm.setOption('indentUnit',4)

Indent effect becomes 40.


问:
Sorting Javascript Array with Split Function
I have an array that looks like this

```<code>var testArray = ['name1:13', 'name2:15', 'name3:13'];
</code>```

I would like to sort the array by the number to the right of the colon.

So far I have this:

```<code>var converted = testArray.map(
            function (item) {
                return item.split(':').map(
            function (num) {
                return parseInt(num);
          });
        })

        alert(converted)
        var sorted = converted.sort(function (a, b) { return a[1] - b[1] })
        alert(sorted);
</code>```

That sorts them in the correct order but I'm not sure how to pass over the first part of each string, the part to the left of the colon.

Right now it returns: NAN,13,NAN,13,NAN,15

Body:
I have an array that looks like this

var testArray = ['name1:13', 'name2:15', 'name3:13'];

I would like to sort the array by the number to the right of the colon.

So far I have this:

var converted = testArray.map(
            function (item) {
                return item.split(':').map(
            function (num) {
                return parseInt(num);
          });
        })

        alert(converted)
        var sorted = converted.sort(function (a, b) { return a[1] - b[1] })
        alert(sorted);

That sorts them in the correct order but I'm not sure how to pass over the first part of each string, the part to the left of the colon.

Right now it returns: NAN,13,NAN,13,NAN,15

Body:
var testArray = ['name1:13', 'name2:15', 'name3:13'];
console.log(testArray.sort((a, b) => (a.split(":")[1] > b.split(":")[1]) ? 1 : -1))


问:
Crystal report. "cannot find the path specified" in windows server 2008 using MVC
This is working properly in may computer but when i deployed it to client test server. this error pop up. the server is windows server 2008 standard edition. I already check the path of the rpt and install CRV and allow access to everyone. I spent almost 2 days and still can't find the solution.</p>

```<code>Server Error in '/QC' Application.

The system cannot find the path specified.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Runtime.InteropServices.COMException: The system cannot find the path specified.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[COMException (0x80004005): The system cannot find the path specified.
]
   CrystalDecisions.ReportAppServer.Controllers.ReportSourceClass.Export(ExportOptions pExportOptions, RequestContext pRequestContext) +0
   CrystalDecisions.ReportSource.EromReportSourceBase.ExportToStream(ExportRequestContext reqContext) +1140
   CrystalDecisions.CrystalReports.Engine.FormatEngine.ExportToStream(ExportRequestContext reqContext) +656
   CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToStream(ExportOptions options) +111
   CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToStream(ExportFormatType formatType) +99
   Sanipex.Infrastructure.Label.PrintToImage(String inputPath, String parameter, String outputPath, ImageFormat formatType) +482
   Sanipex.Controllers.WarehouseController.ScanLabel(Nullable`1 qty, Nullable`1 missinglabel, String txtdate, String product, Nullable`1 linenumber, Nullable`1 ordernumber, String btnsubmit, SessionData model, Cases casemodel) +17807
   lambda_method(Closure , ControllerBase , Object[] ) +465
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +182
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
   System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +58
   System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +225
   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
   System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +99
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9631916
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929
</code>```

答:
I just spent the last five hours trying to figure out why two reports work great in dev but fail on the server.  Originally they were sourced by views but I changed them out to use stored procedures, and that's where things went wrong (on the server only, though).

I'm just going to document (very simply) what I had to do to make these work:

My first problem was that the stored procedure was receiving NULL values for all parameters.  This was because, when setting the report's connection (ODBC) to point to the server, the report lost its parameter mapping to the stored procedure.  I needed to assign the name of the table to the table's TableName property before applying the logon info, then I needed to assign the name to the Location property of the table after:

```<code>foreach(var crTable in doc.Database.Tables) {
    crystalTableLogOnInfo = crTable.LogOnInfo;

    crystalTableLogOnInfo.ConnectionInfo.ServerName = strDSNName;
    crystalTableLogOnInfo.ConnectionInfo.DatabaseName = strDBName;
    crystalTableLogOnInfo.ConnectionInfo.UserID = strUserName;
    crystalTableLogOnInfo.ConnectionInfo.Password = strPassword;
    crystalTableLogOnInfo.TableName = crTable.Name; // this line
    crTable.ApplyLogOnInfo(crystalTableLogOnInfo);
    crTable.Location = crTable.Name;                // and this line
}

doc.VerifyDatabase();
</code>```

Once I added those two lines, the stored proc received the parameter values, but then the report failed when I called its ExportToStream method.  By chance I figured out that I needed to rename the table in the report.  I had to do this because when I had swapped out the view for a stored procedure, Crystal effectively aliased the stored proc with the original view's name and I guess that, somewhere under the hood, Crystal uses the alias when it should be using the real underlying table/view/proc.  Using the "Database Expert", I opposite-clicked on the name of my original view (under the "Selected Tables" box), selected "Rename", and changed it to the name of the stored procedure concatenated with a semicolon and the number 1, such as "spMyReportData;1".

Body:
This is working properly in may computer but when i deployed it to client test server. this error pop up. the server is windows server 2008 standard edition. I already check the path of the rpt and install CRV and allow access to everyone. I spent almost 2 days and still can't find the solution.

Server Error in '/QC' Application.

The system cannot find the path specified.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Runtime.InteropServices.COMException: The system cannot find the path specified.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[COMException (0x80004005): The system cannot find the path specified.
]
   CrystalDecisions.ReportAppServer.Controllers.ReportSourceClass.Export(ExportOptions pExportOptions, RequestContext pRequestContext) +0
   CrystalDecisions.ReportSource.EromReportSourceBase.ExportToStream(ExportRequestContext reqContext) +1140
   CrystalDecisions.CrystalReports.Engine.FormatEngine.ExportToStream(ExportRequestContext reqContext) +656
   CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToStream(ExportOptions options) +111
   CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToStream(ExportFormatType formatType) +99
   Sanipex.Infrastructure.Label.PrintToImage(String inputPath, String parameter, String outputPath, ImageFormat formatType) +482
   Sanipex.Controllers.WarehouseController.ScanLabel(Nullable`1 qty, Nullable`1 missinglabel, String txtdate, String product, Nullable`1 linenumber, Nullable`1 ordernumber, String btnsubmit, SessionData model, Cases casemodel) +17807
   lambda_method(Closure , ControllerBase , Object[] ) +465
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +182
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
   System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +58
   System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +225
   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
   System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +99
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9631916
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929

Body:
I just spent the last five hours trying to figure out why two reports work great in dev but fail on the server.  Originally they were sourced by views but I changed them out to use stored procedures, and that's where things went wrong (on the server only, though).

I'm just going to document (very simply) what I had to do to make these work:

My first problem was that the stored procedure was receiving NULL values for all parameters.  This was because, when setting the report's connection (ODBC) to point to the server, the report lost its parameter mapping to the stored procedure.  I needed to assign the name of the table to the table's TableName property before applying the logon info, then I needed to assign the name to the Location property of the table after:

foreach(var crTable in doc.Database.Tables) {
    crystalTableLogOnInfo = crTable.LogOnInfo;

    crystalTableLogOnInfo.ConnectionInfo.ServerName = strDSNName;
    crystalTableLogOnInfo.ConnectionInfo.DatabaseName = strDBName;
    crystalTableLogOnInfo.ConnectionInfo.UserID = strUserName;
    crystalTableLogOnInfo.ConnectionInfo.Password = strPassword;
    crystalTableLogOnInfo.TableName = crTable.Name; // this line
    crTable.ApplyLogOnInfo(crystalTableLogOnInfo);
    crTable.Location = crTable.Name;                // and this line
}

doc.VerifyDatabase();

Once I added those two lines, the stored proc received the parameter values, but then the report failed when I called its ExportToStream method.  By chance I figured out that I needed to rename the table in the report.  I had to do this because when I had swapped out the view for a stored procedure, Crystal effectively aliased the stored proc with the original view's name and I guess that, somewhere under the hood, Crystal uses the alias when it should be using the real underlying table/view/proc.  Using the "Database Expert", I opposite-clicked on the name of my original view (under the "Selected Tables" box), selected "Rename", and changed it to the name of the stored procedure concatenated with a semicolon and the number 1, such as "spMyReportData;1".


问:
what is the best source for server design patterns/best practices?
I've searched for a while for a good book which covers server designed patterns.  I'm looking for something along the lines of Gang of Four.

Concepts include:

-- Threaded vs Process vs combo based solutions

-- How to triage requests properly.  i.e. I expect only limited requests from any domain, so I may only allocate a certain number of workers per domain.

-- Worker timeouts

-- poll/select/epoll use cases

-- And those things I don't know!

Any suggestions please!

Thanks!

答:
Advanced Programming in the Unix Environment, 2nd Edition is a fantastic resource for learning the details of Unix systems programming. It's extremely well-written (one of my favorite books in the English Language), the depth is excellent, and the focus on four common environments (at the time of publication) help ensure that it is well-rounded. It's not too badly out of date -- new features in newer operating systems may be fantastic for specific problems, but this book really covers the basics very well.

The downside, of course, is that APUE2nd misses out on some fantastic third-party tools such as libevent, which can make programming sockets-based servers significantly easier. (And automatically picks the 'best' of select(2), poll(2), epoll(4), kpoll, and Windows event handling, for the platform.)

As for choosing between threads and processes, it comes down to: how much memory sharing do you want / need between tasks? If each process can run relatively isolated, processes provide better memory protection and no speed penalty. If processes need to interact with each other's objects, or objects 'owned' by a single thread, then threads provide better primitives for sharing data. (But many would argue that the shared memory of threads is an invitation to fun and exciting bugs. It Depends.)


问:
How to use Eloquent relationships with Yajra Datatables?
I am trying to use eloquent relationships to display the name of the patient instead of the patient id foreign key. Instead it only displays the patient id as if it doesn't see the relationship.

My controller function is:

```<code>   public function getActions(){
    $data = Action::all();
    return DataTables::of($data)
   ->addColumn('name',function(Action $action){
       return empty ($action->patient->first_name) ? $action->patient_id : $action->patient->first_name;
        //return DB::raw("SELECT * FROM 'patients' WHERE 'patients_id' = ?", $action->patient_id);
    })
    ->make(true);
}
</code>```

My js function in the view is:

```<code>    <script type="text/javascript">
        $(document).ready(function (){
          $('#actionTable').DataTable({
              processing: true,
              serverSide: true,
              ajax:'{!! route('get.actions')!!}',
              columns:[
                 {data:'action_id', name:'action_id'},
                 {data:'name', name:'name'},
                 {data:'action_status_id', name:'action_status_id'},
                 {data:'is_complete', name:'is_complete'},
              ]
          });
        })
     </script>
</code>```

My Action class is:

```<code>    class Action extends Model
    {
        protected $table ="actions";

        protected $fillable=[
           'user_id', 'patient_id', 'option_id', 'action_status_id', 'is_complete', 'due_date',
        ];

        protected $primary_key = "action_id";

        public $incrementing = false;

        public function patients(){
              return $this->belongsTo('App\Patient','patient_id','action_id');
        }
   }
</code>```

My Patients class is:

```<code>     class Patient extends Model
     {
        protected $table ="patients";

        protected $fillable=[
            'first_name', 'last_name', 'email', 'phone', 'dob', 'gender_id', 'is_active',
        ];

        protected $primary_key = 'patient_id';

        public $incrementing = false;

        public function actions(){
            return $this->hasMany('App\Action','action_id','patient_id');
        }
    }
</code>```

答:
The problem is that you have named your relation function inside your Action model as "patients". And you are calling

$action->patient->first_name.

I suggest renaming the relation function inside your Action Model to

public function patient()

It makes more sense.

Please refer to the documentation for more clarification One to One Relationships

Body:
I am trying to use eloquent relationships to display the name of the patient instead of the patient id foreign key. Instead it only displays the patient id as if it doesn't see the relationship.

My controller function is:

   public function getActions(){
    $data = Action::all();
    return DataTables::of($data)
   ->addColumn('name',function(Action $action){
       return empty ($action->patient->first_name) ? $action->patient_id : $action->patient->first_name;
        //return DB::raw("SELECT * FROM 'patients' WHERE 'patients_id' = ?", $action->patient_id);
    })
    ->make(true);
}

My js function in the view is:

My Action class is:

    class Action extends Model
    {
        protected $table ="actions";

        protected $fillable=[
           'user_id', 'patient_id', 'option_id', 'action_status_id', 'is_complete', 'due_date',
        ];

        protected $primary_key = "action_id";

        public $incrementing = false;

        public function patients(){
              return $this->belongsTo('App\Patient','patient_id','action_id');
        }
   }

My Patients class is:

     class Patient extends Model
     {
        protected $table ="patients";

        protected $fillable=[
            'first_name', 'last_name', 'email', 'phone', 'dob', 'gender_id', 'is_active',
        ];

        protected $primary_key = 'patient_id';

        public $incrementing = false;

        public function actions(){
            return $this->hasMany('App\Action','action_id','patient_id');
        }
    }


问:
Confused with Join logic
I find it so confused that my simple logic doesn't work.

I have a data with 2 columns ID and code.

1 ID can link to multiple code.

So the sample data is like this:

```<code>ID   Code
--   ----
a    1
a    2
a    3
b    1
b    3
c    1
c    3
c    4
d    2
d    3
d    4
</code>```

The rule is that:

Find ID that has code = 1 AND code not equal to 2 AND code =3

So clearly a is fail, b is good, c is good, d is fail.

I have 2 approaches below and neither of them work!

Can you please help?

Many thanks,

Harry

Approach #1:

```<code>create table mytable (
ID int,
code varchar(255)
);

insert into mytable (ID, code)
values('a','1'),('a','2'),('a','3'),('b','1'),('b','3'),('c','1'),('c','3'),('c','4'),('d','2'),('d','3'),('d','4');

select distinct
    ID
from
    mytable
where
    code = 1
    and ID not in (select ID from mytable where code = 2)
    and ID in (select ID from mytable where code = 3);
</code>```

Approach #2: join my table 2 times

```<code>select distinct(T1.ID)
from
    (select distinct(mytable1.ID)
     from mytable mytable1
     join mytable mytable2 on  mytable1.ID = mytable2.ID
     where mytable1.code = 1
       and mytable2.code not in ('2')) as T1
join
    (select distinct(mytable3.ID)
     from mytable mytable3
     where mytable3.code = 3) as T2
on T1.ID = T2.ID
</code>```

答:
I would use aggregation here:

```<code>SELECT ID
FROM (SELECT DISTINCT ID, code FROM mytable) t
GROUP BY ID
HAVING
    COUNT(CASE WHEN code = 1 THEN 1 END) > 0 AND
    COUNT(CASE WHEN code = 2 THEN 1 END) +
        COUNT(CASE WHEN code = 3 THEN 1 END) < 2;
</code>```

The HAVING clause ensures that any matching ID has a code of 1, and also that a code of 2 or 3 happens at most once (i.e. having a code both of 2 and 3 is forbidden, though one or the other is allowed).

Title: Confused with Join logic

Body:
I find it so confused that my simple logic doesn't work.

I have a data with 2 columns ID and code.

1 ID can link to multiple code.

So the sample data is like this:

ID   Code
--   ----
a    1
a    2
a    3
b    1
b    3
c    1
c    3
c    4
d    2
d    3
d    4

The rule is that:

Find ID that has code = 1 AND code not equal to 2 AND code =3

So clearly a is fail, b is good, c is good, d is fail.

I have 2 approaches below and neither of them work!

Can you please help?

Many thanks,

Harry

Approach #1:

create table mytable (
ID int,
code varchar(255)
);

insert into mytable (ID, code)
values('a','1'),('a','2'),('a','3'),('b','1'),('b','3'),('c','1'),('c','3'),('c','4'),('d','2'),('d','3'),('d','4');

select distinct
    ID
from
    mytable
where
    code = 1
    and ID not in (select ID from mytable where code = 2)
    and ID in (select ID from mytable where code = 3);

Approach #2: join my table 2 times

select distinct(T1.ID)
from
    (select distinct(mytable1.ID)
     from mytable mytable1
     join mytable mytable2 on  mytable1.ID = mytable2.ID
     where mytable1.code = 1
       and mytable2.code not in ('2')) as T1
join
    (select distinct(mytable3.ID)
     from mytable mytable3
     where mytable3.code = 3) as T2
on T1.ID = T2.ID

Body:
I would use aggregation here:

SELECT ID
FROM (SELECT DISTINCT ID, code FROM mytable) t
GROUP BY ID
HAVING
    COUNT(CASE WHEN code = 1 THEN 1 END) > 0 AND
    COUNT(CASE WHEN code = 2 THEN 1 END) +
        COUNT(CASE WHEN code = 3 THEN 1 END) < 2;

The HAVING clause ensures that any matching ID has a code of 1, and also that a code of 2 or 3 happens at most once (i.e. having a code both of 2 and 3 is forbidden, though one or the other is allowed).


问:
Route on notification open
Im using react-native-notifications by wix.

I am having trouble routing to a specific screen when notification is opened. I have tried following this https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html. But it is giving me an error.

```<code>import React, { Component } from 'react';
import AppNavigator from './navigation/AppNavigator';
import NetInfo from "@react-native-community/netinfo";
import AppNavigator from './navigation/AppNavigator';
import { NavigationActions } from 'react-navigation';

let _navigator;
function setTopLevelNavigator(navigatorRef) {
_navigator = navigatorRef;
}

function navigate(routeName, params) {
_navigator.dispatch(
 NavigationActions.navigate({
  routeName,
  params,
  })
 );
 }

export default class App extends Component {
constructor(props) {
super(props)

const unsubscribe = NetInfo.addEventListener(state => {
  console.log("Connection type", state.type);
  console.log("Is connected?", state.isConnected);
  navigate("Rating");
});

Notifications.events().registerNotificationOpened((notification, action,
completion) => {
  console.log("Notification opened by device user",
notification.payload);
});

render() {
return (
  <Provider store={store}>
    <Root>
       <AppNavigator ref={navigatorRef => {setTopLevelNavigator(navigatorRef)
  }}/>
    </Root>
  </Provider>
 );
 }
}
</code>```

答:
Step 1: First create a variable to hold navigator like this, place it on top of App.js below the imports

```<code>let _navigator;
function setTopLevelNavigator(navigatorRef) {
  _navigator = navigatorRef;
}
</code>```

Step 2: Then add a ref property to your AppNavigator like this.

```<code>ref={navigatorRef => { setTopLevelNavigator(navigatorRef); }}
</code>```

Step 3: Write the navigate function, which you can call inside the onNotificationRecevied

```<code>function navigate(routeName, params) {
  _navigator.dispatch(
    NavigationActions.navigate({
      routeName,
      params,
    })
  );
}
</code>```

Step 4: Navigate user on receiving notification

```<code>constructor(props) {
    super(props)
    Notifications.events().registerNotificationOpened((notification, action, completion) => {
        navigate("YOURSCREEN", { params:<date-from-notification-or-any-data> });
    })
}
</code>```

PS: Don't forget to import NavigationActions from 'react-natigation'

Title: Route on notification open

Body:
Im using react-native-notifications by wix.

I am having trouble routing to a specific screen when notification is opened. I have tried following this https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html. But it is giving me an error.

import React, { Component } from 'react';
import AppNavigator from './navigation/AppNavigator';
import NetInfo from "@react-native-community/netinfo";
import AppNavigator from './navigation/AppNavigator';
import { NavigationActions } from 'react-navigation';

let _navigator;
function setTopLevelNavigator(navigatorRef) {
_navigator = navigatorRef;
}

function navigate(routeName, params) {
_navigator.dispatch(
 NavigationActions.navigate({
  routeName,
  params,
  })
 );
 }

export default class App extends Component {
constructor(props) {
super(props)

const unsubscribe = NetInfo.addEventListener(state => {
  console.log("Connection type", state.type);
  console.log("Is connected?", state.isConnected);
  navigate("Rating");
});

Notifications.events().registerNotificationOpened((notification, action,
completion) => {
  console.log("Notification opened by device user",
notification.payload);
});

render() {
return (
  <Provider store={store}>
    <Root>
       <AppNavigator ref={navigatorRef => {setTopLevelNavigator(navigatorRef)
  }}/>
    </Root>
  </Provider>
 );
 }
}

Body:
Step 1: First create a variable to hold navigator like this, place it on top of App.js below the imports

let _navigator;
function setTopLevelNavigator(navigatorRef) {
  _navigator = navigatorRef;
}

Step 2: Then add a ref property to your AppNavigator like this.

ref={navigatorRef => { setTopLevelNavigator(navigatorRef); }}

Step 3: Write the navigate function, which you can call inside the onNotificationRecevied

function navigate(routeName, params) {
  _navigator.dispatch(
    NavigationActions.navigate({
      routeName,
      params,
    })
  );
}

Step 4: Navigate user on receiving notification

constructor(props) {
    super(props)
    Notifications.events().registerNotificationOpened((notification, action, completion) => {
        navigate("YOURSCREEN", { params:<date-from-notification-or-any-data> });
    })
}

PS: Don't forget to import NavigationActions from 'react-natigation'


问:
My second scanf is not working - what can I do?
My second scanf in this code is not working, the computer doesn't wait for me to enter the second value.

I know when it happens with %c it is just need to put a space before the %
But can't make it work with %f

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

main()
{
    float a, p;
    printf("Insira seu peso: "); scanf("%.1f", &p);
    printf("Insira sua altura: "); scanf("%.2f", &a);
}
</code>```

答:
Actually not a single scanf is working properly in the code. When we use scanf we are just going to get the answer from the user so we do not need a (.) before the variable "f", float in there. We can make adjustments when we print the number that the user has put. Below I have shown an example:</p>

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

int main()
{
float a, p;
printf("\n Please enter 1st value: ");
scanf("%f", &p);
printf("\n Please enter 2nd value: ");
scanf("%f", &a);

printf("\n The value of p is: %.1f", p);
printf("\n The value of a is: %.2f", a);

printf("\n\n");

system("PAUSE");
return(0);
}
</code>```

Body:
My second scanf in this code is not working, the computer doesn't wait for me to enter the second value.

I know when it happens with %c it is just need to put a space before the %
But can't make it work with %f

#include <stdlib.h>
#include <stdio.h>

main()
{
    float a, p;
    printf("Insira seu peso: "); scanf("%.1f", &p);
    printf("Insira sua altura: "); scanf("%.2f", &a);
}

Body:
Actually not a single scanf is working properly in the code. When we use scanf we are just going to get the answer from the user so we do not need a (.) before the variable "f", float in there. We can make adjustments when we print the number that the user has put. Below I have shown an example:

#include<stdio.h>
#include<stdlib.h>

int main()
{
float a, p;
printf("\n Please enter 1st value: ");
scanf("%f", &p);
printf("\n Please enter 2nd value: ");
scanf("%f", &a);

printf("\n The value of p is: %.1f", p);
printf("\n The value of a is: %.2f", a);

printf("\n\n");

system("PAUSE");
return(0);
}


问:
How to prevent ad blocker from blocking ads on an app
One of my users let the cat out of the bag and told me they were using one of my free apps, which is monetized by ads, but they were blocking the ads with an ad blocker. They told me this mockingly, as if I can't do anything about it.

Can I do something about it? Is there a way to detect that ads are being blocked?

答:
First, let me say that I believe that Ad Blocking, when it comes to applications, is actually a form of piracy. These apps are supported by the ads, and sometimes, a "paid license" to turn off ads and/or add features. By blocking ads, users are stealing potential revenue from the developer that took the time to create the app that you are using.

Anyhow, I want to add a way to help prevent the use of Ad Blockers. I use this method and I do not allow users to use the app if I detect an ad blocker. People get very angry and will give you poor ratings for it. But I also state very clearly in my applications descriptions that you will not be able to use the app if you have an adblocker.

I use the package manager to check if a specific package is installed. While this will not get all of the adblockers, if you keep "up to date" on some of the popular ones, you can get most of them.

```<code>PackageManager pm = activity.getPackageManager ();
Intent intent = pm.getLaunchIntentForPackage ( "de.ub0r.android.adBlock" );
if ( Reflection.isPackageInstalled ( activity, intent ) ) {
  // they have adblock installed
}
</code>```

Body:
First, let me say that I believe that Ad Blocking, when it comes to applications, is actually a form of piracy. These apps are supported by the ads, and sometimes, a "paid license" to turn off ads and/or add features. By blocking ads, users are stealing potential revenue from the developer that took the time to create the app that you are using.

Anyhow, I want to add a way to help prevent the use of Ad Blockers. I use this method and I do not allow users to use the app if I detect an ad blocker. People get very angry and will give you poor ratings for it. But I also state very clearly in my applications descriptions that you will not be able to use the app if you have an adblocker.

I use the package manager to check if a specific package is installed. While this will not get all of the adblockers, if you keep "up to date" on some of the popular ones, you can get most of them.

PackageManager pm = activity.getPackageManager ();
Intent intent = pm.getLaunchIntentForPackage ( "de.ub0r.android.adBlock" );
if ( Reflection.isPackageInstalled ( activity, intent ) ) {
  // they have adblock installed
}


问:
In flutter, how to add an outline button that look like a text field with underline?
In flutter, how to add an outline button that look like a text field with underline? I only need a bottom underline.</p>

```<code>           OutlineButton(
              color: Theme.of(context).buttonColor,
              textColor: Theme.of(context).textTheme.bodyText1.color,
              // disabledColor: Colors.grey,
              disabledTextColor: Colors.black,
              borderSide: (),
              onPressed: () {

              },
          child: Center(
            child: Text(
              "No Reminder",
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 18.0),
            ),
          ),
            )
</code>```

答:
You can use BoxDecoration as parent of your button. OutlineButton outlines all 4 sides or none.
Have a look at their documentation here https://api.flutter.dev/flutter/painting/BorderSide-class.html</p>

Body:
In flutter, how to add an outline button that look like a text field with underline? I only need a bottom underline.

           OutlineButton(
              color: Theme.of(context).buttonColor,
              textColor: Theme.of(context).textTheme.bodyText1.color,
              // disabledColor: Colors.grey,
              disabledTextColor: Colors.black,
              borderSide: (),
              onPressed: () {

              },
          child: Center(
            child: Text(
              "No Reminder",
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 18.0),
            ),
          ),
            )


问:
Android Docx4J Gradle: Duplicate class org.slf4j despite excluding it
I am trying to use the Docx4j library in order to read in the contents of MS Word files selected by the user (I am trying to install it through this example: https://github.com/plutext/Docx4j4Android4). However, I receive the following error when I read in a MS Word file (I didn't include all the errors, but the duplicate classes all belong to org.slf4j.*):

```<code>Duplicate class org.slf4j.ILoggerFactory found in modules slf4j-android-1.6.1-RC1.jar (slf4j-android-1.6.1-RC1.jar) and slf4j-api-1.7.21.jar (org.slf4j:slf4j-api:1.7.21)
Duplicate class org.slf4j.IMarkerFactory found in modules slf4j-android-1.6.1-RC1.jar (slf4j-android-1.6.1-RC1.jar) and slf4j-api-1.7.21.jar (org.slf4j:slf4j-api:1.7.21)
Duplicate class org.slf4j.Logger found in modules slf4j-android-1.6.1-RC1.jar (slf4j-android-1.6.1-RC1.jar) and slf4j-api-1.7.21.jar (org.slf4j:slf4j-api:1.7.21)
........
</code>```

This seems strange, since in my build.gradle, I explicity exclude org.sl4j when implementing the docx4j library.

Below is my build.gradle code:

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.diffchecker"
        minSdkVersion 21
        targetSdkVersion 29
        multiDexEnabled true
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    dexOptions {
        // Comment the following in order to see actual errors, not unhelpful "too many errors"!
//        preDexLibraries = false
        additionalParameters=['--core-library']
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
        exclude("META-INF/*.kotlin_module")
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'io.github.java-diff-utils:java-diff-utils:4.5'
    // For developers using AndroidX in their applications
    implementation 'pub.devrel:easypermissions:3.0.0'
    // For developers using the Android Support Library
    implementation 'pub.devrel:easypermissions:2.0.1'
    implementation 'com.google.android.gms:play-services-ads:18.3.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    //implementation files('libs/commons-text-1.2.jar')
    implementation files('libs/commons-lang3-3.7.jar')
    //Thanks for using https://jar-download.com
    implementation 'org.webjars.bowergithub.telecomsante:pdf-viewer:2.2.0'
    implementation 'com.tom_roush:pdfbox-android:1.8.10.1'
    //implementation files('libs/commons-logging-1.2.jar')
    implementation 'com.bskim:maxheightscrollview:1.0.0@aar'
    implementation 'androidx.gridlayout:gridlayout:1.0.0'
    // Docx4j is the library used to read Word documents
    // https://mvnrepository.com/artifact/org.docx4j/docx4j
    implementation files('libs/commons-lang3-3.7.jar')
    implementation files('libs/commons-text-1.2.jar')

    //implementationtestCompile 'junit:junit:4.12'
    implementation 'javax.xml.bind:jaxb-api:2.2.12'
    implementation 'javax.xml.stream:stax-api:1.0-2'
    implementation 'com.fasterxml:aalto-xml:1.0.0'
    //compile 'org.codehaus.woodstox:stax2-api:4.0.0'
    implementation files('libs/awt-bastardised-17v8.jar')
    implementation files('libs/slf4j-android-1.6.1-RC1.jar')
    implementation files('libs/activation.jar')
    implementation files('libs/additionnal.jar')
    implementation files('libs/jaxb-core-2.3.0-SNAPSHOT-ANDROID.jar')
    implementation files('libs/jaxb-runtime-2.3.0-SNAPSHOT-ANDROID.jar')
    implementation files('libs/istack-commons-runtime-3.0.4-SNAPSHOT.jar')
    // with org.slf4j removed
    implementation('org.docx4j:docx4j:3.3.0') {
        ['org.apache.commons', 'commons-logging', 'org.sl4j'].each {
            exclude group: "$it"
        }
    }

}
</code>```

And below is a screenshot of the library jar files I have:

答: When looking at org.docx4j:docx4j:6.1.2, this raises the question, what you even need libs/slf4j-android-1.6.1-RC1.jar for? org.slf4j is already included and it works on Android without these Android bindings; pdfbox-android is about the same cheese .When reading over these demands - there barely is any real attempt noticeable; because there's no Java/Kotlin code at all.

Body:
I am trying to use the Docx4j library in order to read in the contents of MS Word files selected by the user (I am trying to install it through this example: https://github.com/plutext/Docx4j4Android4). However, I receive the following error when I read in a MS Word file (I didn't include all the errors, but the duplicate classes all belong to org.slf4j.*):

Duplicate class org.slf4j.ILoggerFactory found in modules slf4j-android-1.6.1-RC1.jar (slf4j-android-1.6.1-RC1.jar) and slf4j-api-1.7.21.jar (org.slf4j:slf4j-api:1.7.21)
Duplicate class org.slf4j.IMarkerFactory found in modules slf4j-android-1.6.1-RC1.jar (slf4j-android-1.6.1-RC1.jar) and slf4j-api-1.7.21.jar (org.slf4j:slf4j-api:1.7.21)
Duplicate class org.slf4j.Logger found in modules slf4j-android-1.6.1-RC1.jar (slf4j-android-1.6.1-RC1.jar) and slf4j-api-1.7.21.jar (org.slf4j:slf4j-api:1.7.21)
........

This seems strange, since in my build.gradle, I explicity exclude org.sl4j when implementing the docx4j library.

Below is my build.gradle code:

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.diffchecker"
        minSdkVersion 21
        targetSdkVersion 29
        multiDexEnabled true
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    dexOptions {
        // Comment the following in order to see actual errors, not unhelpful "too many errors"!
//        preDexLibraries = false
        additionalParameters=['--core-library']
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
        exclude("META-INF/*.kotlin_module")
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'io.github.java-diff-utils:java-diff-utils:4.5'
    // For developers using AndroidX in their applications
    implementation 'pub.devrel:easypermissions:3.0.0'
    // For developers using the Android Support Library
    implementation 'pub.devrel:easypermissions:2.0.1'
    implementation 'com.google.android.gms:play-services-ads:18.3.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    //implementation files('libs/commons-text-1.2.jar')
    implementation files('libs/commons-lang3-3.7.jar')
    //Thanks for using https://jar-download.com
    implementation 'org.webjars.bowergithub.telecomsante:pdf-viewer:2.2.0'
    implementation 'com.tom_roush:pdfbox-android:1.8.10.1'
    //implementation files('libs/commons-logging-1.2.jar')
    implementation 'com.bskim:maxheightscrollview:1.0.0@aar'
    implementation 'androidx.gridlayout:gridlayout:1.0.0'
    // Docx4j is the library used to read Word documents
    // https://mvnrepository.com/artifact/org.docx4j/docx4j
    implementation files('libs/commons-lang3-3.7.jar')
    implementation files('libs/commons-text-1.2.jar')

    //implementationtestCompile 'junit:junit:4.12'
    implementation 'javax.xml.bind:jaxb-api:2.2.12'
    implementation 'javax.xml.stream:stax-api:1.0-2'
    implementation 'com.fasterxml:aalto-xml:1.0.0'
    //compile 'org.codehaus.woodstox:stax2-api:4.0.0'
    implementation files('libs/awt-bastardised-17v8.jar')
    implementation files('libs/slf4j-android-1.6.1-RC1.jar')
    implementation files('libs/activation.jar')
    implementation files('libs/additionnal.jar')
    implementation files('libs/jaxb-core-2.3.0-SNAPSHOT-ANDROID.jar')
    implementation files('libs/jaxb-runtime-2.3.0-SNAPSHOT-ANDROID.jar')
    implementation files('libs/istack-commons-runtime-3.0.4-SNAPSHOT.jar')
    // with org.slf4j removed
    implementation('org.docx4j:docx4j:3.3.0') {
        ['org.apache.commons', 'commons-logging', 'org.sl4j'].each {
            exclude group: "$it"
        }
    }

}

And below is a screenshot of the library jar files I have:


问:
Does anyone know any magic command to display wall clock time (i.e. say 21:15:00) of the cell executie on in Jupyter Notebook?
How can I display time of execution of a particular cell in Jupyter Notebook? For example if cell execution started at 21:00 pm, it should display 21:00 pm (or even more precisely) once execution of a particular cell is complete. Is there any magic command for that?</p>

答:
Not very magic:</p>

```<code>from datetime import datetime
print(datetime.now())
</code>```

Body:
Not very magic:

from datetime import datetime
print(datetime.now())


问:
tls: server selected unsupported protocol version 301
I have local kubernetes cluster on vm.
I use containerd as a CRI.
and when i install calico, have the next error with calico-kube-controllers

"Warning  FailedCreatePodSandBox  2m41s (x638 over 140m)  kubelet,
serverhostname  (combined from similar events): Failed to create pod
sandbox: rpc error: code = Unknown desc = failed to setup network for
sandbox
"a46b6b0c52c2adec7749fff781401e481ca911a198e0406d7fa646c6d5d5e781":
error getting ClusterInformation: Get
https://[10.96.0.1]:443/apis/crd.projectcalico.org/v1/clusterinformations/default: tls: server selected unsupported protocol version 301"

P.S with docker as a CRI, works fine

OS version Red Hat Enterprise Linux Server release 7.7 (Maipo)

Openssl version OpenSSL 1.1.1  11 Sep 2018

Configuring tls-min-version for kubelet and kube-api-server didn't help.

答:
solve the promlem.
my cluster works behind corp proxy, and containerd sent requests to 10.96.0.1 through the proxy.
i just add IP 10.96.0.1 to non proxy list to containerd proxy conf.</p>