问:
R: How to filter column as long as it contains combination of values?
I have a df like this:

```<code>VisitID | Item |
1       | A    |
1       | B    |
1       | C    |
1       | D    |
2       | A    |
2       | D    |
2       | B    |
3       | B    |
3       | C    |
4       | D    |
4       | C    |
</code>```

In R, how do I filter for VisitIDs as long as they contain Item A & B?
Expected Outcome:

```<code>VisitID | Item |
1       | A    |
1       | B    |
1       | C    |
1       | D    |
2       | A    |
2       | D    |
2       | B    |
</code>```

I tried df %>% group_by(VisitID) %>% filter(any(Item == 'A' & Item == 'B')) but it doesn't work..

```<code>df <- read_delim("ID | Item
1  | A
1  | B
2  | A
3  | B
1  | C
4  | C
5  | B
3  | A
4  | A
5  | D", delim = "|", trim_ws = TRUE)
</code>```

答:
An otion with data.table

```<code>library(data.table)
setDT(df)[, .SD[all(c("A", "B") %in% Item)], VisitID]
</code>```

Body:
I have a df like this:

VisitID | Item |
1       | A    |
1       | B    |
1       | C    |
1       | D    |
2       | A    |
2       | D    |
2       | B    |
3       | B    |
3       | C    |
4       | D    |
4       | C    |

In R, how do I filter for VisitIDs as long as they contain Item A & B?
Expected Outcome:

VisitID | Item |
1       | A    |
1       | B    |
1       | C    |
1       | D    |
2       | A    |
2       | D    |
2       | B    |

I tried df %>% group_by(VisitID) %>% filter(any(Item == 'A' & Item == 'B')) but it doesn't work..

df <- read_delim("ID | Item
1  | A
1  | B
2  | A
3  | B
1  | C
4  | C
5  | B
3  | A
4  | A
5  | D", delim = "|", trim_ws = TRUE)

Body:
An otion with data.table

library(data.table)
setDT(df)[, .SD[all(c("A", "B") %in% Item)], VisitID]


来源: stackexchange

问:
Use of "in" in a function's arguments
I have been following the Ray Wenderlich book Advanced iOS App Architecture, and they have a protocol that looks like the following:

```<code>protocol RideOptionDeterminedResponder {
  func pickUpUser(in rideOptionID: RideOptionID)
}
</code>```

I don't understand the us of in before the rideOptionID parameter (which, by the way, is just a typealias for String), as I always thought you only used this keyword when writing closures. I've looked around a lot for uses of in but haven't had any luck.

What is the purpose of in here, and how would the function be different if it were absent?

(If you need more information on how this function works in order to explain yourself better, just let me know.)

答:
Functions in Swift support both an external and an internal name. This effectively means you can refer to the same parameter using two different names. That's what in is in the code you provided, an external parameter name.

The difference between external and internal parameters is that you use the first when calling a method, and the second when dealing with the value inside such method's body.

So, you would call the method as such:

// Call the method using the external parameter name in
pickUpUser(in: someRideOptionID)

func pickUpUser(in rideOptionID: RideOptionID) {
  // Do something with the value, accessing it using the internal parameter name rideOptionID
}
```

ContentLicense: CC BY-SA 4.0

Title: Use of "in" in a function's arguments

Body:
I have been following the Ray Wenderlich book Advanced iOS App Architecture, and they have a protocol that looks like the following:

protocol RideOptionDeterminedResponder {
  func pickUpUser(in rideOptionID: RideOptionID)
}

I don't understand the us of in before the rideOptionID parameter (which, by the way, is just a typealias for String), as I always thought you only used this keyword when writing closures. I've looked around a lot for uses of in but haven't had any luck.

What is the purpose of in here, and how would the function be different if it were absent?

(If you need more information on how this function works in order to explain yourself better, just let me know.)


问:
make a simple single instanse class as database helper
I'm trying to use floor library to use simple database in flutter

simple implementation of this library is:

```<code>Future<void> main() async {
  final database = await $FloorFlutterDatabase
      .databaseBuilder('flutter_database.db')
      .build();
  final dao = database.taskDao;

  runApp(FloorApp(dao));
}
</code>```

in my implementation code, i can't access to taskDao from database. for example:

```<code>var dao = db.taskDao
</code>```

my DatabaseHelper class:

```<code>class DatabaseHelper{
  static final _databaseName = "flutter_database.db";

  DatabaseHelper._privateConstructor();
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();

  static $FloorAppDatabase _database;
  static var dao;
  Future<$FloorAppDatabase> get database async{
    if(_database !=null){
      return _database;
    }
    _database = await _initDatabase();
    return _database;
  }

  _initDatabase() async{
    return await $FloorAppDatabase
        .databaseBuilder(_databaseName)
        .build();
  }
}
</code>```

main class to use that:

```<code>void main() async {
  $FloorAppDatabase db = await DatabaseHelper.instance.database;
  //var dao = db.
}
</code>```

答:
Using the get_it library I set up the lazy singletons async this way:

```<code>GetIt serviceLocator = GetIt.instance;

void init() {
  serviceLocator.registerLazySingletonAsync<AppDatabase>(() async =>
      await $FloorAppDatabase.databaseBuilder('app_database.db').build());
  serviceLocator.registerLazySingletonAsync<ExampleDao>(
      () async => (await serviceLocator.getAsync<AppDatabase>()).exampleDao);
}
</code>```

then call service_locator.init() from the main function.

Body:
I'm trying to use floor library to use simple database in flutter

simple implementation of this library is:

Future<void> main() async {
  final database = await $FloorFlutterDatabase
      .databaseBuilder('flutter_database.db')
      .build();
  final dao = database.taskDao;

  runApp(FloorApp(dao));
}

in my implementation code, i can't access to taskDao from database. for example:

var dao = db.taskDao

my DatabaseHelper class:

class DatabaseHelper{
  static final _databaseName = "flutter_database.db";

  DatabaseHelper._privateConstructor();
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();

  static $FloorAppDatabase _database;
  static var dao;
  Future<$FloorAppDatabase> get database async{
    if(_database !=null){
      return _database;
    }
    _database = await _initDatabase();
    return _database;
  }

  _initDatabase() async{
    return await $FloorAppDatabase
        .databaseBuilder(_databaseName)
        .build();
  }
}

main class to use that:

void main() async {
  $FloorAppDatabase db = await DatabaseHelper.instance.database;
  //var dao = db.
}

Body:
Using the get_it library I set up the lazy singletons async this way:

GetIt serviceLocator = GetIt.instance;

void init() {
  serviceLocator.registerLazySingletonAsync<AppDatabase>(() async =>
      await $FloorAppDatabase.databaseBuilder('app_database.db').build());
  serviceLocator.registerLazySingletonAsync<ExampleDao>(
      () async => (await serviceLocator.getAsync<AppDatabase>()).exampleDao);
}

then call service_locator.init() from the main function.


问:
How to implement RouteReuseStrategy shouldDetach for specific routes in Angular 2
I have an Angular 2 module in which I have implemented routing and would like the states stored when navigating.

The user should be able to:

search for documents using a 'search formula'

navigate to one of the results

navigate back to 'searchresult' - without communicating with the server

This is possible including RouteReuseStrategy.

The question is:

How do I implement that the document should not be stored?

So the route path "documents"'s state should be stored and the route path "documents/:id"' state should NOT be stored?

答:
I faced with these issues implementing a custom route reuse strategy:

Perform operations on a route attach/dettach: manage subscriptions, cleanup, etc.;

Preserve only the last parameterised route's state: memory optimisation;

Reuse a component, not a state: manage the state with a state-managment tools.

"Cannot reattach ActivatedRouteSnapshot created from a different route" error;

So I wrote a library solving these issues. The library provides a service and decorators for attach/detach hooks and uses a route's components to store detached routes, not a route's paths.

Example:

```<code>/* Usage with decorators */
@onAttach()
public onAttach(): void {
  // your code...
}

@onDetach()
public onDetach(): void {
  // your code...
}

/* Usage with a service */
public ngOnInit(): void {
  this.cacheRouteReuse
    .onAttach(HomeComponent) // or any route's component
    .subscribe(component => {
      // your code...
    });

  this.cacheRouteReuse
    .onDetach(HomeComponent) // or any route's component
    .subscribe(component => {
      // your code...
    });
}
</code>```

The library: https://www.npmjs.com/package/ng-cache-route-reuse

Body:
I faced with these issues implementing a custom route reuse strategy:

Perform operations on a route attach/dettach: manage subscriptions, cleanup, etc.;

Preserve only the last parameterised route's state: memory optimisation;

Reuse a component, not a state: manage the state with a state-managment tools.

"Cannot reattach ActivatedRouteSnapshot created from a different route" error;

So I wrote a library solving these issues. The library provides a service and decorators for attach/detach hooks and uses a route's components to store detached routes, not a route's paths.

Example:

/* Usage with decorators */
@onAttach()
public onAttach(): void {
  // your code...
}

@onDetach()
public onDetach(): void {
  // your code...
}

/* Usage with a service */
public ngOnInit(): void {
  this.cacheRouteReuse
    .onAttach(HomeComponent) // or any route's component
    .subscribe(component => {
      // your code...
    });

  this.cacheRouteReuse
    .onDetach(HomeComponent) // or any route's component
    .subscribe(component => {
      // your code...
    });
}

The library: https://www.npmjs.com/package/ng-cache-route-reuse


问:
Javascript and google maps api version 3 changing the MapeTypeId via user input
I have been experimenting with google maps API ver 3. I'm having problems dynamically altering google MapTypeid so that a user can change the map type via a select box. I want code that's not bloated and passes the value of a select box to google maps and a change of map style is reflected in the HTML DIV showing that map.

For testing purposes, I constructed 4 if statements that tested for selected index value of HTML select box and then display a map based upon that selection. If i continue like this with other select boxes that change map views on other maps, my code is going to get very long, bloated and spaghetti-like.

```<code>// here is what i have done so far/

JAVASCRIPT

 // display current flight info
document.getElementById("currentplot").innerHTML='Chase Vehicle at '+'<p>'+ lattitude.toFixed(6)+' : '+ longitude.toFixed(6)+' </p>';
document.getElementById("copilot").innerHTML=' Camera Zoom : '+ userzoom;
document.getElementById("cockpitstatus").innerHTML='Altitude : '+'<p>'+ altitude +' miles'+' </p>';

        // this was debugging printout code using document.write but  now it works
        // i have kept it and used it in little flight info divs etc
};

function changemapview(){
 var newmap=document.maptype.mapstyle.options[document.maptype.mapstyle.selectedIndex].value;
 // newmap does contain ROADMAP TERRAIN ETC it's tested and been writtten out to the screen
 // now lets get newmap into google
//BUG TO FIX need to find a way of getting newmap into MapTypeId.TERRAIN ETC
// SO WE CAN REMOVE THE IF STATEMENTS AND REPLACE WITH ONE LINE OF CODE OR MUCH SHORTER CODE

if(userzoom<=0){userzoom=1}
if(userzoom>=20){userzoom=20}

 var latlng = new google.maps.LatLng(lattitude, longitude);// THESE ARE MY GLOBAL LATS AND LONG

if(document.maptype.mapstyle.selectedIndex==0){

    var myOptions = {
      zoom: userzoom,
     center: latlng,
   mapTypeId: google.maps.MapTypeId.ROADMAP,

    };
    }

if(document.maptype.mapstyle.selectedIndex==1){

    var myOptions = {
      zoom: userzoom,
      center: latlng,
     mapTypeId: google.maps.MapTypeId.TERRAIN,

    };
    }

    if(document.maptype.mapstyle.selectedIndex==2){

    var myOptions = {
      zoom: userzoom,
      center: latlng,
     mapTypeId: google.maps.MapTypeId.SATELLITE,

    };
    }

    if(document.maptype.mapstyle.selectedIndex==3){

    var myOptions = {
      zoom: userzoom,
      center: latlng,
   mapTypeId: google.maps.MapTypeId.HYBRID,

    };
    }
    // TRY TO FIND A WAY OF DOING THIS WITHOUT IF STATEMENTS

     var map = new google.maps.Map(document.getElementById("copilotsmap"),
        myOptions);

        var marker = new google.maps.Marker({
      position: latlng,
      title:"copilot this is your last synchronised flight positon"});

       marker.setMap(map);
        // end of google sample code
        // this function changes the copilots map style

}

<!-- above are functions  to dispaly a google maps from google sample code but we are-->
<!-- using variables and click behaviour NOT Magic numbers to display markers etc on flight path-->
function checkbutton(){
// it will be checked anyway if it has come here
if(document.mapchange.updatemap.checked)
{ document.mapchange.updatemap.checked=false;
changemapview();
}
}
</code>```

HTML

```<code><!-- in the middle is a flight panel -->
<div id="flightpanel"> <p> Flight Panel </p>   </div>
<!-- a div to put cockpit readouts etc into-->
<div id="cockpitview"> <p> Cockpit View </p>

 </div>
<!-- an empty div for displaying the output of our map data at current zoom and lattitude / longitude -->
<div id="currentzoom" >

</div>

<!-- a div in the middle for engine controls-->
<div id="enginepanel">  <p> Engine Panel </p></div>

<!-- another empty div for the co pilots map-->
<div id="copilotsmap"> </div>

<!-- dashboard is on coplilots side -->
<div id="dashboard">

  <form id="maptype" name="maptype">
        <label>Change Map Style
            <select name="mapstyle" id="mapstyle"  onchange="changemapview();">
                    <option>ROADMAP</option>
                    <option>TERRAIN</option>
                    <option>SATELLITE</option>
                    <option>HYBRID</option>
            </select>
            </label> Co-Pilots Dashboard
 </form>
<!-- below here are more select boxes etc that all work unrelated to the question
</div>
</code>```

how do i get ride of all the if statements i want to do something like this if possible

```<code>    var myOptions = {
      zoom: userzoom,
     center: latlng,
  // mapTypeId: google.maps.MapTypeId.ROADMAP,

    };
</code>```

instead of saying

```<code> mapTypeId: google.maps.MapTypeId.ROADMAP,
</code>```

i want to say

```<code>mapTypeId: google.maps.MapTypeId.(whatever is in a variable or function)
</code>```

i have tried this kind of approach with no luck

```<code>myOptions.mapTypeId:='google.maps.MapTypeId'+newmap,'

// and various similar combinations
</code>```

答:
```<code>var myMapTypes = new Array('ROADMAP','TERRAIN','SATELLITE','HYBRID');
var newMap = myMapTypes[parseInt(document.maptype.mapstyle.selectedIndex)];
var myOptions = {
    zoom: userzoom,
    center: latlng,
    mapTypeId: google.maps.MapTypeId[newMap]
};
</code>```

Range checking on the array index and so forth left out for brevity/clarity/laziness/etc. Probably a good idea to at least make sure parseInt() returns a value greater than or equal to zero and less than myMapTypes.length.

ContentLicense: CC BY-SA 3.0

Body:
I have been experimenting with google maps API ver 3. I'm having problems dynamically altering google MapTypeid so that a user can change the map type via a select box. I want code that's not bloated and passes the value of a select box to google maps and a change of map style is reflected in the HTML DIV showing that map.

For testing purposes, I constructed 4 if statements that tested for selected index value of HTML select box and then display a map based upon that selection. If i continue like this with other select boxes that change map views on other maps, my code is going to get very long, bloated and spaghetti-like.

// here is what i have done so far/

JAVASCRIPT

 // display current flight info
document.getElementById("currentplot").innerHTML='Chase Vehicle at '+'
'+ lattitude.toFixed(6)+' : '+ longitude.toFixed(6)+'
';
document.getElementById("copilot").innerHTML=' Camera Zoom : '+ userzoom;
document.getElementById("cockpitstatus").innerHTML='Altitude : '+'
'+ altitude +' miles'+'
';

        // this was debugging printout code using document.write but  now it works
        // i have kept it and used it in little flight info divs etc
};

function changemapview(){
 var newmap=document.maptype.mapstyle.options[document.maptype.mapstyle.selectedIndex].value;
 // newmap does contain ROADMAP TERRAIN ETC it's tested and been writtten out to the screen
 // now lets get newmap into google
//BUG TO FIX need to find a way of getting newmap into MapTypeId.TERRAIN ETC
// SO WE CAN REMOVE THE IF STATEMENTS AND REPLACE WITH ONE LINE OF CODE OR MUCH SHORTER CODE

if(userzoom<=0){userzoom=1}
if(userzoom>=20){userzoom=20}

 var latlng = new google.maps.LatLng(lattitude, longitude);// THESE ARE MY GLOBAL LATS AND LONG

if(document.maptype.mapstyle.selectedIndex==0){

    var myOptions = {
      zoom: userzoom,
     center: latlng,
   mapTypeId: google.maps.MapTypeId.ROADMAP,

    };
    }

if(document.maptype.mapstyle.selectedIndex==1){

    var myOptions = {
      zoom: userzoom,
      center: latlng,
     mapTypeId: google.maps.MapTypeId.TERRAIN,

    };
    }

    if(document.maptype.mapstyle.selectedIndex==2){

    var myOptions = {
      zoom: userzoom,
      center: latlng,
     mapTypeId: google.maps.MapTypeId.SATELLITE,

    };
    }

    if(document.maptype.mapstyle.selectedIndex==3){

    var myOptions = {
      zoom: userzoom,
      center: latlng,
   mapTypeId: google.maps.MapTypeId.HYBRID,

    };
    }
    // TRY TO FIND A WAY OF DOING THIS WITHOUT IF STATEMENTS

     var map = new google.maps.Map(document.getElementById("copilotsmap"),
        myOptions);

        var marker = new google.maps.Marker({
      position: latlng,
      title:"copilot this is your last synchronised flight positon"});

       marker.setMap(map);
        // end of google sample code
        // this function changes the copilots map style

}

function checkbutton(){
// it will be checked anyway if it has come here
if(document.mapchange.updatemap.checked)
{ document.mapchange.updatemap.checked=false;
changemapview();
}
}

HTML

 Flight Panel

 Cockpit View

 Engine Panel

  <form id="maptype" name="maptype">
        Change Map Style
            <select name="mapstyle" id="mapstyle"  onchange="changemapview();">
                    <option>ROADMAP</option>
                    <option>TERRAIN</option>
                    <option>SATELLITE</option>
                    <option>HYBRID</option>
            </select>
             Co-Pilots Dashboard
 </form>

Body:
var myMapTypes = new Array('ROADMAP','TERRAIN','SATELLITE','HYBRID');
var newMap = myMapTypes[parseInt(document.maptype.mapstyle.selectedIndex)];
var myOptions = {
    zoom: userzoom,
    center: latlng,
    mapTypeId: google.maps.MapTypeId[newMap]
};

Range checking on the array index and so forth left out for brevity/clarity/laziness/etc. Probably a good idea to at least make sure parseInt() returns a value greater than or equal to zero and less than myMapTypes.length.


问:
Accessing Jenkins-home-directory path in a shell script
I want to run a script as Jenkins job. The first step of the script is to access Jenkins home-directory path? Is it possible to access this in a script?
Also if I am not running this script from Jenkins but some remote server how can I access the path</p>

答:
It's the same as other users:

```<code>cd ~jenkins
</code>```

For imformation, most of the times (by default) /var/lib/jenkins

Body:
It's the same as other users:

cd ~jenkins

For imformation, most of the times (by default) /var/lib/jenkins


问:
Ajax call not executing as expected
I have an ajax call that is not executing how I would expect. I am receiving an error from the browser of "jquery-1.10.2.js:8157 Uncaught TypeError: Cannot read property 'FileGuid' of undefined". I have break points in my CS file at the start of both the GetExportData and Download functions but neither one of them are ever hit. </p>

```<code>function generateExportFile() {
        var datefrom = $('#tab_MHSubpay_datefrom').ejDatePicker("getValue");
        var dateto = $('#tab_MHSubpay_dateto').ejDatePicker("getValue");
        var show = $('#tab_MHSubpay_show').ejDropDownList("getSelectedValue");
        var service = $('#tab_MHSubpay_serviceType').ejDropDownList("getSelectedValue");
        var phase = $('#tab_MHSubpay_phaseCode').ejDropDownList("getSelectedValue");

        $('#accwpopup').ejWaitingPopup({
            showOnInit: true,
            text: "Generating file...",
            target: "#tbldata"
        });

        debugger;
        $.ajax({
            cache: false,
            url: '@Url.Action("GetExportData", "MHSubpay")',
            data: {
                datefrom: datefrom,
                dateto: dateto,
                show: show,
                service: service,
                phase: phase
            },
            success: function (data) {
                $('#accwpopup').ejWaitingPopup('destroy');
                window.location = '@Url.Action("Download", "MHSubpay")?fileGuid=' + data.Data.FileGuid + '&filename=' + data.Data.FileName;
            },
            error: function (data) {
                $('#accwpopup').ejWaitingPopup('destroy');
                showMessage("An error ocurred trying to generate the file", false);
            },
            async: false
        });
    }
</code>```

答: It turns out this was a really dumb mistake that I just kept glossing over. I never updated the server side code, which I recycled from another controller, to be an HttpGet function rather than an HttpPost. Once I switched that the call went through properly. </p>

Title: Ajax call not executing as expected

Body:
I have an ajax call that is not executing how I would expect. I am receiving an error from the browser of "jquery-1.10.2.js:8157 Uncaught TypeError: Cannot read property 'FileGuid' of undefined". I have break points in my CS file at the start of both the GetExportData and Download functions but neither one of them are ever hit.

function generateExportFile() {
        var datefrom = $('#tab_MHSubpay_datefrom').ejDatePicker("getValue");
        var dateto = $('#tab_MHSubpay_dateto').ejDatePicker("getValue");
        var show = $('#tab_MHSubpay_show').ejDropDownList("getSelectedValue");
        var service = $('#tab_MHSubpay_serviceType').ejDropDownList("getSelectedValue");
        var phase = $('#tab_MHSubpay_phaseCode').ejDropDownList("getSelectedValue");

        $('#accwpopup').ejWaitingPopup({
            showOnInit: true,
            text: "Generating file...",
            target: "#tbldata"
        });

        debugger;
        $.ajax({
            cache: false,
            url: '@Url.Action("GetExportData", "MHSubpay")',
            data: {
                datefrom: datefrom,
                dateto: dateto,
                show: show,
                service: service,
                phase: phase
            },
            success: function (data) {
                $('#accwpopup').ejWaitingPopup('destroy');
                window.location = '@Url.Action("Download", "MHSubpay")?fileGuid=' + data.Data.FileGuid + '&filename=' + data.Data.FileName;
            },
            error: function (data) {
                $('#accwpopup').ejWaitingPopup('destroy');
                showMessage("An error ocurred trying to generate the file", false);
            },
            async: false
        });
    }


问:
Where to initialize a reusable object in a ParDo?
An example of my ParDo in my beam job (running with Dataflow runner):

```<code>class StreamEventToJsonConverter : DoFn<MyClass, String>() {
    @ProcessElement
    fun processElement(@Element element: MyClass, receiver: OutputReceiver<String>) {
        val gson = Gson()
        val jsonValue = gson.toJson(element)
        receiver.output(jsonValue)
    }
}
</code>```

My question is: should I initialize the Gson object inside of the processElement function?

Is it only initialized once per worker or everytime a new element enters the function (seems to be overkilled)?

Given that the Gson object is not serializable.

Thank you.

答:
Turned out I can do via a DoFn.Setup function:

Annotation for the method to use to prepare an instance for processing bundles of elements.

This is a good place to initialize transient in-memory resources, such as network connections. The resources can then be disposed in DoFn.Teardown.

Body:
An example of my ParDo in my beam job (running with Dataflow runner):

class StreamEventToJsonConverter : DoFn<MyClass, String>() {
    @ProcessElement
    fun processElement(@Element element: MyClass, receiver: OutputReceiver<String>) {
        val gson = Gson()
        val jsonValue = gson.toJson(element)
        receiver.output(jsonValue)
    }
}

My question is: should I initialize the Gson object inside of the processElement function?

Is it only initialized once per worker or everytime a new element enters the function (seems to be overkilled)?

Given that the Gson object is not serializable.

Thank you.


问:
Handle multiple files in post request with Go
I am using Go to write server-side for a music streaming service. I need to be able to handle album uploads. I want admins to be able to go to http://lisn.rocks/upload, select a folder that has to contain meta.json, cover.jpg, and some .mp3 song files, click upload and the rest to be handled by server.

Here is a simple HTML page I'm using to test this functionality:

    <title>Album Upload</title>

        <form enctype="multipart/form-data" action="/upload" method="POST">
            <input type="file" name="album" webkitdirectory directory multiple>

            <input type="submit" value="Upload">
        </form>

```

I need a handler function that would be able to look at the meta.json file, check its contents and do stuff based on what's there. The meta.json contains all the info I need. Now, I don't need an extensive explanation about reading JSON with Go or other things that go along with it.

I just need to read all files from that folder as separate files. Instead, Go sees them all as a single album file field when I do request.FormFile("album").

答:
As the documentation for FormFile says, it only returns the first file. When the form is submitted, the album field will be an array and you have to use a multipart stream to process each individual file.

```<code>rd, err:=request.MultipartReader()
for {
  part, err:=rd.NextPart()
  if err==io.EOF {
      break
  }
  data,err:=ioutil.ReadAll(part)
  fileName:=part.FileName()
  part.Close()
}
</code>```

You need to add error handling and data processing, etc.

Body:
I am using Go to write server-side for a music streaming service. I need to be able to handle album uploads. I want admins to be able to go to http://lisn.rocks/upload, select a folder that has to contain meta.json, cover.jpg, and some .mp3 song files, click upload and the rest to be handled by server.

Here is a simple HTML page I'm using to test this functionality:

    <title>Album Upload</title>

        <form enctype="multipart/form-data" action="/upload" method="POST">
            <input type="file" name="album" webkitdirectory directory multiple>

            <input type="submit" value="Upload">
        </form>

I need a handler function that would be able to look at the meta.json file, check its contents and do stuff based on what's there. The meta.json contains all the info I need. Now, I don't need an extensive explanation about reading JSON with Go or other things that go along with it.

I just need to read all files from that folder as separate files. Instead, Go sees them all as a single album file field when I do request.FormFile("album").

Body:
As the documentation for FormFile says, it only returns the first file. When the form is submitted, the album field will be an array and you have to use a multipart stream to process each individual file.

rd, err:=request.MultipartReader()
for {
  part, err:=rd.NextPart()
  if err==io.EOF {
      break
  }
  data,err:=ioutil.ReadAll(part)
  fileName:=part.FileName()
  part.Close()
}

You need to add error handling and data processing, etc.


问:
Dynamic Dates SQL Server
I have the below data in SQL.

I need to figure out a way dynamically to get the next dates based the 2 values below. The remaining doses tells me how many dates I will need to find and RXDAYS tells me the increments in which to look for the dates

```<code>Date Shipped    Remaining Doses RXDAYS
2019-06-05      2               30
</code>```

So based on the above I would find the date 30 days after 2019-06-05 and get 2019-07-05 and 30 days after that I would get 2019-08-04.

Is there a way to do this?

答:
You can use DATEADD() function as

```<code>SELECT *, CONVERT(DATE, DATEADD(Day, RXDAYS, DateShipped)) FirstDateToFind,
          CONVERT(DATE, DATEADD(Day, RXDAYS * 2, DateShipped)) SecondDateToFind
FROM
(
  VALUES
  ('2019-06-05',      2,               30)
) T(DateShipped, RemainingDoses, RXDAYS);
</code>```

UPDATE:

It seems like you're looking for generating rows as the following:

```<code>WITH Data AS
(
  SELECT *
  FROM T
  UNION ALL
  SELECT CONVERT(DATE, DATEADD(Day, (RXDAYS * (RemainingDoses - RemainingDoses + 1)), DateShipped)),
         RemainingDoses - 1,
         RXDAYS
  FROM Data
  WHERE RemainingDoses > 0
)
SELECT *
FROM Data
ORDER BY DateShipped;
</code>```

Here is a db<>fiddle

Title: Dynamic Dates SQL Server

Body:
I have the below data in SQL.

I need to figure out a way dynamically to get the next dates based the 2 values below. The remaining doses tells me how many dates I will need to find and RXDAYS tells me the increments in which to look for the dates

Date Shipped    Remaining Doses RXDAYS
2019-06-05      2               30

So based on the above I would find the date 30 days after 2019-06-05 and get 2019-07-05 and 30 days after that I would get 2019-08-04.

Is there a way to do this?

Body:
You can use DATEADD() function as

SELECT *, CONVERT(DATE, DATEADD(Day, RXDAYS, DateShipped)) FirstDateToFind,
          CONVERT(DATE, DATEADD(Day, RXDAYS * 2, DateShipped)) SecondDateToFind
FROM
(
  VALUES
  ('2019-06-05',      2,               30)
) T(DateShipped, RemainingDoses, RXDAYS);

UPDATE:

It seems like you're looking for generating rows as the following:

WITH Data AS
(
  SELECT *
  FROM T
  UNION ALL
  SELECT CONVERT(DATE, DATEADD(Day, (RXDAYS * (RemainingDoses - RemainingDoses + 1)), DateShipped)),
         RemainingDoses - 1,
         RXDAYS
  FROM Data
  WHERE RemainingDoses > 0
)
SELECT *
FROM Data
ORDER BY DateShipped;

Here is a db<>fiddle


问:
WooCommerce Admin Order Page change Discount(s) label
In a recent update to WooCommerce, they have changed the word Discounts to Coupon(s). This is in the order total table. See this screenshot for > clarity https://prnt.sc/sq6xfh

I would like to change this back to Discounts wherever possible as it doesn't really make sense to say Coupons when you have actually applied a discount. Ideally, it would be great to show a Discounts and a Coupon(s) row if required as sometimes you may apply a coupon AND a discount.

For now, I am I trying to change the Discount(s) label as pointed out above in the screenshot.

I have found the code in the plugins core files and know I cannot change that, this is the code:

```<code>    </tr>
    <?php if ( 0 < $order->get_total_discount() ) : ?>
        <tr>
            <td class="label"><?php esc_html_e( 'Coupon(s):', 'woocommerce' ); ?></td>
            <td width="1%"></td>
            <td class="total">-
                <?php echo wc_price( $order->get_total_discount(), array( 'currency' => $order->get_currency() ) ); // WPCS: XSS ok. ?>
            </td>
        </tr>
    <?php endif; ?>
</code>```

I am not sure how to change Coupon(s) to Discounts in the code above via my functions.php

Any help appreciated.
Cheers
Nik

答:
You can use the WordPress gettext hook this way:

```<code>add_filter('gettext', 'custom_strings_translation', 20, 3);
function custom_strings_translation( $translated_text, $text, $domain ) {
global $pagenow, $typenow;

    // Settings
    $current_text = "Coupon(s):";
    $new_text     = "Discount(s):";

    // Targeting admin single order pages
    if( is_admin() && in_array($pagenow, ['post.php', 'post-new.php']) && 'shop_order' === $typenow && $current_text === $text ){
        $translated_text =  __( $new_text, $domain );
    }
    return $translated_text;
}
</code>```

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Related answers:

Rename Woocommerce "Orders" admin submenu

Change admin dashboard WooCommerce widget title

Body:
In a recent update to WooCommerce, they have changed the word Discounts to Coupon(s). This is in the order total table. See this screenshot for > clarity https://prnt.sc/sq6xfh

I would like to change this back to Discounts wherever possible as it doesn't really make sense to say Coupons when you have actually applied a discount. Ideally, it would be great to show a Discounts and a Coupon(s) row if required as sometimes you may apply a coupon AND a discount.

For now, I am I trying to change the Discount(s) label as pointed out above in the screenshot.

I have found the code in the plugins core files and know I cannot change that, this is the code:

    <?php if ( 0 < $order->get_total_discount() ) : ?>

            <?php esc_html_e( 'Coupon(s):', 'woocommerce' ); ?>

            -
                <?php echo wc_price( $order->get_total_discount(), array( 'currency' => $order->get_currency() ) ); // WPCS: XSS ok. ?>

    <?php endif; ?>

I am not sure how to change Coupon(s) to Discounts in the code above via my functions.php

Any help appreciated.
Cheers
Nik

Body:
You can use the WordPress gettext hook this way:

add_filter('gettext', 'custom_strings_translation', 20, 3);
function custom_strings_translation( $translated_text, $text, $domain ) {
global $pagenow, $typenow;

    // Settings
    $current_text = "Coupon(s):";
    $new_text     = "Discount(s):";

    // Targeting admin single order pages
    if( is_admin() && in_array($pagenow, ['post.php', 'post-new.php']) && 'shop_order' === $typenow && $current_text === $text ){
        $translated_text =  __( $new_text, $domain );
    }
    return $translated_text;
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Related answers:

Rename Woocommerce "Orders" admin submenu

Change admin dashboard WooCommerce widget title


问:
Is there any way to open the running of the code in a 'jsfiddle' in full-screen?
Is there any way to open the running of the code in a 'jsfiddle' in full-screen?

I mean the bit in red here:

答:
We can. Save the code and append /show to the url </p>

```<code>Example:
https://jsfiddle.net/q7oam39t/show
</code>```

Body:
We can. Save the code and append /show to the url

Example:
https://jsfiddle.net/q7oam39t/show


问:
How to randomize and then split an ArrayList<String> into two even ArrayLists
i know virtually no java but i'm trying to learn some for this project. I am trying to modify a program called GyaPickupBot which is basically a "pick up game" bot on IRC where players can type: !add in order to get added to a list of players who want to play a game and once enough players !add the bot announces the ip of the game server (i.e. quake server) that the game is to be played on. right now, when the specified number of players !add and the game launches, the bot only lists the players who previously !add'ed before the max number of players was reached. I would like for it to divide all of the players who have !add'ed up into 2 random teams of equal size. I have already done the random part using Collections.shuffle but I have no idea how to divide the players into 2 equally sized teams. I emailed the author who is based in Japan a few weeks ago and he finally replied this morning with some very vague hints on how to do this:

Well... at this time, I don't have much motivation to maintain this code.
I can only suggest you some hints.

```<code>private boolean handleReady(String channel, String sender, String login, String hostname, String message) {
boolean isUpdate = false;
String readyGameID = mgr.getReadyGameID();
if (null != readyGameID) {
// *** add some code here to choose teams and store that result to string variable. something like: "team1: ,,,, team2: ,,,,,"
// *** you can get players list by mgr.getPlayers(readyGameID) in order to divide players to 2 teams randomly

for (String ch : getChannels()) {
sendMessage(ch, mgr.getPickupReadyString(readyGameID));
// sendNotice(ch, mgr.getPickupReadyString(readyGameID));
// *** then, send that string to channel
}
mgr.setLastGame(Calendar.getInstance().getTimeInMillis(), mgr.getPickupReadyString(readyGameID));
ArrayList<String> players = mgr.getPlayers(readyGameID);
for (String nick : players) {
sendNotice(nick, mgr.getPickupReadyPMString(readyGameID));
// *** and send that string to players too
}
isUpdate = mgr.clearPlayers(players);
}
return isUpdate;
</code>```

I know this is probably more than what is asked on here, but I'm really trying to learn this but I can't figure it out and any help would be appreciated

答:
The code below is untested, but should give you an idea on how to proceed. Good luck.</p>

```<code>// retrieve all players
ArrayList<String> players = mgr.getPlayers(readyGameID);
// randomize the list
Collections.shuffle(players);
// instantiate two arraylists for the teams
ArrayList<String> teamRed = new ArrayList<String>();
ArrayList<String> teamBlue = new ArrayList<String>();

// add the first half of players to teamRed
teamRed.addAll(players.subList(0, players.size() / 2 + players.size()%2));
// and the second half to teamBlue
teamBlue.addAll(players.subList(players.size() / 2 + players.size()%2, players.size()));

// now do whatever you need to do with the two teams
</code>```

Body:
i know virtually no java but i'm trying to learn some for this project. I am trying to modify a program called GyaPickupBot which is basically a "pick up game" bot on IRC where players can type: !add in order to get added to a list of players who want to play a game and once enough players !add the bot announces the ip of the game server (i.e. quake server) that the game is to be played on. right now, when the specified number of players !add and the game launches, the bot only lists the players who previously !add'ed before the max number of players was reached. I would like for it to divide all of the players who have !add'ed up into 2 random teams of equal size. I have already done the random part using Collections.shuffle but I have no idea how to divide the players into 2 equally sized teams. I emailed the author who is based in Japan a few weeks ago and he finally replied this morning with some very vague hints on how to do this:

Well... at this time, I don't have much motivation to maintain this code.
I can only suggest you some hints.

private boolean handleReady(String channel, String sender, String login, String hostname, String message) {
boolean isUpdate = false;
String readyGameID = mgr.getReadyGameID();
if (null != readyGameID) {
// *** add some code here to choose teams and store that result to string variable. something like: "team1: ,,,, team2: ,,,,,"
// *** you can get players list by mgr.getPlayers(readyGameID) in order to divide players to 2 teams randomly

for (String ch : getChannels()) {
sendMessage(ch, mgr.getPickupReadyString(readyGameID));
// sendNotice(ch, mgr.getPickupReadyString(readyGameID));
// *** then, send that string to channel
}
mgr.setLastGame(Calendar.getInstance().getTimeInMillis(), mgr.getPickupReadyString(readyGameID));
ArrayList<String> players = mgr.getPlayers(readyGameID);
for (String nick : players) {
sendNotice(nick, mgr.getPickupReadyPMString(readyGameID));
// *** and send that string to players too
}
isUpdate = mgr.clearPlayers(players);
}
return isUpdate;

I know this is probably more than what is asked on here, but I'm really trying to learn this but I can't figure it out and any help would be appreciated

Body:
The code below is untested, but should give you an idea on how to proceed. Good luck.

// retrieve all players
ArrayList<String> players = mgr.getPlayers(readyGameID);
// randomize the list
Collections.shuffle(players);
// instantiate two arraylists for the teams
ArrayList<String> teamRed = new ArrayList<String>();
ArrayList<String> teamBlue = new ArrayList<String>();

// add the first half of players to teamRed
teamRed.addAll(players.subList(0, players.size() / 2 + players.size()%2));
// and the second half to teamBlue
teamBlue.addAll(players.subList(players.size() / 2 + players.size()%2, players.size()));

// now do whatever you need to do with the two teams


问:
Is it possible to check if collection contains field value?
Given the simplified model below I want to write a rule that says MyCollection contains MyField, but all I get is the list of Data Source items to select as if the ValueInputType for collections only works for User.  What should I change in the model to achieve that?

public class MyModel
{
    [Field(Settable = false, DataSourceName = "MyDataSource")]
    public int MyField { get; set; }

    [Field(Settable = false, ValueInputType = ValueInputType.All, DataSourceName = "MyDataSource"))]
    public List<int> MyCollection { get; set; }
}
```

答:
Per the documentation here, numeric value-typed collections can only use ValueInputType.User (look for one of the "IMPORTANT!" headers in the middle of the article). Therefore, you can't use value of the MyField field in your rule conditions. You need to create an in-rule method to achieve that:

```<code>public bool Contains(List<int> collection, [Parameter(DataSourceName = "MyDataSource")] int i)
{
    return collection.Contains(i);
}
</code>```

Having such an in-rule method, your rule could look like this:

```<code>Check if Contains(MyCollection, OneOfTheMembersOfMyDataSource) is True
</code>```

Body:
Per the documentation here, numeric value-typed collections can only use ValueInputType.User (look for one of the "IMPORTANT!" headers in the middle of the article). Therefore, you can't use value of the MyField field in your rule conditions. You need to create an in-rule method to achieve that:

public bool Contains(List<int> collection, [Parameter(DataSourceName = "MyDataSource")] int i)
{
    return collection.Contains(i);
}

Having such an in-rule method, your rule could look like this:

Check if Contains(MyCollection, OneOfTheMembersOfMyDataSource) is True


问:
Can I create a `pytest.mark.failif`?
pytest allows you to skip a test under some condition (i.e.: on a platform):

@pytest.mark.skipif(sys.platform == "win32")
def test_foo(fixture):
    assert bar(fixture)
```

<p>Is there a way to create a mark to make the test <em>fail</em> under a certain condition?</p>

<pre class="lang-py prettyprint-override"><code>@pytest.mark.failif(sys.platform == "win32")
def test_foo(fixture):
    assert bar(fixture)
</code>```

答:
Even without pytest you could write a simple decorator that does this:

def failif(condition: bool, *, reason: str) -> Callable[[T], T]:
    def failif_decorator(func: T) -> T:
        @functools.wraps(func)
        def failif_decorator_inner(*args: Any, **kwargs: Any) -> Any:
            assert not condition, reason
            return func(*args, **kwargs)
        return cast(T, failif_decorator_inner)
    return failif_decorator
```

<p>Usage would be</p>

<pre class="lang-py prettyprint-override"><code>@failif(sys.platform == 'win32', reason='we do not support windows')
def test():
    ...
</code>```

for a pytest-specific solution you could use one of the hooks for registering marks -- though that's quite a bit more involved

Title: Can I create a `pytest.mark.failif`?

Body:
pytest allows you to skip a test under some condition (i.e.: on a platform):

@pytest.mark.skipif(sys.platform == "win32")
def test_foo(fixture):
    assert bar(fixture)

Is there a way to create a mark to make the test fail under a certain condition?

@pytest.mark.failif(sys.platform == "win32")
def test_foo(fixture):
    assert bar(fixture)

Body:
Even without pytest you could write a simple decorator that does this:

def failif(condition: bool, *, reason: str) -> Callable[[T], T]:
    def failif_decorator(func: T) -> T:
        @functools.wraps(func)
        def failif_decorator_inner(*args: Any, **kwargs: Any) -> Any:
            assert not condition, reason
            return func(*args, **kwargs)
        return cast(T, failif_decorator_inner)
    return failif_decorator

Usage would be

@failif(sys.platform == 'win32', reason='we do not support windows')
def test():
    ...

for a pytest-specific solution you could use one of the hooks for registering marks -- though that's quite a bit more involved


问:
What is the shortcut in Visual Studio Code for console.log
I want to know what is the shortcut for console.log in Visual Studio Code?

答:
Type co and hit tab or enter.

Should work out of the box.


问:
Provide lambda function code as S3 Bucket name and Key Name
Right Now i am using inline lambda function code. I want to put the code somewhere in S3 bucket and than Provide it as S3 bucketname and S3 keyname. How can I do it.</p>

答:
```<code>codeDetails = {"S3Bucket": 'bucketname' , "S3Key": 'lambdaCode/Events.zip' }
lambda_resp = lambda_client.create_function(FunctionName='test-lambda',
                Handler = 'lambda_function.lambda_handler',Runtime='python3.7', Role = role_arn, Code=codeDetails ,Timeout=800, MemorySize = 1024, Publish = True)
</code>```

<p>By creating a lambda_client this can be done. </p>

Body:
codeDetails = {"S3Bucket": 'bucketname' , "S3Key": 'lambdaCode/Events.zip' }
lambda_resp = lambda_client.create_function(FunctionName='test-lambda',
                Handler = 'lambda_function.lambda_handler',Runtime='python3.7', Role = role_arn, Code=codeDetails ,Timeout=800, MemorySize = 1024, Publish = True)

By creating a lambda_client this can be done.


问:
having problem with installing Python package
I want install python package. But when I am trying to install "ipython" package and I write:

```<code>pip install ipython
</code>```

It give this error:

```<code>pip install ipython
      ^
SyntaxError: invalid syntax
</code>```

How should I fix this?

答:
It may be a bit confusing at first, but python is a very different shell than the windows cmd shell or any of the unixy shells. Once you've entered python, only python syntax is allowed. Mostly.... there are other shells such as Jupyter notebook and various IDE's that will have extensions to do non-python things.

Since a python error was displayed SyntaxError: invalid syntax it showed that your command had in fact ended up in the python interpreter. The solution is to run the comamnd directly from the command prompt.

Body:
I want install python package. But when I am trying to install "ipython" package and I write:

pip install ipython

It give this error:

pip install ipython
      ^
SyntaxError: invalid syntax

How should I fix this?


问:
R - Repetitions of an array in other array
From a dataframe I get a new array, sliced from a dataframe.
I want to get the amount of times a certain repetition appears on it.

For example

```<code>main <- c(A,B,C,A,B,V,A,B,C,D,E)
p <- c(A,B,C)
q <- c(A,B)

someFunction(main,p)
2

someFunction(main,q)
3
</code>```

I've been messing around with rle but it counts every subrepetion also, undersirable.

Is there a quick solution I'm missing?

答:
I'm not sure if this is the best way, but you can simply do that work by:

```<code>f <- function(a,b)
  if (length(a) > length(b)) 0
  else all(head(b, length(a)) == a) + Recall(a, tail(b, -1))
</code>```

Someone may or may not find a built-in function.

Body:
From a dataframe I get a new array, sliced from a dataframe.
I want to get the amount of times a certain repetition appears on it.

For example

main <- c(A,B,C,A,B,V,A,B,C,D,E)
p <- c(A,B,C)
q <- c(A,B)

someFunction(main,p)
2

someFunction(main,q)
3

I've been messing around with rle but it counts every subrepetion also, undersirable.

Is there a quick solution I'm missing?

Body:
I'm not sure if this is the best way, but you can simply do that work by:

f <- function(a,b)
  if (length(a) > length(b)) 0
  else all(head(b, length(a)) == a) + Recall(a, tail(b, -1))

Someone may or may not find a built-in function.


问:
ifelse not returning a vector in BASE R
Maybe this is too basic of a question. But in my function foo below, I expected that because of using ifelse when I input a vector for the input values, I get a vector output.

But I wonder why in the example below instead of getting > [1] 1   6 in the output, I just get > [1] 1 as the output?

```<code>foo <- function(mpre = NA, mpos = NA, mdif = NA){
ifelse(!is.na(mdif), mdif, ifelse(!is.na(mpre) & !is.na(mpre) & is.na(mdif), mpos - mpre, NA))
}
## EXAMPLE:

foo(c(1,3), c(2,9))
</code>```

答:
We can also do</p>

```<code> foo <- function(mpre, mpos, mdif = NA){

  if(!is.na(mdif)) mdif
    else ifelse(!(is.na(mpre) | is.na(mpre)) & is.na(mdif), mpos - mpre, NA)
    }

  foo(c(1,3), c(2,9))
</code>```

Title: ifelse not returning a vector in BASE R

Body:
Maybe this is too basic of a question. But in my function foo below, I expected that because of using ifelse when I input a vector for the input values, I get a vector output.

But I wonder why in the example below instead of getting > [1] 1   6 in the output, I just get > [1] 1 as the output?

foo <- function(mpre = NA, mpos = NA, mdif = NA){
ifelse(!is.na(mdif), mdif, ifelse(!is.na(mpre) & !is.na(mpre) & is.na(mdif), mpos - mpre, NA))
}
## EXAMPLE:

foo(c(1,3), c(2,9))

Body:
We can also do

 foo <- function(mpre, mpos, mdif = NA){

  if(!is.na(mdif)) mdif
    else ifelse(!(is.na(mpre) | is.na(mpre)) & is.na(mdif), mpos - mpre, NA)
    }

  foo(c(1,3), c(2,9))


问:
How to be sure Progress Bar is stopped
I know that to "stop" the ProgressBar one needs to set its visibility to View.GONE. But ... does that really stop it? There's an animation going in the background that animates the view. Is that animation stopping once it detects the progress bar is GONE or INVISIBILE? I really don't want to have a progress bar continuously running in the background, when not needed. It's a waste of processing power.

Does anyone have any idea?

答:
Looking at ProgressBar.java I found:

```<code>/**
 * Returns whether the ProgressBar is animating or not. This is essentially the same
 * as whether the ProgressBar is {@link #isIndeterminate() indeterminate} and visible,
 * as indeterminate ProgressBars are always animating, and non-indeterminate
 * ProgressBars are not animating.
 *
 * @return true if the ProgressBar is animating, false otherwise.
 */
public boolean isAnimating() {
    return isIndeterminate() && getWindowVisibility() == VISIBLE && isShown();
}

void startAnimation() {
    if (getVisibility() != VISIBLE || getWindowVisibility() != VISIBLE) {
        return;
    }
    ...

@Override
protected void onDetachedFromWindow() {
    if (mIndeterminate) {
        stopAnimation();
    }
    ...
</code>```

I think, ProgressBar will stop animating after you hide it.

Title: How to be sure Progress Bar is stopped

Body:
Looking at ProgressBar.java I found:

/**
 * Returns whether the ProgressBar is animating or not. This is essentially the same
 * as whether the ProgressBar is {@link #isIndeterminate() indeterminate} and visible,
 * as indeterminate ProgressBars are always animating, and non-indeterminate
 * ProgressBars are not animating.
 *
 * @return true if the ProgressBar is animating, false otherwise.
 */
public boolean isAnimating() {
    return isIndeterminate() && getWindowVisibility() == VISIBLE && isShown();
}

void startAnimation() {
    if (getVisibility() != VISIBLE || getWindowVisibility() != VISIBLE) {
        return;
    }
    ...

@Override
protected void onDetachedFromWindow() {
    if (mIndeterminate) {
        stopAnimation();
    }
    ...

I think, ProgressBar will stop animating after you hide it.


问:
Process, memory and network resource tracer
I would like to try to make a process, memory and network resource tracer similar to the one that comes by default in ubuntu for any operating system. But being new in python I don't know how to get these values to be displayed (in principle by console, then I'll do them as graphics). Which library would be easier to do it with?</p>

答:
On linux, you could leverage the /proc filesystem to read the information you need for such a task.

the /proc filesystem is a window into the kernel with a lot of data on each process running. It is displayed as a virtual filesystem, meaning you can access all that info simply by reading and parsing files.

For instance,

from pathlib import Path

proc = Path('/proc')

for proc in proc.iterdir():
    if not proc.name.isnumeric():
        continue # ignore directories that aren't processes

    pid = proc.name
    cmdline = (proc / 'cmdline').read_text()
    print(f'PROCESS : {pid} : {cmdline}')
```

This will list all processes running, along with their commandline.

You have a lot of information you can gather in there.

more info on /proc here

Body:
On linux, you could leverage the /proc filesystem to read the information you need for such a task.

the /proc filesystem is a window into the kernel with a lot of data on each process running. It is displayed as a virtual filesystem, meaning you can access all that info simply by reading and parsing files.

For instance,

from pathlib import Path

proc = Path('/proc')

for proc in proc.iterdir():
    if not proc.name.isnumeric():
        continue # ignore directories that aren't processes

    pid = proc.name
    cmdline = (proc / 'cmdline').read_text()
    print(f'PROCESS : {pid} : {cmdline}')

This will list all processes running, along with their commandline.

You have a lot of information you can gather in there.

more info on /proc here


问:
Storing Pandas dataframe in working memory
Is there some way to take a dataframe, say,

```<code>df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})
</code>```

and store it in temp memory as a binary object that can then be opened with

```<code>open(df, 'rb')
</code>```

So then, rather than do something like

```<code>open('/home/user/data.csv', 'rb')
</code>```

the code would be

```<code>df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})

df_rb = *command to store in temp working memory as binary readable*

open(df_rb, 'rb')
</code>```

答:
You could pickle it to an io.BytesIO object which is in memory

```<code>import pandas as pd
import pickle, io
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})
f = io.BytesIO()
pickle.dump(df,f)
f.seek(0)    # necessary to start reading at the beginning of the "file"
dg = pickle.load(f)

In [48]: dg==df
Out[48]:
      a     b
0  True  True
1  True  True
2  True  True
</code>```

Body:
Is there some way to take a dataframe, say,

df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})

and store it in temp memory as a binary object that can then be opened with

open(df, 'rb')

So then, rather than do something like

open('/home/user/data.csv', 'rb')

the code would be

df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})

df_rb = *command to store in temp working memory as binary readable*

open(df_rb, 'rb')

Body:
You could pickle it to an io.BytesIO object which is in memory

import pandas as pd
import pickle, io
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})
f = io.BytesIO()
pickle.dump(df,f)
f.seek(0)    # necessary to start reading at the beginning of the "file"
dg = pickle.load(f)

In [48]: dg==df
Out[48]:
      a     b
0  True  True
1  True  True
2  True  True


问:
How can i setup a Socket.io client on flutter?
I have a flutter app and i am trying to connect it to a node.js localhost server. it works with react js but I haven't done it in flutter before. can I get help on sending a simple connection to my server socket io? </p>

答:
It's pretty easy. You'll basically have to use this package to connect to your backend. The idea is pretty similar to JavaScript applications.

In case you need it, I already implemented a simple application using it on Flutter. It's pretty straightforward and you only have to focus on mobile/lib/config/socket.dart which is my socket client.

It contains three simple methods used to emit events and subscribe/unsubscribe to events. Any doubts just ask it.

EDIT:
In case you have any problem connecting to your backend add this line to your Android Manifest. I remember I had some problem because of the android version which had cleartext disabled by default.


问:
More efficient way to compute the rowNorms in R?
I wrote a program using an unsupervised K-means algorithm to try and compress images. It now works but in comparison to Python it's incredibly slow! Specifically it's finding the rowNorms thats slow. The array X is 350000+ elements.

This is the particular function:

```<code>find_closest_centroids <- function(X, centroids) {
  m <- nrow(X)
  c <- integer(m)

  for(i in 1:m){
    distances = rowNorms(sweep(centroids,2,X[i,]))

    c[i] = which.min(distances)
  }
  return(c)
}
</code>```

In Python I am able to do it like this:

```<code>def find_closest_centroids(X, centroids):
    m = len(X)
    c = np.zeros(m)

    for i in range(m):
        distances = np.linalg.norm(X[i] - centroids, axis=1)

        c[i] = np.argmin(distances)

    return c
</code>```

Any recommendations?

Thanks.

答:
As dvd280 has noted in his comment, R tends to do worse than many other languages in terms of performance. If are content with the performance of your code in Python, but need the function available in R, you might want to look into the reticulate package which provides an interface to python like the Rcpp package mentioned by dvd280 does for C++.

If you still want to implement this natively in R, be mindful of the data structures you use. For rowwise operations, data frames are a poor choice as they are lists of columns. I'm not sure about the data structures in your code, but rowNorms() seems to be a matrix method. You might get more mileage out of a list of rows structure.

If you feel like getting into dplyr, you could find this vignette on row-wise operations helpful. Make sure you have the latest version of the package, as the vignette is based on dplyr 1.0.

The data.table package tends to yield the best performance for large data sets in R, but I'm not familiar with it, so I can't give you any further directions on that.

Body:
I wrote a program using an unsupervised K-means algorithm to try and compress images. It now works but in comparison to Python it's incredibly slow! Specifically it's finding the rowNorms thats slow. The array X is 350000+ elements.

This is the particular function:

find_closest_centroids <- function(X, centroids) {
  m <- nrow(X)
  c <- integer(m)

  for(i in 1:m){
    distances = rowNorms(sweep(centroids,2,X[i,]))

    c[i] = which.min(distances)
  }
  return(c)
}

In Python I am able to do it like this:

def find_closest_centroids(X, centroids):
    m = len(X)
    c = np.zeros(m)

    for i in range(m):
        distances = np.linalg.norm(X[i] - centroids, axis=1)

        c[i] = np.argmin(distances)

    return c

Any recommendations?

Thanks.


问:
My Update query in SQLite isn't properly updating back to the database
I'm making a form in visual studio that's able to access a database, fill a datatable with the db's table, display the datatable in a datagridview, populate editable fields on screen, and then pass those values of those fields back into the database to their respective columns. My problem is happening on the last step of that, as my update function doesn't seem to be working. I've searched around, but I'm not really sure where I'm going wrong.</p>

```<code>            string query = "UPDATE Actors SET fname=@fName, lname=@lName, sex=@sex, age=@age, action=@action, comic=@comic, drama=@drama, ego=@ego, music=@music, starQual=@starQual, romance=@romance, sexApp=@sexApp, workEth=@workEth, popularity=@popularity WHERE Id=@Id";
            SQLiteConnection myConnection = new SQLiteConnection("Data Source=data.db");
            SQLiteCommand cmd = new SQLiteCommand(query, myConnection);
            myConnection.Open();

            cmd.Parameters.Add(new SQLiteParameter("@fname", enterfName.Text));
            cmd.Parameters.Add(new SQLiteParameter("@lname", enterlName.Text));
            cmd.Parameters.Add(new SQLiteParameter("@sex", enterSex.Text));
            cmd.Parameters.Add(new SQLiteParameter("@age", Convert.ToInt32(enterAge.Value)));
            cmd.Parameters.Add(new SQLiteParameter("@action", Convert.ToInt32(enterAction.Value)));
            cmd.Parameters.Add(new SQLiteParameter("@comic", Convert.ToInt32(enterComic.Value)));
            cmd.Parameters.Add(new SQLiteParameter("@drama", Convert.ToInt32(enterDrama.Value)));
            cmd.Parameters.Add(new SQLiteParameter("@ego", Convert.ToInt32(enterEgo.Value)));
            cmd.Parameters.Add(new SQLiteParameter("@music", Convert.ToInt32(enterMusic.Value)));
            cmd.Parameters.Add(new SQLiteParameter("@starQual", Convert.ToInt32(enterStarQual.Value)));
            cmd.Parameters.Add(new SQLiteParameter("@romance", Convert.ToInt32(enterRomance.Value)));
            cmd.Parameters.Add(new SQLiteParameter("@sexApp", Convert.ToInt32(enterSexApp.Value)));
            cmd.Parameters.Add(new SQLiteParameter("workEth", Convert.ToInt32(enterWorkEth.Value)));
            cmd.Parameters.Add(new SQLiteParameter("@popularity", Convert.ToInt32(enterPopularity.Value)));
            cmd.Parameters.Add(new SQLiteParameter("@Id", Convert.ToInt32(indexHold.Value)));
            cmd.ExecuteNonQuery();
            myConnection.Close();
            //Update gridview with the changes
            updateGridView();
</code>```

答:
You forgot the @ of the parameter

```<code>cmd.Parameters.Add(new SQLiteParameter("@workEth",Convert.ToInt32(enterWorkEth.Value)));
</code>```

Body:
I'm making a form in visual studio that's able to access a database, fill a datatable with the db's table, display the datatable in a datagridview, populate editable fields on screen, and then pass those values of those fields back into the database to their respective columns. My problem is happening on the last step of that, as my update function doesn't seem to be working. I've searched around, but I'm not really sure where I'm going wrong.

            string query = "UPDATE Actors SET fname=@fName, lname=@lName, sex=@sex, age=@age, action=@action, comic=@comic, drama=@drama, ego=@ego, music=@music, starQual=@starQual, romance=@romance, sexApp=@sexApp, workEth=@workEth, popularity=@popularity WHERE Id=@Id";
            SQLiteConnection myConnection = new SQLiteConnection("Data Source=data.db");
            SQLiteCommand cmd = new SQLiteCommand(query, myConnection);
            myConnection.Open();

            cmd.Parameters.Add(new SQLiteParameter("@fname", enterfName.Text));
            cmd.Parameters.Add(new SQLiteParameter("@lname", enterlName.Text));
            cmd.Parameters.Add(new SQLiteParameter("@sex", enterSex.Text));
            cmd.Parameters.Add(new SQLiteParameter("@age", Convert.ToInt32(enterAge.Value)));
            cmd.Parameters.Add(new SQLiteParameter("@action", Convert.ToInt32(enterAction.Value)));
            cmd.Parameters.Add(new SQLiteParameter("@comic", Convert.ToInt32(enterComic.Value)));
            cmd.Parameters.Add(new SQLiteParameter("@drama", Convert.ToInt32(enterDrama.Value)));
            cmd.Parameters.Add(new SQLiteParameter("@ego", Convert.ToInt32(enterEgo.Value)));
            cmd.Parameters.Add(new SQLiteParameter("@music", Convert.ToInt32(enterMusic.Value)));
            cmd.Parameters.Add(new SQLiteParameter("@starQual", Convert.ToInt32(enterStarQual.Value)));
            cmd.Parameters.Add(new SQLiteParameter("@romance", Convert.ToInt32(enterRomance.Value)));
            cmd.Parameters.Add(new SQLiteParameter("@sexApp", Convert.ToInt32(enterSexApp.Value)));
            cmd.Parameters.Add(new SQLiteParameter("workEth", Convert.ToInt32(enterWorkEth.Value)));
            cmd.Parameters.Add(new SQLiteParameter("@popularity", Convert.ToInt32(enterPopularity.Value)));
            cmd.Parameters.Add(new SQLiteParameter("@Id", Convert.ToInt32(indexHold.Value)));
            cmd.ExecuteNonQuery();
            myConnection.Close();
            //Update gridview with the changes
            updateGridView();

Body:
You forgot the @ of the parameter

cmd.Parameters.Add(new SQLiteParameter("@workEth",Convert.ToInt32(enterWorkEth.Value)));


问:
using list of predefined positions on list in r
I have a large and complex list of 10.000 elements and I want to extract only values of a specific position. So, I've made an object only with the positions I want to subset.

```<code>   index
   [1]    1    3    5    9   18   23   24   25   26   32   37   52   56   57   58   59   60   64   70   72   74   75
</code>```

how I can use only these numbers to extract the elements I want?

I tried something like that, but doesn't work

```<code>df[[2]][index][[8]][[1]][[1]]

str(df)
.. .. .. ..$ DisorderMappingRelation        :List of 2
  .. .. .. .. ..$ Name  :List of 2
  .. .. .. .. .. ..$ text  : chr "BTNT (broader term maps to a narrower term)"
  .. .. .. .. .. ..$ .attrs: Named chr "en"
  .. .. .. .. .. .. ..- attr(*, "names")= chr "lang"
  .. .. .. .. ..$ .attrs: Named chr "21541"
  .. .. .. .. .. ..- attr(*, "names")= chr "id"
  .. .. .. ..$ DisorderMappingICDRelation     : NULL
  .. .. .. ..$ DisorderMappingValidationStatus:List of 2
  .. .. .. .. ..$ Name  :List of 2
  .. .. .. .. .. ..$ text  : chr "Validated"
  .. .. .. .. .. ..$ .attrs: Named chr "en"
  .. .. .. .. .. .. ..- attr(*, "names")= chr "lang"
  .. .. .. .. ..$ .attrs: Named chr "21611"
  .. .. .. .. .. ..- attr(*, "names")= chr "id"
  .. .. .. ..$ .attrs                         : Named chr "3669"
  .. .. .. .. ..- attr(*, "names")= chr "id"
  .. .. ..$ ExternalReference:List of 6
  .. .. .. ..$ Source                         : chr "OMIM"
  .. .. .. ..$ Reference                      : chr "219900"
  .. .. .. ..$ DisorderMappingRelation        :List of 2
  .. .. .. .. ..$ Name  :List of 2
  .. .. .. .. .. ..$ text  : chr "BTNT (broader term maps to a narrower term)"
  .. .. .. .. .. ..$ .attrs: Named chr "en"
  .. .. .. .. .. .. ..- attr(*, "names")= chr "lang"
  .. .. .. .. ..$ .attrs: Named chr "21541"
  .. .. .. .. .. ..- attr(*, "names")= chr "id"
  .. .. .. ..$ DisorderMappingICDRelation     : NULL
  .. .. .. ..$ DisorderMappingValidationStatus:List of 2
  .. .. .. .. ..$ Name  :List of 2
  .. .. .. .. .. ..$ text  : chr "Validated"
  .. .. .. .. .. ..$ .attrs: Named chr "en"
  .. .. .. .. .. .. ..- attr(*, "names")= chr "lang"
  .. .. .. .. ..$ .attrs: Named chr "21611"
  .. .. .. .. .. ..- attr(*, "names")= chr "id"
  .. .. .. ..$ .attrs                         : Named chr "11886"
  .. .. .. .. ..- attr(*, "names")= chr "id"
  .. .. ..$ .attrs           : Named chr "7"
  .. .. .. ..- attr(*, "names")= chr "count"
  .. ..$ DisorderDisorderAssociationList:List of 2
  .. .. ..$ text  : chr "\n      "
  .. .. ..$ .attrs: Named chr "0"
  .. .. .. ..- attr(*, "names")= chr "count"
  .. ..$ TextualInformationList         :List of 6
  .. .. ..$ TextualInformation:List of 2
  .. .. .. ..$ TextSectionList:List of 2
  .. .. .. .. ..$ TextSection:List of 3
  .. .. .. .. .. ..$ TextSectionType:List of 2
  .. .. .. .. .. .. ..$ Name  :List of 2
  .. .. .. .. .. .. .. ..$ text  : chr "Definition"
  .. .. .. .. .. .. .. ..$ .attrs: Named chr "en"
  .. .. .. .. .. .. .. .. ..- attr(*, "names")= chr "lang"
  .. .. .. .. .. .. ..$ .attrs: Named chr "16907"
  .. .. .. .. .. .. .. ..- attr(*, "names")= chr "id"
  .. .. .. .. .. ..$ Contents       : chr "A rare lysosomal disease characterized by an accumulation of cystine inside the lysosomes, causing damage in di"| __truncated__
  .. .. .. .. .. ..$ .attrs         : Named chr [1:2] "91672" "en"
  .. .. .. .. .. .. ..- attr(*, "names")= chr [1:2] "id" "lang"
  .. .. .. .. ..$ .attrs     : Named chr "1"
  .. .. .. .. .. ..- attr(*, "names")= chr "count"
  .. .. .. ..$ .attrs         : Named chr [1:2] "1026" "en"
  .. .. .. .. ..- attr(*, "names")= chr [1:2] "id" "lang"
  .. .. ..$ TextualInformation:List of 2
  .. .. .. ..$ TextSectionList:List of 2
  .. .. .. .. ..$ text  : chr "\n          "
  .. .. .. .. ..$ .attrs: Named chr "0"
  .. .. .. .. .. ..- attr(*, "names")= chr "count"
  .. .. .. ..$ .attrs         : Named chr [1:2] "94635" "en"
  .. .. .. .. ..- attr(*, "names")= chr [1:2] "id" "lang"
  .. .. ..$ TextualInformation:List of 2
  .. .. .. ..$ TextSectionList:List of 2
  .. .. .. .. ..$ text  : chr "\n          "
  .. .. .. .. ..$ .attrs: Named chr "0"
  .. .. .. .. .. ..- attr(*, "names")= chr "count"
  .. .. .. ..$ .attrs         : Named chr [1:2] "74141" "en"
  .. .. .. .. ..- attr(*, "names")= chr [1:2] "id" "lang"
  .. .. ..$ TextualInformation:List of 2
  .. .. .. ..$ TextSectionList:List of 2
  .. .. .. .. ..$ text  : chr "\n          "
  .. .. .. .. ..$ .attrs: Named chr "0"
  .. .. .. .. .. ..- attr(*, "names")= chr "count"
  .. .. .. ..$ .attrs         : Named chr [1:2] "92580" "en"
  .. .. .. .. ..- attr(*, "names")= chr [1:2] "id" "lang"
  .. .. ..$ TextualInformation:List of 2
  .. .. .. ..$ TextSectionList:List of 2
  .. .. .. .. ..$ text  : chr "\n          "
  .. .. .. .. ..$ .attrs: Named chr "0"
  .. .. .. .. .. ..- attr(*, "names")= chr "count"
  .. .. .. ..$ .attrs         : Named chr [1:2] "115312" "en"
  .. .. .. .. ..- attr(*, "names")= chr [1:2] "id" "lang"
  .. .. ..$ .attrs            : Named chr "5"
  .. .. .. ..- attr(*, "names")= chr "count"
  .. ..$ .attrs                         : Named chr "11"
  .. .. ..- attr(*, "names")= chr "id"
</code>```

there are some interest paths to extract values

```<code>df[[2]][[i]][[3]][[1]]  #Name
df[[2]][[i]][[1]]  #Class
df[[2]][[i]][[8]][[1]][[1]] #Reference
df[[2]][[i]][[8]][[1]][[2]] #text
</code>```

I want to apply "index" over "i" and extract the values

here is a reproducible and simple example of what I've done

```<code>a = c("a", "b", "c")
b = c("b", "c", "a")
c = c("d", "a", "b")

lis = c(a,b,c)

df = data.frame(unlist(lapply(1:(length(lis[[1]])), function(i) lis[[1]][[i]][[1]])))
colnames(df) = "names"

index = which(df$names == "a")

lis[[1]][[index]][[1]]
</code>```

with only one element it works, by my real index has near 5.000 numbers

答:
We can use sapply to loop over the 'index' and extract the elements one by one (Without a small example, it is not clear though)

```<code>sapply(index, function(i) df[[2]][i][[8]][[1]][[1]])
</code>```

Body:
I have a large and complex list of 10.000 elements and I want to extract only values of a specific position. So, I've made an object only with the positions I want to subset.

   index
   [1]    1    3    5    9   18   23   24   25   26   32   37   52   56   57   58   59   60   64   70   72   74   75

how I can use only these numbers to extract the elements I want?

I tried something like that, but doesn't work

df[[2]][index][[8]][[1]][[1]]

str(df)
.. .. .. ..$ DisorderMappingRelation        :List of 2
  .. .. .. .. ..$ Name  :List of 2
  .. .. .. .. .. ..$ text  : chr "BTNT (broader term maps to a narrower term)"
  .. .. .. .. .. ..$ .attrs: Named chr "en"
  .. .. .. .. .. .. ..- attr(*, "names")= chr "lang"
  .. .. .. .. ..$ .attrs: Named chr "21541"
  .. .. .. .. .. ..- attr(*, "names")= chr "id"
  .. .. .. ..$ DisorderMappingICDRelation     : NULL
  .. .. .. ..$ DisorderMappingValidationStatus:List of 2
  .. .. .. .. ..$ Name  :List of 2
  .. .. .. .. .. ..$ text  : chr "Validated"
  .. .. .. .. .. ..$ .attrs: Named chr "en"
  .. .. .. .. .. .. ..- attr(*, "names")= chr "lang"
  .. .. .. .. ..$ .attrs: Named chr "21611"
  .. .. .. .. .. ..- attr(*, "names")= chr "id"
  .. .. .. ..$ .attrs                         : Named chr "3669"
  .. .. .. .. ..- attr(*, "names")= chr "id"
  .. .. ..$ ExternalReference:List of 6
  .. .. .. ..$ Source                         : chr "OMIM"
  .. .. .. ..$ Reference                      : chr "219900"
  .. .. .. ..$ DisorderMappingRelation        :List of 2
  .. .. .. .. ..$ Name  :List of 2
  .. .. .. .. .. ..$ text  : chr "BTNT (broader term maps to a narrower term)"
  .. .. .. .. .. ..$ .attrs: Named chr "en"
  .. .. .. .. .. .. ..- attr(*, "names")= chr "lang"
  .. .. .. .. ..$ .attrs: Named chr "21541"
  .. .. .. .. .. ..- attr(*, "names")= chr "id"
  .. .. .. ..$ DisorderMappingICDRelation     : NULL
  .. .. .. ..$ DisorderMappingValidationStatus:List of 2
  .. .. .. .. ..$ Name  :List of 2
  .. .. .. .. .. ..$ text  : chr "Validated"
  .. .. .. .. .. ..$ .attrs: Named chr "en"
  .. .. .. .. .. .. ..- attr(*, "names")= chr "lang"
  .. .. .. .. ..$ .attrs: Named chr "21611"
  .. .. .. .. .. ..- attr(*, "names")= chr "id"
  .. .. .. ..$ .attrs                         : Named chr "11886"
  .. .. .. .. ..- attr(*, "names")= chr "id"
  .. .. ..$ .attrs           : Named chr "7"
  .. .. .. ..- attr(*, "names")= chr "count"
  .. ..$ DisorderDisorderAssociationList:List of 2
  .. .. ..$ text  : chr "\n      "
  .. .. ..$ .attrs: Named chr "0"
  .. .. .. ..- attr(*, "names")= chr "count"
  .. ..$ TextualInformationList         :List of 6
  .. .. ..$ TextualInformation:List of 2
  .. .. .. ..$ TextSectionList:List of 2
  .. .. .. .. ..$ TextSection:List of 3
  .. .. .. .. .. ..$ TextSectionType:List of 2
  .. .. .. .. .. .. ..$ Name  :List of 2
  .. .. .. .. .. .. .. ..$ text  : chr "Definition"
  .. .. .. .. .. .. .. ..$ .attrs: Named chr "en"
  .. .. .. .. .. .. .. .. ..- attr(*, "names")= chr "lang"
  .. .. .. .. .. .. ..$ .attrs: Named chr "16907"
  .. .. .. .. .. .. .. ..- attr(*, "names")= chr "id"
  .. .. .. .. .. ..$ Contents       : chr "A rare lysosomal disease characterized by an accumulation of cystine inside the lysosomes, causing damage in di"| __truncated__
  .. .. .. .. .. ..$ .attrs         : Named chr [1:2] "91672" "en"
  .. .. .. .. .. .. ..- attr(*, "names")= chr [1:2] "id" "lang"
  .. .. .. .. ..$ .attrs     : Named chr "1"
  .. .. .. .. .. ..- attr(*, "names")= chr "count"
  .. .. .. ..$ .attrs         : Named chr [1:2] "1026" "en"
  .. .. .. .. ..- attr(*, "names")= chr [1:2] "id" "lang"
  .. .. ..$ TextualInformation:List of 2
  .. .. .. ..$ TextSectionList:List of 2
  .. .. .. .. ..$ text  : chr "\n          "
  .. .. .. .. ..$ .attrs: Named chr "0"
  .. .. .. .. .. ..- attr(*, "names")= chr "count"
  .. .. .. ..$ .attrs         : Named chr [1:2] "94635" "en"
  .. .. .. .. ..- attr(*, "names")= chr [1:2] "id" "lang"
  .. .. ..$ TextualInformation:List of 2
  .. .. .. ..$ TextSectionList:List of 2
  .. .. .. .. ..$ text  : chr "\n          "
  .. .. .. .. ..$ .attrs: Named chr "0"
  .. .. .. .. .. ..- attr(*, "names")= chr "count"
  .. .. .. ..$ .attrs         : Named chr [1:2] "74141" "en"
  .. .. .. .. ..- attr(*, "names")= chr [1:2] "id" "lang"
  .. .. ..$ TextualInformation:List of 2
  .. .. .. ..$ TextSectionList:List of 2
  .. .. .. .. ..$ text  : chr "\n          "
  .. .. .. .. ..$ .attrs: Named chr "0"
  .. .. .. .. .. ..- attr(*, "names")= chr "count"
  .. .. .. ..$ .attrs         : Named chr [1:2] "92580" "en"
  .. .. .. .. ..- attr(*, "names")= chr [1:2] "id" "lang"
  .. .. ..$ TextualInformation:List of 2
  .. .. .. ..$ TextSectionList:List of 2
  .. .. .. .. ..$ text  : chr "\n          "
  .. .. .. .. ..$ .attrs: Named chr "0"
  .. .. .. .. .. ..- attr(*, "names")= chr "count"
  .. .. .. ..$ .attrs         : Named chr [1:2] "115312" "en"
  .. .. .. .. ..- attr(*, "names")= chr [1:2] "id" "lang"
  .. .. ..$ .attrs            : Named chr "5"
  .. .. .. ..- attr(*, "names")= chr "count"
  .. ..$ .attrs                         : Named chr "11"
  .. .. ..- attr(*, "names")= chr "id"

there are some interest paths to extract values

df[[2]][[i]][[3]][[1]]  #Name
df[[2]][[i]][[1]]  #Class
df[[2]][[i]][[8]][[1]][[1]] #Reference
df[[2]][[i]][[8]][[1]][[2]] #text

I want to apply "index" over "i" and extract the values

here is a reproducible and simple example of what I've done

a = c("a", "b", "c")
b = c("b", "c", "a")
c = c("d", "a", "b")

lis = c(a,b,c)

df = data.frame(unlist(lapply(1:(length(lis[[1]])), function(i) lis[[1]][[i]][[1]])))
colnames(df) = "names"

index = which(df$names == "a")

lis[[1]][[index]][[1]]

with only one element it works, by my real index has near 5.000 numbers

Body:
We can use sapply to loop over the 'index' and extract the elements one by one (Without a small example, it is not clear though)

sapply(index, function(i) df[[2]][i][[8]][[1]][[1]])


问:
Ionic Angular - Desktop sidemenu minimized to the side instead of completely hidden
By default in Ionic, the sidemenu will be expanded or hidden by sliding in/out from the side of the screen everytime we click on it.
However, specific for desktop version, I wanted it to be minimized (instead of completely hidden) to the side of the screen (so we can still see the icons on the left side of the screen) when toggling in.

Can this be achieved by modifying the css on either
ion-menu or ion-split-pane ?

答:
I believe not. you want something like this:

Opened:

Closed:

And I'm pretty sure it's not possible using the Ionic UI kit. you have to create your own component.


问:
Uncaught TypeError: Cannot read property 'innerHTML' of null at text inside this blog website I'm trying to write

var x = 0;

function text() {
  var blogtext = document.getElementById("Textarea").value;
  var y = "p" + String(x);
  console.log(typeof y);
  //problem
  document.createElement("p").id = y;
  //
  document.getElementById(y).innerHTML = blogtext;
  //document.write("
"+blogtext+"
");
  x = x + 1;
}
```

When I run this code inside an HTML file the error: Uncaught TypeError occurs, the code is supposed to create a new paragraph tag whose content is the text inputted by the user inside the text area and each paragraph would have a different id as x increases.
Sorry, I'm new to coding this is one of my school's projects.

答:
You are not creating the element right and you are looking for the element before it is added to the page.</p>

```<code>var x = 0;
function text() {
    var blogtext = document.getElementById("Textarea").value;
    var y = "p" + String(x);
    // create the element
    var p = document.createElement("p")
    //set the id
    p.id = y;
    //set the html
    p.innerHTML = blogtext;
    // add it to the page
    // document.getElementById("outputId").appendChild(p)
    document.body.appendChild(p)
    x = x + 1;
}
</code>```

Body:
var x = 0;

function text() {
  var blogtext = document.getElementById("Textarea").value;
  var y = "p" + String(x);
  console.log(typeof y);
  //problem
  document.createElement("p").id = y;
  //
  document.getElementById(y).innerHTML = blogtext;
  //document.write("
"+blogtext+"
");
  x = x + 1;
}

When I run this code inside an HTML file the error: Uncaught TypeError occurs, the code is supposed to create a new paragraph tag whose content is the text inputted by the user inside the text area and each paragraph would have a different id as x increases.
Sorry, I'm new to coding this is one of my school's projects.

Body:
You are not creating the element right and you are looking for the element before it is added to the page.

var x = 0;
function text() {
    var blogtext = document.getElementById("Textarea").value;
    var y = "p" + String(x);
    // create the element
    var p = document.createElement("p")
    //set the id
    p.id = y;
    //set the html
    p.innerHTML = blogtext;
    // add it to the page
    // document.getElementById("outputId").appendChild(p)
    document.body.appendChild(p)
    x = x + 1;
}


问:
Setting up Reverse DNS Records
This question is not directly programming related but I need my Server to pass Spam filters for my app to work properly. I talked to my ISP about rDNS and the guy from tech-support told me if I write an email with what they should add to my DNS record they would do that. My question:

What should I tell him to add if my hostname is "http://niklasfi.de" and my is 78.31.67.216?

Thanks für the answers. I tried searching on the Web but i only very specific anwers concerning a single ISP.

答:
reverse DNS is simply a record where the lookup is to find your host name from your IP address. So you should ask him to add a reverse IN-ADDR entry for 78.31.67.216 with your hostname.

this would be: 216.67.31.78.in-addr.arpa  niklasfi.de

These are also known as PTR records.

Hope this helps

OwnerDisplayName: niklasfi

ContentLicense: CC BY-SA 2.5

Title: Setting up Reverse DNS Records


问:
Make DIV fixed inside a scrollable DIV
Does anyone now how to make a DIV inside another DIV that is scroll-able fixed, so that no matter how much I scroll by, the DIV always stays in the same place?

Any help would be greatly appreciated.

答:
Try this out:</p>

```<code><style type="text/css">
    .scrollable {
        width: 200px;
        height: 200px;
        background: #333;
        overflow: scroll;
    }
    .fixed {
        position: absolute;
        top: 180px;
        width: 200px;
        height: 20px;
        background: #fa2;
    }
</style>
<div class="scrollable">
    im scrollable<br><br>
    im scrollable<br><br>
    im scrollable<br><br>
    im scrollable<br><br>
    im scrollable<br><br>
    im scrollable<br><br>
    <div class="fixed">and I'm fixed</div>
</div>
</code>```

Title: Make DIV fixed inside a scrollable DIV

Body:
Try this out:

<style type="text/css">
    .scrollable {
        width: 200px;
        height: 200px;
        background: #333;
        overflow: scroll;
    }
    .fixed {
        position: absolute;
        top: 180px;
        width: 200px;
        height: 20px;
        background: #fa2;
    }
</style>
<div class="scrollable">
    im scrollable<br><br>
    im scrollable<br><br>
    im scrollable<br><br>
    im scrollable<br><br>
    im scrollable<br><br>
    im scrollable<br><br>
    <div class="fixed">and I'm fixed</div>
</div>


问:
Importing a source dependency with Gradle (Kotlin DSL)
I want to import version 1.0.0 of this project https://github.com/whichdigital/ksv
as a source dependency in a Kotlin project using Gradle 6.3 with Kotlin DSL.

As the page tells me I added this into the settings.gradle.kts of my project

```<code>sourceControl {
    gitRepository(java.net.URI.create("https://github.com/whichdigital/ksv.git")) {
        producesModule("uk.co.whichdigital:ksv")
    }
}
</code>```

and using this dependency in my build.gradle.kts file:

```<code>implementation("uk.co.whichdigital:ksv:1.0.0")
</code>```

trying to import tagged version/release 1.0.0 of the KSV repo. But building my project (importing the KSV repo) fails with following expection:

```<code>TaskDependencyResolveException: Could not determine the dependencies of task ':bootJar'.
...
Caused by: DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all task dependencies for configuration ':runtimeClasspath'.
....
Caused by: ModuleVersionResolveException: Git repository at https://github.com/whichdigital/ksv.git did not contain a project publishing the specified dependency.
Required by:
    project :
</code>```

I'm actually also the person who wrote/published the KSV-repository, so if there's some configuration that I missed, I can add it in the imported or importing project.

答:
"uk.co.whichdigital:ksv:1.0.0" group id is wrong.

Can you please try

```<code>sourceControl {
   gitRepository(java.net.URI.create("https://github.com/whichdigital/ksv.git")) {
     producesModule("uk.co.whichdigital.ksv:ksv")
   }
}
</code>```

implementation("uk.co.whichdigital.ksv:ksv:1.0.0")

Body:
I want to import version 1.0.0 of this project https://github.com/whichdigital/ksv
as a source dependency in a Kotlin project using Gradle 6.3 with Kotlin DSL.

As the page tells me I added this into the settings.gradle.kts of my project

sourceControl {
    gitRepository(java.net.URI.create("https://github.com/whichdigital/ksv.git")) {
        producesModule("uk.co.whichdigital:ksv")
    }
}

and using this dependency in my build.gradle.kts file:

implementation("uk.co.whichdigital:ksv:1.0.0")

trying to import tagged version/release 1.0.0 of the KSV repo. But building my project (importing the KSV repo) fails with following expection:

TaskDependencyResolveException: Could not determine the dependencies of task ':bootJar'.
...
Caused by: DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all task dependencies for configuration ':runtimeClasspath'.
....
Caused by: ModuleVersionResolveException: Git repository at https://github.com/whichdigital/ksv.git did not contain a project publishing the specified dependency.
Required by:
    project :

I'm actually also the person who wrote/published the KSV-repository, so if there's some configuration that I missed, I can add it in the imported or importing project.

Body:
"uk.co.whichdigital:ksv:1.0.0" group id is wrong.

Can you please try

sourceControl {
   gitRepository(java.net.URI.create("https://github.com/whichdigital/ksv.git")) {
     producesModule("uk.co.whichdigital.ksv:ksv")
   }
}

implementation("uk.co.whichdigital.ksv:ksv:1.0.0")


问:
Variable declaration and assignment syntax with old and new variables
In the beow code:

```<code>func sumDigitsIter(n int) int {
    digit_sum := 0
    for n > 0 {
        n, last := split(n)
        digit_sum += last
    }
    return digit_sum
}

func split(n int) (int, int) {
    return n / 10, n % 10
}
</code>```

n cannot be a new n in syntax n, last := split(n)

Without explicit declaration of last variable, How to create a new variable last & re-assign value to existing variable n, what is the syntax?

Because in python, we do this:

```<code>def sumDigitsIter(n):
    digit_sum = 0
    while n > 0:
        n, last = split(n)
        digit_sum = digit_sum + last
    return digit_sum
</code>```

答:
Declare a new variable using a variable declaration. Do not use a short variable declaration.</p>

```<code>func sumDigitsIter(n int) int {
    digit_sum := 0
    for n >= 0 {
        var last int
        n, last = split(n)
        digit_sum += last
    }
    return digit_sum
}
</code>```

Body:
In the beow code:

func sumDigitsIter(n int) int {
    digit_sum := 0
    for n > 0 {
        n, last := split(n)
        digit_sum += last
    }
    return digit_sum
}

func split(n int) (int, int) {
    return n / 10, n % 10
}

n cannot be a new n in syntax n, last := split(n)

Without explicit declaration of last variable, How to create a new variable last & re-assign value to existing variable n, what is the syntax?

Because in python, we do this:

def sumDigitsIter(n):
    digit_sum = 0
    while n > 0:
        n, last = split(n)
        digit_sum = digit_sum + last
    return digit_sum

Body:
Declare a new variable using a variable declaration. Do not use a short variable declaration.

func sumDigitsIter(n int) int {
    digit_sum := 0
    for n >= 0 {
        var last int
        n, last = split(n)
        digit_sum += last
    }
    return digit_sum
}


答:
Both n and last are defined in a new block, so n,last:=v1,v2 will declare n and last as new variables. If you want to keep n and declare last, you have to declare it separately:

```<code>var last int
n,last=split(n)
</code>```

Title: Variable declaration and assignment syntax with old and new variables

Body:
Both n and last are defined in a new block, so n,last:=v1,v2 will declare n and last as new variables. If you want to keep n and declare last, you have to declare it separately:

var last int
n,last=split(n)


问:
Programmatically Create a Business Data Content Source
I have the need to programmatically define a business data content source in Sharepoint 2010 using C# 2010.  I've reviewed ways to do this from within Central Admin, and have seen snippets from MOSS 2007.  However, I've not located examples of doing this in SP 2010.  Can anyone steer me in the proper direction?

Thanks much for your help and guidance.

答:
Using the API

```<code>        string strURL = "http://mySiteUrl";
        SearchContext searchContext;
        using (SPSite searchSite = new SPSite(strURL))
        {
            searchContext = SearchContext.GetContext(searchSite);
        }
        Content sspContent = new Content(searchContext);
        ContentSourceCollection sspContentSources = sspContent.ContentSources;
        BusinessDataContentSource bdcs = (BusinessDataContentSource)sspContentSources.Create(typeof(BusinessDataContentSource), "MyBdcContentSource");
        bdcs.StartAddresses.Add(BusinessDataContentSource.ConstructStartAddress("Default", new Guid("00000000-0000-0000-0000-000000000000"), "LOBSystemName", "LOBSystemInstanceName"));
</code>```

Using Powershell

```<code>$searchapp = Get-SPEnterpriseSearchServiceApplication "My Search Service Application Name"
$lobSystems = @("LOBSystemName1","LOBSystemNameInstance1")
$proxyGroup = Get-SPServiceApplicationProxyGroup -default
New-SPEnterpriseSearchCrawlContentSource -name "My Content Source Name" -searchapplication $searchApp -Type Business -LOBSystemSet $lobSystems -BDCApplicationProxyGroup $proxyGroup
</code>```

Body:
Using the API

        string strURL = "http://mySiteUrl";
        SearchContext searchContext;
        using (SPSite searchSite = new SPSite(strURL))
        {
            searchContext = SearchContext.GetContext(searchSite);
        }
        Content sspContent = new Content(searchContext);
        ContentSourceCollection sspContentSources = sspContent.ContentSources;
        BusinessDataContentSource bdcs = (BusinessDataContentSource)sspContentSources.Create(typeof(BusinessDataContentSource), "MyBdcContentSource");
        bdcs.StartAddresses.Add(BusinessDataContentSource.ConstructStartAddress("Default", new Guid("00000000-0000-0000-0000-000000000000"), "LOBSystemName", "LOBSystemInstanceName"));

Using Powershell

$searchapp = Get-SPEnterpriseSearchServiceApplication "My Search Service Application Name"
$lobSystems = @("LOBSystemName1","LOBSystemNameInstance1")
$proxyGroup = Get-SPServiceApplicationProxyGroup -default
New-SPEnterpriseSearchCrawlContentSource -name "My Content Source Name" -searchapplication $searchApp -Type Business -LOBSystemSet $lobSystems -BDCApplicationProxyGroup $proxyGroup


问:
React - "'value' prop on 'input' should not be null" for some input but not others
In my React app (version 15.5.4), I am getting the following warning for an input field in one of my components:

Warning: 'value' prop on 'input' should not be null. Consider using the empty string to clear the component or 'undefined' for uncontrolled components.

referring to the following jsx:

```<code><label>Description<br />
    <input
        type="text"
        name="description"
        value={this.state.group.description}
        onChange={this.handleChange}
        maxLength="99" />
</label>
</code>```

But I am perplexed by this, because the value of this.state.group.description is set as "" in my constructor:

```<code>this.state = {
    "group": {
        "name": "",
        "description": ""
    }
}
</code>```

and furthering my consternation is the fact that another input field refers to this.state.group.name, and yet no warning is thrown:

```<code><label>Name *<br />
    <input
        type="text"
        name="name"
        value={this.state.group.name}
        onChange={this.handleChange}
        maxLength="99"
        required="required"
        autoFocus />
</label>
</code>```

Am I missing something here? As far as I can tell, I've set up the initial state of these two values as empty strings and referred to them in the same way in the two input fields, yet one throws a warning and one does not.

It's not the end of the world... the app works fine, but I'd really like to understand why this is happening and get my app running clean.

Here's the handleChange:

```<code>handleChange(event) {
    const attribute = event.target.name
    const updatedGroup = this.state.group
    updatedGroup[attribute] = event.target.value
    this.setState({"group": updatedGroup})
}
</code>```

答:
If the value as null then react 15 through the same error. So it's better the default props 'value' of an input should be an empty string in order to run react js code without warning.</p>
```<code><input type="text" value={value == null ? '' : value}/>;
</code>```

Body:
In my React app (version 15.5.4), I am getting the following warning for an input field in one of my components:

Warning: 'value' prop on 'input' should not be null. Consider using the empty string to clear the component or 'undefined' for uncontrolled components.

referring to the following jsx:

Description

    <input
        type="text"
        name="description"
        value={this.state.group.description}
        onChange={this.handleChange}
        maxLength="99" />

But I am perplexed by this, because the value of this.state.group.description is set as "" in my constructor:

this.state = {
    "group": {
        "name": "",
        "description": ""
    }
}

and furthering my consternation is the fact that another input field refers to this.state.group.name, and yet no warning is thrown:

Name *

    <input
        type="text"
        name="name"
        value={this.state.group.name}
        onChange={this.handleChange}
        maxLength="99"
        required="required"
        autoFocus />

Am I missing something here? As far as I can tell, I've set up the initial state of these two values as empty strings and referred to them in the same way in the two input fields, yet one throws a warning and one does not.

It's not the end of the world... the app works fine, but I'd really like to understand why this is happening and get my app running clean.

Here's the handleChange:

handleChange(event) {
    const attribute = event.target.name
    const updatedGroup = this.state.group
    updatedGroup[attribute] = event.target.value
    this.setState({"group": updatedGroup})
}

Body:
If the value as null then react 15 through the same error. So it's better the default props 'value' of an input should be an empty string in order to run react js code without warning.

<input type="text" value={value == null ? '' : value}/>;