问:
Problem in sorting using Comparator interface
I have created a ArrayList of HashMap like

```<code>ArrayList<HashMap<?,?>>  var = new ArrayList<HashMap<?,?>>();
</code>```

My HashMaps contains a String value "name" with key "name".What I want is to sort ArrayList by name so can I do this using Comparator?
Please Help Me.

答:
You could try something like this.

```<code>public int compare(Object o1, Object o2) {
  String one = (String)((HashMap)o1).get("name");
  String two = (String)((HashMap)o2).get("name");
  return one.compareTo(two);
}
</code>```

I haven't compiled this, so be sure to check its correct.  =)

Body:
I have created a ArrayList of HashMap like

ArrayList<HashMap<?,?>>  var = new ArrayList<HashMap<?,?>>();

My HashMaps contains a String value "name" with key "name".What I want is to sort ArrayList by name so can I do this using Comparator?
Please Help Me.

Body:
You could try something like this.

public int compare(Object o1, Object o2) {
  String one = (String)((HashMap)o1).get("name");
  String two = (String)((HashMap)o2).get("name");
  return one.compareTo(two);
}

I haven't compiled this, so be sure to check its correct.  =)


来源: stackexchange

问:
Node.js Application missing from Run Configuration
```<code>System Details
Machine: Mac Catalina
Eclipse: IDE for Javascript and Web Developers installed in system
Node version: v12.13.1
Protractor version: 7.0.0
</code>```

I have created the Protractor project in eclipse and created config.js and spec.js file
project structure in eclipse
 but when I tried to setup TestRunner I don't see Node.js Application under Run Configuration, not sure why it's missing
node.js Application is missing

Please let me know how to get Node.js Application under Run configuration so that I can create Test runner to un protracter test cases, similar to like this which is my expected screen under Run Configuration screen
Expected Node.js Applicaiton

答:
Use Nodeclipse https://nodeclipse.github.io/

File -> New -> Project -> Node.js Project

Choose "Hello Wold" project

Test is first

Then add your modules

see the demo screenshot https://nodeclipse.github.io/demos/navigation#/step-4

ContentLicense: CC BY-SA 4.0

Body:
System Details
Machine: Mac Catalina
Eclipse: IDE for Javascript and Web Developers installed in system
Node version: v12.13.1
Protractor version: 7.0.0

I have created the Protractor project in eclipse and created config.js and spec.js file
project structure in eclipse
 but when I tried to setup TestRunner I don't see Node.js Application under Run Configuration, not sure why it's missing
node.js Application is missing

Please let me know how to get Node.js Application under Run configuration so that I can create Test runner to un protracter test cases, similar to like this which is my expected screen under Run Configuration screen
Expected Node.js Applicaiton


问:
How to execute LINQ query at runtime c#
```<code>"((IEnumerable)sourceData).Cast().Select(ob =>
    new
    {
        SenderId = "Expo-HSE-01",
        IssueId = ob.IncidentNo.Value,
        IssuePointId = String.Join(",", ((IEnumerable)ob.TypeofIncident)
            .Cast()
            .Select(ip => ip.Value)),
        IssueTypeId = "Issue-HSE-General",
        ZoneId = ob.Location.LocationCode.Value
    }"
</code>```

<p>Getting above query as string need to execute this at runtime. </p>

答:
Parse string into a LINQ query

CSharpScripting able to execute the code getting as string.

Title: How to execute LINQ query at runtime c#

Body:
"((IEnumerable)sourceData).Cast().Select(ob =>
    new
    {
        SenderId = "Expo-HSE-01",
        IssueId = ob.IncidentNo.Value,
        IssuePointId = String.Join(",", ((IEnumerable)ob.TypeofIncident)
            .Cast()
            .Select(ip => ip.Value)),
        IssueTypeId = "Issue-HSE-General",
        ZoneId = ob.Location.LocationCode.Value
    }"

Getting above query as string need to execute this at runtime.


问:
Align  content to the left side the flexbox row rather than the right?
How can I align the nav items, Page One and Page Two so that they present to the left rather than to the right?  I can move the content center and to the end, but I simply need to move the two nav items to the left and the flexbox option don't seem to allow me to do so?  Please help, thank you.

#box1 {
  display: flex;
  flex-direction: row;
  min-height: 100vh;
}

#list1 {
  display: flex;
  align-content: space-between;
}

.list2 {
  list-style-type: none;
}

main {
  display: flex;
  flex: 1;
  flex-wrap: wrap;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="list1">
  <nav>
    <ul class="list2">
      <li>Page One</li>
      <li>Page Two</li>
    </ul>

  </nav>
</div></code>```

答:
If mean to have the nav anchors to be aligned left to each other you can simply add flex-inline the li elements if you mean to flex on nav:

.list2 {
  list-style-type: none;
  display: inline-flex;
}

.list2 li {
  margin-right: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="list1">
  <nav >
    <ul class="list2">
    <li>Page One</li>
    <li>Page Two</li>
  </ul>
  </nav>
</div></code>```

or you can also use inline-block on
 elements like in this snippet:

.list2 li {
  display:  inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="list1">
  <nav >
    <ul class="list2">
    <li>Page One</li>
    <li>Page Two</li>
  </ul>
  </nav>
</div></code>```

Title: Align <nav> content to the left side the flexbox row rather than the right?

Body:
How can I align the nav items, Page One and Page Two so that they present to the left rather than to the right?  I can move the content center and to the end, but I simply need to move the two nav items to the left and the flexbox option don't seem to allow me to do so?  Please help, thank you.

#box1 {
  display: flex;
  flex-direction: row;
  min-height: 100vh;
}

#list1 {
  display: flex;
  align-content: space-between;
}

.list2 {
  list-style-type: none;
}

main {
  display: flex;
  flex: 1;
  flex-wrap: wrap;
}

Page One

Page Two

Body:
If mean to have the nav anchors to be aligned left to each other you can simply add flex-inline the li elements if you mean to flex on nav:

.list2 {
  list-style-type: none;
  display: inline-flex;
}

.list2 li {
  margin-right: 5px;
}

<div id="list1">
  <nav >
    <ul class="list2">
    <li>Page One</li>
    <li><a href="page2.html">Page Two</a></li>
  </ul>
  </nav>
</div>

or you can also use inline-block on <li> elements like in this snippet:

.list2 li {
  display:  inline-block;
}

<div id="list1">
  <nav >
    <ul class="list2">
    <li>Page One</li>
    <li><a href="page2.html">Page Two</a></li>
  </ul>
  </nav>
</div>


问:
Unable to push to navigation controller
```<code> override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // 1: try loading the "Detail" view controller and typecasting it to be DetailViewController
    if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController {
        // 2: success! Set its selectedImage property
        vc.selectedImage = pictures[indexPath.row]

        // 3: now push it onto the navigation controller
        navigationController?.pushViewController(vc, animated: true)
    }
}
</code>```

I am facing issue -
1.Cast from 'UIViewController?' to unrelated type 'DetailViewController' always fails
2.Cannot convert value of type 'DetailViewController' to expected argument type 'UIViewController'

答:
Cast from 'UIViewController?' to unrelated type 'DetailViewController' always fails

Make sure that your DetailViewController is a subclass of UIViewController

```<code>class DetailViewController: UIVieController {
</code>```

Also you can use another way to do that and avoid storyboard?.instantiateViewController(withIdentifier:) method (and avoid possible mistakes with storyboard ID): add a segue from prototype tableView cell to your view controller on a storyboard

And then configure detailViewController in prepare(for segue) method of a viewController that owns tableView:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? DetailViewController {
        //configure vc properties here
    }
}
</code>```

Title: Unable to push to navigation controller

Body:
 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // 1: try loading the "Detail" view controller and typecasting it to be DetailViewController
    if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController {
        // 2: success! Set its selectedImage property
        vc.selectedImage = pictures[indexPath.row]

        // 3: now push it onto the navigation controller
        navigationController?.pushViewController(vc, animated: true)
    }
}

I am facing issue -
1.Cast from 'UIViewController?' to unrelated type 'DetailViewController' always fails
2.Cannot convert value of type 'DetailViewController' to expected argument type 'UIViewController'

Body:
Cast from 'UIViewController?' to unrelated type 'DetailViewController' always fails

Make sure that your DetailViewController is a subclass of UIViewController

class DetailViewController: UIVieController {

Also you can use another way to do that and avoid storyboard?.instantiateViewController(withIdentifier:) method (and avoid possible mistakes with storyboard ID): add a segue from prototype tableView cell to your view controller on a storyboard

And then configure detailViewController in prepare(for segue) method of a viewController that owns tableView:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? DetailViewController {
        //configure vc properties here
    }
}


问:
Made a class of Point in python but I'm not quite sure what i did wrong
```<code>#
class Point:

def __init__(self, x, y):
    self.x = x
    self.y = y

def __add__(self, x, y):
    return self.x + self.y

def __sub__(self, x, y):
    return self.x - self.y

p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2

print(p3)
</code>```

<p>OUTPUT:
I get an an output which is looking for the parameter of y but i think i already pass y to it </p>

```<code>Traceback (most recent call last):
  File "C:##################################", line 18, in <module>
    p3 = p1 + p2
TypeError: __add__() missing 1 required positional argument: 'y'
</code>```

答:
You need to indent the functions belonging to the class. Currently, Python thinks __add__ function has nothing to do with Point and has two arguments self and y. If it was indented, self would automatically be set to a reference to the instance.

The second issue is, in built-in magic methods, you only pass a reference to the other object explicitly and access the attributes of the calling object via self by the automatic referencing I mentioned.

```<code>class Point:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

    def __sub__(self, other):
        return Point(self.x - other.x, self.y - other.y)
</code>```

Body:
#
class Point:

def __init__(self, x, y):
    self.x = x
    self.y = y

def __add__(self, x, y):
    return self.x + self.y

def __sub__(self, x, y):
    return self.x - self.y

p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2

print(p3)

OUTPUT:
I get an an output which is looking for the parameter of y but i think i already pass y to it

Traceback (most recent call last):
  File "C:##################################", line 18, in <module>
    p3 = p1 + p2
TypeError: __add__() missing 1 required positional argument: 'y'

Body:
You need to indent the functions belonging to the class. Currently, Python thinks __add__ function has nothing to do with Point and has two arguments self and y. If it was indented, self would automatically be set to a reference to the instance.

The second issue is, in built-in magic methods, you only pass a reference to the other object explicitly and access the attributes of the calling object via self by the automatic referencing I mentioned.

class Point:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

    def __sub__(self, other):
        return Point(self.x - other.x, self.y - other.y)


问:
Pagedlist in partialview
I moved PagedList to PartialView because i use price filter in my page and when click on page number 2 nuber of elements in page are correct but all page was refreshed and i want to refresh only my partialview content. How can do that?

PartialView

```<code>@section Scripts{
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
}
<div class="col-md-12">
    Page: @(Model.Products.PageCount < Model.Products.PageNumber ? 0 : Model.Products.PageNumber)/@Model.Products.PageCount

    @Html.PagedListPager(Model.Products, page => Url.Action("FilterProducts",
    new { page, pageSize = ViewBag.psize }), PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions() { InsertionMode = InsertionMode.Replace, HttpMethod = "GET", UpdateTargetId = "tableContainer" }))
</div>
</code>```

Main View Calling Partial using javascript

```<code> function GetData(minPrice, maxPrice) {
             $.ajax({
                 url: '@Url.Action("FilterProducts", "Home")',
                 data: {
                     minPrice: minPrice,
                     maxPrice: maxPrice,
                     Category: '@Model.Category',
                     Search: '@Model.Search'
                 }
             })
             .done(function (result) {
                  $('#tableContainer').html(result);
             })
             .fail(function (XMLHttpRequest, textStatus, errorThrown)
            {
                alert("FAIL");
            });
        }
</code>```

```<code><div class="col-md-11" id="tableContainer">
            @{
                var filterProdViewModel = new FilterProductsViewModel();
                filterProdViewModel.Products = Model.Products;
                Html.RenderPartial("FilterProducts", filterProdViewModel);
             }
</div>
</code>```

Controller

```<code> public ActionResult Index(string Search, int? page, int? pageSize, int? maxPrice, int? minPrice, string Category = null)
        {

            IPagedList<Product> products;
            List<ProductCategory> prodCat = productCategories.Collection().ToList();
            if (Category == "")
                Category = null;
            int pagesize = (pageSize ?? 5);
            ViewBag.psize = pagesize;
            ViewBag.Min = prodScont.GetMinPrice();
            ViewBag.Max = prodScont.GetMaxPrice();

            products = prodScont.SearchProducts(minPrice, maxPrice, Category, Search).ToPagedList(page ?? 1, pagesize);

            ProductListViewModel model = new ProductListViewModel();
            model.Products = products;
            model.ProductCategories = prodCat;
            model.Category = Category;
            model.Search = Search;
            model.Page = page;
            return View(model);
        }

        public ActionResult FilterProducts(int? page, int? pageSize, int? maxPrice, int? minPrice, string Category = null, string Search = null)
        {
            FilterProductsViewModel model = new FilterProductsViewModel();
            IPagedList<Product> products;
            if (Category == "")
               Category = null;
            int pagesize = (pageSize ?? 5);
            ViewBag.psize = pagesize;

            products = prodScont.SearchProducts(minPrice, maxPrice, Category, Search).ToPagedList(page ?? 1, pagesize);

            model.Products = products;
            return PartialView(model);
        }
</code>```

答:
I found the problem i had to put pagenumber and pagesize paramethers to viewmodel and send it to partialview in my javascript to fix the problem </p>

```<code>function GetData(minPrice, maxPrice) {
             $.ajax({
                 url: '@Url.Action("FilterProducts", "Home")',
                 data: {
                     page: '@Model.Page',
                     pagesize: '@Model.PageSize',
                     minPrice: minPrice,
                     maxPrice: maxPrice,
                     Category: '@Model.Category',
                     Search: '@Model.Search'
                 }
             })
             .done(function (result) {
                  $('#tableContainer').html(result);
             })
             .fail(function (XMLHttpRequest, textStatus, errorThrown)
            {
                alert("FAIL");
            });
        }
    ```
</code>```

Title: Pagedlist in partialview

Body:
I moved PagedList to PartialView because i use price filter in my page and when click on page number 2 nuber of elements in page are correct but all page was refreshed and i want to refresh only my partialview content. How can do that?

PartialView

@section Scripts{

}

    Page: @(Model.Products.PageCount < Model.Products.PageNumber ? 0 : Model.Products.PageNumber)/@Model.Products.PageCount

    @Html.PagedListPager(Model.Products, page => Url.Action("FilterProducts",
    new { page, pageSize = ViewBag.psize }), PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions() { InsertionMode = InsertionMode.Replace, HttpMethod = "GET", UpdateTargetId = "tableContainer" }))

Main View Calling Partial using javascript

 function GetData(minPrice, maxPrice) {
             $.ajax({
                 url: '@Url.Action("FilterProducts", "Home")',
                 data: {
                     minPrice: minPrice,
                     maxPrice: maxPrice,
                     Category: '@Model.Category',
                     Search: '@Model.Search'
                 }
             })
             .done(function (result) {
                  $('#tableContainer').html(result);
             })
             .fail(function (XMLHttpRequest, textStatus, errorThrown)
            {
                alert("FAIL");
            });
        }

            @{
                var filterProdViewModel = new FilterProductsViewModel();
                filterProdViewModel.Products = Model.Products;
                Html.RenderPartial("FilterProducts", filterProdViewModel);
             }

Controller

 public ActionResult Index(string Search, int? page, int? pageSize, int? maxPrice, int? minPrice, string Category = null)
        {

            IPagedList<Product> products;
            List<ProductCategory> prodCat = productCategories.Collection().ToList();
            if (Category == "")
                Category = null;
            int pagesize = (pageSize ?? 5);
            ViewBag.psize = pagesize;
            ViewBag.Min = prodScont.GetMinPrice();
            ViewBag.Max = prodScont.GetMaxPrice();

            products = prodScont.SearchProducts(minPrice, maxPrice, Category, Search).ToPagedList(page ?? 1, pagesize);

            ProductListViewModel model = new ProductListViewModel();
            model.Products = products;
            model.ProductCategories = prodCat;
            model.Category = Category;
            model.Search = Search;
            model.Page = page;
            return View(model);
        }

        public ActionResult FilterProducts(int? page, int? pageSize, int? maxPrice, int? minPrice, string Category = null, string Search = null)
        {
            FilterProductsViewModel model = new FilterProductsViewModel();
            IPagedList<Product> products;
            if (Category == "")
               Category = null;
            int pagesize = (pageSize ?? 5);
            ViewBag.psize = pagesize;

            products = prodScont.SearchProducts(minPrice, maxPrice, Category, Search).ToPagedList(page ?? 1, pagesize);

            model.Products = products;
            return PartialView(model);
        }

Body:
I found the problem i had to put pagenumber and pagesize paramethers to viewmodel and send it to partialview in my javascript to fix the problem

function GetData(minPrice, maxPrice) {
             $.ajax({
                 url: '@Url.Action("FilterProducts", "Home")',
                 data: {
                     page: '@Model.Page',
                     pagesize: '@Model.PageSize',
                     minPrice: minPrice,
                     maxPrice: maxPrice,
                     Category: '@Model.Category',
                     Search: '@Model.Search'
                 }
             })
             .done(function (result) {
                  $('#tableContainer').html(result);
             })
             .fail(function (XMLHttpRequest, textStatus, errorThrown)
            {
                alert("FAIL");
            });
        }
    ```


问:
Tomcat 7.0.73 doesn't work with java 9
Unable to start tomcat based app with java 9 because of default "java.endorsed.dirs" option in catalina.sh.

```<code>-Djava.endorsed.dirs=/usr/local/share/tomcat/endorsed is not supported. Endorsed standards and standalone APIs in modular form will be supported via the concept of upgradeable modules.
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
</code>```

Is there a work around for this?

答:
I can't be sure but ..

Step 1 -- >
it worked for me, I just remove servers from eclipse

Step 2 -->
restarted and add server again (tomcat 7)
Tomcat v7.0 Server at localhost

ContentLicense: CC BY-SA 3.0

Title: Tomcat 7.0.73 doesn't work with java 9

Body:
Unable to start tomcat based app with java 9 because of default "java.endorsed.dirs" option in catalina.sh.

-Djava.endorsed.dirs=/usr/local/share/tomcat/endorsed is not supported. Endorsed standards and standalone APIs in modular form will be supported via the concept of upgradeable modules.
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

Is there a work around for this?


问:
Nest.js - nest cli is not picking up the latest file changes
I wrote a very basic controller like

@Controller('tasks')
export class TasksController {

  constructor(private tasksService: TasksService) {}

  @Get(':id')
  getById(@Param('id') id: string): TaskDto {
    console.log('Get Called>>>', id);
    const task = this.tasksService.getById(id);
    const dto = TaskMapper.toDto(task);

    return dto;
  }

  @Delete(':id')
  remove(@Param('id') id: string): void {
    console.log('Delete Called>>>', id);
    this.tasksService.remove(id);
  }
}

```

I'm using the following URI to call each endpoint via Postman (also tried with the Powershell) with their respective METHOD GET, DELETE.

http://localhost:3000/tasks/83b213a0-8cbf-46e0-a484-e3df7f216e2f

Now, the strangest thing is that CLI is somehow got stuck at one version of the Controller file. Now even if I delete the whole controller, the cli is still mapping the different methods of the Controller.

I've tried different methods of starting the application via various yarn, npm and directly nest commands but nothing seems to pick up the latest file changes.

I've gone through the whole code a zillion times but unable to pinpoint the issue!

答:
Finally got it working, solution was to delete the "dist" folder.

But I still don't understand why this problem occurred in the first place!!

Body:
I wrote a very basic controller like

@Controller('tasks')
export class TasksController {

  constructor(private tasksService: TasksService) {}

  @Get(':id')
  getById(@Param('id') id: string): TaskDto {
    console.log('Get Called>>>', id);
    const task = this.tasksService.getById(id);
    const dto = TaskMapper.toDto(task);

    return dto;
  }

  @Delete(':id')
  remove(@Param('id') id: string): void {
    console.log('Delete Called>>>', id);
    this.tasksService.remove(id);
  }
}

I'm using the following URI to call each endpoint via Postman (also tried with the Powershell) with their respective METHOD GET, DELETE.

http://localhost:3000/tasks/83b213a0-8cbf-46e0-a484-e3df7f216e2f

Now, the strangest thing is that CLI is somehow got stuck at one version of the Controller file. Now even if I delete the whole controller, the cli is still mapping the different methods of the Controller.

I've tried different methods of starting the application via various yarn, npm and directly nest commands but nothing seems to pick up the latest file changes.

I've gone through the whole code a zillion times but unable to pinpoint the issue!


问:
iPhone image stretching (skew)
How do I skew an image? For example, each corner has a CGPoint with coords - p1, p2, p3, p4. Then, I need to set - p4.x+=50, p4.y+=30. So this corner (p4) should be stretched in a 2D perspective and the image should be distorted.

(source: polar-b.com)

I tried to use CATransform3D, but it seems that this cannot be done in such way, since it's only a change the perspective of view (rotate, bring closer/farther one side). Maybe CGAffineTransform can be useful?

If you know the answer, please write a sample code.

Thanks in advance

答:
```<code>struct CATransform3D
{
   CGFloat m11, m12, m13, m14;
   CGFloat m21, m22, m23, m24;
   CGFloat m31, m32, m33, m34;
   CGFloat m41, m42, m43, m44;
};
</code>```

You have to adjust m24 and m14 to get such a shape.

Title: iPhone image stretching (skew)

Body:
struct CATransform3D
{
   CGFloat m11, m12, m13, m14;
   CGFloat m21, m22, m23, m24;
   CGFloat m31, m32, m33, m34;
   CGFloat m41, m42, m43, m44;
};

You have to adjust m24 and m14 to get such a shape.


答:
In your second example, the dimnames of your array is a named list, so you have to remove the names of this list:

```<code>names(dimnames(arr1)) <- NULL
</code>```

Title: Remove one layer of naming in multidimensional array in R

Body:
Comparing the following arrays:

> str(arr)
 num [1:77, 1:65, 1:40] NA NA NA NA NA NA NA NA NA NA ...
 - attr(*, "dimnames")=List of 3
  ..$ : chr [1:77] "2020-04-15T00:29:00.000000000+00:00" "2020-04-15T00:33:00.000000000+00:00" "2020-04-15T00:43:00.000000000+00:00" "2020-04-15T00:48:00.000000000+00:00" ...
  ..$ : chr [1:65] "1" "2" "3" "4" ...
  ..$ : chr [1:40] "v_1" "v_2" "v_3" "v_4" ...

> str(arr1)
 num [1:77, 1:65, 1:40] NA NA NA NA NA NA NA NA NA NA ...
 - attr(*, "dimnames")=List of 3
  ..$ mynano  : chr [1:77] "2020-04-15T00:29:00.000000000+00:00" "2020-04-15T00:33:00.000000000+00:00" "2020-04-15T00:43:00.000000000+00:00" "2020-04-15T00:48:00.000000000+00:00" ...
  ..$ mycat   : chr [1:65] "1" "2" "3" "4" ...
  ..$ values  : chr [1:40] "v_1" "v_2" "v_3" "v_4" ...

You can see arr1 has an additional layer of name, namely: mynano, mycat, and values, whereas arr does not.

How can I remove these names from arr1, while keeping the dimnames below it, as in arr?

Body:
In your second example, the dimnames of your array is a named list, so you have to remove the names of this list:

names(dimnames(arr1)) <- NULL


问:
What is this warning: ConvergenceWarning: lbfgs failed to converge (status=1)
How can I handle this warning??

```<code>Warning (from warnings module):

  File "C:\Users\SAMSUNG\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\linear_model\_logistic.py", line 762
    extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)
ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
</code>```

```<code>urls_data = pd.read_csv("data.csv")
TEST_SIZE = 0.001
type(urls_data)
urls_data.head()

def makeTokens(f):
    tkns_BySlash = str(f.encode('utf-8')).split('/')
    total_Tokens = []
    for i in tkns_BySlash :
        tokens = str(i).split('-')
        tkns_ByDot = []
        for j in range(0, len(tokens)):
            temp_Tokens = str(tokens[j]).split('.')
            tkns_ByDot = tkns_ByDot + temp_Tokens
        total_Tokens = total_Tokens + tokens + tkns_ByDot
    total_Tokens = list(set(total_Tokens))
    if 'com' in total_Tokens:
        total_Tokens.remove('com')
    return total_Tokens

y = urls_data["label"]
url_list = urls_data["url"]
#Data Preprocessing
vectorizer = TfidfVectorizer(tokenizer=makeTokens)
X = vectorizer.fit_transform(url_list)

#Split Train set and Test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = TEST_SIZE, random_state = 42)
###############################logit
logit = LogisticRegression()
logit.fit(X_train, y_train)
</code>```

and this is my code

答:
Change

logit = LogisticRegression()

to

logit = LogisticRegression(max_iter=10000)

and try again.

(Default parameter max_iter of LogisticRegression() equals 1000, so any number larger than 1000 is fine, not necessarily 10000)

You may also standardize your data as the warning said, with sklearn.preprocessing.scale().

Body:
How can I handle this warning??

Warning (from warnings module):

  File "C:\Users\SAMSUNG\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\linear_model\_logistic.py", line 762
    extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)
ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression

urls_data = pd.read_csv("data.csv")
TEST_SIZE = 0.001
type(urls_data)
urls_data.head()

def makeTokens(f):
    tkns_BySlash = str(f.encode('utf-8')).split('/')
    total_Tokens = []
    for i in tkns_BySlash :
        tokens = str(i).split('-')
        tkns_ByDot = []
        for j in range(0, len(tokens)):
            temp_Tokens = str(tokens[j]).split('.')
            tkns_ByDot = tkns_ByDot + temp_Tokens
        total_Tokens = total_Tokens + tokens + tkns_ByDot
    total_Tokens = list(set(total_Tokens))
    if 'com' in total_Tokens:
        total_Tokens.remove('com')
    return total_Tokens

y = urls_data["label"]
url_list = urls_data["url"]
#Data Preprocessing
vectorizer = TfidfVectorizer(tokenizer=makeTokens)
X = vectorizer.fit_transform(url_list)

#Split Train set and Test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = TEST_SIZE, random_state = 42)
###############################logit
logit = LogisticRegression()
logit.fit(X_train, y_train)

and this is my code


问:
Why would CURL time out in 1000ms when I have set up timeout upto 3000ms?
In one of my script I have set up curl time out, CURLOPT_CONNECTTIMEOUT_MS, to 3000ms, but curl time outs much before than that, at an average of 1000ms. Why would it time out so early? </p>

答: Check the version of your CURL and PHP installation. CURLOPT_CONNECTTIMEOUT_MS added in cURL 7.16.2. Available since PHP 5.2.3. http://php.net/manual/en/function.curl-setopt.php</p>


问:
SELECTION SORT USING POINTERS AND FUNCTIONS IN C
```<code>#include<stdio.h>
void functt(int *,int );
int main {
int n;
scanf("%d",&n);
printf("Enter the elements of the array");
int i;
int arr[n];
int *ptr;
ptr=arr;
for (i=0;i<n;i++)
{
    scanf("%d",(p+i));
}
printf("The array elemets are as follows");
for (i=0;i<n;i++)
{
    printf("%d",*(p+i));
}
void functt(arr,n);
return 0;
}

void functt(int *,int n)
{
    int i,j,min;
    for (i=0;i<n;i++)
    {
        min=i;

        for (j=i+1;j<n;j++)
        {
            if(*(p+min)>*(p+j))
            {
                min=j;
            }

        }
    int temp=*(p+min);
    *(p+min)=*(p+j);
    *(p+j)=temp;
}
</code>```

ERRORS:
 https://i.stack.imgur.com/T2iLq.png

Can't run this code due to these errors
PROGRAM IS TO USE SELECTION SORT VIA POINTERS AND FUNCTIONS.
LOGIC SEEMS TO BE CORRECT I THINK BUT IT GIVES SOME ERRORS AS IN THE PNG ATTACHED ABOVE.

答:
There were quite a lot of errors in here. You had named your array pointer ptr but then tried to use one called "p" instead. You had missing brackets in a few places. If you lay out your code nicely, these errors are much easier to see. I have fixed the compile errors in your code and re-arranged the sort function.

Note : I've made a very minimal set of changes in the hope you can see what I did. This is not necessarily the best way to write this code.

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

void functt(int *,int );

int main () {
    int n;

    scanf("%d",&n);
    printf("Enter the elements of the array: ");

    int arr[n];
    int *ptr;
    ptr=arr;

    for (int i=0;i<n;i++)
    {
        scanf("%d",(ptr+i));
    }

    printf("\nThe array elements are as follows: ");
    for (int i=0;i<n;i++)
    {
        printf("%d ",*(ptr+i));
    }

    functt(arr,n);

    printf("\nThe array elements are sorted as follows: ");
    for (int i=0;i<n;i++)
    {
        printf("%d ",*(ptr+i));
    }
    printf("\n");

    return 0;
}

void functt(int *p,int n)
{
    int min;

    for (int i=0;i<n;i++)
    {
        min=i;

        for (int j=i+1;j<n;j++)
        {
            if(*(p+min)>*(p+j))
            {
                int temp=*(p+min);
                *(p+min)=*(p+j);
                *(p+j)=temp;
            }

        }
    }
}
</code>```

Body:
#include<stdio.h>
void functt(int *,int );
int main {
int n;
scanf("%d",&n);
printf("Enter the elements of the array");
int i;
int arr[n];
int *ptr;
ptr=arr;
for (i=0;i<n;i++)
{
    scanf("%d",(p+i));
}
printf("The array elemets are as follows");
for (i=0;i<n;i++)
{
    printf("%d",*(p+i));
}
void functt(arr,n);
return 0;
}

void functt(int *,int n)
{
    int i,j,min;
    for (i=0;i<n;i++)
    {
        min=i;

        for (j=i+1;j<n;j++)
        {
            if(*(p+min)>*(p+j))
            {
                min=j;
            }

        }
    int temp=*(p+min);
    *(p+min)=*(p+j);
    *(p+j)=temp;
}

ERRORS:
 https://i.stack.imgur.com/T2iLq.png

Can't run this code due to these errors
PROGRAM IS TO USE SELECTION SORT VIA POINTERS AND FUNCTIONS.
LOGIC SEEMS TO BE CORRECT I THINK BUT IT GIVES SOME ERRORS AS IN THE PNG ATTACHED ABOVE.

Body:
There were quite a lot of errors in here. You had named your array pointer ptr but then tried to use one called "p" instead. You had missing brackets in a few places. If you lay out your code nicely, these errors are much easier to see. I have fixed the compile errors in your code and re-arranged the sort function.

Note : I've made a very minimal set of changes in the hope you can see what I did. This is not necessarily the best way to write this code.

#include<stdio.h>

void functt(int *,int );

int main () {
    int n;

    scanf("%d",&n);
    printf("Enter the elements of the array: ");

    int arr[n];
    int *ptr;
    ptr=arr;

    for (int i=0;i<n;i++)
    {
        scanf("%d",(ptr+i));
    }

    printf("\nThe array elements are as follows: ");
    for (int i=0;i<n;i++)
    {
        printf("%d ",*(ptr+i));
    }

    functt(arr,n);

    printf("\nThe array elements are sorted as follows: ");
    for (int i=0;i<n;i++)
    {
        printf("%d ",*(ptr+i));
    }
    printf("\n");

    return 0;
}

void functt(int *p,int n)
{
    int min;

    for (int i=0;i<n;i++)
    {
        min=i;

        for (int j=i+1;j<n;j++)
        {
            if(*(p+min)>*(p+j))
            {
                int temp=*(p+min);
                *(p+min)=*(p+j);
                *(p+j)=temp;
            }

        }
    }
}


问:
Time complexity of Python Function Involving List Operations
When I plot the time taken for the following algorithm for different size input, the time complexity appears to be polynomial. I'm not sure which operations account for this.

I'm assuming it's to do with list(s), del l[i] and l[::-1], but I'm not clear what the complexity of these is individually. Can anyone please explain?

Also, is there a way to optimize the algorithm without completely changing the approach? (I know there is a way to bring it down to linear time complexity by using "double-ended pincer-movement".)

```<code>def palindrome_index(s):
    for i, c in enumerate(s):
        l = list(s)
        del l[i]
        if l[::-1] == l:
            return i
    return -1
</code>```

答:
Your algorithm indeed is quadratic in len(s):

In iteration i, you perform linear time operations in the length: creating the list, reversing it, and (on linear on average) erasing element i. Since you perform this len(s) times, it is quadratic in len(s).

I'm assuming it's to do with list(s), del l[i] and l[::-1], but I'm not clear what the complexity of these is individually. Can anyone please explain?

Each of these operations is linear time (at least on average, which is enough to analyze your algorithm). Constructing a list, either from an iterable, or by reversing an existing list, is linear in the length of the list. Deleting element i, at the very least, requires about n - i + 1 shifts of the elements, as each one is moved back once.

Body:
When I plot the time taken for the following algorithm for different size input, the time complexity appears to be polynomial. I'm not sure which operations account for this.

I'm assuming it's to do with list(s), del l[i] and l[::-1], but I'm not clear what the complexity of these is individually. Can anyone please explain?

Also, is there a way to optimize the algorithm without completely changing the approach? (I know there is a way to bring it down to linear time complexity by using "double-ended pincer-movement".)

def palindrome_index(s):
    for i, c in enumerate(s):
        l = list(s)
        del l[i]
        if l[::-1] == l:
            return i
    return -1


问:
Test calling of an external script run via Popen that expects no available data in stdin using pytest
I have an external tool with a command line interface that checks whether any data is provided via stdin by using sys.stdin in select.select([sys.stdin], [], [], 0)[0] and adjusts the expected parameters accordingly. I call this external tool via subprocess and rely on the use case where there is no input provided via stdin.

Now I want to run an automated integration test on this functionality via pytest. But I cannot get it to work without providing the pytest command line option --capture=sys disabling capturing on file descriptor level for all tests. In any other case (also when using capfd.disabled() or capsys.disabled() around the call within the test as these only disable stdout and stderr but not stdin capture), the external tool detects that there would be input provided via stdin, triggering the incorrect conclusions about other parameters and thus causing my test to fail.

For the sake of an example, I basically have something like the following files:

external_script.py:

```<code>import select
import sys

print(sys.stdin in select.select([sys.stdin], [], [], 0)[0])
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
    print(sys.stdin.readline().strip())
print(sys.argv)
</code>```

internal_part.py:

```<code>import subprocess

def call_external():
    popen = subprocess.Popen(["/usr/bin/python3", "external_script.py", "1"],
                             stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    print(popen.communicate()[:2])

if __name__ == "__main__":
    call_external()
</code>```

test.py:

```<code>import internal_part

def test(capsys):
    with capsys.disabled():  # or capfd.disabled()
        internal_part.call_external()
</code>```

When I now run internal_part.py via python, I get the expected output, that sys.stdin is not returned by the call to select.select and thus that no input is available in stdin. But when I run test.py via pytest without --capture=sys, I get output indicating that data was provided via stdin. Reading from sys.stdin then gives an empty string.

If the select.select call where within the internal part, I at least would get an error that this is an unsupported operation of the pseudofile being the redirected stdin. For the external tool, running in its own interpreter, I don't get any indication that something went wrong except that erroneously stdin is detected to provide input.

Is there any option to get this test scenario to work, e.g. by disabling the capture of stdin for this specific test, without disabling the capture on the file descriptor level for all my tests in that test suite?

答:
If you are willing to generate and explicitly pass a file descriptor that is not ready for reading in the production code1, you can generate a new named pipe via os.pipe and pass its reading end as stdin. Obviously, it is somewhat of a workaround for the strange interface to generate a new pipe with the sole purpose of it being empty. But as long as you don't write anything into the pipe, the pipe should not be ready for reading and thus the select.select call should not pick it up. The internal part could then look somewhat like the code below:

```<code>import contextlib
import os
import subprocess

@contextlib.contextmanager
def not_ready_to_read():
    try:
        read_end, write_end = os.pipe()
        yield read_end
    finally:
        os.close(read_end)
        os.close(write_end)

def call_external():
    with not_ready_to_read() as not_ready_stdin:
        popen = subprocess.Popen(["/usr/bin/python3", "external_script.py", "1"],
                                 stdin=not_ready_stdin, stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
        print(popen.communicate()[:2])

if __name__ == "__main__":
    call_external()
</code>```

1This can also help you with other situations where the test via select.select erroneously suggests that some data is passed via stdin, such as if you run the script via the slurm job scheduler. Therefore, it's not an adaption of the production code with the sole purpose of enabling the test.

Body:
I have an external tool with a command line interface that checks whether any data is provided via stdin by using sys.stdin in select.select([sys.stdin], [], [], 0)[0] and adjusts the expected parameters accordingly. I call this external tool via subprocess and rely on the use case where there is no input provided via stdin.

Now I want to run an automated integration test on this functionality via pytest. But I cannot get it to work without providing the pytest command line option --capture=sys disabling capturing on file descriptor level for all tests. In any other case (also when using capfd.disabled() or capsys.disabled() around the call within the test as these only disable stdout and stderr but not stdin capture), the external tool detects that there would be input provided via stdin, triggering the incorrect conclusions about other parameters and thus causing my test to fail.

For the sake of an example, I basically have something like the following files:

external_script.py:

import select
import sys

print(sys.stdin in select.select([sys.stdin], [], [], 0)[0])
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
    print(sys.stdin.readline().strip())
print(sys.argv)

internal_part.py:

import subprocess

def call_external():
    popen = subprocess.Popen(["/usr/bin/python3", "external_script.py", "1"],
                             stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    print(popen.communicate()[:2])

if __name__ == "__main__":
    call_external()

test.py:

import internal_part

def test(capsys):
    with capsys.disabled():  # or capfd.disabled()
        internal_part.call_external()

When I now run internal_part.py via python, I get the expected output, that sys.stdin is not returned by the call to select.select and thus that no input is available in stdin. But when I run test.py via pytest without --capture=sys, I get output indicating that data was provided via stdin. Reading from sys.stdin then gives an empty string.

If the select.select call where within the internal part, I at least would get an error that this is an unsupported operation of the pseudofile being the redirected stdin. For the external tool, running in its own interpreter, I don't get any indication that something went wrong except that erroneously stdin is detected to provide input.

Is there any option to get this test scenario to work, e.g. by disabling the capture of stdin for this specific test, without disabling the capture on the file descriptor level for all my tests in that test suite?

Body:
If you are willing to generate and explicitly pass a file descriptor that is not ready for reading in the production code1, you can generate a new named pipe via os.pipe and pass its reading end as stdin. Obviously, it is somewhat of a workaround for the strange interface to generate a new pipe with the sole purpose of it being empty. But as long as you don't write anything into the pipe, the pipe should not be ready for reading and thus the select.select call should not pick it up. The internal part could then look somewhat like the code below:

import contextlib
import os
import subprocess

@contextlib.contextmanager
def not_ready_to_read():
    try:
        read_end, write_end = os.pipe()
        yield read_end
    finally:
        os.close(read_end)
        os.close(write_end)

def call_external():
    with not_ready_to_read() as not_ready_stdin:
        popen = subprocess.Popen(["/usr/bin/python3", "external_script.py", "1"],
                                 stdin=not_ready_stdin, stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
        print(popen.communicate()[:2])

if __name__ == "__main__":
    call_external()

1This can also help you with other situations where the test via select.select erroneously suggests that some data is passed via stdin, such as if you run the script via the slurm job scheduler. Therefore, it's not an adaption of the production code with the sole purpose of enabling the test.


问:
Update title of button in for loop in swift UIButton
I have been trying to change the title of my UIButton every iteration of a for loop in swift, but it doesn't work as the titles are not being updated.
Heres the code:

```<code>@IBOutlet var generateButton: UIButton!
var x: Double = 0.0
for i in 0...nTokens {
    x = (Double(i)/Double(nTokens)) * 100
    print(self.generateButton.isHighlighted)
    self.generateButton.setTitle("\(x) %", for: .highlighted)
    self.generateButton.titleLabel!.font = UIFont.systemFont(ofSize: 20)
    sleep(3)
}
</code>```

Have already linked generateButton to the correct button in the view, and self.generateButton.isHighlighted always print true. What am I doing wrong? Thanks

答:
Not Sure how your sleep function looks like.Could you make sure that

```<code>self.generateButton.setTitle("\(x) %", for: .highlighted)
</code>```

runs in main thread ?

Body:
I have been trying to change the title of my UIButton every iteration of a for loop in swift, but it doesn't work as the titles are not being updated.
Heres the code:

@IBOutlet var generateButton: UIButton!
var x: Double = 0.0
for i in 0...nTokens {
    x = (Double(i)/Double(nTokens)) * 100
    print(self.generateButton.isHighlighted)
    self.generateButton.setTitle("\(x) %", for: .highlighted)
    self.generateButton.titleLabel!.font = UIFont.systemFont(ofSize: 20)
    sleep(3)
}

Have already linked generateButton to the correct button in the view, and self.generateButton.isHighlighted always print true. What am I doing wrong? Thanks

Body:
Not Sure how your sleep function looks like.Could you make sure that

self.generateButton.setTitle("\(x) %", for: .highlighted)

runs in main thread ?


问:
Create custom event log on remote server with PowerShell
I have an requirement where I need to create an custom event log on different server. I have the command to create the event log on local machine but need it for remote server. The command to create the event log on local machine is

```<code>powershell -command "if([System.Diagnostics.EventLog]::SourceExists('MySource')){Write 'Eventlog already exists'}else{[System.Diagnostics.EventLog]::CreateEventSource('MySource','MyCustomLog')}"
</code>```

I want the same for the remote server.

Please paste the code if possible.

Thanks.

答:
from your post on the Posh Comm

```<code>Invoke-command -computername server,server -scriptblock {if([System.Diagnostics.EventLog]::SourceExists('MySource')){Write 'Eventlog already exists'}else{[System.Diagnostics.EventLog]::CreateEventSource('MySource','MyCustomLog')}}
</code>```

Or Shay Levy's more elegant:

```<code>New-EventLog -LogName application -Source MySource,MyCustomLog -ComputerName PC1 -ErrorAction SilentlyContinue
Write-EventLog -LogName application -Source MySource -EntryType information -Message test -EventId 1234 -Computer PC1
</code>```

Body:
I have an requirement where I need to create an custom event log on different server. I have the command to create the event log on local machine but need it for remote server. The command to create the event log on local machine is

powershell -command "if([System.Diagnostics.EventLog]::SourceExists('MySource')){Write 'Eventlog already exists'}else{[System.Diagnostics.EventLog]::CreateEventSource('MySource','MyCustomLog')}"

I want the same for the remote server.

Please paste the code if possible.

Thanks.

Body:
from your post on the Posh Comm

Invoke-command -computername server,server -scriptblock {if([System.Diagnostics.EventLog]::SourceExists('MySource')){Write 'Eventlog already exists'}else{[System.Diagnostics.EventLog]::CreateEventSource('MySource','MyCustomLog')}}

Or Shay Levy's more elegant:

New-EventLog -LogName application -Source MySource,MyCustomLog -ComputerName PC1 -ErrorAction SilentlyContinue
Write-EventLog -LogName application -Source MySource -EntryType information -Message test -EventId 1234 -Computer PC1


问:
Execute an Authorization Code Grant Flow Using Java Spring Rest Api
I'm trying to call a 3rd party endpoint that requires authorization using Java spring rest Api, so I need to execute an Authorization Code Grant Flow.

I understand the flow where I need to first get the code then exchange the code for a JWT and finally use the JWT to be able to do the secure call.

What's not making sense to me is how am I suppose to set up a redirect URI when I'm using solely working with a backend rest api with no UI. Usually the user is redirected to a login page where they either login with a username/password or 3rd party accounts (google/facebook...)

After alot of googling, all the searches ended with guides to secure my own endpoints rather than access a secure endpoint from my spring boot service

Edit: It's worth mentioning that I'm using solely a backend with no front end (or MVC) whatsoever, after @Partha's comment I did the following:

First, I added a new login endpoint, when accessed via browser(this won't work with swagger/postman) it should redirect the user to the Authorization Server:

```<code>@GetMapping
public void login(HttpServletResponse httpServletResponse) {
    httpServletResponse.setHeader("Location", getAuthServerEndpoint());
    httpServletResponse.setStatus(302);
}
</code>```

Where I built the endpoint to have all the data needed (client_id,redirect_uri...) so it looks something like

https://idpserver.bla/oauth/authorize?client_id=xyz&redirect_uri=http://localhost:8080/token&response_type=code&scope=xyz

Now it sends me to the Login page of the auth Server, after I login, I expect it to redirect me to localhost/token (which is a get request that would retrieve the code and do a post request to get a jwt and save it) but instead, I'm receiving a invalid redirect uri and I'm really not sure if this is an issue from my implementation or the server's

EDIT2: I did a dumb mistake by NOT adding http://localhost:8080/token as a redirect url in the Auth Server since I assumed I didn't need to

答:
Depending if you are using MVC or Webflux a different approach will be required:

MVC: include a "security filter" to do that. You will be able to see an example in the following links:

MVC Securiry Manager

MVC Security Filter

MVC Security Configuration

Webflux: configure your own security manager. You will be able to see an example in the following links:

Webflux Securiry Manager

Webflux Securiry Context

Webflux Security Configuration

As you can see in both ones, an external service is called (using RestTemplate in MVC and WebClient in Webflux), to get the required authorization information and decide if the "logged user" pass the required security logic.

You can adapt it in the way you need.

Body:
I'm trying to call a 3rd party endpoint that requires authorization using Java spring rest Api, so I need to execute an Authorization Code Grant Flow.

I understand the flow where I need to first get the code then exchange the code for a JWT and finally use the JWT to be able to do the secure call.

What's not making sense to me is how am I suppose to set up a redirect URI when I'm using solely working with a backend rest api with no UI. Usually the user is redirected to a login page where they either login with a username/password or 3rd party accounts (google/facebook...)

After alot of googling, all the searches ended with guides to secure my own endpoints rather than access a secure endpoint from my spring boot service

Edit: It's worth mentioning that I'm using solely a backend with no front end (or MVC) whatsoever, after @Partha's comment I did the following:

First, I added a new login endpoint, when accessed via browser(this won't work with swagger/postman) it should redirect the user to the Authorization Server:

@GetMapping
public void login(HttpServletResponse httpServletResponse) {
    httpServletResponse.setHeader("Location", getAuthServerEndpoint());
    httpServletResponse.setStatus(302);
}

Where I built the endpoint to have all the data needed (client_id,redirect_uri...) so it looks something like

https://idpserver.bla/oauth/authorize?client_id=xyz&redirect_uri=http://localhost:8080/token&response_type=code&scope=xyz

Now it sends me to the Login page of the auth Server, after I login, I expect it to redirect me to localhost/token (which is a get request that would retrieve the code and do a post request to get a jwt and save it) but instead, I'm receiving a invalid redirect uri and I'm really not sure if this is an issue from my implementation or the server's

EDIT2: I did a dumb mistake by NOT adding http://localhost:8080/token as a redirect url in the Auth Server since I assumed I didn't need to


问:
Get Json Output with two select query in SQL Server
I would like to output the results of a SELECT statement as a JSON object.

```<code>id    name        active  Status
1     Bob Jones   1       Active
2     John Smith  0       Inactive
</code>```

I need return result like this:

```<code>{"Active"  :[{"id":1,"name":"Bob Jones" ,"active":1}],
 "InActive":[{"id":2,"name":"John Smith","active":0}]}
</code>```

How to use the query?

I am using this code

```<code>DECLARE @JSONTierDetails AS TABLE (TierDetails VARCHAR(8000))

INSERT INTO @JSONTierDetails
    SELECT
        (SELECT id, name, active
         FROM MyTable
         WHERE Status = 'Active'
         FOR JSON PATH, INCLUDE_NULL_VALUES) TierDetails

SELECT TierDetails
FROM @JSONTierDetails
</code>```

Thanks in advance

答:
```<code>-- Table definition
DECLARE @data TABLE(id int, [name] nvarchar(128), active bit, [status] nvarchar(30));

-- Insert test rows
INSERT @data VALUES(1, 'Bob Jones', 1, 'Active'), (2, 'John Smith', 0, 'Inactive');

-- Output
SELECT
    (SELECT id, name FROM @data WHERE active = 1 FOR JSON PATH) AS [Active],
    (SELECT id, name FROM @data WHERE active = 0 FOR JSON PATH) AS [Inactive]
FOR JSON PATH , WITHOUT_ARRAY_WRAPPER;
</code>```

Body:
I would like to output the results of a SELECT statement as a JSON object.

id    name        active  Status
1     Bob Jones   1       Active
2     John Smith  0       Inactive

I need return result like this:

{"Active"  :[{"id":1,"name":"Bob Jones" ,"active":1}],
 "InActive":[{"id":2,"name":"John Smith","active":0}]}

How to use the query?

I am using this code

DECLARE @JSONTierDetails AS TABLE (TierDetails VARCHAR(8000))

INSERT INTO @JSONTierDetails
    SELECT
        (SELECT id, name, active
         FROM MyTable
         WHERE Status = 'Active'
         FOR JSON PATH, INCLUDE_NULL_VALUES) TierDetails

SELECT TierDetails
FROM @JSONTierDetails

Thanks in advance


问:
AWS EC2 Ubuntu instance recovery to specific time
I want to recover my AWS EC2 Ubuntu instance to 2 days before.

How can I do this?

答:
Since you did not previously make any Snapshots of your Amazon EBS volumes, it is not possible to recover the state of the instance to a previous point in time.

An Amazon EBS Snapshot is a backup of the contents of a disk. You might consider taking regular snapshots, or Automating the Amazon EBS snapshot lifecycle.


问:
JLabel wrapping plain text as JTextArea
I have a problem with JLabel and plain text wrapping in it. For plain text wrapping i am using LabelView and i am not very happy about the result it gives to me.

My goal is to get plain text wrapping as in for example JTextArea. I tried WrappedPlainView but it works only with JTextComponent

So my question would be maybe you guys know/or have some advance JLabel views?

note: i do not want to add html to my plain text.

LabelView: http://docs.oracle.com/javase/6/docs/api/javax/swing/text/LabelView.html

WrappedPlainView: http://docs.oracle.com/javase/6/docs/api/javax/swing/text/WrappedPlainView.html

Try this example and look how words are wrapped when frame is resized:

```<code>import javax.swing.*;
import java.awt.*;
public class Example extends JFrame {
private static final String LONG_TEXT = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
                                        "Ut in enim velit. Nunc posuere purus ac odio dictum auctor. " +
                                        "Vivamus nec sem mi. Curabitur sed iaculis nibh. Proin vel massa augue. " +
                                        "Aenean laoreet, tellus ut vulputate mollis, justo eros ornare tortor, " +
                                        "vitae venenatis turpis augue id purus. In quis pretium justo. " +
                                        "Quisque interdum sem at augue ultrices molestie. " +
                                        "Nulla consectetur magna nec est malesuada sed ultricies diam gravida. " +
                                        "Curabitur luctus, nulla nec pulvinar fringilla, enim turpis luctus tellus, " +
                                        "non auctor diam ligula quis lectus.";

public Example()
{
    JTextArea textArea = new JTextArea(LONG_TEXT);
    textArea.setWrapStyleWord(true);
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    textArea.setOpaque(false);
    textArea.setEditable(false);

    add(new JScrollPane(textArea), BorderLayout.CENTER);
    setMinimumSize(new Dimension(100, 100));
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setVisible(true);
}

public static void main(String []args)
{
    new Example();
}
}
</code>```

Take a look to this example and you will see the problem with JLabel wrapping words:

```<code>import javax.swing.*;
import java.awt.*;
public class Example extends JFrame {
private static final String LONG_TEXT = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
                                        "Ut in enim velit. Nunc posuere purus ac odio dictum auctor. " +
                                        "Vivamus nec sem mi. Curabitur sed iaculis nibh. Proin vel massa augue. " +
                                        "Aenean laoreet, tellus ut vulputate mollis, justo eros ornare tortor, " +
                                        "vitae venenatis turpis augue id purus. In quis pretium justo. " +
                                        "Quisque interdum sem at augue ultrices molestie. " +
                                        "Nulla consectetur magna nec est malesuada sed ultricies diam gravida. " +
                                        "Curabitur luctus, nulla nec pulvinar fringilla, enim turpis luctus tellus, " +
                                        "non auctor diam ligula quis lectus.";

public Example()
{
    JLabel label = new JLabel(LONG_TEXT);
    add(label, BorderLayout.CENTER);
    setMinimumSize(new Dimension(100, 100));
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setVisible(true);
}

public static void main(String []args)
{
    new Example();
}
}
</code>```

So the goal is to get JLabel words wrapping as in JTextArea.

NOTE: in real project i am working with javax.swing.text.View`s and i am using LabelView for plain text.

答:
try this</p>

```<code>jLabel.setText(String.format("<html><body style=\"text-align: justify;  text-justify: inter-word;\">%s</body></html>",LONGTEXT));
</code>```

Title: JLabel wrapping plain text as JTextArea

Body:
I have a problem with JLabel and plain text wrapping in it. For plain text wrapping i am using LabelView and i am not very happy about the result it gives to me.

My goal is to get plain text wrapping as in for example JTextArea. I tried WrappedPlainView but it works only with JTextComponent

So my question would be maybe you guys know/or have some advance JLabel views?

note: i do not want to add html to my plain text.

LabelView: http://docs.oracle.com/javase/6/docs/api/javax/swing/text/LabelView.html

WrappedPlainView: http://docs.oracle.com/javase/6/docs/api/javax/swing/text/WrappedPlainView.html

Try this example and look how words are wrapped when frame is resized:

import javax.swing.*;
import java.awt.*;
public class Example extends JFrame {
private static final String LONG_TEXT = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
                                        "Ut in enim velit. Nunc posuere purus ac odio dictum auctor. " +
                                        "Vivamus nec sem mi. Curabitur sed iaculis nibh. Proin vel massa augue. " +
                                        "Aenean laoreet, tellus ut vulputate mollis, justo eros ornare tortor, " +
                                        "vitae venenatis turpis augue id purus. In quis pretium justo. " +
                                        "Quisque interdum sem at augue ultrices molestie. " +
                                        "Nulla consectetur magna nec est malesuada sed ultricies diam gravida. " +
                                        "Curabitur luctus, nulla nec pulvinar fringilla, enim turpis luctus tellus, " +
                                        "non auctor diam ligula quis lectus.";

public Example()
{
    JTextArea textArea = new JTextArea(LONG_TEXT);
    textArea.setWrapStyleWord(true);
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    textArea.setOpaque(false);
    textArea.setEditable(false);

    add(new JScrollPane(textArea), BorderLayout.CENTER);
    setMinimumSize(new Dimension(100, 100));
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setVisible(true);
}

public static void main(String []args)
{
    new Example();
}
}

Take a look to this example and you will see the problem with JLabel wrapping words:

import javax.swing.*;
import java.awt.*;
public class Example extends JFrame {
private static final String LONG_TEXT = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
                                        "Ut in enim velit. Nunc posuere purus ac odio dictum auctor. " +
                                        "Vivamus nec sem mi. Curabitur sed iaculis nibh. Proin vel massa augue. " +
                                        "Aenean laoreet, tellus ut vulputate mollis, justo eros ornare tortor, " +
                                        "vitae venenatis turpis augue id purus. In quis pretium justo. " +
                                        "Quisque interdum sem at augue ultrices molestie. " +
                                        "Nulla consectetur magna nec est malesuada sed ultricies diam gravida. " +
                                        "Curabitur luctus, nulla nec pulvinar fringilla, enim turpis luctus tellus, " +
                                        "non auctor diam ligula quis lectus.";

public Example()
{
    JLabel label = new JLabel(LONG_TEXT);
    add(label, BorderLayout.CENTER);
    setMinimumSize(new Dimension(100, 100));
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setVisible(true);
}

public static void main(String []args)
{
    new Example();
}
}

So the goal is to get JLabel words wrapping as in JTextArea.

NOTE: in real project i am working with javax.swing.text.View`s and i am using LabelView for plain text.

Body:
try this

jLabel.setText(String.format("<html><body style=\"text-align: justify;  text-justify: inter-word;\">%s</body></html>",LONGTEXT));


问:
Maximum absolute difference of value and index sums of Four arrays
You are given four arrays A, B, C, D each of size N.

Find maximum value (M) of given below expression

```<code>M = max(|A[i] - A[j]| + |B[i] - B[j]| + |C[i] - C[j]| + |D[i] - D[j]| + |i -j|)
Where 1 <= i < j  <= N <br />
</code>```

and here |x| refers to the absolute value of x.

Constraints

```<code>2 <= N <= 10^5
1 <= Ai,Bi,Ci,Di <= 10^9
</code>```

Input: N,A,B,C,D

Output: M

Ex.-

```<code>Input-
5
5,7,6,3,9
7,9,2,7,5
1,9,9,3,3
8,4,1,10,5
</code>```

Output-

```<code>24
</code>```

Question picture

I have tried this way

```<code>def max_value(arr1,arr2,arr3,arr4, n):
    res = 0;
    # Iterating two for loop,
    # one for i and another for j.
    for i in range(n):
        for j in range(n):
            temp= abs(arr1[i] - arr1[j]) + abs(arr2[i] - arr2[j]) + abs(arr3[i] - arr3[j]) + abs(arr4[i] - arr4[j]) + abs(i - j)
            if res>temp:
                res = res
            else:
                res = temp
    return res;

</code>```

This is O(n^2).
But I want a better time complexity solution. This will not work for higher values of N.

Here is solution for single array

答:
One can generalize the solution for a single array that you showed. Given a number K of arrays, including the array of indices, one can make 2**K possible combinations of arrays to get rid of the absolute values. It is then easy to just take the max and min of each of these combinations separately and compare them. This is order O(Kn*2^K), much better than the original O(Kn^2) for the values you report.

Here is a code that works on an arbitrary number of input arrays.

```<code>import numpy as np

def run(n, *args):
    aux = np.arange(n)

    K = len(args) + 1
    rows = 2 ** K
    x = np.zeros((rows, n))
    for i in range(rows):
        temp = 0
        for m, a in enumerate(args):
            temp += np.array(a) * ((-1) ** int(f"{i:0{K}b}"[-(1+m)]))
        temp += aux * ((-1) ** int(f"{i:0{K}b}"[-K]))
        x[i] = temp

    x_max = np.max(x, axis=-1)
    x_min = np.min(x, axis=-1)
    res = np.max(x_max - x_min)
    return res
</code>```

The for loop maybe deserves more explanation: in order to make all possible combinations of absolute values, I assign each combination to an integer and rely on the binary representation of this integer to choose which ones of the K vectors must be taken negative.

Body:
You are given four arrays A, B, C, D each of size N.

Find maximum value (M) of given below expression

M = max(|A[i] - A[j]| + |B[i] - B[j]| + |C[i] - C[j]| + |D[i] - D[j]| + |i -j|)
Where 1 <= i < j  <= N

and here |x| refers to the absolute value of x.

Constraints

2 <= N <= 10^5
1 <= Ai,Bi,Ci,Di <= 10^9

Input: N,A,B,C,D

Output: M

Ex.-

Input-
5
5,7,6,3,9
7,9,2,7,5
1,9,9,3,3
8,4,1,10,5

Output-

24

Question picture

I have tried this way

def max_value(arr1,arr2,arr3,arr4, n):
    res = 0;
    # Iterating two for loop,
    # one for i and another for j.
    for i in range(n):
        for j in range(n):
            temp= abs(arr1[i] - arr1[j]) + abs(arr2[i] - arr2[j]) + abs(arr3[i] - arr3[j]) + abs(arr4[i] - arr4[j]) + abs(i - j)
            if res>temp:
                res = res
            else:
                res = temp
    return res;

This is O(n^2).
But I want a better time complexity solution. This will not work for higher values of N.

Here is solution for single array

Body:
One can generalize the solution for a single array that you showed. Given a number K of arrays, including the array of indices, one can make 2**K possible combinations of arrays to get rid of the absolute values. It is then easy to just take the max and min of each of these combinations separately and compare them. This is order O(Kn*2^K), much better than the original O(Kn^2) for the values you report.

Here is a code that works on an arbitrary number of input arrays.

import numpy as np

def run(n, *args):
    aux = np.arange(n)

    K = len(args) + 1
    rows = 2 ** K
    x = np.zeros((rows, n))
    for i in range(rows):
        temp = 0
        for m, a in enumerate(args):
            temp += np.array(a) * ((-1) ** int(f"{i:0{K}b}"[-(1+m)]))
        temp += aux * ((-1) ** int(f"{i:0{K}b}"[-K]))
        x[i] = temp

    x_max = np.max(x, axis=-1)
    x_min = np.min(x, axis=-1)
    res = np.max(x_max - x_min)
    return res

The for loop maybe deserves more explanation: in order to make all possible combinations of absolute values, I assign each combination to an integer and rely on the binary representation of this integer to choose which ones of the K vectors must be taken negative.


问:
How to compare two lists in Python using for loop?
I am doing an exercise that ask me the following tasks. I am stack in the third one:

Create two variables called gandalf and saruman and assign them the spell power lists. Create a variable called spells to store the number of spells that the sorcerers cast.

```<code>spells = 10
gandalf = [10, 11, 13, 30, 22, 11, 10, 33, 22, 22]
saruman = [23, 66, 12, 43, 12, 10, 44, 23, 12, 17]
</code>```

Create two variables called gandalf_wins and saruman_wins. Set both of them to 0.
You will use these variables to count the number of clashes each sorcerer wins.

```<code>gandalf_wins=0
saruman_wins=0
</code>```

Using the lists of spells of both sorcerers, update variables gandalf_wins and saruman_wins to count the number of times each sorcerer wins a clash.

My solution is that but is not comparing all the elements of the list, could you help me?

```<code>for spells in saruman, gandalf:
    if gandalf>saruman:
        gandalf_wins += 1
    elif saruman>gandalf:
        saruman_wins += 1

print("Total gandalf wins:", gandalf_wins)
print("Total saruman wins:", saruman_wins)
</code>```

答:
The problem is in the way your for loop is defined. You should iterate over the elements in the lists and then compare them.</p>

```<code>for s, g in zip(saruman, gandalf):
    if g>s:
        gandalf_wins += 1
    elif s>g:
        saruman_wins += 1
</code>```

Body:
I am doing an exercise that ask me the following tasks. I am stack in the third one:

Create two variables called gandalf and saruman and assign them the spell power lists. Create a variable called spells to store the number of spells that the sorcerers cast.

spells = 10
gandalf = [10, 11, 13, 30, 22, 11, 10, 33, 22, 22]
saruman = [23, 66, 12, 43, 12, 10, 44, 23, 12, 17]

Create two variables called gandalf_wins and saruman_wins. Set both of them to 0.
You will use these variables to count the number of clashes each sorcerer wins.

gandalf_wins=0
saruman_wins=0

Using the lists of spells of both sorcerers, update variables gandalf_wins and saruman_wins to count the number of times each sorcerer wins a clash.

My solution is that but is not comparing all the elements of the list, could you help me?

for spells in saruman, gandalf:
    if gandalf>saruman:
        gandalf_wins += 1
    elif saruman>gandalf:
        saruman_wins += 1

print("Total gandalf wins:", gandalf_wins)
print("Total saruman wins:", saruman_wins)

Body:
The problem is in the way your for loop is defined. You should iterate over the elements in the lists and then compare them.

for s, g in zip(saruman, gandalf):
    if g>s:
        gandalf_wins += 1
    elif s>g:
        saruman_wins += 1


问:
replace dot with comma in vba it doesnt work
I have currency sheet and after run my listing I have numbers like Euro currency 45018,0000 instead 4,5018  What is wrong?</p>

```<code>Application.Workbooks("Zaliczenie.xlsm").Worksheets("Arkusz1").Range("G3:H12").Replace What:=".", Replacement:=","
</code>```

答:
Very easy to do that as below

```<code>Application.Workbooks("Zaliczenie.xlsm").Worksheets("Arkusz1").Range("G3:H12").Replace What:=".", Replacement:="."
</code>```

and now comma takes place instead of dot

Body:
I have currency sheet and after run my listing I have numbers like Euro currency 45018,0000 instead 4,5018  What is wrong?

Application.Workbooks("Zaliczenie.xlsm").Worksheets("Arkusz1").Range("G3:H12").Replace What:=".", Replacement:=","

Body:
Very easy to do that as below

Application.Workbooks("Zaliczenie.xlsm").Worksheets("Arkusz1").Range("G3:H12").Replace What:=".", Replacement:="."

and now comma takes place instead of dot


问:
Unreliable results when scanning multiple ports concurrently
Background:

I was reading through Black Hat Go where the author presents a simple port scanner that uses go routines1:

```<code>package main

import (
    "fmt"
    "net"
)

func main() {
    for i := 1; i <= 9000; i++ {
        go func(j int) {
            address := fmt.Sprintf("127.0.0.1:%d", j)
            conn, err := net.Dial("tcp", address)
            if err != nil {
                return
            }
            conn.Close()
            fmt.Printf("%d open\n", j)
        }(i)
    }
}
</code>```

And then he mentions the following:

Scanning an excessive number of hosts or ports simultaneously may
  cause network or system limitations to skew your results.

To test it, I started 2 php servers2 on ports 8000 and 8500 and ran the above code to scan my local ports.

Each time it gave me inconsistent results. Sometimes it'd detect both the open ports, sometimes it would not.

Question:

Are the inconsistent results due to some limitations in TCP?

Is there a way to calculate the optimal number of ports that can be scanned in parallel so that the results remain correct?

Edit:

I seem to have missed out waitgroups in the above code.

Besides that, is there anything else (OS limitation or protocol limitation) that prevents concurrent port scans over a large range?

答:
Your main function will exit as soon as the for loop has finished. If the main function exits, so do all goroutines started by it. You need to wait for the goroutines to finish. That can be achieved this via sync.WaitGroup, for example.

package main

import (
    "fmt"
    "net"
    "sync"
    "time"
)

func main() {

    // This will help you to keep track of the goroutines
    var wg sync.WaitGroup

    for i := 1; i <= 9000; i++ {

        // Increment the counter for each goroutine you start.
        wg.Add(1)

        go func(j int) {

            // Make sure the wait group counter is decremented when the goroutine exits
            defer wg.Done()

            address := fmt.Sprintf("127.0.0.1:%d", j)
            conn, err := net.DialTimeout("tcp", address, 2 * time.Second)
            if err != nil {
               return
            }
            conn.Close()
            fmt.Printf("%d open\n", j)
        }(i)
    }

    // Wait for all goroutines to finish before exiting main
    wg.Wait()
}
```

<p><strong>EDIT:</strong> For me, it turned out that the code as is did not work due to a lack of file descriptors. The following function works reliably.</p>

<p>It needs better error handling, but does the trick</p>

<pre class="lang-golang prettyprint-override"><code>package main

import (
    "fmt"
    "log"
    "net"
    "sync"
    "time"
)

var minPort = 1
var maxPort = 65535
var timeout = 2 * time.Second
const parallel = 50

func main(){
    fmt.Println("portscan called")

    // Create a buffered channel with a size equal to the number of goroutines
    ctrl := make(chan int, parallel)

    // Keep track of the currently active goroutines
    var wg sync.WaitGroup

    for p := 1; p <= parallel; p++ {
        wg.Add(1)

        // Start a goroutine...
        go func(p int) {
            log.Printf("Starting goroutine %d", p)

            // ...listening to the control channel.
            // For every value this goroutine reads from the
            // channel...
            for i := range ctrl {
                address := fmt.Sprintf("127.0.0.1:%d", i)

                // ...try to conncet to the port.
                conn, err := net.DialTimeout("tcp", address, timeout)
                if err == nil {
                    conn.Close()
                    log.Printf("[%3d]: %5d open", p, i)
                }
                // TBD: ERROR HANDLING!!!
            }

            // If the channel is closed, this goroutine is done.
            wg.Done()
            log.Printf("[%3d]: Exiting", p)
        }(p)
    }

    // Fill the control channel with values.
    // If the channel is full, the write operation
    // to the channel will block until one of the goroutines
    // reads a value from it.
    for i := minPort; i <= maxPort; i++ {
        ctrl <- i
    }
    // We have sent all values, so the channel can be closed.
    // The goroutines will finish their current connection attempt,
    // notice that the channel is closed and will in turn call wg.Done().
    close(ctrl)

    // When all goroutines have announced that they are done, we can exit.
    wg.Wait()
}
</code>```

Body:
Background:

I was reading through Black Hat Go where the author presents a simple port scanner that uses go routines1:

package main

import (
    "fmt"
    "net"
)

func main() {
    for i := 1; i <= 9000; i++ {
        go func(j int) {
            address := fmt.Sprintf("127.0.0.1:%d", j)
            conn, err := net.Dial("tcp", address)
            if err != nil {
                return
            }
            conn.Close()
            fmt.Printf("%d open\n", j)
        }(i)
    }
}

And then he mentions the following:

Scanning an excessive number of hosts or ports simultaneously may
  cause network or system limitations to skew your results.

To test it, I started 2 php servers2 on ports 8000 and 8500 and ran the above code to scan my local ports.

Each time it gave me inconsistent results. Sometimes it'd detect both the open ports, sometimes it would not.

Question:

Are the inconsistent results due to some limitations in TCP?

Is there a way to calculate the optimal number of ports that can be scanned in parallel so that the results remain correct?

Edit:

I seem to have missed out waitgroups in the above code.

Besides that, is there anything else (OS limitation or protocol limitation) that prevents concurrent port scans over a large range?

Body:
Your main function will exit as soon as the for loop has finished. If the main function exits, so do all goroutines started by it. You need to wait for the goroutines to finish. That can be achieved this via sync.WaitGroup, for example.

package main

import (
    "fmt"
    "net"
    "sync"
    "time"
)

func main() {

    // This will help you to keep track of the goroutines
    var wg sync.WaitGroup

    for i := 1; i <= 9000; i++ {

        // Increment the counter for each goroutine you start.
        wg.Add(1)

        go func(j int) {

            // Make sure the wait group counter is decremented when the goroutine exits
            defer wg.Done()

            address := fmt.Sprintf("127.0.0.1:%d", j)
            conn, err := net.DialTimeout("tcp", address, 2 * time.Second)
            if err != nil {
               return
            }
            conn.Close()
            fmt.Printf("%d open\n", j)
        }(i)
    }

    // Wait for all goroutines to finish before exiting main
    wg.Wait()
}

EDIT: For me, it turned out that the code as is did not work due to a lack of file descriptors. The following function works reliably.

It needs better error handling, but does the trick

package main

import (
    "fmt"
    "log"
    "net"
    "sync"
    "time"
)

var minPort = 1
var maxPort = 65535
var timeout = 2 * time.Second
const parallel = 50

func main(){
    fmt.Println("portscan called")

    // Create a buffered channel with a size equal to the number of goroutines
    ctrl := make(chan int, parallel)

    // Keep track of the currently active goroutines
    var wg sync.WaitGroup

    for p := 1; p <= parallel; p++ {
        wg.Add(1)

        // Start a goroutine...
        go func(p int) {
            log.Printf("Starting goroutine %d", p)

            // ...listening to the control channel.
            // For every value this goroutine reads from the
            // channel...
            for i := range ctrl {
                address := fmt.Sprintf("127.0.0.1:%d", i)

                // ...try to conncet to the port.
                conn, err := net.DialTimeout("tcp", address, timeout)
                if err == nil {
                    conn.Close()
                    log.Printf("[%3d]: %5d open", p, i)
                }
                // TBD: ERROR HANDLING!!!
            }

            // If the channel is closed, this goroutine is done.
            wg.Done()
            log.Printf("[%3d]: Exiting", p)
        }(p)
    }

    // Fill the control channel with values.
    // If the channel is full, the write operation
    // to the channel will block until one of the goroutines
    // reads a value from it.
    for i := minPort; i <= maxPort; i++ {
        ctrl <- i
    }
    // We have sent all values, so the channel can be closed.
    // The goroutines will finish their current connection attempt,
    // notice that the channel is closed and will in turn call wg.Done().
    close(ctrl)

    // When all goroutines have announced that they are done, we can exit.
    wg.Wait()
}


问:
Releasing a connection in Rails
I'm using Rails 2.3.8.

What's the best way to release a connection on a model to another database?

Let's say I have ModelB.establish_connection("server_b")

Would ModelB.remove_connection do the trick?  How would I verify that I've successfully removed the connection?

答:
Looks as though remove_connection is what you're looking for.  To verify that you've successfully removed the connection, you could wrap a find method within a rescue block like:</p>

```<code>begin
  ModelB.find(1)
rescue ConnectionNotEstablished
  # if we're here, then we have no connection, which is good in this case
else
  # if we're here, then we still have a connection, which is bad...
end
</code>```

Title: Releasing a connection in Rails

Body:
Looks as though remove_connection is what you're looking for.  To verify that you've successfully removed the connection, you could wrap a find method within a rescue block like:

begin
  ModelB.find(1)
rescue ConnectionNotEstablished
  # if we're here, then we have no connection, which is good in this case
else
  # if we're here, then we still have a connection, which is bad...
end


问:
An annotation can't be used as the annotations argument
I get a error, although do exactly the same that documentation says. Documentation:

```<code>data class PlaylistWithSongs(
    @Embedded val playlist: Playlist,
    @Relation(
         parentColumn = "playlistId",
         entityColumn = "songId",
         associateBy = @Junction(PlaylistSongCrossRef::class)
    )
    val songs: List<Song>
)
</code>```

My problem:

```<code>data class FileEntryWithTags(
        @Embedded val fileEntry: FileEntry,
        @Relation(
                parentColumn = FileEntry.COLUMN_UUID,
                entityColumn = Tag.COLUMN_ID,
                associateBy = @Junction(FileEntryTagCrossRef::class)
        )
        val tags: List<Tag>
)
</code>```

答:
Looks like the Android documentation has a mistake in it. The Annotations - Kotlin Programming Language page from the Kotlin reference tells us:

If an annotation is used as a parameter of another annotation, its name is not prefixed with the @ character:

annotation class ReplaceWith(val expression: String)

annotation class Deprecated(
        val message: String,
        val replaceWith: ReplaceWith = ReplaceWith(""))

@Deprecated("This function is deprecated, use === instead", ReplaceWith("this === other"))
```
</blockquote>

<p>So your code should be:</p>

<pre class="lang-kotlin prettyprint-override"><code>data class FileEntryWithTags(
        @Embedded val fileEntry: FileEntry,
        @Relation(
                parentColumn = FileEntry.COLUMN_UUID,
                entityColumn = Tag.COLUMN_ID,
                associateBy =  Junction(FileEntryTagCrossRef::class)
        )
        val tags: List<Tag>
)
</code>```

Body:
I get a error, although do exactly the same that documentation says. Documentation:

data class PlaylistWithSongs(
    @Embedded val playlist: Playlist,
    @Relation(
         parentColumn = "playlistId",
         entityColumn = "songId",
         associateBy = @Junction(PlaylistSongCrossRef::class)
    )
    val songs: List<Song>
)

My problem:

data class FileEntryWithTags(
        @Embedded val fileEntry: FileEntry,
        @Relation(
                parentColumn = FileEntry.COLUMN_UUID,
                entityColumn = Tag.COLUMN_ID,
                associateBy = @Junction(FileEntryTagCrossRef::class)
        )
        val tags: List<Tag>
)

Body:
Looks like the Android documentation has a mistake in it. The Annotations - Kotlin Programming Language page from the Kotlin reference tells us:

If an annotation is used as a parameter of another annotation, its name is not prefixed with the @ character:

annotation class ReplaceWith(val expression: String)

annotation class Deprecated(
        val message: String,
        val replaceWith: ReplaceWith = ReplaceWith(""))

@Deprecated("This function is deprecated, use === instead", ReplaceWith("this === other"))

So your code should be:

data class FileEntryWithTags(
        @Embedded val fileEntry: FileEntry,
        @Relation(
                parentColumn = FileEntry.COLUMN_UUID,
                entityColumn = Tag.COLUMN_ID,
                associateBy =  Junction(FileEntryTagCrossRef::class)
        )
        val tags: List<Tag>
)


问:
weird variable hoisting in javascript
so we know that variables declared with the var keyword are hoisted and if we try to access their value before they have been initialized we get undefined. However, In the code below logging the name variable logs the function and not undefined why ?

console.log(name);
console.log(lol);

var name = function(args = "Hello World"){
    console.log(args)
}

var lol = function(args = "Hello world") {
    console.log(args)
}
```

<p>the output is </p>

```function(args = "Hello World"){
    console.log(args)
}
```

<p>and</p>

```main.js:57 undefined
```

why isnt name variable undefined ?

答:
Consider the code

console.log(test);

var test = function(args = "Hello World"){
    console.log(args)
}```
</div>
</div>
</p>

<p>This will return <code>undefined</code> because only declarations are hoisted. That is, your code after <em>hoisting</em> will be</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var test;
console.log(test);

test = function(args = "Hello World"){
    console.log(args)
}</code>```

Title: weird variable hoisting in javascript

Body:
so we know that variables declared with the var keyword are hoisted and if we try to access their value before they have been initialized we get undefined. However, In the code below logging the name variable logs the function and not undefined why ?

console.log(name);
console.log(lol);

var name = function(args = "Hello World"){
    console.log(args)
}

var lol = function(args = "Hello world") {
    console.log(args)
}

the output is

function(args = "Hello World"){
    console.log(args)
}

and

main.js:57 undefined

why isnt name variable undefined ?

Body:
Consider the code

console.log(test);

var test = function(args = "Hello World"){
    console.log(args)
}

This will return undefined because only declarations are hoisted. That is, your code after hoisting will be

var test;
console.log(test);

test = function(args = "Hello World"){
    console.log(args)
}


问:
Why is onChanged being called when I navigate back to a fragment?
I have a ViewModel handling my business logic and I am using Koin to inject this into my activity and each of my fragments. However after I navigate from Fragment A - Fragment B and navigate back to Fragment A, my observer is triggered again. Why is this happening and how do I stop this onChanged being triggered when I navigate back?

I have tried setting both 'this' and 'viewLifecycleOwner' as the LifecycleOwner of the LiveData.

I have also tried moving the observable to onCreate, onActivityCreated and onViewCreated

My ViewModel:

```<code>class MyViewModel : ViewModel() {

    private val _myData = MutableLiveData<Data>()
    val myData = LiveData<Data>()
        get() = _myData

    fun doSomething() {
        ... // some code
        _myData.postValue(myResult)
}
</code>```

MyActivity:

```<code>class Activity : BaseActivity() {

    private val viewModel by viewModel<MyViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        setSupportActionBar(main_toolbar)

        subscribeUI()
    }

    private fun subscribeUI() {
        myViewModel.isLoading.observe(this, Observer {
            toggleProgress(it)
        })
    }
}
</code>```

Fragment A:

```<code>class FragmentA : BaseFragment() {

    private val viewModel by sharedViewModel<MyViewModel>()

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        subscribeUI()
    }

    private fun subscribeUI() {
        viewModel.myData.observe(viewLifecycleOwner, Observer {
            val direction =
                FragmentADirections.actionAtoB()
            mainNavController?.navigate(direction)
        })
    }
}
</code>```

Fragment B:

```<code>class FragmentB : BaseFragment() {

    private val authViewModel by sharedViewModel<LoginViewModel>()

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        subscribeUI()
    }

    private fun subscribeUI() {
        viewModel.otherData.observe(viewLifecycleOwner, Observer {
            // Do something else...
        })
    }
}
</code>```

When I navigate from Fragment A -> Fragment B, everything works as I expect. However when I navigate back to Fragment A from Fragment B (by pressing the back button) the onChanged method from the Observer on myData is called and the navigation moves back to Navigation B.

答:
This is an expected behaviour when using MutableLiveData. I think your problem has nothing to do as to where to add or remove subscribers.

MutableLiveData holds last value it is set with.
When we go back to previous fragment, our LiveData observes are notified again with existing values. This is to preserve the state of your fragment and that's the exact purpose of LiveData.

Google itself has addressed this and provided a way to override this behaviour, which is using an Event wrapper.

Create a wrapper to wrap an event.

Create an observer to observe for this wrapped events.

Let's see code in action

Create wrapper event

/**
* Used as a wrapper for data that is exposed via a LiveData that represents an event.
*/
open class Event<out T>(private val content: T) {

 var hasBeenHandled = false
     private set // Allow external read but not write

 /**
  * Returns the content and prevents its use again.
  */
 fun getContentIfNotHandled(): T? {
     return if (hasBeenHandled) {
         null
     } else {
         hasBeenHandled = true
         content
     }
 }

 /**
  * Returns the content, even if it's already been handled.
  */
 fun peekContent(): T = content
}
```

<ol start="2">
<li>Create observer</li>
</ol>

<pre class="lang-kotlin prettyprint-override"><code>class EventObserver<T>(private val onEventUnhandledContent: (T) -> Unit) : Observer<Event<T>> {
 override fun onChanged(event: Event<T>?) {
     event?.getContentIfNotHandled()?.let { value ->
         onEventUnhandledContent(value)
     }
 }
}
</code>```

Declare live data object in View model?

// Declare live data object
val testLiveData: MutableLiveData<Event<Boolean>
             by lazy{ MutableLiveData<Event<Boolean>>() }
```

<ol start="4">
<li>Set data for live data object</li>
</ol>

<pre class="lang-kotlin prettyprint-override"><code>testLiveData.postValue(Event(true))
</code>```

Observe for this live data in fragment

viewModel?.testLiveData?.observe(this, EventObserver { result ->
 // Your actions
}
```

Detailed reference: https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150

Body:
I have a ViewModel handling my business logic and I am using Koin to inject this into my activity and each of my fragments. However after I navigate from Fragment A - Fragment B and navigate back to Fragment A, my observer is triggered again. Why is this happening and how do I stop this onChanged being triggered when I navigate back?

I have tried setting both 'this' and 'viewLifecycleOwner' as the LifecycleOwner of the LiveData.

I have also tried moving the observable to onCreate, onActivityCreated and onViewCreated

My ViewModel:

class MyViewModel : ViewModel() {

    private val _myData = MutableLiveData<Data>()
    val myData = LiveData<Data>()
        get() = _myData

    fun doSomething() {
        ... // some code
        _myData.postValue(myResult)
}

MyActivity:

class Activity : BaseActivity() {

    private val viewModel by viewModel<MyViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        setSupportActionBar(main_toolbar)

        subscribeUI()
    }

    private fun subscribeUI() {
        myViewModel.isLoading.observe(this, Observer {
            toggleProgress(it)
        })
    }
}

Fragment A:

class FragmentA : BaseFragment() {

    private val viewModel by sharedViewModel<MyViewModel>()

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        subscribeUI()
    }

    private fun subscribeUI() {
        viewModel.myData.observe(viewLifecycleOwner, Observer {
            val direction =
                FragmentADirections.actionAtoB()
            mainNavController?.navigate(direction)
        })
    }
}

Fragment B:

class FragmentB : BaseFragment() {

    private val authViewModel by sharedViewModel<LoginViewModel>()

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        subscribeUI()
    }

    private fun subscribeUI() {
        viewModel.otherData.observe(viewLifecycleOwner, Observer {
            // Do something else...
        })
    }
}

When I navigate from Fragment A -> Fragment B, everything works as I expect. However when I navigate back to Fragment A from Fragment B (by pressing the back button) the onChanged method from the Observer on myData is called and the navigation moves back to Navigation B.

Body:
This is an expected behaviour when using MutableLiveData. I think your problem has nothing to do as to where to add or remove subscribers.

MutableLiveData holds last value it is set with.
When we go back to previous fragment, our LiveData observes are notified again with existing values. This is to preserve the state of your fragment and that's the exact purpose of LiveData.

Google itself has addressed this and provided a way to override this behaviour, which is using an Event wrapper.

Create a wrapper to wrap an event.

Create an observer to observe for this wrapped events.

Let's see code in action

Create wrapper event

/**
* Used as a wrapper for data that is exposed via a LiveData that represents an event.
*/
open class Event<out T>(private val content: T) {

 var hasBeenHandled = false
     private set // Allow external read but not write

 /**
  * Returns the content and prevents its use again.
  */
 fun getContentIfNotHandled(): T? {
     return if (hasBeenHandled) {
         null
     } else {
         hasBeenHandled = true
         content
     }
 }

 /**
  * Returns the content, even if it's already been handled.
  */
 fun peekContent(): T = content
}

Create observer

class EventObserver<T>(private val onEventUnhandledContent: (T) -> Unit) : Observer<Event<T>> {
 override fun onChanged(event: Event<T>?) {
     event?.getContentIfNotHandled()?.let { value ->
         onEventUnhandledContent(value)
     }
 }
}

Declare live data object in View model?

// Declare live data object
val testLiveData: MutableLiveData<Event<Boolean>
             by lazy{ MutableLiveData<Event<Boolean>>() }

Set data for live data object

testLiveData.postValue(Event(true))

Observe for this live data in fragment

viewModel?.testLiveData?.observe(this, EventObserver { result ->
 // Your actions
}

Detailed reference: https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150


问:
Could not login in Ubuntu 20.04 LTS
I have just upgraded my operating system Ubuntu 18.04 LTS to Ubuntu 20.04 LTS. But after installing completely, during login I couldn't login even with right password.I checked it was indeed a right password by entering username and password after pressing Ctrl + Alt + F2, I even changed the password from advanced recovery mode but still new password also doesn't work. For the right password the screen goes black for like a second then again comes back in the same purple login screen but with wrong password it says -sorry, that didn't work. please try again. I am new to Linux and any help is appreciated.

答:
It's caused by ticking 'enable automatic logging in' at installation. Open the terminal by pressing Ctrl+Alt+T. Login, then enter

```<code>sudo nano /etc/gdm3/custom.conf
</code>```

Change AutomaticLoginEnable from true to false, save the file, then reboot.

Title: Could not login in Ubuntu 20.04 LTS

Body:
It's caused by ticking 'enable automatic logging in' at installation. Open the terminal by pressing Ctrl+Alt+T. Login, then enter

sudo nano /etc/gdm3/custom.conf

Change AutomaticLoginEnable from true to false, save the file, then reboot.