问:
set ip address python
i use wmi moudle and try to change my own computer IP Address without any success, its seems that there is not any errors in the running but the the ip address didn't changed
i already checked if i have maybe multiple adapters but i have only one

```<code>import wmi

# Obtain network adaptors configurations
nic_configs = wmi.WMI().Win32_NetworkAdapterConfiguration(IPEnabled=True)

# First network adaptor
try:
    nic = nic_configs[0]
except Exception as e:
    raise Exception("חבר קודם את המחשב למתג!")

# IP address, subnetmask and gateway values should be unicode objects
ip = u'192.168.43.99'
subnetmask = u'255.255.0.0'
gateway = u'15.0.0.254'

# Set IP address, subnetmask and default gateway
# Note: EnableStatic() and SetGateways() methods require *lists* of values to be passed
print nic.EnableStatic(IPAddress=[ip],SubnetMask=[subnetmask])
print nic.SetGateways(DefaultIPGateway=[gateway])
</code>```

output:

```<code>(-2147024891,)
(67,)
</code>```

EDIT: I think its due its not running under adminstrator, how can i make it to run automatic by adminstrator?

答: The answer is that if i didn't run as administrator it ignore the code, but when i run it as administrator it worked </p>

Title: set ip address python

Body:
i use wmi moudle and try to change my own computer IP Address without any success, its seems that there is not any errors in the running but the the ip address didn't changed
i already checked if i have maybe multiple adapters but i have only one

import wmi

# Obtain network adaptors configurations
nic_configs = wmi.WMI().Win32_NetworkAdapterConfiguration(IPEnabled=True)

# First network adaptor
try:
    nic = nic_configs[0]
except Exception as e:
    raise Exception("חבר קודם את המחשב למתג!")

# IP address, subnetmask and gateway values should be unicode objects
ip = u'192.168.43.99'
subnetmask = u'255.255.0.0'
gateway = u'15.0.0.254'

# Set IP address, subnetmask and default gateway
# Note: EnableStatic() and SetGateways() methods require *lists* of values to be passed
print nic.EnableStatic(IPAddress=[ip],SubnetMask=[subnetmask])
print nic.SetGateways(DefaultIPGateway=[gateway])

output:

(-2147024891,)
(67,)

EDIT: I think its due its not running under adminstrator, how can i make it to run automatic by adminstrator?


来源: stackexchange

问:
Python script doesn't execute bash commands in cron job
I have written Python script which I want to execute everyday on my server (Cent OS). I need to execute some bash commands directly from my Python script. Everything works fine when I run the script directly from terminal, but bash commands are not executed when cron job executes the script, although the script does the rest of it is job (inserting to database etc).

My crontab looks as follows:

```<code>00 20 * * 1-5 /home/skanydok/script.sh
</code>```

script.sh contains

```<code>#!/bin/bash

python /home/skanydok/serverBarcodeScanner.py
</code>```

I have several methods which are meant to move, copy or delete files from server, an example method looks as follows:

```<code>def copyBackup():
cmd = "cp -r SKANY_DOKUMENTOW_" + str(now)[:10] + '_' + str(random) + " ./backupy"
call(cmd.split(" "))
</code>```

Also I use this code to save all output from method print to a log file:

```<code>class Logger(object):
def __init__(self):
    self.terminal = sys.stdout
    self.log = open("./backupy/log.txt", "a")

def write(self, message):
    self.terminal.write(message)
    self.log.write(message)

sys.stdout = Logger()
</code>```

The log.txt file is not created, all methods which are supposed to execute commands like cp, mv, rm etc. does not work, although they work fine when executing script on server with:

```<code>python /home/skanydok/serverBarcodeScanner.py
</code>```

I think there must be something in the water with cron jobs, all help would be much appreciated.

答: This is a problem with cronjobs per se, but with the fact that your script uses relative path. Relative path are resolved against the "current working directory", which is not the same when you run the script manually from your home directory and when it's run by cron. The solution is, obviously, to only use absolute path in your script. You can harcode them in the python script itself if they are not supposed to change (which seems to be the case here) or use os.path.dirname(os.path.abspath(__file__)) in your python script to get the script's directory path.

ContentLicense: CC BY-SA 3.0

Body:
I have written Python script which I want to execute everyday on my server (Cent OS). I need to execute some bash commands directly from my Python script. Everything works fine when I run the script directly from terminal, but bash commands are not executed when cron job executes the script, although the script does the rest of it is job (inserting to database etc).

My crontab looks as follows:

00 20 * * 1-5 /home/skanydok/script.sh

script.sh contains

#!/bin/bash

python /home/skanydok/serverBarcodeScanner.py

I have several methods which are meant to move, copy or delete files from server, an example method looks as follows:

def copyBackup():
cmd = "cp -r SKANY_DOKUMENTOW_" + str(now)[:10] + '_' + str(random) + " ./backupy"
call(cmd.split(" "))

Also I use this code to save all output from method print to a log file:

class Logger(object):
def __init__(self):
    self.terminal = sys.stdout
    self.log = open("./backupy/log.txt", "a")

def write(self, message):
    self.terminal.write(message)
    self.log.write(message)

sys.stdout = Logger()

The log.txt file is not created, all methods which are supposed to execute commands like cp, mv, rm etc. does not work, although they work fine when executing script on server with:

python /home/skanydok/serverBarcodeScanner.py

I think there must be something in the water with cron jobs, all help would be much appreciated.


问:
convert dictonay in to list in python, Dictonary has multiple value in single key
I want to get the values of the key. but issue is the key has multiple values. I want all the values in normal array/list:
here is my code:

```<code>dict={"Data": ["john", "vincin","tenzin"]}
dictlist=[]
for key, value in dict.items():
    temp = [value]
    dictlist.append(temp)
print(dictlist[0])
</code>```

output:

```<code>[['john', 'vincin', 'tenzin']]
[Finished in 0.1s]
</code>```

Expected result like this(normal list):

```<code>dictlist[0]="john"
dictlist[1]="vincin"
dictlist[2]="tenzin"
</code>```

答:
This is probably what you want:

```<code>dict={"Data": ["john", "vincin","tenzin"]}
dictlist=[]
for key, value in dict.items():
    dictlist.extend(value)
print(dictlist[0])
</code>```

Note 1: don't use keyword dict as variable name

Note 2: this is even more concise: dictlist = sum(dict.values(),[])

Body:
I want to get the values of the key. but issue is the key has multiple values. I want all the values in normal array/list:
here is my code:

dict={"Data": ["john", "vincin","tenzin"]}
dictlist=[]
for key, value in dict.items():
    temp = [value]
    dictlist.append(temp)
print(dictlist[0])

output:

[['john', 'vincin', 'tenzin']]
[Finished in 0.1s]

Expected result like this(normal list):

dictlist[0]="john"
dictlist[1]="vincin"
dictlist[2]="tenzin"

Body:
This is probably what you want:

dict={"Data": ["john", "vincin","tenzin"]}
dictlist=[]
for key, value in dict.items():
    dictlist.extend(value)
print(dictlist[0])

Note 1: don't use keyword dict as variable name

Note 2: this is even more concise: dictlist = sum(dict.values(),[])


答:
A single byte is indeed "restricted". I'll elaborate in a moment.
What you did, was putting 258 individual bytes of value 0 together.

A byte consists of 8 bits. Imagine each bit like a digit, but intead of decimal, we count in binary, because each digit can only have the value 0 or 1.

So we have a number of 8 digits in binary, so we can count from 00000000 to 11111111.

If you translate that to decimal, it just so happens to be from 0 to 255.

Or in hexadecimal from 00 to ff.

Therefore you cannot have a byte of a value > 255, because otherwise you would need 9 digits on binary to count.
It's not just some arbitrary boundry, it is actually a physical limitation.

Edit: To answer your comment.
You can write single bytes like this:

```<code>bytes([210])
</code>```

or multiple like that:

```<code>bytes([210, 55, 31, 55, 150])
</code>```

and exceeding the limitations will indeed cause an Value error:

```<code>bytes([270])
>ValueError: bytes must be in range(0, 256)
</code>```

Note: 256 is not in range(0, 256)

Title: don't understand bytes integer restriction

Body:
from python3 documentation said that "bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that 0 <= x < 256 (attempts to violate this restriction will trigger ValueError" what is that mean, cause i try :

bytes(258)

still result bytes object:

b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

thanks

Body:
A single byte is indeed "restricted". I'll elaborate in a moment.
What you did, was putting 258 individual bytes of value 0 together.

A byte consists of 8 bits. Imagine each bit like a digit, but intead of decimal, we count in binary, because each digit can only have the value 0 or 1.

So we have a number of 8 digits in binary, so we can count from 00000000 to 11111111.

If you translate that to decimal, it just so happens to be from 0 to 255.

Or in hexadecimal from 00 to ff.

Therefore you cannot have a byte of a value > 255, because otherwise you would need 9 digits on binary to count.
It's not just some arbitrary boundry, it is actually a physical limitation.

Edit: To answer your comment.
You can write single bytes like this:

bytes([210])

or multiple like that:

bytes([210, 55, 31, 55, 150])

and exceeding the limitations will indeed cause an Value error:

bytes([270])
>ValueError: bytes must be in range(0, 256)

Note: 256 is not in range(0, 256)


答:
use extend() which will extend list instead of append() which appends another list as item shown below:

```<code>dictlist.extend(temp)
</code>```

updated code:

```<code>dict={"Data": ["john", "vincin","tenzin"]}
dictlist=[]
for key, value in dict.items():
    temp = [value]
    dictlist.extend(temp)

print(dictlist[0])
</code>```

output:

```<code>['john', 'vincin', 'tenzin']
</code>```

Title: convert dictonay in to list in python, Dictonary has multiple value in single key

Body:
use extend() which will extend list instead of append() which appends another list as item shown below:

dictlist.extend(temp)

updated code:

dict={"Data": ["john", "vincin","tenzin"]}
dictlist=[]
for key, value in dict.items():
    temp = [value]
    dictlist.extend(temp)

print(dictlist[0])

output:

['john', 'vincin', 'tenzin']


答:
Just iterate over the items in your list and append them individually to dictlist</p>

```<code>dict={"Data": ["john", "vincin","tenzin"]}
dictlist=[]
for key, value in dict.items():
    for item in value:
        dictlist.append(item)
print(dictlist)
</code>```

Body:
Just iterate over the items in your list and append them individually to dictlist

dict={"Data": ["john", "vincin","tenzin"]}
dictlist=[]
for key, value in dict.items():
    for item in value:
        dictlist.append(item)
print(dictlist)


问:
ES6 export an existing object
How come I can write

```<code>export { function1, function2 };
</code>```

But I can't write

```<code>const funcs = { function1, function2 };
export funcs;
</code>```

Isn't it semantically the same thing?

Is there any way to export all properties from an object without listing them all one by one? I want to be able to import the module as a whole (i.e. import Utils from './utils') and as individual functions (import { function1 } from './util'), but it won't let me use my default export object for normal export:

```<code>const Util = {
   ...
};

export ???; // <- what do I put here? do I really have to list every field in Util?
export default Util;
</code>```

答:
export { function1, function2 }; does not export an object. It is shorthand for

```<code>export {
  function1 as function1,
  function2 as function2
};
</code>```

which does export the function1 and function2 variables from the module scope as named exports.

Is there any way to export all properties from an object without listing them all one by one?

No. Just don't start with an object, but export the functions individually (using the named export function …(…) {…} syntax). Do not create const Utils = {…}.

I want to be able to import the module as a whole (i.e. import Utils from './utils')

You don't need an object in the default export for that. Just import the module namespace object instead:

```<code>import * as Utils from './utils';
</code>```

Title: ES6 export an existing object

Body:
How come I can write

export { function1, function2 };

But I can't write

const funcs = { function1, function2 };
export funcs;

Isn't it semantically the same thing?

Is there any way to export all properties from an object without listing them all one by one? I want to be able to import the module as a whole (i.e. import Utils from './utils') and as individual functions (import { function1 } from './util'), but it won't let me use my default export object for normal export:

const Util = {
   ...
};

export ???; // <- what do I put here? do I really have to list every field in Util?
export default Util;

Body:
export { function1, function2 }; does not export an object. It is shorthand for

export {
  function1 as function1,
  function2 as function2
};

which does export the function1 and function2 variables from the module scope as named exports.

Is there any way to export all properties from an object without listing them all one by one?

No. Just don't start with an object, but export the functions individually (using the named export function …(…) {…} syntax). Do not create const Utils = {…}.

I want to be able to import the module as a whole (i.e. import Utils from './utils')

You don't need an object in the default export for that. Just import the module namespace object instead:

import * as Utils from './utils';


问:
how to minimise a long && statement - Java
I would like to check if all of the items in array squareData[] is 5.

I could just do this:

if(squareData[0] == 5 && squareData[1] == 5 && ...){...}

But it seems rather inefficient.

Is there a way to minimise this into a for loop of some kind?

Note that the size of squareData[] is 9 items

Thanks!

答:
Welcome to java.

Regardless of the array size, the most basic way is

```<code>boolean allEqual = true;

for (long l : squareData) {
    if (l != 5) {
        allEqual = false;
        break;
    }
}
</code>```

Once you dive deeper into the language, you will find new methods to do it.

Body:
Welcome to java.

Regardless of the array size, the most basic way is

boolean allEqual = true;

for (long l : squareData) {
    if (l != 5) {
        allEqual = false;
        break;
    }
}

Once you dive deeper into the language, you will find new methods to do it.


问:
Why might my .click event not fire?
I'm trying to create a carousel using jQuery. I have a prev class and a next class. A button and an a tag, respectively. Neither .click event works. The events are inside document.ready. </p>

```<code><button type="button" class="prev">❮</button>
<a class="next">❯</a>
</code>```

<p>.</p>

```<code>$(document).ready(function(){
    $("#slide1").show();

    $(".next").click(function () {
        if ($slideNumber < 2){
            switch ($slideNumber){
                case 0: $("#slide0").hide();
                case 1: $("#slide1").hide();
            }
            $slideNumber++
        }else { ...
    });

    $(".prev").click(function () {
        if ($slideNumber > 0){
            switch ($slideNumber){
                case 1: $("#slide1").hide();
                case 2: $("#slide2").hide();
            }
            $slideNumber--
        }else { ...
</code>```

答:
use $(ducument).on() instead of..

$(".prev").click(function () and  $(".next").click(function ()

```<code>$(ducument).on(".next","click",function () {
});
</code>```

Title: Why might my .click event not fire?

Body:
I'm trying to create a carousel using jQuery. I have a prev class and a next class. A button and an a tag, respectively. Neither .click event works. The events are inside document.ready.

<button type="button" class="prev">❮</button>
❯

.

$(document).ready(function(){
    $("#slide1").show();

    $(".next").click(function () {
        if ($slideNumber < 2){
            switch ($slideNumber){
                case 0: $("#slide0").hide();
                case 1: $("#slide1").hide();
            }
            $slideNumber++
        }else { ...
    });

    $(".prev").click(function () {
        if ($slideNumber > 0){
            switch ($slideNumber){
                case 1: $("#slide1").hide();
                case 2: $("#slide2").hide();
            }
            $slideNumber--
        }else { ...

Body:
use $(ducument).on() instead of..

$(".prev").click(function () and  $(".next").click(function ()

$(ducument).on(".next","click",function () {
});


问:
Array won't fill in while loop
I am currently working on schedule list for one company and I am really desperate after few hours of trying to figure out what the duck is messing up.

```<code>$schedule = [];

$result = mysql_query("SELECT *
   FROM schedule s
   INNER JOIN workers w
   ON s.worker_id = w.id BETWEEN [date1] AND [date2]");
while ($row = mysql_fetch_array($result)) {
  if(($row['s.time'] >= '8:00') && ($row['s.time'] < '20:00')) {
    if($schedule[$row['s.date']]['info']['name'] == '') {
      $schedule[$row['s.date']]['info']['name']
           = $row['w.name']; // Just one worker
    } else {
       $schedule[$row['s.date']]['info']['name'] .= ',' . $row['name'];
           // IF there is one or more workers, "join" them together by comma
    }
  }
</code>```

NO

This is not the actual code, I just rewrote the while loop with if conditions

I am unable to modify the table

YES

It only returns one worker

I tried yelling at it

I tried many conditions (empty,isset etc.)

I am not quite sure but I think I need to initialize the $schedule['Wed']['info'] first, but it will be pain in the butt.

答:
This is not the actual code

We can only advise based on the code you posted.

While there is an awful lot wrong with the code, the reason its not looping is that the SELECT statement is unparseable. The problem is that you have no visibility of the SELECT statement failing in your code. There is no error checking in your code.

Title: Array won't fill in while loop

Body:
I am currently working on schedule list for one company and I am really desperate after few hours of trying to figure out what the duck is messing up.

$schedule = [];

$result = mysql_query("SELECT *
   FROM schedule s
   INNER JOIN workers w
   ON s.worker_id = w.id BETWEEN [date1] AND [date2]");
while ($row = mysql_fetch_array($result)) {
  if(($row['s.time'] >= '8:00') && ($row['s.time'] < '20:00')) {
    if($schedule[$row['s.date']]['info']['name'] == '') {
      $schedule[$row['s.date']]['info']['name']
           = $row['w.name']; // Just one worker
    } else {
       $schedule[$row['s.date']]['info']['name'] .= ',' . $row['name'];
           // IF there is one or more workers, "join" them together by comma
    }
  }

NO

This is not the actual code, I just rewrote the while loop with if conditions

I am unable to modify the table

YES

It only returns one worker

I tried yelling at it

I tried many conditions (empty,isset etc.)

I am not quite sure but I think I need to initialize the $schedule['Wed']['info'] first, but it will be pain in the butt.


问:
attr.checked not working on dynamically added element

I'm trying to create an element dynamically that is using [attr.checked]

.ts

```<code>public value = true;

ngAfterViewInit(){
  let testElemet = let testElemet = `<input type="checkbox" [attr.checked]="` + this.value + `? 'checked' : null"/>`;
  document.getElementById("test").innerHTML = testElemet;
}
</code>```

.html

```<code><div id=test>
 <!-- element is created here but is not checked -->
</div>

<!-- this element is checked as it should -->
<input type="checkbox" [attr.checked]="value ? 'checked' : null"/>
</code>```

Any explanation would be appreciated.

答:
It doesn't work this way in Angular, there is no $compile service to compile dynamic as in AngularJS.

What you're looking for is dynamic components loading, check this official guide https://angular.io/guide/dynamic-component-loader.

Body:
I'm trying to create an element dynamically that is using [attr.checked]

.ts

public value = true;

ngAfterViewInit(){
  let testElemet = let testElemet = `<input type="checkbox" [attr.checked]="` + this.value + `? 'checked' : null"/>`;
  document.getElementById("test").innerHTML = testElemet;
}

.html

<input type="checkbox" [attr.checked]="value ? 'checked' : null"/>

Any explanation would be appreciated.


问:
Date format in Angularjs in ASP.Net MVC
I have ASP.NET MVC project and I am trying to format date (dd/MM/yyyy) in my cshtml UI but its returning null.

Below is my cshtml code:

```<code>    <tr ng-repeat="item in items">
                        <td>{{item.Id}}</td>
                        <td>{{item.Name}}</td>
                        <td>{{item.Manufacturer}}</td>
                        <td>{{item.BatchNo}}</td>
                        <td width="50px">{{item.ExpiryDate| date: 'dd/MM/yyyy'}}</td>
    </tr>
</code>```

I tried two ways:

1) formatting in .NET cshtml itself but nothings happening:

```<code><td width="50px">{{item.ExpiryDate| date: 'dd/MM/yyyy'}}</td>
</code>```

2) I tried using filter but its returning null:

```<code>medApp.filter('cmdate', [
    '$filter', function ($filter) {
        return function (input) {
            return $filter('date')(new Date(input), 'dd/MM/yyyy');
        };
    }
]);
</code>```

code in cshtml:

```<code><td width="50px">{{item.ExpiryDate| cmdate: 'dd/MM/yyyy'}}</td>
</code>```

Any clue about the issue?

Thanks

答:
your date passing as json format. create the custom filter like this.

```<code>app.filter("cmdate", function() {
    var re = /\/Date\(([0-9]*)\)\//;
    return function(x) {
        var m = x.match(re);
        if( m ) return new Date(parseInt(m[1]));
        else return null;
    };
});
</code>```

Now call it like this

```<code><td width="50px">{{item.ExpiryDate| cmdate | date: 'dd/MM/yyyy'}}</td>
</code>```

Title: Date format in Angularjs in ASP.Net MVC

Body:
I have ASP.NET MVC project and I am trying to format date (dd/MM/yyyy) in my cshtml UI but its returning null.

Below is my cshtml code:

                        {{item.Id}}
                        {{item.Name}}
                        {{item.Manufacturer}}
                        {{item.BatchNo}}
                        {{item.ExpiryDate| date: 'dd/MM/yyyy'}}

I tried two ways:

1) formatting in .NET cshtml itself but nothings happening:

{{item.ExpiryDate| date: 'dd/MM/yyyy'}}

2) I tried using filter but its returning null:

medApp.filter('cmdate', [
    '$filter', function ($filter) {
        return function (input) {
            return $filter('date')(new Date(input), 'dd/MM/yyyy');
        };
    }
]);

code in cshtml:

{{item.ExpiryDate| cmdate: 'dd/MM/yyyy'}}

Any clue about the issue?

Thanks

Body:
your date passing as json format. create the custom filter like this.

app.filter("cmdate", function() {
    var re = /\/Date\(([0-9]*)\)\//;
    return function(x) {
        var m = x.match(re);
        if( m ) return new Date(parseInt(m[1]));
        else return null;
    };
});

Now call it like this

<td width="50px">{{item.ExpiryDate| cmdate | date: 'dd/MM/yyyy'}}</td>


问:
How to Filter table by column in django
I was trying to filter my columns in my django project template
Currently I am able to search in the table and display the rows that have that that value
But I would like to add a dropdown menu that would ask for a particular column value and then filter based on that value

currently my code is

views.py

```<code>def user_profile(request):
    q = request.GET.get('q','')
    custom = Customer.objects.all()
    if q:
        custom1=custom.filter(name__contains=q)
        custom2=custom.filter(Product__contains=q)
        custom3=custom.filter(L3__contains=q)
        custom4=custom.filter(Server_Type__contains=q)
        custom5=custom.filter(Version__contains=q)
        custom6=custom.filter(Status__contains=q)
        custom7=custom.filter(PM__contains=q)
        custom8=custom.filter(CDM__contains=q)
        custom = custom1 | custom2 | custom3 | custom4 | custom5 | custom6 |
                 custom7 | custom8
</code>```

here name product l3 are my fields from my model that I would like to filter from

in my home.html

```<code> <input type="text" class="text_field" id="search" placeholder="Search for..." required>
<input type="button" class="button" onclick="go()" value="go" id="submit">
</code>```

my js.js

```<code>function go(){
    // alert("hellonikhar");
    var q = document.getElementById("search").value;

    window.open("/?q="+q,"_self");
}
</code>```

I am storing the value entered in the textbox in var q and displaying the data but i would like to add a dropdown first which would choose the field and then q should filter based on only that column

答:
Could you please try below query

```<code>Customer.objects.filter(Q(name__icontains=q)
                   |Q(Product__icontains=q)
                   |Q(L3__icontains=q)
                   |Q(Server_Type__icontains=q)
                   |Q(Version__icontains=q)
                   |Q(Status__icontains=q)
                   |Q(PM__icontains=q)
                   |Q(CDM__icontains=q)
                   )
</code>```

Title: How to Filter table by column in django

Body:
I was trying to filter my columns in my django project template
Currently I am able to search in the table and display the rows that have that that value
But I would like to add a dropdown menu that would ask for a particular column value and then filter based on that value

currently my code is

views.py

def user_profile(request):
    q = request.GET.get('q','')
    custom = Customer.objects.all()
    if q:
        custom1=custom.filter(name__contains=q)
        custom2=custom.filter(Product__contains=q)
        custom3=custom.filter(L3__contains=q)
        custom4=custom.filter(Server_Type__contains=q)
        custom5=custom.filter(Version__contains=q)
        custom6=custom.filter(Status__contains=q)
        custom7=custom.filter(PM__contains=q)
        custom8=custom.filter(CDM__contains=q)
        custom = custom1 | custom2 | custom3 | custom4 | custom5 | custom6 |
                 custom7 | custom8

here name product l3 are my fields from my model that I would like to filter from

in my home.html

 <input type="text" class="text_field" id="search" placeholder="Search for..." required>
<input type="button" class="button" onclick="go()" value="go" id="submit">

my js.js

function go(){
    // alert("hellonikhar");
    var q = document.getElementById("search").value;

    window.open("/?q="+q,"_self");
}

I am storing the value entered in the textbox in var q and displaying the data but i would like to add a dropdown first which would choose the field and then q should filter based on only that column

Body:
Could you please try below query

Customer.objects.filter(Q(name__icontains=q)
                   |Q(Product__icontains=q)
                   |Q(L3__icontains=q)
                   |Q(Server_Type__icontains=q)
                   |Q(Version__icontains=q)
                   |Q(Status__icontains=q)
                   |Q(PM__icontains=q)
                   |Q(CDM__icontains=q)
                   )


问:
Force view-port size for print layout with bootstrap grid
My page presents a form that breaks from horizontal to vertical at @screen-tablet which is around ~ 760px. an A4 page width is around ~600px.

In my print.css I'm shrinking all the text, e.g, font-size:85% so that all default font sized 14 will print at around 12. I also want to display the format
 and it's horizontal state, meaning - viewport > 760px. Problem is that the print layout sets the page width at A4 ~600px causing the form to display vertically.

Is there any way to "fool" the layout into thinking it's more than 760px?

(I'm hoping for an answer that doesn't require setting a whole new layout for print - just making it look as it would on desktop).

答:
For this, you can use the @media followed by any of these

@media screen, @media print,@media screen, print

By defining the state of any style at the time of paint you can define every rule on @media screen, print which can work for the range in the document.

Like you want to freeze the viewport to 700px then you can define the @media print rule for @media screen,print and (min-width<=760px) { body,html{ min-width:700px;max-width:700px; }}.
which define and set your viewport to a specific point.

Note: This rule can also be used for other work like transform and
  zoom as an aspect.

ContentLicense: CC BY-SA 4.0


问:
How to transpose from math xy graph to canvas coords in js
I want to draw an XY graph (say X and Y from -100 to +100)

using the HTML canvas and javascript.

Say I'm using a 500x500  how would I transpose to canvas coords?
I'll set the center using canvas.translate()...

I want to do something like the following:

```<code>var cn = $('#myCanvas')[0]
var dr = cn.getContext('2d')
xmin = -100; xmax = 100
ymin = -100  ymax = 100
canvasWidth = cn.width
canvasHeight = cn.height

cn.translate(cn.width/2, cn.height/2) // set 0,0 to center of canvas

trMoveTo(-20, 50)
trLineTo(70, -40)
stroke()

function trMoveTo(x, y) { moveTo (xtr(x), ytr(y)) }
function trLineTo(x, y) { lineTo (xtr(x), ytr(y)) }
function xtr(x) { return ???  }
function ytr(y) { return ???  }
</code>```

The problem is causing me brain reversal convolutions :-(

答:
What you are looking after is a linear transformation from range, e.g., (xmin, xmax) to (cmin, cmax) (c denotes here canvas coordinates). This can be directly described as:

```<code>c = (x - xmin)/(xmax - xmin)*(cmax - cmin) + cmin
</code>```

This formula first rescales x to the range [0,1] and then maps this onto the canvas coordinates spanning the range [cmin, cmax]. In other words, one can check directly that the formula is linear (affine) and xmin maps to cmin while xmax maps to cmax.

In your particular case, cmin for the x-axis seems to be -canvasWidth/2, while cmax = canvasWidth/2, thus

```<code>c = (x - xmin)/(xmax - xmin)*canvasWidth - canvasWidth/2
</code>```

Body:
I want to draw an XY graph (say X and Y from -100 to +100)

using the HTML canvas and javascript.

Say I'm using a 500x500  how would I transpose to canvas coords?
I'll set the center using canvas.translate()...

I want to do something like the following:

var cn = $('#myCanvas')[0]
var dr = cn.getContext('2d')
xmin = -100; xmax = 100
ymin = -100  ymax = 100
canvasWidth = cn.width
canvasHeight = cn.height

cn.translate(cn.width/2, cn.height/2) // set 0,0 to center of canvas

trMoveTo(-20, 50)
trLineTo(70, -40)
stroke()

function trMoveTo(x, y) { moveTo (xtr(x), ytr(y)) }
function trLineTo(x, y) { lineTo (xtr(x), ytr(y)) }
function xtr(x) { return ???  }
function ytr(y) { return ???  }

The problem is causing me brain reversal convolutions :-(

Body:
What you are looking after is a linear transformation from range, e.g., (xmin, xmax) to (cmin, cmax) (c denotes here canvas coordinates). This can be directly described as:

c = (x - xmin)/(xmax - xmin)*(cmax - cmin) + cmin

This formula first rescales x to the range [0,1] and then maps this onto the canvas coordinates spanning the range [cmin, cmax]. In other words, one can check directly that the formula is linear (affine) and xmin maps to cmin while xmax maps to cmax.

In your particular case, cmin for the x-axis seems to be -canvasWidth/2, while cmax = canvasWidth/2, thus

c = (x - xmin)/(xmax - xmin)*canvasWidth - canvasWidth/2


问:
Acceleration/Deceleration Ratio equivalent with KeyFrame
Is there a formula to translate AccelerationRatio or DecelerationRatio to Bezier control points for use in a KeySpline in a SplineDoubleKeyFrame? For example, an "Ease Out" may be DecelerationRatio=0.5, but this doesn't seem equivalent to KeySpline="0.0,0.0 0.5,1.0" or KeySpline="0.5,0 1,0.5".

Would this involve multiple SplineDoubleKeyFrame to achieve DecelerationRatio=0.5? Or is their a particular formula that makes them equivalent in a single frame?

Or is this not to be achieved via a SplineDoubleKeyFrame but a EasingDoubleKeyFrame instead (if so, what is the EasingFunction/EasingMode/Other Attributes)?

Essentially, I'm trying to achieve <DoubleAnimation Storyboard.TargetName="deceleratedRectangle" Storyboard.TargetProperty="(Rectangle.Width)"  DecelerationRatio="0.5" Duration="0:0:10" From="20" To="400" /> with KeyFrames as there will be multiple frames that target the same property path and accelerate/decelerate it.

UPDATE: According to the Microsoft WPF-Silverlight Comparison Whitepaper.pdf on page 7:

The linear interpolation
  can be modified somewhat by adding
  AccelerationRatio and
  DecelerationRatio properties to the
  animation. These attributes
  essentially create three linear
  interpolations for the entire
  animation in order to modify the
  starting and stopping speeds. For
  example, a designer would use these
  attributes to have an object gradually
  pick up speed or stop suddenly.
  Unfortunately, Silverlight does not
  implement these two attributes, but
  the effect can be duplicated using
  keyframe animations with linear interpolation.

So I guess this means it can be done with just 3 key frames, but what the formula is I have no idea.

SOLUTION: For others that may come along that need this, posting the ECMAScript solution crafted by Peter Taylor:

```<code><html>
    <head>
        <title>Acceleration or deceleration with Bezier splines</title>
        <script type="text/javascript"><!--
            function calcBezier() {
                var res = new Array();
                var y0 = +document.getElementById("y0").value;
                var y1 = +document.getElementById("y1").value;
                var t0 = +document.getElementById("t0").value;
                var t1 = +document.getElementById("t1").value;
                var ra = +document.getElementById("ra").value;
                var rd = +document.getElementById("rd").value;

                var ta = t0 + ra * (t1 - t0);
                if (ra > 0) res.push("ta = " + ta + "<br />");
                var td = t1 - rd * (t1 - t0);
                if (rd > 0) res.push("td = " + td + "<br />");

                var vm = 2 * (y1 - y0) / (t1 + td - ta - t0);
                res.push("vm = " + vm + "<br />");

                var ya = y0 + vm * (ta - t0) / 2
                if (ra > 0) res.push("ya = " + ya + "<br />");
                var yd = y1 - vm * (t1 - td) / 2
                if (rd > 0) res.push("yd = " + yd + "<br />");

                res.push('<DiscreteDoubleKeyFrame KeyTime="'+t0+'" Value="'+y0+'" /><br />');

                if (ra > 0) {
                    // y - ya = (t - ta) * vm => t = ta + (y - ya) / vm
                    var p1t = ta - (ya - y0) / vm;
                    // Scale for spline params: (t0,y0):(0,0) and (ta,ya):(1,1)
                    p1t = (p1t - t0) / (ta - t0);
                    // Lift to cubic.
                    res.push('<SplineDoubleKeyFrame KeyTime="'+ta+'" Value="'+ya+'" KeySpline="'+((2*p1t)/3)+',0 '+((2*p1t+1)/3)+','+(1/3)+'" /><br />');
                }

                if (ra + rd < 1) {
                    res.push('<LinearDoubleKeyFrame KeyTime="'+td+'" Value="'+yd+'" /><br />');
                }

                if (rd > 0) {
                    var q1y = 1;
                    var q1t = td + (y1 - yd) / vm;
                    q1t = (q1t - td) / (t1 - td);
                    res.push('<SplineDoubleKeyFrame KeyTime="'+t1+'" Value="'+y1+'" KeySpline="'+((2*q1t)/3)+','+(2/3)+' '+((2*q1t+1)/3)+',1" /><br />');
                }

                document.getElementById("results").innerHTML = res.join("");
            }
        //-->
        </script>
    </head>
    <body>
        <p>Interpolate y from <input id="y0" /> to <input id="y1" />.</p>
        <p>Start time: <input id="t0" />; end time: <input id="t1" />.</p>
        <p>Acceleration ratio: <input id="ra" />; deceleration ratio: <input id="rd" />.</p>
        <p><input type="submit" value="Calculate" onclick="calcBezier();" /></p>
        <p id="results"> </p>
    </body>
</html>
</code>```

答:
General solution

Update: using the geometric interpretation of calculus as the area under a line, I've worked out how to simplify the derivation a lot.

So we're interpolating from y0 at time t0 to y1 at time t1 with acceleration ratio ra and deceleration ratio rd. The definition of the ratios give us the time at which we stop accelerating, ta = t0 + ra * (t1 - t0), and at which we start decelerating, td = t1 - rd * (t1 - t0).

I understand the documentation you quote to mean that it's constant acceleration from t0 to ta, and constant deceleration from td to t1. We'll take the maximum speed reached to be vm.

``` Speed
   |        _____________________________________
vm +       /|                                   |\
   |      /                                       \
   |     /  |                                   |  \
   |    /                                           \
   |   /    |                                   |    \
   |  /                                               \
   | /      |                                   |      \
   |/                                                   \
   +--------+-----------------------------------+--------+---- Time
   t0       ta                                  td       t1```

Then the area of the parallelogram is the distance travelled from t0 to t1, which is y1 - y0. The area of a parallelogram is the product of the height with the average of the parallel sides. So

y1 - y0 = vm * ((t1 - t0) + (td - ta)) / 2

or

vm = 2 * (y1 - y0) / (t1 + td - ta - t0)

Using just the area of the triangles at the end, we can find how far we've travelled when we stop accelerating, ya = y(ta), and when we start decelerating, yd = y(td).

ya = y0 + vm * (ta - t0) / 2

yd = y1 - vm * (t1 - td) / 2

Finally we produce a quadratic Bezier for [t0, ta], a straight line (ta, ya) - (td, yd), and a quadratic Bezier for [td, t1].

For the first Bezier, we have the obvious control points P0 = (t0, y0) and P2 = (ta, ya). To find P1 we use the property that P0-P1 is tangent to the curve and P1-P2 is tangent to the curve (in general, for an order-n curve P0-P1 and P(n-1)-Pn are tangent). So P1 is at the intersection of y=y0 and the straight line of the middle segment. Similarly for the other Bezier: Q0 = (td, yd), Q2 = (t1, y1), and Q1 is at the intersection of y=y1 and the straight line of the middle segment.

Worked example:

No fade in (acceleration ratio = 0), deceleration ratio = 0.5, t0 = 0, t1 = 10 (seconds), y0 = 20, y1 = 400. I think this corresponds to your specific question.

ta = 0 (and we can omit the first quadratic Bezier); td = t1 - 0.5 * (t1 - t0) = 5.

vm = 2 * (y1 - y0) / (t1 + td - ta - t0) = 2 * (400 - 20) / (10 + 5 - 0 - 0) = 2 * 380 / 15 = 152 / 3 ~= 50.67.

Ignore ya because we're skipping that Bezier.

yd = y1 - vm * (t1 - td) / 2 = 400 - 152/3 * (10-5)/2 = 400 - 380/3 = 820/3 ~= 273.3

So the straight line goes from (t=0, y=20) to (t=5, y=273.3). The deceleration Bezier has Q0 = (5, 273.3), Q2 = (10, 400).

To find Q1 we extend the straight line to y=400. The line has equation y - 20 = (t - 0) * (273.3 - 20) / (5 - 0), so t = 5 * (400 - 20) / (273.3 - 20) = 7.5.

So we have straight line (0,20)-(5,273.3) and a quadratic Bezier with control points (5,273.3), (7.5,400) and (10,400).

Translating this into your keyframe

However, there's a slight hitch, which is that Microsoft hasn't deigned to give us quadratic splines. We have to lift the quadratic Q0, Q1, Q2, to the cubic Q0, (Q0 + 2 Q1)  /3, (2 Q1 + Q2) / 3, Q2.

We also have to rescale the control points to 0-1. If we apply that rescaling first, we have (0,0)-(0.5,1)-(1,1). So the cubic is (0,0)-(0.333,0.667)-(0.667,1)-(1,1).

I know splines, but not WPF. I think that the following will do what you want:

```
<DiscreteDoubleKeyFrame KeyTime="0:0:0" Value="20" />
<LinearDoubleKeyFrame KeyTime="0:0:5" Value="273.333" />
<SplineDoubleKeyFrame KeyTime="0:0:10" Value="400" KeySpline="0.333,0.667,0.667,1"/>
```

Universality of the transformation

Rescaling the first Bezier, we map (t0, y0) to (0, 0) and (ta, ya) to (1, 1). Therefore we map (P1.t, P1.y) to ((P1.t - t0) / (ta - t0), (P1.y - y0) / (ya - y0)). But P1 is at the intersection of y = y0 with the straight line of gradient vm through (ta, ya), which therefore has equation (y - ya) = (t - ta) * vm. So P1.y = y0 and P1.t = ta + (y0 - ya) / vm = ta - (ya - y0) / vm. Plugging in our identity ya = y0 + vm * (ta - t0) / 2, we get P1.t = ta - (vm * (ta - t0) / 2) / vm = ta - (ta - t0) / 2 = (ta + t0) / 2.

So rescaling we map P1 to (0.5, 0). Therefore when we lift it to a cubic Bezier, the intermediate control points are always at (1/3, 0) and (2/3, 1/3).

Similarly the deceleration spline always has its scaled intermediate points at (1/3, 2/3) and (2/3, 1).

ContentLicense: CC BY-SA 2.5

Body:
Is there a formula to translate AccelerationRatio or DecelerationRatio to Bezier control points for use in a KeySpline in a SplineDoubleKeyFrame? For example, an "Ease Out" may be DecelerationRatio=0.5, but this doesn't seem equivalent to KeySpline="0.0,0.0 0.5,1.0" or KeySpline="0.5,0 1,0.5".

Would this involve multiple SplineDoubleKeyFrame to achieve DecelerationRatio=0.5? Or is their a particular formula that makes them equivalent in a single frame?

Or is this not to be achieved via a SplineDoubleKeyFrame but a EasingDoubleKeyFrame instead (if so, what is the EasingFunction/EasingMode/Other Attributes)?

Essentially, I'm trying to achieve <DoubleAnimation Storyboard.TargetName="deceleratedRectangle" Storyboard.TargetProperty="(Rectangle.Width)"  DecelerationRatio="0.5" Duration="0:0:10" From="20" To="400" /> with KeyFrames as there will be multiple frames that target the same property path and accelerate/decelerate it.

UPDATE: According to the Microsoft WPF-Silverlight Comparison Whitepaper.pdf on page 7:

The linear interpolation
  can be modified somewhat by adding
  AccelerationRatio and
  DecelerationRatio properties to the
  animation. These attributes
  essentially create three linear
  interpolations for the entire
  animation in order to modify the
  starting and stopping speeds. For
  example, a designer would use these
  attributes to have an object gradually
  pick up speed or stop suddenly.
  Unfortunately, Silverlight does not
  implement these two attributes, but
  the effect can be duplicated using
  keyframe animations with linear interpolation.

So I guess this means it can be done with just 3 key frames, but what the formula is I have no idea.

SOLUTION: For others that may come along that need this, posting the ECMAScript solution crafted by Peter Taylor:

        <title>Acceleration or deceleration with Bezier splines</title>

Interpolate y from <input id="y0" /> to <input id="y1" />.

Start time: <input id="t0" />; end time: <input id="t1" />.

Acceleration ratio: <input id="ra" />; deceleration ratio: <input id="rd" />.

<input type="submit" value="Calculate" onclick="calcBezier();" />

Body:
General solution

Update: using the geometric interpretation of calculus as the area under a line, I've worked out how to simplify the derivation a lot.

So we're interpolating from y0 at time t0 to y1 at time t1 with acceleration ratio ra and deceleration ratio rd. The definition of the ratios give us the time at which we stop accelerating, ta = t0 + ra * (t1 - t0), and at which we start decelerating, td = t1 - rd * (t1 - t0).

I understand the documentation you quote to mean that it's constant acceleration from t0 to ta, and constant deceleration from td to t1. We'll take the maximum speed reached to be vm.

 Speed
   |        _____________________________________
vm +       /|                                   |\
   |      /                                       \
   |     /  |                                   |  \
   |    /                                           \
   |   /    |                                   |    \
   |  /                                               \
   | /      |                                   |      \
   |/                                                   \
   +--------+-----------------------------------+--------+---- Time
   t0       ta                                  td       t1

Then the area of the parallelogram is the distance travelled from t0 to t1, which is y1 - y0. The area of a parallelogram is the product of the height with the average of the parallel sides. So

y1 - y0 = vm * ((t1 - t0) + (td - ta)) / 2

or

vm = 2 * (y1 - y0) / (t1 + td - ta - t0)

Using just the area of the triangles at the end, we can find how far we've travelled when we stop accelerating, ya = y(ta), and when we start decelerating, yd = y(td).

ya = y0 + vm * (ta - t0) / 2

yd = y1 - vm * (t1 - td) / 2

Finally we produce a quadratic Bezier for [t0, ta], a straight line (ta, ya) - (td, yd), and a quadratic Bezier for [td, t1].

For the first Bezier, we have the obvious control points P0 = (t0, y0) and P2 = (ta, ya). To find P1 we use the property that P0-P1 is tangent to the curve and P1-P2 is tangent to the curve (in general, for an order-n curve P0-P1 and P(n-1)-Pn are tangent). So P1 is at the intersection of y=y0 and the straight line of the middle segment. Similarly for the other Bezier: Q0 = (td, yd), Q2 = (t1, y1), and Q1 is at the intersection of y=y1 and the straight line of the middle segment.

Worked example:

No fade in (acceleration ratio = 0), deceleration ratio = 0.5, t0 = 0, t1 = 10 (seconds), y0 = 20, y1 = 400. I think this corresponds to your specific question.

ta = 0 (and we can omit the first quadratic Bezier); td = t1 - 0.5 * (t1 - t0) = 5.

vm = 2 * (y1 - y0) / (t1 + td - ta - t0) = 2 * (400 - 20) / (10 + 5 - 0 - 0) = 2 * 380 / 15 = 152 / 3 ~= 50.67.

Ignore ya because we're skipping that Bezier.

yd = y1 - vm * (t1 - td) / 2 = 400 - 152/3 * (10-5)/2 = 400 - 380/3 = 820/3 ~= 273.3

So the straight line goes from (t=0, y=20) to (t=5, y=273.3). The deceleration Bezier has Q0 = (5, 273.3), Q2 = (10, 400).

To find Q1 we extend the straight line to y=400. The line has equation y - 20 = (t - 0) * (273.3 - 20) / (5 - 0), so t = 5 * (400 - 20) / (273.3 - 20) = 7.5.

So we have straight line (0,20)-(5,273.3) and a quadratic Bezier with control points (5,273.3), (7.5,400) and (10,400).

Translating this into your keyframe

However, there's a slight hitch, which is that Microsoft hasn't deigned to give us quadratic splines. We have to lift the quadratic Q0, Q1, Q2, to the cubic Q0, (Q0 + 2 Q1)  /3, (2 Q1 + Q2) / 3, Q2.

We also have to rescale the control points to 0-1. If we apply that rescaling first, we have (0,0)-(0.5,1)-(1,1). So the cubic is (0,0)-(0.333,0.667)-(0.667,1)-(1,1).

I know splines, but not WPF. I think that the following will do what you want:

<DiscreteDoubleKeyFrame KeyTime="0:0:0" Value="20" />
<LinearDoubleKeyFrame KeyTime="0:0:5" Value="273.333" />
<SplineDoubleKeyFrame KeyTime="0:0:10" Value="400" KeySpline="0.333,0.667,0.667,1"/>

Universality of the transformation

Rescaling the first Bezier, we map (t0, y0) to (0, 0) and (ta, ya) to (1, 1). Therefore we map (P1.t, P1.y) to ((P1.t - t0) / (ta - t0), (P1.y - y0) / (ya - y0)). But P1 is at the intersection of y = y0 with the straight line of gradient vm through (ta, ya), which therefore has equation (y - ya) = (t - ta) * vm. So P1.y = y0 and P1.t = ta + (y0 - ya) / vm = ta - (ya - y0) / vm. Plugging in our identity ya = y0 + vm * (ta - t0) / 2, we get P1.t = ta - (vm * (ta - t0) / 2) / vm = ta - (ta - t0) / 2 = (ta + t0) / 2.

So rescaling we map P1 to (0.5, 0). Therefore when we lift it to a cubic Bezier, the intermediate control points are always at (1/3, 0) and (2/3, 1/3).

Similarly the deceleration spline always has its scaled intermediate points at (1/3, 2/3) and (2/3, 1).


问:
Apache spark text similarity
I am trying the below example in java

Efficient string matching in Apache Spark

This is my code

```<code>public class App {
    public static void main(String[] args) {
        System.out.println("Hello World!");

        System.setProperty("hadoop.home.dir", "D:\\del");

        List<MyRecord> firstRow = new ArrayList<MyRecord>();
        firstRow.add(new App().new MyRecord("1", "Love is blind"));

        List<MyRecord> secondRow = new ArrayList<MyRecord>();
        secondRow.add(new App().new MyRecord("1", "Luv is blind"));

        SparkSession spark = SparkSession.builder().appName("LSHExample").config("spark.master", "local")
                .getOrCreate();

        Dataset firstDataFrame = spark.createDataFrame(firstRow, MyRecord.class);
        Dataset secondDataFrame = spark.createDataFrame(secondRow, MyRecord.class);

        firstDataFrame.show(20, false);
        secondDataFrame.show(20, false);

        RegexTokenizer regexTokenizer = new RegexTokenizer().setInputCol("text").setOutputCol("words")
                .setPattern("\\W");
        NGram ngramTransformer = new NGram().setN(3).setInputCol("words").setOutputCol("ngrams");
        HashingTF hashingTF = new HashingTF().setInputCol("ngrams").setOutputCol("vectors");
        MinHashLSH minHashLSH = new MinHashLSH().setInputCol("vectors").setOutputCol("lsh");

        Pipeline pipeline = new Pipeline()
        .setStages(new PipelineStage[] { regexTokenizer, ngramTransformer, hashingTF, minHashLSH });

        PipelineModel model = pipeline.fit(firstDataFrame);

        Dataset dataset1 = model.transform(firstDataFrame);
        dataset1.show(20,false);

        Dataset dataset2 = model.transform(secondDataFrame);
        dataset2 .show(20,false);

        Transformer[] transformers = model.stages();
        MinHashLSHModel temp = (MinHashLSHModel) transformers[transformers.length - 1];
        temp.approxSimilarityJoin(dataset1, dataset2, 0.01).show(20,false);

    }

    protected class MyRecord {
        private String id;
        private String text;

        private MyRecord(String id, String text) {
            this.id = id;
            this.text = text;
        }

        public String getId() {
            return id;
        }

        public String getText() {
            return text;
        }

    }

}
</code>```

Before invoking the approxSimilarityJoin the two datasets look like below.

Transformed Dataset A

```<code>+---+-------------+-----------------+---------------+-----------------------+----------------+
|id |text         |words            |ngrams         |vectors                |lsh             |
+---+-------------+-----------------+---------------+-----------------------+----------------+
|1  |Love is blind|[love, is, blind]|[love is blind]|(262144,[243005],[1.0])|[[2.02034596E9]]|
+---+-------------+-----------------+---------------+-----------------------+----------------+
</code>```

Transformed Dataset B

```<code>+---+------------+----------------+--------------+----------------------+----------------+
|id |text        |words           |ngrams        |vectors               |lsh             |
+---+------------+----------------+--------------+----------------------+----------------+
|2  |Luv is blind|[luv, is, blind]|[luv is blind]|(262144,[57733],[1.0])|[[7.79808048E8]]|
+---+------------+----------------+--------------+----------------------+----------------+
</code>```

Though the two texts "Love is blind" and "Luv is blind"  are almost similar , I get the below blank output.

```<code>+--------+--------+-------+
|datasetA|datasetB|distCol|
+--------+--------+-------+
+--------+--------+-------+
</code>```

Kindly revert If there is any mistake in the above code .

I tested by giving the same input for both data sets and below is the output. The distCol is zero when both the datasets have same text.

```<code>+--------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------+-------+
|datasetA                                                                                |datasetB                                                                                |distCol|
+--------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------+-------+
|[1,Love is blind,WrappedArray(love, is, blind),WrappedArray(love is blind),(262144,[243005],[1.0]),WrappedArray([2.02034596E9])]|[2,Love is blind,WrappedArray(love, is, blind),WrappedArray(love is blind),(262144,[243005],[1.0]),WrappedArray([2.02034596E9])]|0.0    |
+--------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------+-------+
</code>```

The below example also uses the same concept.

https://databricks.com/blog/2017/05/09/detecting-abuse-scale-locality-sensitive-hashing-uber-engineering.html

I think I am missing some fundamental aspect in this program. Kindly revert.

It worked based upon the suggestions given by user8371915 .

I removed the ngram and increased the numHashTables

```<code>MinHashLSH minHashLSH = new MinHashLSH().setInputCol("features").setOutputCol("hashValues").setNumHashTables(20);
</code>```

Now I am able to relate how this matching works

Below are my two dataset

Dataset A

```<code>+---+-------------+
|id |text         |
+---+-------------+
|1  |Love is blind|
+---+-------------+
</code>```

Dataset B

```<code>+---+-------------------------+
|id |text                     |
+---+-------------------------+
|1  |Love is blind            |
|2  |Luv is blind             |
|3  |Lov is blind             |
|4  |This is totally different|
|5  |God is love              |
|6  |blind love is divine     |
+---+-------------------------+
</code>```

and the final output is below

```<code>+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
|datasetA                                                                                |datasetB                                                                                |distCol|
+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
|[1,Love is blind,WrappedArray(love, is, blind),(262144,[15889,48831,186480],[1.0,1.0,1.0]),WrappedArray([-1.06555007E9], [-1.557513224E9], [-1.590526534E9], [-2.83593282E8], [-1.815588486E9], [-1.411500923E9], [-6.93210471E8], [-8.0411681E7], [-1.713286948E9], [-1.698342316E9], [-9.33829921E8], [-1.240833109E9], [-1.48476096E8], [-1.882820721E9], [-7.50906814E8], [1.99715481E8], [-1.997519365E9], [-1.380314819E9], [-5.92484283E8], [-1.869738298E9])]|[1,Love is blind,WrappedArray(love, is, blind),(262144,[15889,48831,186480],[1.0,1.0,1.0]),WrappedArray([-1.06555007E9], [-1.557513224E9], [-1.590526534E9], [-2.83593282E8], [-1.815588486E9], [-1.411500923E9], [-6.93210471E8], [-8.0411681E7], [-1.713286948E9], [-1.698342316E9], [-9.33829921E8], [-1.240833109E9], [-1.48476096E8], [-1.882820721E9], [-7.50906814E8], [1.99715481E8], [-1.997519365E9], [-1.380314819E9], [-5.92484283E8], [-1.869738298E9])]                            |0.0    |
|[1,Love is blind,WrappedArray(love, is, blind),(262144,[15889,48831,186480],[1.0,1.0,1.0]),WrappedArray([-1.06555007E9], [-1.557513224E9], [-1.590526534E9], [-2.83593282E8], [-1.815588486E9], [-1.411500923E9], [-6.93210471E8], [-8.0411681E7], [-1.713286948E9], [-1.698342316E9], [-9.33829921E8], [-1.240833109E9], [-1.48476096E8], [-1.882820721E9], [-7.50906814E8], [1.99715481E8], [-1.997519365E9], [-1.380314819E9], [-5.92484283E8], [-1.869738298E9])]|[2,Luv is blind,WrappedArray(luv, is, blind),(262144,[15889,48831,84987],[1.0,1.0,1.0]),WrappedArray([-2.021501434E9], [-1.557513224E9], [-1.590526534E9], [-2.83593282E8], [-1.815588486E9], [-6.70773282E8], [-6.93210471E8], [-1.205754635E9], [-1.713286948E9], [-1.698342316E9], [-9.33829921E8], [-1.240833109E9], [4.46435174E8], [-1.882820721E9], [-7.50906814E8], [1.99715481E8], [-1.036250081E9], [-1.380314819E9], [-5.92484283E8], [-1.869738298E9])]                              |0.5    |
|[1,Love is blind,WrappedArray(love, is, blind),(262144,[15889,48831,186480],[1.0,1.0,1.0]),WrappedArray([-1.06555007E9], [-1.557513224E9], [-1.590526534E9], [-2.83593282E8], [-1.815588486E9], [-1.411500923E9], [-6.93210471E8], [-8.0411681E7], [-1.713286948E9], [-1.698342316E9], [-9.33829921E8], [-1.240833109E9], [-1.48476096E8], [-1.882820721E9], [-7.50906814E8], [1.99715481E8], [-1.997519365E9], [-1.380314819E9], [-5.92484283E8], [-1.869738298E9])]|[5,God is love,WrappedArray(god, is, love),(262144,[15889,57304,186480],[1.0,1.0,1.0]),WrappedArray([-7.6253133E7], [-2.6669178E7], [-1.590526534E9], [-2.83593282E8], [-1.060055906E9], [-1.411500923E9], [-9.83191394E8], [-8.0411681E7], [-1.04032919E9], [-1.373403353E9], [-5.63413619E8], [-1.240833109E9], [-1.48476096E8], [-1.7390215E9], [-1.745820849E9], [8.1559665E7], [-1.997519365E9], [-1.635066748E9], [6.38995945E8], [-1.59718287E9])]                                        |0.5    |
|[1,Love is blind,WrappedArray(love, is, blind),(262144,[15889,48831,186480],[1.0,1.0,1.0]),WrappedArray([-1.06555007E9], [-1.557513224E9], [-1.590526534E9], [-2.83593282E8], [-1.815588486E9], [-1.411500923E9], [-6.93210471E8], [-8.0411681E7], [-1.713286948E9], [-1.698342316E9], [-9.33829921E8], [-1.240833109E9], [-1.48476096E8], [-1.882820721E9], [-7.50906814E8], [1.99715481E8], [-1.997519365E9], [-1.380314819E9], [-5.92484283E8], [-1.869738298E9])]|[6,blind love is divine,WrappedArray(blind, love, is, divine),(262144,[15889,25596,48831,186480],[1.0,1.0,1.0,1.0]),WrappedArray([-1.06555007E9], [-1.557513224E9], [-1.590526534E9], [-1.627956291E9], [-1.815588486E9], [-1.411500923E9], [-6.93210471E8], [-8.0411681E7], [-1.713286948E9], [-1.698342316E9], [-9.33829921E8], [-1.240833109E9], [-1.93451596E9], [-1.882820721E9], [-7.50906814E8], [-1.152091375E9], [-1.997519365E9], [-1.380314819E9], [-8.50494401E8], [-1.869738298E9])]|0.25   |
|[1,Love is blind,WrappedArray(love, is, blind),(262144,[15889,48831,186480],[1.0,1.0,1.0]),WrappedArray([-1.06555007E9], [-1.557513224E9], [-1.590526534E9], [-2.83593282E8], [-1.815588486E9], [-1.411500923E9], [-6.93210471E8], [-8.0411681E7], [-1.713286948E9], [-1.698342316E9], [-9.33829921E8], [-1.240833109E9], [-1.48476096E8], [-1.882820721E9], [-7.50906814E8], [1.99715481E8], [-1.997519365E9], [-1.380314819E9], [-5.92484283E8], [-1.869738298E9])]|[3,Lov is blind,WrappedArray(lov, is, blind),(262144,[15889,48831,81946],[1.0,1.0,1.0]),WrappedArray([-1.06555007E9], [-1.557513224E9], [-1.590526534E9], [-2.83593282E8], [-1.88316392E9], [-1.776275893E9], [-6.93210471E8], [-1.39927757E8], [-1.713286948E9], [-1.698342316E9], [-1.164990332E9], [-1.240833109E9], [-1.519529732E9], [-1.882820721E9], [-7.50906814E8], [1.99715481E8], [-1.036250081E9], [-1.380314819E9], [-1.808919173E9], [-1.869738298E9])]                            |0.5    |
+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
</code>```

答:
I have a few suggestions:

If you use NGrams consider more granular tokenizer. The goal here is to correct for misspellings:

```<code>RegexTokenizer regexTokenizer = new RegexTokenizer()
   .setInputCol("text")
   .setOutputCol("words")
   .setPattern("");

NGram ngramTransformer = new NGram()
  .setN(3)
  .setInputCol("words")
  .setOutputCol("ngrams");
</code>```

With your current code (NGram(3) and sentence three words split by \W) three you'll get only one token and no similarity.

Increase number of hash tables (setNumHashTables) for LSH. Default value (1) is to small for anything but simple examples.

Normalize Unicode strings. There is a Scala Transformer in What is the best way to remove accents with apache spark dataframes in PySpark?

Remove capitalization. You can use SQLTransformer:

```<code>import org.apache.spark.ml.feature.SQLTransformer

val sqlTrans = new SQLTransformer().setStatement(
   "SELECT *, lower(normalized_text) FROM __THIS__")
</code>```

Title: Apache spark text similarity

Body:
I am trying the below example in java

Efficient string matching in Apache Spark

This is my code

public class App {
    public static void main(String[] args) {
        System.out.println("Hello World!");

        System.setProperty("hadoop.home.dir", "D:\\del");

        List<MyRecord> firstRow = new ArrayList<MyRecord>();
        firstRow.add(new App().new MyRecord("1", "Love is blind"));

        List<MyRecord> secondRow = new ArrayList<MyRecord>();
        secondRow.add(new App().new MyRecord("1", "Luv is blind"));

        SparkSession spark = SparkSession.builder().appName("LSHExample").config("spark.master", "local")
                .getOrCreate();

        Dataset firstDataFrame = spark.createDataFrame(firstRow, MyRecord.class);
        Dataset secondDataFrame = spark.createDataFrame(secondRow, MyRecord.class);

        firstDataFrame.show(20, false);
        secondDataFrame.show(20, false);

        RegexTokenizer regexTokenizer = new RegexTokenizer().setInputCol("text").setOutputCol("words")
                .setPattern("\\W");
        NGram ngramTransformer = new NGram().setN(3).setInputCol("words").setOutputCol("ngrams");
        HashingTF hashingTF = new HashingTF().setInputCol("ngrams").setOutputCol("vectors");
        MinHashLSH minHashLSH = new MinHashLSH().setInputCol("vectors").setOutputCol("lsh");

        Pipeline pipeline = new Pipeline()
        .setStages(new PipelineStage[] { regexTokenizer, ngramTransformer, hashingTF, minHashLSH });

        PipelineModel model = pipeline.fit(firstDataFrame);

        Dataset dataset1 = model.transform(firstDataFrame);
        dataset1.show(20,false);

        Dataset dataset2 = model.transform(secondDataFrame);
        dataset2 .show(20,false);

        Transformer[] transformers = model.stages();
        MinHashLSHModel temp = (MinHashLSHModel) transformers[transformers.length - 1];
        temp.approxSimilarityJoin(dataset1, dataset2, 0.01).show(20,false);

    }

    protected class MyRecord {
        private String id;
        private String text;

        private MyRecord(String id, String text) {
            this.id = id;
            this.text = text;
        }

        public String getId() {
            return id;
        }

        public String getText() {
            return text;
        }

    }

}

Before invoking the approxSimilarityJoin the two datasets look like below.

Transformed Dataset A

+---+-------------+-----------------+---------------+-----------------------+----------------+
|id |text         |words            |ngrams         |vectors                |lsh             |
+---+-------------+-----------------+---------------+-----------------------+----------------+
|1  |Love is blind|[love, is, blind]|[love is blind]|(262144,[243005],[1.0])|[[2.02034596E9]]|
+---+-------------+-----------------+---------------+-----------------------+----------------+

Transformed Dataset B

+---+------------+----------------+--------------+----------------------+----------------+
|id |text        |words           |ngrams        |vectors               |lsh             |
+---+------------+----------------+--------------+----------------------+----------------+
|2  |Luv is blind|[luv, is, blind]|[luv is blind]|(262144,[57733],[1.0])|[[7.79808048E8]]|
+---+------------+----------------+--------------+----------------------+----------------+

Though the two texts "Love is blind" and "Luv is blind"  are almost similar , I get the below blank output.

+--------+--------+-------+
|datasetA|datasetB|distCol|
+--------+--------+-------+
+--------+--------+-------+

Kindly revert If there is any mistake in the above code .

I tested by giving the same input for both data sets and below is the output. The distCol is zero when both the datasets have same text.

+--------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------+-------+
|datasetA                                                                                |datasetB                                                                                |distCol|
+--------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------+-------+
|[1,Love is blind,WrappedArray(love, is, blind),WrappedArray(love is blind),(262144,[243005],[1.0]),WrappedArray([2.02034596E9])]|[2,Love is blind,WrappedArray(love, is, blind),WrappedArray(love is blind),(262144,[243005],[1.0]),WrappedArray([2.02034596E9])]|0.0    |
+--------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------------------+-------+

The below example also uses the same concept.

https://databricks.com/blog/2017/05/09/detecting-abuse-scale-locality-sensitive-hashing-uber-engineering.html

I think I am missing some fundamental aspect in this program. Kindly revert.

It worked based upon the suggestions given by user8371915 .

I removed the ngram and increased the numHashTables

MinHashLSH minHashLSH = new MinHashLSH().setInputCol("features").setOutputCol("hashValues").setNumHashTables(20);

Now I am able to relate how this matching works

Below are my two dataset

Dataset A

+---+-------------+
|id |text         |
+---+-------------+
|1  |Love is blind|
+---+-------------+

Dataset B

+---+-------------------------+
|id |text                     |
+---+-------------------------+
|1  |Love is blind            |
|2  |Luv is blind             |
|3  |Lov is blind             |
|4  |This is totally different|
|5  |God is love              |
|6  |blind love is divine     |
+---+-------------------------+

and the final output is below

+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
|datasetA                                                                                |datasetB                                                                                |distCol|
+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
|[1,Love is blind,WrappedArray(love, is, blind),(262144,[15889,48831,186480],[1.0,1.0,1.0]),WrappedArray([-1.06555007E9], [-1.557513224E9], [-1.590526534E9], [-2.83593282E8], [-1.815588486E9], [-1.411500923E9], [-6.93210471E8], [-8.0411681E7], [-1.713286948E9], [-1.698342316E9], [-9.33829921E8], [-1.240833109E9], [-1.48476096E8], [-1.882820721E9], [-7.50906814E8], [1.99715481E8], [-1.997519365E9], [-1.380314819E9], [-5.92484283E8], [-1.869738298E9])]|[1,Love is blind,WrappedArray(love, is, blind),(262144,[15889,48831,186480],[1.0,1.0,1.0]),WrappedArray([-1.06555007E9], [-1.557513224E9], [-1.590526534E9], [-2.83593282E8], [-1.815588486E9], [-1.411500923E9], [-6.93210471E8], [-8.0411681E7], [-1.713286948E9], [-1.698342316E9], [-9.33829921E8], [-1.240833109E9], [-1.48476096E8], [-1.882820721E9], [-7.50906814E8], [1.99715481E8], [-1.997519365E9], [-1.380314819E9], [-5.92484283E8], [-1.869738298E9])]                            |0.0    |
|[1,Love is blind,WrappedArray(love, is, blind),(262144,[15889,48831,186480],[1.0,1.0,1.0]),WrappedArray([-1.06555007E9], [-1.557513224E9], [-1.590526534E9], [-2.83593282E8], [-1.815588486E9], [-1.411500923E9], [-6.93210471E8], [-8.0411681E7], [-1.713286948E9], [-1.698342316E9], [-9.33829921E8], [-1.240833109E9], [-1.48476096E8], [-1.882820721E9], [-7.50906814E8], [1.99715481E8], [-1.997519365E9], [-1.380314819E9], [-5.92484283E8], [-1.869738298E9])]|[2,Luv is blind,WrappedArray(luv, is, blind),(262144,[15889,48831,84987],[1.0,1.0,1.0]),WrappedArray([-2.021501434E9], [-1.557513224E9], [-1.590526534E9], [-2.83593282E8], [-1.815588486E9], [-6.70773282E8], [-6.93210471E8], [-1.205754635E9], [-1.713286948E9], [-1.698342316E9], [-9.33829921E8], [-1.240833109E9], [4.46435174E8], [-1.882820721E9], [-7.50906814E8], [1.99715481E8], [-1.036250081E9], [-1.380314819E9], [-5.92484283E8], [-1.869738298E9])]                              |0.5    |
|[1,Love is blind,WrappedArray(love, is, blind),(262144,[15889,48831,186480],[1.0,1.0,1.0]),WrappedArray([-1.06555007E9], [-1.557513224E9], [-1.590526534E9], [-2.83593282E8], [-1.815588486E9], [-1.411500923E9], [-6.93210471E8], [-8.0411681E7], [-1.713286948E9], [-1.698342316E9], [-9.33829921E8], [-1.240833109E9], [-1.48476096E8], [-1.882820721E9], [-7.50906814E8], [1.99715481E8], [-1.997519365E9], [-1.380314819E9], [-5.92484283E8], [-1.869738298E9])]|[5,God is love,WrappedArray(god, is, love),(262144,[15889,57304,186480],[1.0,1.0,1.0]),WrappedArray([-7.6253133E7], [-2.6669178E7], [-1.590526534E9], [-2.83593282E8], [-1.060055906E9], [-1.411500923E9], [-9.83191394E8], [-8.0411681E7], [-1.04032919E9], [-1.373403353E9], [-5.63413619E8], [-1.240833109E9], [-1.48476096E8], [-1.7390215E9], [-1.745820849E9], [8.1559665E7], [-1.997519365E9], [-1.635066748E9], [6.38995945E8], [-1.59718287E9])]                                        |0.5    |
|[1,Love is blind,WrappedArray(love, is, blind),(262144,[15889,48831,186480],[1.0,1.0,1.0]),WrappedArray([-1.06555007E9], [-1.557513224E9], [-1.590526534E9], [-2.83593282E8], [-1.815588486E9], [-1.411500923E9], [-6.93210471E8], [-8.0411681E7], [-1.713286948E9], [-1.698342316E9], [-9.33829921E8], [-1.240833109E9], [-1.48476096E8], [-1.882820721E9], [-7.50906814E8], [1.99715481E8], [-1.997519365E9], [-1.380314819E9], [-5.92484283E8], [-1.869738298E9])]|[6,blind love is divine,WrappedArray(blind, love, is, divine),(262144,[15889,25596,48831,186480],[1.0,1.0,1.0,1.0]),WrappedArray([-1.06555007E9], [-1.557513224E9], [-1.590526534E9], [-1.627956291E9], [-1.815588486E9], [-1.411500923E9], [-6.93210471E8], [-8.0411681E7], [-1.713286948E9], [-1.698342316E9], [-9.33829921E8], [-1.240833109E9], [-1.93451596E9], [-1.882820721E9], [-7.50906814E8], [-1.152091375E9], [-1.997519365E9], [-1.380314819E9], [-8.50494401E8], [-1.869738298E9])]|0.25   |
|[1,Love is blind,WrappedArray(love, is, blind),(262144,[15889,48831,186480],[1.0,1.0,1.0]),WrappedArray([-1.06555007E9], [-1.557513224E9], [-1.590526534E9], [-2.83593282E8], [-1.815588486E9], [-1.411500923E9], [-6.93210471E8], [-8.0411681E7], [-1.713286948E9], [-1.698342316E9], [-9.33829921E8], [-1.240833109E9], [-1.48476096E8], [-1.882820721E9], [-7.50906814E8], [1.99715481E8], [-1.997519365E9], [-1.380314819E9], [-5.92484283E8], [-1.869738298E9])]|[3,Lov is blind,WrappedArray(lov, is, blind),(262144,[15889,48831,81946],[1.0,1.0,1.0]),WrappedArray([-1.06555007E9], [-1.557513224E9], [-1.590526534E9], [-2.83593282E8], [-1.88316392E9], [-1.776275893E9], [-6.93210471E8], [-1.39927757E8], [-1.713286948E9], [-1.698342316E9], [-1.164990332E9], [-1.240833109E9], [-1.519529732E9], [-1.882820721E9], [-7.50906814E8], [1.99715481E8], [-1.036250081E9], [-1.380314819E9], [-1.808919173E9], [-1.869738298E9])]                            |0.5    |
+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+

Body:
I have a few suggestions:

If you use NGrams consider more granular tokenizer. The goal here is to correct for misspellings:

RegexTokenizer regexTokenizer = new RegexTokenizer()
   .setInputCol("text")
   .setOutputCol("words")
   .setPattern("");

NGram ngramTransformer = new NGram()
  .setN(3)
  .setInputCol("words")
  .setOutputCol("ngrams");

With your current code (NGram(3) and sentence three words split by \W) three you'll get only one token and no similarity.

Increase number of hash tables (setNumHashTables) for LSH. Default value (1) is to small for anything but simple examples.

Normalize Unicode strings. There is a Scala Transformer in What is the best way to remove accents with apache spark dataframes in PySpark?

Remove capitalization. You can use SQLTransformer:

import org.apache.spark.ml.feature.SQLTransformer

val sqlTrans = new SQLTransformer().setStatement(
   "SELECT *, lower(normalized_text) FROM __THIS__")


问:
is a domain necessary to https-encrypt my ec2 server?
This question is based on this stackoverflow question, on how to further secure my connection to the public.

My end goal is to have a react native app making request to my aws EC2 server. I obviously want the user login credentials to make a safe travel from the app to my server. For now im sending the credentials with http Authorization headers "basic username:password". This can be intercepted as i understand.

My AWS EC2 server can be reached with an elastic IP i've created. I'm using self signed certification which is not considerd "secure" by browsers. To get a secure certficiation i need to connect it with a domain, not an ip.

It seems illogical for me to expose my backend server to the public even more by getting a domain. I am fairly certain I've misunderstood the whole thing. All I want is to make safe requests to my server.

EDIT: My requests gets blocked, like the question i linked to, i need to approve the certification in the browser, after that i can access. I cant do this in every devide the app will be installed in.

Info about my backend:

```<code>AWS EC2 Micro
Windows Server 2016
Mulesoft 3.9.0CE listening to 0.0.0.0(all)
</code>```

The keystore has a SAN included of my ec2:

```<code>keytool -genkeypair -keystore keystore.jks   -dname "CN=localhost,
OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown"  -keypass password
-storepass password  -keyalg RSA  -sigalg SHA1withRSA  -keysize 2048  -alias
mule  -ext SAN=DNS:publicAWS-DNS,IP:elasticIP -validity 9999
</code>```

Is my traffic already encrypted but just not considered "safe" by browsers? Is this ok?

Do i need to specify the IP with SANs when creating jks?

Thank you

答:
There are multiple levels of security you need to implement to secure you application.

Encrypt the communication from browser client to the ec2 instance you need to use SSL Certificate Signed by a Certificate Authority (You can get free certificates from Amazon) to avoid man in the middle attacks.

Implement authentication (Using Username and Passwords) for access control(Who can access your system).

Implement authorization (Who can do what).

Note: To attach free SSL certificates issued by Amazon Certificate Authority you need to use a Application Load Balancer(ALB) where the certificate attached to the ALB and then connect the ALB to the EC2 instance.

Is domain necessary for the backend?

It necessary though its not mandatory, since if you use a self-signed certificate for the IP address of the EC2 instance, browsers will request to proceed with caution.

Body:
This question is based on this stackoverflow question, on how to further secure my connection to the public.

My end goal is to have a react native app making request to my aws EC2 server. I obviously want the user login credentials to make a safe travel from the app to my server. For now im sending the credentials with http Authorization headers "basic username:password". This can be intercepted as i understand.

My AWS EC2 server can be reached with an elastic IP i've created. I'm using self signed certification which is not considerd "secure" by browsers. To get a secure certficiation i need to connect it with a domain, not an ip.

It seems illogical for me to expose my backend server to the public even more by getting a domain. I am fairly certain I've misunderstood the whole thing. All I want is to make safe requests to my server.

EDIT: My requests gets blocked, like the question i linked to, i need to approve the certification in the browser, after that i can access. I cant do this in every devide the app will be installed in.

Info about my backend:

AWS EC2 Micro
Windows Server 2016
Mulesoft 3.9.0CE listening to 0.0.0.0(all)

The keystore has a SAN included of my ec2:

keytool -genkeypair -keystore keystore.jks   -dname "CN=localhost,
OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown"  -keypass password
-storepass password  -keyalg RSA  -sigalg SHA1withRSA  -keysize 2048  -alias
mule  -ext SAN=DNS:publicAWS-DNS,IP:elasticIP -validity 9999

Is my traffic already encrypted but just not considered "safe" by browsers? Is this ok?

Do i need to specify the IP with SANs when creating jks?

Thank you


问:
Getting "Sorry, I didn't get any response." message when I tried Hand-off feature
When I tried Multi-surface conversations (Hand-off from Google Home to Android Google Assistant), I'm getting "Sorry, I didn't get any response."
I'm using Action SDK and locale is "ja".

Here is my response:

```<code>{
    "conversationToken": "(token)",
    "expectUserResponse": true,
    "isInSandbox": true,
    "expectedInputs": [
        {
            "possibleIntents": [
                {
                    "intent": "actions.intent.NEW_SURFACE",
                    "inputValueData": {
                        "@type": "type.googleapis.com/google.actions.v2.NewSurfaceValueSpec",
                        "context": "Sure, I have some sample images for you.",
                        "notificationTitle": "Sample Images",
                        "capabilities": [
                            "actions.capability.SCREEN_OUTPUT"
                        ]
                    }
                }
            ],
            "inputPrompt": {
                "richInitialPrompt": {
                    "items": {
                        "simpleResponse": {
                            "textToSpeech": "PLACEHOLDER_FOR_NEW_SURFACE"
                        }
                    }
                }
            }
        }
    ]
}
</code>```

Does anyone know why?

答:
It seems to be available only in english but i find no clear statement about this on any documentation.

I tried the exact same code in english and in french, it works in english, not in french.

Body:
When I tried Multi-surface conversations (Hand-off from Google Home to Android Google Assistant), I'm getting "Sorry, I didn't get any response."
I'm using Action SDK and locale is "ja".

Here is my response:

{
    "conversationToken": "(token)",
    "expectUserResponse": true,
    "isInSandbox": true,
    "expectedInputs": [
        {
            "possibleIntents": [
                {
                    "intent": "actions.intent.NEW_SURFACE",
                    "inputValueData": {
                        "@type": "type.googleapis.com/google.actions.v2.NewSurfaceValueSpec",
                        "context": "Sure, I have some sample images for you.",
                        "notificationTitle": "Sample Images",
                        "capabilities": [
                            "actions.capability.SCREEN_OUTPUT"
                        ]
                    }
                }
            ],
            "inputPrompt": {
                "richInitialPrompt": {
                    "items": {
                        "simpleResponse": {
                            "textToSpeech": "PLACEHOLDER_FOR_NEW_SURFACE"
                        }
                    }
                }
            }
        }
    ]
}

Does anyone know why?


问:
How to introduce new subelement node in an xml file using python
I am new to Python programming .
I have a xml file in which one snippet is as below .

```<code><relationship name="a_to_b">
  <containment>
    <parent>
      <hasClass name="a" />
    </parent>
    <child>
      <hasClass name="b" />
    </child>
  </containment>
</relationship>
</code>```

Now I have to update this section with the below content .

```<code><relationship name="a_to_b">
  <containment>
    <parent>
      <hasClass name="a">
         <mimName>top</mimName>
       </hasClass>
    </parent>
    <child>
      <hasClass name="b">
        <mimName>top</mimName>
      </hasClass>
    </child>
  </containment>
</relationship>
</code>```

I am using ElmentTree module .
How can I achieve this .
Python version 2.6 .

I am using below code .

```<code>tree = ET.ElementTree(file=xml) ;
root=tree.getroot() ;
print("Root tag of xml : "+root.tag) ;
#child_of_root=root;
#print("Root tag attribute of xml : "+root.attrib) ;

def fun(root):
   #if root.tag is not 'relationship':
      for child_of_root in root :
          #print("Tag : "+child_of_root.tag) ;
          attribut=child_of_root.attrib ;
          #print "Value : %s" %  attribut.get('name')
          if (child_of_root.tag == 'hasClass' and attribut.get('name') == 'MeContext') or (child_of_root.tag == 'hasClass' and attribut.get('name') == 'ManagedElement') :
           print(child_of_root.tag,attribut.get('name')) ;
           new_data = ET.SubElement(child_of_root, 'mimName');
           new_data.text = 'Top'
       fun(child_of_root)

fun(root);
</code>```

答:
Use xml.etree.ElementTree.SubElement to add tags within another tag. Copying from Python.org ->

```<code>>>> a = ET.Element('a')
>>> b = ET.SubElement(a, 'b')
>>> c = ET.SubElement(a, 'c')
>>> d = ET.SubElement(c, 'd')
>>> ET.dump(a)
<a><b /><c><d /></c></a>
</code>```

Body:
I am new to Python programming .
I have a xml file in which one snippet is as below .

<relationship name="a_to_b">
  <containment>
    <parent>
      <hasClass name="a" />
    </parent>
    <child>
      <hasClass name="b" />
    </child>
  </containment>
</relationship>

Now I have to update this section with the below content .

<relationship name="a_to_b">
  <containment>
    <parent>
      <hasClass name="a">
         <mimName>top</mimName>
       </hasClass>
    </parent>
    <child>
      <hasClass name="b">
        <mimName>top</mimName>
      </hasClass>
    </child>
  </containment>
</relationship>

I am using ElmentTree module .
How can I achieve this .
Python version 2.6 .

I am using below code .

tree = ET.ElementTree(file=xml) ;
root=tree.getroot() ;
print("Root tag of xml : "+root.tag) ;
#child_of_root=root;
#print("Root tag attribute of xml : "+root.attrib) ;

def fun(root):
   #if root.tag is not 'relationship':
      for child_of_root in root :
          #print("Tag : "+child_of_root.tag) ;
          attribut=child_of_root.attrib ;
          #print "Value : %s" %  attribut.get('name')
          if (child_of_root.tag == 'hasClass' and attribut.get('name') == 'MeContext') or (child_of_root.tag == 'hasClass' and attribut.get('name') == 'ManagedElement') :
           print(child_of_root.tag,attribut.get('name')) ;
           new_data = ET.SubElement(child_of_root, 'mimName');
           new_data.text = 'Top'
       fun(child_of_root)

fun(root);

Body:
Use xml.etree.ElementTree.SubElement to add tags within another tag. Copying from Python.org ->

>>> a = ET.Element('a')
>>> b = ET.SubElement(a, 'b')
>>> c = ET.SubElement(a, 'c')
>>> d = ET.SubElement(c, 'd')
>>> ET.dump(a)
<a><b /><c><d /></c></a>


问:
How to upgrade to latest version of java JDK using homebrew cask?
I have been following these instructions to install the latest java jdk:

```<code>www.lonecpluspluscoder.com/2017/04/27/installing-java-8-jdk-os-x-using-homebrew/

brew cask install java
</code>```

This works great, but when a new version comes out, how do I make sure I can upgrade to that version and ensure that old versions of the jdk are not sitting around on my system?

答:
```<code>brew cask reinstall java
</code>```

This command will uninstall old version of jdk and install the latest version

Body:
I have been following these instructions to install the latest java jdk:

www.lonecpluspluscoder.com/2017/04/27/installing-java-8-jdk-os-x-using-homebrew/

brew cask install java

This works great, but when a new version comes out, how do I make sure I can upgrade to that version and ensure that old versions of the jdk are not sitting around on my system?

Body:
brew cask reinstall java

This command will uninstall old version of jdk and install the latest version


答:
```<code>boolean allFive = true;
for ( int i = 0; i < squareData.length; ++i ) {
  if ( 5 != squareData[i] ) {
    allFive = false;
    break;
  }
}
System.out.println(
  allFive ? "All entries are five." : "At least one entry is not five."
);
</code>```

Title: how to minimise a long && statement - Java

Body:
I would like to check if all of the items in array squareData[] is 5.

I could just do this:

if(squareData[0] == 5 && squareData[1] == 5 && ...){...}

But it seems rather inefficient.

Is there a way to minimise this into a for loop of some kind?

Note that the size of squareData[] is 9 items

Thanks!


问:
C++ containers' iterators
This question may sounds lame, but I haven't found clear answer. Can I assume, that iterator returned by map's find() method will this points at the same data even if I'll add (or remove) other elements to the same map? It's unclear for me if map's iterator points at position in map or at specific data...

答:
You can keep using the same iterator after insert or erase operations. The standard says (C++03 standard, Section 23.1.2, paragraph 8):

The insert members shall not affect the validity of iterators and references to the container, and the erase
  members shall invalidate only iterators and references to the erased elements.

This is true for all associative containers (map, set, multimap, multiset).

Title: C++ containers' iterators


问:
How to change Cpanel Login page link?
How can I change the link of my cpanel login page, like my login page opens when I type : www.mywebsitename.com/cpanel which I think is very insecure now as my visitors are growing. Top website don't follow such practice if you try /cpanel in their link, it redirects you to 404 Page. Any help?</p>

答:
Changing/removing default cPanel URLs.

For the /whm and /cpanel urls, remove/change these lines or similar matched lines located on the /usr/local/apache/conf/httpd.conf file:

ScriptAliasMatch ^/?cpanel/?$ /usr/local/cpanel/cgi-sys/redirect.cgi
 ScriptAliasMatch ^/?webmail/?$ /usr/local/cpanel/cgi-sys/wredirect.cgi
 ScriptAliasMatch ^/?whm/?$ /usr/local/cpanel/cgi-sys/whmredirect.cgi
Then run the following commands for the changes to take effect.

/usr/local/cpanel/bin/apache_conf_distiller --update
 /scripts/rebuildhttpdconf
 /etc/init.d/httpd restart

Title: How to change Cpanel Login page link?


问:
How to print to the screen - "console.log is not a function"
I have tried numerous ways...what am I doing wrong??? I am determined to learn and really understand this.</p>

```<code>//On line 2, declare a variable myName and give it your name.
var myName = "Jeanne";
//On line 4, use console.log to print out the myName variable.
console.log ("Jeanne");
//On line 7, change the value of myName to be just the first 2 letters of your name.
myName.substring(0, 2);
//On line 9, use console.log to print out the myName variable;
console.log("Jeanne");
</code>```

答:
Presumably you assigned something else to console.log, something that wasn't a function console.log = 5 console.log() </p>

<p>// obviously not referring to a function any more restart your environment. ie. refresh the page</p>

Body:
I have tried numerous ways...what am I doing wrong??? I am determined to learn and really understand this.

//On line 2, declare a variable myName and give it your name.
var myName = "Jeanne";
//On line 4, use console.log to print out the myName variable.
console.log ("Jeanne");
//On line 7, change the value of myName to be just the first 2 letters of your name.
myName.substring(0, 2);
//On line 9, use console.log to print out the myName variable;
console.log("Jeanne");

Body:
Presumably you assigned something else to console.log, something that wasn't a function console.log = 5 console.log()

// obviously not referring to a function any more restart your environment. ie. refresh the page


问:
matplotlib how to make text to have the same length visually after filling space
I am struggling to make the text in matplotlib to have the same visual length after filling space. It always doesn't work for me.

Here is what I have tried,

```<code>from matplotlib import pyplot as plt

fig = plt.figure()
plt.text(0,1,'how are you', bbox=dict(facecolor='red', alpha=0.5))
plt.text(0,0,'how'.ljust(len('how are you'), bbox=dict(facecolor='red', alpha=0.5))
plt.show()
</code>```

And ideas?

Thanks!

答:
ljust appends as many spaces to the text as you specify. However with normal fonts a space is smaller than most other letters. Compare:

The lower text is a written in a so called monospace font, where each letter (including space) has the same space - hence the name.

You would need to use such a font to make your program work in the intended way:

```<code>from matplotlib import pyplot as plt
plt.rcParams['font.family'] = 'monospace'

fig = plt.figure()
plt.text(0,1,'how are you', bbox=dict(facecolor='red', alpha=0.5))
plt.text(0,0,'how'.ljust(len('how are you')), bbox=dict(facecolor='red', alpha=0.5))
plt.show()
</code>```

If this is not an option, you may place a rectangle behind the text of which you set the width to your desire, see this question Matplotlib: how to specify width of x-label bounding box

Body:
I am struggling to make the text in matplotlib to have the same visual length after filling space. It always doesn't work for me.

Here is what I have tried,

from matplotlib import pyplot as plt

fig = plt.figure()
plt.text(0,1,'how are you', bbox=dict(facecolor='red', alpha=0.5))
plt.text(0,0,'how'.ljust(len('how are you'), bbox=dict(facecolor='red', alpha=0.5))
plt.show()

And ideas?

Thanks!

Body:
ljust appends as many spaces to the text as you specify. However with normal fonts a space is smaller than most other letters. Compare:

The lower text is a written in a so called monospace font, where each letter (including space) has the same space - hence the name.

You would need to use such a font to make your program work in the intended way:

from matplotlib import pyplot as plt
plt.rcParams['font.family'] = 'monospace'

fig = plt.figure()
plt.text(0,1,'how are you', bbox=dict(facecolor='red', alpha=0.5))
plt.text(0,0,'how'.ljust(len('how are you')), bbox=dict(facecolor='red', alpha=0.5))
plt.show()

If this is not an option, you may place a rectangle behind the text of which you set the width to your desire, see this question Matplotlib: how to specify width of x-label bounding box


答:
I hope I got your question right.

I tested your example in a WPF project, and I created a similar effect using DoubleAnimationUsingKeyFrames and SplineDoubleKeyFrame. Here is what I did in a Storyboard (this is for deceleration):

```<code><DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)" Storyboard.TargetName="rectangle">
    <SplineDoubleKeyFrame KeyTime="0" Value="1"/>
    <SplineDoubleKeyFrame KeyTime="0:0:3" Value="3.45" KeySpline="0,0.52,0.51,1"/>
</DoubleAnimationUsingKeyFrames>
</code>```

The trick is about setting the Bezier for the SplineDoubleKeyFrame. If you want a smooth acceleration/deceleration, try using a Bezier closer to a linear form.

In addition: the Acceleration/DecelerationRatio is for a whole animation, but the KeySpline is valid for only a KeyFrame. So consider this, if you have an animation consisting of multiple KeyFrames.

Title: Acceleration/Deceleration Ratio equivalent with KeyFrame

Body:
I hope I got your question right.

I tested your example in a WPF project, and I created a similar effect using DoubleAnimationUsingKeyFrames and SplineDoubleKeyFrame. Here is what I did in a Storyboard (this is for deceleration):

<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)" Storyboard.TargetName="rectangle">
    <SplineDoubleKeyFrame KeyTime="0" Value="1"/>
    <SplineDoubleKeyFrame KeyTime="0:0:3" Value="3.45" KeySpline="0,0.52,0.51,1"/>
</DoubleAnimationUsingKeyFrames>

The trick is about setting the Bezier for the SplineDoubleKeyFrame. If you want a smooth acceleration/deceleration, try using a Bezier closer to a linear form.

In addition: the Acceleration/DecelerationRatio is for a whole animation, but the KeySpline is valid for only a KeyFrame. So consider this, if you have an animation consisting of multiple KeyFrames.