问:
Redux states modification is not reflected right after dispatch. Is dispatch async?
I have gone through the community and found many people saying the dispatch function in redux is synchronous. However, when I build the following app with react-redux, I find a bug seemingly due to the asynchronous behavior of my dispatch function. So I wonder what is the cause of the following codes and how to solve it (or perhaps replace the design pattern with better practices).

It is basically a part where

user selects a value from a drop-down menu

the app stores it in states

the app reads from states and inquires an API with argument based on that state value the user chooses.

After I have chosen a value in the drop-down, the fetching raises an error of incorrect param format because my query URL is example.com?param=undefined (the initial state is undefined). When I select the second time there is no such format error (obviously, because the setting of states is finished at least once anyway and at least the param format is correct)

Dropdown (using react-select)

```<code>class Dropdown extends Component {
    onValueChange(v) {
        this.props.setSomeValue(v);
        this.props.queryData();
    }
    render() {
        return <Some-react-select-Dropdown
            value={this.props.someValue}
            onChange={this.onValueChange}
        />
    }
}

export default connect(state => {
    someValue: state.someValue
}, dispatch => {
    setSomeValue: dispatch(setSomeValue(v))
})
</code>```

App

class App extends Component {
    queryData() {
        fetch(`example.com?param=${this.props.someValue}`/*, ...*/).then(/*...*/)
    }
    render() {
        return <Dropdown
            queryData={this.queryData}
        />
    }
}

export default connect(state => {
    someValue: state.someValue.value // because react-select stores selected value in {label, value} format
})(App)
```

I expect the program to perform state-setting (via dispatch) and fetching synchronously, so that the query URL can be successfully generated. However (as is mentioned above), my choosing dropdown value for the first time makes the app to inquire an API with initial state of undefined.

答:
You are correct to deduce that the value has not finished changing after executing your action here.

```<code>onValueChange(v) {
    this.props.setSomeValue(v); <-- creates action, updates redux-state
    this.props.queryData(); <-- executes before action above is complete.
}
</code>```

The two functions you wrote are running to execution and not synchronously. You can workaround this by using the componentDidUpdate() lifecycle method

Put this in your Dropdown Component

```<code>componentDidUpdate(prevProps){
    if(prevProps.someValue !== this.props.someValue){
          this.props.queryData();
    }
}
</code>```

So now you can run queryData() once it is confirmed that your someValue state has changed.

Body:
I have gone through the community and found many people saying the dispatch function in redux is synchronous. However, when I build the following app with react-redux, I find a bug seemingly due to the asynchronous behavior of my dispatch function. So I wonder what is the cause of the following codes and how to solve it (or perhaps replace the design pattern with better practices).

It is basically a part where

user selects a value from a drop-down menu

the app stores it in states

the app reads from states and inquires an API with argument based on that state value the user chooses.

After I have chosen a value in the drop-down, the fetching raises an error of incorrect param format because my query URL is example.com?param=undefined (the initial state is undefined). When I select the second time there is no such format error (obviously, because the setting of states is finished at least once anyway and at least the param format is correct)

Dropdown (using react-select)

class Dropdown extends Component {
    onValueChange(v) {
        this.props.setSomeValue(v);
        this.props.queryData();
    }
    render() {
        return <Some-react-select-Dropdown
            value={this.props.someValue}
            onChange={this.onValueChange}
        />
    }
}

export default connect(state => {
    someValue: state.someValue
}, dispatch => {
    setSomeValue: dispatch(setSomeValue(v))
})

App

class App extends Component {
    queryData() {
        fetch(`example.com?param=${this.props.someValue}`/*, ...*/).then(/*...*/)
    }
    render() {
        return <Dropdown
            queryData={this.queryData}
        />
    }
}

export default connect(state => {
    someValue: state.someValue.value // because react-select stores selected value in {label, value} format
})(App)

I expect the program to perform state-setting (via dispatch) and fetching synchronously, so that the query URL can be successfully generated. However (as is mentioned above), my choosing dropdown value for the first time makes the app to inquire an API with initial state of undefined.

Body:
You are correct to deduce that the value has not finished changing after executing your action here.

onValueChange(v) {
    this.props.setSomeValue(v); <-- creates action, updates redux-state
    this.props.queryData(); <-- executes before action above is complete.
}

The two functions you wrote are running to execution and not synchronously. You can workaround this by using the componentDidUpdate() lifecycle method

Put this in your Dropdown Component

componentDidUpdate(prevProps){
    if(prevProps.someValue !== this.props.someValue){
          this.props.queryData();
    }
}

So now you can run queryData() once it is confirmed that your someValue state has changed.


来源: stackexchange

问:
AppEngine standard and Memorystore connection issue
I have Memorystore instance:

```<code>gcloud redis instances list --region europe-west1
INSTANCE_NAME      VERSION    REGION        TIER   SIZE_GB  HOST      PORT  NETWORK  RESERVED_IP  STATUS  CREATE_TIME
sm-cache  REDIS_4_0  europe-west1  BASIC  1        10.1.1.3  6379  default  10.1.1.0/28  READY   2019-05-30T19:03:29
</code>```

and App Engine standard application running in same region.

There is VPC required to connect. I tried adding it without lack. What should be CIDR for such connection? Same as for Memorystore does not work:

```<code>gcloud beta compute networks vpc-access connectors describe sm-01-vpc --region europe-west1
ipCidrRange: 10.1.1.0/28
maxThroughput: 1000
minThroughput: 200
name: projects/salesmanago-data-01/locations/europe-west1/connectors/sm-01-vpc
network: default
state: ERROR
</code>```

What IP I should use in Spring Boot configuration? Any suggestions? This is not clearly described in docs and tutorials.

So far I am getting error in application:

```<code>Unable to connect to Redis; nested exception is io.lettuce.core.RedisConnectionException: Unable to connect to 10.1.1.3:6379
</code>```

答:
What should be CIDR for such connection? Same as for Memorystore does not work:

Use the ip range does not exist in your VPC network and different from the one memorystore uses.

What IP I should use in Spring Boot configuration

The IP showed in gcloud redis instances list --region europe-west1

BTW Serverless seems only work on us-central1 as of now, not sure if it works on europe-west1

ContentLicense: CC BY-SA 4.0

Body:
I have Memorystore instance:

gcloud redis instances list --region europe-west1
INSTANCE_NAME      VERSION    REGION        TIER   SIZE_GB  HOST      PORT  NETWORK  RESERVED_IP  STATUS  CREATE_TIME
sm-cache  REDIS_4_0  europe-west1  BASIC  1        10.1.1.3  6379  default  10.1.1.0/28  READY   2019-05-30T19:03:29

and App Engine standard application running in same region.

There is VPC required to connect. I tried adding it without lack. What should be CIDR for such connection? Same as for Memorystore does not work:

gcloud beta compute networks vpc-access connectors describe sm-01-vpc --region europe-west1
ipCidrRange: 10.1.1.0/28
maxThroughput: 1000
minThroughput: 200
name: projects/salesmanago-data-01/locations/europe-west1/connectors/sm-01-vpc
network: default
state: ERROR

What IP I should use in Spring Boot configuration? Any suggestions? This is not clearly described in docs and tutorials.

So far I am getting error in application:

Unable to connect to Redis; nested exception is io.lettuce.core.RedisConnectionException: Unable to connect to 10.1.1.3:6379


问:
Building a tree recursively in JavaScript
I am trying to build a tree recursively from an array of objects. I am currently using the reduce() method to iterate through the items in the array and figure out which children belong to a particular item and populating it, then recursively populating the children of those children and so on. However, I have been unable to take the last nodes(e.g persian and siamese in this case) and put them in array(see expected and current output below)

```<code>    let categories = [
        { id: 'animals', parent: null },
        { id: 'mammals', parent: 'animals' },
        { id: 'cats', parent: 'mammals' },
        { id: 'dogs', parent: 'mammals' },
        { id: 'chihuahua', parent: 'dogs' },
        { id: 'labrador', parent: 'dogs' },
        { id: 'persian', parent: 'cats' },
        { id: 'siamese', parent: 'cats' }
    ];

   const reduceTree = (categories, parent = null) =>
    categories.reduce(
        (tree, currentItem) => {

            if(currentItem.parent == parent){
               tree[currentItem.id] = reduceTree(categories, currentItem.id);
            }

            return tree;
        },
        {}
   )

   console.log(JSON.stringify(reduceTree(categories), null, 1));
</code>```

expected output:

```<code>{
    "animals": {
        "mammals": {
            "cats": [     // <-- an array of cat strings
                "persian",
                "siamese"
            ],
            "dogs": [     // <-- an array of dog strings
                "chihuahua",
                "labrador"
            ]
        }
    }
}
</code>```

current output:

```<code>{
    "animals": {
        "mammals": {
            "cats": {       // <-- an object with cat keys
                "persian": {},
                "siamese": {}
            },
            "dogs": {       // <-- an object with dog keys
                "chihuahua": {},
                "labrador": {}
            }
          }
     }
}
</code>```

How should I go about solving the problem?

答:
I put a condition to merge the result as an array if a node has no child. Try this

let categories = [
        { id: 'animals', parent: null },
        { id: 'mammals', parent: 'animals' },
        { id: 'cats', parent: 'mammals' },
        { id: 'dogs', parent: 'mammals' },
        { id: 'chihuahua', parent: 'dogs' },
        { id: 'labrador', parent: 'dogs' },
        { id: 'persian', parent: 'cats' },
        { id: 'siamese', parent: 'cats' }
    ];

   const reduceTree = (categories, parent = null) =>
    categories.reduce(
        (tree, currentItem) => {

            if(currentItem.parent == parent){
                let val = reduceTree(categories, currentItem.id);
                if( Object.keys(val).length == 0){
                    Object.keys(tree).length == 0 ? tree = [currentItem.id] : tree.push(currentItem.id);
                }
                else{
                    tree[currentItem.id] = val;
                }
            }
            return tree;
        },
        {}
   )

   console.log(JSON.stringify(reduceTree(categories), null, 1));```

NOTE: if your data structure changes again this parser might fail for some other scenarios.

Body:
I am trying to build a tree recursively from an array of objects. I am currently using the reduce() method to iterate through the items in the array and figure out which children belong to a particular item and populating it, then recursively populating the children of those children and so on. However, I have been unable to take the last nodes(e.g persian and siamese in this case) and put them in array(see expected and current output below)

    let categories = [
        { id: 'animals', parent: null },
        { id: 'mammals', parent: 'animals' },
        { id: 'cats', parent: 'mammals' },
        { id: 'dogs', parent: 'mammals' },
        { id: 'chihuahua', parent: 'dogs' },
        { id: 'labrador', parent: 'dogs' },
        { id: 'persian', parent: 'cats' },
        { id: 'siamese', parent: 'cats' }
    ];

   const reduceTree = (categories, parent = null) =>
    categories.reduce(
        (tree, currentItem) => {

            if(currentItem.parent == parent){
               tree[currentItem.id] = reduceTree(categories, currentItem.id);
            }

            return tree;
        },
        {}
   )

   console.log(JSON.stringify(reduceTree(categories), null, 1));

expected output:

{
    "animals": {
        "mammals": {
            "cats": [     // <-- an array of cat strings
                "persian",
                "siamese"
            ],
            "dogs": [     // <-- an array of dog strings
                "chihuahua",
                "labrador"
            ]
        }
    }
}

current output:

{
    "animals": {
        "mammals": {
            "cats": {       // <-- an object with cat keys
                "persian": {},
                "siamese": {}
            },
            "dogs": {       // <-- an object with dog keys
                "chihuahua": {},
                "labrador": {}
            }
          }
     }
}

How should I go about solving the problem?

Body:
I put a condition to merge the result as an array if a node has no child. Try this

let categories = [
        { id: 'animals', parent: null },
        { id: 'mammals', parent: 'animals' },
        { id: 'cats', parent: 'mammals' },
        { id: 'dogs', parent: 'mammals' },
        { id: 'chihuahua', parent: 'dogs' },
        { id: 'labrador', parent: 'dogs' },
        { id: 'persian', parent: 'cats' },
        { id: 'siamese', parent: 'cats' }
    ];

   const reduceTree = (categories, parent = null) =>
    categories.reduce(
        (tree, currentItem) => {

            if(currentItem.parent == parent){
                let val = reduceTree(categories, currentItem.id);
                if( Object.keys(val).length == 0){
                    Object.keys(tree).length == 0 ? tree = [currentItem.id] : tree.push(currentItem.id);
                }
                else{
                    tree[currentItem.id] = val;
                }
            }
            return tree;
        },
        {}
   )

   console.log(JSON.stringify(reduceTree(categories), null, 1));

NOTE: if your data structure changes again this parser might fail for some other scenarios.


问:
Fancybox defaults issue with customized zoom
I'm setting up a custom zoom button and want to implement it. For some reason my defaults aren't applying to the popup.

I've tried including the out of the box structure, but to no avail.

```<code>jQuery(function($) {
$(document).ready(function() {
    // Create template for zoom button
$.fancybox.defaults.tpl.zoom = '<button class="fancybox-button fancybox-zoom"><div class="zoom"><span class="zoom-inner"></span></div></button>';

// Choose what buttons to display by default
$.fancybox.defaults.buttons = [
  'fullScreen',
  'thumbs',
  'zoom',
  'close'
];

$( '.fancybox' ).fancybox({

  onInit : function( instance ) {

    // Make zoom icon clickable
    instance.$refs.toolbar.find('.fancybox-zoom').on('click', function() {

      if ( instance.isScaledDown() ) {
        instance.scaleToActual();

      } else {
        instance.scaleToFit();
      }

    });
  }
});

});});
</code>```

Expected results is an understanding of how to implement the new zoom as well as other buttons.

答:
The first step would be to learn to debug the code. Hit F12 to open developer tools and check Console tab. You will see this JS error message:

```<code>Uncaught TypeError: Cannot set property 'zoom' of undefined
</code>```

And the reason is that you have used tpl instead of btnTpl property, so, replace that and it will work fine - https://codepen.io/anon/pen/OYaxeb?editors=1010

btw, you could also use $.extend() to tweak defaults:

```<code>$.extend(true, $.fancybox.defaults, {
  btnTpl : {
    // Create template for zoom button
    zoom : '<button class="fancybox-button fancybox-zoom"><div class="zoom"><span class="zoom-inner"></span></div></button>'
  },

  // Choose what buttons to display by default
  buttons : [
    'fullScreen',
    'thumbs',
    'zoom',
    'close'
  ]
});
</code>```

Body:
I'm setting up a custom zoom button and want to implement it. For some reason my defaults aren't applying to the popup.

I've tried including the out of the box structure, but to no avail.

jQuery(function($) {
$(document).ready(function() {
    // Create template for zoom button
$.fancybox.defaults.tpl.zoom = '<button class="fancybox-button fancybox-zoom">

</button>';

// Choose what buttons to display by default
$.fancybox.defaults.buttons = [
  'fullScreen',
  'thumbs',
  'zoom',
  'close'
];

$( '.fancybox' ).fancybox({

  onInit : function( instance ) {

    // Make zoom icon clickable
    instance.$refs.toolbar.find('.fancybox-zoom').on('click', function() {

      if ( instance.isScaledDown() ) {
        instance.scaleToActual();

      } else {
        instance.scaleToFit();
      }

    });
  }
});

});});

Expected results is an understanding of how to implement the new zoom as well as other buttons.

Body:
The first step would be to learn to debug the code. Hit F12 to open developer tools and check Console tab. You will see this JS error message:

Uncaught TypeError: Cannot set property 'zoom' of undefined

And the reason is that you have used tpl instead of btnTpl property, so, replace that and it will work fine - https://codepen.io/anon/pen/OYaxeb?editors=1010

btw, you could also use $.extend() to tweak defaults:

$.extend(true, $.fancybox.defaults, {
  btnTpl : {
    // Create template for zoom button
    zoom : '<button class="fancybox-button fancybox-zoom"><div class="zoom"><span class="zoom-inner"></span></div></button>'
  },

  // Choose what buttons to display by default
  buttons : [
    'fullScreen',
    'thumbs',
    'zoom',
    'close'
  ]
});


问:
Implementing downloadable code and content plugins for Android
I'm kinda new to a plugin development in Java and Android, so I wanted to ask this basic question.

Consider that I have some framework which has some Factory which can produce certain classes - these classes perform some plugin-like functionality. I want to implement a plugin system that would be able to somehow download new plugins from some server and make them available for that Factory for creation.

And the basic requirements for plugin is:

it contains code by implementing some common interface

it contains resources (for example drawables)

For example this might be a "shapes" drawing app. each plugin has code to draw() a shape, optionally by using bitmap for filling that shape - in this case bitmap is supplied with a plugin as a resource.

How should I go about this? Any pointers to google search terms and hints are appreciated, thanks :)

答:
I don't think you can do this on Android, because of security restrictions. It is very likely that your only option is to distribute plugins as separate application in the Market (like Doplhin browser does).

However, the problem to be solved is: how are you going to discover those plugins? To answer this we would need to know how do you intend to use those plugins. If should be easy if your plugins are plain old activities.

I found this post for you: http://mylifewithandroid.blogspot.com/2010/06/plugins.html

ContentLicense: CC BY-SA 3.0


问:
Material Design plugin in Sketch: How do you export the generated theme?
We are using the Material Design Theme Editor plugin in Sketch. It creates this amazing Style Guide and Material Design theme right in your Sketch file. Does anyone know to export then import the theme generated in Sketch to Android Studio?</p>

答:
Take a look at Material Components for Android (MDC-Android) https://github.com/material-components/material-components-android.

The catalog module has demonstrations of all the components.
The material-theme-builder module lets you enter typography, shape, and color styling in Android Studio and then shows what the customized theme looks like. See the docs on the repo.

You can then design in sketch, manually add your chosen typography, shape, and color styling into material-theme-builder and check/fine tune how all the MD components look. Lastly copy the theme resources into your own project as per the repo docs.

It's not as simple as just exporting straight from sketch into your Android build.


问:
Building Name using current location
I am trying to get House number using  CLLocationManagerDelegate and MKMapViewDelegate but it did not work. By using this i am getting Sub-locality area and sub administrative thoroughfare and sub-through fare but not getting building name.

Please help how to get building name

I have already tried using CLLocationManagerDelegate method reversegeocoder and CLLocationManagerDelegate.

```<code> CLGeocoder().reverseGeocodeLocation(location){ (placemark, error)   in
        let place = placemark?[0]

 print(placemark?[0].addressDictionary?[0])

        let subloc = place?.subLocality
        let city = place?.locality
        print("\(subloc!),\(city!),\(place?.administrativeArea)")
        print(place?.areasOfInterest?.count)
        if let subLocal = place?.subLocality, let cityCustom = place?.locality
       {
         self.locationname.text = ("\(subLocal),\(cityCustom)")
        self.locationname.text = (placemark?[0].addressDictionary?[0]) as? String
         self.address = self.locationname.text ?? ""
        print(placemark?[0].addressDictionary?[0]) as? String
        if let marks = placemark, marks.count > 0 {
            let placemark = marks[0]
            let postalAddress = placemark.addressDictionary

            if let address = postalAddress?.first {

                print("\(address)")
            }
            if let State = placemark.addressDictionary?["State"]{

                print("\(State)")
            }
            if let Street = placemark.addressDictionary?["Street"]{

                print("\(Street)")
            }
            if let Name = placemark.addressDictionary?["Name"]{

                print("\(Name)")
            }
            if let Thoroughfare = placemark.addressDictionary?["Thoroughfare"]{

                print("\(Thoroughfare)")
            }
            if let subThoroughfare = placemark.addressDictionary?["SubThoroughfare"]{

                print("\(subThoroughfare)")
            }
            if let FormattedAddressLines = placemark.addressDictionary?["FormattedAddressLines"]{

                print("\(FormattedAddressLines)")
                self.locationname.text = (FormattedAddressLines as AnyObject).componentsJoined(by: ",") as? String
                self.address = self.locationname.text ?? ""
                 self.locationname.numberOfLines = 2
                 self.locationname.sizeToFit()
                self.locationname.textAlignment = .center
            }
        }

     }
    else
     {
         self.alertbox(title1: UrlSheet.UrlName.msgTitle, message1: "Location service is disabled on your phone at the moment. Please enable the same before marking the attendance.")
      }
    self.mapviews.isUserInteractionEnabled = false
    manager.stopUpdatingLocation()
   }
</code>```

Expected Result:

```<code>DLf-Tower A, Jasola Distric Center,New Delhi
Actual Result:  Jasola Distric Center,New Delhi
</code>```

答: Visit: https://developer.apple.com/documentation/corelocation/clplacemark For All Supported Placemark by Apple</p>

Title: Building Name using current location

Body:
I am trying to get House number using  CLLocationManagerDelegate and MKMapViewDelegate but it did not work. By using this i am getting Sub-locality area and sub administrative thoroughfare and sub-through fare but not getting building name.

Please help how to get building name

I have already tried using CLLocationManagerDelegate method reversegeocoder and CLLocationManagerDelegate.

 CLGeocoder().reverseGeocodeLocation(location){ (placemark, error)   in
        let place = placemark?[0]

 print(placemark?[0].addressDictionary?[0])

        let subloc = place?.subLocality
        let city = place?.locality
        print("\(subloc!),\(city!),\(place?.administrativeArea)")
        print(place?.areasOfInterest?.count)
        if let subLocal = place?.subLocality, let cityCustom = place?.locality
       {
         self.locationname.text = ("\(subLocal),\(cityCustom)")
        self.locationname.text = (placemark?[0].addressDictionary?[0]) as? String
         self.address = self.locationname.text ?? ""
        print(placemark?[0].addressDictionary?[0]) as? String
        if let marks = placemark, marks.count > 0 {
            let placemark = marks[0]
            let postalAddress = placemark.addressDictionary

            if let address = postalAddress?.first {

                print("\(address)")
            }
            if let State = placemark.addressDictionary?["State"]{

                print("\(State)")
            }
            if let Street = placemark.addressDictionary?["Street"]{

                print("\(Street)")
            }
            if let Name = placemark.addressDictionary?["Name"]{

                print("\(Name)")
            }
            if let Thoroughfare = placemark.addressDictionary?["Thoroughfare"]{

                print("\(Thoroughfare)")
            }
            if let subThoroughfare = placemark.addressDictionary?["SubThoroughfare"]{

                print("\(subThoroughfare)")
            }
            if let FormattedAddressLines = placemark.addressDictionary?["FormattedAddressLines"]{

                print("\(FormattedAddressLines)")
                self.locationname.text = (FormattedAddressLines as AnyObject).componentsJoined(by: ",") as? String
                self.address = self.locationname.text ?? ""
                 self.locationname.numberOfLines = 2
                 self.locationname.sizeToFit()
                self.locationname.textAlignment = .center
            }
        }

     }
    else
     {
         self.alertbox(title1: UrlSheet.UrlName.msgTitle, message1: "Location service is disabled on your phone at the moment. Please enable the same before marking the attendance.")
      }
    self.mapviews.isUserInteractionEnabled = false
    manager.stopUpdatingLocation()
   }

Expected Result:

DLf-Tower A, Jasola Distric Center,New Delhi
Actual Result:  Jasola Distric Center,New Delhi


问:
Multiprocessing/multithreading for database query in Python
I have millions of records in database and I want to read it through Python and store it in pandas data frame .
The problem is the select query processing time is very high.
To reduce the query processing time I try to perform multi threading on it
I created 3 threads and make the query on basis of each thread like

```<code>Select * from ( select *,rownum over (order by col1) rn from table) where rn%3=0

Select * from ( select *,rownum over (order by col1) rn from table) where rn%3=1

Select * from ( select *,rownum over (order by col1) rn from table) where rn%3=2
</code>```

Then I run the each query with threading in Python by threading package.

But it also not reducing the time much

Is there any other approach I can take to reduce the query  reading time.
Note- I have used both jdbc and odbc connection

答:
You can use multi-threading only if the underlying database engine supports it. You should check for that. For your question, I think the attached link will help you:
see this
If the answer helps you then help the community by selecting it as the best answer.</p>

Body:
I have millions of records in database and I want to read it through Python and store it in pandas data frame .
The problem is the select query processing time is very high.
To reduce the query processing time I try to perform multi threading on it
I created 3 threads and make the query on basis of each thread like

Select * from ( select *,rownum over (order by col1) rn from table) where rn%3=0

Select * from ( select *,rownum over (order by col1) rn from table) where rn%3=1

Select * from ( select *,rownum over (order by col1) rn from table) where rn%3=2

Then I run the each query with threading in Python by threading package.

But it also not reducing the time much

Is there any other approach I can take to reduce the query  reading time.
Note- I have used both jdbc and odbc connection


问:
I have this error: java.sql.SQLException: Invalid column name in Java application
I built an app that counts some tax forms in a table and has to insert the number in another table.
When I count the tax forms in the first table I do it with this sql query :

```<code>select count(distinct cui) from dec_declaratii where id > 142321849 and
tip_declaratie='D212' and anul_duk>=2019 and cod_stare_prelucrare_intern
in ('DUK_VLD', 'GEN_MSJ')";
</code>```

When I run it from Oracle Toad it works but when i put it in java and I try to get the result with rs.getString("count(distinct cui)") it gives me this error :
java.sql.SQLException: Invalid column name

Why is this happening ?

What can I do to make it work ?

I tried writing count(distinct cui) with capital letters and if I write count(*) it works but I need the distinct number of tax forms.

```<code>public class Baza {

int idmin = 142321849;
int rezultat = 391320;

    String host = "xxx";
    String user = "xxx";
    String pass = "xxx";
    String user2 = "xxx";
    String pass2 = "xxx";

    String host2 = "xxx";
    String nr = "0";
public void conectare() {

    try {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection con = DriverManager.getConnection(host, user, pass);
    Statement st = con.createStatement();
    String sql = "select count(distinct cui) from dec_declaratii where id
> 142321849 and tip_declaratie='D212' and anul_duk>=2019 and
cod_stare_prelucrare_intern in ('DUK_VLD', 'GEN_MSJ')";
    ResultSet rs = st.executeQuery(sql);
    while(rs.next()) {
       nr = rs.getString("count(DISTINCT CUI)");
       System.out.println(nr);
    }
    }catch(Exception e) {System.out.println(e);}
    int nr2 = Integer.parseInt(nr);

    try {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection con = DriverManager.getConnection(host2, user2, pass2);
     Statement st = con.createStatement();
     String sql = "update nr_tot_dec_212 set nr_dec='"+nr+"', data=sysdate
where id=1";
     st.executeUpdate(sql);

    }catch(Exception e) {System.out.println(e);}
 }

}
</code>```

I would like to get the result of the query : select count(distinct cui) from dec_declaratii where id > 142321849 and tip_declaratie='D212' and anul_duk>=2019 and cod_stare_prelucrare_intern in ('DUK_VLD', 'GEN_MSJ')"; in a Java variable. It gives me this error:java.sql.SQLException: Invalid column name

答:
use alias for name the column of your count </p>

```<code>select count(distinct cui) as cnt from dec_declaratii where id > 142321849 and
tip_declaratie='D212' and anul_duk>=2019 and cod_stare_prelucrare_intern
in ('DUK_VLD', 'GEN_MSJ')";
</code>```

Body:
I built an app that counts some tax forms in a table and has to insert the number in another table.
When I count the tax forms in the first table I do it with this sql query :

select count(distinct cui) from dec_declaratii where id > 142321849 and
tip_declaratie='D212' and anul_duk>=2019 and cod_stare_prelucrare_intern
in ('DUK_VLD', 'GEN_MSJ')";

When I run it from Oracle Toad it works but when i put it in java and I try to get the result with rs.getString("count(distinct cui)") it gives me this error :
java.sql.SQLException: Invalid column name

Why is this happening ?

What can I do to make it work ?

I tried writing count(distinct cui) with capital letters and if I write count(*) it works but I need the distinct number of tax forms.

public class Baza {

int idmin = 142321849;
int rezultat = 391320;

    String host = "xxx";
    String user = "xxx";
    String pass = "xxx";
    String user2 = "xxx";
    String pass2 = "xxx";

    String host2 = "xxx";
    String nr = "0";
public void conectare() {

    try {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection con = DriverManager.getConnection(host, user, pass);
    Statement st = con.createStatement();
    String sql = "select count(distinct cui) from dec_declaratii where id
> 142321849 and tip_declaratie='D212' and anul_duk>=2019 and
cod_stare_prelucrare_intern in ('DUK_VLD', 'GEN_MSJ')";
    ResultSet rs = st.executeQuery(sql);
    while(rs.next()) {
       nr = rs.getString("count(DISTINCT CUI)");
       System.out.println(nr);
    }
    }catch(Exception e) {System.out.println(e);}
    int nr2 = Integer.parseInt(nr);

    try {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection con = DriverManager.getConnection(host2, user2, pass2);
     Statement st = con.createStatement();
     String sql = "update nr_tot_dec_212 set nr_dec='"+nr+"', data=sysdate
where id=1";
     st.executeUpdate(sql);

    }catch(Exception e) {System.out.println(e);}
 }

}

I would like to get the result of the query : select count(distinct cui) from dec_declaratii where id > 142321849 and tip_declaratie='D212' and anul_duk>=2019 and cod_stare_prelucrare_intern in ('DUK_VLD', 'GEN_MSJ')"; in a Java variable. It gives me this error:java.sql.SQLException: Invalid column name

Body:
use alias for name the column of your count

select count(distinct cui) as cnt from dec_declaratii where id > 142321849 and
tip_declaratie='D212' and anul_duk>=2019 and cod_stare_prelucrare_intern
in ('DUK_VLD', 'GEN_MSJ')";


问:
Display 2 tables in 1 view
I want to display 2 tables in 1 view

like this:

```<code>{{ $match->title }}
{{ $distance->distance }}
</code>```

but I can't get it to work.

This is my controller:

```<code>public function bikeGamesMatch(Request $request){
    $matches = BikeGame::find($request->id);
    $distances = Distance::find($request->id);
    dd($matches);
    return view('bike_games.match', compact("matches","distances"));
}
</code>```

why does the $distances return to null when I dd(): it?

this is my view:

```<code><th scope="col" class="text-center"><strong>Game Title:</strong>
             @foreach($matches as $match)
             {{ $match->title }}
             @endforeach
              </th>
                <th scope="col" class="text-center"><strong>Target: Distance</strong>
              @foreach($distances as $distance)
             {{ $distance->distance }} {{ $distance->unit }}
             @endforeach
</th>
</code>```

If I do this the view gives me 404

```<code>$matches = BikeGame::find($request->id)->firstOrFail();
$distances = Distance::find($request->id)->firstOrFail();
</code>```

What am I doing wrong here?

答:
use has one relationship between two model :: BikeGame & Distance .

give then Unique id. like Bike_id & Distance_id.

Bikegame model =>

```<code>public function distance(){
    return $this->hasOne('App\Distance','Distance_id', 'id');
}
</code>```

Distance Model =>

```<code>public function bike()
{
    return $this->belongsTO('App\Bikegame', 'Distance_id','id');
}
</code>```

in your controller ex.

```<code> $bike = BikeGame::with('distance')->find($id);
 $bike->bikename    = request('bikename');
 $bike->distance->distacekm = $request->distacekm;
 $bike->distance->dismm = $request->dismm;
</code>```

try this step

Title: Display 2 tables in 1 view

Body:
I want to display 2 tables in 1 view

like this:

{{ $match->title }}
{{ $distance->distance }}

but I can't get it to work.

This is my controller:

public function bikeGamesMatch(Request $request){
    $matches = BikeGame::find($request->id);
    $distances = Distance::find($request->id);
    dd($matches);
    return view('bike_games.match', compact("matches","distances"));
}

why does the $distances return to null when I dd(): it?

this is my view:

Game Title:
             @foreach($matches as $match)
             {{ $match->title }}
             @endforeach

                Target: Distance
              @foreach($distances as $distance)
             {{ $distance->distance }} {{ $distance->unit }}
             @endforeach

If I do this the view gives me 404

$matches = BikeGame::find($request->id)->firstOrFail();
$distances = Distance::find($request->id)->firstOrFail();

What am I doing wrong here?

Body:
use has one relationship between two model :: BikeGame & Distance .

give then Unique id. like Bike_id & Distance_id.

Bikegame model =>

public function distance(){
    return $this->hasOne('App\Distance','Distance_id', 'id');
}

Distance Model =>

public function bike()
{
    return $this->belongsTO('App\Bikegame', 'Distance_id','id');
}

in your controller ex.

 $bike = BikeGame::with('distance')->find($id);
 $bike->bikename    = request('bikename');
 $bike->distance->distacekm = $request->distacekm;
 $bike->distance->dismm = $request->dismm;

try this step


问:
sql query customer who ordered more than 15 times
how to get list of customers who ordered more than 15times.
i have customerId , orderId , orderValue , orderDate.

I tried

```<code>select *  from customertable Group By customerId having count (*) > 15
</code>```

答:
You can try below -</p>

```<code>select customerid
  from customertable
  Group By customerId having count (distinct orderid) >= 15
</code>```

Body:
how to get list of customers who ordered more than 15times.
i have customerId , orderId , orderValue , orderDate.

I tried

select *  from customertable Group By customerId having count (*) > 15

Body:
You can try below -

select customerid
  from customertable
  Group By customerId having count (distinct orderid) >= 15


问:
I can await fs.readdir but I don't know why
https://github.com/SimulatedGREG/electron-vue

I used this template to make electron.

And I am using this library.

https://www.npmjs.com/package/fs-extra

https://nodejs.org/docs/latest-v11.x/api/fs.html

By this document, I can write like this.

```<code>await fs.readdir
</code>```

But the electron template, it is using electron@2.0.4 and which is using node@8.9.3.

So I checked here.

https://nodejs.org/docs/latest-v8.x/api/fs.html

It looks like the function doesn't return promise.

But I actually can await fs functions using fs-extra in electron@2.0.4.

Both develop and build.

Why is this?

result of

```<code>console.log(fs.readdir())
</code>```

Is like below.

It's Promise.

But I don't know why I can do this in electron@2.0.4.

答:
If you're using Node > 8.16 (I believe), you can use promisify in the utils module:

```<code>const { promisify } = require('utils');
const fs = require('fs');
const readdir = promisify(fs.readdir);

(async () => {
  const res = await readdir('./path');
  console.log(res);
})();
</code>```

Body:
https://github.com/SimulatedGREG/electron-vue

I used this template to make electron.

And I am using this library.

https://www.npmjs.com/package/fs-extra

https://nodejs.org/docs/latest-v11.x/api/fs.html

By this document, I can write like this.

await fs.readdir

But the electron template, it is using electron@2.0.4 and which is using node@8.9.3.

So I checked here.

https://nodejs.org/docs/latest-v8.x/api/fs.html

It looks like the function doesn't return promise.

But I actually can await fs functions using fs-extra in electron@2.0.4.

Both develop and build.

Why is this?

result of

console.log(fs.readdir())

Is like below.

It's Promise.

But I don't know why I can do this in electron@2.0.4.

Body:
If you're using Node > 8.16 (I believe), you can use promisify in the utils module:

const { promisify } = require('utils');
const fs = require('fs');
const readdir = promisify(fs.readdir);

(async () => {
  const res = await readdir('./path');
  console.log(res);
})();


问:
After changing branch I lost my code from it
I know this is a bit newbie question. I have my frontend branch and backend branch. I wrote backend code on this one branch and when I switch tu frontend my code from backend is not visible. What sould I do, just merge them together?

Cheers

答: IF you want to view the back end code again switch back to the back end branch. In  git, a branch has its own code the whole purpose of creating branches is to keep a separate copy for adding features or doing any change without affecting the master branch normally this is a</p>


问:
How a save in a list the elements of a first list that are not contained in a second list with duplicate values?
I have a problem with a heuristic for Virtual Graph where I have to count the elements of numbers from two integer lists: I have to put in a list the numbers of the first one and the numbers that are not in the second list.

I've tried with two addAll and a removeAll(secondList) and it works but when the lists have duplicates It doesn't work because removes the duplicate element too:

        //Test lists
        List<Integer> ls1 = Arrays.asList(1,1,2,3);
        List<Integer> ls3 = Arrays.asList(1,3);
        List<Integer> s = new ArrayList<>();

        s.addAll(ls1);
        System.out.println("Add " + ls1);
        s.addAll(ls3);
        System.out.println("Add " + ls3);
        System.out.println("New list" + s);
        s.removeAll(ls3);
        System.out.println("Expected value (1,2)");
        System.out.println("Result List " + s);
```

The new list is [1, 1, 2, 3, 1, 3] and the expected output is [1,2] but the actual output is only 2.

答:
Remove elements present in ls2 from ls1 as :

```<code>List<Integer> ls1 = Arrays.asList(1, 1, 2, 3);
List<Integer> ls2 = Arrays.asList(1, 3);
List<Integer> s = new ArrayList<>(ls1);
ls2.forEach(s::remove);
</code>```

Body:
I have a problem with a heuristic for Virtual Graph where I have to count the elements of numbers from two integer lists: I have to put in a list the numbers of the first one and the numbers that are not in the second list.

I've tried with two addAll and a removeAll(secondList) and it works but when the lists have duplicates It doesn't work because removes the duplicate element too:

        //Test lists
        List<Integer> ls1 = Arrays.asList(1,1,2,3);
        List<Integer> ls3 = Arrays.asList(1,3);
        List<Integer> s = new ArrayList<>();

        s.addAll(ls1);
        System.out.println("Add " + ls1);
        s.addAll(ls3);
        System.out.println("Add " + ls3);
        System.out.println("New list" + s);
        s.removeAll(ls3);
        System.out.println("Expected value (1,2)");
        System.out.println("Result List " + s);

The new list is [1, 1, 2, 3, 1, 3] and the expected output is [1,2] but the actual output is only 2.

Body:
Remove elements present in ls2 from ls1 as :

List<Integer> ls1 = Arrays.asList(1, 1, 2, 3);
List<Integer> ls2 = Arrays.asList(1, 3);
List<Integer> s = new ArrayList<>(ls1);
ls2.forEach(s::remove);


问:
How to setup NoIP service with multiple NoIP accounts on Ubuntu server
As suggested in title, is there a way to setup the ubuntu server with multiple NoIP account?

The reason for multiple account is that there are different domains registered in different NoIP account and all these domains needed to point to the same ubuntu server.

It seems that the NoIP client only accept one account in the configuration file. noip2 -C

Service provider https://www.noip.com/

答: You need to subscribe to NoIP services in order to support multiple domains for the same server. You cannot do it with free service.</p>


问:
Convert multiple png to gif as an animation in R
I have a bunch of png files in a directory and I want to convert them into a gif (animated) file via R. Can you please advise how to do that? </p>

答:
Here is some dummy code you can use:

First use the magick package for the GIF
Use the magrittr package or the dplyr package for the %>%

```<code>library(magick)
library(magrittr)
</code>```

Then list files in the directory, and combine into gif
fps is frames per second

```<code>list.files(path='/$PATH/', pattern = '*.png', full.names = TRUE) %>%
        image_read() %>% # reads each path file
        image_join() %>% # joins image
        image_animate(fps=4) %>% # animates, can opt for number of loops
        image_write("FileName.gif") # write to current dir
</code>```

Body:
Here is some dummy code you can use:

First use the magick package for the GIF
Use the magrittr package or the dplyr package for the %>%

library(magick)
library(magrittr)

Then list files in the directory, and combine into gif
fps is frames per second

list.files(path='/$PATH/', pattern = '*.png', full.names = TRUE) %>%
        image_read() %>% # reads each path file
        image_join() %>% # joins image
        image_animate(fps=4) %>% # animates, can opt for number of loops
        image_write("FileName.gif") # write to current dir


问:
Error installing gems that use native extensions on Ubuntu, Ruby 1.9.2 via RVM
I get an error while trying to install the ffi gem:

```<code>~ - 16:54>gem i ffi
Building native extensions.  This could take a while...
ERROR:  Error installing ffi:
        ERROR: Failed to build gem native extension.

        rake RUBYARCHDIR=/home/mdemare/.rvm/gems/ruby-1.9.2-p136/gems/ffi-1.0.6/lib RUBYLIBDIR=/home/mdemare/.rvm/gems/ruby-1.9.2-p136/gems/ffi-1.0.6/lib
/home/mdemare/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/site_ruby/1.9.1/rubygems.rb:370:in `bin_path': can't find gem rake ([">= 0"]) with executable rake (Gem::GemNotFoundException)
        from /home/mdemare/.rvm/gems/ruby-1.9.2-p136/bin/rake:19:in `<main>'

Gem files will remain installed in /home/mdemare/.rvm/gems/ruby-1.9.2-p136/gems/ffi-1.0.6 for inspection.
Results logged to /home/mdemare/.rvm/gems/ruby-1.9.2-p136/gems/ffi-1.0.6/gen/gem_make.out
</code>```

I'm getting frequent errors of all kinds while installing gems with native extensions, so I assume that there's something broken with my Ubuntu installation, but I've no idea what. I'll post any information you need to diagnose the problem.

EDIT: When I cd to the ffi gem (mentioned in the second but last line), and run the rake line in line 6, I get "Could not find RubyGem rake-compiler".

After gem i rake-compiler, and run rake again, I get this:

```<code>configure: error: source directory already configured; run "make distclean" there first
make: *** [/home/mdemare/.rvm/gems/ruby-1.9.2-p136/gems/ffi-1.0.6/build/x86_64-linux/ffi_c/1.9.2/libffi/.libs/libffi_convenience.a] Error 1
rake aborted!
Command failed with status (2): [make...]
</code>```

Update:

These are my rake gemspecs:

```<code>~ - 10:59>find ~/.rvm/ -name 'rake-0.8.7.gemspec'
~/.rvm/gems/ruby-1.9.2-p136/specifications/rake-0.8.7.gemspec
~/.rvm/gems/ruby-1.9.2-p136@global/specifications/rake-0.8.7.gemspec
~/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/gems/1.9.1/specifications/rake-0.8.7.gemspec
</code>```

The last one is where gem looks, but that gemspec is different from the first one, and doesn't include the executable. Copying the long one doesn't quite solve the problem though - I get a file not found for the rake executable.

答:
Thanks @Tim Morris and @danv, your answers / comments helped. I adjusted for my setup, which is based more towards a superuser environment. Now this is what /usr/local/rvm/gems/ruby-1.9.2-p180/bin/rake looks like on my server:</p>

```<code>require 'rubygems'

version = ">= 0"
ENV['GEM_HOME']=ENV['GEM_HOME'] || "/usr/local/rvm/gems/ruby-1.9.2-p180"
ENV['GEM_PATH']=ENV['GEM_PATH'] || "/usr/local/rvm/gems/ruby-1.9.2-p180:/usr/local/rvm/gems/ruby-1.9.2-p180@global"

if ARGV.first =~ /^_(.*)_$/ and Gem::Version.correct? $1 then
  version = $1
  ARGV.shift
end

gem 'rake', version
load Gem.bin_path('rake', 'rake', version)
</code>```

Body:
I get an error while trying to install the ffi gem:

~ - 16:54>gem i ffi
Building native extensions.  This could take a while...
ERROR:  Error installing ffi:
        ERROR: Failed to build gem native extension.

        rake RUBYARCHDIR=/home/mdemare/.rvm/gems/ruby-1.9.2-p136/gems/ffi-1.0.6/lib RUBYLIBDIR=/home/mdemare/.rvm/gems/ruby-1.9.2-p136/gems/ffi-1.0.6/lib
/home/mdemare/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/site_ruby/1.9.1/rubygems.rb:370:in `bin_path': can't find gem rake ([">= 0"]) with executable rake (Gem::GemNotFoundException)
        from /home/mdemare/.rvm/gems/ruby-1.9.2-p136/bin/rake:19:in `'

Gem files will remain installed in /home/mdemare/.rvm/gems/ruby-1.9.2-p136/gems/ffi-1.0.6 for inspection.
Results logged to /home/mdemare/.rvm/gems/ruby-1.9.2-p136/gems/ffi-1.0.6/gen/gem_make.out

I'm getting frequent errors of all kinds while installing gems with native extensions, so I assume that there's something broken with my Ubuntu installation, but I've no idea what. I'll post any information you need to diagnose the problem.

EDIT: When I cd to the ffi gem (mentioned in the second but last line), and run the rake line in line 6, I get "Could not find RubyGem rake-compiler".

After gem i rake-compiler, and run rake again, I get this:

configure: error: source directory already configured; run "make distclean" there first
make: *** [/home/mdemare/.rvm/gems/ruby-1.9.2-p136/gems/ffi-1.0.6/build/x86_64-linux/ffi_c/1.9.2/libffi/.libs/libffi_convenience.a] Error 1
rake aborted!
Command failed with status (2): [make...]

Update:

These are my rake gemspecs:

~ - 10:59>find ~/.rvm/ -name 'rake-0.8.7.gemspec'
~/.rvm/gems/ruby-1.9.2-p136/specifications/rake-0.8.7.gemspec
~/.rvm/gems/ruby-1.9.2-p136@global/specifications/rake-0.8.7.gemspec
~/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/gems/1.9.1/specifications/rake-0.8.7.gemspec

The last one is where gem looks, but that gemspec is different from the first one, and doesn't include the executable. Copying the long one doesn't quite solve the problem though - I get a file not found for the rake executable.

Body:
Thanks @Tim Morris and @danv, your answers / comments helped. I adjusted for my setup, which is based more towards a superuser environment. Now this is what /usr/local/rvm/gems/ruby-1.9.2-p180/bin/rake looks like on my server:

require 'rubygems'

version = ">= 0"
ENV['GEM_HOME']=ENV['GEM_HOME'] || "/usr/local/rvm/gems/ruby-1.9.2-p180"
ENV['GEM_PATH']=ENV['GEM_PATH'] || "/usr/local/rvm/gems/ruby-1.9.2-p180:/usr/local/rvm/gems/ruby-1.9.2-p180@global"

if ARGV.first =~ /^_(.*)_$/ and Gem::Version.correct? $1 then
  version = $1
  ARGV.shift
end

gem 'rake', version
load Gem.bin_path('rake', 'rake', version)


问:
I want to search and create listview inside viewpager how it is possible
I want to search from activity and create list on the basis of search result inside the fragment ( In View Pager  ).

```<code>public interface SearchImpl {
      public void searchQuery(String val);
}
</code>```

Fragment

```<code>public class MyFragment extends Fragment implements SearchImpl {

    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
         view = inflater.inflate(R.layout.fragment_almanca, container, false);
        return view;
    }

    @Override
    public void searchQuery(String val) {
       Log.e("getted", val);
    }
}
</code>```

Acitivty

```<code> @Override
</code>```

public boolean onCreateOptionsMenu(Menu menu) {

```<code>getMenuInflater().inflate(R.menu.main, menu);

SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
        Log.e("setted", "" + query);
        try {
            MyFragment myFGM=new MyFragment();
            myFGM.searchQuery(query);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        return false;
    }
});
return super.onCreateOptionsMenu(menu);
}
</code>```

I am getting null pointer exception for ListView inside fragment.

答:
Instead of using a SearchView try to use the EditText. Add a TextWatcher to it..

```<code>private TextWatcherListener watcherListener;

edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start,
                                          int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start,
                                      int before, int count) {
                    watcherListener.onEditBoxEdited(String.valueOf(s));
            }
        });

    }
</code>```

Create a method and use this method in a fragment.

```<code>public void setWatcherListener(TextWatcherListener listener) {
        watcherListener = listener;
    }
</code>```

In fragment

```<code>((ActivityName) getActivity()).setWatcherListener(new TextWatcherListener() {
                                @Override
                                public void onEditBoxEdited(String value) {
                                    //Do something with value
                                }
                            });
</code>```

There's no need of an interface as you can access the methods from an activity through a fragment.

Body:
I want to search from activity and create list on the basis of search result inside the fragment ( In View Pager  ).

public interface SearchImpl {
      public void searchQuery(String val);
}

Fragment

public class MyFragment extends Fragment implements SearchImpl {

    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
         view = inflater.inflate(R.layout.fragment_almanca, container, false);
        return view;
    }

    @Override
    public void searchQuery(String val) {
       Log.e("getted", val);
    }
}

Acitivty

 @Override

public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.main, menu);

SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
        Log.e("setted", "" + query);
        try {
            MyFragment myFGM=new MyFragment();
            myFGM.searchQuery(query);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        return false;
    }
});
return super.onCreateOptionsMenu(menu);
}

I am getting null pointer exception for ListView inside fragment.

Body:
Instead of using a SearchView try to use the EditText. Add a TextWatcher to it..

private TextWatcherListener watcherListener;

edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start,
                                          int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start,
                                      int before, int count) {
                    watcherListener.onEditBoxEdited(String.valueOf(s));
            }
        });

    }

Create a method and use this method in a fragment.

public void setWatcherListener(TextWatcherListener listener) {
        watcherListener = listener;
    }

In fragment

((ActivityName) getActivity()).setWatcherListener(new TextWatcherListener() {
                                @Override
                                public void onEditBoxEdited(String value) {
                                    //Do something with value
                                }
                            });

There's no need of an interface as you can access the methods from an activity through a fragment.


问:
How to fetch certain column data from datasource?
I want to fetch the specified column from a data source(i.e. exclude certain columns) because even I don't show the data in UI, the data is loaded. (it is visible from Network tabs in Browser DevTools).

So far, I found the automatic data load and query builder/ query script provide the filters and sorting of the data but loads all the columns.

I have tried record owner security and role based security but this will make the data inaccessible to some users.

答:
You can try creating a Calculated SQL Model to limit columns being pulled.

Let's take an example where you have a Student model with Name and City as the only two fields. You can add a new Calculated SQL with this SQL query and only Name column would be pulled.

```<code>SELECT Name FROM Student
</code>```

Please refer to the official guide here. Feel free to comment if you want some clarification!

Hope this helps.

Body:
You can try creating a Calculated SQL Model to limit columns being pulled.

Let's take an example where you have a Student model with Name and City as the only two fields. You can add a new Calculated SQL with this SQL query and only Name column would be pulled.

SELECT Name FROM Student

Please refer to the official guide here. Feel free to comment if you want some clarification!

Hope this helps.


问:
Checkbox-based selection doesn't work with bootstrap themes
I'm using kendo-grid with checkbox-based selection, as per version ^2017.2.621. The selection checkboxes are working until I add bootstrap theme.

The grid is initialized like this:

```<code>$(this.$refs.kendogrid).kendoGrid({
  dataSource: [
    { id: "1", title: "name 1" },
    { id: "2", title: "name 2" },
    { id: "3", title: "name 3" }
  ],
  columns: [
    { selectable: true },
    { field: "id", title: "ID number" },
    { field: "title", title: "Title" }
  ]
});
</code>```

Then I just import themes:

```<code>import "@progress/kendo-theme-bootstrap/dist/all.css";
import "bootstrap";
</code>```

And voila - any checkbox now is just a gray field and doesn't react to clicks (and it's not just visual, the selection doesn't work underneath).

Any solutions? Surely someone should have used kendo-grid selection with bootstrap since 2017...

答:
Found the issue: kendo is garbage and full of bugs.

2017.2.621 doesn't work with bootstrap-theming properly because it doesn't create a link between labels and checkboxes, so clicking on a label doesn't change the state of checkbox linked (because it's not linked at all).

One need to upgrade to a newer version or manually fix SELECTCOLUMNTMPL and SELECTCOLUMNHEADERTMPL properties in kendo.grid.js source file.

Body:
I'm using kendo-grid with checkbox-based selection, as per version ^2017.2.621. The selection checkboxes are working until I add bootstrap theme.

The grid is initialized like this:

$(this.$refs.kendogrid).kendoGrid({
  dataSource: [
    { id: "1", title: "name 1" },
    { id: "2", title: "name 2" },
    { id: "3", title: "name 3" }
  ],
  columns: [
    { selectable: true },
    { field: "id", title: "ID number" },
    { field: "title", title: "Title" }
  ]
});

Then I just import themes:

import "@progress/kendo-theme-bootstrap/dist/all.css";
import "bootstrap";

And voila - any checkbox now is just a gray field and doesn't react to clicks (and it's not just visual, the selection doesn't work underneath).

Any solutions? Surely someone should have used kendo-grid selection with bootstrap since 2017...


问:
How to use varchar in node.js sequelize?
I'm using Sequelize 4.42.0 in Node.js, and I want to create some fields in SQL Server 2014, with type of varchar(100).

According to the docs, DataTypes.STRING should be map to Varchar.

And I'm using below code:

```<code>const sequlize = new Sequelize("Test", "komeil", "1234", {
host: "localhost",
dialect: "mssql",
operatorsAliases: false,
define: {
    timestamps: false
}
,
logging: false
});
const User2 = sequlize.define("User2", {
Id: {
    type: Sequlize.STRING(100),
    primaryKey: true,
    allowNull: false
}
}, { freezeTableName: true });
</code>```

I expecting varchar(100) field, but it generates nvarchar(100)

答:
Seems it is an error in docs: see
https://github.com/sequelize/sequelize/issues/6036</p>

Body:
I'm using Sequelize 4.42.0 in Node.js, and I want to create some fields in SQL Server 2014, with type of varchar(100).

According to the docs, DataTypes.STRING should be map to Varchar.

And I'm using below code:

const sequlize = new Sequelize("Test", "komeil", "1234", {
host: "localhost",
dialect: "mssql",
operatorsAliases: false,
define: {
    timestamps: false
}
,
logging: false
});
const User2 = sequlize.define("User2", {
Id: {
    type: Sequlize.STRING(100),
    primaryKey: true,
    allowNull: false
}
}, { freezeTableName: true });

I expecting varchar(100) field, but it generates nvarchar(100)


问:
Unshift array method slow downs Dom listing
I wanna replace img src using array unshift method, while doing this process the previous image is shown from 2 to 3 seconds and then replace my new image url

```<code>   var data = {"id":"124", "url":"img.jpg"};
   var data1 = {"id":"1234", "url":"img1.png"};
   var array = [data];
   array.unshift(data1);

</code>```

```

I have expected the new data comes without any delay, and never shown the previous image url, but unfortunately i faced the problem of previous image data load first then change the new one.

答:
Try this, it will works for you.

```

```$(".imageLoad").load(function() {
  // Image loaded do action
}).each(function() {
  if(this.complete){
       $(this).load();
       (or use, if you have class ng-hide)
       $(".imageLoad").removeClass('ng-hide');
   }
});
```

Body:
I wanna replace img src using array unshift method, while doing this process the previous image is shown from 2 to 3 seconds and then replace my new image url

   var data = {"id":"124", "url":"img.jpg"};
   var data1 = {"id":"1234", "url":"img1.png"};
   var array = [data];
   array.unshift(data1);

I have expected the new data comes without any delay, and never shown the previous image url, but unfortunately i faced the problem of previous image data load first then change the new one.

Body:
Try this, it will works for you.

<img class="imageLoad ng-hide" ng-src = data.url />

$(".imageLoad").load(function() {
  // Image loaded do action
}).each(function() {
  if(this.complete){
       $(this).load();
       (or use, if you have class ng-hide)
       $(".imageLoad").removeClass('ng-hide');
   }
});


问:
Invalid transport, must be an object with a log method winston mongodb logging
I want to store my error logs in mongoDB collection. I am using winston & winston -mongoDB.

Getting the error:

throw new Error('Invalid transport, must be an object with a log
  method.'); Error: Invalid transport, must be an object with a log
  method.

Here is the code in logger file.
    Here is my code:
    import appRoot from 'app-root-path';
    import {
        createLogger,
        transports,
        format,
    } from 'winston';

```<code>import * as winston from 'winston';

require('winston-mongodb');

const options = {
    fileInfo: {
        level: 'info',
        filename: `${appRoot}/logs/info.log`,
        handleExceptions: true,
        json: true,
        maxsize: 5242880, // 5MB
        maxFiles: 5,
        colorize: false,
        timestamp: true,
    },
    mongoDB: {
        db: 'mongodb://127.0.0.1:27017/test',
        collection: 'log',
        level: 'info',
        storeHost: true,
        capped: true,
    },
};

winston.add(winston.transports.MongoDB, options.mongoDB);

const logger = createLogger({
    format: format.combine(
        format.timestamp({
            format: 'YYYY-MM-DD HH:mm:ss',
        }),
        format.json()
    ),
    transports: [
        new transports.File(options.fileInfo)
    ],
});

logger.stream = {
    write: (message, encoding) => {
        logger.info(message);
    },
};

export default logger;
</code>```

Versions:

```<code> "mongoose": "^5.2.6",
    "morgan": "^1.9.0",
    "winston": "^3.0.0",
    "winston-mongodb": "^4.0.3",
    mongodb@3.1.1
</code>```

答: I had the similar problem so what I did is alter the package.json with the line from "winston": "^3.0.0" to "winston": "2.*" then entered this command npm install -save winston in the command line

Body:
I want to store my error logs in mongoDB collection. I am using winston & winston -mongoDB.

Getting the error:

throw new Error('Invalid transport, must be an object with a log
  method.'); Error: Invalid transport, must be an object with a log
  method.

Here is the code in logger file.
    Here is my code:
    import appRoot from 'app-root-path';
    import {
        createLogger,
        transports,
        format,
    } from 'winston';

import * as winston from 'winston';

require('winston-mongodb');

const options = {
    fileInfo: {
        level: 'info',
        filename: `${appRoot}/logs/info.log`,
        handleExceptions: true,
        json: true,
        maxsize: 5242880, // 5MB
        maxFiles: 5,
        colorize: false,
        timestamp: true,
    },
    mongoDB: {
        db: 'mongodb://127.0.0.1:27017/test',
        collection: 'log',
        level: 'info',
        storeHost: true,
        capped: true,
    },
};

winston.add(winston.transports.MongoDB, options.mongoDB);

const logger = createLogger({
    format: format.combine(
        format.timestamp({
            format: 'YYYY-MM-DD HH:mm:ss',
        }),
        format.json()
    ),
    transports: [
        new transports.File(options.fileInfo)
    ],
});

logger.stream = {
    write: (message, encoding) => {
        logger.info(message);
    },
};

export default logger;

Versions:

 "mongoose": "^5.2.6",
    "morgan": "^1.9.0",
    "winston": "^3.0.0",
    "winston-mongodb": "^4.0.3",
    mongodb@3.1.1


问:
How to exec bash script w/o exiting shell
I want to execute a bash script in the current shell, not a subshell/subprocess. I believe using exec allows you to do that.
But if I run:

```<code>exec ./my_script.sh
</code>```

the shell will exit and it will say "process completed". Is there a way to execute a script in the same shell somehow w/o exiting the process.

note the only thing my_script.sh does is:

```<code>export foo=bar
</code>```

but if there was some error in my script, it didn't appear in the console.

答:
man page says:-

exec [-cl] [-a name] [command [arguments]]
        If command is specified, it replaces the shell.  No new  process
        is  created.  The arguments become the arguments to command.  If
        the -l option is supplied,  the  shell  places  a  dash  at  the
        beginning  of  the  zeroth  argument passed to command.This is
        what login(1) does.  The -c option causes command to be executed
        with  an empty environment.

if you want to execute a bash script in the current shell,you can try

bash my_script.sh or ./my_script.sh

Body:
I want to execute a bash script in the current shell, not a subshell/subprocess. I believe using exec allows you to do that.
But if I run:

exec ./my_script.sh

the shell will exit and it will say "process completed". Is there a way to execute a script in the same shell somehow w/o exiting the process.

note the only thing my_script.sh does is:

export foo=bar

but if there was some error in my script, it didn't appear in the console.


问:
Flexbox item does not shrink when only one item
In flexbox, if you set flex-flow: column nowrap and the elements inside have non-zero value of flex shrink, they should shrink down to all fit inside the flex container.

I have found that if you have only one item in this container and it has content bigger than the flex-container then it will not shrink down. But if other elements are included in the container (if it is not the only item) then it will shrink down.

Best visualized in this CodePen.

Here is the same code from the CodePen.

.container {
  padding: 10px;
  height: 100px;
  width: 100px;
  background: red;
  margin: 5px 20px;
  display: flex;
  flex-flow: column nowrap;
  align-items: center;
}

.item {
  width: 80px;
  height: 40px;
  background: blue;
  margin: 5px;
  /* same as
  flex: 1 1 40px;
  */
}

.super.item {
  height: 200px;
}

.item div {
  width: 10px;
  height: 150px;
  background: black;
}

body {
  margin: 0;
  display: flex;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'>
  </div>
</div>

<div class='container'>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'>
    <div></div>
  </div>
</div>

<div class='container'>
  <div class='item super'>
  </div>
</div>

<div class='container'>
  <div class='item super'>
    <div></div>
  </div>
</div></code>```

Is there an explanation on why that last div does not shrink to fit the flex container?

答:
I don't know if you are talking about it or not.
Your div is taking width and height as item.
so whenever you add another div it will add height of 150px.</p>

```<code>.item div{
  width: 10px;
  height: 150px;
  background: black;
}
</code>```

Body:
In flexbox, if you set flex-flow: column nowrap and the elements inside have non-zero value of flex shrink, they should shrink down to all fit inside the flex container.

I have found that if you have only one item in this container and it has content bigger than the flex-container then it will not shrink down. But if other elements are included in the container (if it is not the only item) then it will shrink down.

Best visualized in this CodePen.

Here is the same code from the CodePen.

.container {
  padding: 10px;
  height: 100px;
  width: 100px;
  background: red;
  margin: 5px 20px;
  display: flex;
  flex-flow: column nowrap;
  align-items: center;
}

.item {
  width: 80px;
  height: 40px;
  background: blue;
  margin: 5px;
  /* same as
  flex: 1 1 40px;
  */
}

.super.item {
  height: 200px;
}

.item div {
  width: 10px;
  height: 150px;
  background: black;
}

body {
  margin: 0;
  display: flex;
}

Is there an explanation on why that last div does not shrink to fit the flex container?

Body:
I don't know if you are talking about it or not.
Your div is taking width and height as item.
so whenever you add another div it will add height of 150px.

.item div{
  width: 10px;
  height: 150px;
  background: black;
}


问:
Is it possible to upload 3D models to Google Maps?
I am interested if it is possible to add 3D models of buildings in Google Maps? Although Google (and community) have 3D mapped biggest cities, there a lot of cities that remain flat (2D), but have interesting landscape and tall buildings that stand out. For example, my hometown Rīga, Latvia.

As I searched this question, a lot of resources came up that states "nope, the community can no longer add 3D models - Google is now mapping everything with satellites".. but that info is 2-5 years old. And information in different forums is conflicting, so it is worth a shot for a new discussion.

There is even SE question with exactly the same question. Since more than 2.5 years have passed I feel that things might have changed, so please do not mark this as a duplicate to a super-old post. :)

Question - is this true?
Or (even today) it is possible to add 3D models to Google Maps? If yes, then please provide any guide/link/information how to do it.

答:
Seems like it still is not possible.

Hello @Diezvai No, It isn't possible right now.

Several years ago when Sketchup was still for Google, we had this
  ability to create 3D models and submit them for public visibility on
  Google Earth as dear @ermest mentioned. Also in Map Maker we had some
  basic tools to create simple 3D models of buildings but both retired
  years ago. Even we missed the tool for creating flat polygons!

After that (and also simultaneously in labs) Google focused on smart
  modeling the world. These days system gathers needed information and
  images from many resources like satellite, aerial photography, photos
  from users, street view photography and many others to generate 3D
  models of buildings, trees and even cars! Also system doing same for
  showing simple models of buildings on Google Maps.

So there is no tool for users to create 3D models and upload them to
  Google Maps or Google Earth. Maybe currently smart 3D modeling aren't
  available in somewhere (like Iran for example) but by improving
  artificial intelligence and more data one day they will.

Source - https://www.localguidesconnect.com/t5/General-Discussion/Is-it-possible-to-upload-3D-models-to-Google-Maps/m-p/1802100/highlight/false#M495932


问:
Node.JS: Cannot connect to Microsoft Azure Database when using Sequelize
I am trying to connect Azure database using the express + Sequelize. I cannot get connection to work.

I have modified the database.json connection file like this:

```<code>"development": {
    "username": "XXX",
    "password": "XXX",
    "database": "XXX",
    "host": "XXX",
    "dialect": "mssql",
    "port": 1433,
    "dialectOptions": {
      "encrypt": true
    }
  }
</code>```

I try to connect with sequelizer like this

```<code>  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}
</code>```

I get error message:
https://i.imgur.com/FQdZCeZ.png

If I directly change Sequelize connection without using the JSON file and connect it like this:

```<code>sequelize = new Sequelize('XXX', 'XXX', 'XXX', { host: 'XXX', dialect: 'mssql', dialectOptions: { options: { encrypt: true } } });
</code>```

I get error about Username being empty:
https://i.imgur.com/JbkOgIU.png

I have tried connection with MySql and everything works in there. Problems are only when connecting to Azure database. Any help would be great guys! Thank you.

答: Got it working! I didnt have Tedious Installed. Aftet that all is working.</p>

Body:
I am trying to connect Azure database using the express + Sequelize. I cannot get connection to work.

I have modified the database.json connection file like this:

"development": {
    "username": "XXX",
    "password": "XXX",
    "database": "XXX",
    "host": "XXX",
    "dialect": "mssql",
    "port": 1433,
    "dialectOptions": {
      "encrypt": true
    }
  }

I try to connect with sequelizer like this

  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

I get error message:
https://i.imgur.com/FQdZCeZ.png

If I directly change Sequelize connection without using the JSON file and connect it like this:

sequelize = new Sequelize('XXX', 'XXX', 'XXX', { host: 'XXX', dialect: 'mssql', dialectOptions: { options: { encrypt: true } } });

I get error about Username being empty:
https://i.imgur.com/JbkOgIU.png

I have tried connection with MySql and everything works in there. Problems are only when connecting to Azure database. Any help would be great guys! Thank you.


问:
Escape special characters in HTML
I'm wondering whether I can escape special characters in Html without using
Html Number:

```<code>%#60 = <
%#62 = >
</code>```

I know I need to use %#60 to represent '<' in Html

Is any special tags that can escape all special character?

e.g.

```<code><special_tag>
any special characters can be shown without using Html Numbers
</special_tag>
</code>```

答:
Wrap it in pre tag

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

Title: Escape special characters in HTML

Body:
I'm wondering whether I can escape special characters in Html without using
Html Number:

%#60 = <
%#62 = >

I know I need to use %#60 to represent '<' in Html

Is any special tags that can escape all special character?

e.g.

<special_tag>
any special characters can be shown without using Html Numbers
</special_tag>

Body:
Wrap it in pre tag

<pre>
    >
</pre>


问:
Save Email attachments to Google drive Attachment name deletes the letter automatically
I have created the flow to save my outlook attachment to save it google drive as a separate folder when ever I receive email with attachment.

But the problem is on the below highlighted screenshot when I type really slowly to the core Attachments From in the folder path it works but if I do the normal typing it keeps on deleting the letter. Any idea how to fix this behavior.

答:
The point is you probably have selected some destination folder from drop-down menu and that is why such a miracle happens. And I guess it is not a bug but a feature.

How to overcome that? Just type/paste your desired value or add a dynamic content (or both).


问:
Error occurred in the mediation of the class mediator WSO2 ESB
I used wso2 esb 5.0 for create proxy services. I created proxy service using class mediator. Below is the java class.

```<code>public class CalculatePaymentAmount extends AbstractMediator {

    public boolean mediate(MessageContext messageContext) {

        String noOfMonths = messageContext.getEnvelope().getBody().getFirstElement().
                getFirstChildWithName(new QName("noOfMonths")).getText();

        String InsuranceRate = messageContext.getEnvelope().getBody().getFirstElement().
                getFirstChildWithName(new QName("InsuranceRate")).getText();

        DecimalFormat decimalFormat = new DecimalFormat("#.##");

        double totalAmount = Double.parseDouble(noOfMonths) * Double.parseDouble(InsuranceRate);

        messageContext.setProperty("noOfMonths", noOfMonths);
        messageContext.setProperty("paymentAmount", decimalFormat.format(totalAmount));

        return true;
    }

    public String getType() {
        return null;
    }

    public void setTraceState(int traceState) {
        traceState = 0;
    }

    public int getTraceState() {
        return 0;
    }

}
</code>```

I created the proxy service using class mediator. Below define the proxy code.

```<code><?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="PaymentAmountProxy"
       startOnLoad="true"
       statistics="disable"
       trace="disable"
       transports="http,https">
   <target>
      <inSequence>
         <log/>
         <class name="com.mediator.java.CalculatePaymentAmount"/>
         <property expression="get-property('default','noOfMonths')"
                   name="getNoOfMonths"
                   scope="default"
                   type="STRING"/>
         <property expression="get-property('default','paymentAmount')"
                   name="getPaymentAmount"
                   scope="default"
                   type="STRING"/>
         <log>
            <property expression="get-property('default','getNoOfMonths')"
                      name="No.Of Months:"/>
            <property expression="get-property('default','getPaymentAmount')"
                      name="Paymrent Amount:"/>
         </log>
      </inSequence>
   </target>
   <description/>
</proxy>
</code>```

This one working fine and gave expected response.
But when I use this class mediator with other mediators, it getting errors when I invoked the proxy service.
Below mentioned the proxy service that I used with class mediator.

```<code><?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="LatestLicenseRenewalSystem"
       startOnLoad="true"
       statistics="disable"
       trace="disable"
       transports="http,https">
   <target>
      <inSequence>
         <log/>
         <property expression="get-property('transport','VehicleNo')"
                   name="vehicleNo"
                   scope="default"
                   type="STRING"/>
         <log>
            <property expression="get-property('default','vehicleNo')" name="VehicleNo"/>
         </log>
         <payloadFactory media-type="xml">
            <format>
               <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                                 xmlns:wsa="http://www.w3.org/2005/08/addressing"
                                 xmlns:sam="http://sample.esb.org">
                  <soapenv:Header/>
                  <soapenv:Body>
                     <sam:getPolicyID>
                        <sam:vehicleNumber>$1</sam:vehicleNumber>
                     </sam:getPolicyID>
                  </soapenv:Body>
               </soapenv:Envelope>
            </format>
            <args>
               <arg evaluator="xml" expression="get-property('default','vehicleNo')"/>
            </args>
         </payloadFactory>
         <log level="full"/>
         <header name="Action" scope="default" value="urn:getCertificateID"/>
         <call>
            <endpoint>
               <address format="soap12"
                        uri="http://172.17.0.1:9763/services/EmissionTestService.EmissionTestServiceHttpSoap12Endpoint/">
                  <enableAddressing/>
               </address>
            </endpoint>
         </call>
         <log level="full"/>
         <property xmlns:ns="http://sample.esb.org"
                   expression="//ns:getCertificateIDResponse/ns:return"
                   name="certificateID"
                   scope="default"
                   type="STRING"/>
         <log>
            <property expression="get-property('default','certificateID')"
                      name="CertificateID"/>
         </log>
         <class name="com.mediator.java.CalculatePaymentAmount"/>
         <property expression="get-property('default','noOfMonths')"
                   name="getNoOfMonths"
                   scope="default"
                   type="STRING"/>
         <property expression="get-property('default','paymentAmount')"
                   name="getPaymentAmount"
                   scope="default"
                   type="STRING"/>
         <log>
            <property expression="get-property('default','getNoOfMonths')"
                      name="No.Of Months:"/>
            <property expression="get-property('default','getPaymentAmount')"
                      name="Paymrent Amount:"/>
         </log>
         <respond/>
      </inSequence>
   </target>
   <description/>
</proxy>
</code>```

Below error is occurred when invoking the above proxy service.

```<code>LogMediator To: http://www.w3.org/2005/08/addressing/anonymous, WSAction: urn:getCertificateIDResponse, SOAPAction: urn:getCertificateIDResponse, ReplyTo: http://www.w3.org/2005/08/addressing/anonymous, MessageID: urn:uuid:6f4557eb-b8ff-4c19-bbe8-4c7e929d8386, Direction: request, MESSAGE = Executing default 'fault' sequence, ERROR_CODE = 0, ERROR_MESSAGE = Error occured in the mediation of the class mediator, Envelope: <?xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"><soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing"><wsa:Action>urn:getCertificateIDResponse</wsa:Action><wsa:RelatesTo>urn:uuid:6f4557eb-b8ff-4c19-bbe8-4c7e929d8386</wsa:RelatesTo></soapenv:Header><soapenv:Body><ns:getCertificateIDResponse xmlns:ns="http://sample.esb.org"><ns:return>-1250719063</ns:return></ns:getCertificateIDResponse></soapenv:Body></soapenv:Envelope>
</code>```

Can anyone help me to solve this. Any help or workarounds are really appreciated.

答:
For solve this issue, use payloadFactory mediator before the class mediator and set the parameters for the payload. I mentioned below the code.</p>

```<code><payloadFactory media-type="xml">
            <format>
               <paymentDetails xmlns="">
                  <noOfMonths>$1</noOfMonths>
                  <InsuranceRate>$2</InsuranceRate>
               </paymentDetails>
            </format>
            <args>
               <arg evaluator="xml" expression="get-property('default','noOfMonths')"/>
               <arg evaluator="xml" expression="get-property('default','InsuranceRate')"/>
            </args>
         </payloadFactory>
         <class name="com.mediator.java.CalculatePaymentAmount"/>
</code>```

Body:
I used wso2 esb 5.0 for create proxy services. I created proxy service using class mediator. Below is the java class.

public class CalculatePaymentAmount extends AbstractMediator {

    public boolean mediate(MessageContext messageContext) {

        String noOfMonths = messageContext.getEnvelope().getBody().getFirstElement().
                getFirstChildWithName(new QName("noOfMonths")).getText();

        String InsuranceRate = messageContext.getEnvelope().getBody().getFirstElement().
                getFirstChildWithName(new QName("InsuranceRate")).getText();

        DecimalFormat decimalFormat = new DecimalFormat("#.##");

        double totalAmount = Double.parseDouble(noOfMonths) * Double.parseDouble(InsuranceRate);

        messageContext.setProperty("noOfMonths", noOfMonths);
        messageContext.setProperty("paymentAmount", decimalFormat.format(totalAmount));

        return true;
    }

    public String getType() {
        return null;
    }

    public void setTraceState(int traceState) {
        traceState = 0;
    }

    public int getTraceState() {
        return 0;
    }

}

I created the proxy service using class mediator. Below define the proxy code.

<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="PaymentAmountProxy"
       startOnLoad="true"
       statistics="disable"
       trace="disable"
       transports="http,https">
   <target>
      <inSequence>
         <log/>
         <class name="com.mediator.java.CalculatePaymentAmount"/>
         <property expression="get-property('default','noOfMonths')"
                   name="getNoOfMonths"
                   scope="default"
                   type="STRING"/>
         <property expression="get-property('default','paymentAmount')"
                   name="getPaymentAmount"
                   scope="default"
                   type="STRING"/>
         <log>
            <property expression="get-property('default','getNoOfMonths')"
                      name="No.Of Months:"/>
            <property expression="get-property('default','getPaymentAmount')"
                      name="Paymrent Amount:"/>
         </log>
      </inSequence>
   </target>
   <description/>
</proxy>

This one working fine and gave expected response.
But when I use this class mediator with other mediators, it getting errors when I invoked the proxy service.
Below mentioned the proxy service that I used with class mediator.

<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="LatestLicenseRenewalSystem"
       startOnLoad="true"
       statistics="disable"
       trace="disable"
       transports="http,https">
   <target>
      <inSequence>
         <log/>
         <property expression="get-property('transport','VehicleNo')"
                   name="vehicleNo"
                   scope="default"
                   type="STRING"/>
         <log>
            <property expression="get-property('default','vehicleNo')" name="VehicleNo"/>
         </log>
         <payloadFactory media-type="xml">
            <format>
               <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                                 xmlns:wsa="http://www.w3.org/2005/08/addressing"
                                 xmlns:sam="http://sample.esb.org">
                  <soapenv:Header/>
                  <soapenv:Body>
                     <sam:getPolicyID>
                        <sam:vehicleNumber>$1</sam:vehicleNumber>
                     </sam:getPolicyID>
                  </soapenv:Body>
               </soapenv:Envelope>
            </format>
            <args>
               <arg evaluator="xml" expression="get-property('default','vehicleNo')"/>
            </args>
         </payloadFactory>
         <log level="full"/>

         <call>
            <endpoint>
               <address format="soap12"
                        uri="http://172.17.0.1:9763/services/EmissionTestService.EmissionTestServiceHttpSoap12Endpoint/">
                  <enableAddressing/>
               </address>
            </endpoint>
         </call>
         <log level="full"/>
         <property xmlns:ns="http://sample.esb.org"
                   expression="//ns:getCertificateIDResponse/ns:return"
                   name="certificateID"
                   scope="default"
                   type="STRING"/>
         <log>
            <property expression="get-property('default','certificateID')"
                      name="CertificateID"/>
         </log>
         <class name="com.mediator.java.CalculatePaymentAmount"/>
         <property expression="get-property('default','noOfMonths')"
                   name="getNoOfMonths"
                   scope="default"
                   type="STRING"/>
         <property expression="get-property('default','paymentAmount')"
                   name="getPaymentAmount"
                   scope="default"
                   type="STRING"/>
         <log>
            <property expression="get-property('default','getNoOfMonths')"
                      name="No.Of Months:"/>
            <property expression="get-property('default','getPaymentAmount')"
                      name="Paymrent Amount:"/>
         </log>
         <respond/>
      </inSequence>
   </target>
   <description/>
</proxy>

Below error is occurred when invoking the above proxy service.

LogMediator To: http://www.w3.org/2005/08/addressing/anonymous, WSAction: urn:getCertificateIDResponse, SOAPAction: urn:getCertificateIDResponse, ReplyTo: http://www.w3.org/2005/08/addressing/anonymous, MessageID: urn:uuid:6f4557eb-b8ff-4c19-bbe8-4c7e929d8386, Direction: request, MESSAGE = Executing default 'fault' sequence, ERROR_CODE = 0, ERROR_MESSAGE = Error occured in the mediation of the class mediator, Envelope: <?xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"><soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing"><wsa:Action>urn:getCertificateIDResponse</wsa:Action><wsa:RelatesTo>urn:uuid:6f4557eb-b8ff-4c19-bbe8-4c7e929d8386</wsa:RelatesTo></soapenv:Header><soapenv:Body><ns:getCertificateIDResponse xmlns:ns="http://sample.esb.org"><ns:return>-1250719063</ns:return></ns:getCertificateIDResponse></soapenv:Body></soapenv:Envelope>

Can anyone help me to solve this. Any help or workarounds are really appreciated.

Body:
For solve this issue, use payloadFactory mediator before the class mediator and set the parameters for the payload. I mentioned below the code.

<payloadFactory media-type="xml">
            <format>
               <paymentDetails xmlns="">
                  <noOfMonths>$1</noOfMonths>
                  <InsuranceRate>$2</InsuranceRate>
               </paymentDetails>
            </format>
            <args>
               <arg evaluator="xml" expression="get-property('default','noOfMonths')"/>
               <arg evaluator="xml" expression="get-property('default','InsuranceRate')"/>
            </args>
         </payloadFactory>
         <class name="com.mediator.java.CalculatePaymentAmount"/>


问:
How to make a function as default in azure function app?
I have an azure function app (abc.azurewebsites.net) and have a function named Function1 defined in it. (abc.azurewebsites.net/api/Function1?code=def==)

Is there a way in which, I can define this Function1 as default and all the incoming requests to abc.azurewebsites.net gets routed to my Function1?

Thanks.

答:
You could use proxy to get this.

Follow this tutorial, and the Route template should be /, and then you should change your function authLevel to anonymous like this.

1.Set the application setting add HELLO_HOST(any parameter same as the backend url) with value <YourBackendApp>.azurewebsites.net.

2.Create the proxy.

3.Set your function to anonymous then your function don't need API keys code to call it.

Then below my test result, it's a HTTP trigger function with query string &name=<yourname>.


问:
Form button not being disabled
I have a form button that is not being disabled. I am doing a check to see if password match and meet a minimum length. Here is my code

```<code>  <div id="wrapper">
    <section>
      <div class="page-container">
        <p class="profile-details">
          Please enter a username and password to create your profile
        </p>
        <form [formGroup]="profileDetailsForm">
          <div>
            <label for="username">Username</label>
            <input id="username" type="text" formControlName="username" size="50" />
          </div>
          <div>
            <label for="password">Password</label>
            <input id="password" type="password" formControlName="password" />
          </div>
          <div>
            <label for="confirmPassword">Confirm Password</label>
            <input
              type="password"
              id="confirmPassword"
              (ngModelChange)="onCheckPasswordFields()"
              formControlName="confirmPassword"
            />
            <p *ngIf="isConfirmPasswordFails" class="error">
              * Password and Confirm Password do not match, please try again.
            </p>
          </div>
          <button (click)="onCreateProfile()" [disabled]="passwordsMatch == 'false'">CREATE PROFILE</button>
        </form>
      </div>
    </section>
  </div>

  onCheckPasswordFields() {
    const passwordField = this.profileDetailsForm.value.password;
    const confirmPasswordField = this.profileDetailsForm.value.confirmPassword;
    if ((passwordField === confirmPasswordField) && (confirmPasswordField.length > 7)) {
      this.passwordsMatch = true;
    } else {
      this.passwordsMatch = false;
    }
  }

  onCreateProfile() {
    this.profileDetails.username = this.profileDetailsForm.get('username').value;
    this.profileDetails.password = this.profileDetailsForm.get('password').value;
    this.profileDetails.confirmPassword = this.profileDetailsForm.get('confirmPassword').value;
    this.create.emit(this.profileDetails);
    localStorage.setItem('userName', this.profileDetails.username)
  }
</code>```

I am not sure what I a missing here. I thought it was because passwordsMatch was not instantiated but I am declaring it passwordsMatch: boolean = false;

Please assist.

答:
When you use  passwordsMatch == 'false' is equivalent to checking false=="false" that's why it is not working. You can make make passwordsMatch==false which will work , but it is not proper way of doing things when you use boolean you dont need to compare them just use passwordsMatch alone. If you want to reverse it, use !passwordsMatch.

```<code><button (click)="onCreateProfile()" [disabled]="passwordsMatch">CREATE PROFILE</button>
</code>```

For reversing ,

```<code><button (click)="onCreateProfile()" [disabled]="!passwordsMatch">CREATE PROFILE</button>
</code>```

Title: Form button not being disabled

Body:
I have a form button that is not being disabled. I am doing a check to see if password match and meet a minimum length. Here is my code

          Please enter a username and password to create your profile

        <form [formGroup]="profileDetailsForm">

            Username
            <input id="username" type="text" formControlName="username" size="50" />

            Password
            <input id="password" type="password" formControlName="password" />

            Confirm Password
            <input
              type="password"
              id="confirmPassword"
              (ngModelChange)="onCheckPasswordFields()"
              formControlName="confirmPassword"
            />

              * Password and Confirm Password do not match, please try again.

          <button (click)="onCreateProfile()" [disabled]="passwordsMatch == 'false'">CREATE PROFILE</button>
        </form>

  onCheckPasswordFields() {
    const passwordField = this.profileDetailsForm.value.password;
    const confirmPasswordField = this.profileDetailsForm.value.confirmPassword;
    if ((passwordField === confirmPasswordField) && (confirmPasswordField.length > 7)) {
      this.passwordsMatch = true;
    } else {
      this.passwordsMatch = false;
    }
  }

  onCreateProfile() {
    this.profileDetails.username = this.profileDetailsForm.get('username').value;
    this.profileDetails.password = this.profileDetailsForm.get('password').value;
    this.profileDetails.confirmPassword = this.profileDetailsForm.get('confirmPassword').value;
    this.create.emit(this.profileDetails);
    localStorage.setItem('userName', this.profileDetails.username)
  }

I am not sure what I a missing here. I thought it was because passwordsMatch was not instantiated but I am declaring it passwordsMatch: boolean = false;

Please assist.

Body:
When you use  passwordsMatch == 'false' is equivalent to checking false=="false" that's why it is not working. You can make make passwordsMatch==false which will work , but it is not proper way of doing things when you use boolean you dont need to compare them just use passwordsMatch alone. If you want to reverse it, use !passwordsMatch.

<button (click)="onCreateProfile()" [disabled]="passwordsMatch">CREATE PROFILE</button>

For reversing ,

<button (click)="onCreateProfile()" [disabled]="!passwordsMatch">CREATE PROFILE</button>