问:
List attributes of an object
Is there a way to grab a list of attributes that exist on instances of a class?

```<code>class new_class():
    def __init__(self, number):
        self.multi = int(number) * 2
        self.str = str(number)

a = new_class(2)
print(', '.join(a.SOMETHING))
</code>```

The desired result is that "multi, str" will be output.  I want this to see the current attributes from various parts of a script.

答:
Using __dict__ or vars does not work because it misses out __slots__.

Using __dict__ and __slots__ does not work because it misses out __slots__ from base classes.

Using dir does not work because it includes class attributes, such as methods or properties, as well as the object attributes.

Using vars is equivalent to using __dict__.

This is the best I have:

```<code>from typing import Dict

def get_attrs( x : object ) -> Dict[str, object]:
    mro      = type( x ).mro()
    attrs    = { }
    has_dict = False
    sentinel = object()

    for klass in mro:
        for slot in getattr( klass, "__slots__", () ):
            v = getattr( x, slot, sentinel )

            if v is sentinel:
                continue

            if slot == "__dict__":
                assert not has_dict, "Multiple __dicts__?"
                attrs.update( v )
                has_dict = True
            else:
                attrs[slot] = v

    if not has_dict:
        attrs.update( getattr( x, "__dict__", { } ) )

    return attrs
</code>```

Title: List attributes of an object

Body:
Is there a way to grab a list of attributes that exist on instances of a class?

class new_class():
    def __init__(self, number):
        self.multi = int(number) * 2
        self.str = str(number)

a = new_class(2)
print(', '.join(a.SOMETHING))

The desired result is that "multi, str" will be output.  I want this to see the current attributes from various parts of a script.

LastEditorDisplayName: Roger Pate

Body:
Using __dict__ or vars does not work because it misses out __slots__.

Using __dict__ and __slots__ does not work because it misses out __slots__ from base classes.

Using dir does not work because it includes class attributes, such as methods or properties, as well as the object attributes.

Using vars is equivalent to using __dict__.

This is the best I have:

from typing import Dict

def get_attrs( x : object ) -> Dict[str, object]:
    mro      = type( x ).mro()
    attrs    = { }
    has_dict = False
    sentinel = object()

    for klass in mro:
        for slot in getattr( klass, "__slots__", () ):
            v = getattr( x, slot, sentinel )

            if v is sentinel:
                continue

            if slot == "__dict__":
                assert not has_dict, "Multiple __dicts__?"
                attrs.update( v )
                has_dict = True
            else:
                attrs[slot] = v

    if not has_dict:
        attrs.update( getattr( x, "__dict__", { } ) )

    return attrs


来源: stackexchange

问:
Redirecting the output of both stdout and stderr?
I have one program, which writes its output to stderr and it also runs a executable internally
which writes to stdout. I want to redirect the output of both to the same file using redirection operator something like "./a.out 2> output.txt", but this redirects the stderr, How to specify stdout also here.</p>

答:
Or simply</p>

```<code>./a.out &> output.txt
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Or simply

./a.out &> output.txt

ContentLicense: CC BY-SA 3.0


问:
How can i make flat button size as it's child size
i want to make button size like it's text child size
i will attach  example photo , and i'll attach the code that i write

this is my code :

```<code>        Expanded(
        child: FlatButton(
          minWidth: double.infinity,
          height: 20,
          child: FlatButton(
            onPressed: (){},
            color: Colors.grey,
           shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10) ,
            ),
            child: Text(
              'SHOP' ,
              style: TextStyle(
                color: Colors.blueAccent,
                fontWeight: FontWeight.bold ,
                fontSize: 16 ,
              ),
</code>```

and this is the photo
photo

答:
```<code>GestureDetector{
onTap:(){},
child:Container(
child:Material(
shape:RoundRectangleBorder()
child:Center(
child:'Text')))
}
</code>```

You can use properties of Material widget this way. If you don't provide height to container it will adjust to the child size. i.e. text size

ContentLicense: CC BY-SA 4.0

Body:
i want to make button size like it's text child size
i will attach  example photo , and i'll attach the code that i write

this is my code :

        Expanded(
        child: FlatButton(
          minWidth: double.infinity,
          height: 20,
          child: FlatButton(
            onPressed: (){},
            color: Colors.grey,
           shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10) ,
            ),
            child: Text(
              'SHOP' ,
              style: TextStyle(
                color: Colors.blueAccent,
                fontWeight: FontWeight.bold ,
                fontSize: 16 ,
              ),

and this is the photo
photo

Body:
GestureDetector{
onTap:(){},
child:Container(
child:Material(
shape:RoundRectangleBorder()
child:Center(
child:'Text')))
}

You can use properties of Material widget this way. If you don't provide height to container it will adjust to the child size. i.e. text size


问:
Stream controller not registering sink event flutter
I am using the bloc pattern to handle state in my app. However, sinking data into my stream is not working. I have a formfield and a button that returns null if the text field is empty.
Here is my bloc

```<code>class SavingsCategoryBloc {
    final amount = PublishSubject<int>();

    Stream<int> get amountStream => amount.stream;
    Function(int) get amountSink => amount.sink.add;
}
</code>```

This is my screen

```<code>class _StartSavingPageState extends State<StartSavingPage> {
    final SavingsCategoryBloc bloc = SavingsCategoryBloc();
    ...

    @override
    Widget build(BuildContext context) {
    ...
     Container(
             padding: EdgeInsets.symmetric(
             horizontal: 15.0, vertical: 15.0),
             child: TextField(
             onChanged: (String value) => bloc.amountSink,
                 keyboardType: TextInputType.number,
                 controller: amountController,
                 decoration: InputDecoration(
                    labelText: 'AMOUNT TO SAVE ',
                    labelStyle: TextStyle(
                    fontFamily: 'Montserrat',
                    fontSize: 2.1 * SizeConfig.textMultiplier,
                    color: Colors.grey),
                    focusedBorder: UnderlineInputBorder(
                       borderSide:
                        BorderSide(color: Colors.purple))),
                      ),
                    ),

                 ....

                Container(
                      padding: EdgeInsets.symmetric(
                          horizontal: 15.0, vertical: 15.0),
                      decoration: BoxDecoration(
                          borderRadius:
                              BorderRadius.all(Radius.circular(25.0))),
                      width: double.infinity,
                      child: StreamBuilder(
                          stream: bloc.amountStream,
                          builder: (context, snapshot) {
                            return RaisedButton(
                              elevation: 5.0,
                              onPressed: snapshot.hasData
                                  ? () => print('hi')
                                  : null,
                              padding: EdgeInsets.all(15.0),
                              color: Colors.purple,
                              child: Text(
                                'SAVE',
                                style: TextStyle(
                                  color: Colors.white,
                                  letterSpacing: 1.5,
                                  fontSize: 18.0,
                                  fontWeight: FontWeight.bold,
                                  fontFamily: 'OpenSans',
                                ),
                              ),
                            );
                          }),
                    )
</code>```

The button remains disabled even when the formfield is not empty.

答:
You was not adding data in stream as well as you was not using streamcontroller.

Following Example clear your idea.

```<code>import 'dart:async';
import 'package:flutter/material.dart';
import 'package:rxdart/subjects.dart';

class SavingsCategoryBloc {
  final _counterController = PublishSubject<int>();

  Stream<int> get amountStream => _counterController.stream;
  Sink<int> get amountSink => _counterController.sink;

  dispose() {
    _counterController.close();
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(body: HomeWidget()),
    );
  }
}

class HomeWidget extends StatefulWidget {
  const HomeWidget({Key key}) : super(key: key);

  @override
  _HomeWidgetState createState() => _HomeWidgetState();
}

class _HomeWidgetState extends State<HomeWidget> {
  SavingsCategoryBloc bloc = SavingsCategoryBloc();

  @override
  void dispose() {
    bloc.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          TextField(
            onChanged: (String value) => bloc.amountSink.add(int.parse(value)),
            keyboardType: TextInputType.number,
            decoration: InputDecoration(
                labelText: 'AMOUNT TO SAVE ',
                labelStyle:
                    TextStyle(fontFamily: 'Montserrat', color: Colors.grey),
                focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Colors.purple))),
          ),
          SizedBox(
            height: 20,
          ),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 15.0),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(25.0))),
            width: double.infinity,
            child: StreamBuilder(
                stream: bloc.amountStream,
                //    initialData: "",
                builder: (context, snapshot) {
                  return RaisedButton(
                    elevation: 5.0,
                    onPressed: snapshot.hasData ? () => print('hi') : null,
                    padding: EdgeInsets.all(15.0),
                    color: Colors.purple,
                    child: Text(
                      'SAVE',
                      style: TextStyle(
                        color: Colors.white,
                        letterSpacing: 1.5,
                        fontSize: 18.0,
                        fontWeight: FontWeight.bold,
                        fontFamily: 'OpenSans',
                      ),
                    ),
                  );
                }),
          )
        ],
      ),
    );
  }
}
</code>```

Body:
I am using the bloc pattern to handle state in my app. However, sinking data into my stream is not working. I have a formfield and a button that returns null if the text field is empty.
Here is my bloc

class SavingsCategoryBloc {
    final amount = PublishSubject<int>();

    Stream<int> get amountStream => amount.stream;
    Function(int) get amountSink => amount.sink.add;
}

This is my screen

class _StartSavingPageState extends State<StartSavingPage> {
    final SavingsCategoryBloc bloc = SavingsCategoryBloc();
    ...

    @override
    Widget build(BuildContext context) {
    ...
     Container(
             padding: EdgeInsets.symmetric(
             horizontal: 15.0, vertical: 15.0),
             child: TextField(
             onChanged: (String value) => bloc.amountSink,
                 keyboardType: TextInputType.number,
                 controller: amountController,
                 decoration: InputDecoration(
                    labelText: 'AMOUNT TO SAVE ',
                    labelStyle: TextStyle(
                    fontFamily: 'Montserrat',
                    fontSize: 2.1 * SizeConfig.textMultiplier,
                    color: Colors.grey),
                    focusedBorder: UnderlineInputBorder(
                       borderSide:
                        BorderSide(color: Colors.purple))),
                      ),
                    ),

                 ....

                Container(
                      padding: EdgeInsets.symmetric(
                          horizontal: 15.0, vertical: 15.0),
                      decoration: BoxDecoration(
                          borderRadius:
                              BorderRadius.all(Radius.circular(25.0))),
                      width: double.infinity,
                      child: StreamBuilder(
                          stream: bloc.amountStream,
                          builder: (context, snapshot) {
                            return RaisedButton(
                              elevation: 5.0,
                              onPressed: snapshot.hasData
                                  ? () => print('hi')
                                  : null,
                              padding: EdgeInsets.all(15.0),
                              color: Colors.purple,
                              child: Text(
                                'SAVE',
                                style: TextStyle(
                                  color: Colors.white,
                                  letterSpacing: 1.5,
                                  fontSize: 18.0,
                                  fontWeight: FontWeight.bold,
                                  fontFamily: 'OpenSans',
                                ),
                              ),
                            );
                          }),
                    )

The button remains disabled even when the formfield is not empty.

Body:
You was not adding data in stream as well as you was not using streamcontroller.

Following Example clear your idea.

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:rxdart/subjects.dart';

class SavingsCategoryBloc {
  final _counterController = PublishSubject<int>();

  Stream<int> get amountStream => _counterController.stream;
  Sink<int> get amountSink => _counterController.sink;

  dispose() {
    _counterController.close();
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(body: HomeWidget()),
    );
  }
}

class HomeWidget extends StatefulWidget {
  const HomeWidget({Key key}) : super(key: key);

  @override
  _HomeWidgetState createState() => _HomeWidgetState();
}

class _HomeWidgetState extends State<HomeWidget> {
  SavingsCategoryBloc bloc = SavingsCategoryBloc();

  @override
  void dispose() {
    bloc.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          TextField(
            onChanged: (String value) => bloc.amountSink.add(int.parse(value)),
            keyboardType: TextInputType.number,
            decoration: InputDecoration(
                labelText: 'AMOUNT TO SAVE ',
                labelStyle:
                    TextStyle(fontFamily: 'Montserrat', color: Colors.grey),
                focusedBorder: UnderlineInputBorder(
                    borderSide: BorderSide(color: Colors.purple))),
          ),
          SizedBox(
            height: 20,
          ),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 15.0),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(25.0))),
            width: double.infinity,
            child: StreamBuilder(
                stream: bloc.amountStream,
                //    initialData: "",
                builder: (context, snapshot) {
                  return RaisedButton(
                    elevation: 5.0,
                    onPressed: snapshot.hasData ? () => print('hi') : null,
                    padding: EdgeInsets.all(15.0),
                    color: Colors.purple,
                    child: Text(
                      'SAVE',
                      style: TextStyle(
                        color: Colors.white,
                        letterSpacing: 1.5,
                        fontSize: 18.0,
                        fontWeight: FontWeight.bold,
                        fontFamily: 'OpenSans',
                      ),
                    ),
                  );
                }),
          )
        ],
      ),
    );
  }
}


问:
Why does lua 5.1 interpret certain integers incorrectly?
Lua 5.1 appears interpret many perfectly valid 64b integers as

```<code>1,805,996,217,335,808,768
</code>```

while the largest signed valid 64b integer is

```<code>9,223,372,036,854,775,807
</code>```

Here is an example of the unfortunate output:

```<code>Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio
> return 1805996217335808768 == 1805996217335808804
true
> return 1805996217335808768 == 1805996217335808805
true
> return 1805996217335808768 == 1805996217335808806
true
> return 1805996217335808768 == 1805996217335808769
true
> return 1805996217335808768 == 1805996217335808767
true
</code>```

One would expect to see a false everywhere there is a true here.

Edit (flagged as duplicate):

This is not a duplicate of this question because you cannot compile Lua 5.1 to handle 64b integers.

答:
Lua 5.1 uses double type with precision of 53 bits.

Only first 53 bits of number will be stored in double fraction part.
Max effective integer is 9007199254740991. If number is greater as 9007199254740991, last bits until 53 bits will be zeroed.

54 bits number:

```<code>18014398509481983 = 111111111111111111111111111111111111111111111111111111b
</code>```

internally will be stored as

```<code>18014398509481982 = 111111111111111111111111111111111111111111111111111110b
</code>```

as only first 53 bits are used, so both are equal.

Body:
Lua 5.1 appears interpret many perfectly valid 64b integers as

1,805,996,217,335,808,768

while the largest signed valid 64b integer is

9,223,372,036,854,775,807

Here is an example of the unfortunate output:

Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio
> return 1805996217335808768 == 1805996217335808804
true
> return 1805996217335808768 == 1805996217335808805
true
> return 1805996217335808768 == 1805996217335808806
true
> return 1805996217335808768 == 1805996217335808769
true
> return 1805996217335808768 == 1805996217335808767
true

One would expect to see a false everywhere there is a true here.

Edit (flagged as duplicate):

This is not a duplicate of this question because you cannot compile Lua 5.1 to handle 64b integers.

Body:
Lua 5.1 uses double type with precision of 53 bits.

Only first 53 bits of number will be stored in double fraction part.
Max effective integer is 9007199254740991. If number is greater as 9007199254740991, last bits until 53 bits will be zeroed.

54 bits number:

18014398509481983 = 111111111111111111111111111111111111111111111111111111b

internally will be stored as

18014398509481982 = 111111111111111111111111111111111111111111111111111110b

as only first 53 bits are used, so both are equal.


问:
not able to create Java Object from Json having double quote in value
I have same query. My JSON is as below.

```<code>String json="{ "credentials": { "password": "Password"123", "emailAddress": "skylineadmin@gmail.com" }, "clientTimeMs": 1582006455421, "callerRole": 0 }"
</code>```

key = password and value is "Password"123" it contains " (double quote).. I am not able to create a java object from this json as it is invalidated.

```<code>Gson gson = new Gson();
gson.fromJson(json, PasswordResetDetails.java);
</code>```

Above code snippet is not Working.

答:
If you are doing this for learning / testing purpose all you need to do is escaping the double quote using :

```<code>String json="{ "credentials": { "password": "Password\"123", "emailAddress": "skylineadmin@gmail.com" }, "clientTimeMs": 1582006455421, "callerRole": 0 }"
</code>```

If this is a real scenario then I would like to suggest to change the source in order to make sure it provides valid JSON.

There are countless possibilities to check if your JSON is valid (JSON linting), here's one.

Body:
I have same query. My JSON is as below.

String json="{ "credentials": { "password": "Password"123", "emailAddress": "skylineadmin@gmail.com" }, "clientTimeMs": 1582006455421, "callerRole": 0 }"

key = password and value is "Password"123" it contains " (double quote).. I am not able to create a java object from this json as it is invalidated.

Gson gson = new Gson();
gson.fromJson(json, PasswordResetDetails.java);

Above code snippet is not Working.

Body:
If you are doing this for learning / testing purpose all you need to do is escaping the double quote using :

String json="{ "credentials": { "password": "Password\"123", "emailAddress": "skylineadmin@gmail.com" }, "clientTimeMs": 1582006455421, "callerRole": 0 }"

If this is a real scenario then I would like to suggest to change the source in order to make sure it provides valid JSON.

There are countless possibilities to check if your JSON is valid (JSON linting), here's one.


问:
numpy array for float values within range
With regards to efficiency, how can we create a large numpy array where the values are float numbers within a specific range.

For example, for a 1-D numpy array of fixed size where the values are between 0 and 200,000,000.00 (i.e. values in [0, 200,000,000.00]), I can create the array using the smallest data type for floats (float16) and then validate any new value (from user input) before inserting it to the array:

```<code>import numpy as np

a = np.empty(shape=(1000,), dtype=np.float16))
pos = 0

new_value = input('Enter new value: ')

# validate
new_value = round(new_value, 2)
if new_value in np.arange(0.00, 200000000.00, 0.01):
    # fill in new value
    a[pos] = new_value
    pos = pos + 1
</code>```

The question is, can we enforce the new_value validity (in terms of the already-known minimum/maximum values and number of decimals) based on the dtype of the array?

In other words, the fact that we know the range and number of decimals on the time of creating the array, does this gives us any opportunity to (more) efficiently insert valid values in the array?

答:
I am a bit confused how your code even run because it's not working as it is presented here.

It is also a bit unclear why you want to append new values to an empty array you have created beforehand. Did you meant to fill the created array with the new incoming values instead of appending?

```<code>np.arange(0.00, 200000000.00, 0.01)
</code>```

This line is causing problems as it creates a huge array with values leading to a MemoryError in my environment just to check if the new_value is in a certain range.

Extending my comment and fixing issues with your code my solution would look like

```<code>import numpy as np

max_value =  200000000
arr = np.empty(shape=(1000,), dtype=np.float16)

new_value = float(input('Enter new value: ')) # More checks might be useful if input is numeric

# validate
if 0 <= new_value <= max_value:
    new_value = round(new_value, 2) # round only if range criterion is fulfilled
    arr = np.append(arr, new_value) # in case you really want to append your value
</code>```

Body:
With regards to efficiency, how can we create a large numpy array where the values are float numbers within a specific range.

For example, for a 1-D numpy array of fixed size where the values are between 0 and 200,000,000.00 (i.e. values in [0, 200,000,000.00]), I can create the array using the smallest data type for floats (float16) and then validate any new value (from user input) before inserting it to the array:

import numpy as np

a = np.empty(shape=(1000,), dtype=np.float16))
pos = 0

new_value = input('Enter new value: ')

# validate
new_value = round(new_value, 2)
if new_value in np.arange(0.00, 200000000.00, 0.01):
    # fill in new value
    a[pos] = new_value
    pos = pos + 1

The question is, can we enforce the new_value validity (in terms of the already-known minimum/maximum values and number of decimals) based on the dtype of the array?

In other words, the fact that we know the range and number of decimals on the time of creating the array, does this gives us any opportunity to (more) efficiently insert valid values in the array?

Body:
I am a bit confused how your code even run because it's not working as it is presented here.

It is also a bit unclear why you want to append new values to an empty array you have created beforehand. Did you meant to fill the created array with the new incoming values instead of appending?

np.arange(0.00, 200000000.00, 0.01)

This line is causing problems as it creates a huge array with values leading to a MemoryError in my environment just to check if the new_value is in a certain range.

Extending my comment and fixing issues with your code my solution would look like

import numpy as np

max_value =  200000000
arr = np.empty(shape=(1000,), dtype=np.float16)

new_value = float(input('Enter new value: ')) # More checks might be useful if input is numeric

# validate
if 0 <= new_value <= max_value:
    new_value = round(new_value, 2) # round only if range criterion is fulfilled
    arr = np.append(arr, new_value) # in case you really want to append your value


问:
How to add additional paths to baseurl using Javascript
I have a base URL

```<code>url= 'www.baseUrl.com'
</code>```

I have an array of my paths Paths = [path1,path2,path3]

how do i create something like perhaps i need to do a loop?

```<code>www.baseUrl.com/path1
www.baseUrl.com/path2
www.baseUrl.com/path3
</code>```

答:
I think you might want something like this:</p>

```<code>let url = 'www.baseUrl.com';

const paths = [
    'path1',
    'path2',
    'path3',
];

function getFullUrlByPath(path) {
    return url + '/' + paths[path++];
}

getFullUrlByPath(1);
// Will return www.baseUrl.com/path1
</code>```

Body:
I have a base URL

url= 'www.baseUrl.com'

I have an array of my paths Paths = [path1,path2,path3]

how do i create something like perhaps i need to do a loop?

www.baseUrl.com/path1
www.baseUrl.com/path2
www.baseUrl.com/path3

Body:
I think you might want something like this:

let url = 'www.baseUrl.com';

const paths = [
    'path1',
    'path2',
    'path3',
];

function getFullUrlByPath(path) {
    return url + '/' + paths[path++];
}

getFullUrlByPath(1);
// Will return www.baseUrl.com/path1


问:
PHP SOAP request not populating XML parameter
I am trying to make a simple SOAP call:

```<code>$aHTTP['http']['header'] =  "Content-Type: text/xml; charset=utf-8";
$aHTTP['http']['header'] =  "SOAPAction: http://url.com/LoginAndGetStudentsData";
$context = stream_context_create($aHTTP);
$options = array(
    'soap_version'=> SOAP_1_1,
    'trace'=> true,
    'exceptions'=> true,                // disable exceptions
    'features'=> SOAP_SINGLE_ELEMENT_ARRAYS,
    'encoding'=> 'UTF-8',
    'cache_wsdl'=>WSDL_CACHE_NONE,
    'stream_context=>'=>$context,
);
$client  = new SoapClient($baseURL."?wsdl", $options);
$response = $client->LoginAndGetStudentsData($xmlstring2);
</code>```

When I check the $xmlstring2 variable, I see it is indeed populated by my XML string:

```<code><username>****</username>
<password>****</password>
<p><OrbitId>1</OrbitId><HasLessons xsi:nil="true"/><HasLearningPrograms xsi:nil="true"/><ContextYear>2020</ContextYear><IdNumber xsi:nil="true"/><FillExtraFields>true</FillExtraFields><FromUpdateDate xsi:nil="true"/><ToUpdateDate xsi:nil="true"/><IncludeDivisionInfo>true</IncludeDivisionInfo><IncludeProgramInfo>true</IncludeProgramInfo><IncludeAccumulatedAcademicPoints>false</IncludeAccumulatedAcademicPoints><IncludeMoneyBalanceInfo>false</IncludeMoneyBalanceInfo><IncludePassportImage>false</IncludePassportImage><IncludeSpecializationData>true</IncludeSpecializationData><IncludeWsProgramInfoDetails>false</IncludeWsProgramInfoDetails><IncludeRegistraionRoadMaps>false</IncludeRegistraionRoadMaps><FromStudentCreationDate xsi:nil="true"/><ToStudentCreationDate xsi:nil="true"/><FromStudentLearningProgramUpdateDate xsi:nil="true"/><ToStudentLearningProgramUpdateDate xsi:nil="true"/><FromRegistraionRoadMapUpdateDate xsi:nil="true"/><ToRegistraionRoadMapUpdateDate xsi:nil="true"/></p>
</code>```

However, when I use:

```<code>die("Request: ".$client->__getLastRequest()."\nEnd Request");
</code>```

I get the following:

```<code><?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://url.com/"><SOAP-ENV:Body><ns1:LoginAndGetStudentsData/></SOAP-ENV:Body></SOAP-ENV:Envelope>
</code>```

The XML is not populated in the SOAP call.
I checked the documentation, but I can't fine what I'm getting wrong.
These are the WSDL functions:

```<code><wsdl:definitions xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:tns="http://url.net/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://url.net/">
<script/>
<wsdl:types>
<s:schema elementFormDefault="qualified" targetNamespace="http://url.net/">
<s:element name="LoginAndGetStudentsData">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="username" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="password" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="p" type="tns:StudentRequestParameters"/>
</s:sequence>
</s:complexType>
</s:element>
<s:complexType name="StudentRequestParameters">
<s:sequence>
<s:element minOccurs="1" maxOccurs="1" name="OrbitId" nillable="true" type="s:int"/>
<s:element minOccurs="0" maxOccurs="1" name="OrbitIds" type="tns:ArrayOfInt"/>
<s:element minOccurs="1" maxOccurs="1" name="HasLessons" nillable="true" type="s:boolean"/>
<s:element minOccurs="1" maxOccurs="1" name="HasLearningPrograms" nillable="true" type="s:boolean"/>
<s:element minOccurs="1" maxOccurs="1" name="ContextYear" nillable="true" type="s:int"/>
<s:element minOccurs="1" maxOccurs="1" name="IdNumber" nillable="true" type="s:int"/>
<s:element minOccurs="1" maxOccurs="1" name="FillExtraFields" nillable="true" type="s:boolean"/>
<s:element minOccurs="1" maxOccurs="1" name="FromUpdateDate" nillable="true" type="s:dateTime"/>
<s:element minOccurs="1" maxOccurs="1" name="ToUpdateDate" nillable="true" type="s:dateTime"/>
<s:element minOccurs="1" maxOccurs="1" name="IncludeDivisionInfo" nillable="true" type="s:boolean"/>
<s:element minOccurs="1" maxOccurs="1" name="IncludeProgramInfo" nillable="true" type="s:boolean"/>
<s:element minOccurs="1" maxOccurs="1" name="IncludeAccumulatedAcademicPoints" type="s:boolean"/>
<s:element minOccurs="1" maxOccurs="1" name="IncludeMoneyBalanceInfo" nillable="true" type="s:boolean"/>
<s:element minOccurs="1" maxOccurs="1" name="IncludePassportImage" nillable="true" type="s:boolean"/>
<s:element minOccurs="1" maxOccurs="1" name="IncludeSpecializationData" nillable="true" type="s:boolean"/>
<s:element minOccurs="0" maxOccurs="1" name="OtherId" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="FullNameContains" type="s:string"/>
<s:element minOccurs="1" maxOccurs="1" name="IncludeWsProgramInfoDetails" type="s:boolean"/>
<s:element minOccurs="1" maxOccurs="1" name="IncludeRegistraionRoadMaps" nillable="true" type="s:boolean"/>
<s:element minOccurs="1" maxOccurs="1" name="FromStudentCreationDate" nillable="true" type="s:dateTime"/>
<s:element minOccurs="1" maxOccurs="1" name="ToStudentCreationDate" nillable="true" type="s:dateTime"/>
<s:element minOccurs="1" maxOccurs="1" name="FromStudentLearningProgramUpdateDate" nillable="true" type="s:dateTime"/>
<s:element minOccurs="1" maxOccurs="1" name="ToStudentLearningProgramUpdateDate" nillable="true" type="s:dateTime"/>
<s:element minOccurs="1" maxOccurs="1" name="FromRegistraionRoadMapUpdateDate" nillable="true" type="s:dateTime"/>
<s:element minOccurs="1" maxOccurs="1" name="ToRegistraionRoadMapUpdateDate" nillable="true" type="s:dateTime"/>
<s:element minOccurs="0" maxOccurs="1" name="Phone" type="s:string"/>
</s:sequence>
</s:complexType>
</code>```

答:
Without complete WSDL I think you should try:

```<code>$response = $client->LoginAndGetStudentsData(['username'=>'foo','password'=>'bar', 'p'=>[]]);
</code>```

Then look at

```<code>die("Request: ".$client->__getLastRequest()."\nEnd Request");
</code>```

and see if those parameters are populated but be aware that it might actually require proper structure of third parameter to properly encode it. Note minOccurs="1" in that wsdl and prepare p as regular php array. It should work. If not then read about php soal __soapCall + array of SoapParam but that should not be necessary.

Body:
I am trying to make a simple SOAP call:

$aHTTP['http']['header'] =  "Content-Type: text/xml; charset=utf-8";
$aHTTP['http']['header'] =  "SOAPAction: http://url.com/LoginAndGetStudentsData";
$context = stream_context_create($aHTTP);
$options = array(
    'soap_version'=> SOAP_1_1,
    'trace'=> true,
    'exceptions'=> true,                // disable exceptions
    'features'=> SOAP_SINGLE_ELEMENT_ARRAYS,
    'encoding'=> 'UTF-8',
    'cache_wsdl'=>WSDL_CACHE_NONE,
    'stream_context=>'=>$context,
);
$client  = new SoapClient($baseURL."?wsdl", $options);
$response = $client->LoginAndGetStudentsData($xmlstring2);

When I check the $xmlstring2 variable, I see it is indeed populated by my XML string:

<username>****</username>
<password>****</password>

<OrbitId>1</OrbitId><HasLessons xsi:nil="true"/><HasLearningPrograms xsi:nil="true"/><ContextYear>2020</ContextYear><IdNumber xsi:nil="true"/><FillExtraFields>true</FillExtraFields><FromUpdateDate xsi:nil="true"/><ToUpdateDate xsi:nil="true"/><IncludeDivisionInfo>true</IncludeDivisionInfo><IncludeProgramInfo>true</IncludeProgramInfo><IncludeAccumulatedAcademicPoints>false</IncludeAccumulatedAcademicPoints><IncludeMoneyBalanceInfo>false</IncludeMoneyBalanceInfo><IncludePassportImage>false</IncludePassportImage><IncludeSpecializationData>true</IncludeSpecializationData><IncludeWsProgramInfoDetails>false</IncludeWsProgramInfoDetails><IncludeRegistraionRoadMaps>false</IncludeRegistraionRoadMaps><FromStudentCreationDate xsi:nil="true"/><ToStudentCreationDate xsi:nil="true"/><FromStudentLearningProgramUpdateDate xsi:nil="true"/><ToStudentLearningProgramUpdateDate xsi:nil="true"/><FromRegistraionRoadMapUpdateDate xsi:nil="true"/><ToRegistraionRoadMapUpdateDate xsi:nil="true"/>

However, when I use:

die("Request: ".$client->__getLastRequest()."\nEnd Request");

I get the following:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://url.com/"><SOAP-ENV:Body><ns1:LoginAndGetStudentsData/></SOAP-ENV:Body></SOAP-ENV:Envelope>

The XML is not populated in the SOAP call.
I checked the documentation, but I can't fine what I'm getting wrong.
These are the WSDL functions:

<wsdl:definitions xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:tns="http://url.net/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://url.net/">

Body:
Without complete WSDL I think you should try:

$response = $client->LoginAndGetStudentsData(['username'=>'foo','password'=>'bar', 'p'=>[]]);

Then look at

die("Request: ".$client->__getLastRequest()."\nEnd Request");

and see if those parameters are populated but be aware that it might actually require proper structure of third parameter to properly encode it. Note minOccurs="1" in that wsdl and prepare p as regular php array. It should work. If not then read about php soal __soapCall + array of SoapParam but that should not be necessary.


问:
How to show react variable values in loop in table td tag
i use axios to get values, now i want to display the values in td tag in a loop how to execute it.

my code is :

```<code>let apiUrl = "http://api_url_here";
axios.get(apiUrl, {headers: headers})
  .then((response) => {
    console.log(response.data[0].provider.firstName);
    //console.log(token);[0]
  })
</code>```

My td code is:

```<code><tr>
  <td className="font-weight-medium"> <img className="logo" src={jessica} alt="pam-logo" /> </td>
  <td>jessicajames@gmail.com </td>
  <td>(012)-876789876</td>
  <td>Family Physician</td>
  <td>23145655</td>
  <td>Mountain view,Ave</td>
  <td><Icon icon={editIcon} width="20px"/>  <Icon icon={deleteIcon} width="20px"/></td>
</tr>
</code>```

I need that response.data[0].provider.firstName in 1st td and correspondingly the same for all and it should be in loop to get next iteration.

答:
If response.data is the list with your table content, add this to your render() method:

return response.data.map((item, index) => {

      {item.foo}
      {item.bar}
      ...

});
```

Body:
i use axios to get values, now i want to display the values in td tag in a loop how to execute it.

my code is :

let apiUrl = "http://api_url_here";
axios.get(apiUrl, {headers: headers})
  .then((response) => {
    console.log(response.data[0].provider.firstName);
    //console.log(token);[0]
  })

My td code is:

  jessicajames@gmail.com
  (012)-876789876
  Family Physician
  23145655
  Mountain view,Ave
  <Icon icon={editIcon} width="20px"/>  <Icon icon={deleteIcon} width="20px"/>

I need that response.data[0].provider.firstName in 1st td and correspondingly the same for all and it should be in loop to get next iteration.

Body:
If response.data is the list with your table content, add this to your render() method:

return response.data.map((item, index) => {
   <tr key={index}>
      <td>{item.foo}</td>
      <td>{item.bar}</td>
      ...
   </tr>
});


问:
Upload APK with Python and Selenium to web page interpreted as URL
I want to upload a .apk file to Kaspersky's online scanner by using selenium and Python. However, the file is interpreted as a URL when I use selenium's send_keys() method.

The relevant HTML looks like this:

```<code>    <div class="container">
      <div class="div-field-home">
        <div class="div-hero-scanner-wrapper">
<!-- ======= -->

          <div class="acenter pdv-1x" id="drop-area">
            <form action="" id="SendForm">
              <div class="d-inline">
                  <div class="tags-inline amiddle file-load-group">
                      <input id="txt-input-01" type="text" class="small" placeholder="Drag-and-drop a file or paste a link here" maxlength="2000" txtvalue="">
                      <a href="#" class="d-inline bt-attach bt-attach-file"><img src="/resources/img/attach.png" class="w-100" alt=""><img src="/resources/img/attach_inactive.png" class="w-100" alt=""></a>
                      <a href="#" class="btn upper small bt-attach-res bt-attach-file">Attach file</a>
                      <a href="#" class="btn upper clr-ff bg-02 small bt-check bt-disable" analytics-event="StartScan.Click">Scan</a>
                  </div>
</code>```

Code:

```<code>kaspersky_base_URL = "https://virusdesk.kaspersky.com/#"

driver = webdriver.Firefox()
driver.get(kaspersky_base_URL)
file = "/home/user/filepath"

driver.implicitly_wait(30)

input = driver.find_element_by_id("txt-input-01")
input.send_keys(file)

driver.implicitly_wait(60)

links = driver.find_elements_by_xpath('//a[contains(@href, "#")]')
for elem in links:
    if 'SCAN' in elem.text:
        elem.click()

</code>```

I have also tried to change the input type=text to type=file. It is changed, but the same error keeps occurring.
I think that the problem might be that one has to click on the file attack link for the text to be interpreted as a file. But not completely sure.

Any help would be appreciated!

答:
Seems you were close enough. To upload a .apk file to Kaspersky's online scanner using Selenium and python you need to induce WebDriverWait for the element_to_be_clickable() while:

Dragging and Dropping the apk file from your local system or

Providing the link of the apk url.

Following the second method of providing the link of the apk url, you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

```<code>driver.get('https://virusdesk.kaspersky.com/#')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#txt-input-01"))).send_keys("https://drive.google.com/file/d/1ZspxTOnQpqcuvI0rDAkBsB_Y-gRzIEaq/view/GranthamBuild14022020.apk")
</code>```

Using XPATH:

```<code>driver.get('https://virusdesk.kaspersky.com/#')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='txt-input-01']"))).send_keys("https://drive.google.com/file/d/1ZspxTOnQpqcuvI0rDAkBsB_Y-gRzIEaq/view/GranthamBuild14022020.apk")
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Browser Snapshot:

Body:
I want to upload a .apk file to Kaspersky's online scanner by using selenium and Python. However, the file is interpreted as a URL when I use selenium's send_keys() method.

The relevant HTML looks like this:

            <form action="" id="SendForm">

                      <input id="txt-input-01" type="text" class="small" placeholder="Drag-and-drop a file or paste a link here" maxlength="2000" txtvalue="">

                      Attach file
                      Scan

Code:

kaspersky_base_URL = "https://virusdesk.kaspersky.com/#"

driver = webdriver.Firefox()
driver.get(kaspersky_base_URL)
file = "/home/user/filepath"

driver.implicitly_wait(30)

input = driver.find_element_by_id("txt-input-01")
input.send_keys(file)

driver.implicitly_wait(60)

links = driver.find_elements_by_xpath('//a[contains(@href, "#")]')
for elem in links:
    if 'SCAN' in elem.text:
        elem.click()

I have also tried to change the input type=text to type=file. It is changed, but the same error keeps occurring.
I think that the problem might be that one has to click on the file attack link for the text to be interpreted as a file. But not completely sure.

Any help would be appreciated!

Body:
Seems you were close enough. To upload a .apk file to Kaspersky's online scanner using Selenium and python you need to induce WebDriverWait for the element_to_be_clickable() while:

Dragging and Dropping the apk file from your local system or

Providing the link of the apk url.

Following the second method of providing the link of the apk url, you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

driver.get('https://virusdesk.kaspersky.com/#')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#txt-input-01"))).send_keys("https://drive.google.com/file/d/1ZspxTOnQpqcuvI0rDAkBsB_Y-gRzIEaq/view/GranthamBuild14022020.apk")

Using XPATH:

driver.get('https://virusdesk.kaspersky.com/#')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='txt-input-01']"))).send_keys("https://drive.google.com/file/d/1ZspxTOnQpqcuvI0rDAkBsB_Y-gRzIEaq/view/GranthamBuild14022020.apk")

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Browser Snapshot:


问:
"Activemq not found" error after running custom Docker image
We have a legacy application that I am trying to dockerize. The jar of the application has both the application and an activemq bundled together. (We cannot change the way it is built). And has certain installation steps. I created the following initial Dockerfile for this however I am facing an issue (mentioned after the Dockerfile) when I run the image.

The Dockerfile looks like this :

```<code>FROM registry:4000/openjdk:8-jre-alpine

RUN addgroup -S appuser && adduser -S -G appuser appuser

ADD ./fe.jar /home/appuser

RUN chmod +x /home/appuser/fe.jar \
&& chown appuser:appuser /home/appuser/fe.jar

USER appuser

RUN ["java", "-jar", "/home/appuser/fe.jar", "-i"]

WORKDIR /home/appuser/fe/activemq/bin

CMD ["/bin/sh", "-c", "activemq"]
</code>```

The RUN command extracts the application and the activemq at the location into folder called fe.

The WORKDIR seems to be setting the working directly to activemq/bin. I confirmed this by using sh script which triggers when the image is run. In the sh script I trigger an ls and pwd command to see the contents and the location.

However when I run the image which triggers the CMD command I get the error that :

```<code>/bin/sh: activemq: not found
</code>```

What can be the possible issue here?

答:
Found the problem. The activemq script starts with #!/bin/bash and I am trying to run it using sh. I need to first install bash in the image and then run the activemq script using one.
I got the hint from this answer : docker alpine /bin/sh script.sh not found
Now it moved ahead however the container dies after running immediately. Not sure what the issue is. Doesn't even give any error.</p>

Body:
We have a legacy application that I am trying to dockerize. The jar of the application has both the application and an activemq bundled together. (We cannot change the way it is built). And has certain installation steps. I created the following initial Dockerfile for this however I am facing an issue (mentioned after the Dockerfile) when I run the image.

The Dockerfile looks like this :

FROM registry:4000/openjdk:8-jre-alpine

RUN addgroup -S appuser && adduser -S -G appuser appuser

ADD ./fe.jar /home/appuser

RUN chmod +x /home/appuser/fe.jar \
&& chown appuser:appuser /home/appuser/fe.jar

USER appuser

RUN ["java", "-jar", "/home/appuser/fe.jar", "-i"]

WORKDIR /home/appuser/fe/activemq/bin

CMD ["/bin/sh", "-c", "activemq"]

The RUN command extracts the application and the activemq at the location into folder called fe.

The WORKDIR seems to be setting the working directly to activemq/bin. I confirmed this by using sh script which triggers when the image is run. In the sh script I trigger an ls and pwd command to see the contents and the location.

However when I run the image which triggers the CMD command I get the error that :

/bin/sh: activemq: not found

What can be the possible issue here?


问:
MySQL performance tuning for DELETE query
Can any one help me to re-write the query to speed up the execution time? It took 37 seconds to execute.

```<code>DELETE FROM storefront_categories
WHERE userid IN (SELECT userid
                FROM MASTER
                where expirydate<'2020-2-4'
                )
</code>```

At the same time, this query took only 4.69 seconds only to execute.

```<code>DELETE FROM storefront_categories
WHERE userid NOT IN (SELECT userid FROM MASTER)
</code>```

The table storefront_categories have 97K records where as in MASTER have 40K records. We have created a index on MASTER.expirydate field.

答:
I would advise you to use NOT EXISTS with the correct index:

```<code>DELETE sc
    FROM storefront_categories sc
    WHERE NOT EXISTS (SELECT 1
                      FROM master m
                      WHERE m.userid = sc.userid AND
                            m.expirydate < '2020-02-04'
                     );
</code>```

The index you want is on master(userid, expirydate).  The order of the columns is important.  For this version, an index on storefront_categories does not help.

Note that I changed the date format.  I recommend using YYYY-MM-DD to avoid ambiguity -- and to use the full 10 characters.

Body:
Can any one help me to re-write the query to speed up the execution time? It took 37 seconds to execute.

DELETE FROM storefront_categories
WHERE userid IN (SELECT userid
                FROM MASTER
                where expirydate<'2020-2-4'
                )

At the same time, this query took only 4.69 seconds only to execute.

DELETE FROM storefront_categories
WHERE userid NOT IN (SELECT userid FROM MASTER)

The table storefront_categories have 97K records where as in MASTER have 40K records. We have created a index on MASTER.expirydate field.

Body:
I would advise you to use NOT EXISTS with the correct index:

DELETE sc
    FROM storefront_categories sc
    WHERE NOT EXISTS (SELECT 1
                      FROM master m
                      WHERE m.userid = sc.userid AND
                            m.expirydate < '2020-02-04'
                     );

The index you want is on master(userid, expirydate).  The order of the columns is important.  For this version, an index on storefront_categories does not help.

Note that I changed the date format.  I recommend using YYYY-MM-DD to avoid ambiguity -- and to use the full 10 characters.


问:
Adding url path to backend HAPROXY
I want to add a path to url if only no path defined. E.g.

hostname:8080 -> then add /fe:   ->   hostname:8080/fe

The answer from https://stackoverflow.com/a/40488319/12501050 does not work:

```<code>acl p_root path -i /
http-request set-path /fe if p_root
</code>```

as it blocks the other requests. E.g.

hostname:8080/fe/getUsers

答:
This part is little tricky to implement, but not that hard to work. Something like this works.

```<code>acl p_root path -i /
acl is_domain hdr(host) -i myhostname.io
redirect code 301 location myhostname.io/fe if is_domain p_root
</code>```

Hope this is helps.

Title: Adding url path to backend HAPROXY

Body:
I want to add a path to url if only no path defined. E.g.

hostname:8080 -> then add /fe:   ->   hostname:8080/fe

The answer from https://stackoverflow.com/a/40488319/12501050 does not work:

acl p_root path -i /
http-request set-path /fe if p_root

as it blocks the other requests. E.g.

hostname:8080/fe/getUsers

Body:
This part is little tricky to implement, but not that hard to work. Something like this works.

acl p_root path -i /
acl is_domain hdr(host) -i myhostname.io
redirect code 301 location myhostname.io/fe if is_domain p_root

Hope this is helps.


问:
I'm trying to create a search function that would call a fragment having somewhat similar name than what is searched. Has anyone done this?
I already have dozens of fragments that each displays its own information. Now - if that's possible -, I'm trying to add a search box that would show a list of relevant fragment names. I'm naming them based on what they contained and launch the one that is clicked.

I'm thinking of using Activity.getsupportfragmentmanager().findfragmentbyID function, but the fragment would then need to have been launched within the activity which is far from what I needed.

Could somebody here please point me in the right direction?

答:
Activity.getSupportFragmentManager().findFragmentByID finds the current fragment sitting in the xml layout in that ID

If you do FragmentManager.beginTransaction().replace(R.id.whatever,fragment1).commit()

and then do Activity.getSupportFragmentManager().findFragmentByID(R.id.whatever)

it will find fragment1

then right after you do

```<code>FragmentManager.beginTransaction().replace(R.id.whatever,fragment2).commit()
Activity.getSupportFragmentManager().findFragmentByID(R.id.whatever)
</code>```

it will find fragment2

If each fragment has its own ID, this method will work.

Body:
Activity.getSupportFragmentManager().findFragmentByID finds the current fragment sitting in the xml layout in that ID

If you do FragmentManager.beginTransaction().replace(R.id.whatever,fragment1).commit()

and then do Activity.getSupportFragmentManager().findFragmentByID(R.id.whatever)

it will find fragment1

then right after you do

FragmentManager.beginTransaction().replace(R.id.whatever,fragment2).commit()
Activity.getSupportFragmentManager().findFragmentByID(R.id.whatever)

it will find fragment2

If each fragment has its own ID, this method will work.


问:
JS: async function
I'am new in JS and had some problems with async function.
I have a function, that return data from MongoDB. I create a promise, and get collection with empty object.

```<code>async function getRating(item, applicant) {
let arr = await Applicant.find({ proff: item }).sort({ ball: "desc" });
let rating = arr.findIndex(item => item._id.equals(applicant._id));
let spec = await Spec.findById(item);
const el = { spec, rating };
return el;}

router.get("/test", auth, async (req, res) => {
let applicant = await Applicant.findOne({ user: req.user.id });
let ratings = [];
applicant.proff.forEach(item => {
    const rating = getRating(item, applicant)
    .then(rating => ratings.push(rating))
    .catch(err => console.log(err));
     ratings.push(rating);
});
await res.json(ratings);
});
</code>```

When I check in Postman, this return me array: [{},{},{}]

Please help.

答:
this part is still async, you have to use await</p>

```<code> const rating = getRating(item, applicant).then(rating => ratings.push(rating)).catch(err....
</code>```

Title: JS: async function

Body:
I'am new in JS and had some problems with async function.
I have a function, that return data from MongoDB. I create a promise, and get collection with empty object.

async function getRating(item, applicant) {
let arr = await Applicant.find({ proff: item }).sort({ ball: "desc" });
let rating = arr.findIndex(item => item._id.equals(applicant._id));
let spec = await Spec.findById(item);
const el = { spec, rating };
return el;}

router.get("/test", auth, async (req, res) => {
let applicant = await Applicant.findOne({ user: req.user.id });
let ratings = [];
applicant.proff.forEach(item => {
    const rating = getRating(item, applicant)
    .then(rating => ratings.push(rating))
    .catch(err => console.log(err));
     ratings.push(rating);
});
await res.json(ratings);
});

When I check in Postman, this return me array: [{},{},{}]

Please help.

Body:
this part is still async, you have to use await

 const rating = getRating(item, applicant).then(rating => ratings.push(rating)).catch(err....


问:
Cannot save Excel file in Rstudio after binding data
I am trying to save an Excel workbook from Rstudio, in which new data was added, the way I am saving it is with saveworkbook from openxlsx library, but it gives me the following error:

Error in zip_internal(zipfile, files, recurse, compression_level, append = FALSE, : zip error: Cannot add file [Content_Types].xmlto archivefile383c1b9b6cc7.xlsx`` in file zip.c:394

For more background for the excel file, it's size is around 28Mb.

When I first opened the file in Excel 2007 the software told me that it couldn't read the file, after Excel managed to fix the file its summary was:

removed part /xl/comments1.xml part with xml error. (comments) load error

I don't know if it was Excel 2007 fix that caused the error Rstudio it gives me,  zip_internal.

Also the file uses Excel formulas to extract information of other pages to others.

Does the link between information of different pages contributes to this error?

Below is the code on how i am implementing the program.

```<code>library(pdftools)
library(dplyr)
library(openxlsx)
#For smartbind
library(gtools)

#load exel file
old_data<- readWorkbook("file.xlsx", sheet = "Raw");

#bind the new data into old data
new_data<-smartbind(old_data, pdf_refined);

# Write updated data frame to existing worksheet
wb<- loadWorkbook("file.xlsx")
writeData(wb, sheet = "Raw", new_data)

# Save file (with new name for testing purposes)
saveWorkbook(wb, "file.xlsx", overwrite = TRUE)
</code>```

At the end wb ends up as object containing active binding.

When Run the head(new_data) and attributes(new_data), after applying data.frame(new_data) it gives this:

```<code>Column class mismatch for 'Original'. Converting column to class 'character'.Column class mismatch for 'Bank'. Converting column to class 'character'.Column class mismatch for 'Date'. Converting column to class 'character'.Column class mismatch for 'Original'. Converting column to class 'character'.Column class mismatch for 'Bank'. Converting column to class 'character'.$names
[1] "X1"             "Date"          "Original" "Bank" "X5"

$row.names
   [1] "1:1"    "1:2"    "1:3"    "1:4"    "1:5"    "1:6"    "1:7"    "1:8"    "1:9"    "1:10"
  [11] "1:11"   "1:12"   "1:13"   "1:14"   "1:15"   "1:16"   "1:17"   "1:18"   "1:19"   "1:20"
  [21] "1:21"   "1:22"   "1:23"   "1:24"   "1:25"   "1:26"   "1:27"   "1:28"   "1:29"   "1:30"
  [31] "1:31"   "1:32"   "1:33"   "1:34"   "1:35"   "1:36"   "1:37"   "1:38"   "1:39"   "1:40"
  [41] "1:41"   "1:42"   "1:43"   "1:44"   "1:45"   "1:46"   "1:47"   "1:48"   "1:49"   "1:50"
  [51] "1:51"   "1:52"   "1:53"   "1:54"   "1:55"   "1:56"   "1:57"   "1:58"   "1:59"   "1:60"
  [61] "1:61"   "1:62"   "1:63"   "1:64"   "1:65"   "1:66"   "1:67"   "1:68"   "1:69"   "1:70"
  [71] "1:71"   "1:72"   "1:73"   "1:74"   "1:75"   "1:76"   "1:77"   "1:78"   "1:79"   "1:80"
  [81] "1:81"   "1:82"   "1:83"   "1:84"   "1:85"   "1:86"   "1:87"   "1:88"   "1:89"   "1:90"
[ reached getOption("max.print") -- omitted 802 entries ]

$class
[1] "data.frame"
</code>```

答:
Unfortunately, I am facing the same error and could not solve it for my machine, yet.
(my github issue)

In some other cases the openxlsx::saveWorkbook() function did not work properly due to a missing temp variable in the system environment. So, may be, it works for you to use Sys.setenv() to set a TMP variable.
Look here for the github issue on that.

Body:
I am trying to save an Excel workbook from Rstudio, in which new data was added, the way I am saving it is with saveworkbook from openxlsx library, but it gives me the following error:

Error in zip_internal(zipfile, files, recurse, compression_level, append = FALSE, : zip error: Cannot add file [Content_Types].xmlto archivefile383c1b9b6cc7.xlsx`` in file zip.c:394

For more background for the excel file, it's size is around 28Mb.

When I first opened the file in Excel 2007 the software told me that it couldn't read the file, after Excel managed to fix the file its summary was:

removed part /xl/comments1.xml part with xml error. (comments) load error

I don't know if it was Excel 2007 fix that caused the error Rstudio it gives me,  zip_internal.

Also the file uses Excel formulas to extract information of other pages to others.

Does the link between information of different pages contributes to this error?

Below is the code on how i am implementing the program.

library(pdftools)
library(dplyr)
library(openxlsx)
#For smartbind
library(gtools)

#load exel file
old_data<- readWorkbook("file.xlsx", sheet = "Raw");

#bind the new data into old data
new_data<-smartbind(old_data, pdf_refined);

# Write updated data frame to existing worksheet
wb<- loadWorkbook("file.xlsx")
writeData(wb, sheet = "Raw", new_data)

# Save file (with new name for testing purposes)
saveWorkbook(wb, "file.xlsx", overwrite = TRUE)

At the end wb ends up as object containing active binding.

When Run the head(new_data) and attributes(new_data), after applying data.frame(new_data) it gives this:

Column class mismatch for 'Original'. Converting column to class 'character'.Column class mismatch for 'Bank'. Converting column to class 'character'.Column class mismatch for 'Date'. Converting column to class 'character'.Column class mismatch for 'Original'. Converting column to class 'character'.Column class mismatch for 'Bank'. Converting column to class 'character'.$names
[1] "X1"             "Date"          "Original" "Bank" "X5"

$row.names
   [1] "1:1"    "1:2"    "1:3"    "1:4"    "1:5"    "1:6"    "1:7"    "1:8"    "1:9"    "1:10"
  [11] "1:11"   "1:12"   "1:13"   "1:14"   "1:15"   "1:16"   "1:17"   "1:18"   "1:19"   "1:20"
  [21] "1:21"   "1:22"   "1:23"   "1:24"   "1:25"   "1:26"   "1:27"   "1:28"   "1:29"   "1:30"
  [31] "1:31"   "1:32"   "1:33"   "1:34"   "1:35"   "1:36"   "1:37"   "1:38"   "1:39"   "1:40"
  [41] "1:41"   "1:42"   "1:43"   "1:44"   "1:45"   "1:46"   "1:47"   "1:48"   "1:49"   "1:50"
  [51] "1:51"   "1:52"   "1:53"   "1:54"   "1:55"   "1:56"   "1:57"   "1:58"   "1:59"   "1:60"
  [61] "1:61"   "1:62"   "1:63"   "1:64"   "1:65"   "1:66"   "1:67"   "1:68"   "1:69"   "1:70"
  [71] "1:71"   "1:72"   "1:73"   "1:74"   "1:75"   "1:76"   "1:77"   "1:78"   "1:79"   "1:80"
  [81] "1:81"   "1:82"   "1:83"   "1:84"   "1:85"   "1:86"   "1:87"   "1:88"   "1:89"   "1:90"
[ reached getOption("max.print") -- omitted 802 entries ]

$class
[1] "data.frame"


问:
How do I look for a byte sequence in a file?
I want to finde this arrange of bytes in a file :

[18][53][80][67] (HEX)
00011000 1010011 10000000 1100111

The bytes represent Matroska Segment EBML ID  https://www.matroska.org/technical/specs/index.html

I try to search in the file like this but with no results :

```<code>    is.seekg (0, is.end);
    int length = is.tellg();
    is.seekg (0, is.beg);

    char * buffer = new char [8];

    std::cout << "Reading " << length << " characters... ";
    // read data as a block:
      for(int i=0;i<length;i++){
       std::cout<<i<<std::endl;
       is.read (buffer,sizeof(char));
       if((int)(unsigned  char)buffer[0] == 1)
           if((int)(unsigned  char)buffer[1] == 8)
               if((int)(unsigned  char)buffer[3] == 10)
                   if((int)(unsigned  char)buffer[4] == 3)
                       if((int)(unsigned  char)buffer[5]==8)
                           if((int)(unsigned  char)buffer[6]==0)
                               if((int)(unsigned  char)buffer[7]==12)
                                   if((int)(unsigned  char)buffer[8]==7)
                                       std::cout<<"finish !!!!";
</code>```

Is my approach wrong?

答:
If I correctly understood you, you could use the search algorithm:</p>

```<code>// ...
std::ifstream is( file_name, std::ios::binary );
if ( !is )
  return -1;
std::array<std::char, 4> ebml_id{ 0x18, 0x53, 0x80, 0x67 };
auto res = std::search( std::istream_iterator<char>( is ), std::istream_iterator<char>(), ebml_id.begin(), ebml_id.end() );
// ...
</code>```

Body:
I want to finde this arrange of bytes in a file :

[18][53][80][67] (HEX)
00011000 1010011 10000000 1100111

The bytes represent Matroska Segment EBML ID  https://www.matroska.org/technical/specs/index.html

I try to search in the file like this but with no results :

    is.seekg (0, is.end);
    int length = is.tellg();
    is.seekg (0, is.beg);

    char * buffer = new char [8];

    std::cout << "Reading " << length << " characters... ";
    // read data as a block:
      for(int i=0;i<length;i++){
       std::cout<<i<<std::endl;
       is.read (buffer,sizeof(char));
       if((int)(unsigned  char)buffer[0] == 1)
           if((int)(unsigned  char)buffer[1] == 8)
               if((int)(unsigned  char)buffer[3] == 10)
                   if((int)(unsigned  char)buffer[4] == 3)
                       if((int)(unsigned  char)buffer[5]==8)
                           if((int)(unsigned  char)buffer[6]==0)
                               if((int)(unsigned  char)buffer[7]==12)
                                   if((int)(unsigned  char)buffer[8]==7)
                                       std::cout<<"finish !!!!";

Is my approach wrong?

Body:
If I correctly understood you, you could use the search algorithm:

// ...
std::ifstream is( file_name, std::ios::binary );
if ( !is )
  return -1;
std::array<std::char, 4> ebml_id{ 0x18, 0x53, 0x80, 0x67 };
auto res = std::search( std::istream_iterator<char>( is ), std::istream_iterator<char>(), ebml_id.begin(), ebml_id.end() );
// ...


问:
Pandas Series to Pandas Dataframe
I have an object <class 'pandas.core.series.Series'> that looks like this:

```<code>DataFrame(cfd_appr).transpose().sum(axis=1)
2022.12.06_Bild 2.txt     524.0
2022.12.06_Bild 3.txt     620.0
2022.12.06_Bild 4.txt     535.0
2022.12.06_Bild 5.txt     799.0
2022.12.06_Bild 6.txt    1032.0
2022.12.06_Bild 8.txt       4.0
dtype: float64
</code>```

Created by DataFrame(some_cfd).transpose().sum(axis=1). Now I need to transform it so it would look as follows:

```<code>                              1
2022.12.06_Bild 2.txt     524.0
2022.12.06_Bild 3.txt     620.0
2022.12.06_Bild 4.txt     535.0
2022.12.06_Bild 5.txt     799.0
2022.12.06_Bild 6.txt    1032.0
2022.12.06_Bild 8.txt       4.0
</code>```

After hours of reading Pandas documentation I still can't figure out how to do that. It should be a <class 'pandas.core.frame.DataFrame'> with a single-level indexing. Each time is use reset_index() it created some new (index?) column, and using set_index('index') creates a two-level column indexing that I don't need.

I can imagine there area many corresponding cases, so sorry in advance if it already was answered somewhere, but so far I have not find the solution. Any help would be appreciated.

答:
Use Series.to_frame:

```<code>pd.DataFrame(cfd_appr).transpose().sum(axis=1).to_frame(1)
</code>```

Title: Pandas Series to Pandas Dataframe

Body:
I have an object <class 'pandas.core.series.Series'> that looks like this:

DataFrame(cfd_appr).transpose().sum(axis=1)
2022.12.06_Bild 2.txt     524.0
2022.12.06_Bild 3.txt     620.0
2022.12.06_Bild 4.txt     535.0
2022.12.06_Bild 5.txt     799.0
2022.12.06_Bild 6.txt    1032.0
2022.12.06_Bild 8.txt       4.0
dtype: float64

Created by DataFrame(some_cfd).transpose().sum(axis=1). Now I need to transform it so it would look as follows:

                              1
2022.12.06_Bild 2.txt     524.0
2022.12.06_Bild 3.txt     620.0
2022.12.06_Bild 4.txt     535.0
2022.12.06_Bild 5.txt     799.0
2022.12.06_Bild 6.txt    1032.0
2022.12.06_Bild 8.txt       4.0

After hours of reading Pandas documentation I still can't figure out how to do that. It should be a <class 'pandas.core.frame.DataFrame'> with a single-level indexing. Each time is use reset_index() it created some new (index?) column, and using set_index('index') creates a two-level column indexing that I don't need.

I can imagine there area many corresponding cases, so sorry in advance if it already was answered somewhere, but so far I have not find the solution. Any help would be appreciated.

Body:
Use Series.to_frame:

pd.DataFrame(cfd_appr).transpose().sum(axis=1).to_frame(1)


问:
Discord selfbot - answering on messages from everyone
I have Discord selfbot in node.js and I wanna make a bot answering to massages from other server members, for example, if someone type "hey" selfbot will send into DMs "I'm busy rn, sorry"

I have this code but it is not working, I did not get any error but it is not working :(

```<code>client.on('message', message => {
  if (message.content.startsWith('hey'))
    target.send('im afk')
})
</code>```

答:
```<code>client.on('message', message => {
    console.log('Message received: ' + message.content);
    if(message.content === 'hey') {
        message.author.send("Im busy rn, sorry!");
    }
});
</code>```

Try outputting the console output to double check that the message content is actually received properly. Also try using message.content === '' (however this will only work if the whole message content is 'hey')

Body:
I have Discord selfbot in node.js and I wanna make a bot answering to massages from other server members, for example, if someone type "hey" selfbot will send into DMs "I'm busy rn, sorry"

I have this code but it is not working, I did not get any error but it is not working :(

client.on('message', message => {
  if (message.content.startsWith('hey'))
    target.send('im afk')
})

Body:
client.on('message', message => {
    console.log('Message received: ' + message.content);
    if(message.content === 'hey') {
        message.author.send("Im busy rn, sorry!");
    }
});

Try outputting the console output to double check that the message content is actually received properly. Also try using message.content === '' (however this will only work if the whole message content is 'hey')


问:
How to make a method for that part of SAP-GUI script using Java and JNI?
I have some methods already that I'm using for connecting to SAP GUI Scripting Engine using Java & JACOB library - I'm somehow unable to make one more method I'd like to use.

I am using "PoojaGugu"
https://github.com/PoojaGugu/SAP-GuiClient-Automation/blob/master/Java/library/src/main/java/com/library/generic/SAPGeneric.java
for studying the case.

I already tried copying some methods with editing some places in it, although it did not work. I can't provide you with examples.

So let me get to the actual problem here. I've got quite a lot of VBA code right now. I've been messing around with Java - just to get to know something else than making a macros in Excel. I'm using VB for connecting to SAP scripting engine, just to automate some work I've got. I can't make a proper method using Java&Jacob to do specifically this:

```<code>Set grid = session.FindById("wnd[0]/usr/cntlWC_INSP_CHAR/shellcont/shell")
grid.pressToolbarButton "&SORT_DSC"
</code>```

That is how it looks like in my Excel macro, that one works. To simplify it:

```<code>session.FindById("wnd[0]/usr/cntlWC_INSP_CHAR/shellcont/shell").pressToolbarButton "&SORT_DSC"
</code>```

It is pushing a button with id &SORT_DSC on SapGrid object. But using examples mentioned earlier I can provide you with a method that works on the very same display (transaction) on a very same "grid" scope:

```<code> */SAPGuiGridSelectOrDeselectColumn
       * Objective - to  select or deselect the column  in the grid
       * parameter  : partial id string , column name , SelectOrDeselect - Pass true to select column and false to Deselect the column
       * created by Venkata Siva kumar
       */
      public void SAPGuiGridSelectOrDeselectColumn(String idstr, String column, boolean SelectOrDeselect) throws Exception
      {

          String id = getSAPObjectIDHelperMethod(getSession(), "ID", idstr, "", "");
          session = new ActiveXComponent(getSession().invoke("FindById",id).toDispatch());
          if (SelectOrDeselect)
              Dispatch.call(session, "selectColumn", column);

          else
              Dispatch.call(session, "deselectColumn", column);

      }

      /*SAPGuiGridSelectOrDeselectColumn
</code>```

This one is selecting columns from the table on that same page. To give you an image on how I do it in VBA:

```<code>grid.selectColumn "VARIANCE"
</code>```

where a "grid" is previously mentioned path/object adress. It selects a column named "VARIANCE" withing the same SapGuiGrid scope that I want to press the %SORT button. That method works.

I wanted to make my method based on this one to click the button I mentioned earlier with no success (not only that method to be honest). How can I proceed?

答:
This is what I came up with:

```<code>ActiveXComponent guiShellObject= new ActiveXComponent(Session.invoke("findById", "wnd[0]/usr/cntlWC_INSP_CHAR/shellcont/shell").toDispatch());
guiShellObject.invoke("pressToolbarButton", "&SORT_DSC");
</code>```

That would replace:

```<code>session.FindById("wnd[0]/usr/cntlWC_INSP_CHAR/shellcont/shell").pressToolbarButton "&SORT_DSC"
</code>```

Above example is self-explaining enough. I did not know how to do that untill I learned that I can pass on additional parameters with invoke method than only one.

Body:
I have some methods already that I'm using for connecting to SAP GUI Scripting Engine using Java & JACOB library - I'm somehow unable to make one more method I'd like to use.

I am using "PoojaGugu"
https://github.com/PoojaGugu/SAP-GuiClient-Automation/blob/master/Java/library/src/main/java/com/library/generic/SAPGeneric.java
for studying the case.

I already tried copying some methods with editing some places in it, although it did not work. I can't provide you with examples.

So let me get to the actual problem here. I've got quite a lot of VBA code right now. I've been messing around with Java - just to get to know something else than making a macros in Excel. I'm using VB for connecting to SAP scripting engine, just to automate some work I've got. I can't make a proper method using Java&Jacob to do specifically this:

Set grid = session.FindById("wnd[0]/usr/cntlWC_INSP_CHAR/shellcont/shell")
grid.pressToolbarButton "&SORT_DSC"

That is how it looks like in my Excel macro, that one works. To simplify it:

session.FindById("wnd[0]/usr/cntlWC_INSP_CHAR/shellcont/shell").pressToolbarButton "&SORT_DSC"

It is pushing a button with id &SORT_DSC on SapGrid object. But using examples mentioned earlier I can provide you with a method that works on the very same display (transaction) on a very same "grid" scope:

 */SAPGuiGridSelectOrDeselectColumn
       * Objective - to  select or deselect the column  in the grid
       * parameter  : partial id string , column name , SelectOrDeselect - Pass true to select column and false to Deselect the column
       * created by Venkata Siva kumar
       */
      public void SAPGuiGridSelectOrDeselectColumn(String idstr, String column, boolean SelectOrDeselect) throws Exception
      {

          String id = getSAPObjectIDHelperMethod(getSession(), "ID", idstr, "", "");
          session = new ActiveXComponent(getSession().invoke("FindById",id).toDispatch());
          if (SelectOrDeselect)
              Dispatch.call(session, "selectColumn", column);

          else
              Dispatch.call(session, "deselectColumn", column);

      }

      /*SAPGuiGridSelectOrDeselectColumn

This one is selecting columns from the table on that same page. To give you an image on how I do it in VBA:

grid.selectColumn "VARIANCE"

where a "grid" is previously mentioned path/object adress. It selects a column named "VARIANCE" withing the same SapGuiGrid scope that I want to press the %SORT button. That method works.

I wanted to make my method based on this one to click the button I mentioned earlier with no success (not only that method to be honest). How can I proceed?

Body:
This is what I came up with:

ActiveXComponent guiShellObject= new ActiveXComponent(Session.invoke("findById", "wnd[0]/usr/cntlWC_INSP_CHAR/shellcont/shell").toDispatch());
guiShellObject.invoke("pressToolbarButton", "&SORT_DSC");

That would replace:

session.FindById("wnd[0]/usr/cntlWC_INSP_CHAR/shellcont/shell").pressToolbarButton "&SORT_DSC"

Above example is self-explaining enough. I did not know how to do that untill I learned that I can pass on additional parameters with invoke method than only one.


问:
NNS: Is there a way to omit certain features in a prediction?
I'd like to train a nearest-neighbor search model with something like the following -

```<code>        | feature_A | feature_B | feature_C |
---------------------------------------------
point_1 |       0.0 |       5.1 |      94.9 |
point_2 |      80.7 |      35.3 |      64.7 |
</code>```

And so on, with many more features and data points.

We can then pass a point for prediction, such as [0.3, 5.0, 94.0] -> returns point_1 as is typical in nearest-neighbor search.

What I'd like to do, also, is pass a value for a certain feature or subset of features and return the closest point, ignoring all other features, like so:

[None, 5.0, None] -> returns point_1

[80.0, None, 64.7] -> returns point_2

The problem is that these nulls can't be passed to the model and they can't really be inferred to be 0.0 as this is not what the prediction is asking for. The feature needs to be omitted entirely from the calculation.

Is there a way to do this natively using Sagemaker/Scikit-learn libraries without having to build multiple models or write a custom implementation of NNS?

答:
In general, the problem of doing prediction for data with missingness is hard and not solvable.

To put it in statistical terms: The predicted nearest neighbor for some test point xₜ is denoted ŷ(xₜ). Let some of the components of xₜ be missing, so we write xₜ=(zₜ,wₜ), where the components wₜ is missing. Then, the confidence in that the model predicts k can be written like Pr(ŷ(xₜ)=k)=P(ŷ(zₜ)=k)= ∫I(k=ŷ(zₜ,w))p(w|zₜ)dw, where I(t)=1 if t=true and 0 otherwise. Finally, you could select the prediction ỹ(xₜ) to be the mode of Pr(ŷ(xₜ)=k), i.e. ỹ(xₜ) = argmax_k Pr(ŷ(xₜ)=k).

This is a tough problem, since you need to estimate some conditional densities to compute the integral. You would also need to compute the integral for all possible nearest neighbors.

If you make some restricting assumption, such as Missing Completely At Random, then the problem simplifies, as p(w|zₜ)=p(w) from the independence. Your predictions will probably worsen, though. There is no simple way to resolve this problem.

Thus, you need a trade-off between statistical soundness and practical application. This is usually made by some kind of imputation. I think you should have some imputation technique that captures the correlations in the data reasonable well.

I would probably use the knn-imputer in sklearn to impute the missing values, and then just go for nearest-neighbor search on the imputed data.

Body:
I'd like to train a nearest-neighbor search model with something like the following -

        | feature_A | feature_B | feature_C |
---------------------------------------------
point_1 |       0.0 |       5.1 |      94.9 |
point_2 |      80.7 |      35.3 |      64.7 |

And so on, with many more features and data points.

We can then pass a point for prediction, such as [0.3, 5.0, 94.0] -> returns point_1 as is typical in nearest-neighbor search.

What I'd like to do, also, is pass a value for a certain feature or subset of features and return the closest point, ignoring all other features, like so:

[None, 5.0, None] -> returns point_1

[80.0, None, 64.7] -> returns point_2

The problem is that these nulls can't be passed to the model and they can't really be inferred to be 0.0 as this is not what the prediction is asking for. The feature needs to be omitted entirely from the calculation.

Is there a way to do this natively using Sagemaker/Scikit-learn libraries without having to build multiple models or write a custom implementation of NNS?


问:
How to Show Notifications when get close to Beacon even if the app is closed?
I have created a mini App that helps me playing with beacons.

-what i have done so far-

So until now, I have successfully connected my App to the beacon, made 2 texts, so when I'm in the app and get in the beacon's range, the texts are changing so I can see that, move 2m away or turning the beacon upside down so it simulates Out of range, and it will show the message that I'm not in the range anymore.

So far so good, I have also successfully made the app to show notifications when I get close to the beacon, and when I click the notification to open a second activity.

-the problem-

Now, I want to show a notification when I get in the beacon's range, and the app is closed (not in the background). And after, when I click on that Notification to open my app / open App Google Play's Page if not installed.

I have searched on the internet but I haven't found anything conclusive.

If you guys know anything, or have you accomplished this task, it would be great if you can help with it.
If you need more info like, my activities code I can upload it, but I considered unimportant.

Thanks!

答:
Two points:

In order to make a phone react to a beacon without your app installed (e.g. to launch a PlayStore page)  you need an app prei-nstalled on all phones that does this for you.  The Google Play Services app used to do this through the Nearby feature, but it was discontinued in Nov. 2018 because of spam concerns.  Since then this is no longer possible to do.

If you do have your app installed it is a straightforward process to detect in the background and send notifications.  The Android Beacon Library provides instructions here:. https://altbeacon.github.io/android-beacon-library/notifications.html


问:
Why does a multicolumn foreign key allow nonexisting values
Consider the following tables:

```<code>CREATE TABLE Foo
(
   FooId1 int NOT NULL,
   FooId2 int NOT NULL,
   PRIMARY KEY(FooId1, FooId2)
);

INSERT INTO Foo(FooId1, FooId2) VALUES (1, 10), (2, 20);

CREATE TABLE Bar
(
   BarId int NOT NULL PRIMARY KEY,
   FooId1 int NULL,
   FooId2 int NULL
);

ALTER TABLE Bar ADD CONSTRAINT FK_FOO
    FOREIGN KEY(FooId1, FooId2)
    REFERENCES Foo(FooId1, FooId2);

INSERT INTO Bar(BarId) VALUES(42);
</code>```

If I then try

```<code>UPDATE Bar
    SET FooId1 = 3,
        FooId2 = 30
    WHERE BarId = 42;
</code>```

I'm getting an foreign key violation as expected. But if I do

```<code>UPDATE Bar
    SET FooId1 = NULL,
        FooId2 = 30
    WHERE BarId = 42;
</code>```

it works without an error. I would have expected that even though the fields FooId1 and FooId2 are nullable the combination of both would always be checked against the foreign key. Why does the DB allow this UPDATE?

答:
When a value other than NULL is entered into the column of a FOREIGN
  KEY constraint, the value must exist in the referenced column;
  otherwise, a foreign key violation error message is returned. To make
  sure that all values of a composite foreign key constraint are
  verified, specify NOT NULL on all the participating columns.
  Create Foreign Key Relationships

According to this explanation of the MSDN, you should define the Food1 and Food2 columns of the Bar columns with NOT NULL constraint.

```<code>CREATE TABLE Bar
(
   BarId int NOT NULL PRIMARY KEY,
   FooId1 int NOT NULL,
   FooId2 int NOT NULL
)
</code>```

So that the following insert will not work;

```<code>INSERT INTO Bar(BarId) VALUES(42)

Msg 515, Level 16, State 2, Line 23
Cannot insert the value NULL into column 'FooId1', table 'AdventureWorks2017.dbo.Bar'; column does not allow nulls. INSERT fails.
The statement has been terminated.
</code>```

Body:
Consider the following tables:

CREATE TABLE Foo
(
   FooId1 int NOT NULL,
   FooId2 int NOT NULL,
   PRIMARY KEY(FooId1, FooId2)
);

INSERT INTO Foo(FooId1, FooId2) VALUES (1, 10), (2, 20);

CREATE TABLE Bar
(
   BarId int NOT NULL PRIMARY KEY,
   FooId1 int NULL,
   FooId2 int NULL
);

ALTER TABLE Bar ADD CONSTRAINT FK_FOO
    FOREIGN KEY(FooId1, FooId2)
    REFERENCES Foo(FooId1, FooId2);

INSERT INTO Bar(BarId) VALUES(42);

If I then try

UPDATE Bar
    SET FooId1 = 3,
        FooId2 = 30
    WHERE BarId = 42;

I'm getting an foreign key violation as expected. But if I do

UPDATE Bar
    SET FooId1 = NULL,
        FooId2 = 30
    WHERE BarId = 42;

it works without an error. I would have expected that even though the fields FooId1 and FooId2 are nullable the combination of both would always be checked against the foreign key. Why does the DB allow this UPDATE?

Body:
When a value other than NULL is entered into the column of a FOREIGN
  KEY constraint, the value must exist in the referenced column;
  otherwise, a foreign key violation error message is returned. To make
  sure that all values of a composite foreign key constraint are
  verified, specify NOT NULL on all the participating columns.
  Create Foreign Key Relationships

According to this explanation of the MSDN, you should define the Food1 and Food2 columns of the Bar columns with NOT NULL constraint.

CREATE TABLE Bar
(
   BarId int NOT NULL PRIMARY KEY,
   FooId1 int NOT NULL,
   FooId2 int NOT NULL
)

So that the following insert will not work;

INSERT INTO Bar(BarId) VALUES(42)

Msg 515, Level 16, State 2, Line 23
Cannot insert the value NULL into column 'FooId1', table 'AdventureWorks2017.dbo.Bar'; column does not allow nulls. INSERT fails.
The statement has been terminated.


答:
to_frame can be used to convert a Series to DataFrame.

```<code>series = DataFrame(some_cfd).transpose().sum(axis=1)

# The provided name (1) will substitute for the series name
df = series.to_frame(1)
</code>```

And the output should be:

```<code>>>> print(df)

                              1
2022.12.06_Bild 2.txt     524.0
2022.12.06_Bild 3.txt     620.0
2022.12.06_Bild 4.txt     535.0
2022.12.06_Bild 5.txt     799.0
2022.12.06_Bild 6.txt    1032.0
2022.12.06_Bild 8.txt       4.0
</code>```

Title: Pandas Series to Pandas Dataframe

Body:
to_frame can be used to convert a Series to DataFrame.

series = DataFrame(some_cfd).transpose().sum(axis=1)

# The provided name (1) will substitute for the series name
df = series.to_frame(1)

And the output should be:

>>> print(df)

                              1
2022.12.06_Bild 2.txt     524.0
2022.12.06_Bild 3.txt     620.0
2022.12.06_Bild 4.txt     535.0
2022.12.06_Bild 5.txt     799.0
2022.12.06_Bild 6.txt    1032.0
2022.12.06_Bild 8.txt       4.0


问:
How to check if a file exists in Ansible?
I have to check whether a file exists in /etc/. If the file exists then I have to skip the task.
Here is the code I am using:

```<code>- name: checking the file exists
  command: touch file.txt
  when: $(! -s /etc/file.txt)
</code>```

答:
Below is the ansible play which i used to remove the file if the file exists on OS end.

```<code> - name: find out /etc/init.d/splunk file exists or not'
      stat:
        path: /etc/init.d/splunk
      register: splunkresult
      tags:
        - always

    - name: 'Remove splunk from init.d file if splunk already running'
      file:
        path: /etc/init.d/splunk
        state: absent
      when: splunkresult.stat.exists == true
      ignore_errors: yes
      tags:
        - always
</code>```

I have used play condition as like below

```<code>when: splunkresult.stat.exists == true --> Remove the file
</code>```

you can give true/false based on your requirement

```<code>when: splunkresult.stat.exists == false
when: splunkresult.stat.exists == true
</code>```

Body:
I have to check whether a file exists in /etc/. If the file exists then I have to skip the task.
Here is the code I am using:

- name: checking the file exists
  command: touch file.txt
  when: $(! -s /etc/file.txt)

Body:
Below is the ansible play which i used to remove the file if the file exists on OS end.

 - name: find out /etc/init.d/splunk file exists or not'
      stat:
        path: /etc/init.d/splunk
      register: splunkresult
      tags:
        - always

    - name: 'Remove splunk from init.d file if splunk already running'
      file:
        path: /etc/init.d/splunk
        state: absent
      when: splunkresult.stat.exists == true
      ignore_errors: yes
      tags:
        - always

I have used play condition as like below

when: splunkresult.stat.exists == true --> Remove the file

you can give true/false based on your requirement

when: splunkresult.stat.exists == false
when: splunkresult.stat.exists == true


问:
MATLAB to C++: Coder: not consistent array dimension concatenation
adapting the code from this coder-compatible solution to read csv data i ran into the following issue during the runtime issue check of Matlab Coder:

```<code>Error using cat>>check_non_axis_size (line 283)
Dimensions of arrays being concatenated are not consistent.

Error in cat>>cat_impl (line 102)
check_non_axis_size(isempty, i, sizes{i}, varargin{:});

Error in cat (line 22)
result = cat_impl(@always_isempty_matrix, axis, varargin{:});

Error in readCsv (line 28)
coder.ceval('sscanf', [token, NULL], ['%lf', NULL], coder.wref(result(k)));
</code>```

my adaptation:

```<code>function result = readCsv(filepath, rows, columns)

NULL = char(0);
fid = fopen(filepath, 'r');
% read entire file into char array
remainder = fread(fid, '*char');

% preallocation for speedup
result = coder.nullcopy(zeros(columns,rows));
k = 1;
while ~isempty(remainder)

    % comma, newline
    delimiters = [',', char(10)];

    % strtok ignores leading delimiter,
    % returns chars upto, but not including,
    % the next delimiter
    [token,remainder] = strtok(remainder, delimiters);

    % string to double conversion
    % no need to worry about return type / order
    % since we only look at one token at a time
    if coder.target('MATLAB')
          result(k) = sscanf(token, '%f');
    else
        coder.ceval('sscanf', [token, NULL], ['%lf', NULL], coder.wref(result(k)));
    end
    k = k + 1;
end

% workaround for filling column-major but breaks on single-line csv
result = reshape(result,rows, [])';
disp(k)
fclose(fid);
</code>```

the .csv in case is a 200x51 matrix

testing in matlab: works as expected - the .csv is read 1:1 as with csvread()

the error pops up during code generation, and as far as I understand, an issue with writing the result of sscanf into the preallocated result array - but only for the c code.

Addendum: a line with only integer values (1,1,1,...,0) works fine, a line with actual floats (6.7308,38.7101,...,40.5999,0) breaks with the aforementioned error.

答:
```<code>remainder = fread(f, [1, Inf], '*char');
</code>```

turns out sizeA argument is not optional in this case

Body:
adapting the code from this coder-compatible solution to read csv data i ran into the following issue during the runtime issue check of Matlab Coder:

Error using cat>>check_non_axis_size (line 283)
Dimensions of arrays being concatenated are not consistent.

Error in cat>>cat_impl (line 102)
check_non_axis_size(isempty, i, sizes{i}, varargin{:});

Error in cat (line 22)
result = cat_impl(@always_isempty_matrix, axis, varargin{:});

Error in readCsv (line 28)
coder.ceval('sscanf', [token, NULL], ['%lf', NULL], coder.wref(result(k)));

my adaptation:

function result = readCsv(filepath, rows, columns)

NULL = char(0);
fid = fopen(filepath, 'r');
% read entire file into char array
remainder = fread(fid, '*char');

% preallocation for speedup
result = coder.nullcopy(zeros(columns,rows));
k = 1;
while ~isempty(remainder)

    % comma, newline
    delimiters = [',', char(10)];

    % strtok ignores leading delimiter,
    % returns chars upto, but not including,
    % the next delimiter
    [token,remainder] = strtok(remainder, delimiters);

    % string to double conversion
    % no need to worry about return type / order
    % since we only look at one token at a time
    if coder.target('MATLAB')
          result(k) = sscanf(token, '%f');
    else
        coder.ceval('sscanf', [token, NULL], ['%lf', NULL], coder.wref(result(k)));
    end
    k = k + 1;
end

% workaround for filling column-major but breaks on single-line csv
result = reshape(result,rows, [])';
disp(k)
fclose(fid);

the .csv in case is a 200x51 matrix

testing in matlab: works as expected - the .csv is read 1:1 as with csvread()

the error pops up during code generation, and as far as I understand, an issue with writing the result of sscanf into the preallocated result array - but only for the c code.

Addendum: a line with only integer values (1,1,1,...,0) works fine, a line with actual floats (6.7308,38.7101,...,40.5999,0) breaks with the aforementioned error.

Body:
remainder = fread(f, [1, Inf], '*char');

turns out sizeA argument is not optional in this case


问:
query on manyToMany field with related_name
my models:

```<code>class Course(models.Model):
    pass

class CourseRun(models.Model):
    course = models.ForeignKey(Course, related_name='course_runs')

class Category(models.Model):
    courses = models.ManyToManyField(Course, related_name='category_set')
</code>```

for some reason I was forced to add many2many in Category model instead of Course model

my question:
how can I search on CourseRun by category id

somethings like this:

```<code>CourseRun.objects.filter(course__category__in=[1, 2])
</code>```

答:
If you set the related_query_name [Django-doc], then that is the name you should use when filtering in reverse. If you set the related_name [Django-doc], and not a related_query_name, then Django will use the related_name for the related_query_name as well. If you do not set a related_name and related_query_name, then related_name will default to modelname_set (so here category_set) and related_query_name to modelname (so here category).

Option 1: use the related_name

So you can filter with the related_name in your query:

```<code>CourseRun.objects.filter(course__<b>category_set</b>__in=[1, 2])</code>```

Option 2: set a related_query_name

Another option is to set the related_query_name to something else, for example 'category':

```<code>class Category(models.Model):
    courses = models.ManyToManyField(
        Course,
        related_name='category_set',
        <b>related_query_name='category'</b>
    )</code>```

Then you can filter with:

```<code>CourseRun.objects.filter(course__<b>category</b>__in=[1, 2])</code>```

Body:
my models:

class Course(models.Model):
    pass

class CourseRun(models.Model):
    course = models.ForeignKey(Course, related_name='course_runs')

class Category(models.Model):
    courses = models.ManyToManyField(Course, related_name='category_set')

for some reason I was forced to add many2many in Category model instead of Course model

my question:
how can I search on CourseRun by category id

somethings like this:

CourseRun.objects.filter(course__category__in=[1, 2])

Body:
If you set the related_query_name [Django-doc], then that is the name you should use when filtering in reverse. If you set the related_name [Django-doc], and not a related_query_name, then Django will use the related_name for the related_query_name as well. If you do not set a related_name and related_query_name, then related_name will default to modelname_set (so here category_set) and related_query_name to modelname (so here category).

Option 1: use the related_name

So you can filter with the related_name in your query:

CourseRun.objects.filter(course__category_set__in=[1, 2])

Option 2: set a related_query_name

Another option is to set the related_query_name to something else, for example 'category':

class Category(models.Model):
    courses = models.ManyToManyField(
        Course,
        related_name='category_set',
        related_query_name='category'
    )

Then you can filter with:

CourseRun.objects.filter(course__category__in=[1, 2])


问:
Audio Route Button - AirPlay
I am currently playing audio through AudioQueues.  I would like to allow users to connect to Airplay devices.

If I create an MPVolumeView and use the 'showsRouteButton' to display the route button I can successfully connect.

Is there a way to change the Audio Route to Airplay without using the MPVolumeView?  Or a simpler Apple view that is just the route button?

答:
Since iOS 11 you can use AVRoutePicker :</p>

```<code>import AVKit

let rpv = AVRoutePickerView()
view.addSubview(rpv)
</code>```

Title: Audio Route Button - AirPlay

Body:
Since iOS 11 you can use AVRoutePicker :

import AVKit

let rpv = AVRoutePickerView()
view.addSubview(rpv)


问:
Using a Regular Expression to Add Parameters Within Quotation Marks in Bash
I have a string stored in a file in this format:

VAR_NAME="Param1=p1 Param2=p2"

I need to write a regular expression which will allow me to add parameters to the variable between the quotes i.e;

VAR_NAME="Param1=p1 Param2=p2 Param3=P3"

I have created a RegEx which seems to work for me here, however, I am not sure how to implement this into my bash script.

How can I edit the above string to add parameters between quotation the marks from within a Bash script?

答:
You may use sed:

```<code>text='VAR_NAME="Param1=p1 Param2=p2"'
sed 's,VAR_NAME="\([^"]*\)",GRUB_CMDLINE_LINUX="\1 Param3=p3",' <<< "$text"
# => GRUB_CMDLINE_LINUX="Param1=p1 Param2=p2 Param3=p3"

# Or, assign the result to a variable:
result="$(sed 's,VAR_NAME="\([^"]*\)",GRUB_CMDLINE_LINUX="\1 Param3=p3",' <<< "$text")"
echo "$result"
# => GRUB_CMDLINE_LINUX="Param1=p1 Param2=p2 Param3=p3"
</code>```

See the online demo

Body:
You may use sed:

text='VAR_NAME="Param1=p1 Param2=p2"'
sed 's,VAR_NAME="\([^"]*\)",GRUB_CMDLINE_LINUX="\1 Param3=p3",' <<< "$text"
# => GRUB_CMDLINE_LINUX="Param1=p1 Param2=p2 Param3=p3"

# Or, assign the result to a variable:
result="$(sed 's,VAR_NAME="\([^"]*\)",GRUB_CMDLINE_LINUX="\1 Param3=p3",' <<< "$text")"
echo "$result"
# => GRUB_CMDLINE_LINUX="Param1=p1 Param2=p2 Param3=p3"

See the online demo


问:
Bulk update Postgres table
I have a table with around 200 million records and I have added 2 new columns to it. Now the 2 columns need values from a different table. Nearly 80% of the rows will be updated.

I tried update but it takes more than 2 hours to complete.

The main table has a composite primary key of 4 columns. I have dropped it and dropped an index that is present on a column before updating. Now the update takes little over than 1 hour.

Is there any other way to speed up this update process (like batch processing).

Edit: I used the other table(from where values will be matched for update) in from clause of the update statement.

答:
Not really. Make sure that max_wal_size is high enough that you don't get too many checkpoints.

After the update, the table will be bloated to about twice its original size.
That bloat can be avoided if you update in batches and VACUUM in between, but that will not make processing faster.

Title: Bulk update Postgres table