问:
Incrementing a string by one for each iteration of loop
I have some string and for each string I have to increment value of it's last element by 1.

For Example:

Suppose I have a temp variable which gets a string each time when loop iterates.

Strings are in following forms:

```<code>String s1=abc,cde=1 //here I want to increment value of cde by 1

String s2=gef,pqwl=let2-1  //here also I want to increase value by 1
</code>```

These type of string can come randomly, so I need to provide such a handling
whether the string is of type s1 or s2 it should increment its value by 1 every time.

```<code>Expected output:

abc,cde=2
if same string comes again: abc,cde=3
gef,pqwl=let2-2
if same string comes again: gef,pqwl=let2-3
and so on
</code>```

Please help

答:
While you can use a String to store a number, it is essentially a sequence of characters, and as such cannot be incremented (in fact, the statement "increment a String" makes about as much sense as the statement "increment the smell of roses").

I would suggest you have a look at the tutorial for data types in Java:

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

If you're trying to store a number, then you're probably looking for byte, int, long or short if you want a whole number, or float or double for decimal numbers. If you're trying to create an association (that is, an integer value mapped to a String key), then you should use an implementation of java.util.Map, such as HashMap, or in a few specific use cases TreeMap.

Incrementing the value of a number stored as value in a map is simply a matter of replacing the value with the given key:

```<code>Map<String,Integer> map = new HashMap<>();
// Add value
map.put(key, originalValue);
// Increment value by 1
map.put(key, map.get(key)+1);
</code>```

In addition, if you're using Java 8, you could also use replaceAll to increment all values in a Map:

```<code>map.replaceAll((key,value) -> value+1);
</code>```

Body:
I have some string and for each string I have to increment value of it's last element by 1.

For Example:

Suppose I have a temp variable which gets a string each time when loop iterates.

Strings are in following forms:

String s1=abc,cde=1 //here I want to increment value of cde by 1

String s2=gef,pqwl=let2-1  //here also I want to increase value by 1

These type of string can come randomly, so I need to provide such a handling
whether the string is of type s1 or s2 it should increment its value by 1 every time.

Expected output:

abc,cde=2
if same string comes again: abc,cde=3
gef,pqwl=let2-2
if same string comes again: gef,pqwl=let2-3
and so on

Please help

Body:
While you can use a String to store a number, it is essentially a sequence of characters, and as such cannot be incremented (in fact, the statement "increment a String" makes about as much sense as the statement "increment the smell of roses").

I would suggest you have a look at the tutorial for data types in Java:

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

If you're trying to store a number, then you're probably looking for byte, int, long or short if you want a whole number, or float or double for decimal numbers. If you're trying to create an association (that is, an integer value mapped to a String key), then you should use an implementation of java.util.Map, such as HashMap, or in a few specific use cases TreeMap.

Incrementing the value of a number stored as value in a map is simply a matter of replacing the value with the given key:

Map<String,Integer> map = new HashMap<>();
// Add value
map.put(key, originalValue);
// Increment value by 1
map.put(key, map.get(key)+1);

In addition, if you're using Java 8, you could also use replaceAll to increment all values in a Map:

map.replaceAll((key,value) -> value+1);


来源: stackexchange

问:
how to get ipv4 address of particular adapter via batch script in windows 10
I am trying to fetch the ipv4 address of the particular adapter(say Ethernet adapter Local Area Connection* 14) is there any command or script to do that in windows 10 . if somebody already had done in past thanks to share it .

Input -- adapter name

Output -- only adapter's ip address

答:
You can give a try with this batch script to get :

Private LAN IP (ipv4)

External Public IP

MAC Address

@echo off
Title Get (LAN ,Public) (IP) and MAC Addresses by Hackoo 2017
mode con cols=80 lines=5 & Color 9E
echo( & echo(
echo   Please Wait a While ... Searching for (LAN ,Public)(IP) and MAC addresses ...
Set "LogFile=%~dpn0.txt"
@for /f "delims=[] tokens=2" %%a in ('ping -4 -n 1 %ComputerName% ^| findstr [') do (
    set "LAN_IP=%%a"
)

for /f "tokens=2 delims=: " %%A in (
  'nslookup myip.opendns.com. resolver1.opendns.com 2^>NUL^|find "Address:"'
) Do set ExtIP=%%A

@For /f %%a in ('getmac /NH /FO Table') do  (
    @For /f %%b in ('echo %%a') do (
        If /I NOT "%%b"=="N/A" (
            Set "MY_MAC=%%b"
        )
    )
)
    Cls
    echo(
    echo                My Private LAN IP       : %LAN_IP%
    echo                My External Public IP   : %ExtIP%
    echo                MAC Addres              : %MY_MAC%

(
    echo My Private LAN IP      : %LAN_IP%
    echo My External Public IP  : %ExtIP%
    echo MAC Address            : %MY_MAC%

)>"%LogFile%"
Timeout /T 5 /NoBreak>nul
Start "" "%LogFile%"
```

ContentLicense: CC BY-SA 3.0


问:
Accumulator within a DO loop
My goal is to create 10,000 randomly generated numbers between 0 and 1, organize them into ten bins evenly spaced between 0 and 1, and compute a frequency for each bin. This is my code so far.

```<code>program listrand
implicit none
integer :: n,p
integer :: a,b,c,d,e,f,g,h,i,j = 0
real :: xran
!real, dimension(10,2) :: bin_and_freq -- list of bins and frequency

do n = 1,10000
    call random_number(xran)
            if (xran <  0.1) then
                a = a + 1
            elseif (xran>0.1 .and. xran<0.2) then
                b = b + 1
            elseif (xran>0.2 .and. xran<0.3) then
                c = c+1
            elseif (xran>0.3 .and. xran<0.4) then
                d = d+1
            elseif (xran>0.4 .and. xran<0.5) then
                e = e + 1
            elseif (xran>0.5 .and. xran<0.6) then
                f = f+1
            elseif (xran>0.6 .and. xran<0.7) then
                g = g+1
            elseif (xran>0.7 .and. xran<0.8) then
                h=h+1
            elseif (xran>0.8 .and. xran<0.9) then
                i=i+1
            else
                j = j+1
            endif
enddo
print *, a,b,c,d,e,f,g,h,i,j
end program listrand
</code>```

I am getting an unexpected output:
    988        1036   133225987        1004         934         986        1040       33770  1406729616        1052.

Why are c,h, and i so large? Also, is there a more efficient way of going about this than using the unwieldy IF/ELSEIF block I have?

答:
If speed of execution is one's main concern, and if one is willing to trade space for time, this might appeal:

```<code>PROGRAM listrand

  IMPLICIT NONE

  INTEGER, PARAMETER :: nbins = 10
  INTEGER, PARAMETER :: nsamples = 10**4
  INTEGER :: bin_hits(0:nbins-1)
  REAL :: xran(nsamples)
  INTEGER :: binned_rn(nsamples), n

  bin_hits = 0

  CALL RANDOM_NUMBER(xran)
  binned_rn = INT(nbins*xran)
  DO n = 1, nsamples
    bin_hits(binned_rn(n)) = bin_hits(binned_rn(n)) +1
  END DO

  WRITE(*,*) bin_hits

END PROGRAM listrand
</code>```

In a limited number of tests this version is 3 - 4 times as fast as @chw21's version.

Title: Accumulator within a DO loop

Body:
My goal is to create 10,000 randomly generated numbers between 0 and 1, organize them into ten bins evenly spaced between 0 and 1, and compute a frequency for each bin. This is my code so far.

program listrand
implicit none
integer :: n,p
integer :: a,b,c,d,e,f,g,h,i,j = 0
real :: xran
!real, dimension(10,2) :: bin_and_freq -- list of bins and frequency

do n = 1,10000
    call random_number(xran)
            if (xran <  0.1) then
                a = a + 1
            elseif (xran>0.1 .and. xran<0.2) then
                b = b + 1
            elseif (xran>0.2 .and. xran<0.3) then
                c = c+1
            elseif (xran>0.3 .and. xran<0.4) then
                d = d+1
            elseif (xran>0.4 .and. xran<0.5) then
                e = e + 1
            elseif (xran>0.5 .and. xran<0.6) then
                f = f+1
            elseif (xran>0.6 .and. xran<0.7) then
                g = g+1
            elseif (xran>0.7 .and. xran<0.8) then
                h=h+1
            elseif (xran>0.8 .and. xran<0.9) then
                i=i+1
            else
                j = j+1
            endif
enddo
print *, a,b,c,d,e,f,g,h,i,j
end program listrand

I am getting an unexpected output:
    988        1036   133225987        1004         934         986        1040       33770  1406729616        1052.

Why are c,h, and i so large? Also, is there a more efficient way of going about this than using the unwieldy IF/ELSEIF block I have?

Body:
If speed of execution is one's main concern, and if one is willing to trade space for time, this might appeal:

PROGRAM listrand

  IMPLICIT NONE

  INTEGER, PARAMETER :: nbins = 10
  INTEGER, PARAMETER :: nsamples = 10**4
  INTEGER :: bin_hits(0:nbins-1)
  REAL :: xran(nsamples)
  INTEGER :: binned_rn(nsamples), n

  bin_hits = 0

  CALL RANDOM_NUMBER(xran)
  binned_rn = INT(nbins*xran)
  DO n = 1, nsamples
    bin_hits(binned_rn(n)) = bin_hits(binned_rn(n)) +1
  END DO

  WRITE(*,*) bin_hits

END PROGRAM listrand

In a limited number of tests this version is 3 - 4 times as fast as @chw21's version.


问:
Perform .join on value in array of objects
If I have an array of strings, I can use the .join() method to get a single string, with each element separated by commas, like so:

```<code>["Joe", "Kevin", "Peter"].join(", ") // => "Joe, Kevin, Peter"
</code>```

I have an array of objects, and I’d like to perform a similar operation on a value held within it; so from

```<code>[
  {name: "Joe", age: 22},
  {name: "Kevin", age: 24},
  {name: "Peter", age: 21}
]
</code>```

perform the join method only on the name attribute, to achieve the same output as before.

Currently I have the following function:

```<code>function joinObj(a, attr){
  var out = [];

  for (var i = 0; i < a.length; i++){
    out.push(a[i][attr]);
  }

  return out.join(", ");
}
</code>```

There’s nothing wrong with that code, it works, but all of a sudden I’ve gone from a simple, succinct line of code to a very imperative function. Is there a more succinct, ideally more functional way of writing this?

答:
lets say the objects array is referenced by the variable users

If ES6 can be used then the easiest solution will be:

```<code>users.map(user => user.name).join(', ');
</code>```

If not, and lodash can be used so :

```<code> _.map(users, function(user) {
     return user.name;
 }).join(', ');
</code>```

Body:
If I have an array of strings, I can use the .join() method to get a single string, with each element separated by commas, like so:

["Joe", "Kevin", "Peter"].join(", ") // => "Joe, Kevin, Peter"

I have an array of objects, and I’d like to perform a similar operation on a value held within it; so from

[
  {name: "Joe", age: 22},
  {name: "Kevin", age: 24},
  {name: "Peter", age: 21}
]

perform the join method only on the name attribute, to achieve the same output as before.

Currently I have the following function:

function joinObj(a, attr){
  var out = [];

  for (var i = 0; i < a.length; i++){
    out.push(a[i][attr]);
  }

  return out.join(", ");
}

There’s nothing wrong with that code, it works, but all of a sudden I’ve gone from a simple, succinct line of code to a very imperative function. Is there a more succinct, ideally more functional way of writing this?

Body:
lets say the objects array is referenced by the variable users

If ES6 can be used then the easiest solution will be:

users.map(user => user.name).join(', ');

If not, and lodash can be used so :

 _.map(users, function(user) {
     return user.name;
 }).join(', ');


问:
Emacs buffer creation/switching function
I would like to make function that creates a buffer named 'console', if it does not exist and runs a few commands.  If the buffer already exists I want it to only switch to it.</p>

答:
get-buffer-create ("Return the buffer specified by BUFFER-OR-NAME, creating a new one if needed.") will handle creating the buffer if one doesn't exist. Then use switch-to-buffer ("Make BUFFER-OR-NAME current and display it in selected window.") to switch to the buffer.

So something like this will do the trick:

```<code>(switch-to-buffer (get-buffer-create "console"))
</code>```

ContentLicense: CC BY-SA 2.5

Body:
get-buffer-create ("Return the buffer specified by BUFFER-OR-NAME, creating a new one if needed.") will handle creating the buffer if one doesn't exist. Then use switch-to-buffer ("Make BUFFER-OR-NAME current and display it in selected window.") to switch to the buffer.

So something like this will do the trick:

(switch-to-buffer (get-buffer-create "console"))

OwnerDisplayName: please delete me


问:
To shuffle two list and merge into one list
I want to merge two list into one
  eg:

```<code>    A  B
    3  7
    1  8
    9  2
    31 4
</code>```

Desired answer:

```<code>    A
    3
    8
    9
    4
</code>```

It would be helpful if you anyone can tell me Code of this query?

答:
If A and B are vectors:

```<code>A[c(FALSE, TRUE)] <- B[c(FALSE, TRUE)]
A
</code>```

```<code>[1] 3 8 9 4
</code>```

If A and B are columns of a data frmae (which appears to be the case judging from the printed output)

```<code>DF$A[c(FALSE, TRUE)] <- DF$B[c(FALSE, TRUE)]
DF
</code>```

```<code>  A B
1 3 7
2 8 8
3 9 2
4 4 4
</code>```

Body:
I want to merge two list into one
  eg:

    A  B
    3  7
    1  8
    9  2
    31 4

Desired answer:

    A
    3
    8
    9
    4

It would be helpful if you anyone can tell me Code of this query?

Body:
If A and B are vectors:

A[c(FALSE, TRUE)] <- B[c(FALSE, TRUE)]
A

[1] 3 8 9 4

If A and B are columns of a data frmae (which appears to be the case judging from the printed output)

DF$A[c(FALSE, TRUE)] <- DF$B[c(FALSE, TRUE)]
DF

  A B
1 3 7
2 8 8
3 9 2
4 4 4


问:
Getting the rows cell to line up with parameters in a stored procedure
I am using a datagridview on a win app designed in c#2010 express.
 In the _row leave event of my datagrid I would like to use the
TableAdapter.usp_insert() that I created. But how does one match up the data in the cells of the datagridview row to the parameters in the stored procedure.

This is what if found so far!

```<code>Int i;
i = datagridview1.SelectedCells[0].RowIndex;
...
....
// Eventually
string id = dataGridView1.Rows[i].cell[0].Value.ToString();
@para1 = id;
</code>```

Etc..

What do you think?

答:
It seems that I solved my problem

Int i;

i = datagridview1.SelectedCells[0].RowIndex; ... ....

Eventually assign the the specific column/row to the declared value:

string id = dataGridView1.Rows[i].cell[0].Value.ToString();

 @para1 = id;
Etc..

is that answer I needed

Body:
I am using a datagridview on a win app designed in c#2010 express.
 In the _row leave event of my datagrid I would like to use the
TableAdapter.usp_insert() that I created. But how does one match up the data in the cells of the datagridview row to the parameters in the stored procedure.

This is what if found so far!

Int i;
i = datagridview1.SelectedCells[0].RowIndex;
...
....
// Eventually
string id = dataGridView1.Rows[i].cell[0].Value.ToString();
@para1 = id;

Etc..

What do you think?


问:
Warning: touchID deprecated in iOS 11.0
I'm supporting Touch ID and Face ID within my app. To support older versions of iOS I'm using the following code:

```<code>if #available(iOS 11.0, *) {
    biometricsNotEnrolled = LAError.biometryNotEnrolled
    biometricsLocked = LAError.biometryLockout
} else {
    biometricsNotEnrolled = LAError.touchIDNotEnrolled
    biometricsLocked = LAError.touchIDLockout
}

switch(error) {
case biometricsNotEnrolled:
    // Do stuff
case LAError.passcodeNotSet:
    // Do stuff
case biometricsLocked:
    // Do stuff
default:
    // Do stuff
}
</code>```

But when I compile I will get the following warnings:

```<code>warning: 'touchIDLockout' was deprecated in iOS 11.0: use LAErrorBiometryLockout

warning: 'touchIDNotEnrolled' was deprecated in iOS 11.0: use LAErrorBiometryNotEnrolled

warning: 'touchIDNotAvailable' was deprecated in iOS 11.0: use LAErrorBiometryNotAvailable
</code>```

How can I get rid of the warning?

答: When you are setting deployment target of some iOS version, deprecate message will show for that version, in this case its for iOS 11, lower the deployment target will stop showing the warning.</p>

Title: Warning: touchID deprecated in iOS 11.0

Body:
I'm supporting Touch ID and Face ID within my app. To support older versions of iOS I'm using the following code:

if #available(iOS 11.0, *) {
    biometricsNotEnrolled = LAError.biometryNotEnrolled
    biometricsLocked = LAError.biometryLockout
} else {
    biometricsNotEnrolled = LAError.touchIDNotEnrolled
    biometricsLocked = LAError.touchIDLockout
}

switch(error) {
case biometricsNotEnrolled:
    // Do stuff
case LAError.passcodeNotSet:
    // Do stuff
case biometricsLocked:
    // Do stuff
default:
    // Do stuff
}

But when I compile I will get the following warnings:

warning: 'touchIDLockout' was deprecated in iOS 11.0: use LAErrorBiometryLockout

warning: 'touchIDNotEnrolled' was deprecated in iOS 11.0: use LAErrorBiometryNotEnrolled

warning: 'touchIDNotAvailable' was deprecated in iOS 11.0: use LAErrorBiometryNotAvailable

How can I get rid of the warning?


问:
How to programmatically set action for barButtonItem in swift 3?
Here is what I used previously,

```<code>var barButtonItem = UIBarButtonItem(image: backImgs, style: UIBarButtonItemStyle.plain, target: self, action: Selector("menuButtonTapped:"))
</code>```

But there is some syntax changes for Swift 3.

答:
In Swift 3, you can add UIBarButtonItem like that,

```<code>let addButton = UIBarButtonItem(image:UIImage(named:"your_icon_name"), style:.plain, target:self, action:#selector(YourControllerName.buttonAction(_:)))
addButton.tintColor = UIColor.white
self.navigationItem.rightBarButtonItem = addButton
</code>```

And handle button action like that,

```<code>func buttonAction(_ sender: UIBarButtonItem) {

}
</code>```

Hope it helps.

ContentLicense: CC BY-SA 4.0

Body:
Here is what I used previously,

var barButtonItem = UIBarButtonItem(image: backImgs, style: UIBarButtonItemStyle.plain, target: self, action: Selector("menuButtonTapped:"))

But there is some syntax changes for Swift 3.

Body:
In Swift 3, you can add UIBarButtonItem like that,

let addButton = UIBarButtonItem(image:UIImage(named:"your_icon_name"), style:.plain, target:self, action:#selector(YourControllerName.buttonAction(_:)))
addButton.tintColor = UIColor.white
self.navigationItem.rightBarButtonItem = addButton

And handle button action like that,

func buttonAction(_ sender: UIBarButtonItem) {

}

Hope it helps.


问:
MongoDB: Does findOne retrieve the whole collection from the database to the server
I am trying to make a website and I'm using mongoDB to store my database. I have a question about the performance about the query findOne which I've used widely. Does this query take the whole collection from the database to the server and then perform the iteration over it or does it perform the iteration on the database and just return the document to the server? Picking up the whole collection from the server will be an issue because transferring such a huge chunk of data will take time. </p>

答:
Quoting official MongoDB documentation:

findOne - Returns one document that satisfies the specified query criteria on
  the collection or view. If multiple documents satisfy the query, this
  method returns the first document according to the natural order which
  reflects the order of documents on the disk.

Obviously implied is that the database itself will only return one collection, and in addition, you could always use postman, or console.log to check what the server returns (if you're not sure).


问:
Kotlin and idiomatic way to write, 'if not null, else...' based around mutable value
Suppose we have this code:

```<code>class QuickExample {

    fun function(argument: SomeOtherClass) {
        if (argument.mutableProperty != null ) {
            doSomething(argument.mutableProperty)
        } else {
            doOtherThing()
        }
    }

    fun doSomething(argument: Object) {}

    fun doOtherThing() {}
}

class SomeOtherClass {
    var mutableProperty: Object? = null
}
</code>```

Unlike in Java, where you could be left alone to worry about null dereferencing at runtime, this doesn't compile - quite rightly. Of course, mutableProperty may no longer be null once within the 'if'.

My question is what's the best way to handle this?

A few options are apparent. Without using any new Kotlin language features, the simplest way is obviously to copy the value to a method-scope one that won't subsequently change.

There's this:

```<code>fun function(argument: SomeOtherClass) {
    argument.mutableProperty?.let {
        doSomething(it)
        return
    }
    doOtherThing()
}
</code>```

This has the obvious disadvantage that you need to return early or otherwise avoid executing the subsequent code - OK in certain, small contexts, but has a smell to it.

Then there's this possibility:

```<code>fun function(argument: SomeOtherClass) {
    argument.mutableProperty.let {
        when {
            it != null -> {
                doSomething(it)
            }
            else -> {
                doOtherThing()
            }
        }
    }
}
</code>```

but whilst it has greater clarity of purpose, arguably it's more unwieldy and verbose than the Java-style way of dealing with this.

Am I missing anything, and is there a preferred idiom with which to achieve this?

答:
add custom inline function as below:

```<code>inline fun <T> T?.whenNull(block: T?.() -> Unit): T? {
    if (this == null) block()
    return this@whenNull
}

inline fun <T> T?.whenNonNull(block: T.() -> Unit): T? {
    this?.block()
    return this@whenNonNull
}
</code>```

then you can write code like this:

```<code>var nullableVariable :Any? = null
nullableVariable.whenNonNull {
    doSomething(nullableVariable)
}.whenNull {
    doOtherThing()
}
</code>```

Body:
Suppose we have this code:

class QuickExample {

    fun function(argument: SomeOtherClass) {
        if (argument.mutableProperty != null ) {
            doSomething(argument.mutableProperty)
        } else {
            doOtherThing()
        }
    }

    fun doSomething(argument: Object) {}

    fun doOtherThing() {}
}

class SomeOtherClass {
    var mutableProperty: Object? = null
}

Unlike in Java, where you could be left alone to worry about null dereferencing at runtime, this doesn't compile - quite rightly. Of course, mutableProperty may no longer be null once within the 'if'.

My question is what's the best way to handle this?

A few options are apparent. Without using any new Kotlin language features, the simplest way is obviously to copy the value to a method-scope one that won't subsequently change.

There's this:

fun function(argument: SomeOtherClass) {
    argument.mutableProperty?.let {
        doSomething(it)
        return
    }
    doOtherThing()
}

This has the obvious disadvantage that you need to return early or otherwise avoid executing the subsequent code - OK in certain, small contexts, but has a smell to it.

Then there's this possibility:

fun function(argument: SomeOtherClass) {
    argument.mutableProperty.let {
        when {
            it != null -> {
                doSomething(it)
            }
            else -> {
                doOtherThing()
            }
        }
    }
}

but whilst it has greater clarity of purpose, arguably it's more unwieldy and verbose than the Java-style way of dealing with this.

Am I missing anything, and is there a preferred idiom with which to achieve this?

Body:
add custom inline function as below:

inline fun <T> T?.whenNull(block: T?.() -> Unit): T? {
    if (this == null) block()
    return this@whenNull
}

inline fun <T> T?.whenNonNull(block: T.() -> Unit): T? {
    this?.block()
    return this@whenNonNull
}

then you can write code like this:

var nullableVariable :Any? = null
nullableVariable.whenNonNull {
    doSomething(nullableVariable)
}.whenNull {
    doOtherThing()
}


问:
How do I wrap a function with an object in a class in javascript?
Let's say I have a class named Human.

```<code>function Human(name, gender, age, personality){
    this.name = name;
    this.gender = gender;
    this.age = age;
    this.personality = personality;
}
</code>```

and I have some functions for the class such as greeting and introduce. So I create them like this:

```<code>Human.prototype.introduce = function() {
    var _gender = {"M": "Boy", "F": "Girl"};
    switch(this.personality)
    {
    case "passionate":
        alert("Hi, how are you? My name is " + this.name + ". I'm " + this.age + " years old " + _gender[this.gender] + ". ");
        break;
    case "aggressive":
        alert("I'm " + this.name + ". What you want? ");
        break;
    }
}

Human.prototype.greeting = function() {
    alert("Hi!");
}
</code>```

Since introduce and greeting can be grouped by the same category (let's name it speak), how can I simply wrap this two functions with an object? I've tried this:

```<code>Human.prototype.speak = {};
Human.prototype.speak.greeting = function(){
    alert("Hi!");
}
Human.prototype.speak.introduce = function(){
var _gender = {"M": "Boy", "F": "Girl"};
        switch(this.personality)
        {
        case "passionate":
            alert("Hi, how are you? My name is " + this.name + ". I'm " + this.age + " years old " + _gender[this.gender] + ". ");
            break;
        case "aggressive":
            alert("I'm " + this.name + ". What you want? ");
            break;
        }
}
</code>```

Now the question is, when a function is wrapped by an object, this in the introduce function is no longer referring to the instance. So how can I work this out?

I would like to call the function as this:

```<code>var eminem = new Human("Marshall Mathers", "M", 45, "aggressive");
eminem.speak.introduce();
</code>```

答:
Based on the accepted answer you could write a few lines of code to automatically rebind all your functions using Object.keys and forEach.

```<code>function Human(name, gender, age, personality){
    this.name = name;
    this.gender = gender;
    this.age = age;
    this.personality = personality;

    Object.keys(this.speak).filter(function(key) {
        return typeof this.speak[key] === 'function';
    }, this).forEach(function(key) {
        this.speak[key] = this.speak[key].bind(this);
    }, this);
}
</code>```

Also you could easily improve this code to not only iterate the functions of the 'speak' object.

Body:
Let's say I have a class named Human.

function Human(name, gender, age, personality){
    this.name = name;
    this.gender = gender;
    this.age = age;
    this.personality = personality;
}

and I have some functions for the class such as greeting and introduce. So I create them like this:

Human.prototype.introduce = function() {
    var _gender = {"M": "Boy", "F": "Girl"};
    switch(this.personality)
    {
    case "passionate":
        alert("Hi, how are you? My name is " + this.name + ". I'm " + this.age + " years old " + _gender[this.gender] + ". ");
        break;
    case "aggressive":
        alert("I'm " + this.name + ". What you want? ");
        break;
    }
}

Human.prototype.greeting = function() {
    alert("Hi!");
}

Since introduce and greeting can be grouped by the same category (let's name it speak), how can I simply wrap this two functions with an object? I've tried this:

Human.prototype.speak = {};
Human.prototype.speak.greeting = function(){
    alert("Hi!");
}
Human.prototype.speak.introduce = function(){
var _gender = {"M": "Boy", "F": "Girl"};
        switch(this.personality)
        {
        case "passionate":
            alert("Hi, how are you? My name is " + this.name + ". I'm " + this.age + " years old " + _gender[this.gender] + ". ");
            break;
        case "aggressive":
            alert("I'm " + this.name + ". What you want? ");
            break;
        }
}

Now the question is, when a function is wrapped by an object, this in the introduce function is no longer referring to the instance. So how can I work this out?

I would like to call the function as this:

var eminem = new Human("Marshall Mathers", "M", 45, "aggressive");
eminem.speak.introduce();

Body:
Based on the accepted answer you could write a few lines of code to automatically rebind all your functions using Object.keys and forEach.

function Human(name, gender, age, personality){
    this.name = name;
    this.gender = gender;
    this.age = age;
    this.personality = personality;

    Object.keys(this.speak).filter(function(key) {
        return typeof this.speak[key] === 'function';
    }, this).forEach(function(key) {
        this.speak[key] = this.speak[key].bind(this);
    }, this);
}

Also you could easily improve this code to not only iterate the functions of the 'speak' object.


问:
Does Netezza support programming i.e. does it have PL/SQL equivalent?
Given that netezza has SQL equilalent in Netezza SQL does it support more powerful within-netezza-solutions through some programming model like PL/SQL?</p>

答: Yes, they have what is called NZPLSQL which is based off of postgres' PL/pgSQL.</p>


问:
Semaphore in Azure Web Job
I am wondering if a Semaphore (lock) would work in Azure functions.
I do not want two separate webjobs running at the same time. The webjobs live on the same app service plan.

Is this something I can guarantee with a semaphore? (as this enables cross process locking?)

答:
First question: you're talking about Functions and WebJobs. Which one is it?

If your App Service Plan does any scaling, the semaphore will not work since two instances might be started on two different machines. The good thing: (for WebJobs) there's a simple solution for that.

```<code>[Singleton]
public static async Task ProcessImage([BlobTrigger("images")] Stream image)
{
     // Process the image
}
</code>```

In this example, only a single instance of the ProcessImage function will run at any given time. When the function is triggered by a new image being added to the images container, the runtime will first attempt to acquire the lock (blob lease). Once acquired, the lock is held (and the blob lease is renewed) for the duration of the function execution, ensuring no other instances will run. If another function instance is triggered while this function is running it will wait for the lock, periodically polling for it.

You can find more information here: Azure WebJobs SDK - Singleton

Edit:

If you're using Azure Functions: those running based on a TimerTrigger seem to run as Singletons.

The timer trigger supports multi-instance scale-out. A single instance of a particular timer function is run across all instances.

Title: Semaphore in Azure Web Job

Body:
First question: you're talking about Functions and WebJobs. Which one is it?

If your App Service Plan does any scaling, the semaphore will not work since two instances might be started on two different machines. The good thing: (for WebJobs) there's a simple solution for that.

[Singleton]
public static async Task ProcessImage([BlobTrigger("images")] Stream image)
{
     // Process the image
}

In this example, only a single instance of the ProcessImage function will run at any given time. When the function is triggered by a new image being added to the images container, the runtime will first attempt to acquire the lock (blob lease). Once acquired, the lock is held (and the blob lease is renewed) for the duration of the function execution, ensuring no other instances will run. If another function instance is triggered while this function is running it will wait for the lock, periodically polling for it.

You can find more information here: Azure WebJobs SDK - Singleton

Edit:

If you're using Azure Functions: those running based on a TimerTrigger seem to run as Singletons.

The timer trigger supports multi-instance scale-out. A single instance of a particular timer function is run across all instances.


问:
android.os.ServiceSpecificException Caller does not own BCM26 (code 13)
I have written a Xamarin.Android C# class that manages the io pins for the Android Things OS running on my Raspberry Pi 3. When I try to read the pin this exception is raised:

android.os.ServiceSpecificException: Caller does not own BCM26 (code
  13)

from :

```<code>1   // setup
2   var io = new PeripheralManagerService();
3   Gpio p = io.OpenGpio("BCM26");
4   p.SetDirection(Gpio.DirectionIn);
5
6   // later I read it
7   if (p.Value == HIGH)
8      Console.WriteLine("Pin is high");
9   // Exception raised
</code>```

What should I do to resolve this issue?

edit: The code above will actually work. I tried to only extract the relevant parts into a small sample of code because the original was multi threaded and too complicated to post, which led to an answer why the exception was raised. It wasn't related to Android Services and Permissions. The pin I tried to read was closed after having its direction set. Removing the call to close resolved this issue.

答: Pin must remain open (don't close it until you've really finished with it) otherwise attempts to read the pin would raise the cryptic exception which confused me with Android permissions like internet-use or record-audio permissions. </p>

Body:
I have written a Xamarin.Android C# class that manages the io pins for the Android Things OS running on my Raspberry Pi 3. When I try to read the pin this exception is raised:

android.os.ServiceSpecificException: Caller does not own BCM26 (code
  13)

from :

1   // setup
2   var io = new PeripheralManagerService();
3   Gpio p = io.OpenGpio("BCM26");
4   p.SetDirection(Gpio.DirectionIn);
5
6   // later I read it
7   if (p.Value == HIGH)
8      Console.WriteLine("Pin is high");
9   // Exception raised

What should I do to resolve this issue?

edit: The code above will actually work. I tried to only extract the relevant parts into a small sample of code because the original was multi threaded and too complicated to post, which led to an answer why the exception was raised. It wasn't related to Android Services and Permissions. The pin I tried to read was closed after having its direction set. Removing the call to close resolved this issue.


问:
Multiple filter condition in Spark Filter method
How to write multiple case in filter() method in spark using scala like, I have an Rdd of cogroup

```<code>(1,(CompactBuffer(1,john,23),CompactBuffer(1,john,24)).filter(x => (x._2._1 != x._2._2))//value not equal
(2,(CompactBuffer(),CompactBuffer(2,Arun,24)).filter(x => (x._2._1==null))//Second tuple first value is null
(3,(CompactBuffer(3,kumar,25),CompactBuffer()).filter(x => (x._2._2==null))//Second tuple second value is null

val a = source_primary_key.cogroup(destination_primary_key).filter(x => (x._2._1 != x._2._2))

val c=  a.map { y =>

    val key = y._1
    val value = y._2

    srcs = value._1.mkString(",")
    destt = value._2.mkString(",")

    if (srcs.equalsIgnoreCase(destt) == false) {
      srcmis :+= srcs
      destmis :+= destt
    }

    if (srcs == "") {
      extraindest :+= destt.mkString("")
    }

    if (destt == "") {
      extrainsrc :+= srcs.mkString("")
    }

}
</code>```

How to store each condition in 3 different Array[String]

I tried like above but seems naive, is there anyway way we can do it efficiently ?

答:
For testing purpose, I created following rdds

```<code>val source_primary_key = sc.parallelize(Seq((1,(1,"john",23)),(3,(3,"kumar",25))))
val destination_primary_key = sc.parallelize(Seq((1,(1,"john",24)),(2,(2,"arun",24))))
</code>```

Then I cogrouped as you did

```<code>val coGrouped = source_primary_key.cogroup(destination_primary_key)
</code>```

Now is the step to filter the cogrouped rdd to three separate rdds as

```<code>val a = coGrouped.filter(x => !x._2._1.isEmpty && !x._2._2.isEmpty)
val b = coGrouped.filter(x => x._2._1.isEmpty && !x._2._2.isEmpty)
val c = coGrouped.filter(x => !x._2._1.isEmpty && x._2._2.isEmpty)
</code>```

I hope the answer is helpful

Body:
How to write multiple case in filter() method in spark using scala like, I have an Rdd of cogroup

(1,(CompactBuffer(1,john,23),CompactBuffer(1,john,24)).filter(x => (x._2._1 != x._2._2))//value not equal
(2,(CompactBuffer(),CompactBuffer(2,Arun,24)).filter(x => (x._2._1==null))//Second tuple first value is null
(3,(CompactBuffer(3,kumar,25),CompactBuffer()).filter(x => (x._2._2==null))//Second tuple second value is null

val a = source_primary_key.cogroup(destination_primary_key).filter(x => (x._2._1 != x._2._2))

val c=  a.map { y =>

    val key = y._1
    val value = y._2

    srcs = value._1.mkString(",")
    destt = value._2.mkString(",")

    if (srcs.equalsIgnoreCase(destt) == false) {
      srcmis :+= srcs
      destmis :+= destt
    }

    if (srcs == "") {
      extraindest :+= destt.mkString("")
    }

    if (destt == "") {
      extrainsrc :+= srcs.mkString("")
    }

}

How to store each condition in 3 different Array[String]

I tried like above but seems naive, is there anyway way we can do it efficiently ?

Body:
For testing purpose, I created following rdds

val source_primary_key = sc.parallelize(Seq((1,(1,"john",23)),(3,(3,"kumar",25))))
val destination_primary_key = sc.parallelize(Seq((1,(1,"john",24)),(2,(2,"arun",24))))

Then I cogrouped as you did

val coGrouped = source_primary_key.cogroup(destination_primary_key)

Now is the step to filter the cogrouped rdd to three separate rdds as

val a = coGrouped.filter(x => !x._2._1.isEmpty && !x._2._2.isEmpty)
val b = coGrouped.filter(x => x._2._1.isEmpty && !x._2._2.isEmpty)
val c = coGrouped.filter(x => !x._2._1.isEmpty && x._2._2.isEmpty)

I hope the answer is helpful


问:
How to get content details in YouTube Search API v3 ? (Swift)
I am using this to get the information of the video such title and image.

```<code>var urlString = "https://www.googleapis.com/youtube/v3/search?part=snippet&fields=items(id,snippet(title,channelTitle,thumbnails))&order=viewCount&q=\(text)&type=video&maxResults=25&key=\(apiKey)"
</code>```

This above URL will return a JSON.

```<code>     ["items": <__NSArrayI 0x1c41b03e0>(
{
    id =     {
        kind = "youtube#video";
        videoId = n3T3K2MHNjM;
    };
    snippet =     {
        channelTitle = "Ty Dolla $ign";
        thumbnails =         {
            default =             {
                height = 90;
                url = "https://i.ytimg.com/vi/n3T3K2MHNjM/default.jpg";
                width = 120;
            };
            high =             {
                height = 360;
                url = "https://i.ytimg.com/vi/n3T3K2MHNjM/hqdefault.jpg";
                width = 480;
            };
            medium =             {
                height = 180;
                url = "https://i.ytimg.com/vi/n3T3K2MHNjM/mqdefault.jpg";
                width = 320;
            };
        };
        title = "Ty Dolla $ign & Future - Darkside feat. Kiiara (from Bright: The Album) [Official Audio]";
    };
},
</code>```

but there is no content details in the JSON I would like to access the content details since its contains the duration of the video which i needed. I had try to access with url like this by inserting the contentDetails into the URL but it is not working.

```<code>var urlString = "https://www.googleapis.com/youtube/v3/search?part=snippet&fields=items(id,contentDetails,snippet(title,channelTitle,thumbnails))&order=viewCount&q=\(text)&type=video&maxResults=25&key=\(apiKey)"
</code>```

How can i retrieve the content details also ?

答:
The search API v3 does not have the duration in the search API , you need use the video API to get the video information.

```<code>var urlString = "https://www.googleapis.com/youtube/v3/videos?key=\(apiKey)&part=contentDetails&id="
</code>```

Use this URL and then add in the id behind like this U4_Os5LNVjg, s23mnsidmm for multiple ID and then use this to convert the duration format from YouTube
How to Convert duration form youtube api in swift?

Body:
I am using this to get the information of the video such title and image.

var urlString = "https://www.googleapis.com/youtube/v3/search?part=snippet&fields=items(id,snippet(title,channelTitle,thumbnails))&order=viewCount&q=\(text)&type=video&maxResults=25&key=\(apiKey)"

This above URL will return a JSON.

     ["items": <__NSArrayI 0x1c41b03e0>(
{
    id =     {
        kind = "youtube#video";
        videoId = n3T3K2MHNjM;
    };
    snippet =     {
        channelTitle = "Ty Dolla $ign";
        thumbnails =         {
            default =             {
                height = 90;
                url = "https://i.ytimg.com/vi/n3T3K2MHNjM/default.jpg";
                width = 120;
            };
            high =             {
                height = 360;
                url = "https://i.ytimg.com/vi/n3T3K2MHNjM/hqdefault.jpg";
                width = 480;
            };
            medium =             {
                height = 180;
                url = "https://i.ytimg.com/vi/n3T3K2MHNjM/mqdefault.jpg";
                width = 320;
            };
        };
        title = "Ty Dolla $ign & Future - Darkside feat. Kiiara (from Bright: The Album) [Official Audio]";
    };
},

but there is no content details in the JSON I would like to access the content details since its contains the duration of the video which i needed. I had try to access with url like this by inserting the contentDetails into the URL but it is not working.

var urlString = "https://www.googleapis.com/youtube/v3/search?part=snippet&fields=items(id,contentDetails,snippet(title,channelTitle,thumbnails))&order=viewCount&q=\(text)&type=video&maxResults=25&key=\(apiKey)"

How can i retrieve the content details also ?

Body:
The search API v3 does not have the duration in the search API , you need use the video API to get the video information.

var urlString = "https://www.googleapis.com/youtube/v3/videos?key=\(apiKey)&part=contentDetails&id="

Use this URL and then add in the id behind like this U4_Os5LNVjg, s23mnsidmm for multiple ID and then use this to convert the duration format from YouTube
How to Convert duration form youtube api in swift?


问:
Double byte character cannot be displayed in figure label
I use double byte name in data frame and used data.plot method.
But double byte name cannot be displayed in figure label.
(Showed in a red box of attached picture)
What shall I do?

enter image description here

答:
I can do it.
Installation steps are as follow:</p>

```<code>!wget http://ipafont.ipa.go.jp/old/ipaexfont/ipaexg00201.php
!mv ipaexg00201.php ipaexg00201.zip
!unzip ipaexg00201.zip
!cp ipaexg00201/ipaexg.ttf $HOME/.local/lib/python2.7/site-packages/matplotlib/mpl-data/fonts/ttf/
!cp $HOME/.local/lib/python2.7/site-packages/matplotlib/mpl-    data/matplotlibrc $HOME/.config/matplotlib/
!echo 'font.family : IPAexGothic' >>   $HOME/.config/matplotlib/matplotlibrc
!rm -r $HOME/.cache/matplotlib/*
import matplotlib
print(matplotlib.rcParams['font.family'])
import matplotlib.pyplot as plt
%matplotlib inline
plt.figure()
plt.xlabel(u'豆腐 - tofu')
plt.title(u'豆腐 - TOFU')
</code>```

Body:
I can do it.
Installation steps are as follow:

!wget http://ipafont.ipa.go.jp/old/ipaexfont/ipaexg00201.php
!mv ipaexg00201.php ipaexg00201.zip
!unzip ipaexg00201.zip
!cp ipaexg00201/ipaexg.ttf $HOME/.local/lib/python2.7/site-packages/matplotlib/mpl-data/fonts/ttf/
!cp $HOME/.local/lib/python2.7/site-packages/matplotlib/mpl-    data/matplotlibrc $HOME/.config/matplotlib/
!echo 'font.family : IPAexGothic' >>   $HOME/.config/matplotlib/matplotlibrc
!rm -r $HOME/.cache/matplotlib/*
import matplotlib
print(matplotlib.rcParams['font.family'])
import matplotlib.pyplot as plt
%matplotlib inline
plt.figure()
plt.xlabel(u'豆腐 - tofu')
plt.title(u'豆腐 - TOFU')


问:
Jasper Subreport InputStream Header does not show the image
I have a main report and subreport, and I pass a parameter to subreport as inputstream. I will use this parameter as a logo(image) in my subreport header. If I add the image to subreport and use this parameter, subreport shows only first record of my datasource and the image. If I do not use this image, my subreport lists all records of my datasource. I tried to put the image in detail, header, and title, but it did not work. If I use an image directly from subreport, it works well, but I need to send this parameter(filepath) from Java.

What can be the problem?

Edit: I provide some code.

Main report:

```<code> <?xml version="1.0" encoding="UTF-8"?>
    <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="e-BordroIsciToplu" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="a3c2690b-2af8-4210-8775-cb69cd6557f7">
    <property name="ireport.zoom" value="1.5394743546921228"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <property name="ireport.background.image.properties" value="true,true,0.25,138,273,0,0,386,161"/>
    <parameter name="SUBREPORT_DIR" class="java.lang.String" isForPrompting="false">
        <defaultValueExpression><![CDATA["W:\\Projects\\modules\\common\\src\\resources\\report\\templates\\"]]></defaultValueExpression>
    </parameter>
    <parameter name="ANTET" class="java.io.InputStream"/>
    <parameter name="AY" class="java.lang.String"/>
    <field name="topluInfo" class="java.util.List"/>
    <detail>
        <band height="109" splitType="Stretch">
            <subreport runToBottom="false">
                <reportElement positionType="Float" stretchType="RelativeToTallestObject" x="0" y="0" width="533" height="100" uuid="cd6571c7-c8da-4120-868f-82999376c3d3"/>
                <parametersMapExpression><![CDATA[]]></parametersMapExpression>
                <subreportParameter name="SUBREPORT_DIR">
                    <subreportParameterExpression><![CDATA[]]>  </subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="AY">
                    <subreportParameterExpression><![CDATA[$P{AY}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="ANTET">
                    <subreportParameterExpression><![CDATA[$P{ANTET}]]></subreportParameterExpression>
                </subreportParameter>
                <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{topluInfo})]]></dataSourceExpression>
                <subreportExpression><![CDATA[$P{SUBREPORT_DIR} + "e-topluSubreportTest.jasper"]]></subreportExpression>
            </subreport>
        </band>
    </detail>
</jasperReport>
</code>```

Subreport:

```<code><?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="e-topluSubreport" language="groovy" pageWidth="595" pageHeight="842" columnWidth="545" leftMargin="20" rightMargin="30" topMargin="20" bottomMargin="20" uuid="a3c2690b-2af8-4210-8775-cb69cd6557f7">
    <property name="ireport.zoom" value="1.5394743546921228"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <property name="ireport.background.image.properties" value="true,true,0.25,138,273,0,0,386,161"/>
    <parameter name="SUBREPORT_DIR" class="java.lang.String" isForPrompting="false">
        <defaultValueExpression><![CDATA["W:\\Projects\\modules\\common\\src\\resources\\report\\templates\\"]]></defaultValueExpression>
    </parameter>
    <parameter name="ANTET" class="java.io.InputStream"/>
    <parameter name="AY" class="java.lang.String"/>
    <detail>
        <band height="139" splitType="Stretch">
            <staticText>
                <reportElement x="5" y="105" width="185" height="15" uuid="023f69c4-13a4-419e-b64b-d41da9f937fa"/>
                <box>
                    <pen lineWidth="0.25"/>
                    <topPen lineWidth="0.25"/>
                    <leftPen lineWidth="0.25"/>
                    <bottomPen lineWidth="0.25"/>
                    <rightPen lineWidth="0.25"/>
                </box>
                <textElement verticalAlignment="Middle">
                    <font size="8" isBold="true" pdfEncoding="Cp1254"/>
                </textElement>
                <text><![CDATA[  BORDRO TÜRÜ  ]]></text>
            </staticText>
            <staticText>
                <reportElement x="5" y="120" width="185" height="15" uuid="e7aac3af-4436-4488-9b00-e93ed875119f"/>
                <box>
                    <pen lineWidth="0.25"/>
                    <topPen lineWidth="0.25"/>
                    <leftPen lineWidth="0.25"/>
                    <bottomPen lineWidth="0.25"/>
                    <rightPen lineWidth="0.25"/>
                </box>
                <textElement verticalAlignment="Middle">
                    <font size="8" isBold="true" pdfEncoding="Cp1254"/>
                </textElement>
                <text><![CDATA[  PARA BİRİMİ]]></text>
            </staticText>
            <staticText>
                <reportElement x="5" y="79" width="500" height="15" uuid="55328d4d-8ce4-44aa-9217-405be02338b6"/>
                <box>
                    <pen lineWidth="0.0"/>
                    <topPen lineWidth="0.0"/>
                    <leftPen lineWidth="0.0"/>
                    <bottomPen lineWidth="0.0"/>
                    <rightPen lineWidth="0.0"/>
                </box>
                <textElement verticalAlignment="Middle">
                    <font size="8" isBold="true" pdfEncoding="Cp1254"/>
                </textElement>
                <text><![CDATA[* test]]></text>
            </staticText>
            <image>
                <reportElement x="5" y="23" width="101" height="35" uuid="057a515d-61a7-4f54-9c5e-234acaede0e5"/>
                <imageExpression><![CDATA[$P{ANTET}]]></imageExpression>
            </image>
        </band>
        <band height="50"/>
    </detail>
</jasperReport>
</code>```

答: I found the solution. I remove the image from the subreport and put the image in the page header of the main report. It solved my problem but I am still wondering the previous problem why it shows only one record. Thanks for your comments and valuable time.</p>

Body:
I have a main report and subreport, and I pass a parameter to subreport as inputstream. I will use this parameter as a logo(image) in my subreport header. If I add the image to subreport and use this parameter, subreport shows only first record of my datasource and the image. If I do not use this image, my subreport lists all records of my datasource. I tried to put the image in detail, header, and title, but it did not work. If I use an image directly from subreport, it works well, but I need to send this parameter(filepath) from Java.

What can be the problem?

Edit: I provide some code.

Main report:

 <?xml version="1.0" encoding="UTF-8"?>
    <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="e-BordroIsciToplu" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="a3c2690b-2af8-4210-8775-cb69cd6557f7">
    <property name="ireport.zoom" value="1.5394743546921228"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <property name="ireport.background.image.properties" value="true,true,0.25,138,273,0,0,386,161"/>
    <parameter name="SUBREPORT_DIR" class="java.lang.String" isForPrompting="false">
        <defaultValueExpression><![CDATA["W:\\Projects\\modules\\common\\src\\resources\\report\\templates\\"]]></defaultValueExpression>
    </parameter>
    <parameter name="ANTET" class="java.io.InputStream"/>
    <parameter name="AY" class="java.lang.String"/>
    <field name="topluInfo" class="java.util.List"/>
    <detail>
        <band height="109" splitType="Stretch">
            <subreport runToBottom="false">
                <reportElement positionType="Float" stretchType="RelativeToTallestObject" x="0" y="0" width="533" height="100" uuid="cd6571c7-c8da-4120-868f-82999376c3d3"/>
                <parametersMapExpression><![CDATA[]]></parametersMapExpression>
                <subreportParameter name="SUBREPORT_DIR">
                    <subreportParameterExpression><![CDATA[]]>  </subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="AY">
                    <subreportParameterExpression><![CDATA[$P{AY}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="ANTET">
                    <subreportParameterExpression><![CDATA[$P{ANTET}]]></subreportParameterExpression>
                </subreportParameter>
                <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{topluInfo})]]></dataSourceExpression>
                <subreportExpression><![CDATA[$P{SUBREPORT_DIR} + "e-topluSubreportTest.jasper"]]></subreportExpression>
            </subreport>
        </band>
    </detail>
</jasperReport>

Subreport:

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="e-topluSubreport" language="groovy" pageWidth="595" pageHeight="842" columnWidth="545" leftMargin="20" rightMargin="30" topMargin="20" bottomMargin="20" uuid="a3c2690b-2af8-4210-8775-cb69cd6557f7">
    <property name="ireport.zoom" value="1.5394743546921228"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <property name="ireport.background.image.properties" value="true,true,0.25,138,273,0,0,386,161"/>
    <parameter name="SUBREPORT_DIR" class="java.lang.String" isForPrompting="false">
        <defaultValueExpression><![CDATA["W:\\Projects\\modules\\common\\src\\resources\\report\\templates\\"]]></defaultValueExpression>
    </parameter>
    <parameter name="ANTET" class="java.io.InputStream"/>
    <parameter name="AY" class="java.lang.String"/>
    <detail>
        <band height="139" splitType="Stretch">
            <staticText>
                <reportElement x="5" y="105" width="185" height="15" uuid="023f69c4-13a4-419e-b64b-d41da9f937fa"/>
                <box>
                    <pen lineWidth="0.25"/>
                    <topPen lineWidth="0.25"/>
                    <leftPen lineWidth="0.25"/>
                    <bottomPen lineWidth="0.25"/>
                    <rightPen lineWidth="0.25"/>
                </box>
                <textElement verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[  BORDRO TÜRÜ  ]]></text>
            </staticText>
            <staticText>
                <reportElement x="5" y="120" width="185" height="15" uuid="e7aac3af-4436-4488-9b00-e93ed875119f"/>
                <box>
                    <pen lineWidth="0.25"/>
                    <topPen lineWidth="0.25"/>
                    <leftPen lineWidth="0.25"/>
                    <bottomPen lineWidth="0.25"/>
                    <rightPen lineWidth="0.25"/>
                </box>
                <textElement verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[  PARA BİRİMİ]]></text>
            </staticText>
            <staticText>
                <reportElement x="5" y="79" width="500" height="15" uuid="55328d4d-8ce4-44aa-9217-405be02338b6"/>
                <box>
                    <pen lineWidth="0.0"/>
                    <topPen lineWidth="0.0"/>
                    <leftPen lineWidth="0.0"/>
                    <bottomPen lineWidth="0.0"/>
                    <rightPen lineWidth="0.0"/>
                </box>
                <textElement verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[* test]]></text>
            </staticText>
            <image>
                <reportElement x="5" y="23" width="101" height="35" uuid="057a515d-61a7-4f54-9c5e-234acaede0e5"/>
                <imageExpression><![CDATA[$P{ANTET}]]></imageExpression>
            </image>
        </band>
        <band height="50"/>
    </detail>
</jasperReport>


问:
PHP, SMTP - Subject in email shows International Characters as HTML_Entities
I've spent over half a day on this - just trying to get the email Subject to appear normal. But international characters appear as HTML_Entities when the email lands in the inbox.

For example: Tydzień o Jedność

Shows up as: Tydzień o Jedność

I already encode the email Subject for UTF-8:

$this->subject = "=?UTF-8?B?" . base64_encode($this->subject) . "?=";

When I get the email (Gmail), the header appears as:

Subject: =?UTF-8?B?VHlkemllJiMzMjQ7IG8gSmVkbm8mIzM0NzsmIzI2Mzs=?=

So it seems to encode properly. But for some reason, Gmail still displays the Subject with HTML_Entities.

Any ideas?

See code: SMTP mail class

答:
If it were me, I'd encode the string with

```<code>$this->subject = mb_encode_mimeheader($this->subject);
</code>```

Using your example string of Tydzień o Jedność, this produces the encoded output

```<code>=?UTF-8?B?VHlkemllw4XChCBvIEplZG5vw4XCm8OEwoc=?=
</code>```

The Subject header you gave in your question decodes to include the HTML entities:

```<code>echo mb_decode_mimeheader('=?UTF-8?B?VHlkemllJiMzMjQ7IG8gSmVkbm8mIzM0NzsmIzI2Mzs=?=');
</code>```

gives the string Tydzień o Jedność.  Presumably, the string got HTML encoded before it was base64 encoded.

Body:
If it were me, I'd encode the string with

$this->subject = mb_encode_mimeheader($this->subject);

Using your example string of Tydzień o Jedność, this produces the encoded output

=?UTF-8?B?VHlkemllw4XChCBvIEplZG5vw4XCm8OEwoc=?=

The Subject header you gave in your question decodes to include the HTML entities:

echo mb_decode_mimeheader('=?UTF-8?B?VHlkemllJiMzMjQ7IG8gSmVkbm8mIzM0NzsmIzI2Mzs=?=');

gives the string Tydzie&#324; o Jedno&#347;&#263;.  Presumably, the string got HTML encoded before it was base64 encoded.


问:
Is there a way to show slide up panel that shows more data when user slides it up?

I would like to have ability to slide up and down the panel to see more data as seen in the image.  Prefer to have cross platform solution. I have tried to use the SlideOverKit but it does not seem to have this sort of ability - or could I be wrong?  Would there be a better solution out there for such a scenario?

答:
There are many way to achieve a sliding panel, here is one using a PanGestureRecognizer for a swipe up / down on an absolute layout:

```<code><AbsoluteLayout BackgroundColor="Silver" AbsoluteLayout.LayoutBounds="0,1,1,1">
<!--
    Your page's content here
-->
    <StackLayout x:Name="bottomDrawer" BackgroundColor="Olive" AbsoluteLayout.LayoutBounds="0.5,1.00,0.9,0.04" AbsoluteLayout.LayoutFlags="All">
        <StackLayout.GestureRecognizers>
            <PanGestureRecognizer PanUpdated="PanGestureHandler" />
        </StackLayout.GestureRecognizers>
<!--
    Your sliding panel's content here
-->
        <Label x:Name="swipeLabel" Text="Swipe me up" TextColor="Black" HorizontalOptions="Center" />
        <Button Text="Click Me" BackgroundColor="Silver" TextColor="Black" BorderColor="Gray" BorderWidth="5" BorderRadius="20" />
        <Image Source="whome" />
    </StackLayout>
</AbsoluteLayout>
</code>```

The PanGestureRecognizer handler:

```<code>double? layoutHeight;
double layoutBoundsHeight;
int direction;
const double layoutPropHeightMax = 0.75;
const double layoutPropHeightMin = 0.04;
void PanGestureHandler(object sender, PanUpdatedEventArgs e)
{
    layoutHeight = layoutHeight ?? ((sender as StackLayout).Parent as AbsoluteLayout).Height;
    switch (e.StatusType)
    {
        case GestureStatus.Started:
            layoutBoundsHeight = AbsoluteLayout.GetLayoutBounds(sender as StackLayout).Height;
            break;
        case GestureStatus.Running:
            direction = e.TotalY < 0 ? 1 : -1;
            break;
        case GestureStatus.Completed:
            if (direction > 0) // snap to max/min, you could use an animation....
            {
                AbsoluteLayout.SetLayoutBounds(bottomDrawer, new Rectangle(0.5, 1.00, 0.9, layoutPropHeightMax));
                swipeLabel.Text = "Swipe me down";
            }
            else
            {
                AbsoluteLayout.SetLayoutBounds(bottomDrawer, new Rectangle(0.5, 1.00, 0.9, layoutPropHeightMin));
                swipeLabel.Text = "Swipe me up";
            }
            break;
    }
}
</code>```

You can add dragging to the pan gesture by setting the "panel" size in the GestureStatus.Running case statement. Something like will get you started:

```<code>case GestureStatus.Running:
    direction = e.TotalY < 0 ? 1 : -1;
    var yProp = layoutBoundsHeight + (-e.TotalY / (double)layoutHeight);
    if ((yProp > layoutPropHeightMin) & (yProp < layoutPropHeightMax))
        AbsoluteLayout.SetLayoutBounds(bottomDrawer, new Rectangle(0.5, 1.00, 0.9, yProp));
    break;
</code>```

Note: Personally I would use this style of dragging as a prototype only as it is glitchy. I would write a custom renderer per platform to avoid the Forms' layout manager.

Body:
There are many way to achieve a sliding panel, here is one using a PanGestureRecognizer for a swipe up / down on an absolute layout:

<AbsoluteLayout BackgroundColor="Silver" AbsoluteLayout.LayoutBounds="0,1,1,1">
<!--
    Your page's content here
-->
    <StackLayout x:Name="bottomDrawer" BackgroundColor="Olive" AbsoluteLayout.LayoutBounds="0.5,1.00,0.9,0.04" AbsoluteLayout.LayoutFlags="All">
        <StackLayout.GestureRecognizers>
            <PanGestureRecognizer PanUpdated="PanGestureHandler" />
        </StackLayout.GestureRecognizers>
<!--
    Your sliding panel's content here
-->
        <Label x:Name="swipeLabel" Text="Swipe me up" TextColor="Black" HorizontalOptions="Center" />
        <Button Text="Click Me" BackgroundColor="Silver" TextColor="Black" BorderColor="Gray" BorderWidth="5" BorderRadius="20" />
        <Image Source="whome" />
    </StackLayout>
</AbsoluteLayout>

The PanGestureRecognizer handler:

double? layoutHeight;
double layoutBoundsHeight;
int direction;
const double layoutPropHeightMax = 0.75;
const double layoutPropHeightMin = 0.04;
void PanGestureHandler(object sender, PanUpdatedEventArgs e)
{
    layoutHeight = layoutHeight ?? ((sender as StackLayout).Parent as AbsoluteLayout).Height;
    switch (e.StatusType)
    {
        case GestureStatus.Started:
            layoutBoundsHeight = AbsoluteLayout.GetLayoutBounds(sender as StackLayout).Height;
            break;
        case GestureStatus.Running:
            direction = e.TotalY < 0 ? 1 : -1;
            break;
        case GestureStatus.Completed:
            if (direction > 0) // snap to max/min, you could use an animation....
            {
                AbsoluteLayout.SetLayoutBounds(bottomDrawer, new Rectangle(0.5, 1.00, 0.9, layoutPropHeightMax));
                swipeLabel.Text = "Swipe me down";
            }
            else
            {
                AbsoluteLayout.SetLayoutBounds(bottomDrawer, new Rectangle(0.5, 1.00, 0.9, layoutPropHeightMin));
                swipeLabel.Text = "Swipe me up";
            }
            break;
    }
}

You can add dragging to the pan gesture by setting the "panel" size in the GestureStatus.Running case statement. Something like will get you started:

case GestureStatus.Running:
    direction = e.TotalY < 0 ? 1 : -1;
    var yProp = layoutBoundsHeight + (-e.TotalY / (double)layoutHeight);
    if ((yProp > layoutPropHeightMin) & (yProp < layoutPropHeightMax))
        AbsoluteLayout.SetLayoutBounds(bottomDrawer, new Rectangle(0.5, 1.00, 0.9, yProp));
    break;

Note: Personally I would use this style of dragging as a prototype only as it is glitchy. I would write a custom renderer per platform to avoid the Forms' layout manager.


问:
How to access a method from another class without using extends keyword?
I have a main class followed by two sub classes.

As below

```<code>public class Guitar  {

   public static void main(String argd[]) {
       Artist output = new Artist();
       output.perfomance();
   }
}

  class Artist  {
    String Name;
    void perfomance () {

    }

  }

  class Album {

  }
</code>```

Is it possible to call method performance from Artist class and use it in Album class without extends keyword?

答:
You could use composition instead of inheritance.

If Album extends Artist then you are suggesting the and Album IS-A Artist.
However if an Album has an Artist as a member then Album HAS-A Artist.

See IS-A vs HAS-A

So one approach might be to do

```<code>class Album {
  Artist artist;

  Album(Artist artist) {
    this.artist = artist;
  }

  void playLive() {
    artist.performance();
  }
}
</code>```

So to call you might do

```<code>public class Guitar  {

  public static void main(String[] args) {
     Artist prince = new Artist();
     Album purpleRain = new Album(prince);
     purpleRain.playLive();
  }
}
</code>```

Body:
I have a main class followed by two sub classes.

As below

public class Guitar  {

   public static void main(String argd[]) {
       Artist output = new Artist();
       output.perfomance();
   }
}

  class Artist  {
    String Name;
    void perfomance () {

    }

  }

  class Album {

  }

Is it possible to call method performance from Artist class and use it in Album class without extends keyword?

Body:
You could use composition instead of inheritance.

If Album extends Artist then you are suggesting the and Album IS-A Artist.
However if an Album has an Artist as a member then Album HAS-A Artist.

See IS-A vs HAS-A

So one approach might be to do

class Album {
  Artist artist;

  Album(Artist artist) {
    this.artist = artist;
  }

  void playLive() {
    artist.performance();
  }
}

So to call you might do

public class Guitar  {

  public static void main(String[] args) {
     Artist prince = new Artist();
     Album purpleRain = new Album(prince);
     purpleRain.playLive();
  }
}


问:
jQuery autocomplete - need to initiate only when a special character is typed
I'm sure you guys have seen this excellent plugin:

http://code.drewwilson.com/entry/autosuggest-jquery-plugin

I checked it out and could not find an option to initiate the autosuggest plugin only when a specific character is typed. In this case I need it to be the at sign '@'.

I see it has the option to set a minimum number of characters:
minChars: number (1 by default)

However, I need for the dropdown to NOT show until the @ sign is typed.

FYI, here are the options in jquery.autoSuggest.js

```<code>        var defaults = {
        asHtmlID: false,
        startText: "Enter Name Here",
        emptyText: "No Results Found",
        preFill: {},
        limitText: "No More Selections Are Allowed",
        selectedItemProp: "value", //name of object property
        selectedValuesProp: "value", //name of object property
        searchObjProps: "value", //comma separated list of object property names
        queryParam: "q",
        retrieveLimit: false, //number for 'limit' param on ajax request
        extraParams: "",
        matchCase: false,
        minChars: 1,
        keyDelay: 400,
        resultsHighlight: true,
        neverSubmit: false,
        selectionLimit: false,
        showResultList: true,
        start: function(){},
        selectionClick: function(elem){},
        selectionAdded: function(elem){},
        selectionRemoved: function(elem){ elem.remove(); },
        formatList: false, //callback function
        beforeRetrieve: function(string){ return string; },
        retrieveComplete: function(data){ return data; },
        resultClick: function(data){},
        resultsComplete: function(){}
    };
    var opts = $
</code>```

Thanks!

答:
I have never used this control before, but it looks like you're going to want to look into the jquery.autoSuggest.js file (non minified). Check out this case statement. I think you'll need to change the default: case to case x: where x is the ascii code for the key you want to use to trigger the autocomplete.

```<code>                switch(e.keyCode) {
                    case 38: // up
                        e.preventDefault();
                        moveSelection("up");
                        break;
                    case 40: // down
                        e.preventDefault();
                        moveSelection("down");
                        break;
                    case 8:  // delete
                        if(input.val() == ""){
                            var last = values_input.val().split(",");
                            last = last[last.length - 2];
                            selections_holder.children().not(org_li.prev()).removeClass("selected");
                            if(org_li.prev().hasClass("selected")){
                                values_input.val(values_input.val().replace(","+last+",",","));
                                opts.selectionRemoved.call(this, org_li.prev());
                            } else {
                                opts.selectionClick.call(this, org_li.prev());
                                org_li.prev().addClass("selected");
                            }
                        }
                        if(input.val().length == 1){
                            results_holder.hide();
                             prev = "";
                        }
                        if($(":visible",results_holder).length > 0){
                            if (timeout){ clearTimeout(timeout); }
                            timeout = setTimeout(function(){ keyChange(); }, opts.keyDelay);
                        }
                        break;
                    case 9: case 188:  // tab or comma
                        tab_press = true;
                        var i_input = input.val().replace(/(,)/g, "");
                        if(i_input != "" && values_input.val().search(","+i_input+",") < 0 && i_input.length >= opts.minChars){
                            e.preventDefault();
                            var n_data = {};
                            n_data[opts.selectedItemProp] = i_input;
                            n_data[opts.selectedValuesProp] = i_input;
                            var lis = $("li", selections_holder).length;
                            add_selected_item(n_data, "00"+(lis+1));
                            input.val("");
                        }
                    case 13: // return
                        tab_press = false;
                        var active = $("li.active:first", results_holder);
                        if(active.length > 0){
                            active.click();
                            results_holder.hide();
                        }
                        if(opts.neverSubmit || active.length > 0){
                            e.preventDefault();
                        }
                        break;
                    default:
                        if(opts.showResultList){
                            if(opts.selectionLimit && $("li.as-selection-item", selections_holder).length >= opts.selectionLimit){
                                results_ul.html('<li class="as-message">'+opts.limitText+'</li>');
                                results_holder.show();
                            } else {
                                if (timeout){ clearTimeout(timeout); }
                                timeout = setTimeout(function(){ keyChange(); }, opts.keyDelay);
                            }
                        }
                        break;
                }
</code>```

Could be more like this

```<code>                switch(e.keyCode) {
                    case 38: // up
                        e.preventDefault();
                        moveSelection("up");
                        break;
                    case 40: // down
                        e.preventDefault();
                        moveSelection("down");
                        break;
                    case 8:  // delete
                        if(input.val() == ""){
                            var last = values_input.val().split(",");
                            last = last[last.length - 2];
                            selections_holder.children().not(org_li.prev()).removeClass("selected");
                            if(org_li.prev().hasClass("selected")){
                                values_input.val(values_input.val().replace(","+last+",",","));
                                opts.selectionRemoved.call(this, org_li.prev());
                            } else {
                                opts.selectionClick.call(this, org_li.prev());
                                org_li.prev().addClass("selected");
                            }
                        }
                        if(input.val().length == 1){
                            results_holder.hide();
                             prev = "";
                        }
                        if($(":visible",results_holder).length > 0){
                            if (timeout){ clearTimeout(timeout); }
                            timeout = setTimeout(function(){ keyChange(); }, opts.keyDelay);
                        }
                        break;
                    case 9: case 188:  // tab or comma
                        tab_press = true;
                        var i_input = input.val().replace(/(,)/g, "");
                        if(i_input != "" && values_input.val().search(","+i_input+",") < 0 && i_input.length >= opts.minChars){
                            e.preventDefault();
                            var n_data = {};
                            n_data[opts.selectedItemProp] = i_input;
                            n_data[opts.selectedValuesProp] = i_input;
                            var lis = $("li", selections_holder).length;
                            add_selected_item(n_data, "00"+(lis+1));
                            input.val("");
                        }
                    case 13: // return
                        tab_press = false;
                        var active = $("li.active:first", results_holder);
                        if(active.length > 0){
                            active.click();
                            results_holder.hide();
                        }
                        if(opts.neverSubmit || active.length > 0){
                            e.preventDefault();
                        }
                        break;
                    case x:
                        if(opts.showResultList){
                            if(opts.selectionLimit && $("li.as-selection-item", selections_holder).length >= opts.selectionLimit){
                                results_ul.html('<li class="as-message">'+opts.limitText+'</li>');
                                results_holder.show();
                            } else {
                                if (timeout){ clearTimeout(timeout); }
                                timeout = setTimeout(function(){ keyChange(); }, opts.keyDelay);
                            }
                        }
                        break;
                    default:
                            //Do Nothing
                }
</code>```

Body:
I'm sure you guys have seen this excellent plugin:

http://code.drewwilson.com/entry/autosuggest-jquery-plugin

I checked it out and could not find an option to initiate the autosuggest plugin only when a specific character is typed. In this case I need it to be the at sign '@'.

I see it has the option to set a minimum number of characters:
minChars: number (1 by default)

However, I need for the dropdown to NOT show until the @ sign is typed.

FYI, here are the options in jquery.autoSuggest.js

        var defaults = {
        asHtmlID: false,
        startText: "Enter Name Here",
        emptyText: "No Results Found",
        preFill: {},
        limitText: "No More Selections Are Allowed",
        selectedItemProp: "value", //name of object property
        selectedValuesProp: "value", //name of object property
        searchObjProps: "value", //comma separated list of object property names
        queryParam: "q",
        retrieveLimit: false, //number for 'limit' param on ajax request
        extraParams: "",
        matchCase: false,
        minChars: 1,
        keyDelay: 400,
        resultsHighlight: true,
        neverSubmit: false,
        selectionLimit: false,
        showResultList: true,
        start: function(){},
        selectionClick: function(elem){},
        selectionAdded: function(elem){},
        selectionRemoved: function(elem){ elem.remove(); },
        formatList: false, //callback function
        beforeRetrieve: function(string){ return string; },
        retrieveComplete: function(data){ return data; },
        resultClick: function(data){},
        resultsComplete: function(){}
    };
    var opts = $

Thanks!

Body:
I have never used this control before, but it looks like you're going to want to look into the jquery.autoSuggest.js file (non minified). Check out this case statement. I think you'll need to change the default: case to case x: where x is the ascii code for the key you want to use to trigger the autocomplete.

                switch(e.keyCode) {
                    case 38: // up
                        e.preventDefault();
                        moveSelection("up");
                        break;
                    case 40: // down
                        e.preventDefault();
                        moveSelection("down");
                        break;
                    case 8:  // delete
                        if(input.val() == ""){
                            var last = values_input.val().split(",");
                            last = last[last.length - 2];
                            selections_holder.children().not(org_li.prev()).removeClass("selected");
                            if(org_li.prev().hasClass("selected")){
                                values_input.val(values_input.val().replace(","+last+",",","));
                                opts.selectionRemoved.call(this, org_li.prev());
                            } else {
                                opts.selectionClick.call(this, org_li.prev());
                                org_li.prev().addClass("selected");
                            }
                        }
                        if(input.val().length == 1){
                            results_holder.hide();
                             prev = "";
                        }
                        if($(":visible",results_holder).length > 0){
                            if (timeout){ clearTimeout(timeout); }
                            timeout = setTimeout(function(){ keyChange(); }, opts.keyDelay);
                        }
                        break;
                    case 9: case 188:  // tab or comma
                        tab_press = true;
                        var i_input = input.val().replace(/(,)/g, "");
                        if(i_input != "" && values_input.val().search(","+i_input+",") < 0 && i_input.length >= opts.minChars){
                            e.preventDefault();
                            var n_data = {};
                            n_data[opts.selectedItemProp] = i_input;
                            n_data[opts.selectedValuesProp] = i_input;
                            var lis = $("li", selections_holder).length;
                            add_selected_item(n_data, "00"+(lis+1));
                            input.val("");
                        }
                    case 13: // return
                        tab_press = false;
                        var active = $("li.active:first", results_holder);
                        if(active.length > 0){
                            active.click();
                            results_holder.hide();
                        }
                        if(opts.neverSubmit || active.length > 0){
                            e.preventDefault();
                        }
                        break;
                    default:
                        if(opts.showResultList){
                            if(opts.selectionLimit && $("li.as-selection-item", selections_holder).length >= opts.selectionLimit){
                                results_ul.html('<li class="as-message">'+opts.limitText+'</li>');
                                results_holder.show();
                            } else {
                                if (timeout){ clearTimeout(timeout); }
                                timeout = setTimeout(function(){ keyChange(); }, opts.keyDelay);
                            }
                        }
                        break;
                }

Could be more like this

                switch(e.keyCode) {
                    case 38: // up
                        e.preventDefault();
                        moveSelection("up");
                        break;
                    case 40: // down
                        e.preventDefault();
                        moveSelection("down");
                        break;
                    case 8:  // delete
                        if(input.val() == ""){
                            var last = values_input.val().split(",");
                            last = last[last.length - 2];
                            selections_holder.children().not(org_li.prev()).removeClass("selected");
                            if(org_li.prev().hasClass("selected")){
                                values_input.val(values_input.val().replace(","+last+",",","));
                                opts.selectionRemoved.call(this, org_li.prev());
                            } else {
                                opts.selectionClick.call(this, org_li.prev());
                                org_li.prev().addClass("selected");
                            }
                        }
                        if(input.val().length == 1){
                            results_holder.hide();
                             prev = "";
                        }
                        if($(":visible",results_holder).length > 0){
                            if (timeout){ clearTimeout(timeout); }
                            timeout = setTimeout(function(){ keyChange(); }, opts.keyDelay);
                        }
                        break;
                    case 9: case 188:  // tab or comma
                        tab_press = true;
                        var i_input = input.val().replace(/(,)/g, "");
                        if(i_input != "" && values_input.val().search(","+i_input+",") < 0 && i_input.length >= opts.minChars){
                            e.preventDefault();
                            var n_data = {};
                            n_data[opts.selectedItemProp] = i_input;
                            n_data[opts.selectedValuesProp] = i_input;
                            var lis = $("li", selections_holder).length;
                            add_selected_item(n_data, "00"+(lis+1));
                            input.val("");
                        }
                    case 13: // return
                        tab_press = false;
                        var active = $("li.active:first", results_holder);
                        if(active.length > 0){
                            active.click();
                            results_holder.hide();
                        }
                        if(opts.neverSubmit || active.length > 0){
                            e.preventDefault();
                        }
                        break;
                    case x:
                        if(opts.showResultList){
                            if(opts.selectionLimit && $("li.as-selection-item", selections_holder).length >= opts.selectionLimit){
                                results_ul.html('<li class="as-message">'+opts.limitText+'</li>');
                                results_holder.show();
                            } else {
                                if (timeout){ clearTimeout(timeout); }
                                timeout = setTimeout(function(){ keyChange(); }, opts.keyDelay);
                            }
                        }
                        break;
                    default:
                            //Do Nothing
                }


问:
Vertically aling form with bootstrap 4
I am using bootstrap 4 beta 2 and I am not able to center a form on the page...

This is the link with my code

https://codepen.io/davidrodri/pen/jawpeJ

```<code><div class="container">
  <div class="row justify-content-center h-100 align-middle">
    <div class="align-self-center">
        <form>
          <h2 class="text-center">Benvenuto</h2>
            <div class="form-group">
                <label for="username">Utente</label>
                <input type="text"  class="form-control"  id="username" >
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <input type="password" class="form-control"  id="password" >
            </div>
            <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
        </form>
    </div>
  </div>
</div>
</code>```

答:
Apply following css to parent div

Updated cdoepen https://codepen.io/anon/pen/oowaav

```<code>.parentdiv{
    align-items: center;
    display: flex;
    height: 100vh;
}
</code>```

Title: Vertically aling form with bootstrap 4

Body:
I am using bootstrap 4 beta 2 and I am not able to center a form on the page...

This is the link with my code

https://codepen.io/davidrodri/pen/jawpeJ

        <form>

Benvenuto

                Utente
                <input type="text"  class="form-control"  id="username" >

                Password
                <input type="password" class="form-control"  id="password" >

            <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
        </form>

Body:
Apply following css to parent div

Updated cdoepen https://codepen.io/anon/pen/oowaav

.parentdiv{
    align-items: center;
    display: flex;
    height: 100vh;
}


问:
Trying to remove a RecycleView item(Loaded from webservices) by swiping left or right
I was trying to remove a particular listitem of a recyclerview which is loaded the data from Url.

Here is my MainActivity

```<code>    public class MainActivity extends AppCompatActivity {
    String responseFromServer;
    Button btnGetData;
    RecyclerView rView;
    ProgressDialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnGetData = (Button)findViewById(R.id.btnGetData);
        rView = (RecyclerView)findViewById(R.id.rVIew);
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Please Wait");
        LinearLayoutManager manager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        rView.setLayoutManager(manager);
        btnGetData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               refreshAdapter();
            }
        });

    }
    class PlacesTask extends AsyncTask<String,String,String>
    {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... strings) {
            WebMethods methods = new WebMethods();
            responseFromServer = methods.getData();
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            pDialog.dismiss();
            setOutData(responseFromServer);
        }
    }
    public void setOutData(String  response)
    {
        ParserClass parserClass = new ParserClass();
        ArrayList<PlacesData> data = parserClass.getData(response);
        final MyRecyclerAdapter adapter = new MyRecyclerAdapter(MainActivity.this,data);
        rView.setAdapter(adapter);

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                rView.removeViewAt(viewHolder.getAdapterPosition());
               // adapter.notifyDataSetChanged();
             //   adapter.notifyItemRemoved(viewHolder.getAdapterPosition());

                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
               //adapter.notifyItemChanged(viewHolder.getAdapterPosition());
               // adapter.notifyItemRemoved(viewHolder.getAdapterPosition());

            }
        });
        itemTouchHelper.attachToRecyclerView(rView);
    }
    public void refreshAdapter()
    {
        PlacesTask task = new PlacesTask();
        task.execute();
    }
}
</code>```

and my Adapter class is

MyRecyclerAdapter.java

```<code>    public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecycler> {
    MainActivity activity;
    LayoutInflater inflater;
    ArrayList<PlacesData> data;
    public MyRecyclerAdapter(MainActivity activity,ArrayList<PlacesData> data)
    {
        inflater = LayoutInflater.from(activity);
        this.activity =activity;
        this.data = data;
    }
    @Override
    public MyRecycler onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.singleitem,null);
        MyRecycler recycler = new MyRecycler(view);
        return recycler;
    }

    @Override
    public void onBindViewHolder(MyRecycler holder, final int position) {
        holder.tvName.setText(data.get(position).getName());
        holder.tvRating.setText(data.get(position).getRating());
        Picasso.with(activity).load(data.get(position).getIcon()).into(holder.imgIcon);
        holder.btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                data.remove(data.get(position));
                notifyDataSetChanged();
            }
        });
    }

    @Override
    public int getItemCount() {
        return data.size();
    }
}
</code>```

While using the delete button it is working fine but by swiping it is not working it is showing empty space and the adapter is not updating properly.

I am new this swipe deletion process i was learning it so suggest me possible changes or suggest me any best approach to do this

I have swiped two list items but the space is showing.. i have tried all

```<code>        adapter.notifyDataSetChanged();
        adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
        adapter.notifyItemChanged(viewHolder.getAdapterPosition());
</code>```

答:
```<code>By These Changes I got the solution

 ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {

            return false;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            data.remove(data.get(viewHolder.getAdapterPosition()));
            adapter.notifyDataSetChanged();

        }
    });
    itemTouchHelper.attachToRecyclerView(rView);
    adapter.notifyDataSetChanged();
</code>```

Thanks for your support

Body:
I was trying to remove a particular listitem of a recyclerview which is loaded the data from Url.

Here is my MainActivity

    public class MainActivity extends AppCompatActivity {
    String responseFromServer;
    Button btnGetData;
    RecyclerView rView;
    ProgressDialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnGetData = (Button)findViewById(R.id.btnGetData);
        rView = (RecyclerView)findViewById(R.id.rVIew);
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Please Wait");
        LinearLayoutManager manager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        rView.setLayoutManager(manager);
        btnGetData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               refreshAdapter();
            }
        });

    }
    class PlacesTask extends AsyncTask<String,String,String>
    {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... strings) {
            WebMethods methods = new WebMethods();
            responseFromServer = methods.getData();
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            pDialog.dismiss();
            setOutData(responseFromServer);
        }
    }
    public void setOutData(String  response)
    {
        ParserClass parserClass = new ParserClass();
        ArrayList<PlacesData> data = parserClass.getData(response);
        final MyRecyclerAdapter adapter = new MyRecyclerAdapter(MainActivity.this,data);
        rView.setAdapter(adapter);

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                rView.removeViewAt(viewHolder.getAdapterPosition());
               // adapter.notifyDataSetChanged();
             //   adapter.notifyItemRemoved(viewHolder.getAdapterPosition());

                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
               //adapter.notifyItemChanged(viewHolder.getAdapterPosition());
               // adapter.notifyItemRemoved(viewHolder.getAdapterPosition());

            }
        });
        itemTouchHelper.attachToRecyclerView(rView);
    }
    public void refreshAdapter()
    {
        PlacesTask task = new PlacesTask();
        task.execute();
    }
}

and my Adapter class is

MyRecyclerAdapter.java

    public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecycler> {
    MainActivity activity;
    LayoutInflater inflater;
    ArrayList<PlacesData> data;
    public MyRecyclerAdapter(MainActivity activity,ArrayList<PlacesData> data)
    {
        inflater = LayoutInflater.from(activity);
        this.activity =activity;
        this.data = data;
    }
    @Override
    public MyRecycler onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.singleitem,null);
        MyRecycler recycler = new MyRecycler(view);
        return recycler;
    }

    @Override
    public void onBindViewHolder(MyRecycler holder, final int position) {
        holder.tvName.setText(data.get(position).getName());
        holder.tvRating.setText(data.get(position).getRating());
        Picasso.with(activity).load(data.get(position).getIcon()).into(holder.imgIcon);
        holder.btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                data.remove(data.get(position));
                notifyDataSetChanged();
            }
        });
    }

    @Override
    public int getItemCount() {
        return data.size();
    }
}

While using the delete button it is working fine but by swiping it is not working it is showing empty space and the adapter is not updating properly.

I am new this swipe deletion process i was learning it so suggest me possible changes or suggest me any best approach to do this

I have swiped two list items but the space is showing.. i have tried all

        adapter.notifyDataSetChanged();
        adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
        adapter.notifyItemChanged(viewHolder.getAdapterPosition());

Body:
By These Changes I got the solution

 ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {

            return false;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            data.remove(data.get(viewHolder.getAdapterPosition()));
            adapter.notifyDataSetChanged();

        }
    });
    itemTouchHelper.attachToRecyclerView(rView);
    adapter.notifyDataSetChanged();

Thanks for your support