问:
binding to compound path
I'm creating a resource in the window xaml.
That resource is a controller, like this

```<code><Window.Resources>
  <ext:Controller x:Key="Controller"/>
</Window.Resource>
</code>```

I have controls in my xaml that I want to bind to "compund members" in the Controller, so to speak.
Like if I hade a string in the controller and I want to bind to that strings length

```<code><TextBlock Text="{Binding Source={StaticResource Controller},Path=myString.Length}"/>
</code>```

or something like that.

It seems like a weird way to do it but I want to keep all of those members in the controller as opposed to making them separate resources, so they have access to certain things in the controller.

The real essence of the problem is that I have a couple of Windows and I want them to share the common resource (an instance of Controller).
So  i put a static instnace of controller in controller. i actually want to bind like

```<code><TextBlock Text="{Binding Source={StaticResource Controller},Path=StaticInstance.memberProperty/>
</code>```

Is it possible to bind to a member of a member or what approach should I be using instead of wanting the "compound path in the binding", so to speak?

Thanks, guys!
Appreciate the help

答:
StaticInstance is not a property of your resource (which is an instance) since it is static. If you want to bind to static members you can use the x:Static markup extension, note that the syntax is quite specific.

The binding probably would look like this:

```<code>{Binding Source={x:Static myns:Controller.StaticInstance}, Path=memberProperty}
</code>```

Title: binding to compound path

Body:
I'm creating a resource in the window xaml.
That resource is a controller, like this

<Window.Resources>
  <ext:Controller x:Key="Controller"/>
</Window.Resource>

I have controls in my xaml that I want to bind to "compund members" in the Controller, so to speak.
Like if I hade a string in the controller and I want to bind to that strings length

<TextBlock Text="{Binding Source={StaticResource Controller},Path=myString.Length}"/>

or something like that.

It seems like a weird way to do it but I want to keep all of those members in the controller as opposed to making them separate resources, so they have access to certain things in the controller.

The real essence of the problem is that I have a couple of Windows and I want them to share the common resource (an instance of Controller).
So  i put a static instnace of controller in controller. i actually want to bind like

<TextBlock Text="{Binding Source={StaticResource Controller},Path=StaticInstance.memberProperty/>

Is it possible to bind to a member of a member or what approach should I be using instead of wanting the "compound path in the binding", so to speak?

Thanks, guys!
Appreciate the help

Body:
StaticInstance is not a property of your resource (which is an instance) since it is static. If you want to bind to static members you can use the x:Static markup extension, note that the syntax is quite specific.

The binding probably would look like this:

{Binding Source={x:Static myns:Controller.StaticInstance}, Path=memberProperty}


来源: stackexchange

问:
I am unable to remove index.php from URl in codeigniter 3.1.11
I tried adding .htaccess in root folder from the documentation available. i searched all over the internet but nothing solved my problem.

code inside .htaccess

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

</code>```

made a changes in apache file httpd

```<code>LoadModule rewrite_module modules/mod_rewrite.so

</code>```

can anyone tell me what could be the reason?

答:
```<code>Find the below code
 $config['index_page'] = "index.php"
Remove index.php
$config['index_page'] = ""
</code>```

Write below code in .htaccess file

```<code><IfModule mod_rewrite.c>
 RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I tried adding .htaccess in root folder from the documentation available. i searched all over the internet but nothing solved my problem.

code inside .htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

made a changes in apache file httpd

LoadModule rewrite_module modules/mod_rewrite.so

can anyone tell me what could be the reason?

Body:
Find the below code
 $config['index_page'] = "index.php"
Remove index.php
$config['index_page'] = ""

Write below code in .htaccess file

<IfModule mod_rewrite.c>
 RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>


问:
Cannot have multiple operations with the same operationId: clearCache
I have imported an API from swagger-UI and able to create an api and product,But when I am trying to publish ,I am getting this error.
 Cannot have multiple operations with the same operationId: clearCache
Cannot have multiple operations with the same operationId: getConfigurationJSON
any help would be appreciated.</p>

答:
If you add the --skip-validation flag only one of the getByID
  operations will be generated
  https://github.com/swagger-api/swagger-editor/issues/1146#issuecomment-270006562

ContentLicense: CC BY-SA 3.0


问:
ValueError: Cannot query "": Must be "Group" instance
I create custom user and Group model inherit the Abstract user modeland auth Group model.

But I create the staff member and give some permission the same error trigger.
then check the user permission the same error trigger.

Put some code or error .
How to figure out this error??
 `

```<code>(Pdb) user=request.user
(Pdb) user
<SimpleLazyObject: <User: Gaurav@gmail.com>>
(Pdb) user.groups.first()
<UserGroup: Test>
(Pdb) g1=user.groups.first()
(Pdb) g1.permissions.all()
<QuerySet [<Permission: auth | group | Can add group>, <Permission: auth | group | Can change group>, <Permission: auth | group | Can delete group>, <Permission: auth | group | Can view group>, <Permission: camera | CameraGroup | Can add CameraGroup>, <Permission: camera | CameraGroup | Can change CameraGroup>, <Permission: camera | CameraGroup | Can delete CameraGroup>, <Permission: camera | CameraGroup | Can view CameraGroup>]>
(Pdb) user.has_perm('view_cameragroup')
*** ValueError: Cannot query "Gaurav@gmail.com": Must be "Group" instance.`
</code>```

答:
Your parameter in has_perm() method seems incorrect. Parameter for checking permission made from app label, permission code and model name. For example your app name is blog and your model name is Post. If you want user have view permission then you can check it by user.has_perm('blog.view_post').

You can get further guidance from django documentation : https://docs.djangoproject.com/en/3.0/topics/auth/default/#default-permissions

I hope this will help you :)

Body:
I create custom user and Group model inherit the Abstract user modeland auth Group model.

But I create the staff member and give some permission the same error trigger.
then check the user permission the same error trigger.

Put some code or error .
How to figure out this error??
 `

(Pdb) user=request.user
(Pdb) user
<SimpleLazyObject: <User: Gaurav@gmail.com>>
(Pdb) user.groups.first()
<UserGroup: Test>
(Pdb) g1=user.groups.first()
(Pdb) g1.permissions.all()
<QuerySet [<Permission: auth | group | Can add group>, <Permission: auth | group | Can change group>, <Permission: auth | group | Can delete group>, <Permission: auth | group | Can view group>, <Permission: camera | CameraGroup | Can add CameraGroup>, <Permission: camera | CameraGroup | Can change CameraGroup>, <Permission: camera | CameraGroup | Can delete CameraGroup>, <Permission: camera | CameraGroup | Can view CameraGroup>]>
(Pdb) user.has_perm('view_cameragroup')
*** ValueError: Cannot query "Gaurav@gmail.com": Must be "Group" instance.`


问:
Click is not working sometimes when Div is loaded through Ajax
I am appending The div in html after i get ajax success response.
E.g :

```<code><span class="slick-custom-arrow slick-prev" onclick="slickSlides(this);return false;"><svg width="30" height="37" viewBox="0 0 30 37" fill="none" xmlns="http://www.w3.org/2000/svg"><use xlink:href="#pro-arrow-left"></use></svg></span>
</code>```

This is the click function :

```<code>function slickSlides(el){
    console.log("clicked");
}
</code>```

I add 5-10 div with this span and this function runs randomly, by randomly i mean if click on 4th span the click does not work and some times on 1st it does not work and sometimes it works for all spans.
More confusing thing is Clicking 1st time does not work and on 2nd click it works
Does someone has this problem before ?

答:
Event to a parent which already exists.

$(document).on("click", ".slick-custom-arrow", function() {
   alert('clicked ',$(this).html())
 });
$.ajax({
  url: "http://dummy.restapiexample.com/api/v1/employees",
  cache: false,
  success: function(html){
    html.data.forEach(function(el,idx){
       if(idx<=10){
          let data='
 '+(idx+1)+' Span ';
          $("#container").append(data);
       }
    })

  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div id="container">
  <span class="slick-custom-arrow">0 Span</span>
</div></code>```

```<code>$(document).on("click", ".slick-custom-arrow", function() {
   // Your code here
 });
</code>```

Body:
I am appending The div in html after i get ajax success response.
E.g :

<svg width="30" height="37" viewBox="0 0 30 37" fill="none" xmlns="http://www.w3.org/2000/svg"><use xlink:href="#pro-arrow-left"></use></svg>

This is the click function :

function slickSlides(el){
    console.log("clicked");
}

I add 5-10 div with this span and this function runs randomly, by randomly i mean if click on 4th span the click does not work and some times on 1st it does not work and sometimes it works for all spans.
More confusing thing is Clicking 1st time does not work and on 2nd click it works
Does someone has this problem before ?

Body:
Event to a parent which already exists.

$(document).on("click", ".slick-custom-arrow", function() {
   alert('clicked ',$(this).html())
 });
$.ajax({
  url: "http://dummy.restapiexample.com/api/v1/employees",
  cache: false,
  success: function(html){
    html.data.forEach(function(el,idx){
       if(idx<=10){
          let data='<br><span class="slick-custom-arrow" > '+(idx+1)+' Span </span>';
          $("#container").append(data);
       }
    })

  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div id="container">
  <span class="slick-custom-arrow">0 Span</span>
</div>

$(document).on("click", ".slick-custom-arrow", function() {
   // Your code here
 });


问:
How to Encrypt the Video file in SD-CARD in react native
I'm developing app using react native. basically this app do some encryption in devices internal memory such as videos and pic. Is this possible with react native.</p>

答: This question is quite broad, but you can access the filesystem with React Native by using react-native-fs. When you have filesystem access, it's just a matter of choosing which encryption algorithm you want to use. One possibility is react-native-aes.


问:
Select distinct in BIRT from flat files
I have a CSV file that look something like this:

```<code>Test, Result, Case, Type
------------------------
t1  , pass  , c1  , Functional
t2  , fail  , c1  , Operational
t3  , fail  , c2  , Functional
t4  , fail  , c2  , Operational
</code>```

I'd like to define a new dataset that is a single-column list of the unique values of the 'Type' column:

```<code>TestType
--------
Functional
Operational
Regression
</code>```

If I were hitting a database, I could use some SQL like

```<code>SELECT DISTINCT type
FROM thatFile
</code>```

But it seems in BIRT (Actuate BIRT Designer v11) I don't have that luxury.  Right now I'm working with data objects...should I be using an information object instead?

答: Forgot I asked this, so I may as well jot down what I did.  Turns out that Information Objects will indeed be a fine route.  Otherwise, a data object is equally okay to use - create a new dataset and use 'distinct' in the 'query' tab of the wizard.  </p>

ContentLicense: CC BY-SA 2.5

Title: Select distinct in BIRT from flat files

Body:
I have a CSV file that look something like this:

Test, Result, Case, Type
------------------------
t1  , pass  , c1  , Functional
t2  , fail  , c1  , Operational
t3  , fail  , c2  , Functional
t4  , fail  , c2  , Operational

I'd like to define a new dataset that is a single-column list of the unique values of the 'Type' column:

TestType
--------
Functional
Operational
Regression

If I were hitting a database, I could use some SQL like

SELECT DISTINCT type
FROM thatFile

But it seems in BIRT (Actuate BIRT Designer v11) I don't have that luxury.  Right now I'm working with data objects...should I be using an information object instead?


问:
how to get the place details from place ID in android(kotlin)
Hi i want to get place details with placeID and add marker in android maps activity using kotlin. i have done it with latlng but am not getting with placeID . can any pleease help.
my code with latlng .

```<code>override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap

        val mdis= LatLng(1.301440, 103.847980)

        mMap.addMarker(MarkerOptions().position(mdis).title("MDIS").icon(BitmapDescriptorFactory.fromResource(R.drawable.icon)))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(mdis))
        mMap.animateCamera(CameraUpdateFactory.zoomIn())
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15F),2000,null)
        mMap.uiSettings.isZoomControlsEnabled=true
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mMap.isMyLocationEnabled = true
        }
        else {//condition for Marshmello and above
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), MY_PERMISSION_FINE_LOCATION)
            }
        }
        mMap.setOnMarkerClickListener(this)
    }
</code>```

Tried this and am getting error at  placesClient.fetchPlace(request).addOnSuccessListener(response) ->{
Error says Type mismatch Required: OnSuccessListener
                         found : FetchplaceResponse

This is my updated code :

```<code> override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap

        var mdisplaceId = "ChIJRwCirzca2jERhd68E52R_2Q"
        //val placesClient = Places.createClient(this)

        var placeFields : List<Place.Field>
        placeFields = Arrays.asList(Place.Field.ID , Place.Field.NAME)

       var  request :  FetchPlaceRequest
        request = FetchPlaceRequest.newInstance(mdisplaceId, placeFields)

        lateinit var response : FetchPlaceResponse
        lateinit var placesClient : PlacesClient
            placesClient.fetchPlace(request).addOnSuccessListener(response) ->{  //error at this line near response
            var place : Place
             place = response.getPlace()
        })
    }
</code>```

答:
Use Geocoding api,

https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY

which will return the following json response,

```<code>{
"results" : [
  {
     "address_components" : [
        {
           "long_name" : "277",
           "short_name" : "277",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Bedford Avenue",
           "short_name" : "Bedford Ave",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Williamsburg",
           "short_name" : "Williamsburg",
           "types" : [ "neighborhood", "political" ]
        },
        {
           "long_name" : "Brooklyn",
           "short_name" : "Brooklyn",
           "types" : [ "political", "sublocality", "sublocality_level_1" ]
        },
        {
           "long_name" : "Kings County",
           "short_name" : "Kings County",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "New York",
           "short_name" : "NY",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "11211",
           "short_name" : "11211",
           "types" : [ "postal_code" ]
        }
     ],
     "formatted_address" : "277 Bedford Ave, Brooklyn, NY 11211, USA",
     "geometry" : {
        "location" : {
           "lat" : 40.7142205,
           "lng" : -73.9612903
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 40.71556948029149,
              "lng" : -73.95994131970849
           },
           "southwest" : {
              "lat" : 40.7128715197085,
              "lng" : -73.9626392802915
           }
        }
     },
     "place_id" : "ChIJd8BlQ2BZwokRAFUEcm_qrcA",
     "types" : [ "street_address" ]
  }
],
"status" : "OK"
}
</code>```

Get the lat long from geometry object and add marker on the google maps.

Body:
Hi i want to get place details with placeID and add marker in android maps activity using kotlin. i have done it with latlng but am not getting with placeID . can any pleease help.
my code with latlng .

override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap

        val mdis= LatLng(1.301440, 103.847980)

        mMap.addMarker(MarkerOptions().position(mdis).title("MDIS").icon(BitmapDescriptorFactory.fromResource(R.drawable.icon)))
        mMap.moveCamera(CameraUpdateFactory.newLatLng(mdis))
        mMap.animateCamera(CameraUpdateFactory.zoomIn())
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15F),2000,null)
        mMap.uiSettings.isZoomControlsEnabled=true
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mMap.isMyLocationEnabled = true
        }
        else {//condition for Marshmello and above
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), MY_PERMISSION_FINE_LOCATION)
            }
        }
        mMap.setOnMarkerClickListener(this)
    }

Tried this and am getting error at  placesClient.fetchPlace(request).addOnSuccessListener(response) ->{
Error says Type mismatch Required: OnSuccessListener
                         found : FetchplaceResponse

This is my updated code :

 override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap

        var mdisplaceId = "ChIJRwCirzca2jERhd68E52R_2Q"
        //val placesClient = Places.createClient(this)

        var placeFields : List<Place.Field>
        placeFields = Arrays.asList(Place.Field.ID , Place.Field.NAME)

       var  request :  FetchPlaceRequest
        request = FetchPlaceRequest.newInstance(mdisplaceId, placeFields)

        lateinit var response : FetchPlaceResponse
        lateinit var placesClient : PlacesClient
            placesClient.fetchPlace(request).addOnSuccessListener(response) ->{  //error at this line near response
            var place : Place
             place = response.getPlace()
        })
    }

Body:
Use Geocoding api,

https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY

which will return the following json response,

{
"results" : [
  {
     "address_components" : [
        {
           "long_name" : "277",
           "short_name" : "277",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Bedford Avenue",
           "short_name" : "Bedford Ave",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Williamsburg",
           "short_name" : "Williamsburg",
           "types" : [ "neighborhood", "political" ]
        },
        {
           "long_name" : "Brooklyn",
           "short_name" : "Brooklyn",
           "types" : [ "political", "sublocality", "sublocality_level_1" ]
        },
        {
           "long_name" : "Kings County",
           "short_name" : "Kings County",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "New York",
           "short_name" : "NY",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "11211",
           "short_name" : "11211",
           "types" : [ "postal_code" ]
        }
     ],
     "formatted_address" : "277 Bedford Ave, Brooklyn, NY 11211, USA",
     "geometry" : {
        "location" : {
           "lat" : 40.7142205,
           "lng" : -73.9612903
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 40.71556948029149,
              "lng" : -73.95994131970849
           },
           "southwest" : {
              "lat" : 40.7128715197085,
              "lng" : -73.9626392802915
           }
        }
     },
     "place_id" : "ChIJd8BlQ2BZwokRAFUEcm_qrcA",
     "types" : [ "street_address" ]
  }
],
"status" : "OK"
}

Get the lat long from geometry object and add marker on the google maps.


问:
MariaDB configuration
I run this command in my Centos 7 server:

```<code>frappe@vps [~/frappe-bench]# bench new-site erp.local
</code>```

but I got this error:

```<code>frappe@vps [~/frappe-bench]# bench new-site erp.local
MySQL root password:
================================================================================
Creation of your site - erp.local failed because MariaDB is not properly
configured to use the Barracuda storage engine.
Please add the settings below to MariaDB's my.cnf, restart MariaDB then
run `bench new-site erp.local` again.

[mysqld]
character-set-client-handshake = FALSE
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

[mysql]
default-character-set = utf8mb4

================================================================================
frappe@vps [~/frappe-bench]#
</code>```

When I see /etc/my.cnf file, I encounter this:

```<code>!includedir /etc/my.cnf.d
</code>```

So, I look at that folder and then opened "settings.cnf" file and I have found exact the same configuration.

What else do I have to see?

Regards
Jaime

答:
```<code>add the following information to /etc/mysql/mariadb.cnf

[mysqld]
character-set-client-handshake = FALSE
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

[mysql]
default-character-set = utf8mb4

then 'flush privileges;' MariaDB database
</code>```

Title: MariaDB configuration

Body:
I run this command in my Centos 7 server:

frappe@vps [~/frappe-bench]# bench new-site erp.local

but I got this error:

frappe@vps [~/frappe-bench]# bench new-site erp.local
MySQL root password:
================================================================================
Creation of your site - erp.local failed because MariaDB is not properly
configured to use the Barracuda storage engine.
Please add the settings below to MariaDB's my.cnf, restart MariaDB then
run `bench new-site erp.local` again.

[mysqld]
character-set-client-handshake = FALSE
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

[mysql]
default-character-set = utf8mb4

================================================================================
frappe@vps [~/frappe-bench]#

When I see /etc/my.cnf file, I encounter this:

!includedir /etc/my.cnf.d

So, I look at that folder and then opened "settings.cnf" file and I have found exact the same configuration.

What else do I have to see?

Regards
Jaime


问:
model:generate gives "Missing required arguments: name, attributes"
I'm on the Windows console and here is a script of my package.json:

```<code>scripts: {
    ...
    "sequelize": "node_modules\\.bin\\sequelize.cmd"
}
</code>```

When I run this command: npm run-script sequelize model:generate --name Person --attributes name:string,age:integer, I get this error:

Missing required arguments: name, attributes

But when I run this command: node_modules\.bin\sequelize.cmd model:generate --name Person --attributes name:string,age:integer it works well.

Why do I get this problem?

Thank you for your help.

答:
just use this command

sequelize migration:create --name migrationName

this command working 100%

Body:
I'm on the Windows console and here is a script of my package.json:

scripts: {
    ...
    "sequelize": "node_modules\\.bin\\sequelize.cmd"
}

When I run this command: npm run-script sequelize model:generate --name Person --attributes name:string,age:integer, I get this error:

Missing required arguments: name, attributes

But when I run this command: node_modules\.bin\sequelize.cmd model:generate --name Person --attributes name:string,age:integer it works well.

Why do I get this problem?

Thank you for your help.


问:
Want nondetects to show on ggplot figure
I would like my nondetects to show on my graph (so it doesn't just look like no data was collected at a particular location on a particular date).  I was thinking of making them triangles?  I am not sure that I have my csv set up correctly, or that I am using the right commands. I appreciate any insight.

Note: I put 0 in the "Results" column for the nondetects and in the "Detects" column I assigned a 1 to all detects and a 0 to all nondetects. I think this may be part of my issue-but I'm not sure how to resolve it...
Here is my code:

Example Data

```<code>Date       Reservoir           Result    Detects
9/24/2019  Epilimnion          0.2       1
9/24/2019  Metalimnion         0.6       1
9/24/2019  Hypolimnion         1.8       1
10/8/2019  Epilimnion          0         0
10/8/2019  Metalimnion         1.9       1
10/8/2019  Hypolimnion         3.7       1
10/22/2019  Epilimnion         0         0
10/22/2019  Metalimnion        0         0
10/22/2019  Hypolimnion        2.7       1

    TN<-read.csv("TN.csv", header=TRUE)
    library(lubridate)
    library(ggplot2)
    library(scales)
ggplot(TN, aes(x = mdy(Date), y = Result, color = Reservoir, pch=ifelse(Detects, 19, 17), cex = 1.5))+
  geom_point(size = 4)+
  ylab("Total Nitrogen (mg/L)") +
  scale_x_date(name = "", breaks = date_breaks("1 month"), labels = date_format("%b %Y"),
               limits = c(mdy("08/30/2019"),mdy("1/10/2020"))) +
  scale_color_discrete(labels = c("Hypolimnion", "Metalimnion (Bottom)", "Metalimnion (Top)", "Epilimnion"),
                       breaks = c("Hypolimnion", "Metalimnion (Bottom)", "Metalimnion (Top)", "Epilimnion")) +
  theme(legend.position="bottom", legend.text=element_text(size=12, face="bold"),
        axis.text.x = element_text(angle = 45, vjust = 1.0, hjust = 1.0, size=12,), axis.text.y = element_text(size=12), axis.title.y = element_text(vjust=3, size=12, face="bold"),
        legend.title=element_blank(),
        plot.title = element_text(hjust = 0.5))
</code>```

答:
The error is informative:

```<code>Error: A continuous variable can not be mapped to shape
</code>```

Which refers to the pch argument:

```<code>pch=ifelse(Detects, 19, 17)
</code>```

And as MrFlick mentioned, this is what ggplot calls a shape. The numbers 19 and 17 may look discrete to a human eye, but they are actually continuous (=numeric) to a computer (in this case R). Discrete in ggplot sense meaning categorical (=factor). So, mutate this variable into a factor, use it directly as the shape argument (btw pch works too) and Bob's your uncle:

```<code>TN %>%
  mutate(Detects=factor(Detects)) %>%
  ggplot(aes(x = mdy(Date), y = Result, color = Reservoir, pch=Detects), size = 1.5) +
  geom_point(size = 4)+
  ylab("Total Nitrogen (mg/L)") +
  scale_x_date(name = "", breaks = date_breaks("1 month"), labels = date_format("%b %Y"),
               limits = c(mdy("08/30/2019"),mdy("1/10/2020"))) +
  #scale_color_discrete(labels = c("Hypolimnion", "Metalimnion (Bottom)", "Metalimnion (Top)", "Epilimnion"),
  #                     breaks = c("Hypolimnion", "Metalimnion (Bottom)", "Metalimnion (Top)", "Epilimnion")) +
  theme(legend.position="bottom", legend.text=element_text(size=12, face="bold"),
        axis.text.x = element_text(angle = 45, vjust = 1.0, hjust = 1.0, size=12,),
        axis.text.y = element_text(size=12), axis.title.y = element_text(vjust=3, size=12, face="bold"),
  #      legend.title=element_blank(),
        plot.title = element_text(hjust = 0.5))
</code>```

Note that I removed your scale_color_discrete override and I recommend not hiding the legend titles.

Body:
I would like my nondetects to show on my graph (so it doesn't just look like no data was collected at a particular location on a particular date).  I was thinking of making them triangles?  I am not sure that I have my csv set up correctly, or that I am using the right commands. I appreciate any insight.

Note: I put 0 in the "Results" column for the nondetects and in the "Detects" column I assigned a 1 to all detects and a 0 to all nondetects. I think this may be part of my issue-but I'm not sure how to resolve it...
Here is my code:

Example Data

Date       Reservoir           Result    Detects
9/24/2019  Epilimnion          0.2       1
9/24/2019  Metalimnion         0.6       1
9/24/2019  Hypolimnion         1.8       1
10/8/2019  Epilimnion          0         0
10/8/2019  Metalimnion         1.9       1
10/8/2019  Hypolimnion         3.7       1
10/22/2019  Epilimnion         0         0
10/22/2019  Metalimnion        0         0
10/22/2019  Hypolimnion        2.7       1

    TN<-read.csv("TN.csv", header=TRUE)
    library(lubridate)
    library(ggplot2)
    library(scales)
ggplot(TN, aes(x = mdy(Date), y = Result, color = Reservoir, pch=ifelse(Detects, 19, 17), cex = 1.5))+
  geom_point(size = 4)+
  ylab("Total Nitrogen (mg/L)") +
  scale_x_date(name = "", breaks = date_breaks("1 month"), labels = date_format("%b %Y"),
               limits = c(mdy("08/30/2019"),mdy("1/10/2020"))) +
  scale_color_discrete(labels = c("Hypolimnion", "Metalimnion (Bottom)", "Metalimnion (Top)", "Epilimnion"),
                       breaks = c("Hypolimnion", "Metalimnion (Bottom)", "Metalimnion (Top)", "Epilimnion")) +
  theme(legend.position="bottom", legend.text=element_text(size=12, face="bold"),
        axis.text.x = element_text(angle = 45, vjust = 1.0, hjust = 1.0, size=12,), axis.text.y = element_text(size=12), axis.title.y = element_text(vjust=3, size=12, face="bold"),
        legend.title=element_blank(),
        plot.title = element_text(hjust = 0.5))

Body:
The error is informative:

Error: A continuous variable can not be mapped to shape

Which refers to the pch argument:

pch=ifelse(Detects, 19, 17)

And as MrFlick mentioned, this is what ggplot calls a shape. The numbers 19 and 17 may look discrete to a human eye, but they are actually continuous (=numeric) to a computer (in this case R). Discrete in ggplot sense meaning categorical (=factor). So, mutate this variable into a factor, use it directly as the shape argument (btw pch works too) and Bob's your uncle:

TN %>%
  mutate(Detects=factor(Detects)) %>%
  ggplot(aes(x = mdy(Date), y = Result, color = Reservoir, pch=Detects), size = 1.5) +
  geom_point(size = 4)+
  ylab("Total Nitrogen (mg/L)") +
  scale_x_date(name = "", breaks = date_breaks("1 month"), labels = date_format("%b %Y"),
               limits = c(mdy("08/30/2019"),mdy("1/10/2020"))) +
  #scale_color_discrete(labels = c("Hypolimnion", "Metalimnion (Bottom)", "Metalimnion (Top)", "Epilimnion"),
  #                     breaks = c("Hypolimnion", "Metalimnion (Bottom)", "Metalimnion (Top)", "Epilimnion")) +
  theme(legend.position="bottom", legend.text=element_text(size=12, face="bold"),
        axis.text.x = element_text(angle = 45, vjust = 1.0, hjust = 1.0, size=12,),
        axis.text.y = element_text(size=12), axis.title.y = element_text(vjust=3, size=12, face="bold"),
  #      legend.title=element_blank(),
        plot.title = element_text(hjust = 0.5))

Note that I removed your scale_color_discrete override and I recommend not hiding the legend titles.


问:
SQL behaviour when executing queries with conjunctions
If I have a SQL query that is performing an existence check against three tables:

```<code>IF EXISTS(SELECT [KEY] FROM [Table1] WHERE [KEY]='Key1')
    AND EXISTS(SELECT [KEY] FROM [Table2] WHERE [KEY]='Key2')
    AND EXISTS(SELECT [KEY] FROM [Table3] WHERE [KEY]='Key3')
</code>```

Does SQL Server support 'early exit' for conditional statements, such that if the initial exists check against [Table1] returns false, the remaining two exists checks are not executed?

Assuming Microsoft SQL Server as the backend, what locking behaviour would I expect to see on the three referenced tables, again assuming that the initial exists check against Table1 will return false?

Some basic testing using functions instead of actual queries would suggest that 'early exit' is supported, but lock analysis during query execution also suggests that a lock is acquired on all three tables which contradicts the 'early exit' findings.

Does SQL Server acquire a lock on all tables in a query, just in case it needs them later on?

答: SQL Server does do short-circuit evaluation, but you cannot control the order in which it chooses to evaluate the clauses, unless you do so via a CASE statement.

Body:
If I have a SQL query that is performing an existence check against three tables:

IF EXISTS(SELECT [KEY] FROM [Table1] WHERE [KEY]='Key1')
    AND EXISTS(SELECT [KEY] FROM [Table2] WHERE [KEY]='Key2')
    AND EXISTS(SELECT [KEY] FROM [Table3] WHERE [KEY]='Key3')

Does SQL Server support 'early exit' for conditional statements, such that if the initial exists check against [Table1] returns false, the remaining two exists checks are not executed?

Assuming Microsoft SQL Server as the backend, what locking behaviour would I expect to see on the three referenced tables, again assuming that the initial exists check against Table1 will return false?

Some basic testing using functions instead of actual queries would suggest that 'early exit' is supported, but lock analysis during query execution also suggests that a lock is acquired on all three tables which contradicts the 'early exit' findings.

Does SQL Server acquire a lock on all tables in a query, just in case it needs them later on?


问:
Setting the Style in qml Qt
I want to set the Style for my elements in qml. For that, I want to use a style like Material Style. Using the example which can be found under:

https://doc.qt.io/qt-5/qtquickcontrols2-material.html

```<code>import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Controls.Material 2.12

ApplicationWindow {
   visible: true

   Material.theme: Material.Dark
   Material.accent: Material.Purple

   Column {
       anchors.centerIn: parent

       RadioButton { text: qsTr("Small") }
       RadioButton { text: qsTr("Medium");  checked: true }
       RadioButton { text: qsTr("Large") }
     }
}
</code>```

Gives me the result seen in the image I attached.
No matter which Style I use, nothing changes.

I am currently using the newest free Qt version under a Windows 10 Os.

Can anyone help me?
And is it possible to globally overwrite a Style and make an own Style, simply in QML.

答:
You have to set the style from C++ as well. See this Qt documentation.

So in you main add QQuickStyle::setStyle("Material");

Title: Setting the Style in qml Qt

Body:
I want to set the Style for my elements in qml. For that, I want to use a style like Material Style. Using the example which can be found under:

https://doc.qt.io/qt-5/qtquickcontrols2-material.html

import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Controls.Material 2.12

ApplicationWindow {
   visible: true

   Material.theme: Material.Dark
   Material.accent: Material.Purple

   Column {
       anchors.centerIn: parent

       RadioButton { text: qsTr("Small") }
       RadioButton { text: qsTr("Medium");  checked: true }
       RadioButton { text: qsTr("Large") }
     }
}

Gives me the result seen in the image I attached.
No matter which Style I use, nothing changes.

I am currently using the newest free Qt version under a Windows 10 Os.

Can anyone help me?
And is it possible to globally overwrite a Style and make an own Style, simply in QML.


问:
Remove only files inside directory and subdirectory
Remove only files inside directory and subdirectory

Not the directory
Not the subdirectory

only want to delete the files inside directory and subdirectory

答:
To remove all the files under dir/subdir/file (both dir/subdir/file and dir/subdir/subsubdir/file will be removed):

find dir/subdir -type f -delete
```

<ul>
<li>To remove files at most one level below <code>dir/subdir</code> (this removes <code>dir/subdir/file</code> but not <code>dir/subdir/subsubdir/file</code>):</li>
</ul>

<pre class="lang-sh prettyprint-override"><code>find dir/subdir -maxdepth 1 -type f -delete
</code>```

To remove dir/file and dir/subdir/file but not dir/subdir/subsubdir/file:

find dir dir/subdir -maxdepth 1 -type f -delete
```

Body:
To remove all the files under dir/subdir/file (both dir/subdir/file and dir/subdir/subsubdir/file will be removed):

find dir/subdir -type f -delete

To remove files at most one level below dir/subdir (this removes dir/subdir/file but not dir/subdir/subsubdir/file):

find dir/subdir -maxdepth 1 -type f -delete

To remove dir/file and dir/subdir/file but not dir/subdir/subsubdir/file:

find dir dir/subdir -maxdepth 1 -type f -delete


问:
setting cq:tags and ajax call together in page properties: Loosing textfield data on page reload
I have a scenario where, in AEM page properties. On click of a button in Page properties:
(1). I need get cq:tags and automatically set into a page properties - for this I need a page reload,
(2). also, in the same call I am getting the response from ajax call to be shown into a textfield.

to get point (1) from above, I need to reload the page.
but as soon as I try to do so using window.location.reload(); , I loose that data(from ajax call at point (2)) which is setting in the text field(DOM element).

And when if I don't call window.location.reload();, my cq:tags are not set.

$.ajax({
            type : 'GET',
            url : '/abc/def/ijk.json',
            data : {
                pagePath : pagePathURL
            },
            success : function(data) {

```<code>            if (data != "" || data != undefined) {
                var jsonObj = JSON.parse(data);
                if (jsonObj != undefined && jsonObj.Success == true) {
                         // tried here

                        if (jsonObj.PageTitle != undefined) {
                        var pageTitle = jsonObj.PageTitle;

                        $('.some-text').val(pageTitle);
                    }
</code>```

What have I tried so far:

```<code>// after  jsonObj.Success == true
window.location.reload();
setTimeout(console.log(data),4000000);
</code>```

How can I do both together ?

答:
You have conflicting requirements. You can't keep form data when also refreshing the page. Websites don't work that way. You have to post the data - the cq:tags as well the text for the text field - to the corresponding nodes. Which are basically just AJAX requests in the background. You could also show notifications indicating what data was automatically saved.

Then, you can refresh the page (which might be optional at this point, as the data is persisted).

If that does not match your requirements, save the form data in the local storage and read it, if necessary.

Body:
I have a scenario where, in AEM page properties. On click of a button in Page properties:
(1). I need get cq:tags and automatically set into a page properties - for this I need a page reload,
(2). also, in the same call I am getting the response from ajax call to be shown into a textfield.

to get point (1) from above, I need to reload the page.
but as soon as I try to do so using window.location.reload(); , I loose that data(from ajax call at point (2)) which is setting in the text field(DOM element).

And when if I don't call window.location.reload();, my cq:tags are not set.

$.ajax({
            type : 'GET',
            url : '/abc/def/ijk.json',
            data : {
                pagePath : pagePathURL
            },
            success : function(data) {

            if (data != "" || data != undefined) {
                var jsonObj = JSON.parse(data);
                if (jsonObj != undefined && jsonObj.Success == true) {
                         // tried here

                        if (jsonObj.PageTitle != undefined) {
                        var pageTitle = jsonObj.PageTitle;

                        $('.some-text').val(pageTitle);
                    }

What have I tried so far:

// after  jsonObj.Success == true
window.location.reload();
setTimeout(console.log(data),4000000);

How can I do both together ?


问:
How to use ISNULL on multiple fields in a Infromatica filter condition?
I have scenario where i have to check for the null values in multiple fields based on that i informatica should whether to load the record into target or not.

Example: I have col1, col2,col3,col4 fields. If any of these fields isnull then ignore that record else load the record.

Please suggest me how to approach this scenario.

TIA!

答:
You can concatenate all the fields, if the result is null it means that at least one column is null:

NOT ISNULL(col1||col2||col3||col4)


问:
Perl Out Of Memory when parsing json with regexp inside
I am parsing a very simple json file and perl is running out of memory. I am using the JSON lib from cpan. I am reading the json from a file named "data.json". I am also using the File::Slurper module.

```<code>use JSON;
use File::Slurper;

my $file = read_text("data.json");
my @data = decode_json($file);
print @data;
</code>```

In my data.json file I have an array of objects with regexp inside each obj.

```<code>[
{
  "val": "test",
  "reg": "m/^(match)/"
}
...3 more entries
]
</code>```

WHen i run this it says

Out of memory!

how can i bypass this?

答:
It is not clear what causes the error in your code. See the following sample code which does same job in a little different way.

```<code>use strict;
use warnings;
use feature 'say';

use JSON;
use Data::Dumper;

my $file = do { local $/; <DATA> };

my @data = decode_json($file);

say Dumper(\@data);

__DATA__
[
    {
      "val": "test1",
      "reg": "m/^(match)/"
    },
    {
      "val": "test2",
      "reg": "m/^(match)/"
    },
    {
      "val": "test3",
      "reg": "m/^(match)/"
    },
    {
      "val": "test4",
      "reg": "m/^(match)/"
    }
]
</code>```

Output

```<code>$VAR1 = [
          [
            {
              'val' => 'test1',
              'reg' => 'm/^(match)/'
            },
            {
              'val' => 'test2',
              'reg' => 'm/^(match)/'
            },
            {
              'val' => 'test3',
              'reg' => 'm/^(match)/'
            },
            {
              'reg' => 'm/^(match)/',
              'val' => 'test4'
            }
          ]
        ];
</code>```

Body:
I am parsing a very simple json file and perl is running out of memory. I am using the JSON lib from cpan. I am reading the json from a file named "data.json". I am also using the File::Slurper module.

use JSON;
use File::Slurper;

my $file = read_text("data.json");
my @data = decode_json($file);
print @data;

In my data.json file I have an array of objects with regexp inside each obj.

[
{
  "val": "test",
  "reg": "m/^(match)/"
}
...3 more entries
]

WHen i run this it says

Out of memory!

how can i bypass this?

Body:
It is not clear what causes the error in your code. See the following sample code which does same job in a little different way.

use strict;
use warnings;
use feature 'say';

use JSON;
use Data::Dumper;

my $file = do { local $/; <DATA> };

my @data = decode_json($file);

say Dumper(\@data);

__DATA__
[
    {
      "val": "test1",
      "reg": "m/^(match)/"
    },
    {
      "val": "test2",
      "reg": "m/^(match)/"
    },
    {
      "val": "test3",
      "reg": "m/^(match)/"
    },
    {
      "val": "test4",
      "reg": "m/^(match)/"
    }
]

Output

$VAR1 = [
          [
            {
              'val' => 'test1',
              'reg' => 'm/^(match)/'
            },
            {
              'val' => 'test2',
              'reg' => 'm/^(match)/'
            },
            {
              'val' => 'test3',
              'reg' => 'm/^(match)/'
            },
            {
              'reg' => 'm/^(match)/',
              'val' => 'test4'
            }
          ]
        ];


问:
Simulate API 29 Vibrations in 26 and below
I want to simulate API 29 vibration effects:

```<code>EFFECT_CLICK
EFFECT_DOUBLE_CLICK
EFFECT_HEAVY_CLICK
EFFECT_TICK
</code>```

in version 26 and lower as well. Does anybody know how these translate?

答:
It is more or less h/w compatibility.

2 things here,

VibrationEffect is already added in Api Level 26
https://developer.android.com/reference/android/os/VibrationEffect

Vibrator is deprecated from Api Level 26 & VibrationEffect comes into play as mentioned above
https://developer.android.com/reference/android/os/Vibrator.html#vibrate(long%5B%5D,%20int)

Body:
I want to simulate API 29 vibration effects:

EFFECT_CLICK
EFFECT_DOUBLE_CLICK
EFFECT_HEAVY_CLICK
EFFECT_TICK

in version 26 and lower as well. Does anybody know how these translate?


问:
Trying to create basic application using HERE Android Lite SDK
I am trying to run a basic example of an application with new Android Lite SDK from HERE and getting such error:

```<code>E/AndroidTangramPlatformBridge: parse
    org.xmlpull.v1.XmlPullParserException: END_TAG expected (position:START_TAG (empty) <axis tag='wdth' stylevalue='100.0'>@279:51 in java.io.InputStreamReader@739274e)
        at org.kxml2.io.KXmlParser.nextText(KXmlParser.java:2088)
        at com.here.sdk.mapviewlite.FontFileParser.processDocument(Unknown Source:105)
        at com.here.sdk.mapviewlite.FontFileParser.parse(Unknown Source:21)
        at com.here.sdk.mapviewlite.FontFileParser.parse(Unknown Source:18)
        at com.here.sdk.mapviewlite.AndroidTangramPlatformBridge.<init>(Unknown Source:33)
        at com.here.sdk.mapviewlite.MapViewLite.onCreate(Unknown Source:6)
        at com.here.hellomap.MainActivity.onCreate(MainActivity.java:46)
        at android.app.Activity.performCreate(Activity.java:7458)
        at android.app.Activity.performCreate(Activity.java:7448)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1286)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3409)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3614)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
        at android.os.Handler.dispatchMessage(Handler.java:112)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7625)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
D/HwCustConnectivityManagerImpl: isBlockNetworkRequestByNonAis, INVALID_SUBSCRIPTION_ID
D/ActivityThread: add activity client record, r= ActivityRecord{d1ae1ac token=android.os.BinderProxy@853d260 {com.here.hellomap/com.here.hellomap.MainActivity}} token= android.os.BinderProxy@853d260
E/: [ZeroHung]zrhung_get_config: Get config failed for wp[0x0008]
D/ZrHung.AppEyeUiProbe: notify runnable to start.
I/HwSecImmHelper: mSecurityInputMethodService is null
D/HwAppInnerBoostImpl: set config for com.here.hellomap BOOST_FLAG=false REPORT_DURATION_CLICK=1000 REPORT_TIMES_CLICK=3 REPORT_DURATION_SLIDE=5000 REPORT_TIMES_SLIDE=16
D/OpenGLRenderer:   HWUI Binary is  enabled
W/HiTouch_HiTouchSensor: depended package hiTouch does n't exist!
I/HiTouch_HiTouchSensor: HiTouch restricted: system app HiTouch don't exist.
D/HiTouch_PressGestureDetector: onAttached, package=com.here.hellomap, windowType=1, mHiTouchRestricted=true
E/analytics: [ERROR] analytics - Failed to get the authentication token: Authentication failed, error code: 1
E/analytics: [ERROR] analytics - Failed to get the authentication token: Authentication failed, error code: 1
    [ERROR] analytics - Invalid access key
I/HwPhoneWindow: updateLayoutParamsColor false mSpecialSet=false, mForcedNavigationBarColor=false, navigationBarColor=ff000000, mNavBarShow=true, mIsFloating=false
I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0

</code>```

I see only a blank map on my HUAWEI P Smart (on Virtual device code runs normally).
Does anyone have an idea of how to solve it?

答:
Please check authentication token for android Lite version. Also check for the permission java class that has to be correctly written. The accompanying example apps can be found on GitHub : https://github.com/heremaps/here-sdk-examples

To try out these examples, add your HERE credentials (access_key_id and access_key_secret) to the AndroidManifest.xml file, and add the HERE SDK to the libs folder.

Body:
I am trying to run a basic example of an application with new Android Lite SDK from HERE and getting such error:

E/AndroidTangramPlatformBridge: parse
    org.xmlpull.v1.XmlPullParserException: END_TAG expected (position:START_TAG (empty) <axis tag='wdth' stylevalue='100.0'>@279:51 in java.io.InputStreamReader@739274e)
        at org.kxml2.io.KXmlParser.nextText(KXmlParser.java:2088)
        at com.here.sdk.mapviewlite.FontFileParser.processDocument(Unknown Source:105)
        at com.here.sdk.mapviewlite.FontFileParser.parse(Unknown Source:21)
        at com.here.sdk.mapviewlite.FontFileParser.parse(Unknown Source:18)
        at com.here.sdk.mapviewlite.AndroidTangramPlatformBridge.<init>(Unknown Source:33)
        at com.here.sdk.mapviewlite.MapViewLite.onCreate(Unknown Source:6)
        at com.here.hellomap.MainActivity.onCreate(MainActivity.java:46)
        at android.app.Activity.performCreate(Activity.java:7458)
        at android.app.Activity.performCreate(Activity.java:7448)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1286)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3409)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3614)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
        at android.os.Handler.dispatchMessage(Handler.java:112)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7625)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
D/HwCustConnectivityManagerImpl: isBlockNetworkRequestByNonAis, INVALID_SUBSCRIPTION_ID
D/ActivityThread: add activity client record, r= ActivityRecord{d1ae1ac token=android.os.BinderProxy@853d260 {com.here.hellomap/com.here.hellomap.MainActivity}} token= android.os.BinderProxy@853d260
E/: [ZeroHung]zrhung_get_config: Get config failed for wp[0x0008]
D/ZrHung.AppEyeUiProbe: notify runnable to start.
I/HwSecImmHelper: mSecurityInputMethodService is null
D/HwAppInnerBoostImpl: set config for com.here.hellomap BOOST_FLAG=false REPORT_DURATION_CLICK=1000 REPORT_TIMES_CLICK=3 REPORT_DURATION_SLIDE=5000 REPORT_TIMES_SLIDE=16
D/OpenGLRenderer:   HWUI Binary is  enabled
W/HiTouch_HiTouchSensor: depended package hiTouch does n't exist!
I/HiTouch_HiTouchSensor: HiTouch restricted: system app HiTouch don't exist.
D/HiTouch_PressGestureDetector: onAttached, package=com.here.hellomap, windowType=1, mHiTouchRestricted=true
E/analytics: [ERROR] analytics - Failed to get the authentication token: Authentication failed, error code: 1
E/analytics: [ERROR] analytics - Failed to get the authentication token: Authentication failed, error code: 1
    [ERROR] analytics - Invalid access key
I/HwPhoneWindow: updateLayoutParamsColor false mSpecialSet=false, mForcedNavigationBarColor=false, navigationBarColor=ff000000, mNavBarShow=true, mIsFloating=false
I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0

I see only a blank map on my HUAWEI P Smart (on Virtual device code runs normally).
Does anyone have an idea of how to solve it?


问:
git branch continually getting recreated on pull
I have a git branch that continually gets 'recreated' with an alternating letter case every time I perform a 'git pull'. Assuming the branch name is 'a' (or 'A' for all I know), one 'git pull' will produce the line:

```<code>* [new branch]      a       -> origin/a
</code>```

And then the next 'git pull' will produce:

```<code>* [new branch]      A       -> origin/A
</code>```

This never stops. I don't know how the branch got created (or what it is for) as someone else created it.

How do I tame this branch and make it stop doing this?

答:
As mentioned in the comments, both refs/heads/A and refs/heads/a exist on the remote. That does mean that two distinct branches exist there. (Git itself is case sensitive, as are most non-Windows filesystems.)

If, however, you're using Windows, that would probably explain this problem. Refs are created as individual files, one per ref. Git sees both on the remote, but then when it attempts to update them locally, only one exists, so the other is always created. The internal order of the two operations must then be such that the newly created one overwrites the other, leading to the alternation.

If the refs are pointing to the same commit, then the solution is to delete one of them on the remote:

```<code>git push origin :refs/heads/A
</code>```

Body:
I have a git branch that continually gets 'recreated' with an alternating letter case every time I perform a 'git pull'. Assuming the branch name is 'a' (or 'A' for all I know), one 'git pull' will produce the line:

* [new branch]      a       -> origin/a

And then the next 'git pull' will produce:

* [new branch]      A       -> origin/A

This never stops. I don't know how the branch got created (or what it is for) as someone else created it.

How do I tame this branch and make it stop doing this?

Body:
As mentioned in the comments, both refs/heads/A and refs/heads/a exist on the remote. That does mean that two distinct branches exist there. (Git itself is case sensitive, as are most non-Windows filesystems.)

If, however, you're using Windows, that would probably explain this problem. Refs are created as individual files, one per ref. Git sees both on the remote, but then when it attempts to update them locally, only one exists, so the other is always created. The internal order of the two operations must then be such that the newly created one overwrites the other, leading to the alternation.

If the refs are pointing to the same commit, then the solution is to delete one of them on the remote:

git push origin :refs/heads/A


问:
Error "void is an invalid type for the variable passwordMethod1"

Discription: This program check password between 7 to 16

characters which contain only characters, numeric digits and underscore

and first character*/

import java.util.*;

```<code>public class PasswordValidationOne {
 /**my hints on how to solve this problem
 * the length of the string must not less 7 and must not more than 16 character
 **/
public static void main (String[] args) {
      Scanner scan = new Scanner(System.in);
      System.out.println("Enter a password");
      String password = scan.nextLine();

      public  void  passwordMethod1( password) {
            int lengthPassword = password.length(); // getting the length of the string password
            boolean containsDigit = password.matches("*.\\d*.");
            boolean containsUnderscore = password.contains("_");
            char firstCharacter = password.charAt(0);
            if((lengthPassword >= 7&& lengthPassword<=16)&& (containsDigit == true) && (containsUnderscore == true)&& (firstCharacter >= 'A' && firstCharacter <= 'z') )
                System.out.println("Password Accepted! You can proceed");
            else
                System.out.println("Password not accepted! Retry");
      } //end of method passwordMethod1()

}// end of main method
</code>```

}//end of the class

答:
The error is correct, if a bit misleading (apparently). This

```<code>public  void  passwordMethod1( password) {
</code>```

is missing the type for password, you wanted

```<code>public  void  passwordMethod1(String password) {
</code>```

Also you cannot declare a method inside another method (move that block outside main).

Body:
Discription: This program check password between 7 to 16

characters which contain only characters, numeric digits and underscore

and first character*/

import java.util.*;

public class PasswordValidationOne {
 /**my hints on how to solve this problem
 * the length of the string must not less 7 and must not more than 16 character
 **/
public static void main (String[] args) {
      Scanner scan = new Scanner(System.in);
      System.out.println("Enter a password");
      String password = scan.nextLine();

      public  void  passwordMethod1( password) {
            int lengthPassword = password.length(); // getting the length of the string password
            boolean containsDigit = password.matches("*.\\d*.");
            boolean containsUnderscore = password.contains("_");
            char firstCharacter = password.charAt(0);
            if((lengthPassword >= 7&& lengthPassword<=16)&& (containsDigit == true) && (containsUnderscore == true)&& (firstCharacter >= 'A' && firstCharacter <= 'z') )
                System.out.println("Password Accepted! You can proceed");
            else
                System.out.println("Password not accepted! Retry");
      } //end of method passwordMethod1()

}// end of main method

}//end of the class

Body:
The error is correct, if a bit misleading (apparently). This

public  void  passwordMethod1( password) {

is missing the type for password, you wanted

public  void  passwordMethod1(String password) {

Also you cannot declare a method inside another method (move that block outside main).


问:
stagehand command not found when trying to create new application
I just installed stagehand on my mac and the install went off without a hitch, but when I try using it to spawn a new dart application I get this error -bash: stagehand: command not found. Any ideas?

答: On MacOS run this command: export PATH="$PATH":"$HOME/.pub-cache/bin"</p>


问:
Convert digits in string to ints and then back to string
Say I have a string: formula = "C3H12O4"

How can I convert the digit chars in the string to ints?
My end goal is to do something along the lines of:

formula * 4

Once converted formula chars to an int, it would be best to report the result back to a string, thus

outputting as:

"C12H48O16"

答:
```<code>formula = "C3H12O4"
</code>```

Code

```<code>p formula.gsub(/\d+/) { |x| x.to_i * 4 }
</code>```

output

```<code>"C12H48O16"
</code>```

Body:
formula = "C3H12O4"

Code

p formula.gsub(/\d+/) { |x| x.to_i * 4 }

output

"C12H48O16"


问:
RuntimeException: Unable to instantiate application
When I run my application, everytime I am getting the below exception in my logcat:

```<code> 04-14 09:29:53.965: W/dalvikvm(1020): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
    04-14 09:29:53.985: E/AndroidRuntime(1020): FATAL EXCEPTION: main
    04-14 09:29:53.985: E/AndroidRuntime(1020): java.lang.RuntimeException: Unable to instantiate application   android.app.Application: java.lang.NullPointerException
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.LoadedApk.makeApplication(LoadedApk.java:482)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.ActivityThread.handleBindApplication(ActivityThread.java:3938)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.ActivityThread.access$1300(ActivityThread.java:123)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1185)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.os.Handler.dispatchMessage(Handler.java:99)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.os.Looper.loop(Looper.java:137)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.ActivityThread.main(ActivityThread.java:4424)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at java.lang.reflect.Method.invokeNative(Native Method)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at java.lang.reflect.Method.invoke(Method.java:511)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at dalvik.system.NativeStart.main(Native Method)
    04-14 09:29:53.985: E/AndroidRuntime(1020): Caused by: java.lang.NullPointerException
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.LoadedApk.initializeJavaContextClassLoader(LoadedApk.java:362)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.LoadedApk.getClassLoader(LoadedApk.java:305)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.LoadedApk.makeApplication(LoadedApk.java:474)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     ... 11 more
</code>```

Note: When I uninstall the app from the emulator and run it, then I don't get this exception but when I re-run the installed application in emulator, I am getting this. Please help.

答:
Simple Solution:

Just Restart your emulator or mobile device. And the problem is gone!
Reason for this issue was due to a previous app activity was wrongly halted.

Body:
When I run my application, everytime I am getting the below exception in my logcat:

 04-14 09:29:53.965: W/dalvikvm(1020): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
    04-14 09:29:53.985: E/AndroidRuntime(1020): FATAL EXCEPTION: main
    04-14 09:29:53.985: E/AndroidRuntime(1020): java.lang.RuntimeException: Unable to instantiate application   android.app.Application: java.lang.NullPointerException
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.LoadedApk.makeApplication(LoadedApk.java:482)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.ActivityThread.handleBindApplication(ActivityThread.java:3938)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.ActivityThread.access$1300(ActivityThread.java:123)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1185)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.os.Handler.dispatchMessage(Handler.java:99)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.os.Looper.loop(Looper.java:137)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.ActivityThread.main(ActivityThread.java:4424)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at java.lang.reflect.Method.invokeNative(Native Method)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at java.lang.reflect.Method.invoke(Method.java:511)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at dalvik.system.NativeStart.main(Native Method)
    04-14 09:29:53.985: E/AndroidRuntime(1020): Caused by: java.lang.NullPointerException
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.LoadedApk.initializeJavaContextClassLoader(LoadedApk.java:362)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.LoadedApk.getClassLoader(LoadedApk.java:305)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     at android.app.LoadedApk.makeApplication(LoadedApk.java:474)
    04-14 09:29:53.985: E/AndroidRuntime(1020):     ... 11 more

Note: When I uninstall the app from the emulator and run it, then I don't get this exception but when I re-run the installed application in emulator, I am getting this. Please help.


问:
Enable CORS via Web.config not working for .net WebApi
I am trying to get CORS working for my MVC Post action.

I have an MVC attribute:

```<code>using System;
using System.Configuration;
using System.Web.Mvc;
using System.Web.WebPages.Razor.Configuration;

namespace MyApp
{
    public class AllowCorsJsonAttribute : ActionFilterAttribute
    {
        private static String _allowHosts = null;
        public static String AllowHosts
        {
            get
            {
                if(_allowHosts == null)
                {
                    _allowHosts = ConfigurationManager.AppSettings["CorsAllowHost"] ?? "";
                }
                return _allowHosts;
            }
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
#if DEBUG
            if (filterContext.RequestContext.HttpContext.Request.IsLocal)
            {
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", AllowHosts);
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "*");
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Methods", "*");
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials", "true");
            }
#endif
            base.OnActionExecuting(filterContext);
        }
    }
}
</code>```

To Enable CORS for my web api controllers I do this:

```<code>public static class WebApiConfig
{
    private static void EnableCrossSiteRequests(HttpConfiguration config)
    {
#if DEBUG
        var cors = new EnableCorsAttribute(
            origins: AllowCorsJsonAttribute.AllowHosts,
            headers: "*",
            methods: "*")
        {
            SupportsCredentials = true
        };
        config.EnableCors(cors);
#endif
    }

    public static void Register(HttpConfiguration config)
    {
        EnableCrossSiteRequests(config);
        ....
    }
</code>```

I am able to do GET/PUT/etc to my webAPI2 controllers alright. I am able to do Get requests to my MVC controller actions which have the [AllowCorsJson] attribute. However, I am unable to POST to an MVC action as the preflight OPTIONS check keeps failing. The options response has none of the CORS headers in it. It is like my Attribute is not even working for  POST methods.

This get request works when I have the attribute applied to it.

```<code>    [AllowCorsJson]
    public ActionResult GetExecuteModel(Int32 id)
    {
        var editorModel = GetExecutionModel(id);
        editorModel.UserList = null;
        return Json(editorModel, JsonRequestBehavior.AllowGet);
    }
</code>```

However POST'ing to this URL fails:

```<code>    [HttpPost]
    [AllowCorsJson]
    public ActionResult ExecuteSave(MyModel myModel)
    {
        if (!ModelState.IsValid)
        {
            Response.StatusCode = (Int32)HttpStatusCode.BadRequest;
            return Json(ModelState);
        }

        UpdateMyModel(myModel);

        return Json(null);
    }
</code>```

For some reason the the my Filter Attribute does not seem to fire when POST'ing to the ExecuteSave function. Why would this be?

Help appreciated.

答:
try one of the following

config.EnableCors(new EnableCorsAttribute("http://localhost:1219", headers: "*", methods: "*"));

config.Filters.Add(new AuthorizeAttribute());

Body:
I am trying to get CORS working for my MVC Post action.

I have an MVC attribute:

using System;
using System.Configuration;
using System.Web.Mvc;
using System.Web.WebPages.Razor.Configuration;

namespace MyApp
{
    public class AllowCorsJsonAttribute : ActionFilterAttribute
    {
        private static String _allowHosts = null;
        public static String AllowHosts
        {
            get
            {
                if(_allowHosts == null)
                {
                    _allowHosts = ConfigurationManager.AppSettings["CorsAllowHost"] ?? "";
                }
                return _allowHosts;
            }
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
#if DEBUG
            if (filterContext.RequestContext.HttpContext.Request.IsLocal)
            {
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", AllowHosts);
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "*");
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Methods", "*");
                filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials", "true");
            }
#endif
            base.OnActionExecuting(filterContext);
        }
    }
}

To Enable CORS for my web api controllers I do this:

public static class WebApiConfig
{
    private static void EnableCrossSiteRequests(HttpConfiguration config)
    {
#if DEBUG
        var cors = new EnableCorsAttribute(
            origins: AllowCorsJsonAttribute.AllowHosts,
            headers: "*",
            methods: "*")
        {
            SupportsCredentials = true
        };
        config.EnableCors(cors);
#endif
    }

    public static void Register(HttpConfiguration config)
    {
        EnableCrossSiteRequests(config);
        ....
    }

I am able to do GET/PUT/etc to my webAPI2 controllers alright. I am able to do Get requests to my MVC controller actions which have the [AllowCorsJson] attribute. However, I am unable to POST to an MVC action as the preflight OPTIONS check keeps failing. The options response has none of the CORS headers in it. It is like my Attribute is not even working for  POST methods.

This get request works when I have the attribute applied to it.

    [AllowCorsJson]
    public ActionResult GetExecuteModel(Int32 id)
    {
        var editorModel = GetExecutionModel(id);
        editorModel.UserList = null;
        return Json(editorModel, JsonRequestBehavior.AllowGet);
    }

However POST'ing to this URL fails:

    [HttpPost]
    [AllowCorsJson]
    public ActionResult ExecuteSave(MyModel myModel)
    {
        if (!ModelState.IsValid)
        {
            Response.StatusCode = (Int32)HttpStatusCode.BadRequest;
            return Json(ModelState);
        }

        UpdateMyModel(myModel);

        return Json(null);
    }

For some reason the the my Filter Attribute does not seem to fire when POST'ing to the ExecuteSave function. Why would this be?

Help appreciated.


问:
How to tweak this melee script to be more responsive?
I followed this video to get a damage script : https://www.youtube.com/watch?v=aSeE7u8Cs-I&list=PLZ1b66Z1KFKiaTYwyayb8-L7D6bdiaHzc&index=11

The problem is, it's for a gun and for some reason even when the raycast is dead ahead sometimes the knife hit won't register. Is there any way to maybe just make it so that anything a unit in front of me takes damage on click/attack?

This is the current code I have:

```<code>void Start()
    {
        animator = GetComponentInChildren<Animator>();
    }

    // Update is called once per frame
    void Update()
    {

        if (Input.GetButtonDown("Attack"))
        {
            StartCoroutine(Poke());
        }
        else
        {

        }

        IEnumerator Poke()
        {
            RaycastHit knife;
            //this line was causing weird delay but I can't remember 100% what it was for and if it's still needed
            //isAttacking = true;
                if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out knife))

                {
                    knife.transform.SendMessage("DamageZombie", DamageAmount, SendMessageOptions.DontRequireReceiver);
                }
                animator.SetBool("isAttacking", true);
                yield return new WaitForSeconds(.1f);
                animator.SetBool("isAttacking", false);
            }
    }
} ```

```

答:
Well you are probably hitting some other collider, some GameObject that doesn't have any component attached that has a method called DamageZombie.

There are multiple ways to limit the Raycast to specific targets:

Physics.Raycast takes additional parameters

maxDistance

 The max distance the ray should check for collisions.

layerMask

A Layer mask that is used to selectively ignore Colliders when casting a ray.

So putting your target enemies on a specific Layer you can already limit the Raycast to only hit these and only when they are close enough:

```<code>// Adjust here which layer(s) you want to hit via the Inspector
public LayerMask targetLayers;

...

if (Physics.Raycast(new Ray(transform.position, transform.forward), out var hit, 1f, (int)targetLayers))
{
    // Do something
}
</code>```

So this already filters the raycast and only hits the first object found within the range of 1 unit and only on the layer(s) configured in targetLayers.

As you said you wanted to hit everything you can actually use Physics.RaycastAll and then iterate through all hits

```<code>var hits = Physics.RaycastAll(new Ray(transform.position, transform.forward), 1f, targetLayers);
foreach(var hit in hits)
{
    // Do something
}
</code>```

Now this basically does the same as before but now hits every object within a range of 1 unit and on the layer(s) configured in targetLayers.

Using Tags you can limit even further and check after the Raycast what you have hit.

```<code>foreach(var hit in hits)
{
    if(!hit.CompareTag("Zombie")) continue;

    // Do something
}
</code>```

Finally in general do NOT use SendMessage! It is extremely inefficient and insecure .. you will never know if the object you are hitting even has a component implementing such a method at all ... or if you changed this string in every place after renaming the method ...

Rather actually get the component you want to hit!

```<code>var damageScript = hit.GetComponent<YOURSCRIPT>();
if(damageScript)
{
    damageScript.DamageZombie(DamageAmount);
}
</code>```

Body:
I followed this video to get a damage script : https://www.youtube.com/watch?v=aSeE7u8Cs-I&list=PLZ1b66Z1KFKiaTYwyayb8-L7D6bdiaHzc&index=11

The problem is, it's for a gun and for some reason even when the raycast is dead ahead sometimes the knife hit won't register. Is there any way to maybe just make it so that anything a unit in front of me takes damage on click/attack?

This is the current code I have:

void Start()
    {
        animator = GetComponentInChildren<Animator>();
    }

    // Update is called once per frame
    void Update()
    {

        if (Input.GetButtonDown("Attack"))
        {
            StartCoroutine(Poke());
        }
        else
        {

        }

        IEnumerator Poke()
        {
            RaycastHit knife;
            //this line was causing weird delay but I can't remember 100% what it was for and if it's still needed
            //isAttacking = true;
                if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out knife))

                {
                    knife.transform.SendMessage("DamageZombie", DamageAmount, SendMessageOptions.DontRequireReceiver);
                }
                animator.SetBool("isAttacking", true);
                yield return new WaitForSeconds(.1f);
                animator.SetBool("isAttacking", false);
            }
    }
} ```

Body:
Well you are probably hitting some other collider, some GameObject that doesn't have any component attached that has a method called DamageZombie.

There are multiple ways to limit the Raycast to specific targets:

Physics.Raycast takes additional parameters

maxDistance

 The max distance the ray should check for collisions.

layerMask

A Layer mask that is used to selectively ignore Colliders when casting a ray.

So putting your target enemies on a specific Layer you can already limit the Raycast to only hit these and only when they are close enough:

// Adjust here which layer(s) you want to hit via the Inspector
public LayerMask targetLayers;

...

if (Physics.Raycast(new Ray(transform.position, transform.forward), out var hit, 1f, (int)targetLayers))
{
    // Do something
}

So this already filters the raycast and only hits the first object found within the range of 1 unit and only on the layer(s) configured in targetLayers.

As you said you wanted to hit everything you can actually use Physics.RaycastAll and then iterate through all hits

var hits = Physics.RaycastAll(new Ray(transform.position, transform.forward), 1f, targetLayers);
foreach(var hit in hits)
{
    // Do something
}

Now this basically does the same as before but now hits every object within a range of 1 unit and on the layer(s) configured in targetLayers.

Using Tags you can limit even further and check after the Raycast what you have hit.

foreach(var hit in hits)
{
    if(!hit.CompareTag("Zombie")) continue;

    // Do something
}

Finally in general do NOT use SendMessage! It is extremely inefficient and insecure .. you will never know if the object you are hitting even has a component implementing such a method at all ... or if you changed this string in every place after renaming the method ...

Rather actually get the component you want to hit!

var damageScript = hit.GetComponent<YOURSCRIPT>();
if(damageScript)
{
    damageScript.DamageZombie(DamageAmount);
}


问:
Combining two monochrome bitmaps to one colorful
I have a button, which may be in two states: pressed and unpressed. Each state is represented by monochrome (black & white) bitmap, which can be edited in my simple editor. What I want is to to display one colorful bitmap which combines somehow those two bitmaps so that user can see all information on the one picture. How this can be achieved? </p>

答:
You can put them as 2 channels of a color image (e.g. using cvMerge())

You can add them together (properly scaled)

You can XOR them.

Try playing with Photoshop's layer options (Multiply, screen, transparencies etc.)


答:
As the docs points out:

To run an application with the Material style, see Using Styles in Qt Quick Controls.

There are several ways to set the style in Qt Quick Controls 2:

Using QQuickStyle in C++:

add QT += quickcontrols2 in your .pro and use #include <QQuickStyle> and QQuickStyle::setStyle("Material"); in main.cpp

Command line argument:

You can run from the console/CMD by adding the argument: ./your_executable -style material.

If you use Qt Creator you can go to Projects-> Build & Run-> Run and in Command line arguments add: -style material.

Environment variable:

You can run from the console/CMD: QT_QUICK_CONTROLS_STYLE=material ./your_executable

If you are using Qt Creator you can add it in the section Projects-> Build & Run-> Run-> Run Environment.

or add qputenv("QT_QUICK_CONTROLS_STYLE", "material"); in main.cpp.

Configuration file:

The qtquickcontrols2.conf file must be created:

```<code>[Controls]
Style=Material
</code>```

and must be in a qresource:

<RCC>
    <qresource prefix="/">
        <file>main.qml</file>
        <file>qtquickcontrols2.conf</file>
    </qresource>
</RCC>
```

Title: Setting the Style in qml Qt

Body:
As the docs points out:

To run an application with the Material style, see Using Styles in Qt Quick Controls.

There are several ways to set the style in Qt Quick Controls 2:

Using QQuickStyle in C++:

add QT += quickcontrols2 in your .pro and use #include <QQuickStyle> and QQuickStyle::setStyle("Material"); in main.cpp

Command line argument:

You can run from the console/CMD by adding the argument: ./your_executable -style material.

If you use Qt Creator you can go to Projects-> Build & Run-> Run and in Command line arguments add: -style material.

Environment variable:

You can run from the console/CMD: QT_QUICK_CONTROLS_STYLE=material ./your_executable

If you are using Qt Creator you can add it in the section Projects-> Build & Run-> Run-> Run Environment.

or add qputenv("QT_QUICK_CONTROLS_STYLE", "material"); in main.cpp.

Configuration file:

The qtquickcontrols2.conf file must be created:

[Controls]
Style=Material

and must be in a qresource:

<RCC>
    <qresource prefix="/">
        <file>main.qml</file>
        <file>qtquickcontrols2.conf</file>
    </qresource>
</RCC>


问:
UITextfield leftView/rightView padding on iOS7
The leftView and rightView views of an UITextField on iOS7 are really close to the textfield border.

How may I add some (horizontal) padding to those items?

I tried modifying the frame, but did not work

```<code>uint padding = 10;//padding for iOS7
UIImageView * iconImageView = [[UIImageView alloc] initWithImage:iconImage];
iconImageView.frame = CGRectMake(0 + padding, 0, 16, 16);
textField.leftView = iconImageView;
</code>```

Please, note that I'm not interested in adding padding to the textfield's text, like this Set padding for UITextField with UITextBorderStyleNone

答:
This works for me just like I looking for:

```<code>func addImageViewInsideMyTextField() {
    let someView = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 24))
    let imageView = UIImageView(image: UIImage(named: "accountImage"))
    imageView.frame = CGRect(x: 16, y: 0, width: 24, height: 24)
    imageView.contentMode = .scaleAspectFit
    someView.addSubview(imageView)

    self.myTextField.leftView = someView
    self.myTextField.leftViewMode = .always
}
</code>```

Body:
The leftView and rightView views of an UITextField on iOS7 are really close to the textfield border.

How may I add some (horizontal) padding to those items?

I tried modifying the frame, but did not work

uint padding = 10;//padding for iOS7
UIImageView * iconImageView = [[UIImageView alloc] initWithImage:iconImage];
iconImageView.frame = CGRectMake(0 + padding, 0, 16, 16);
textField.leftView = iconImageView;

Please, note that I'm not interested in adding padding to the textfield's text, like this Set padding for UITextField with UITextBorderStyleNone

Body:
This works for me just like I looking for:

func addImageViewInsideMyTextField() {
    let someView = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 24))
    let imageView = UIImageView(image: UIImage(named: "accountImage"))
    imageView.frame = CGRect(x: 16, y: 0, width: 24, height: 24)
    imageView.contentMode = .scaleAspectFit
    someView.addSubview(imageView)

    self.myTextField.leftView = someView
    self.myTextField.leftViewMode = .always
}


问:
Can't use dict.values() with min func's key
I created a dict:

```<code>scores = {5: 35044.51299744237, 25: 29016.41319191076, 50: 27405.930473214907, 100: 27282.50803885739, 250: 27893.822225701646, 500: 29454.18598068598}
</code>```

I can use min function with it using:

```<code>min(scores.keys(),key = lambda x: scores[x])
min(scores, key=scores.get)
</code>```

but when I try to use:

```<code>min(scores.keys(),key = scores.values())
</code>```

I get an error :

'dict_values' object is not callable

Could someone please explain why?

答:
You get 'dict_values' object is not callable because the key argument in min requires a callable object (an object that has __call__ method). In your case scores.values() returns an object with type <class 'dict_values'> that is not callable.

```<code>>>> dct = {}
>>> type(dct.values())
<class 'dict_values'>
>>> callable(dct.values())
False
</code>```

If you wish to get the key with the minimal value, you should try something like this.

```<code>min(scores.items(), key=lambda x: x[1])[0]
</code>```

Or with operator.itemgetter:

```<code>from operator import itemgetter
min(scores.items(), key=itemgetter(1))[0]
</code>```

In other words, min applies key function to the elements provided by scores.items().

If you try scores.keys(), as in your question, min function knows nothing about its values. Though you still can do this:

```<code>min(scores.keys(), key=lambda key: scores[key])
</code>```

But I wouldn't recommend this solution, because key function contains scores inside that can lead to undefined behavior in some cases.

Body:
I created a dict:

scores = {5: 35044.51299744237, 25: 29016.41319191076, 50: 27405.930473214907, 100: 27282.50803885739, 250: 27893.822225701646, 500: 29454.18598068598}

I can use min function with it using:

min(scores.keys(),key = lambda x: scores[x])
min(scores, key=scores.get)

but when I try to use:

min(scores.keys(),key = scores.values())

I get an error :

'dict_values' object is not callable

Could someone please explain why?

Body:
You get 'dict_values' object is not callable because the key argument in min requires a callable object (an object that has __call__ method). In your case scores.values() returns an object with type <class 'dict_values'> that is not callable.

>>> dct = {}
>>> type(dct.values())
<class 'dict_values'>
>>> callable(dct.values())
False

If you wish to get the key with the minimal value, you should try something like this.

min(scores.items(), key=lambda x: x[1])[0]

Or with operator.itemgetter:

from operator import itemgetter
min(scores.items(), key=itemgetter(1))[0]

In other words, min applies key function to the elements provided by scores.items().

If you try scores.keys(), as in your question, min function knows nothing about its values. Though you still can do this:

min(scores.keys(), key=lambda key: scores[key])

But I wouldn't recommend this solution, because key function contains scores inside that can lead to undefined behavior in some cases.


问:
Remove specific array from multiple array set using jquery
I have two checkboxes. When I check one, the code will get status and id of that checkbox and push into array, if that value is not present already

The array set become like this

```<code>  [8,0] [10,0]
</code>```

Requirements:

It is inserting [8,0] [8,0] twice if I check and then uncheck and again check it so this should not insert multiple times same values

Remove specific array from set of array so if I uncheck chkecbox then remove only [8,0] but keep  [10,0]

var positions = [];

$("body").on('click', '.check_box', function() {
  var id = $(this).attr('data-id');
  var status = $(this).attr('data-status');
  if ($(this).prop("checked") == true) { // if click on check
    if (!$.inArray(id, positions)) positions.push(id); // if id and status not in array then only push
    positions.push([id, status]); //  it will  insert  like [8,10] but geting duplicate  [8,10] [8,10]
    console.log(positions);
  } else {
    // if uncheck checkbox

    //  remove specific  value like  [8,0] or if value present [10,0] then remove this
    console.log(positions);
  }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="check_box" data-id="8" data-status="0">

<input type="checkbox" class="check_box" data-id="10" data-status="0"></code>```

答:
You can use indexOf to check if object is present in array & add only if it doesn't exist

For removing, you can use filter & select only those objects in array which are not exactly as you specify

var positions = [];

$("body").on('click', '.check_box', function() {
  var id = $(this).attr('data-id');
  var status = $(this).attr('data-status');
  if ($(this).prop("checked") == true) {
    var exists = false;
    positions.forEach((p) => {
      if (id == p[0] && status == p[1]);
        exists = true;
    });
    if (!exists) {
      positions.push([id, status]);
    }
  } else {
    positions = positions.filter(function(a) {
      return !(a[0] == id && a[1] == status);
    });
  }
  console.log(positions);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="check_box" data-id="8" data-status="0">

<input type="checkbox" class="check_box" data-id="10" data-status="0"></code>```

Explanation

In The first loop .each we iterate through each existing values in array & set exist to true when we find an element which has id & status same as the one we selected

If after loop we have exist as true, we know it already exists & we won't push it to array, otherwise we will push it to the array

In else condition we have used filter function of array, this fuction filters the array & only keep the elements for which we returned true, for elements we return false, it gets removed from resulting array

So we did check every element of array for exact match of id & status & if its matched we return false, so it gets removed from the resulting array

Body:
I have two checkboxes. When I check one, the code will get status and id of that checkbox and push into array, if that value is not present already

The array set become like this

  [8,0] [10,0]

Requirements:

It is inserting [8,0] [8,0] twice if I check and then uncheck and again check it so this should not insert multiple times same values

Remove specific array from set of array so if I uncheck chkecbox then remove only [8,0] but keep  [10,0]

var positions = [];

$("body").on('click', '.check_box', function() {
  var id = $(this).attr('data-id');
  var status = $(this).attr('data-status');
  if ($(this).prop("checked") == true) { // if click on check
    if (!$.inArray(id, positions)) positions.push(id); // if id and status not in array then only push
    positions.push([id, status]); //  it will  insert  like [8,10] but geting duplicate  [8,10] [8,10]
    console.log(positions);
  } else {
    // if uncheck checkbox

    //  remove specific  value like  [8,0] or if value present [10,0] then remove this
    console.log(positions);
  }

});

<input type="checkbox" class="check_box" data-id="8" data-status="0">

<input type="checkbox" class="check_box" data-id="10" data-status="0">

Body:
You can use indexOf to check if object is present in array & add only if it doesn't exist

For removing, you can use filter & select only those objects in array which are not exactly as you specify

var positions = [];

$("body").on('click', '.check_box', function() {
  var id = $(this).attr('data-id');
  var status = $(this).attr('data-status');
  if ($(this).prop("checked") == true) {
    var exists = false;
    positions.forEach((p) => {
      if (id == p[0] && status == p[1]);
        exists = true;
    });
    if (!exists) {
      positions.push([id, status]);
    }
  } else {
    positions = positions.filter(function(a) {
      return !(a[0] == id && a[1] == status);
    });
  }
  console.log(positions);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="check_box" data-id="8" data-status="0">

<input type="checkbox" class="check_box" data-id="10" data-status="0">

Explanation

In The first loop .each we iterate through each existing values in array & set exist to true when we find an element which has id & status same as the one we selected

If after loop we have exist as true, we know it already exists & we won't push it to array, otherwise we will push it to the array

In else condition we have used filter function of array, this fuction filters the array & only keep the elements for which we returned true, for elements we return false, it gets removed from resulting array

So we did check every element of array for exact match of id & status & if its matched we return false, so it gets removed from the resulting array


问:
Front-End Mail Client on wordpress?Possible?
I have a wish to somehow create on front-end a page with webmail client, to access up to 20+ email accounts, also send/recieve emails, etc. Like Thunderbird, or any other email client but on web. I didn't found any plugin for this purpose and maybe you have some ideas how to do that? Thanks!</p>

答:
this might be extremely hard if you wish to build from scratch. My best guess is that you need to find an open-source email client and integrate it within the WP framework. But that also will be hard to do, finding an open-source email client will save a ton and tons of time to build a strong email client but you're going to have to customize its structure to make compatible with WordPress environment, like database calls, authentication and more.
Still, you can always build a simple email client that checks the client email server grab his emails, and send an email if they want to, this is possible using the POP, SMTP PHP functionalities that allows you to talk to the email server.

Thanks


问:
Iterate over model instance field names and values in template
I'm trying to create a basic template to display the selected instance's field values, along with their names.  Think of it as just a standard output of the values of that instance in table format, with the field name (verbose_name specifically if specified on the field) in the first column and the value of that field in the second column.

For example, let's say we have the following model definition:

```<code>class Client(Model):
    name = CharField(max_length=150)
    email = EmailField(max_length=100, verbose_name="E-mail")
</code>```

I would want it to be output in the template like so (assume an instance with the given values):

```<code>Field Name      Field Value
----------      -----------
Name            Wayne Koorts
E-mail          waynes@email.com
</code>```

What I'm trying to achieve is being able to pass an instance of the model to a template and be able to iterate over it dynamically in the template, something like this:

```<code><table>
    {% for field in fields %}
        <tr>
            <td>{{ field.name }}</td>
            <td>{{ field.value }}</td>
        </tr>
    {% endfor %}
</table>
</code>```

Is there a neat, "Django-approved" way to do this?  It seems like a very common task, and I will need to do it often for this particular project.

答:
  {% for mfild in fields%}
   {{mfild}}
  {% endfor%}

    {%for v in records%}

         {{v.id}}
         {{v.title}}
         {{v.desc}}

    {% endfor%}

enter code here```

Body:
I'm trying to create a basic template to display the selected instance's field values, along with their names.  Think of it as just a standard output of the values of that instance in table format, with the field name (verbose_name specifically if specified on the field) in the first column and the value of that field in the second column.

For example, let's say we have the following model definition:

class Client(Model):
    name = CharField(max_length=150)
    email = EmailField(max_length=100, verbose_name="E-mail")

I would want it to be output in the template like so (assume an instance with the given values):

Field Name      Field Value
----------      -----------
Name            Wayne Koorts
E-mail          waynes@email.com

What I'm trying to achieve is being able to pass an instance of the model to a template and be able to iterate over it dynamically in the template, something like this:

    {% for field in fields %}

            {{ field.name }}
            {{ field.value }}

    {% endfor %}

Is there a neat, "Django-approved" way to do this?  It seems like a very common task, and I will need to do it often for this particular project.

Body:
<table border='1'>
 <tr>
  {% for mfild in fields%}
   <td>{{mfild}}</td>
  {% endfor%}
 </tr>
    {%for v in records%}
        <tr>
         <td>{{v.id}}</td>
         <td>{{v.title}}</td>
         <td class="">{{v.desc}}</td>

        </tr>

    {% endfor%}
 </table>

enter code here