问:
Pyspark: Create Schema from Json Schema involving Array columns
I have defined my schema for the df in a json file as follows:

```<code>{
    "table1":{
        "fields":[
            {"metadata":{}, "name":"first_name", "type":"string", "nullable":false},
            {"metadata":{}, "name":"last_name", "type":"string", "nullable":false},
            {"metadata":{}, "name":"subjects", "type":"array","items":{"type":["string", "string"]}, "nullable":false},
            {"metadata":{}, "name":"marks", "type":"array","items":{"type":["integer", "integer"]}, "nullable":false},
            {"metadata":{}, "name":"dept", "type":"string", "nullable":false}
        ]
    }

}
</code>```

EG JSON DATA:

```<code>{
    "table1": [
        {
            "first_name":"john",
            "last_name":"doe",
            "subjects":["maths","science"],
            "marks":[90,67],
            "dept":"abc"
        },
        {
            "first_name":"dan",
            "last_name":"steyn",
            "subjects":["maths","science"],
            "marks":[90,67],
            "dept":"abc"
        },
        {
            "first_name":"rose",
            "last_name":"wayne",
            "subjects":["maths","science"],
            "marks":[90,67],
            "dept":"abc"
        },
        {
            "first_name":"nat",
            "last_name":"lee",
            "subjects":["maths","science"],
            "marks":[90,67],
            "dept":"abc"
        },
        {
            "first_name":"jim",
            "last_name":"lim",
            "subjects":["maths","science"],
            "marks":[90,67],
            "dept":"abc"
        }
    ]
}
</code>```

I want to create the equivalent spark schema from this json file. Below is my code: (reference: Create spark dataframe schema from json schema representation)

```<code>with open(schemaFile) as s:
 schema = json.load(s)["table1"]
 source_schema = StructType.fromJson(schema)
</code>```

The above code works fine if i dont have any array columns. But throws the below error if i have array columns in my schema.

"Could not parse datatype: array"
("Could not parse datatype: %s" json_value)

答:
In your case there was an issue with the representation of the arrays. The correct syntax is:

{ "metadata": {},
   "name": "marks",
    "nullable": true, "type": {"containsNull": true, "elementType": "long", "type": "array" } }.

In order to retrieve the schema from json you can write the next pyspark snippet:

jsonData = """{
    "table1": [{
            "first_name": "john",
            "last_name": "doe",
            "subjects": ["maths", "science"],
            "marks": [90, 67],
            "dept": "abc"
        },
        {
            "first_name": "dan",
            "last_name": "steyn",
            "subjects": ["maths", "science"],
            "marks": [90, 67],
            "dept": "abc"
        },
        {
            "first_name": "rose",
            "last_name": "wayne",
            "subjects": ["maths", "science"],
            "marks": [90, 67],
            "dept": "abc"
        },
        {
            "first_name": "nat",
            "last_name": "lee",
            "subjects": ["maths", "science"],
            "marks": [90, 67],
            "dept": "abc"
        },
        {
            "first_name": "jim",
            "last_name": "lim",
            "subjects": ["maths", "science"],
            "marks": [90, 67],
            "dept": "abc"
        }
    ]
}"""

df = spark.read.json(sc.parallelize([jsonData]))

df.schema.json()
```

<p>This should output:</p>

```{
    "fields": [{
        "metadata": {},
        "name": "table1",
        "nullable": true,
        "type": {
            "containsNull": true,
            "elementType": {
                "fields": [{
                    "metadata": {},
                    "name": "dept",
                    "nullable": true,
                    "type": "string"
                }, {
                    "metadata": {},
                    "name": "first_name",
                    "nullable": true,
                    "type": "string"
                }, {
                    "metadata": {},
                    "name": "last_name",
                    "nullable": true,
                    "type": "string"
                }, {
                    "metadata": {},
                    "name": "marks",
                    "nullable": true,
                    "type": {
                        "containsNull": true,
                        "elementType": "long",
                        "type": "array"
                    }
                }, {
                    "metadata": {},
                    "name": "subjects",
                    "nullable": true,
                    "type": {
                        "containsNull": true,
                        "elementType": "string",
                        "type": "array"
                    }
                }],
                "type": "struct"
            },
            "type": "array"
        }
    }],
    "type": "struct"
}
```

<p>Alternatively, you could use <code>df.schema.simpleString()</code> this will return an relatively simpler schema format:</p>

```struct<table1:array<struct<dept:string,first_name:string,last_name:string,marks:array<bigint>,subjects:array<string>>>>
```

<p>Finally you can store the schema above into a file and load it later on with:</p>

```import json
new_schema = StructType.fromJson(json.loads(schema_json))
```

As you did already. Remember that you could achieve the described process dynamically as well for any json data.

Body:
I have defined my schema for the df in a json file as follows:

{
    "table1":{
        "fields":[
            {"metadata":{}, "name":"first_name", "type":"string", "nullable":false},
            {"metadata":{}, "name":"last_name", "type":"string", "nullable":false},
            {"metadata":{}, "name":"subjects", "type":"array","items":{"type":["string", "string"]}, "nullable":false},
            {"metadata":{}, "name":"marks", "type":"array","items":{"type":["integer", "integer"]}, "nullable":false},
            {"metadata":{}, "name":"dept", "type":"string", "nullable":false}
        ]
    }

}

EG JSON DATA:

{
    "table1": [
        {
            "first_name":"john",
            "last_name":"doe",
            "subjects":["maths","science"],
            "marks":[90,67],
            "dept":"abc"
        },
        {
            "first_name":"dan",
            "last_name":"steyn",
            "subjects":["maths","science"],
            "marks":[90,67],
            "dept":"abc"
        },
        {
            "first_name":"rose",
            "last_name":"wayne",
            "subjects":["maths","science"],
            "marks":[90,67],
            "dept":"abc"
        },
        {
            "first_name":"nat",
            "last_name":"lee",
            "subjects":["maths","science"],
            "marks":[90,67],
            "dept":"abc"
        },
        {
            "first_name":"jim",
            "last_name":"lim",
            "subjects":["maths","science"],
            "marks":[90,67],
            "dept":"abc"
        }
    ]
}

I want to create the equivalent spark schema from this json file. Below is my code: (reference: Create spark dataframe schema from json schema representation)

with open(schemaFile) as s:
 schema = json.load(s)["table1"]
 source_schema = StructType.fromJson(schema)

The above code works fine if i dont have any array columns. But throws the below error if i have array columns in my schema.

"Could not parse datatype: array"
("Could not parse datatype: %s" json_value)

Body:
In your case there was an issue with the representation of the arrays. The correct syntax is:

{ "metadata": {},
   "name": "marks",
    "nullable": true, "type": {"containsNull": true, "elementType": "long", "type": "array" } }.

In order to retrieve the schema from json you can write the next pyspark snippet:

jsonData = """{
    "table1": [{
            "first_name": "john",
            "last_name": "doe",
            "subjects": ["maths", "science"],
            "marks": [90, 67],
            "dept": "abc"
        },
        {
            "first_name": "dan",
            "last_name": "steyn",
            "subjects": ["maths", "science"],
            "marks": [90, 67],
            "dept": "abc"
        },
        {
            "first_name": "rose",
            "last_name": "wayne",
            "subjects": ["maths", "science"],
            "marks": [90, 67],
            "dept": "abc"
        },
        {
            "first_name": "nat",
            "last_name": "lee",
            "subjects": ["maths", "science"],
            "marks": [90, 67],
            "dept": "abc"
        },
        {
            "first_name": "jim",
            "last_name": "lim",
            "subjects": ["maths", "science"],
            "marks": [90, 67],
            "dept": "abc"
        }
    ]
}"""

df = spark.read.json(sc.parallelize([jsonData]))

df.schema.json()

This should output:

{
    "fields": [{
        "metadata": {},
        "name": "table1",
        "nullable": true,
        "type": {
            "containsNull": true,
            "elementType": {
                "fields": [{
                    "metadata": {},
                    "name": "dept",
                    "nullable": true,
                    "type": "string"
                }, {
                    "metadata": {},
                    "name": "first_name",
                    "nullable": true,
                    "type": "string"
                }, {
                    "metadata": {},
                    "name": "last_name",
                    "nullable": true,
                    "type": "string"
                }, {
                    "metadata": {},
                    "name": "marks",
                    "nullable": true,
                    "type": {
                        "containsNull": true,
                        "elementType": "long",
                        "type": "array"
                    }
                }, {
                    "metadata": {},
                    "name": "subjects",
                    "nullable": true,
                    "type": {
                        "containsNull": true,
                        "elementType": "string",
                        "type": "array"
                    }
                }],
                "type": "struct"
            },
            "type": "array"
        }
    }],
    "type": "struct"
}

Alternatively, you could use df.schema.simpleString() this will return an relatively simpler schema format:

struct<table1:array<struct<dept:string,first_name:string,last_name:string,marks:array<bigint>,subjects:array<string>>>>

Finally you can store the schema above into a file and load it later on with:

import json
new_schema = StructType.fromJson(json.loads(schema_json))

As you did already. Remember that you could achieve the described process dynamically as well for any json data.


来源: stackexchange

问:
nested expression in mapbox
I have an expression that I am using in a mapbox map to decide which icon I want to show. It looks like this:

```<code>"icon-image": [
  "case",
  ["==", ["get", "matched"], "True"],
  "greenmarkertick",
  "redmarkercross",
]
</code>```

I need to add another condition to this expression, as when matched is True but something else doesn't match, in this case:

```<code>["!=", ["get", "vehicle"], ["get", "standstill_vehicle"]]
</code>```

I have tried adding this directly to my case expression, like so:

```<code>"icon-image": [
  "case",
  ["==", ["get", "matched"], "True"],
  "greenmarker",
  ["!=", ["get", "vehicle"], ["get", "standstill_vehicle"]],
  "orangemarker",
  "redmarker",
]
</code>```

but this didn't work.

Basically what I need is an expression that checks if the the matched property is true and then checks to see if the vehicle properties match.

If they do display a green marker, if they don't display an orange marker. If matched is false then a red marker should be displayed.

Any help with this would be much appreciated.

答:
I realised that the positioning of the expressions in the case expression does matter. So , I solved my problem with the following expression:

```<code>"icon-image": [
  "case",
  ["all", ["==", ["get", "matched"], "True"], ["!=", ["get", "vehicle"], ["get", "standstill_vehicle"]]],
  "orangemarker",
  ["==", ["get", "matched"], "True"],
  "greenmarker",
  "redmarker",
]
</code>```

ContentLicense: CC BY-SA 4.0

Title: nested expression in mapbox

Body:
I have an expression that I am using in a mapbox map to decide which icon I want to show. It looks like this:

"icon-image": [
  "case",
  ["==", ["get", "matched"], "True"],
  "greenmarkertick",
  "redmarkercross",
]

I need to add another condition to this expression, as when matched is True but something else doesn't match, in this case:

["!=", ["get", "vehicle"], ["get", "standstill_vehicle"]]

I have tried adding this directly to my case expression, like so:

"icon-image": [
  "case",
  ["==", ["get", "matched"], "True"],
  "greenmarker",
  ["!=", ["get", "vehicle"], ["get", "standstill_vehicle"]],
  "orangemarker",
  "redmarker",
]

but this didn't work.

Basically what I need is an expression that checks if the the matched property is true and then checks to see if the vehicle properties match.

If they do display a green marker, if they don't display an orange marker. If matched is false then a red marker should be displayed.

Any help with this would be much appreciated.

Body:
I realised that the positioning of the expressions in the case expression does matter. So , I solved my problem with the following expression:

"icon-image": [
  "case",
  ["all", ["==", ["get", "matched"], "True"], ["!=", ["get", "vehicle"], ["get", "standstill_vehicle"]]],
  "orangemarker",
  ["==", ["get", "matched"], "True"],
  "greenmarker",
  "redmarker",
]


问:
ExitCode always has null does not show the actual return value from exe
I am calling my exe from powershell script like shown below.

```<code>$file = $PSScriptRoot + "\executor.exe"
$code = (Start-Process -WindowStyle Hidden $file -Verb runAs -ArgumentList $Logfile).StandardOutput.ToString;
$nid = (Get-Process "executor.exe").id
Wait-Process -Id $nid

if ($code -eq 1) {
    LogWrite "Execution succeeded"
} else
{
    LogWrite "Execution Failed"
}
</code>```

I have a int main function in my exe program which would return 1 on success, and 0 on failure.
When i try to get the ExitCode(using $LASTEXITCODE) from powershell script it always shows null(neither 1 nor 0), But my exe is returning 1 as expected.
How do i capture the return value of exe in powershell script?

答:
You can use this:

```<code>$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = # path to your exe file

# additional options:
$psi.UseShellExecute = $false
$psi.CreateNoWindow = $false
$psi.WindowStyle = "Maximized"

$p = New-Object System.Diagnostics.Process
$p.StartInfo = $psi
$p.Start() | Out-Null # returns $true if the process started, $false otherwise
$p.WaitForExit()

# here's the exitcode
$exitCode = $p.ExitCode
</code>```

Create the process start info, to specify the executable path, and additional options. It's important to use .WaitForExit() to wait until the process finishes.

What you have tried doesn't get the app exitcode, but what the application write to standard console, which, in your case, I assume is nothing. If you could modify the exe to write to the console, what you did would work.

Body:
I am calling my exe from powershell script like shown below.

$file = $PSScriptRoot + "\executor.exe"
$code = (Start-Process -WindowStyle Hidden $file -Verb runAs -ArgumentList $Logfile).StandardOutput.ToString;
$nid = (Get-Process "executor.exe").id
Wait-Process -Id $nid

if ($code -eq 1) {
    LogWrite "Execution succeeded"
} else
{
    LogWrite "Execution Failed"
}

I have a int main function in my exe program which would return 1 on success, and 0 on failure.
When i try to get the ExitCode(using $LASTEXITCODE) from powershell script it always shows null(neither 1 nor 0), But my exe is returning 1 as expected.
How do i capture the return value of exe in powershell script?

Body:
You can use this:

$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = # path to your exe file

# additional options:
$psi.UseShellExecute = $false
$psi.CreateNoWindow = $false
$psi.WindowStyle = "Maximized"

$p = New-Object System.Diagnostics.Process
$p.StartInfo = $psi
$p.Start() | Out-Null # returns $true if the process started, $false otherwise
$p.WaitForExit()

# here's the exitcode
$exitCode = $p.ExitCode

Create the process start info, to specify the executable path, and additional options. It's important to use .WaitForExit() to wait until the process finishes.

What you have tried doesn't get the app exitcode, but what the application write to standard console, which, in your case, I assume is nothing. If you could modify the exe to write to the console, what you did would work.


问:
Get the current order of specific attribute of elements in class as array in jquery-ui sortable
I am trying to get an array of attributes of ordered elements in jquery-ui sortable.

Below is the code I've tried

```<code>$(".topic_keywords").sortable();

$(".box-item").draggable();

var keywordOrder = $(".topic_keywords").sortable("toArray", {attribute: 'data-id'});

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

Here are the elements

```<code><ul class="topic_keywords" data-id="1">
      <li class="box-item" data-id="1">Item 1</li>
      <li class="box-item" data-id="2">Item 2</li>
</ul>
<ul class="topic_keywords" data-id="2">
    <li class="box-item" data-id="3">Item 3</li>
    <li class="box-item" data-id="4">Item 4</li>
</ul>
</code>```

However, I am only getting the ordered array of first sortable class. How can I get the array from whichever class I am currently sorting the elements of?

答:
To get the order of items that are currently being sorted, I recommend using the update event.

update( event, ui )

  This event is triggered when the user stopped sorting and the DOM position has changed.

Here's a demonstration:

$(".topic_keywords").sortable({

  update: function(event, ui) {

    var keywordOrder = $(this).sortable("toArray", {
      attribute: 'data-id'
    });

    console.log(keywordOrder);

  }

});```
<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>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />

<ul class="topic_keywords" data-id="1">
  <li class="box-item" data-id="1">Item 1</li>
  <li class="box-item" data-id="2">Item 2</li>
</ul>
<ul class="topic_keywords" data-id="2">
  <li class="box-item" data-id="3">Item 3</li>
  <li class="box-item" data-id="4">Item 4</li>
</ul></code>```

Body:
I am trying to get an array of attributes of ordered elements in jquery-ui sortable.

Below is the code I've tried

$(".topic_keywords").sortable();

$(".box-item").draggable();

var keywordOrder = $(".topic_keywords").sortable("toArray", {attribute: 'data-id'});

console.log(keywordOrder);

Here are the elements

Item 1

Item 2

Item 3

Item 4

However, I am only getting the ordered array of first sortable class. How can I get the array from whichever class I am currently sorting the elements of?

Body:
To get the order of items that are currently being sorted, I recommend using the update event.

update( event, ui )

  This event is triggered when the user stopped sorting and the DOM position has changed.

Here's a demonstration:

$(".topic_keywords").sortable({

  update: function(event, ui) {

    var keywordOrder = $(this).sortable("toArray", {
      attribute: 'data-id'
    });

    console.log(keywordOrder);

  }

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />

<ul class="topic_keywords" data-id="1">
  <li class="box-item" data-id="1">Item 1</li>
  <li class="box-item" data-id="2">Item 2</li>
</ul>
<ul class="topic_keywords" data-id="2">
  <li class="box-item" data-id="3">Item 3</li>
  <li class="box-item" data-id="4">Item 4</li>
</ul>


问:
Is there a way to limit the number of Jenkins builds triggered by a Gerrit merge event that was submitted using "Submit With Parents"?
After completing a series of local commits into a local branch of a project using git and Gerrit, I push that series of changes into Gerrit for review and ultimately merge. In Gerrit, I see the "Submit With Parents" button for all but one of these commits. This is expected behavior, and I have come to understand why.

In Jenkins, I also utilize a Jenkinsfile to build out my pipelines and in doing so I also use the Gerrit Triggers plugin to react to the event stream in Gerrit. More specifically, I hook onto the merge event to trigger release ready builds for testing purposes.

When I submit each change individually, Jenkins triggers a build and moves along it's merry way building things one at a time. But... If I merge with parents (assume large feature implementation), Gerrit triggers an event for every single commit in the series. What I am curious to know, is if there is a way in either Jenkins or Gerrit to only handle the event from the child commit and omit the events for the parents?

答:
Jenkins/Gerrit have not a way to handle specifically this but I'll suggest some workarounds:

1) You could add a "Topic" to the Gerrit Trigger on Jenkins with something like a "build" value. Doing this, Jenkins will only build merged changes of this topic and you only need to add the "build" topic to the child change to let Jenkins know what commit you want to build.

2) You could change the Gerrit trigger from "Change Merged" to "Comment Added Contains Regular Expression" with something like a "build" value. Doing this, Jenkins will not build when the changes are merged and you can trigger the build from the child commit just adding a "build" comment in the child change on Gerrit.

I hope this helps


问:
Need to convert EMF to jpeg,png file formats using java
I need to convert the emf,wmf file formats to png or jpeg using full java code(since these formats are not supported in some browsers)..Can anybody guide me..

Thanks in advance

答: Other options: FreeHEP and Apache Batik.  I haven't tried them, though.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Why I am getting 404 error on reloading localhost in Angular?
I have seen many related question on this but none of them helped me to resolve this issue.

I have created my routing as app-routing.module.ts

```<code>const routes: Routes = [
 { path: 'home', component: LandingpageComponent, canActivate: [AuthGuard] },
 { path: '', redirectTo: '/home', pathMatch: 'full' },
 { path: 'trade-order', component: TradeOrderComponent},
 { path: '**', component: NotFoundComponent },
];

@NgModule({
 imports: [RouterModule.forRoot(routes)],
 exports: [RouterModule]
})
</code>```

I have created the whole project and build the project with

```<code>ng build --prod
</code>```

with above code dist folder is created and then after I host this folder on IIS

When i try to access with www.test.com it redirect automatically to www.test.com/home as default page i set as home on route but when I try to reload same URL it display me 404 error.

So I have created file name with .htaccess and in that written text as

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
</code>```

But it did not worked for me .
Do I need to replace {REQUEST_FILENAME} with some other name or do I need to make some change on IIS?

Do I need to replace .htaccess code with some other code.

You can relate my question same as here or as here

I know I will get negative marks on this but to me real I am not able to understand the answer written on different post.

Update 1

As suggested by Nanotage I have created web.config an wrote code as

```<code><configuration>
<system.webServer>
 <rewrite>
<rules>
  <rule name="Redirect all requests" stopProcessing="true">
    <match url=".*" />
    <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
    </conditions>
    <action type="Rewrite" url="/home" />
    <!--<action type="Rewrite" url="/" />-->
    </rule>
</rules>
  </rewrite>
 </system.webServer>
</configuration>
</code>```

image as

答:
A .htaccess file is what the apache web server uses. On IIS it's handled by a web.config file.

I host an angular application on an IIS server, and we use this web.config file

```<code><configuration>
<system.webServer>
  <rewrite>
    <rules>
      <rule name="Redirect all requests" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/HelloWorld/" />
        <!--<action type="Rewrite" url="/" />-->
        </rule>
    </rules>
  </rewrite>
</system.webServer>
</configuration>
</code>```

(shamelessly stolen from Hosting an Angular Web application in IIS server)

Remember you can also add this file to your angular.json file as an asset, and it will be automatically included in the dist directory when you build.

Body:
I have seen many related question on this but none of them helped me to resolve this issue.

I have created my routing as app-routing.module.ts

const routes: Routes = [
 { path: 'home', component: LandingpageComponent, canActivate: [AuthGuard] },
 { path: '', redirectTo: '/home', pathMatch: 'full' },
 { path: 'trade-order', component: TradeOrderComponent},
 { path: '**', component: NotFoundComponent },
];

@NgModule({
 imports: [RouterModule.forRoot(routes)],
 exports: [RouterModule]
})

I have created the whole project and build the project with

ng build --prod

with above code dist folder is created and then after I host this folder on IIS

When i try to access with www.test.com it redirect automatically to www.test.com/home as default page i set as home on route but when I try to reload same URL it display me 404 error.

So I have created file name with .htaccess and in that written text as

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]

But it did not worked for me .
Do I need to replace {REQUEST_FILENAME} with some other name or do I need to make some change on IIS?

Do I need to replace .htaccess code with some other code.

You can relate my question same as here or as here

I know I will get negative marks on this but to me real I am not able to understand the answer written on different post.

Update 1

As suggested by Nanotage I have created web.config an wrote code as

<configuration>
<system.webServer>
 <rewrite>
<rules>
  <rule name="Redirect all requests" stopProcessing="true">
    <match url=".*" />
    <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
    </conditions>
    <action type="Rewrite" url="/home" />

    </rule>
</rules>
  </rewrite>
 </system.webServer>
</configuration>

image as

Body:
A .htaccess file is what the apache web server uses. On IIS it's handled by a web.config file.

I host an angular application on an IIS server, and we use this web.config file

<configuration>
<system.webServer>
  <rewrite>
    <rules>
      <rule name="Redirect all requests" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/HelloWorld/" />
        <!--<action type="Rewrite" url="/" />-->
        </rule>
    </rules>
  </rewrite>
</system.webServer>
</configuration>

(shamelessly stolen from Hosting an Angular Web application in IIS server)

Remember you can also add this file to your angular.json file as an asset, and it will be automatically included in the dist directory when you build.


问:
How to make the timelines stop stucking together?
I have a javafx project which there is a circle and four buttons(left,right,up,down). When you press a button the circle will start move on button s direction. If you press another button the circle has to change direction. If you press the circle it will turn red and the timeline will stop. The problem is every time you press the button for a second time it will update the timeline but it will make another timeline and the circle will go carzy.

I've tried to stop the timeline every time someone press a button but didn't work.

Timeline animation;
btnL.setOnAction(e -> {
 if(check == false){
  animation = new Timeline(new KeyFrame(Duration.millis(50), f->  moveBall('l')));
  animation.setCycleCount(Timeline.INDEFINITE);
  animation.play();
  check = true;
 }
});
btnR.setOnAction(e -> {
 if(check == false){
  animation = new Timeline(new KeyFrame(Duration.millis(50), f-> moveBall('r')));
  animation.setCycleCount(Timeline.INDEFINITE);
  animation.play();
  check = true;
 }
});
btnU.setOnAction(e -> {
 if(check == false){
  animation = new Timeline(new KeyFrame(Duration.millis(50), f->
moveBall('u')));
  animation.setCycleCount(Timeline.INDEFINITE);
  animation.play();
  check = true;
 }
});
btnD.setOnAction(e -> {
 if(check == false){
  animation = new Timeline(new KeyFrame(Duration.millis(50), f-> moveBall('d')));
  animation.setCycleCount(Timeline.INDEFINITE);
  animation.play();
  check = true;
 }
});
circle.setOnMouseClicked(e -> {
 circle.setFill(Color.RED);
 animation.stop();
 check = false;
});
```

In the end I made a boolean check to checking if someone has press the button and the ball is moving any other button will do nothing. But I believe there is anoter solution more correct.

答:
Stopping the timeline before creating a new one should work:

```<code>btnL.setOnAction(e -> {
    if(!check) {
        if (animation != null) {
            animation.stop(); // stop old animation
        }
        animation = new Timeline(new KeyFrame(Duration.millis(50), f->  moveBall('l')));
        animation.setCycleCount(Timeline.INDEFINITE);
        animation.play();
        check = true;
    }
});
</code>```

Since the only thing you're changing is the char you pass to moveBall, you could simply store this value in a field and use only a single Timeline:

```<code>private char direction = 0;
private final Timeline animation = new Timeline(new KeyFrame(Duration.millis(50), f-> moveBall(direction)));

{
    animation.setCycleCount(Timeline.INDEFINITE);
}

private void setDirection(char direction) {
    if (!check) {
        this.direction = direction;
        animation.playFromStart();
        check = true;
    }
}
</code>```

```<code>btnL.setOnAction(e -> setDirection('l'));
btnR.setOnAction(e -> setDirection('r'));
...
</code>```

Note: I'm assuming check is set to false somewhere in code that you have not shown. Otherwise only a click on the circle allows other button presses for other button press from having any effect after the initial one. If not, simply remove the if and the assignment and keep only the rest of the body of the if.

Body:
I have a javafx project which there is a circle and four buttons(left,right,up,down). When you press a button the circle will start move on button s direction. If you press another button the circle has to change direction. If you press the circle it will turn red and the timeline will stop. The problem is every time you press the button for a second time it will update the timeline but it will make another timeline and the circle will go carzy.

I've tried to stop the timeline every time someone press a button but didn't work.

Timeline animation;
btnL.setOnAction(e -> {
 if(check == false){
  animation = new Timeline(new KeyFrame(Duration.millis(50), f->  moveBall('l')));
  animation.setCycleCount(Timeline.INDEFINITE);
  animation.play();
  check = true;
 }
});
btnR.setOnAction(e -> {
 if(check == false){
  animation = new Timeline(new KeyFrame(Duration.millis(50), f-> moveBall('r')));
  animation.setCycleCount(Timeline.INDEFINITE);
  animation.play();
  check = true;
 }
});
btnU.setOnAction(e -> {
 if(check == false){
  animation = new Timeline(new KeyFrame(Duration.millis(50), f->
moveBall('u')));
  animation.setCycleCount(Timeline.INDEFINITE);
  animation.play();
  check = true;
 }
});
btnD.setOnAction(e -> {
 if(check == false){
  animation = new Timeline(new KeyFrame(Duration.millis(50), f-> moveBall('d')));
  animation.setCycleCount(Timeline.INDEFINITE);
  animation.play();
  check = true;
 }
});
circle.setOnMouseClicked(e -> {
 circle.setFill(Color.RED);
 animation.stop();
 check = false;
});

In the end I made a boolean check to checking if someone has press the button and the ball is moving any other button will do nothing. But I believe there is anoter solution more correct.

Body:
Stopping the timeline before creating a new one should work:

btnL.setOnAction(e -> {
    if(!check) {
        if (animation != null) {
            animation.stop(); // stop old animation
        }
        animation = new Timeline(new KeyFrame(Duration.millis(50), f->  moveBall('l')));
        animation.setCycleCount(Timeline.INDEFINITE);
        animation.play();
        check = true;
    }
});

Since the only thing you're changing is the char you pass to moveBall, you could simply store this value in a field and use only a single Timeline:

private char direction = 0;
private final Timeline animation = new Timeline(new KeyFrame(Duration.millis(50), f-> moveBall(direction)));

{
    animation.setCycleCount(Timeline.INDEFINITE);
}

private void setDirection(char direction) {
    if (!check) {
        this.direction = direction;
        animation.playFromStart();
        check = true;
    }
}

btnL.setOnAction(e -> setDirection('l'));
btnR.setOnAction(e -> setDirection('r'));
...

Note: I'm assuming check is set to false somewhere in code that you have not shown. Otherwise only a click on the circle allows other button presses for other button press from having any effect after the initial one. If not, simply remove the if and the assignment and keep only the rest of the body of the if.


问:
pthread without static decelaration with class
Inside the class I declared the thread function. I used static keyword because with out static keyword it is not working with class.

But if the type of the function is static I could not able to access the member function and public variables of the class

```<code>#include <iostream>
#include <pthread.h>
using namespace std;

class Base{

private:
    static  void * fpga_read(void*); // Thread function
    void foo_2();
public:
    /* member variables */
    void foo(void);

protected:
    int b;
};

void Base::foo(void)
{
    pthread_t id;
    pthread_create(&id, NULL,fpga_read,NULL);
    cout << "\nInside base class" << endl;
}
void * Base::fpga_read(void *p)
{
    cout << "\nInside thread function " << endl;
    // error: invalid use of member ‘Base::b’ in static member function
    cout << "Value of B inside thread class" << b;

    int b;
}

int main()
{
    Base a;
    a.foo();

    pthread_exit(NULL);
    return 0;
}
</code>```

Any-body tell me how to use thread function with-out static keyword. so i can able to access all class variables.

答:
You do not need any static member function. You can use the argument parameter of pthread_create and that stateless lambda functions decay to normal function pointers to make code which almost looks like what you actually wrote:

Godbolt link: https://godbolt.org/z/QIGNUX

#include <iostream>
#include <pthread.h>

class Base {
public:
    Base(int state) noexcept : b{state} {}

    void foo();

private:
    int b;

    void fpga_read() {
        std::cout << "Value of B inside thread class" < void* {
        Base* this_ = static_cast<Base*>(that);
        this_->fpga_read();
        return nullptr;
    }, static_cast<void*>(this));
    pthread_join(thread, nullptr);
}
```

Body:
Inside the class I declared the thread function. I used static keyword because with out static keyword it is not working with class.

But if the type of the function is static I could not able to access the member function and public variables of the class

#include <iostream>
#include <pthread.h>
using namespace std;

class Base{

private:
    static  void * fpga_read(void*); // Thread function
    void foo_2();
public:
    /* member variables */
    void foo(void);

protected:
    int b;
};

void Base::foo(void)
{
    pthread_t id;
    pthread_create(&id, NULL,fpga_read,NULL);
    cout << "\nInside base class" << endl;
}
void * Base::fpga_read(void *p)
{
    cout << "\nInside thread function " << endl;
    // error: invalid use of member ‘Base::b’ in static member function
    cout << "Value of B inside thread class" << b;

    int b;
}

int main()
{
    Base a;
    a.foo();

    pthread_exit(NULL);
    return 0;
}

Any-body tell me how to use thread function with-out static keyword. so i can able to access all class variables.

Body:
You do not need any static member function. You can use the argument parameter of pthread_create and that stateless lambda functions decay to normal function pointers to make code which almost looks like what you actually wrote:

Godbolt link: https://godbolt.org/z/QIGNUX

#include <iostream>
#include <pthread.h>

class Base {
public:
    Base(int state) noexcept : b{state} {}

    void foo();

private:
    int b;

    void fpga_read() {
        std::cout << "Value of B inside thread class" << b;
    }
};

void Base::foo()
{
    pthread_t thread;
    pthread_create(&thread, nullptr, [](void* that) -> void* {
        Base* this_ = static_cast<Base*>(that);
        this_->fpga_read();
        return nullptr;
    }, static_cast<void*>(this));
    pthread_join(thread, nullptr);
}


问:
Replace identical placeholders in a string using an array of replacement strings
I have a text:

foo {{bar}} foo {{bar}} foo

I have an array:

```<code>$bar[0] = 'lol';
$bar[1] = 'kek';
</code>```

I want to have this result:

foo lol foo kek foo

I tried this:

```<code>preg_replace("/{{bar}}/usi",$bar,$text);
</code>```

but it doesn't work.

答:
Another idea would be preg_replace_callback() together with array_shift.

```<code>$res = preg_replace_callback('/{{bar}}/', function($m) use (&$bar) {
  return array_shift($bar);
}, $str);
</code>```

to modify $bar from inside the callback function, it's &passed by reference

for the anonymous Callback function to work, you'd probably need PHP v5.4+

Here is a demo at 3v4l.org

Body:
I have a text:

foo {{bar}} foo {{bar}} foo

I have an array:

$bar[0] = 'lol';
$bar[1] = 'kek';

I want to have this result:

foo lol foo kek foo

I tried this:

preg_replace("/{{bar}}/usi",$bar,$text);

but it doesn't work.

Body:
Another idea would be preg_replace_callback() together with array_shift.

$res = preg_replace_callback('/{{bar}}/', function($m) use (&$bar) {
  return array_shift($bar);
}, $str);

to modify $bar from inside the callback function, it's &passed by reference

for the anonymous Callback function to work, you'd probably need PHP v5.4+

Here is a demo at 3v4l.org


问:
iSeries Access ODBC Driver with unixodbc on Debian - Invalid UTF-8 characters being returned from iSeries
Using ODBC driver, ibm-iaccess-1.1.0.10-1.0.amd64, on Debian Linux. When I perform a php sql query and validate the response, I see some of the data returned is not valid utf-8.

mb_check_encoding returns 'false' and the character on screen in a chrome browser is the diamond question mark character.

This happens on a few CHAR field types.

```<code>if(!mb_check_encoding($row["field"])) {
 ... exit with utf-8 error
}
</code>```

I can work around this by converting from UTF-8 to UTF-8:

```<code>mb_convert_encoding($row["field"], 'UTF-8', 'UTF-8');
</code>```

/etc/odbc.ini:

```<code>[as400]
Description = iSeries Access ODBC Driver
Driver = iSeries Access ODBC Driver
system = as400
Naming = 0
DefaultLibraries = *usrlibl
DefaultPkgLibrary = QGPL
DefaultPackage = A/DEFAULT(IBM),2,0,1,0,512
ConnectionType = 0
CommitMode = 1
ExtendedDynamic = 1
AllowDataCompression = 1
AllowUnsupportedChar = 0
ForceTranslation = 1
Trace = 0
Charset = UTF-8
</code>```

/etc/odbcinst.ini:

```<code>Description=IBM i Access for Linux 64-bit ODBC Driver
Driver=/usr/lib/libcwbodbc.so
Setup=/usr/lib/libcwbodbcs.so
fileusage=1
dontdlclose=1
</code>```

Additionally, does IBM document any of the odbc parameters? It seems like this is blindly trying parameters until something works.

答:
A single byte install of OS/400 always returns Latin1 charset via ODBC to Linux. This is from my experience with very old versions (V4). I digged into documentation a few months ago and it seems to provide UTF-8 only with a DBCS-Install.

I can't say if this is still true for current versions of i.

Body:
Using ODBC driver, ibm-iaccess-1.1.0.10-1.0.amd64, on Debian Linux. When I perform a php sql query and validate the response, I see some of the data returned is not valid utf-8.

mb_check_encoding returns 'false' and the character on screen in a chrome browser is the diamond question mark character.

This happens on a few CHAR field types.

if(!mb_check_encoding($row["field"])) {
 ... exit with utf-8 error
}

I can work around this by converting from UTF-8 to UTF-8:

mb_convert_encoding($row["field"], 'UTF-8', 'UTF-8');

/etc/odbc.ini:

[as400]
Description = iSeries Access ODBC Driver
Driver = iSeries Access ODBC Driver
system = as400
Naming = 0
DefaultLibraries = *usrlibl
DefaultPkgLibrary = QGPL
DefaultPackage = A/DEFAULT(IBM),2,0,1,0,512
ConnectionType = 0
CommitMode = 1
ExtendedDynamic = 1
AllowDataCompression = 1
AllowUnsupportedChar = 0
ForceTranslation = 1
Trace = 0
Charset = UTF-8

/etc/odbcinst.ini:

Description=IBM i Access for Linux 64-bit ODBC Driver
Driver=/usr/lib/libcwbodbc.so
Setup=/usr/lib/libcwbodbcs.so
fileusage=1
dontdlclose=1

Additionally, does IBM document any of the odbc parameters? It seems like this is blindly trying parameters until something works.


问:
Why use the INCLUDE clause when creating an index?
While studying for the 70-433 exam I noticed you can create a covering index in one of the following two ways.

```<code>CREATE INDEX idx1 ON MyTable (Col1, Col2, Col3)
</code>```

-- OR --

```<code>CREATE INDEX idx1 ON MyTable (Col1) INCLUDE (Col2, Col3)
</code>```

The INCLUDE clause is new to me.  Why would you use it and what guidelines would you suggest in determining whether to create a covering index with or without the INCLUDE clause?

答:
One reason to prefer INCLUDE over key-columns if you don't need that column in the key is documentation. That makes evolving indexes much more easy in the future.

Considering your example:

```<code>CREATE INDEX idx1 ON MyTable (Col1) INCLUDE (Col2, Col3)
</code>```

That index is best if your query looks like this:

```<code>SELECT col2, col3
  FROM MyTable
 WHERE col1 = ...
</code>```

Of course you should not put columns in INCLUDE if you can get an additional benefit from having them in the key part. Both of the following queries would actually prefer the col2 column in the key of the index.

```<code>SELECT col2, col3
  FROM MyTable
 WHERE col1 = ...
   AND col2 = ...
</code>```

```<code>SELECT TOP 1 col2, col3
  FROM MyTable
 WHERE col1 = ...
 ORDER BY col2
</code>```

Let's assume this is not the case and we have col2 in the INCLUDE clause because there is just no benefit of having it in the tree part of the index.

Fast forward some years.

You need to tune this query:

```<code>SELECT TOP 1 col2
  FROM MyTable
 WHERE col1 = ...
 ORDER BY another_col
</code>```

To optimize that query, the following index would be great:

```<code>CREATE INDEX idx1 ON MyTable (Col1, another_col) INCLUDE (Col2)
</code>```

If you check what indexes you have on that table already, your previous index might still be there:

```<code>CREATE INDEX idx1 ON MyTable (Col1) INCLUDE (Col2, Col3)
</code>```

Now you know that Col2 and Col3 are not part of the index tree and are thus not used to narrow the read index range nor for ordering the rows. Is is rather safe to add another_column to the end of the key-part of the index (after col1). There is little risk to break anything:

```<code>DROP INDEX idx1 ON MyTable;
CREATE INDEX idx1 ON MyTable (Col1, another_col) INCLUDE (Col2, Col3);
</code>```

That index will become bigger, which still has some risks, but it is generally better to extend existing indexes compared to introducing new ones.

If you would have an index without INCLUDE, you could not know what queries you would break by adding another_col right after Col1.

```<code>CREATE INDEX idx1 ON MyTable (Col1, Col2, Col3)
</code>```

What happens if you add another_col between Col1 and Col2? Will other queries suffer?

There are other "benefits" of INCLUDE vs. key columns if you add those columns just to avoid fetching them from the table. However, I consider the documentation aspect the most important one.

To answer your question:

what guidelines would you suggest in determining whether to create a covering index with or without the INCLUDE clause?

If you add a column to the index for the sole purpose to have that column available in the index without visiting the table, put it into the INCLUDE clause.

If adding the column to the index key brings additional benefits (e.g. for order by or because it can narrow the read index range) add it to the key.

You can read a longer discussion about this here:

https://use-the-index-luke.com/blog/2019-04/include-columns-in-btree-indexes

Body:
While studying for the 70-433 exam I noticed you can create a covering index in one of the following two ways.

CREATE INDEX idx1 ON MyTable (Col1, Col2, Col3)

-- OR --

CREATE INDEX idx1 ON MyTable (Col1) INCLUDE (Col2, Col3)

The INCLUDE clause is new to me.  Why would you use it and what guidelines would you suggest in determining whether to create a covering index with or without the INCLUDE clause?

Body:
One reason to prefer INCLUDE over key-columns if you don't need that column in the key is documentation. That makes evolving indexes much more easy in the future.

Considering your example:

CREATE INDEX idx1 ON MyTable (Col1) INCLUDE (Col2, Col3)

That index is best if your query looks like this:

SELECT col2, col3
  FROM MyTable
 WHERE col1 = ...

Of course you should not put columns in INCLUDE if you can get an additional benefit from having them in the key part. Both of the following queries would actually prefer the col2 column in the key of the index.

SELECT col2, col3
  FROM MyTable
 WHERE col1 = ...
   AND col2 = ...

SELECT TOP 1 col2, col3
  FROM MyTable
 WHERE col1 = ...
 ORDER BY col2

Let's assume this is not the case and we have col2 in the INCLUDE clause because there is just no benefit of having it in the tree part of the index.

Fast forward some years.

You need to tune this query:

SELECT TOP 1 col2
  FROM MyTable
 WHERE col1 = ...
 ORDER BY another_col

To optimize that query, the following index would be great:

CREATE INDEX idx1 ON MyTable (Col1, another_col) INCLUDE (Col2)

If you check what indexes you have on that table already, your previous index might still be there:

CREATE INDEX idx1 ON MyTable (Col1) INCLUDE (Col2, Col3)

Now you know that Col2 and Col3 are not part of the index tree and are thus not used to narrow the read index range nor for ordering the rows. Is is rather safe to add another_column to the end of the key-part of the index (after col1). There is little risk to break anything:

DROP INDEX idx1 ON MyTable;
CREATE INDEX idx1 ON MyTable (Col1, another_col) INCLUDE (Col2, Col3);

That index will become bigger, which still has some risks, but it is generally better to extend existing indexes compared to introducing new ones.

If you would have an index without INCLUDE, you could not know what queries you would break by adding another_col right after Col1.

CREATE INDEX idx1 ON MyTable (Col1, Col2, Col3)

What happens if you add another_col between Col1 and Col2? Will other queries suffer?

There are other "benefits" of INCLUDE vs. key columns if you add those columns just to avoid fetching them from the table. However, I consider the documentation aspect the most important one.

To answer your question:

what guidelines would you suggest in determining whether to create a covering index with or without the INCLUDE clause?

If you add a column to the index for the sole purpose to have that column available in the index without visiting the table, put it into the INCLUDE clause.

If adding the column to the index key brings additional benefits (e.g. for order by or because it can narrow the read index range) add it to the key.

You can read a longer discussion about this here:

https://use-the-index-luke.com/blog/2019-04/include-columns-in-btree-indexes


问:
c++ select issue
So I'm trying to build a async server... Here is a summary of what I have so far:

```<code>int sockfd;
int max;
fd_set socks;
set<int> conns;

bind();
listen(sockfd);

while(1){
    FD_ZERO(&socks);
    max = sockfd;
    FD_SET(sockfd, &socks);
    for(set<int>::iterator it=conns.begin(); it!=conns.end(); it++){
        FD_SET(*it, &socks);
        if(max < *it){
            max = *it;
        }
    }

    int res = select(max+1, &socks, NULL, NULL, NULL);

    if(res < 0){
        cerr << "ERROR with select" << endl;
        break;
    }else if(res){
        if(FD_ISSET(sockfd, &socks)){
            //new connection
            int new_sockfd = accept();
            conns.insert(new_sockfd);
        }else{
            for(set<int>::iterator it=conns.begin(); it!=conns.end(); it++){
                if(FD_ISSET(*it, &socks){
                    char buffer[256];
                    read(buffer, 256, *it);
                    cout << buffer << endl;
                    close(*it);
                    conns.erase(*it);
                }
            }
        }
    }
}
</code>```

What ends up happening is... If I connect a client-1, and then client-2. And then I try and send data using Client-2 and then Client-1... it works...

However, If I connect client-1 and then connect client-2... and then try to send data using client-1. Select() returns a -1...

Help?

答:
Take a look into man pages for select. The important part is :

Under the following conditions, pselect() and select() shall fail and set errno to:

EBADF

One or more of the file descriptor sets specified a file descriptor that is not a valid open file descriptor.

EINTR

The function was interrupted before any of the selected events occurred and before the timeout interval expired.

If SA_RESTART has been set for the interrupting signal, it is implementation-defined whether the function restarts or returns with [EINTR].

EINVAL

An invalid timeout interval was specified.

EINVAL

The nfds argument is less than 0 or greater than FD_SETSIZE.

EINVAL

One of the specified file descriptors refers to a STREAM or multiplexer that is linked (directly or indirectly) downstream from a multiplexer.

errno should tell you what is wrong.

This is just a quess, but when you close the connection, your file descriptor becomes invalid. I guess the error from select should be EBADF

Title: c++ select issue

Body:
So I'm trying to build a async server... Here is a summary of what I have so far:

int sockfd;
int max;
fd_set socks;
set<int> conns;

bind();
listen(sockfd);

while(1){
    FD_ZERO(&socks);
    max = sockfd;
    FD_SET(sockfd, &socks);
    for(set<int>::iterator it=conns.begin(); it!=conns.end(); it++){
        FD_SET(*it, &socks);
        if(max < *it){
            max = *it;
        }
    }

    int res = select(max+1, &socks, NULL, NULL, NULL);

    if(res < 0){
        cerr << "ERROR with select" << endl;
        break;
    }else if(res){
        if(FD_ISSET(sockfd, &socks)){
            //new connection
            int new_sockfd = accept();
            conns.insert(new_sockfd);
        }else{
            for(set<int>::iterator it=conns.begin(); it!=conns.end(); it++){
                if(FD_ISSET(*it, &socks){
                    char buffer[256];
                    read(buffer, 256, *it);
                    cout << buffer << endl;
                    close(*it);
                    conns.erase(*it);
                }
            }
        }
    }
}

What ends up happening is... If I connect a client-1, and then client-2. And then I try and send data using Client-2 and then Client-1... it works...

However, If I connect client-1 and then connect client-2... and then try to send data using client-1. Select() returns a -1...

Help?


问:
Bound service leaks memory
I wrote a basic bound service based on the Android documentation, but LeakCanary is telling me the service is leaking.

Is there a leak or have I misconfigured LeakCanary?

How can I write a bound service that does not leak?

The Code

```<code>class LocalService : Service() {

  private val binder = LocalBinder()
  private val generator = Random()

  val randomNumber: Int
    get() = generator.nextInt(100)

  inner class LocalBinder : Binder() {
    fun getService(): LocalService = this@LocalService
  }

  override fun onBind(intent: Intent): IBinder {
    return binder
  }

  override fun onDestroy() {
    super.onDestroy()
    LeakSentry.refWatcher.watch(this) // Only modification is to add LeakCanary
  }
}
</code>```

If I bind to the service from an activity as follows, LeakCanary detects the service has leaked

```<code>class MainActivity: Activity() {

  private var service: LocalService? = null
  private val serviceConnection = object: ServiceConnection {
    override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
      service = (binder as LocalBinder).getService()
    }
    override fun onServiceDisconnected(name: ComponentName?) {
      service = null
    }
  }

  override fun onStart() {
    super.onStart()
    bindService(Intent(this, LocalService::class.java), serviceConnection, BIND_AUTO_CREATE)
  }

  override fun onStop() {
    super.onStop()
    service?.let {
      unbindService(serviceConnection)
      service = null
    }
  }
}
</code>```

```<code>┬
├─ com.example.serviceleak.LocalService$LocalBinder
│    Leaking: NO (it's a GC root)
│    ↓ LocalService$LocalBinder.this$0
│                               ~~~~~~
╰→ com.example.serviceleak.LocalService
     Leaking: YES (RefWatcher was watching this)
</code>```

答:
I don't know if it's late to answer but after reading your question I also setup leakCanary in my project and found this leak. I was sure that it's because of the inner binder class which is holding the reference of outer class which is service here. That is why in your leak log it shows LocationService is leaking.
I found a solution by @commonsguy here and implemented the solution with a bit simpler example here. Hope this helps. Keep coding, stay blessed.</p>

Title: Bound service leaks memory

Body:
I wrote a basic bound service based on the Android documentation, but LeakCanary is telling me the service is leaking.

Is there a leak or have I misconfigured LeakCanary?

How can I write a bound service that does not leak?

The Code

class LocalService : Service() {

  private val binder = LocalBinder()
  private val generator = Random()

  val randomNumber: Int
    get() = generator.nextInt(100)

  inner class LocalBinder : Binder() {
    fun getService(): LocalService = this@LocalService
  }

  override fun onBind(intent: Intent): IBinder {
    return binder
  }

  override fun onDestroy() {
    super.onDestroy()
    LeakSentry.refWatcher.watch(this) // Only modification is to add LeakCanary
  }
}

If I bind to the service from an activity as follows, LeakCanary detects the service has leaked

class MainActivity: Activity() {

  private var service: LocalService? = null
  private val serviceConnection = object: ServiceConnection {
    override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
      service = (binder as LocalBinder).getService()
    }
    override fun onServiceDisconnected(name: ComponentName?) {
      service = null
    }
  }

  override fun onStart() {
    super.onStart()
    bindService(Intent(this, LocalService::class.java), serviceConnection, BIND_AUTO_CREATE)
  }

  override fun onStop() {
    super.onStop()
    service?.let {
      unbindService(serviceConnection)
      service = null
    }
  }
}

┬
├─ com.example.serviceleak.LocalService$LocalBinder
│    Leaking: NO (it's a GC root)
│    ↓ LocalService$LocalBinder.this$0
│                               ~~~~~~
╰→ com.example.serviceleak.LocalService
     Leaking: YES (RefWatcher was watching this)


问:
How can I find out if an ES6 value is var / const / let after it is declared?
I know I can find out if a value is var const or let by looking at where it is declared. However I am wondering - mainly for debugging, developing JS compilers, and academic interest - if it is possible to find out the immutability / scope of a variable (var / const / let-ness) after it has been created.

ie

```<code>doThing(something)
</code>```

Would return

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

Or equivalent. Like we can determine types with typeof or something.constructor.name for constructors.

答:
You can distinguish let and const from var with direct eval in the same function as the variable:

```<code>let a;

try {
    eval('var a');
    // it was undeclared or declared using var
} catch (error) {
    // it was let/const
}
</code>```

As @JonasWilms had written earlier, you can distinguish let from const by attempting assignment:

{
  let x = 5;
  let isConst = false;

  try {
    x = x;
  } catch (err) {
    isConst = true;
  }

  console.log(isConst ? 'const x' : 'let x');
}

{
  const x = 5;
  let isConst = false;

  try {
    x = x;
  } catch (err) {
    isConst = true;
  }

  console.log(isConst ? 'const x' : 'let x');
}```

Body:
I know I can find out if a value is var const or let by looking at where it is declared. However I am wondering - mainly for debugging, developing JS compilers, and academic interest - if it is possible to find out the immutability / scope of a variable (var / const / let-ness) after it has been created.

ie

doThing(something)

Would return

let

Or equivalent. Like we can determine types with typeof or something.constructor.name for constructors.

Body:
You can distinguish let and const from var with direct eval in the same function as the variable:

let a;

try {
    eval('var a');
    // it was undeclared or declared using var
} catch (error) {
    // it was let/const
}

As @JonasWilms had written earlier, you can distinguish let from const by attempting assignment:

{
  let x = 5;
  let isConst = false;

  try {
    x = x;
  } catch (err) {
    isConst = true;
  }

  console.log(isConst ? 'const x' : 'let x');
}

{
  const x = 5;
  let isConst = false;

  try {
    x = x;
  } catch (err) {
    isConst = true;
  }

  console.log(isConst ? 'const x' : 'let x');
}


问:
How to measure the amount of memory webview consumes?
Would there be a way to programmatically measure and monitor the memory consumed by

```<code>WebView.loadUrl
</code>```

when we open a webview activity in our Android app?

I have noticed that for some reason the webpage that I open using WebView.loadUrl has some memory leak and the amount of memory it uses keeps on increasing under random conditions. I wanted to programatically catch that and run some method if the memory usage of my WebView page goes beyond a certain range.

答:
Finding a specific method memory usage is sort if not so possible but there is a small trick to get a probable estimate:

Run the following code and save it somewhere

Run the webview.loadurl("...")

Rerun the following code and subtract the new memory usage from previous to get an idea of how much memory the webview.loadUrl max use at maximum

final Runtime runtime = Runtime.getRuntime();
final long usedMemInMB=(runtime.totalMemory() - runtime.freeMemory()) / 1048576L;
final long maxHeapSizeInMB=runtime.maxMemory() / 1048576L;
final long availHeapSizeInMB = maxHeapSizeInMB - usedMemInMB;

Body:
Would there be a way to programmatically measure and monitor the memory consumed by

WebView.loadUrl

when we open a webview activity in our Android app?

I have noticed that for some reason the webpage that I open using WebView.loadUrl has some memory leak and the amount of memory it uses keeps on increasing under random conditions. I wanted to programatically catch that and run some method if the memory usage of my WebView page goes beyond a certain range.


问:
Dialogflow v2 android sdk - Add QueryParameters to QueryInput
i'm actually trying to use Dialogflow v2 with java sdk in android.

I can already make queries to dialogflow but I wanted to send some payload with my query.
Because of this, I discovered the QueryParameters object and I already set it with my desired payload.

The problem is, I have both QueryInput and QueryParameters defined but there is no documentation (or code references in the source code) about how to apply the parameters to the input before trying to detect the intent.

```<code>SessionsClient.create().use { sessionsClient ->
            // Set the session name using the sessionId (UUID) and projectID
            val session = SessionName.of(PROJECT_ID, UUID)

            System.out.println("Session Path: $session")

            // Set the text (input) and language code (en) for the query
            val textInput = TextInput.newBuilder().setText(text).setLanguageCode(LANGUAGE_CODE)

            // Build the query with the TextInput
            val queryInput = QueryInput.newBuilder().setText(textInput).build()

            // Set payload
            val payload = "{someid: $someid}"
            val queryParameters = QueryParameters.newBuilder().setPayload(Struct.parseFrom(payload.toByteArray())).build()

            // (HERE I NEED TO ADD THE PARAMETERS TO INPUT)

            // Performs the detect intent request
            val response = sessionsClient.detectIntent(session, queryInput)

            // returns the query result
            return response.queryResult
        }
</code>```

答:
After hours of deep searching, I managed to find the DetectIntentRequest class.

```<code>            //Build the request
            val request = DetectIntentRequest.newBuilder()
                .setSession(session.toString())
                .setQueryInput(queryInput)
                .setQueryParams(queryParameters)
                .build()

            // Performs the detect intent request
            val response = sessionsClient.detectIntent(request)
</code>```

Note: if you are using other languages probably you 'll have a third
  parameter in detectIntent function to place your queryParameters

Body:
i'm actually trying to use Dialogflow v2 with java sdk in android.

I can already make queries to dialogflow but I wanted to send some payload with my query.
Because of this, I discovered the QueryParameters object and I already set it with my desired payload.

The problem is, I have both QueryInput and QueryParameters defined but there is no documentation (or code references in the source code) about how to apply the parameters to the input before trying to detect the intent.

SessionsClient.create().use { sessionsClient ->
            // Set the session name using the sessionId (UUID) and projectID
            val session = SessionName.of(PROJECT_ID, UUID)

            System.out.println("Session Path: $session")

            // Set the text (input) and language code (en) for the query
            val textInput = TextInput.newBuilder().setText(text).setLanguageCode(LANGUAGE_CODE)

            // Build the query with the TextInput
            val queryInput = QueryInput.newBuilder().setText(textInput).build()

            // Set payload
            val payload = "{someid: $someid}"
            val queryParameters = QueryParameters.newBuilder().setPayload(Struct.parseFrom(payload.toByteArray())).build()

            // (HERE I NEED TO ADD THE PARAMETERS TO INPUT)

            // Performs the detect intent request
            val response = sessionsClient.detectIntent(session, queryInput)

            // returns the query result
            return response.queryResult
        }

Body:
After hours of deep searching, I managed to find the DetectIntentRequest class.

            //Build the request
            val request = DetectIntentRequest.newBuilder()
                .setSession(session.toString())
                .setQueryInput(queryInput)
                .setQueryParams(queryParameters)
                .build()

            // Performs the detect intent request
            val response = sessionsClient.detectIntent(request)

Note: if you are using other languages probably you 'll have a third
  parameter in detectIntent function to place your queryParameters


问:
How to add a date in SQL?
How to add or sub a date?

```<code>SELECT DATEADD(month, -1, '2017-08-25') AS DATEADD
</code>```

ERROR:

Msg 242, Level 16, State 3, Line 98

  The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

答:
Your query works fine in SQL Server (see here).

You may have arcane internationalization settings that do not treat '2015-08-25' as YYYY-MM-DD.

There are two choices.  You can drop the hyphens:

```<code>SELECT DATEADD(month, -1, '20170825') AS DATEADD
</code>```

SQL Server always treats date strings with eight digits as a date in the format YYYYMMDD.

Or do an explicit conversion:

```<code>SELECT DATEADD(month, -1, CONVERT(DATE, '2017-08-25', 120)) AS DATEADD
</code>```

Title: How to add a date in SQL?

Body:
How to add or sub a date?

SELECT DATEADD(month, -1, '2017-08-25') AS DATEADD

ERROR:

Msg 242, Level 16, State 3, Line 98

  The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

Body:
Your query works fine in SQL Server (see here).

You may have arcane internationalization settings that do not treat '2015-08-25' as YYYY-MM-DD.

There are two choices.  You can drop the hyphens:

SELECT DATEADD(month, -1, '20170825') AS DATEADD

SQL Server always treats date strings with eight digits as a date in the format YYYYMMDD.

Or do an explicit conversion:

SELECT DATEADD(month, -1, CONVERT(DATE, '2017-08-25', 120)) AS DATEADD


问:
How do I always answer No to any prompt with a bash script?
I have a program that runs and asks users certain questions. I want to automate it so that every question is responded to with No.</p>

答:
If you find that yes answers too fast for some reason, you can slow things down a little by using a modified version of @Brian Campbell 's answer - this adds in 0.1 seconds of delay in between each repitition of the word "no"

while true; do echo no; sleep 0.1s; done | <command here>
```


问:
Does Java read a single byte in big endian bit order?
So we can talk about the endianness of both the bit and byte order.
When I read the next byte from FileInputStream, for example, I practically get an 8-bit signed integer, but I have no idea what is the bit order with which Java calculates the byte's integer value. Which comes first, the most significant or the least significant bit?

(sign bit, 2^6 ..... 2^0)
Or...
(2^0, ..... 2^6, sign bit)

答: in int first bit is the sign, the rest is the value, the last bit is the least significant bit.


问:
Move a File from Azure File Storage to Azure Blob Storage
I have rather foolishly uploaded a vhd to Azure file storage thinking I can create a virtual machine from it only to find out it really needs to be in blob storage.

I know I can just upload it again - but it is very large and my upload speed is very slow.

My question is - can I move a file from file storage to blob storage without downloading/uploading again? I.e. is there anything in the Azure portal UI to do it, or even a PowerShell command?

答:
In c#:

```<code>public static CloudFile GetFileReference(CloudFileDirectory parent, string path)
{
    var filename = Path.GetFileName(path);
    var fullPath = Path.GetDirectoryName(path);
    if (fullPath == string.Empty)
    {
        return parent.GetFileReference(filename);
    }
    var dirReference = GetDirectoryReference(parent, fullPath);
    return dirReference.GetFileReference(filename);
}

public static CloudFileDirectory GetDirectoryReference(CloudFileDirectory parent, string path)
{
    if (path.Contains(@"\"))
    {
        var paths = path.Split('\\');
        return GetDirectoryReference(parent.GetDirectoryReference(paths.First()), string.Join(@"\", paths.Skip(1)));
    }
    else
    {
        return parent.GetDirectoryReference(path);
    }
}
</code>```

The code to copy:

```<code>// Source File Storage
string azureStorageAccountName = "shareName";
string azureStorageAccountKey = "XXXXX";
string name = "midrive";
CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(azureStorageAccountName, azureStorageAccountKey), true);
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
CloudFileShare fileShare = fileClient.GetShareReference(name);
CloudFileDirectory directorio = fileShare.GetRootDirectoryReference();
CloudFile cloudFile = GetFileReference(directorio, "SourceFolder\\fileName.pdf");

// Destination Blob
string destAzureStorageAccountName = "xx";
string destAzureStorageAccountKey = "xxxx";
CloudStorageAccount destStorageAccount = new CloudStorageAccount(new StorageCredentials(destAzureStorageAccountName, destAzureStorageAccountKey), true);
CloudBlobClient destClient = destStorageAccount.CreateCloudBlobClient();
CloudBlobContainer destContainer = destClient.GetContainerReference("containerName");
CloudBlockBlob destBlob = destContainer.GetBlockBlobReference("fileName.pdf");

// copy
await TransferManager.CopyAsync(cloudFile, destBlob, true);
</code>```

Body:
In c#:

public static CloudFile GetFileReference(CloudFileDirectory parent, string path)
{
    var filename = Path.GetFileName(path);
    var fullPath = Path.GetDirectoryName(path);
    if (fullPath == string.Empty)
    {
        return parent.GetFileReference(filename);
    }
    var dirReference = GetDirectoryReference(parent, fullPath);
    return dirReference.GetFileReference(filename);
}

public static CloudFileDirectory GetDirectoryReference(CloudFileDirectory parent, string path)
{
    if (path.Contains(@"\"))
    {
        var paths = path.Split('\\');
        return GetDirectoryReference(parent.GetDirectoryReference(paths.First()), string.Join(@"\", paths.Skip(1)));
    }
    else
    {
        return parent.GetDirectoryReference(path);
    }
}

The code to copy:

// Source File Storage
string azureStorageAccountName = "shareName";
string azureStorageAccountKey = "XXXXX";
string name = "midrive";
CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(azureStorageAccountName, azureStorageAccountKey), true);
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
CloudFileShare fileShare = fileClient.GetShareReference(name);
CloudFileDirectory directorio = fileShare.GetRootDirectoryReference();
CloudFile cloudFile = GetFileReference(directorio, "SourceFolder\\fileName.pdf");

// Destination Blob
string destAzureStorageAccountName = "xx";
string destAzureStorageAccountKey = "xxxx";
CloudStorageAccount destStorageAccount = new CloudStorageAccount(new StorageCredentials(destAzureStorageAccountName, destAzureStorageAccountKey), true);
CloudBlobClient destClient = destStorageAccount.CreateCloudBlobClient();
CloudBlobContainer destContainer = destClient.GetContainerReference("containerName");
CloudBlockBlob destBlob = destContainer.GetBlockBlobReference("fileName.pdf");

// copy
await TransferManager.CopyAsync(cloudFile, destBlob, true);


问:
How to send pramas through post function in jquery?
I have some javascript code which uses jQuery to call $.post(). I want to send a string parameter to that function, but my attempts have been unsuccessful. I tried this function call I saw on another post, but it didn't work $.post(SavePoint, { data });

```<code>myTimer = (function(ctx) {
  $.post(getPoint).done(function(xml) {
    parseXml(xml);

    var lon = (parseFloat($xml.find("lon").text()) + 180) * (screen.height / 360);
    var lat = (parseFloat($xml.find("lat").text()) + 90) * (screen.width / 180);

    draw(ctx, rout, lat, lon);

    if (recordTime <= 0 && recordTime > -0.2) {
      $.post(SaveToFile);
      isSaveNeeded = "false";
    }

    var isSaveNeeded = document.getElementById("isSaveNeeded").value;
    if (isSaveNeeded == "true") {
      var latS = parseFloat($xml.find("lat").text());
      var lonS = parseFloat($xml.find("lon").text());
      var rudderS = parseFloat($xml.find("rudder").text());
      var throttleS = parseFloat($xml.find("throttle").text());

      var data = latS + "," + lonS + "," + rudderS + "," + throttleS + ",";
      alert(data);

      $.post(SavePoint, {
        data
      }); //This func call doesn't work..

      alert(data);
      recordTime -= 0.25;
    }
  });
});

setInterval(function() {
  myTimer(ctx);
}, 1000 / rate);
</code>```

答:
$.post take the second param as object not string, I think your data is string, take reference from following. In SavePoint endpoint you will gate data params.

```<code>var data = latS + "," + lonS + "," + rudderS + "," + throttleS + ",";
alert(data);
$.post(SavePoint, { data: data },
    function(returnedData){
         console.log(returnedData);
}).fail(function(){
      console.log("error");
});
</code>```

Body:
I have some javascript code which uses jQuery to call $.post(). I want to send a string parameter to that function, but my attempts have been unsuccessful. I tried this function call I saw on another post, but it didn't work $.post(SavePoint, { data });

myTimer = (function(ctx) {
  $.post(getPoint).done(function(xml) {
    parseXml(xml);

    var lon = (parseFloat($xml.find("lon").text()) + 180) * (screen.height / 360);
    var lat = (parseFloat($xml.find("lat").text()) + 90) * (screen.width / 180);

    draw(ctx, rout, lat, lon);

    if (recordTime <= 0 && recordTime > -0.2) {
      $.post(SaveToFile);
      isSaveNeeded = "false";
    }

    var isSaveNeeded = document.getElementById("isSaveNeeded").value;
    if (isSaveNeeded == "true") {
      var latS = parseFloat($xml.find("lat").text());
      var lonS = parseFloat($xml.find("lon").text());
      var rudderS = parseFloat($xml.find("rudder").text());
      var throttleS = parseFloat($xml.find("throttle").text());

      var data = latS + "," + lonS + "," + rudderS + "," + throttleS + ",";
      alert(data);

      $.post(SavePoint, {
        data
      }); //This func call doesn't work..

      alert(data);
      recordTime -= 0.25;
    }
  });
});

setInterval(function() {
  myTimer(ctx);
}, 1000 / rate);

Body:
$.post take the second param as object not string, I think your data is string, take reference from following. In SavePoint endpoint you will gate data params.

var data = latS + "," + lonS + "," + rudderS + "," + throttleS + ",";
alert(data);
$.post(SavePoint, { data: data },
    function(returnedData){
         console.log(returnedData);
}).fail(function(){
      console.log("error");
});


答:
I used to do this but its a little hacky...

I create a variable and try to change it and if it throws an error then it's a const variable,.

I create a variable and try to change it on the {} braces, if the value is different then it was initially created then it's a var, if not then it's a let variable.

Title: How can I find out if an ES6 value is var / const / let after it is declared?


问:
firebaseAuth.logout workf for menu activity but not for profile activity
I may entangled myself in this but I can't seem to see any reason why this doesn't work.

In the MenuActivity the menu items and their functionalities work fine. Log out works perfectly. When I extent the MenuActivity to the ProfileActivity, for some reason the log out button doesn't work the same, the app crashes and displays the message "My application has stopped xClose the application".

Here are all the classes:

MenuActivity.java:

package com.example.myapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import com.google.firebase.auth.FirebaseAuth;

public class MenuActivity extends AppCompatActivity {

    private FirebaseAuth firebaseAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);

        firebaseAuth = FirebaseAuth.getInstance();
    }

    private void Logout(){
        firebaseAuth.signOut();
        finish();
        startActivity(new Intent(MenuActivity.this, MainActivity.class));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflate = getMenuInflater();
        inflate.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch(item.getItemId()){
            case R.id.logoutMenu:{
                Logout();
                return true;
            }
            case R.id.profileMenu:
                startActivity(new Intent(MenuActivity.this, ProfileActivity.class));
        }
        return super.onOptionsItemSelected(item);
    }

}
```

<p>ProfileActivity.java</p>

<pre class="lang-java prettyprint-override"><code>package com.example.myapplication;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class ProfileActivity extends MenuActivity {

    private TextView userName, userEmail, phoneNumber;
    private Button editProfile, btnChangePassword;
    private FirebaseAuth firebaseAuth;
    private FirebaseDatabase firebaseDatabase;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        userName = findViewById(R.id.tvName3);
        userEmail = findViewById(R.id.tvEmail3);
        phoneNumber = findViewById(R.id.tvPhone3);
        editProfile = findViewById(R.id.btnEditProfile);
        btnChangePassword = findViewById(R.id.btnChangePassword);

        firebaseAuth = FirebaseAuth.getInstance();
        firebaseDatabase = FirebaseDatabase.getInstance();

        final DatabaseReference databaseReference = firebaseDatabase.getReference(firebaseAuth.getUid());

        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                UserProfile userProfile = dataSnapshot.getValue(UserProfile.class);
                userName.setText("Name: " + userProfile.getUserName());
                userEmail.setText("Email: " + userProfile.getUserEmail());
                phoneNumber.setText("Phone: " + userProfile.getUserPhone());
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(ProfileActivity.this, databaseError.getCode(), Toast.LENGTH_SHORT);
            }
        });

        editProfile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ProfileActivity.this, UpdateProfile.class));
            }
        });
        btnChangePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ProfileActivity.this, ChangePassword.class));
            }
        });
    }
}

</code>```

and the menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    android:id="@+id/main_menu" >
    <item
        android:id="@+id/logoutMenu"
        android:orderInCategory="100"
        app:showAsAction="always"
        android:title="Logout">
    </item>

    <item
        android:id="@+id/profileMenu"
        android:orderInCategory="200"
        app:showAsAction="never"
        android:title="Profile">
    </item>

    <item
        android:id="@+id/refreshMenu"
        android:orderInCategory="300"
        app:showAsAction="never"
        android:title="Refresh">
    </item>
</menu>
```

<p>Here are the logcat messages</p>

<pre class="lang-java prettyprint-override"><code>2019-05-31 09:15:56.742 20660-20660/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 20660
    android.content.res.Resources$NotFoundException: String resource ID #0xfffffffd
        at android.content.res.Resources.getText(Resources.java:338)
        at android.widget.Toast.makeText(Toast.java:304)
        at com.example.myapplication.ProfileActivity$1.onCancelled(ProfileActivity.java:58)
        at com.google.firebase.database.core.ValueEventRegistration.fireCancelEvent(com.google.firebase:firebase-database@@17.0.0:80)
        at com.google.firebase.database.core.view.CancelEvent.fire(com.google.firebase:firebase-database@@17.0.0:40)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@17.0.0:55)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:169)
        at android.app.ActivityThread.main(ActivityThread.java:6585)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
</code>```

Is there something I did wrong in the ProfileActivity that interferes with the menu?

答:
```<code>  private void Logout(){
    firebaseAuth.signOut();
    startActivity(new Intent(MenuActivity.this, MainActivity.class));
}
</code>```

try this logout function

Body:
I may entangled myself in this but I can't seem to see any reason why this doesn't work.

In the MenuActivity the menu items and their functionalities work fine. Log out works perfectly. When I extent the MenuActivity to the ProfileActivity, for some reason the log out button doesn't work the same, the app crashes and displays the message "My application has stopped xClose the application".

Here are all the classes:

MenuActivity.java:

package com.example.myapplication;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

import com.google.firebase.auth.FirebaseAuth;

public class MenuActivity extends AppCompatActivity {

    private FirebaseAuth firebaseAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);

        firebaseAuth = FirebaseAuth.getInstance();
    }

    private void Logout(){
        firebaseAuth.signOut();
        finish();
        startActivity(new Intent(MenuActivity.this, MainActivity.class));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflate = getMenuInflater();
        inflate.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch(item.getItemId()){
            case R.id.logoutMenu:{
                Logout();
                return true;
            }
            case R.id.profileMenu:
                startActivity(new Intent(MenuActivity.this, ProfileActivity.class));
        }
        return super.onOptionsItemSelected(item);
    }

}

ProfileActivity.java

package com.example.myapplication;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class ProfileActivity extends MenuActivity {

    private TextView userName, userEmail, phoneNumber;
    private Button editProfile, btnChangePassword;
    private FirebaseAuth firebaseAuth;
    private FirebaseDatabase firebaseDatabase;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        userName = findViewById(R.id.tvName3);
        userEmail = findViewById(R.id.tvEmail3);
        phoneNumber = findViewById(R.id.tvPhone3);
        editProfile = findViewById(R.id.btnEditProfile);
        btnChangePassword = findViewById(R.id.btnChangePassword);

        firebaseAuth = FirebaseAuth.getInstance();
        firebaseDatabase = FirebaseDatabase.getInstance();

        final DatabaseReference databaseReference = firebaseDatabase.getReference(firebaseAuth.getUid());

        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                UserProfile userProfile = dataSnapshot.getValue(UserProfile.class);
                userName.setText("Name: " + userProfile.getUserName());
                userEmail.setText("Email: " + userProfile.getUserEmail());
                phoneNumber.setText("Phone: " + userProfile.getUserPhone());
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(ProfileActivity.this, databaseError.getCode(), Toast.LENGTH_SHORT);
            }
        });

        editProfile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ProfileActivity.this, UpdateProfile.class));
            }
        });
        btnChangePassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ProfileActivity.this, ChangePassword.class));
            }
        });
    }
}

and the menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    android:id="@+id/main_menu" >
    <item
        android:id="@+id/logoutMenu"
        android:orderInCategory="100"
        app:showAsAction="always"
        android:title="Logout">
    </item>

    <item
        android:id="@+id/profileMenu"
        android:orderInCategory="200"
        app:showAsAction="never"
        android:title="Profile">
    </item>

    <item
        android:id="@+id/refreshMenu"
        android:orderInCategory="300"
        app:showAsAction="never"
        android:title="Refresh">
    </item>
</menu>

Here are the logcat messages

2019-05-31 09:15:56.742 20660-20660/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 20660
    android.content.res.Resources$NotFoundException: String resource ID #0xfffffffd
        at android.content.res.Resources.getText(Resources.java:338)
        at android.widget.Toast.makeText(Toast.java:304)
        at com.example.myapplication.ProfileActivity$1.onCancelled(ProfileActivity.java:58)
        at com.google.firebase.database.core.ValueEventRegistration.fireCancelEvent(com.google.firebase:firebase-database@@17.0.0:80)
        at com.google.firebase.database.core.view.CancelEvent.fire(com.google.firebase:firebase-database@@17.0.0:40)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@17.0.0:55)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:169)
        at android.app.ActivityThread.main(ActivityThread.java:6585)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Is there something I did wrong in the ProfileActivity that interferes with the menu?

Body:
  private void Logout(){
    firebaseAuth.signOut();
    startActivity(new Intent(MenuActivity.this, MainActivity.class));
}

try this logout function


问:
Passing context on test cases for React shallow enzyme -jest
How can I pass the context and extract the data in a helper method?

See the below snippet:

```<code>import AppContext from '../../context/AppContext'
import extractDatta from '../../helper';

class App extends Component{
  static contextType = AppContext

  componentWillMount(){
   const resolvedData = extractData("/home",this.context)
  }

 render(){
   return(
  )
 }

}
</code>```

helper/index.js:

```<code>const extractData = (path, context) => {
  // getting context as undefined
}
</code>```

App.test.js:

```<code>describe('App test suites', () => {
  let wrapper;
  let appContext;
  beforeEach(() => {
    appContext = {name: "Application"}
    wrapper = shallow(<Supplier />, { appContext })
  })
  it('Should render the App Component', () => {
    expect(wrapper).toMatchSnapshot();
  })
})
</code>```

Any help appreciated :)

答:
So here is my hacky workaround whilst the Enzyme team work on finishing [https://github.com/airbnb/enzyme/issues/1553](React 16 support). I'm providing the legacy contextTypes on the component class, allowing the context to be passed as per the docs.

```<code>import PropTypes from "prop-types";

describe('App test suites', () => {
  let wrapper;
  let appContext;
  beforeEach(() => {
    appContext = {name: "Application"}

    // Hack in the legacy context API just for tests. You'll get a warning, but it
    // ought to work...
    Supplier.contextTypes = {
      name: PropTypes.string
    }

    wrapper = shallow(<Supplier />, { appContext })
  })

  it('Should render the App Component', () => {
    expect(wrapper).toMatchSnapshot();
  })
})
</code>```

Body:
How can I pass the context and extract the data in a helper method?

See the below snippet:

import AppContext from '../../context/AppContext'
import extractDatta from '../../helper';

class App extends Component{
  static contextType = AppContext

  componentWillMount(){
   const resolvedData = extractData("/home",this.context)
  }

 render(){
   return(
  )
 }

}

helper/index.js:

const extractData = (path, context) => {
  // getting context as undefined
}

App.test.js:

describe('App test suites', () => {
  let wrapper;
  let appContext;
  beforeEach(() => {
    appContext = {name: "Application"}
    wrapper = shallow(<Supplier />, { appContext })
  })
  it('Should render the App Component', () => {
    expect(wrapper).toMatchSnapshot();
  })
})

Any help appreciated :)

Body:
So here is my hacky workaround whilst the Enzyme team work on finishing [https://github.com/airbnb/enzyme/issues/1553](React 16 support). I'm providing the legacy contextTypes on the component class, allowing the context to be passed as per the docs.

import PropTypes from "prop-types";

describe('App test suites', () => {
  let wrapper;
  let appContext;
  beforeEach(() => {
    appContext = {name: "Application"}

    // Hack in the legacy context API just for tests. You'll get a warning, but it
    // ought to work...
    Supplier.contextTypes = {
      name: PropTypes.string
    }

    wrapper = shallow(<Supplier />, { appContext })
  })

  it('Should render the App Component', () => {
    expect(wrapper).toMatchSnapshot();
  })
})


问:
Extracing elements from a nested list based on elements of another nested list
I have two nested lists - one containing userids and their individual location and the second nested list containing product first element and list of userid who have purchased the products. I need to find the unique locations of purchasers for each product.

I am able to get the results by using nested for loops. However, i wanted to the same by list comprehension. i don't want to use dataframes or sql commands.

```<code>users=([1,'MX'],[2,'EN'],[3,'US'],[4,'FR'],[5,'US'],[6,'EN'],[7,'MX'])

    prod=[
        (1005,[5]),
        (1004,[2,4,1]),
        (1003,[3,5]),
        (1002,[7,5,2]),
        (1001,[6,5,1])
        ]
    for p in prod:
        prod_loc=[]
        for u in p[1]:
          for uloc in users:

            if u==uloc[0]:
                if uloc[1] not in prod_loc:
                    prod_loc.append(uloc[1])

            else:
                continue
        print (p[0],prod_loc)

</code>```

Body:
I have two nested lists - one containing userids and their individual location and the second nested list containing product first element and list of userid who have purchased the products. I need to find the unique locations of purchasers for each product.

I am able to get the results by using nested for loops. However, i wanted to the same by list comprehension. i don't want to use dataframes or sql commands.

users=([1,'MX'],[2,'EN'],[3,'US'],[4,'FR'],[5,'US'],[6,'EN'],[7,'MX'])

    prod=[
        (1005,[5]),
        (1004,[2,4,1]),
        (1003,[3,5]),
        (1002,[7,5,2]),
        (1001,[6,5,1])
        ]
    for p in prod:
        prod_loc=[]
        for u in p[1]:
          for uloc in users:

            if u==uloc[0]:
                if uloc[1] not in prod_loc:
                    prod_loc.append(uloc[1])

            else:
                continue
        print (p[0],prod_loc)

Body:
You can do this:

from itertools import groupby

users=([1,'MX'],[2,'EN'],[3,'US'],[4,'FR'],[5,'US'],[6,'EN'],[7,'MX'])

prod=[
    (1005,[5]),
    (1004,[2,4,1]),
    (1003,[3,5]),
    (1002,[7,5,2]),
    (1001,[6,5,1])
    ]

temp = [(p[0],u[1]) for p in prod for u in users if u[0] in p[1]]
result = []

for id, locations in groupby(temp, key=lambda x: x[0]):
            result.append((id, {x[1] for x in locations}))

The ouput is:

[(1005, {'US'}), (1004, {'MX', 'FR', 'EN'}), (1003, {'US'}), (1002, {'EN', 'US', 'MX'}), (1001, {'MX', 'US', 'EN'})]


问:
To convert a data coming in 2x to 1x clock in verilog or systemverilog
I am working on validation. I current face a problem of converting a data that is coming to a unit in 2x clock.

For a signal of 132 bits it travels as 66 bit bus in 2x clock.

At receiving again all the clock conversion is to be done from 2x to 1x getting back all 132 bits of the signal.

Can somebody help me on how to do this ?

Thanks a lot in advance.

答: Here's an excellent paper on clock domain crossing techniques.</p>