问:
Reset CSS badge content after ajax call
I have a page which contains some navigation tabs.  If there is a notification for that tab a badge is displayed.  When the tab is in focus, I want an ajax call to make a server request and if the response is successful, I want the badge to be reset to zero.  I can display the badge and the ajax call returns successfully (I have not included this in the code below) and then when I try to set the data attribute for the tab, the value doesn't change.

The relevant code is as follows:

```<code><div class="container-fluid">
    <br/>
    <div class="col-sm-10">
        <div class="panel with-nav-tabs panel-tab-block">
            <div class="panel-heading">
                <ul class="nav nav-tabs">
                    <li class="active">
                        <a data-toggle="tab" class="" href="#projects-tab">Projects</a>
                    </li>
                    <li>
                        <a data-toggle="tab" id="forum-notification-badge" class="notification-badge"
                        data-notification-badge="1" href="#forum-tab">Forum</a>
                    </li>
                </ul>
            </div>
            <div class="panel-body">
                <div class="tab-content">
                    <div id="projects-tab" class="tab-pane fade in active">
                        <div class="row">

                                <div class="col-sm-12">
                                    <div class="panel with-nav-tabs panel-tab-block">
                                        <h1>
                                            Projects
                                        </h1>

                                    </div>
                                </div>
                        </div>
                        <div class="row">
                            <div class="spacer-sml"></div>
                        </div>
                        <div class="row">
                            <div class="spacer-sml"></div>
                        </div>
                    </div>
                    <div id="forum-tab" class="tab-pane fade">
                        <div class="tab-block-content forum-posts">
                            <div class="">
                                <div class="col-sm-12">
                                    <h1>
                                        Forum
                                    </h1>
                                </div>

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

JQuery:

```<code>jQuery(document).ready(function( $ ) {

    $('#forum-notification-badge').on("focus", function() {
        var self = $(this);

        //Do ajax call if success reset the badge to zero
        self.data("notification-badge","0");
        console.log("set badge to zero");

    });

});
</code>```

css:

```<code>.nav {
    border: 1px;
    border-color: #2f70b1;
}
.nav-bar {
    margin-bottom: 0px !important;
}
.navbar-default {
    background-color: #1d3c5c;
    border-color: #000000;
    font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
    -webkit-transition: all 0.35s;
    -moz-transition: all 0.35s;
    transition: all 0.35s;
    margin-bottom: 0px !important;
    border-radius: 0px;
}

.navbar-default .navbar-header .navbar-brand {
    color: #777;
    font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
    font-weight: 700;
    text-transform: uppercase;
}

.navbar-default .navbar-header .navbar-brand:hover, .navbar-default .navbar-header .navbar-brand:focus{
    color: #777;
}

.navbar-default .navbar-header .navbar-toggle {
    font-weight: 700;
    font-size: 12px;
    color: #222222;
    text-transform: uppercase;
}

.navbar-default .nav>li>a, .navbar-default .nav>li>a:focus {
    text-transform: uppercase;
    font-weight: 700;
    font-size: 13px;
    color: #222222;
}

.navbar-default .nav>li>a:hover, .navbar-default .nav>li>a:focus:hover {

}

.navbar-default .nav>li.active>a, .navbar-default .nav>li.active>a:focus{
    color: #F05F40 !important;
    background-color: transparent;
}

.navbar-default .nav>li.active>a:hover, .navbar-default .nav>li.active>a:focus:hover{
    background-color: #1d3c5c;
}

@media ( min-width : 768px) {
    .navbar-default {
        background-color: #1d3c5c;

    }
    .navbar-default .navbar-header .navbar-brand {
        color: #ddd;
    }
    .navbar-default .navbar-header .navbar-brand:hover, .navbar-default .navbar-header .navbar-brand:focus
        {
        color: white;
    }
    .navbar-default .nav>li>a, .navbar-default .nav>li>a:focus {
        color: #ddd;
    }
    .navbar-default .nav>li>a:hover, .navbar-default .nav>li>a:focus:hover {
        color: white;
    }
    .navbar-default.affix {
        background-color: white;

    }
    .navbar-default.affix .navbar-header .navbar-brand {
        color: #F05F40;
        font-size: 14px;
    }
    .navbar-default.affix .navbar-header .navbar-brand:hover,
        .navbar-default.affix .navbar-header .navbar-brand:focus {
        color: #eb3812;
    }
    .navbar-default.affix .nav>li>a, .navbar-default.affix .nav>li>a:focus {
        color: #222222;
    }
    .navbar-default.affix .nav>li>a:hover, .navbar-default.affix .nav>li>a:focus:hover
        {
        color: #F05F40;
    }
}

.navbar-default .navbar-nav>li>a:focus, .navbar-default .navbar-nav>li>a:hover {
    background-color: #286090;
}
.panel.with-nav-tabs.panel-tab-block{
    box-shadow: none;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
}

.with-nav-tabs.panel-tab-block .nav-tabs > li > a,
.with-nav-tabs.panel-tab-block .nav-tabs > li > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > li > a:focus {
    color: #ffffff;
    background-color: #999999;
}
.with-nav-tabs.panel-tab-block .nav-tabs > .open > a,
.with-nav-tabs.panel-tab-block .nav-tabs > .open > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > .open > a:focus,
.with-nav-tabs.panel-tab-block .nav-tabs > li > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > li > a:focus {
    color: #fff;
    background-color: #666666 ;

}
.with-nav-tabs.panel-tab-block .nav-tabs > li.active > a,
.with-nav-tabs.panel-tab-block .nav-tabs > li.active > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > li.active > a:focus {
    color: #fff;
    background-color: #2f70b1;
    border-color: #2f70b1;
}
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu {
    background-color: #428bca;
    border-color: #3071a9;
}
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > li > a {
    color: #fff;
}
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > li > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > li > a:focus {
    background-color: #3071a9;
}
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > .active > a,
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > .active > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > .active > a:focus {
    background-color: #4a9fe9;
}

.tab-block-content {
    color: #202020;
}

.notification-badge {
    position:relative;
    padding-right: 1em;
}

.notification-badge[data-notification-badge]:after {
   content:attr(data-notification-badge);
   position:absolute;
   top:-0.75em;
   right:-0.75em;
   font-size:0.75em;
   background:red;
   color:white;
   width:1.5em;
   height:1.5em;
   text-align:center;
   line-height:1.5em;
   border-radius:50%;
   box-shadow:0 0 1px #333;
}
</code>```

I have also created a jsfiddle

答:
Use attr() instead.

```<code>$('#forum-notification-badge').on("focus", function() {
    var self = $(this);

    //Do ajax call if success reset the badge to zero
    self.attr("data-notification-badge",0);
    console.log("set badge to zero");

});
</code>```

Title: Reset CSS badge content after ajax call

Body:
I have a page which contains some navigation tabs.  If there is a notification for that tab a badge is displayed.  When the tab is in focus, I want an ajax call to make a server request and if the response is successful, I want the badge to be reset to zero.  I can display the badge and the ajax call returns successfully (I have not included this in the code below) and then when I try to set the data attribute for the tab, the value doesn't change.

The relevant code is as follows:

                        Projects

                        Forum

                                            Projects

                                        Forum

JQuery:

jQuery(document).ready(function( $ ) {

    $('#forum-notification-badge').on("focus", function() {
        var self = $(this);

        //Do ajax call if success reset the badge to zero
        self.data("notification-badge","0");
        console.log("set badge to zero");

    });

});

css:

.nav {
    border: 1px;
    border-color: #2f70b1;
}
.nav-bar {
    margin-bottom: 0px !important;
}
.navbar-default {
    background-color: #1d3c5c;
    border-color: #000000;
    font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
    -webkit-transition: all 0.35s;
    -moz-transition: all 0.35s;
    transition: all 0.35s;
    margin-bottom: 0px !important;
    border-radius: 0px;
}

.navbar-default .navbar-header .navbar-brand {
    color: #777;
    font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
    font-weight: 700;
    text-transform: uppercase;
}

.navbar-default .navbar-header .navbar-brand:hover, .navbar-default .navbar-header .navbar-brand:focus{
    color: #777;
}

.navbar-default .navbar-header .navbar-toggle {
    font-weight: 700;
    font-size: 12px;
    color: #222222;
    text-transform: uppercase;
}

.navbar-default .nav>li>a, .navbar-default .nav>li>a:focus {
    text-transform: uppercase;
    font-weight: 700;
    font-size: 13px;
    color: #222222;
}

.navbar-default .nav>li>a:hover, .navbar-default .nav>li>a:focus:hover {

}

.navbar-default .nav>li.active>a, .navbar-default .nav>li.active>a:focus{
    color: #F05F40 !important;
    background-color: transparent;
}

.navbar-default .nav>li.active>a:hover, .navbar-default .nav>li.active>a:focus:hover{
    background-color: #1d3c5c;
}

@media ( min-width : 768px) {
    .navbar-default {
        background-color: #1d3c5c;

    }
    .navbar-default .navbar-header .navbar-brand {
        color: #ddd;
    }
    .navbar-default .navbar-header .navbar-brand:hover, .navbar-default .navbar-header .navbar-brand:focus
        {
        color: white;
    }
    .navbar-default .nav>li>a, .navbar-default .nav>li>a:focus {
        color: #ddd;
    }
    .navbar-default .nav>li>a:hover, .navbar-default .nav>li>a:focus:hover {
        color: white;
    }
    .navbar-default.affix {
        background-color: white;

    }
    .navbar-default.affix .navbar-header .navbar-brand {
        color: #F05F40;
        font-size: 14px;
    }
    .navbar-default.affix .navbar-header .navbar-brand:hover,
        .navbar-default.affix .navbar-header .navbar-brand:focus {
        color: #eb3812;
    }
    .navbar-default.affix .nav>li>a, .navbar-default.affix .nav>li>a:focus {
        color: #222222;
    }
    .navbar-default.affix .nav>li>a:hover, .navbar-default.affix .nav>li>a:focus:hover
        {
        color: #F05F40;
    }
}

.navbar-default .navbar-nav>li>a:focus, .navbar-default .navbar-nav>li>a:hover {
    background-color: #286090;
}
.panel.with-nav-tabs.panel-tab-block{
    box-shadow: none;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
}

.with-nav-tabs.panel-tab-block .nav-tabs > li > a,
.with-nav-tabs.panel-tab-block .nav-tabs > li > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > li > a:focus {
    color: #ffffff;
    background-color: #999999;
}
.with-nav-tabs.panel-tab-block .nav-tabs > .open > a,
.with-nav-tabs.panel-tab-block .nav-tabs > .open > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > .open > a:focus,
.with-nav-tabs.panel-tab-block .nav-tabs > li > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > li > a:focus {
    color: #fff;
    background-color: #666666 ;

}
.with-nav-tabs.panel-tab-block .nav-tabs > li.active > a,
.with-nav-tabs.panel-tab-block .nav-tabs > li.active > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > li.active > a:focus {
    color: #fff;
    background-color: #2f70b1;
    border-color: #2f70b1;
}
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu {
    background-color: #428bca;
    border-color: #3071a9;
}
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > li > a {
    color: #fff;
}
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > li > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > li > a:focus {
    background-color: #3071a9;
}
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > .active > a,
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > .active > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > .active > a:focus {
    background-color: #4a9fe9;
}

.tab-block-content {
    color: #202020;
}

.notification-badge {
    position:relative;
    padding-right: 1em;
}

.notification-badge[data-notification-badge]:after {
   content:attr(data-notification-badge);
   position:absolute;
   top:-0.75em;
   right:-0.75em;
   font-size:0.75em;
   background:red;
   color:white;
   width:1.5em;
   height:1.5em;
   text-align:center;
   line-height:1.5em;
   border-radius:50%;
   box-shadow:0 0 1px #333;
}

I have also created a jsfiddle

Body:
Use attr() instead.

$('#forum-notification-badge').on("focus", function() {
    var self = $(this);

    //Do ajax call if success reset the badge to zero
    self.attr("data-notification-badge",0);
    console.log("set badge to zero");

});


来源: stackexchange

问:
how to write multiple vtkUnstructuredGrid in one .vtu file
I want to write multiple unstructured grids in one .vtu file.

I tried below. MakeHexagonalPrism() and MakeHexahedron() return vtkSmartPointer type.
The result is there was only one unstructured grid in the output file.

```<code>  vtkSmartPointer<vtkXMLUnstructuredGridWriter> writer =
    vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New();
  writer->SetFileName(filename.c_str());
  writer->SetInputData(MakeHexagonalPrism());
  writer->SetInputData(MakeHexahedron());
  writer->Write();
</code>```

I also tried below. The type of cellArray1 and cellArray2  is vtkSmartPointer. The result is there was only one type of unstructured grid in the output file.

```<code>  vtkSmartPointer<vtkUnstructuredGrid> unstructuredGrid =
    vtkSmartPointer<vtkUnstructuredGrid>::New();
  unstructuredGrid->SetPoints(points);
  unstructuredGrid->SetCells(VTK_TETRA, cellArray1);
  unstructuredGrid->SetCells(VTK_WEDGE, cellArray2);
</code>```

I do not know how to write multiple unstructured grids in one .vtu file.
I'd be grateful for any hints.

答:
As described by the documentation, the vtkUnstructuredGrid class is very versatile.

dataset represents arbitrary combinations of all possible cell types

You could use the vtkAppendFilter in order to append different data sets into one then write the output as a vtkUnstructuredGrid result in a .vtu file.

```<code>// create the append filter
vtkSmartPointer<vtkAppendFilter> append =
vtkSmartPointer<vtkAppendfilter>::New();

// add each data set
append->AddInputData(MakeHexagonalPrism());
append->AddInputData(MakeHexahedron());
append->Update();

// write the result
vtkSmartPointer<vtkXMLUnstructuredGridWriter> writer =
vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New();
writer->SetFileName(filename.c_str());
writer->SetInputData(append->GetOutput());
</code>```

EDIT: I added the missing Update() function call as suggested by Amit Singh

ContentLicense: CC BY-SA 3.0

Body:
I want to write multiple unstructured grids in one .vtu file.

I tried below. MakeHexagonalPrism() and MakeHexahedron() return vtkSmartPointer type.
The result is there was only one unstructured grid in the output file.

  vtkSmartPointer<vtkXMLUnstructuredGridWriter> writer =
    vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New();
  writer->SetFileName(filename.c_str());
  writer->SetInputData(MakeHexagonalPrism());
  writer->SetInputData(MakeHexahedron());
  writer->Write();

I also tried below. The type of cellArray1 and cellArray2  is vtkSmartPointer. The result is there was only one type of unstructured grid in the output file.

  vtkSmartPointer<vtkUnstructuredGrid> unstructuredGrid =
    vtkSmartPointer<vtkUnstructuredGrid>::New();
  unstructuredGrid->SetPoints(points);
  unstructuredGrid->SetCells(VTK_TETRA, cellArray1);
  unstructuredGrid->SetCells(VTK_WEDGE, cellArray2);

I do not know how to write multiple unstructured grids in one .vtu file.
I'd be grateful for any hints.

Body:
As described by the documentation, the vtkUnstructuredGrid class is very versatile.

dataset represents arbitrary combinations of all possible cell types

You could use the vtkAppendFilter in order to append different data sets into one then write the output as a vtkUnstructuredGrid result in a .vtu file.

// create the append filter
vtkSmartPointer<vtkAppendFilter> append =
vtkSmartPointer<vtkAppendfilter>::New();

// add each data set
append->AddInputData(MakeHexagonalPrism());
append->AddInputData(MakeHexahedron());
append->Update();

// write the result
vtkSmartPointer<vtkXMLUnstructuredGridWriter> writer =
vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New();
writer->SetFileName(filename.c_str());
writer->SetInputData(append->GetOutput());

EDIT: I added the missing Update() function call as suggested by Amit Singh


问:
Adding to a List/Array in a Loop
Beginner coder here! I am looking to make a loop that will check the list named "budget" to see if its negative, and if it is, it will use the "years" list to add the year to the list named "nodef". My end result is to have the list "nodef" to contain all the years that have no deficits.

```<code>budget = [-1075,1225,4239,6084,1489,4031,1846,600,-6409,-19262,-14011,-12969,-9220,-10453,-10315,-3500,-1500,600,600,900]

years = [2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019]

nodef = []

i = 0

if i <21:

 if budget[i]<0:

   nodef.append(years[i])
   i += 1
else:

print(nodef)
</code>```

This is what I have at the moment. Please let me know how I can approve upon this. This is purely for my own curiosity.

答:
Another way of doing it would be:

```<code>nodef = list(map(lambda k: years[k], filter(lambda i: budget[i]<0, range(len(budget)))))
print(nodef)
</code>```

It produces the following output:

```<code>[2000, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016]
</code>```

Title: Adding to a List/Array in a Loop

Body:
Beginner coder here! I am looking to make a loop that will check the list named "budget" to see if its negative, and if it is, it will use the "years" list to add the year to the list named "nodef". My end result is to have the list "nodef" to contain all the years that have no deficits.

budget = [-1075,1225,4239,6084,1489,4031,1846,600,-6409,-19262,-14011,-12969,-9220,-10453,-10315,-3500,-1500,600,600,900]

years = [2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019]

nodef = []

i = 0

if i <21:

 if budget[i]<0:

   nodef.append(years[i])
   i += 1
else:

print(nodef)

This is what I have at the moment. Please let me know how I can approve upon this. This is purely for my own curiosity.

Body:
Another way of doing it would be:

nodef = list(map(lambda k: years[k], filter(lambda i: budget[i]<0, range(len(budget)))))
print(nodef)

It produces the following output:

[2000, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016]


问:
Filter array of dates
I know that there is .filter () in it that filters an array to return it just the way I want, and using a lot to search, when we pass what we want to search in that array.

However I'm having trouble filtering an array of dates like this:

```<code>["08:00" "09:00" "10:10" "10:30" "10:50" "11:30" "11:50" "12:00"];
</code>```

I need to filter it by past date I have start date and end date, for example step to it " 09:00 " and " 11:30 " it should return to me:

```<code>["10:10" "10:30" "10:50"]
</code>```

Trying to do this I did so in my typescript:

```<code>1. this.schedules = this.navigation.lineSelected.schedules;
2. this.schedules.filter (item => {
3. item> this.hourNow && item <this.hourFinish
4.});
</code>```

On line 1 I get all the times I have, so on line 2.4 I filter this array, but it returns everything to me.

How can I do this?

Translating what I need:

I'm going to have two strings of hours like "12:00" and "15:00" I need to make comparisons in my array, because I need the hours that are between interval as in the above example.

When I say time I'm talking about a string, so I need to compare string if it's bigger or not than the other type string that are below "12:00" will not appear in my final array, and strings larger than "15:00" will also do not.

This is the best way I can explain what I need, I do not see any other option to explain. Simply filter an array

答:
If you want to do it in a more archaic way without using filter or Date you can use this. I'd personally use Nina's answer.</p>

```<code>var timestamps = ["08:00","09:00","10:10","10:30","10:50","11:30","11:50","12:00"];

function compareTimeString(time1, time2) {
    time1 = time1.split(":");
    time2 = time2.split(":");

    time1 = parseInt(time1[0]) * 60 + parseInt(time1[1]);
    time2 = parseInt(time2[0]) * 60 + parseInt(time2[1]);

    return time1 > time2 ? true : false;
}

function middleTime(startTime,endTime, timestamps) {
    var times = []

    for(i=0; i<timestamps.length; i++) {
        if(!compareTimeString(startTime,timestamps[i]) &&
            compareTimeString(endTime,timestamps[i])) {
            times.push(timestamps[i])
        }
    }

    return times;
}
</code>```

Title: Filter array of dates

Body:
I know that there is .filter () in it that filters an array to return it just the way I want, and using a lot to search, when we pass what we want to search in that array.

However I'm having trouble filtering an array of dates like this:

["08:00" "09:00" "10:10" "10:30" "10:50" "11:30" "11:50" "12:00"];

I need to filter it by past date I have start date and end date, for example step to it " 09:00 " and " 11:30 " it should return to me:

["10:10" "10:30" "10:50"]

Trying to do this I did so in my typescript:

1. this.schedules = this.navigation.lineSelected.schedules;
2. this.schedules.filter (item => {
3. item> this.hourNow && item <this.hourFinish
4.});

On line 1 I get all the times I have, so on line 2.4 I filter this array, but it returns everything to me.

How can I do this?

Translating what I need:

I'm going to have two strings of hours like "12:00" and "15:00" I need to make comparisons in my array, because I need the hours that are between interval as in the above example.

When I say time I'm talking about a string, so I need to compare string if it's bigger or not than the other type string that are below "12:00" will not appear in my final array, and strings larger than "15:00" will also do not.

This is the best way I can explain what I need, I do not see any other option to explain. Simply filter an array

Body:
If you want to do it in a more archaic way without using filter or Date you can use this. I'd personally use Nina's answer.

var timestamps = ["08:00","09:00","10:10","10:30","10:50","11:30","11:50","12:00"];

function compareTimeString(time1, time2) {
    time1 = time1.split(":");
    time2 = time2.split(":");

    time1 = parseInt(time1[0]) * 60 + parseInt(time1[1]);
    time2 = parseInt(time2[0]) * 60 + parseInt(time2[1]);

    return time1 > time2 ? true : false;
}

function middleTime(startTime,endTime, timestamps) {
    var times = []

    for(i=0; i<timestamps.length; i++) {
        if(!compareTimeString(startTime,timestamps[i]) &&
            compareTimeString(endTime,timestamps[i])) {
            times.push(timestamps[i])
        }
    }

    return times;
}


问:
Send Packets to another subnet/network using Sockets
I am trying to find out whether the machines in a network are running a certain app. More like, I am trying to resolve addresses of nodes in a network.

I built a small code based on ARP, but it works only on a local network(same subnet). What I want to do is resolve addresses out of the subnet i.e. all other nodes.

I read these answers: UDP broadcast packets across subnets
and Broadcast on different subnets

But they all talk about changing router setting or creating a multicast network.

From what I read for multicasting to work, I need to create a multitask network beforehand. Is it really necessary?

And for changing router setting, does it really have to be a "special" router?

This is all for a college assignment and would be demonstrating it probably on an ad-hoc network or something like that.
I am open to ideas to solve the original problem.

PS:
1. I am a beginner in networking so do excuse me for any fault or misinterpretation.

I am using sockets and C(No other option).

Edit 1:
I am well aware ARP is useless outside the subnet. I mentioned it because I used it and it helped explaining the problem.

Edit 2:

The original problem is:

Building a chat application, nothing fancy sending messages from one point to another, without using a  central server of any kind. Not even a hybrid network with a central store is allowed.

i.e. if A and B are two clients, A should directly connect to B and vice versa.
I did some research and decided to use P2P architecture. And now I am stuck to how will A discover address of B. If I know the subnet of B, I can brute force and locate B but since I don't have such information what do I do?

答:
ARP is not intended to be routed outside the local network, where in IPv4, the "local network" typically corresponds to a subnet.  You should not expect ARP traffic to transit routers from inside to outside or vise versa.

Similarly, UDP broadcasts generally do not propagate outside the local network, and it's a good thing that they don't, for reasons related to both security and traffic volume.

From what I read for multicasting to work, I need to create a multitask network beforehand. Is it really necessary?

Basically, yes.  Your routers need to be configured to support multicasting (which may be their default).  All participants need to agree on and join the same multicast group.  There might not be a need for any new networking hardware, but multicast communication has its own protocols and network requirements; it is not merely a broadcast that can traverse network boundaries.

And for changing router setting, does it really have to be a "special" router?

If you mean changing router settings so that UDP broadcasts are routed between networks, you do indeed need a router that exposes this capability.  But I urge you not to do this, as it will let broadcasts from all other sources, for all other reasons transit the router, too.  At minimum, this will significantly increase the noisiness of all networks involved, but it could produce bona fide misbehavior of applications and services other than yours.


问:
Modeling relationships with domain models
In my system, an User can be member of a Team.

I got a domain model called Team which contains id, name, member_count and is_channel. So when I fetch teams in the repository I retrieve the Team domain model.

How would I model the relation between a User and a Team? Because when talking about the relation I don’t care about the member_count and is_channel from the Team model. I even have extra data in the relation which is a role_type.

Should I create a domain model for the relation called TeamScope or something? That contains id, user_id, team_id, role_type?

答:
You should almost definitely model a TeamMember object which contains both a link to the User, a link to the Team, and the role the user plays on that team.

Teams have a list of TeamMembers, Users have a list of TeamMembers.  Teams have a MemberCount (not sure if this is static, or dynamic from the count of TeamMembers), and I have no idea what is_channel means...


问:
Using Proxy Authorization Header with ScalajHTTP
I'm getting a 407 error using scalajHTTP. I read through the repository and it seems like I should be able to pass the basic auth credentials as a base64 encoded value. I've also tried using the helper method described in the GitHub issues .proxyAuth but that is no longer part of HTTPRequest in ScalaJ according to error messages (as well as it not being in the documentation)

Any ideas? My endpoint URL is HTTPS as well as my proxy (for additional context)

```<code> val proxyHost= s"https://$forwardProxy"
 val requestForward = Http(url).postData(redactedSecret)
   .option(HttpOptions.allowUnsafeSSL)
   .headers(("Content-Type", "application/json"), ("Proxy-Authorization", s"Basic $proxyAuth"))
   .proxy(proxyHost, 8080).asString
 val responseForward: HttpResponse[String] = requestForward
</code>```

答:
I found a solution to this problem. I researched around and after trying http client libraries, I kept getting 407 errors even though they all support proxy auth. Anyway, I ended up having to do the following.

add

```<code>import java.net.{Authenticator,PasswordAuthentication}
</code>```

and the modified code body that I previously above looks like:

```<code>val requestForward: HttpRequest = Http(url).postData(data)
.header("Content-Type", "application/json")
.proxy(proxyHost, 8080)
.option(HttpOptions.allowUnsafeSSL)
Authenticator.setDefault(new Authenticator() {
 override def getPasswordAuthentication(): PasswordAuthentication = {
  new PasswordAuthentication( s"$username", s"$password".toCharArray())
 }
})
</code>```

So as you can see I removed the header from the original request object and instead overrode the credentials. Make sure you do this before you call on the response object.

Body:
I'm getting a 407 error using scalajHTTP. I read through the repository and it seems like I should be able to pass the basic auth credentials as a base64 encoded value. I've also tried using the helper method described in the GitHub issues .proxyAuth but that is no longer part of HTTPRequest in ScalaJ according to error messages (as well as it not being in the documentation)

Any ideas? My endpoint URL is HTTPS as well as my proxy (for additional context)

 val proxyHost= s"https://$forwardProxy"
 val requestForward = Http(url).postData(redactedSecret)
   .option(HttpOptions.allowUnsafeSSL)
   .headers(("Content-Type", "application/json"), ("Proxy-Authorization", s"Basic $proxyAuth"))
   .proxy(proxyHost, 8080).asString
 val responseForward: HttpResponse[String] = requestForward

Body:
I found a solution to this problem. I researched around and after trying http client libraries, I kept getting 407 errors even though they all support proxy auth. Anyway, I ended up having to do the following.

add

import java.net.{Authenticator,PasswordAuthentication}

and the modified code body that I previously above looks like:

val requestForward: HttpRequest = Http(url).postData(data)
.header("Content-Type", "application/json")
.proxy(proxyHost, 8080)
.option(HttpOptions.allowUnsafeSSL)
Authenticator.setDefault(new Authenticator() {
 override def getPasswordAuthentication(): PasswordAuthentication = {
  new PasswordAuthentication( s"$username", s"$password".toCharArray())
 }
})

So as you can see I removed the header from the original request object and instead overrode the credentials. Make sure you do this before you call on the response object.


问:
How to remove duplicate values of only one column element based on another column
I have data where I have one element of interest (111) in a column. My data looks something like this:

```<code>pcp2 <- data.frame(A = c(rep(111, 4), rep(222, 5), rep(111,5),
        rep(222,5)),B= c(rep(1,9), rep(2,10)))

     A  B
1   111 1
2   111 1
3   111 1
4   111 1
5   222 1
6   222 1
7   222 1
8   222 1
9   222 1
10  111 2
11  111 2
12  111 2
13  111 2
14  111 2
15  222 2
16  222 2
17  222 2
18  222 2
19  222 2
</code>```

I want to collapse all of only variable 222 and leave all 111 untouched throughout my data based upon the IDs in column B like so:

```<code>     A  B
1   111 1
2   111 1
3   111 1
4   111 1
5   222 1
6   111 2
7   111 2
8   111 2
9   111 2
10  111 2
11  222 2
</code>```

All I have been able to find that is close reduces all the variables (both 111 and 222).

```<code>library(data.table)
dat <- as.data.table(pcp2, key = "B")
data <- dat[, by = key(dat)][!duplicated(A == "222")]
</code>```

as follows:

```<code>   A    B
1 111   1
2 222   2
</code>```

I've played around with various iterations of this code and others, but other things I've tried as well have just gotten my data down to two rows or collapsed both 111 and 222. I.e. this wouldn't be sufficient:

```<code>   A  B
1 111 1
2 222 2
3 111 2
4 222 2
</code>```

Does anyone have any guidance for how you would maintain the 111 and collapse the 222 within one column based on another column like the example (B in this case)? I know other examples are similar but none seem to give the option to specify not collapsing a particular variable within one column while collapsing the other(s).

Body:
I have data where I have one element of interest (111) in a column. My data looks something like this:

pcp2 <- data.frame(A = c(rep(111, 4), rep(222, 5), rep(111,5),
        rep(222,5)),B= c(rep(1,9), rep(2,10)))

     A  B
1   111 1
2   111 1
3   111 1
4   111 1
5   222 1
6   222 1
7   222 1
8   222 1
9   222 1
10  111 2
11  111 2
12  111 2
13  111 2
14  111 2
15  222 2
16  222 2
17  222 2
18  222 2
19  222 2

I want to collapse all of only variable 222 and leave all 111 untouched throughout my data based upon the IDs in column B like so:

     A  B
1   111 1
2   111 1
3   111 1
4   111 1
5   222 1
6   111 2
7   111 2
8   111 2
9   111 2
10  111 2
11  222 2

All I have been able to find that is close reduces all the variables (both 111 and 222).

library(data.table)
dat <- as.data.table(pcp2, key = "B")
data <- dat[, by = key(dat)][!duplicated(A == "222")]

as follows:

   A    B
1 111   1
2 222   2

I've played around with various iterations of this code and others, but other things I've tried as well have just gotten my data down to two rows or collapsed both 111 and 222. I.e. this wouldn't be sufficient:

   A  B
1 111 1
2 222 2
3 111 2
4 222 2

Does anyone have any guidance for how you would maintain the 111 and collapse the 222 within one column based on another column like the example (B in this case)? I know other examples are similar but none seem to give the option to specify not collapsing a particular variable within one column while collapsing the other(s).

Body:
Here's a dplyr solution using slice. This solution does not assume that the other values of A other than 111 are 222:

library(dplyr)

pcp2 %>%
  group_by(B, A) %>%
  slice(if(any(A == "111")) 1:n() else 1)

Alternatively using data.table:

library(data.table)

setDT(pcp2)[, .I[if(any(A=="111")) 1:.N else 1], by = c("B", "A")][,.SD, .SDcols = A:B]

Result:

# A tibble: 12 x 2
# Groups:   B, A [5]
       A     B
   <dbl> <dbl>
 1   111     1
 2   111     1
 3   111     1
 4   111     1
 5   222     1
 6   111     2
 7   111     2
 8   111     2
 9   111     2
10   111     2
11   222     2
12   333     2

      A B
 1: 111 1
 2: 111 1
 3: 111 1
 4: 111 1
 5: 222 1
 6: 111 2
 7: 111 2
 8: 111 2
 9: 111 2
10: 111 2
11: 222 2
12: 333 2

Data:

pcp2 <- data.frame(A = c(rep(111, 4), rep(222, 5), rep(111,5),
                         rep(222,5), rep(333, 5)), B= c(rep(1,9), rep(2,10), rep(2, 5)))


问:
How can I change this date and time format to yyyy-mm-dd hh:mm:ss using bash, this is from an apache log file
```<code>49,10.96.25.156,1274x40x1,-,02/Nov/2017:21:14:31,http-nio-443-exec-20,"POST/rest/webResources/1.0/resourcesHTTP/1.1",503,40,0,"-","SilkPerformer17.0""-"
50,10.96.25.156,1274x41x1,-,02/Nov/2017:21:14:31,http-nio-443-exec-25,"POST/rest/webResources/1.0/resourcesHTTP/1.1",503,40,0,"-","SilkPerformer17.0""9myyx9"
</code>```

This is how the log file looks, any help would be appreciated. Thanks!

答:
You can use either date or awk to do the conversion.
If you have the dateutils package installed, here is a straightforward command that you can use

```<code>dateutils.dconv -S -i "%d/%b/%Y:" -f "%F " < file.log
</code>```

-i to specify input date format

-f to specify output date format

-S sed mode, to process only the matched date string

Input

```<code>49,10.96.25.156,1274x40x1,-,02/Nov/2017:21:14:31,http-nio-443-exec-20
</code>```

Output

```<code>49,10.96.25.156,1274x40x1,-,2017-11-02 21:14:31,http-nio-443-exec-20
</code>```

Body:
49,10.96.25.156,1274x40x1,-,02/Nov/2017:21:14:31,http-nio-443-exec-20,"POST/rest/webResources/1.0/resourcesHTTP/1.1",503,40,0,"-","SilkPerformer17.0""-"
50,10.96.25.156,1274x41x1,-,02/Nov/2017:21:14:31,http-nio-443-exec-25,"POST/rest/webResources/1.0/resourcesHTTP/1.1",503,40,0,"-","SilkPerformer17.0""9myyx9"

This is how the log file looks, any help would be appreciated. Thanks!

Body:
You can use either date or awk to do the conversion.
If you have the dateutils package installed, here is a straightforward command that you can use

dateutils.dconv -S -i "%d/%b/%Y:" -f "%F " < file.log

-i to specify input date format

-f to specify output date format

-S sed mode, to process only the matched date string

Input

49,10.96.25.156,1274x40x1,-,02/Nov/2017:21:14:31,http-nio-443-exec-20

Output

49,10.96.25.156,1274x40x1,-,2017-11-02 21:14:31,http-nio-443-exec-20


问:
Unity3D glTF Invalid array at buffers when loading a 3d object
I'm using the glTF Unity3D Loader. I want to load some 3D Objects with glTF format in real time. With the glTF files they included in the examples, it works great. But when I try to load my 3D Object I'm getting this error:

Does anyone know how can I approach this?

```<code>Exception: Invalid array at: buffers
GLTF.Extensions.JsonReaderExtensions.ReadList[Buffer] (Newtonsoft.Json.JsonReader reader, System.Func`1 deserializerFunc) (at C:/Users/johnmce/Documents/GitHub/UnityGLTF/GLTFSerialization/GLTFSerialization/Extensions/GLTFJsonExtensions.cs:50)
GLTF.Schema.GLTFRoot.Deserialize (System.IO.TextReader textReader) (at C:/Users/johnmce/Documents/GitHub/UnityGLTF/GLTFSerialization/GLTFSerialization/Schema/GLTFRoot.cs:151)
GLTF.GLTFParser.ParseString (System.String gltfContent) (at C:/Users/johnmce/Documents/GitHub/UnityGLTF/GLTFSerialization/GLTFSerialization/GLTFParser.cs:123)
GLTF.GLTFParser.ParseJson (System.Byte[] gltfBinary) (at C:/Users/johnmce/Documents/GitHub/UnityGLTF/GLTFSerialization/GLTFSerialization/GLTFParser.cs:40)
UnityGLTF.GLTFSceneImporter+<Load>c__Iterator0.MoveNext () (at Assets/UnityGLTF/Scripts/GLTFSceneImporter.cs:124)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)
</code>```

答:
Solution:

Many files that are Version 1.1 aren't supported by the current 2.0 parser.

Body:
I'm using the glTF Unity3D Loader. I want to load some 3D Objects with glTF format in real time. With the glTF files they included in the examples, it works great. But when I try to load my 3D Object I'm getting this error:

Does anyone know how can I approach this?

Exception: Invalid array at: buffers
GLTF.Extensions.JsonReaderExtensions.ReadList[Buffer] (Newtonsoft.Json.JsonReader reader, System.Func`1 deserializerFunc) (at C:/Users/johnmce/Documents/GitHub/UnityGLTF/GLTFSerialization/GLTFSerialization/Extensions/GLTFJsonExtensions.cs:50)
GLTF.Schema.GLTFRoot.Deserialize (System.IO.TextReader textReader) (at C:/Users/johnmce/Documents/GitHub/UnityGLTF/GLTFSerialization/GLTFSerialization/Schema/GLTFRoot.cs:151)
GLTF.GLTFParser.ParseString (System.String gltfContent) (at C:/Users/johnmce/Documents/GitHub/UnityGLTF/GLTFSerialization/GLTFSerialization/GLTFParser.cs:123)
GLTF.GLTFParser.ParseJson (System.Byte[] gltfBinary) (at C:/Users/johnmce/Documents/GitHub/UnityGLTF/GLTFSerialization/GLTFSerialization/GLTFParser.cs:40)
UnityGLTF.GLTFSceneImporter+<Load>c__Iterator0.MoveNext () (at Assets/UnityGLTF/Scripts/GLTFSceneImporter.cs:124)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)


问:
Class 'App\Http\Controllers\Excel' not found in Laravel
In my controller I have the code as below:

```<code>Excel::create('Laravel Excel', function($excel) {

        $excel->sheet('Excel sheet', function($sheet) {

            $sheet->setOrientation('landscape');

        });

    })->export('xls');
</code>```

In config/app.php in aliases array i have defined this:

```<code>'Excel'     => 'Maatwebsite\Excel\ExcelServiceProvider',
</code>```

I dont know why i cant make it work this library...
Any idea?

答:
After all this you need to check whether or not you have this at the top:</p>

```<code>use Maatwebsite\Excel\Facades\Excel;
</code>```

Body:
In my controller I have the code as below:

Excel::create('Laravel Excel', function($excel) {

        $excel->sheet('Excel sheet', function($sheet) {

            $sheet->setOrientation('landscape');

        });

    })->export('xls');

In config/app.php in aliases array i have defined this:

'Excel'     => 'Maatwebsite\Excel\ExcelServiceProvider',

I dont know why i cant make it work this library...
Any idea?

Body:
After all this you need to check whether or not you have this at the top:

use Maatwebsite\Excel\Facades\Excel;


问:
Query with subquery returns null
I Have a query with returns no results despite there are still plenty of rows to process.

```<code>SELECT O.[OrderLineId]
, O.[Article]
, O.[ArticleDescription]
, O.[QtyOrdered]
, O.[QtyDelivered]
, O.[BoxId]
, O.[Status]
, O.[Picker]
, O.[PickLocation]
, O.[Sorting]
, O.[DateCreated]
, O.[DateModified]
FROM [dbo].[PickBatch] P
INNER JOIN [dbo].[Boxes] B ON P.PickBatchId = B.PickBatchId
INNER JOIN [dbo].[OrderLines] O ON B.BoxId = O.BoxId
WHERE P.PickBatchId = @PickBatchId
AND (O.[Status] = @Status)
AND (O.[PickLocation] = (SELECT TOP(1) O.[PickLocation]
                        FROM [dbo].[PickBatch] P
                      INNER JOIN [dbo].[Boxes] B ON P.PickBatchId = B.PickBatchId
                      INNER JOIN [dbo].[OrderLines] O ON B.BoxId = O.BoxId
                      WHERE P.PickBatchId = @PickBatchId
                      AND O.[Status] = @Status
                      ORDER BY O.Sorting))
</code>```

It looks like the subquery returns a result and meanwhile the status is changed so that the main query returns no results. Is this possible? Or do I make another mistake?

When the query returns no results the users is prompted that everything is picked and he can start a new batch. When he want's to start a new batch there a check if he hasn't an open batch. This fires few queries and this query. Then the query returns a result. So basically query is fired no results, sec. later same query returns results.

答: Can you describe primary keys for this tables. I think problem with sub query always return a row but don't matched with main query values.

Title: Query with subquery returns null

Body:
I Have a query with returns no results despite there are still plenty of rows to process.

SELECT O.[OrderLineId]
, O.[Article]
, O.[ArticleDescription]
, O.[QtyOrdered]
, O.[QtyDelivered]
, O.[BoxId]
, O.[Status]
, O.[Picker]
, O.[PickLocation]
, O.[Sorting]
, O.[DateCreated]
, O.[DateModified]
FROM [dbo].[PickBatch] P
INNER JOIN [dbo].[Boxes] B ON P.PickBatchId = B.PickBatchId
INNER JOIN [dbo].[OrderLines] O ON B.BoxId = O.BoxId
WHERE P.PickBatchId = @PickBatchId
AND (O.[Status] = @Status)
AND (O.[PickLocation] = (SELECT TOP(1) O.[PickLocation]
                        FROM [dbo].[PickBatch] P
                      INNER JOIN [dbo].[Boxes] B ON P.PickBatchId = B.PickBatchId
                      INNER JOIN [dbo].[OrderLines] O ON B.BoxId = O.BoxId
                      WHERE P.PickBatchId = @PickBatchId
                      AND O.[Status] = @Status
                      ORDER BY O.Sorting))

It looks like the subquery returns a result and meanwhile the status is changed so that the main query returns no results. Is this possible? Or do I make another mistake?

When the query returns no results the users is prompted that everything is picked and he can start a new batch. When he want's to start a new batch there a check if he hasn't an open batch. This fires few queries and this query. Then the query returns a result. So basically query is fired no results, sec. later same query returns results.


答:
The Limited Broadcast (255.255.255.255, which is used by ARP requests as the destination address, and ARP only works for IPv4 on the local LAN) cannot cross a router, and a Network Broadcast (last network address, where the host is all ones) by default cannot cross a router (Directed Broadcast) because it is a security risk (see RFC 2644, Changing the Default for Directed Broadcasts in Routers).

Some routers can be configured to forward directed broadcasts, but this can be dangerous.

Multicast is a form of broadcast. Multicast routing is very different than unicast routing, and every router in a path must be configured for multicast routing. Also, hosts must subscribe to a multicast group before they will even listen for packets from a multicast group. Additionally, there are some multicast groups that all hosts listen for, but those are link-local multicasts that cannot be forwarded off the local LAN.

Title: Send Packets to another subnet/network using Sockets

Body:
I am trying to find out whether the machines in a network are running a certain app. More like, I am trying to resolve addresses of nodes in a network.

I built a small code based on ARP, but it works only on a local network(same subnet). What I want to do is resolve addresses out of the subnet i.e. all other nodes.

I read these answers: UDP broadcast packets across subnets
and Broadcast on different subnets

But they all talk about changing router setting or creating a multicast network.

From what I read for multicasting to work, I need to create a multitask network beforehand. Is it really necessary?

And for changing router setting, does it really have to be a "special" router?

This is all for a college assignment and would be demonstrating it probably on an ad-hoc network or something like that.
I am open to ideas to solve the original problem.

PS:
1. I am a beginner in networking so do excuse me for any fault or misinterpretation.

I am using sockets and C(No other option).

Edit 1:
I am well aware ARP is useless outside the subnet. I mentioned it because I used it and it helped explaining the problem.

Edit 2:

The original problem is:

Building a chat application, nothing fancy sending messages from one point to another, without using a  central server of any kind. Not even a hybrid network with a central store is allowed.

i.e. if A and B are two clients, A should directly connect to B and vice versa.
I did some research and decided to use P2P architecture. And now I am stuck to how will A discover address of B. If I know the subnet of B, I can brute force and locate B but since I don't have such information what do I do?


问:
Declare and assign multiple string variables at the same time
I'm declaring some strings that are empty, so it won't throw errors later on.

I've read that this was the proper way:

```<code>string Camnr = Klantnr = Ordernr = Bonnr = Volgnr = Omschrijving = Startdatum = Bonprioriteit = Matsoort = Dikte = Draaibaarheid = Draaiomschrijving = Orderleverdatum = Regeltaakkode = Gebruiksvoorkeur = Regelcamprog = Regeltijd = Orderrelease = "";
</code>```

But that doesn't work. I get this error: Klantnr does not exist in the current context.

What did I do wrong?

答:
Fairly old question but incase someone goes back.

This isn't as compact as the other answers above, but fairly readable and easier to type using Visual Studio Multi-Line selection shortcut [Alt+ Shift + ↑] (or other directions)

```<code>string Camnr = string.Empty;
string Klantnr = string.Empty;
</code>```

Type out all variable names on new lines. Multi-Select in front of them an type "string". Multi-Select behind them and type "= string.Empty;".

Body:
I'm declaring some strings that are empty, so it won't throw errors later on.

I've read that this was the proper way:

string Camnr = Klantnr = Ordernr = Bonnr = Volgnr = Omschrijving = Startdatum = Bonprioriteit = Matsoort = Dikte = Draaibaarheid = Draaiomschrijving = Orderleverdatum = Regeltaakkode = Gebruiksvoorkeur = Regelcamprog = Regeltijd = Orderrelease = "";

But that doesn't work. I get this error: Klantnr does not exist in the current context.

What did I do wrong?

Body:
Fairly old question but incase someone goes back.

This isn't as compact as the other answers above, but fairly readable and easier to type using Visual Studio Multi-Line selection shortcut [Alt+ Shift + ↑] (or other directions)

string Camnr = string.Empty;
string Klantnr = string.Empty;

Type out all variable names on new lines. Multi-Select in front of them an type "string". Multi-Select behind them and type "= string.Empty;".


问:
Awk - Call for a second associated value from file1 after finding a match in file2
I have a code to read gene names from file1 and find them in file2, then I put them together into a table, my problem is that I need to add another column with the associated "start" value from file1 into the table, but couldn't make it. I've tried, but I don't know much about awk in first place, so any help is welcomed.

The idea of final table is:

```<code>File1_gen  File2_gen  Start_from_file1  Value_1_from_file2  Value_2_from_file2
</code>```

File 1:
This file has ~70.000 rows and 4 columns; row number, gene name, gene start and gene end, and I just need gene name and start from this

```<code>        seqnames    start   end
10  Gen_3992149.1   851 900
11  Gen_0011774.1   3899    4043
12  Gen_0011774.1   7628    7692
13  Gen_3993605.1   522 535
</code>```

File 2:
Then, the second file has ~100.000 rows and 3 columns; gene name, and start and end values, and I need the three of them

```<code>Gen_3993605.1   1   602
Gen_3989779.1   691 1002
Gen_3989835.1   1   993
Gen_0011774.1   1476    1712
Gen_0011774.1   5125    6931
Gen_0011774.1   8838    12313
</code>```

I've already have a pseudocode that do almost all of this

```<code>awk '
FNR == NR {
  # reading file1
    scaf[$2]
    co_id[$3]
next
}
{
  # reading file2
  for (i in scaf) {
    id in co_id
    if ( i == $1 )
    print "[1] "  i "\t" "[2] " $1 "\t" "[3] " id "\t" "[4] " $4 "\t" "[5] "$5
    }
       }
 ' Search.txt Genes.txt
</code>```

Resulting something like this:

```<code>[1] Gen_3993605.1       [2] Gen_3993605.1       [3] 522    [4] 1    [5] 602
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899    [4] 1476    [5] 1712
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899    [4] 5125    [5] 6931
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899    [4] 8838    [5] 12313
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628    [4] 1476    [5] 1712
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628    [4] 5125    [5] 6931
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628    [4] 8838    [5] 12313
</code>```

As you can see, the [3] column is empty, and I know the 'id in co_id' is wrong, but it was the last attempt I tried.

In other words, how can I call the associated "start" value for each gene in file1 into the new table I've made?

Edit: Changed the sample data for something that should work. And if there is repeated gene names it should show all the combinations.

答:
Second attempt ... based on updated question with a) reduced data set and b) additional requirement to support gene name showing up more than once in either data file.

Sample data:

```<code>$ cat gene.1
10  Gen_3992149.1   851 900
11  Gen_0011774.1   3899    4043
12  Gen_0011774.1   7628    7692
13  Gen_3993605.1   522 535

$ cat gene.2
Gen_3993605.1   1   602
Gen_3989779.1   691 1002
Gen_3989835.1   1   993
Gen_0011774.1   1476    1712
Gen_0011774.1   5125    6931
Gen_0011774.1   8838    12313
</code>```

Another awk solution:

```<code>$ awk '
# process first file; use gene name and row number as indices for 2-dimensional array;
# $2=gene/name, $1=row/number, $3=start/value
FNR==NR { start[$2][$1]=$3
          next }

# process second file
{ # loop through list of first dimension indices (ie, gene names)
  for (x in start)
      # if gene name ($1) shows up as first dimension index in our array ...
      if ( $1==x)
         # loop through the associated 2nd dimension, printing the desired results
         { for (y in start[x])
               { print "[1] " x "\t" "[2] " x "\t" "[3] " start[x][y] "\t" "[4] " $2 "\t" "[5] "$3 }
         }
} ' gene.1 gene.2 | sort

[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899        [4] 1476        [5] 1712
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899        [4] 5125        [5] 6931
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899        [4] 8838        [5] 12313
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628        [4] 1476        [5] 1712
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628        [4] 5125        [5] 6931
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628        [4] 8838        [5] 12313
[1] Gen_3993605.1       [2] Gen_3993605.1       [3] 522 [4] 1   [5] 602
</code>```

NOTE: piped the results through sort for basic sorting; could modify the sort criteria depending on desired output

As mentioned in my previous answer: If the output needs to be displayed with fixed width columns then that could be accomplished by replacing the print with an appropriate printf format string. (Alternatively, use @karakfa's example of the column command.)

Body:
I have a code to read gene names from file1 and find them in file2, then I put them together into a table, my problem is that I need to add another column with the associated "start" value from file1 into the table, but couldn't make it. I've tried, but I don't know much about awk in first place, so any help is welcomed.

The idea of final table is:

File1_gen  File2_gen  Start_from_file1  Value_1_from_file2  Value_2_from_file2

File 1:
This file has ~70.000 rows and 4 columns; row number, gene name, gene start and gene end, and I just need gene name and start from this

        seqnames    start   end
10  Gen_3992149.1   851 900
11  Gen_0011774.1   3899    4043
12  Gen_0011774.1   7628    7692
13  Gen_3993605.1   522 535

File 2:
Then, the second file has ~100.000 rows and 3 columns; gene name, and start and end values, and I need the three of them

Gen_3993605.1   1   602
Gen_3989779.1   691 1002
Gen_3989835.1   1   993
Gen_0011774.1   1476    1712
Gen_0011774.1   5125    6931
Gen_0011774.1   8838    12313

I've already have a pseudocode that do almost all of this

awk '
FNR == NR {
  # reading file1
    scaf[$2]
    co_id[$3]
next
}
{
  # reading file2
  for (i in scaf) {
    id in co_id
    if ( i == $1 )
    print "[1] "  i "\t" "[2] " $1 "\t" "[3] " id "\t" "[4] " $4 "\t" "[5] "$5
    }
       }
 ' Search.txt Genes.txt

Resulting something like this:

[1] Gen_3993605.1       [2] Gen_3993605.1       [3] 522    [4] 1    [5] 602
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899    [4] 1476    [5] 1712
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899    [4] 5125    [5] 6931
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899    [4] 8838    [5] 12313
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628    [4] 1476    [5] 1712
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628    [4] 5125    [5] 6931
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628    [4] 8838    [5] 12313

As you can see, the [3] column is empty, and I know the 'id in co_id' is wrong, but it was the last attempt I tried.

In other words, how can I call the associated "start" value for each gene in file1 into the new table I've made?

Edit: Changed the sample data for something that should work. And if there is repeated gene names it should show all the combinations.

Body:
Second attempt ... based on updated question with a) reduced data set and b) additional requirement to support gene name showing up more than once in either data file.

Sample data:

$ cat gene.1
10  Gen_3992149.1   851 900
11  Gen_0011774.1   3899    4043
12  Gen_0011774.1   7628    7692
13  Gen_3993605.1   522 535

$ cat gene.2
Gen_3993605.1   1   602
Gen_3989779.1   691 1002
Gen_3989835.1   1   993
Gen_0011774.1   1476    1712
Gen_0011774.1   5125    6931
Gen_0011774.1   8838    12313

Another awk solution:

$ awk '
# process first file; use gene name and row number as indices for 2-dimensional array;
# $2=gene/name, $1=row/number, $3=start/value
FNR==NR { start[$2][$1]=$3
          next }

# process second file
{ # loop through list of first dimension indices (ie, gene names)
  for (x in start)
      # if gene name ($1) shows up as first dimension index in our array ...
      if ( $1==x)
         # loop through the associated 2nd dimension, printing the desired results
         { for (y in start[x])
               { print "[1] " x "\t" "[2] " x "\t" "[3] " start[x][y] "\t" "[4] " $2 "\t" "[5] "$3 }
         }
} ' gene.1 gene.2 | sort

[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899        [4] 1476        [5] 1712
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899        [4] 5125        [5] 6931
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 3899        [4] 8838        [5] 12313
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628        [4] 1476        [5] 1712
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628        [4] 5125        [5] 6931
[1] Gen_0011774.1       [2] Gen_0011774.1       [3] 7628        [4] 8838        [5] 12313
[1] Gen_3993605.1       [2] Gen_3993605.1       [3] 522 [4] 1   [5] 602

NOTE: piped the results through sort for basic sorting; could modify the sort criteria depending on desired output

As mentioned in my previous answer: If the output needs to be displayed with fixed width columns then that could be accomplished by replacing the print with an appropriate printf format string. (Alternatively, use @karakfa's example of the column command.)


问:
python threads hangs but no exception
I'm using threads with queue, the loop contains like 6000 items but it suddenly hangs in 5000 or more and never continue although no thread through any exception code is as below</p>

```<code>def extract_data():
    while True:
       empty_flag = False
       try:
           id = q2.get(timeout = 60)
       except Empty:
           empty_flag = True

      if not empty_flag:
           "do some processing here"

           q2.task_done()

threads_number = 5
q2 = Queue(threads_number * 2)
for i in range(threads_number):
    t = Thread(target=extract_data)
    t.daemon = True
    t.start()

try:
    for i,nbd in enumerate(lst[0:],0):  --> list contains 6000 itemts
        print "%d of %d\r" %(i+1,len(new_nbds)),   --> print hangs here in item (5898 of 6000) or hangs when finish and never end (6000 of 6000)
        sys.stdout.flush()
        q2.put(nbd)

    q2.join()

except KeyboardInterrupt:
    sys.exit(1)
</code>```

答: your Queue size is for 10 element and you are pushing 6000 element from a loop even though you are popping it concurrently from five different threads. I doubt during pushing and popping from the loop and thread respectively there is a synchronization issue arise and it leads to deadlock. Make the Queue size bigger that might solve your issue. Like q2 = Queue(threads_number * 10)

Title: python threads hangs but no exception

Body:
I'm using threads with queue, the loop contains like 6000 items but it suddenly hangs in 5000 or more and never continue although no thread through any exception code is as below

def extract_data():
    while True:
       empty_flag = False
       try:
           id = q2.get(timeout = 60)
       except Empty:
           empty_flag = True

      if not empty_flag:
           "do some processing here"

           q2.task_done()

threads_number = 5
q2 = Queue(threads_number * 2)
for i in range(threads_number):
    t = Thread(target=extract_data)
    t.daemon = True
    t.start()

try:
    for i,nbd in enumerate(lst[0:],0):  --> list contains 6000 itemts
        print "%d of %d\r" %(i+1,len(new_nbds)),   --> print hangs here in item (5898 of 6000) or hangs when finish and never end (6000 of 6000)
        sys.stdout.flush()
        q2.put(nbd)

    q2.join()

except KeyboardInterrupt:
    sys.exit(1)


问:
Locust tasks that follow redirects
I'm load testing a local API that will redirect a user based on a few conditions. Locust is not redirecting the simulated users hitting the end points and I know this because the app logs all redirects. If I manually hit the end points using curl, I can see the status is 302 and the Location header is set.

According to the embedded clients.HttpSession.request object, the allow_redirects option is set to True by default.

Any ideas?

答:
We use redirection in our locust test, especially during the login phase. The redirects are handled for us without a hitch. Print the status_code of the  response that you get back. Is it 200, 3xx or something worse?

Another suggestion: Don't throw your entire testing workflow into the locust file. That makes it too difficult to debug problems. Instead, create a standalone python script that uses the python requests library directly to simulate your workflow. Iron out any kinks, like redirection problems, in that simple, non-locust test script. Once you have that working, extract what you did into a file or class and have the locust task use the class.

Here is an example of what I mean. FooApplication does the real work. He is consumed by the locust file and a simple test script.

foo_app.py

```<code>class FooApplication():
    def __init__(self, client):
        self.client = client
        self.is_logged_in = False

    def login(self):
        self.client.cookies.clear()
        self.is_logged_in = False
        name = '/login'
        response = self.client.post('/login', {
            'user': 'testuser',
            'password': '12345'
        }, allow_redirects=True, name=name)
        if not response.ok:
            self.log_failure('Login failed', name, response)

    def load_foo(self):
        name = '/foo'
        response = self.client.get('/foo', name=name)
        if not response.ok:
            self.log_failure('Foo request failed ', name, response)

    def log_failure(self, message, name, response):
        pass # add some logging
</code>```

foo_test_client.py

```<code># Use this test file to iron out kinks in your request workflow
import requests
from locust.clients import HttpSession
from foo_app import FooApplication

client = HttpSession('http://dev.foo.com')
app = FooApplication(client)
app.login()
app.load_foo()
</code>```

locustfile.py

```<code>from foo_app import FooApplication
class FooTaskSet(TaskSet):
    def on_start(self):
        self.foo = FooApplication(self.client)

    @task(1)
    def login(self):
        if not self.foo.is_logged_in:
            self.foo.login()

    @task(5) # 5x more likely to load a foo vs logging in again
    def load_foo(self):
        if self.foo.is_logged_in:
            self.load_foo()
        else:
            self.login()
</code>```

Title: Locust tasks that follow redirects

Body:
We use redirection in our locust test, especially during the login phase. The redirects are handled for us without a hitch. Print the status_code of the  response that you get back. Is it 200, 3xx or something worse?

Another suggestion: Don't throw your entire testing workflow into the locust file. That makes it too difficult to debug problems. Instead, create a standalone python script that uses the python requests library directly to simulate your workflow. Iron out any kinks, like redirection problems, in that simple, non-locust test script. Once you have that working, extract what you did into a file or class and have the locust task use the class.

Here is an example of what I mean. FooApplication does the real work. He is consumed by the locust file and a simple test script.

foo_app.py

class FooApplication():
    def __init__(self, client):
        self.client = client
        self.is_logged_in = False

    def login(self):
        self.client.cookies.clear()
        self.is_logged_in = False
        name = '/login'
        response = self.client.post('/login', {
            'user': 'testuser',
            'password': '12345'
        }, allow_redirects=True, name=name)
        if not response.ok:
            self.log_failure('Login failed', name, response)

    def load_foo(self):
        name = '/foo'
        response = self.client.get('/foo', name=name)
        if not response.ok:
            self.log_failure('Foo request failed ', name, response)

    def log_failure(self, message, name, response):
        pass # add some logging

foo_test_client.py

# Use this test file to iron out kinks in your request workflow
import requests
from locust.clients import HttpSession
from foo_app import FooApplication

client = HttpSession('http://dev.foo.com')
app = FooApplication(client)
app.login()
app.load_foo()

locustfile.py

from foo_app import FooApplication
class FooTaskSet(TaskSet):
    def on_start(self):
        self.foo = FooApplication(self.client)

    @task(1)
    def login(self):
        if not self.foo.is_logged_in:
            self.foo.login()

    @task(5) # 5x more likely to load a foo vs logging in again
    def load_foo(self):
        if self.foo.is_logged_in:
            self.load_foo()
        else:
            self.login()

ContentLicense: CC BY-SA 4.0


问:
Looking for the biggest number before and after 'i' in list
I'm sorry if the title is confusing. Here's a better explanation:
So basically what I need to do is iterate through every number in list and print the biggest number west (list[0:i]) and the biggest number east. If the biggest number is smaller than i, we print i. So for list [1, 3, 2, 4, 3] the output should be:
1 4
3 4
3 4
4 4
4 3

I thought my code was correct but it doesn't work for the last number in list, is anyone able to help?

'a' is the list in my code

```<code>a = [1, 3, 2, 4, 3]
for i in a:
    west = a[0:i]
    east = a[i:int(len(a))]
    if max(west) > i:
        print(max(west))
    else:
        print(i)
    if max(east) > i:
        print(max(east))
    else:
        print(i)
</code>```

答:
this may work... not fully tested but it looks correct

```<code>a = [1, 3, 2, 4, 3]
for i in a[:-1]:
    west = a[0:i]
    east = a[i:int(len(a))]
    if max(west) > i:
        print(max(west))
    else:
        print(i)
    if max(east) > i:
        print(max(east))
    else:
        print(i)
num = a[-1]
west = a[0:-1]
if max(west) > num:
    print(max(west))
else:
    print(str(a[-1]))
print(str(a[-1]))
</code>```

Output: 1 4 3 4 4 4 4 3

Body:
I'm sorry if the title is confusing. Here's a better explanation:
So basically what I need to do is iterate through every number in list and print the biggest number west (list[0:i]) and the biggest number east. If the biggest number is smaller than i, we print i. So for list [1, 3, 2, 4, 3] the output should be:
1 4
3 4
3 4
4 4
4 3

I thought my code was correct but it doesn't work for the last number in list, is anyone able to help?

'a' is the list in my code

a = [1, 3, 2, 4, 3]
for i in a:
    west = a[0:i]
    east = a[i:int(len(a))]
    if max(west) > i:
        print(max(west))
    else:
        print(i)
    if max(east) > i:
        print(max(east))
    else:
        print(i)

Body:
this may work... not fully tested but it looks correct

a = [1, 3, 2, 4, 3]
for i in a[:-1]:
    west = a[0:i]
    east = a[i:int(len(a))]
    if max(west) > i:
        print(max(west))
    else:
        print(i)
    if max(east) > i:
        print(max(east))
    else:
        print(i)
num = a[-1]
west = a[0:-1]
if max(west) > num:
    print(max(west))
else:
    print(str(a[-1]))
print(str(a[-1]))

Output: 1 4 3 4 4 4 4 3


问:
How do I close the dialog properly , if the dialog is opened by mainframe
I have a mainframe and clicked the pushbutton to open a new dialog ,

the dialog have a timer , let the timer to show message at 3sec interval ,

but if I click the top right close button to close the dialog , the messagebox still run ,

how to avoid it ?

Thanks!

```<code>from PySide2.QtWidgets import QApplication,QMainWindow,QTabWidget,QWidget
from PySide2.QtWidgets import QMessageBox,QFileDialog,QErrorMessage
from PySide2 import QtCore, QtGui, QtWidgets
class UI_Test20(object):
    def setupUi(self, Test202):
        Test202.setObjectName("Test202")
        Test202.resize(100,100)
        self.centralwidget = QtWidgets.QWidget(Test202)
        self.centralwidget.setObjectName("centralwidget")
        self.pb = QtWidgets.QPushButton(self.centralwidget)
        self.pb.setText('push button!')
        Test202.setCentralWidget(self.centralwidget)
        self.pb.clicked.connect(self.btnClicked)
        self.retranslateUi(Test202)
        QtCore.QMetaObject.connectSlotsByName(Test202)

    def retranslateUi(self, Test202):
        Test202.setWindowTitle(QtWidgets.QApplication.translate("Test202", "MainWindow", None, -1))

    def btnClicked(self):
        self.ui = Ui_Dialog1(self)
        self.ui.show()

class Test20(QMainWindow, UI_Test20) :

    def __init__(self, parent):
        super(Test20, self).__init__(parent)
        self.setupUi(self)
</code>```

and the dialog code

```<code>class Ui_Dialog1(QtWidgets.QDialog):

    def __init__(self, parent=None):
        super(Ui_Dialog1, self).__init__(parent)
        self.p = parent
        self.setupUi(self)

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.update)
        self.timer.start(3000)
    def update(self):
        QMessageBox.information(self,'123','123')

    def setupUi(self, Dialog1):
        Dialog1.setObjectName("Dialog1")
        Dialog1.resize(333, 173)
</code>```

main

```<code>if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    ui = Test20(None)
    ui.show()
    sys.exit(app.exec_())
</code>```

答:
When you call show() method with QDialog your dialog will be modeless and will be hidden not deleted when it's close. To make sure your dialog deleted add one more line in your dialog init method:</p>

```<code>def __init__(self, parent=None):
    super(Ui_Dialog1, self).__init__(parent)
    self.p = parent
    self.setupUi(self)

    self.timer = QtCore.QTimer()
    self.timer.timeout.connect(self.update)
    self.timer.start(3000)
    #Make sure that your dialog will be deleted not hidden
    self.setAttribute(QtGui.Qt.WA_DeleteOnClose)
</code>```

Body:
I have a mainframe and clicked the pushbutton to open a new dialog ,

the dialog have a timer , let the timer to show message at 3sec interval ,

but if I click the top right close button to close the dialog , the messagebox still run ,

how to avoid it ?

Thanks!

from PySide2.QtWidgets import QApplication,QMainWindow,QTabWidget,QWidget
from PySide2.QtWidgets import QMessageBox,QFileDialog,QErrorMessage
from PySide2 import QtCore, QtGui, QtWidgets
class UI_Test20(object):
    def setupUi(self, Test202):
        Test202.setObjectName("Test202")
        Test202.resize(100,100)
        self.centralwidget = QtWidgets.QWidget(Test202)
        self.centralwidget.setObjectName("centralwidget")
        self.pb = QtWidgets.QPushButton(self.centralwidget)
        self.pb.setText('push button!')
        Test202.setCentralWidget(self.centralwidget)
        self.pb.clicked.connect(self.btnClicked)
        self.retranslateUi(Test202)
        QtCore.QMetaObject.connectSlotsByName(Test202)

    def retranslateUi(self, Test202):
        Test202.setWindowTitle(QtWidgets.QApplication.translate("Test202", "MainWindow", None, -1))

    def btnClicked(self):
        self.ui = Ui_Dialog1(self)
        self.ui.show()

class Test20(QMainWindow, UI_Test20) :

    def __init__(self, parent):
        super(Test20, self).__init__(parent)
        self.setupUi(self)

and the dialog code

class Ui_Dialog1(QtWidgets.QDialog):

    def __init__(self, parent=None):
        super(Ui_Dialog1, self).__init__(parent)
        self.p = parent
        self.setupUi(self)

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.update)
        self.timer.start(3000)
    def update(self):
        QMessageBox.information(self,'123','123')

    def setupUi(self, Dialog1):
        Dialog1.setObjectName("Dialog1")
        Dialog1.resize(333, 173)

main

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    ui = Test20(None)
    ui.show()
    sys.exit(app.exec_())

Body:
When you call show() method with QDialog your dialog will be modeless and will be hidden not deleted when it's close. To make sure your dialog deleted add one more line in your dialog init method:

def __init__(self, parent=None):
    super(Ui_Dialog1, self).__init__(parent)
    self.p = parent
    self.setupUi(self)

    self.timer = QtCore.QTimer()
    self.timer.timeout.connect(self.update)
    self.timer.start(3000)
    #Make sure that your dialog will be deleted not hidden
    self.setAttribute(QtGui.Qt.WA_DeleteOnClose)


问:
Getting 'undefined' returned when trying to sort array of objects with TimSort
Here is a code snippet that is very close to what I'm trying to implement in my project: https://repl.it/@Twinbird24/TimSort-example

```<code>var timsort = require('timsort');

const arr = [
  {
    name: 'Amy',
    age: 23
  },
  {
    name: 'Bob',
    age: 34
  },
  {
    name: 'Cary',
    age: 18
  }
];

function sort(objectsArr, sortBy, sortOrder = 'ascending') {
  function stringCompare(a, b) {
    return a.sortBy - b.sortBy;
  }
  return timsort.sort(objectsArr, stringCompare);
}

const sortedArr = sort(arr, 'name');

console.log(sortedArr);
</code>```

Here is the package I'm using: https://www.npmjs.com/package/timsort

I'm trying to sort my array of objects by each object's name property, which holds a string—although my function can also be passed another item to sort by (i.e. 'age').

The documentation for TimSort is not very clear and looking through the source code I'm still not quite able to figure out how to configure my code.

You'll notice in my code that I would also like to choose to sort by 'ascending' or 'descending' but I'm not sure how to add that into the TimSort method I'm using.

答:
Your string compare doesn't compare strings.  It will only work for types like numbers or those that have a valueOf, like Date.

Perhaps if you changed it to a  b ? 1 : 0, it would work a little better.  So how about this?:

```<code>function sort(objectsArr, sortBy, sortOrder = 'ascending') {
  function stringCompare(a, b) {
    const left = a[sortBy], right = b[sortBy];
    return left < right ? -1 : left > right ? 1 : 0;
  }
  return timsort.sort(objectsArr, stringCompare);
}
</code>```

This still doesn't answer you ascending/descending question.  It should be straightforward from here, but please ask another question if you can't get it.

Body:
Here is a code snippet that is very close to what I'm trying to implement in my project: https://repl.it/@Twinbird24/TimSort-example

var timsort = require('timsort');

const arr = [
  {
    name: 'Amy',
    age: 23
  },
  {
    name: 'Bob',
    age: 34
  },
  {
    name: 'Cary',
    age: 18
  }
];

function sort(objectsArr, sortBy, sortOrder = 'ascending') {
  function stringCompare(a, b) {
    return a.sortBy - b.sortBy;
  }
  return timsort.sort(objectsArr, stringCompare);
}

const sortedArr = sort(arr, 'name');

console.log(sortedArr);

Here is the package I'm using: https://www.npmjs.com/package/timsort

I'm trying to sort my array of objects by each object's name property, which holds a string—although my function can also be passed another item to sort by (i.e. 'age').

The documentation for TimSort is not very clear and looking through the source code I'm still not quite able to figure out how to configure my code.

You'll notice in my code that I would also like to choose to sort by 'ascending' or 'descending' but I'm not sure how to add that into the TimSort method I'm using.

Body:
Your string compare doesn't compare strings.  It will only work for types like numbers or those that have a valueOf, like Date.

Perhaps if you changed it to a < b ? -1 : a > b ? 1 : 0, it would work a little better.  So how about this?:

function sort(objectsArr, sortBy, sortOrder = 'ascending') {
  function stringCompare(a, b) {
    const left = a[sortBy], right = b[sortBy];
    return left < right ? -1 : left > right ? 1 : 0;
  }
  return timsort.sort(objectsArr, stringCompare);
}

This still doesn't answer you ascending/descending question.  It should be straightforward from here, but please ask another question if you can't get it.


问:
Turning off the D garbage collector
I'm a C++ programmer thats considering using D for a personal project I want to play around with.  I was wondering if there's a way to completely disable the garbage collector, and what the risks are of doing so.

I know I can manage my own memory by overriding new and delete to use malloc and free, but if I did that I'd rather the garbage collector not run at all.

答: The GC can be removed and replaced with a simple wrapper around malloc/free. </p>

OwnerDisplayName: BigSandwich

ContentLicense: CC BY-SA 2.5

Title: Turning off the D garbage collector

OwnerDisplayName: BCS


问:
Grab view from touch event
i have a quick question,

I have a view with multiple subviews.

In my view i have touches began etc..

is there a way to retrieve a subview from the touches began without having to detect the location from the touch and then have a big if else to c which subview is in that specific area.

Thanks.

答: My solution is instead of calculating the touch position from the super view. Sub class the child view and get the touch position form there only and convert the point with respect to the super view.</p>

Title: Grab view from touch event


问:
Behavior of class variables
```<code>>>> class a:
...     b=5
...     def __init__(self,x,y):
...             self.x=x
...             self.y=y
...
>>> p=a(5,6)
>>> q=a(5,6)
>>> a.b
5
>>> a.b+=1
>>> p.b
6
>>> q.b
6
>>> q.b-=1
>>> q.b
5
>>> p.b
6
>>> a.b
6
</code>```

As you see, on changing the class variable by an instance's method, the same doesn't gets reflected in the class variable and the class variable of other instance. Why is it so?

答:
Because q.b -= 1 creates an instance variable with the name b, look in your __dict__:

```<code>q.__dict__
{'b': 4, 'x': 5, 'y': 6}

p.__dict__
{'x': 5, 'y': 6}
</code>```

q.b is different than a.b, you've shadowed a.b after the assignment. Take note that this isn't a Python 3 specific issue, Python 2 also behaves in the same way.

This is clearly stated in the assignment statement section of the Language Reference:

Note: If the object is a class instance and the attribute reference occurs on both sides of the assignment operator, the RHS expression, a.x can access either an instance attribute or (if no instance attribute exists) a class attribute. The LHS target a.x is always set as an instance attribute, creating it if necessary. Thus, the two occurrences of a.x do not necessarily refer to the same attribute: if the RHS expression refers to a class attribute, the LHS creates a new instance attribute as the target of the assignment:

```<code>class Cls:
    x = 3             # class variable
inst = Cls()
inst.x = inst.x + 1   # writes inst.x as 4 leaving Cls.x as 3
</code>```

This description does not necessarily apply to descriptor attributes, such as properties created with property().

Title: Behavior of class variables

Body:
>>> class a:
...     b=5
...     def __init__(self,x,y):
...             self.x=x
...             self.y=y
...
>>> p=a(5,6)
>>> q=a(5,6)
>>> a.b
5
>>> a.b+=1
>>> p.b
6
>>> q.b
6
>>> q.b-=1
>>> q.b
5
>>> p.b
6
>>> a.b
6

As you see, on changing the class variable by an instance's method, the same doesn't gets reflected in the class variable and the class variable of other instance. Why is it so?

Body:
Because q.b -= 1 creates an instance variable with the name b, look in your __dict__:

q.__dict__
{'b': 4, 'x': 5, 'y': 6}

p.__dict__
{'x': 5, 'y': 6}

q.b is different than a.b, you've shadowed a.b after the assignment. Take note that this isn't a Python 3 specific issue, Python 2 also behaves in the same way.

This is clearly stated in the assignment statement section of the Language Reference:

Note: If the object is a class instance and the attribute reference occurs on both sides of the assignment operator, the RHS expression, a.x can access either an instance attribute or (if no instance attribute exists) a class attribute. The LHS target a.x is always set as an instance attribute, creating it if necessary. Thus, the two occurrences of a.x do not necessarily refer to the same attribute: if the RHS expression refers to a class attribute, the LHS creates a new instance attribute as the target of the assignment:

class Cls:
    x = 3             # class variable
inst = Cls()
inst.x = inst.x + 1   # writes inst.x as 4 leaving Cls.x as 3

This description does not necessarily apply to descriptor attributes, such as properties created with property().


问:
How can I redirect the "bin" and "obj" directories to a different location?
Is there a way to tell Visual Studio to use a different location for the bin and obj directories?

For example, if my project is in C:\my\myprojects.csproj, how can I have the obj and bin directories in, say, D:\otherdirectory\bin and D:\otherdirectory\obj. The Visual Studio project option offer only to redirect the bin directory, not the obj directory.

Also, bonus question: Can I use environment variables, not full or relative paths?

Is this possible?

答:
Refer to this article and use the nodes BaseOutputPath (for the bin folder) and BaseIntermediateOutputPath (for the obj folder) in the .proj file.

Given below is a way to modify your debug and release folders relative to bin -

In Solution Explorer, select the C# project you want to configure
build parameters on.

Next, from the Visual Studio menu bar, select Project → Properties. The Property Pages dialog will appear for your project.

Choose the Configuration (Release/Debug) you want to change and expand the Configuration Properties node in the left hand pane. Select the Studio is placed in the "Output path" attribute of the Outputs
property sheet.

Be aware that the output path is specified separately for each kind of
build configuration, and that setting it on one configuration doesn't
set it on all the remaining ones.

Original source - http://www.eggheadcafe.com/software/aspnet/32040244/how-to-change-the-obj-folder.aspx


问:
Printing select results from an array with a while loop
So I have this assignment where we build upon a website we created little by little each week. This week I have to write some javascript code that's function is to display a requested number of results from within an array. The number requested is entered in a form text input. The instructions are as follows:

a. Create an input that acts as a fill in the blank for a sentence that prompts the user to
enter the number of job duties they want to see.

b. Create a button that calls a function when clicked (the function created in the next step)

c. Crate a function that takes the user input and assigns the value to a variable.

d. Create an array with at least five job duties in it.

e. Create a new variable and set it equal to the inputted value minus 1

f. Create a while loop that runs while the variable (that represents the index value that we want to print) is greater than or equal to the minimum array value.

g. Within the while loop have two things happen: Have the innerHTML of some element within your page be replaced with the array value that corresponds to the index number that we want printed. You specify the array value by the format arrayname[indexnumber]. Also Have the index subtract one from itself to count down

At this point your function should run, but it does not work properly. Only the array value at the last index is printed. To fix this, we need to concatenate the results of the loop.

i. Create a new variable outside of the loop and set it to be equal to blank

You do this by setting it equal to “”

ii. Within the loop, make this variable to be equal to itself plus the array value that we want printed.

iii. Now change the innerHTML to be equal to this variable.

I have this so far yet its not working:

function showDuties() {
  var numDuties = document.getElementById('pfJobs').value;

  var pfDuties = ["Auditing", "Close out registers", "Clean free weights",
    "Sign up new members", "File paperwork"
  ]

  var i = numDuties - 1

  while (i >= 0) {
    document.getElementById('pfj').innerHTML = pfDuties[0, 1, 2, 3, 4];
    i--;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <input type="submit" value="Click here"    onclick="showDuties()">
    to see my top
 <input type="text" id="pfJobs" />
   job duties here.
 <p id = "pfj">
 </p>
</form></code>```

What this ends up doing is replacing the text in the paragraph tag in my HTML with an element from within the array, but it only flashes on the screen for half a second then disappears.

I apologize if my formatting is incorrect this is my first time using this site.
Any help would be greatly appreciated.

答:
Here's one way of doing it but depending on what you're trying to do other approaches may be better.  The key is to remember the DOM is dynamic and you can add and subtract nodes from it.

function showDuties() {
  document.getElementById('pj').innerHTML='';
  var numDuties = document.getElementById('pfJobs').value;

  var pfDuties = ["Auditing", "Close out registers", "Clean free weights",
    "Sign up new members", "File paperwork"]

    // Create the list element:
    var list = document.createElement('ul');

    for(var i = 0; i < numDuties; i++) {
        // Create the list item:
        var item = document.createElement('li');

        // Set its contents:
        item.appendChild(document.createTextNode(pfDuties[i]));

        // Add it to the list:
        list.appendChild(item);
    }

    // Finally, return the constructed list:

// Add the contents
document.getElementById('pj').appendChild(list);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Add HTML Here -->
<div id='pj'></div>
<input id='pfJobs' onchange='showDuties()' /></code>```

Body:
So I have this assignment where we build upon a website we created little by little each week. This week I have to write some javascript code that's function is to display a requested number of results from within an array. The number requested is entered in a form text input. The instructions are as follows:

a. Create an input that acts as a fill in the blank for a sentence that prompts the user to
enter the number of job duties they want to see.

b. Create a button that calls a function when clicked (the function created in the next step)

c. Crate a function that takes the user input and assigns the value to a variable.

d. Create an array with at least five job duties in it.

e. Create a new variable and set it equal to the inputted value minus 1

f. Create a while loop that runs while the variable (that represents the index value that we want to print) is greater than or equal to the minimum array value.

g. Within the while loop have two things happen: Have the innerHTML of some element within your page be replaced with the array value that corresponds to the index number that we want printed. You specify the array value by the format arrayname[indexnumber]. Also Have the index subtract one from itself to count down

At this point your function should run, but it does not work properly. Only the array value at the last index is printed. To fix this, we need to concatenate the results of the loop.

i. Create a new variable outside of the loop and set it to be equal to blank

You do this by setting it equal to “”

ii. Within the loop, make this variable to be equal to itself plus the array value that we want printed.

iii. Now change the innerHTML to be equal to this variable.

I have this so far yet its not working:

function showDuties() {
  var numDuties = document.getElementById('pfJobs').value;

  var pfDuties = ["Auditing", "Close out registers", "Clean free weights",
    "Sign up new members", "File paperwork"
  ]

  var i = numDuties - 1

  while (i >= 0) {
    document.getElementById('pfj').innerHTML = pfDuties[0, 1, 2, 3, 4];
    i--;
  }

<form>
  <input type="submit" value="Click here"    onclick="showDuties()">
    to see my top
 <input type="text" id="pfJobs" />
   job duties here.

</form>

What this ends up doing is replacing the text in the paragraph tag in my HTML with an element from within the array, but it only flashes on the screen for half a second then disappears.

I apologize if my formatting is incorrect this is my first time using this site.
Any help would be greatly appreciated.

Body:
Here's one way of doing it but depending on what you're trying to do other approaches may be better.  The key is to remember the DOM is dynamic and you can add and subtract nodes from it.

function showDuties() {
  document.getElementById('pj').innerHTML='';
  var numDuties = document.getElementById('pfJobs').value;

  var pfDuties = ["Auditing", "Close out registers", "Clean free weights",
    "Sign up new members", "File paperwork"]

    // Create the list element:
    var list = document.createElement('ul');

    for(var i = 0; i < numDuties; i++) {
        // Create the list item:
        var item = document.createElement('li');

        // Set its contents:
        item.appendChild(document.createTextNode(pfDuties[i]));

        // Add it to the list:
        list.appendChild(item);
    }

    // Finally, return the constructed list:

// Add the contents
document.getElementById('pj').appendChild(list);
}

<!-- Add HTML Here -->
<div id='pj'></div>
<input id='pfJobs' onchange='showDuties()' />


问:
Unable to Hide Page Action Button in Firefox 57
I was wanting to remove the Page Action button in Firefox's url bar, so I added the following line to my userChrome.css file:

```<code>#urlbar-page-action-button {display:none !important;}
</code>```

However, nothing happened. How can I accomplish what I'm attempting?

I'm using Firefox Nightly version 57.0a1 on a Macbook.

答:
I had some trouble with your solution.  It seems # is the selector for id, not class... etc.

You can modify the userChrome.css file in <userprofile>/chrome/userChome.css.  Verify your profile directory locations with about:profiles.

Here's the content of my newly formed userChrome.css file:

```<code>/* Do not remove the @namespace line -- it's required for correct functioning */
@namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");

/* -- Test to see if this file is loaded correctly -- */
/* * {background-color:red !important;} /* *emphasis* important, '!' isn't NOT in CSS */

/*
 * HTML element to hide:
 * <image xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
 * id="pageActionButton" class="urlbar-icon urlbar-page-action" role="button"
 * tooltiptext="Page actions" onmousedown="BrowserPageActions.mainButtonClicked(event);"
 * />
 *
 * element: image
 * id: pageActionButton
 * class: urlbar-icon urlbar-page-action
 */

image#pageActionButton {display:none !important;}
image.urlbar-page-action {display:none !important;}
                   /* who knows, maybe we get lucky and they change only one. */
</code>```

Once done, you should have gotten rid of the new Firefox 57.0 hamburger ellipsis button built into the address bar with no "Remove from Address Bar" option that all the other buttons (pocket, favorite) have.

Body:
I was wanting to remove the Page Action button in Firefox's url bar, so I added the following line to my userChrome.css file:

#urlbar-page-action-button {display:none !important;}

However, nothing happened. How can I accomplish what I'm attempting?

I'm using Firefox Nightly version 57.0a1 on a Macbook.

Body:
I had some trouble with your solution.  It seems # is the selector for id, not class... etc.

You can modify the userChrome.css file in <userprofile>/chrome/userChome.css.  Verify your profile directory locations with about:profiles.

Here's the content of my newly formed userChrome.css file:

/* Do not remove the @namespace line -- it's required for correct functioning */
@namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");

/* -- Test to see if this file is loaded correctly -- */
/* * {background-color:red !important;} /* *emphasis* important, '!' isn't NOT in CSS */

/*
 * HTML element to hide:
 * <image xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
 * id="pageActionButton" class="urlbar-icon urlbar-page-action" role="button"
 * tooltiptext="Page actions" onmousedown="BrowserPageActions.mainButtonClicked(event);"
 * />
 *
 * element: image
 * id: pageActionButton
 * class: urlbar-icon urlbar-page-action
 */

image#pageActionButton {display:none !important;}
image.urlbar-page-action {display:none !important;}
                   /* who knows, maybe we get lucky and they change only one. */

Once done, you should have gotten rid of the new Firefox 57.0 hamburger ellipsis button built into the address bar with no "Remove from Address Bar" option that all the other buttons (pocket, favorite) have.


答:
You can add a click handler that imitates a form submit without the added hassle. Then capture your value from the input with document.getElementById

Then use slice or ES6 spread on the array as those 2 methods don't mutate the original array.

I also added a check that your index will never be more than the length of your array.

document.getElementById('submit').addEventListener('click', myFunction);

function myFunction() {
let pfDuties = ["Auditing", "Close out registers", "Clean free weights",
  "Sign up new members", "File paperwork"
  ];
  let index = document.getElementById('input').value;
  if (index > pfDuties.length) {
    document.getElementById('pfj').innerText = 'Value is greater than the number of duties';
    return;
  }
  // slice
  let result = pfDuties.slice(0, index).concat(pfDuties.slice(index + 1));
  // spread
  let result2 = [...pfDuties.slice(0, index), ...pfDuties.slice(index + 1)];
  // you can return either array here just did both to show example
  document.getElementById('pfj').innerHTML = result.join('
');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Value<br>
<input type="text" id="input">
<br><br>
<button id="submit">Submit</button>
<p id="pfj"></p></code>```

Title: Printing select results from an array with a while loop

Body:
You can add a click handler that imitates a form submit without the added hassle. Then capture your value from the input with document.getElementById

Then use slice or ES6 spread on the array as those 2 methods don't mutate the original array.

I also added a check that your index will never be more than the length of your array.

document.getElementById('submit').addEventListener('click', myFunction);

function myFunction() {
let pfDuties = ["Auditing", "Close out registers", "Clean free weights",
  "Sign up new members", "File paperwork"
  ];
  let index = document.getElementById('input').value;
  if (index > pfDuties.length) {
    document.getElementById('pfj').innerText = 'Value is greater than the number of duties';
    return;
  }
  // slice
  let result = pfDuties.slice(0, index).concat(pfDuties.slice(index + 1));
  // spread
  let result2 = [...pfDuties.slice(0, index), ...pfDuties.slice(index + 1)];
  // you can return either array here just did both to show example
  document.getElementById('pfj').innerHTML = result.join('<br>');
}

Value<br>
<input type="text" id="input">
<br><br>
<button id="submit">Submit</button>
<p id="pfj"></p>