问:
How to open a excel file after it gets downloaded in javascript?
I download an excel file (.xls) by using below code:

JavaScript Code:

window.location = result.filename;

After downloading, I want to open a excel file automatically  without clicking on it. I want JavaScript code for opening excel file automatically.

I tested with following function code. But it runs only in Internet Explorer, not in Mozilla, Chrome...

```<code>function openExcelFile(strFilePath) {
var objExcel;
objExcel = new ActiveXObject("Excel.Application");
objExcel.Visible = true;
objExcel.Workbooks.Open(strFilePath);
}
</code>```

By using above code, the excel file open automatically after it gets downloaded in Internet Explorer.

I want JavaScript code for opening excel file automatically after downloaded by working in all browsers.

How can I achieve this?

答:
pass the excel file path to the controller. it will works fine with all browsers.</p>

```<code>public ActionResult GetFile(string path)
{

    string extension = new FileInfo(path).Extension;
    if (extension != null || extension != string.Empty)
    {
        switch (extension)
        {
            case ".xls":
                return File(path, "application/vnd.ms-excel");
            case ".xlsx":
                return File(path, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        }
    }
    return View("Index");
}
</code>```

Body:
I download an excel file (.xls) by using below code:

JavaScript Code:

window.location = result.filename;

After downloading, I want to open a excel file automatically  without clicking on it. I want JavaScript code for opening excel file automatically.

I tested with following function code. But it runs only in Internet Explorer, not in Mozilla, Chrome...

function openExcelFile(strFilePath) {
var objExcel;
objExcel = new ActiveXObject("Excel.Application");
objExcel.Visible = true;
objExcel.Workbooks.Open(strFilePath);
}

By using above code, the excel file open automatically after it gets downloaded in Internet Explorer.

I want JavaScript code for opening excel file automatically after downloaded by working in all browsers.

How can I achieve this?

Body:
pass the excel file path to the controller. it will works fine with all browsers.

public ActionResult GetFile(string path)
{

    string extension = new FileInfo(path).Extension;
    if (extension != null || extension != string.Empty)
    {
        switch (extension)
        {
            case ".xls":
                return File(path, "application/vnd.ms-excel");
            case ".xlsx":
                return File(path, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        }
    }
    return View("Index");
}


来源: stackexchange

问:
Error in SQL Syntax use near '06:09:43 WHERE Book_id = 19 AND Date_issued = 2017-03-29 17:28:34' at line 1

ERROR: Could not able to execute You have an error in your SQL syntax;
  check the manual that corresponds to your MariaDB server version for
  the right syntax to use near '06:09:43 WHERE Book_id = 19 AND
  Date_issued = 2017-03-29 17:28:34' at line 1

I've been getting the above error upon executing the following code -

```<code>if(isset($_GET['rt']))//rt is a variable I'm passing in an anchor tag
{
$dateis=$_GET['rt'];
}
if(isset($_GET['id']))//id is also sent along with rt
{
$bk_id=$_GET['id'];
}
$ret = 'returned successfully';
$date = date('Y-m-d H:i:s');
if(mysqli_query($conn, "UPDATE issued_books SET Date_returned = $date WHERE Book_id = $bk_id AND Date_issued = $dateis"))
{
    $fine = mysqli_query($conn, "SELECT DATEDIFF('$dateis', '$date') AS days");
    $fine = $fine*10;
    mysqli_query($conn, "UPDATE issued_books SET Fine_amt = (Fine_amt + $fine) WHERE Date_issued = $dateis");
    mysqli_query($conn, "UPDATE library_books SET Available = (Available + 1) WHERE Book_id = $bk_id");
    header("Location: return-books.php?book=".urlencode($ret));
} else{
    echo "ERROR: Could not able to execute " .mysqli_error($conn);
}
</code>```

答:
In your first update query use ' single quotes here

```<code> Date_returned = '$date'
</code>```

I also suggest to use pdo

ContentLicense: CC BY-SA 3.0

Body:
ERROR: Could not able to execute You have an error in your SQL syntax;
  check the manual that corresponds to your MariaDB server version for
  the right syntax to use near '06:09:43 WHERE Book_id = 19 AND
  Date_issued = 2017-03-29 17:28:34' at line 1

I've been getting the above error upon executing the following code -

if(isset($_GET['rt']))//rt is a variable I'm passing in an anchor tag
{
$dateis=$_GET['rt'];
}
if(isset($_GET['id']))//id is also sent along with rt
{
$bk_id=$_GET['id'];
}
$ret = 'returned successfully';
$date = date('Y-m-d H:i:s');
if(mysqli_query($conn, "UPDATE issued_books SET Date_returned = $date WHERE Book_id = $bk_id AND Date_issued = $dateis"))
{
    $fine = mysqli_query($conn, "SELECT DATEDIFF('$dateis', '$date') AS days");
    $fine = $fine*10;
    mysqli_query($conn, "UPDATE issued_books SET Fine_amt = (Fine_amt + $fine) WHERE Date_issued = $dateis");
    mysqli_query($conn, "UPDATE library_books SET Available = (Available + 1) WHERE Book_id = $bk_id");
    header("Location: return-books.php?book=".urlencode($ret));
} else{
    echo "ERROR: Could not able to execute " .mysqli_error($conn);
}

Body:
In your first update query use ' single quotes here

 Date_returned = '$date'

I also suggest to use pdo


问:
How do I dynamically assign properties to an object in TypeScript?
If I wanted to programatically assign a property to an object in Javascript, I would do it like this:

```<code>var obj = {};
obj.prop = "value";
</code>```

But in TypeScript, this generates an error:

The property 'prop' does not exist on value of type '{}'

How am I supposed to assign any new property to an object in TypeScript?

答:
dynamically assign properties to an object in TypeScript.

to do that You just need to use typescript interfaces like so:

```<code>interface IValue {
    prop1: string;
    prop2: string;
}

interface IType {
    [code: string]: IValue;
}
</code>```

you can use it like that

```<code>var obj: IType = {};
obj['code1'] = {
    prop1: 'prop 1 value',
    prop2: 'prop 2 value'
};
</code>```

Body:
If I wanted to programatically assign a property to an object in Javascript, I would do it like this:

var obj = {};
obj.prop = "value";

But in TypeScript, this generates an error:

The property 'prop' does not exist on value of type '{}'

How am I supposed to assign any new property to an object in TypeScript?

Body:
dynamically assign properties to an object in TypeScript.

to do that You just need to use typescript interfaces like so:

interface IValue {
    prop1: string;
    prop2: string;
}

interface IType {
    [code: string]: IValue;
}

you can use it like that

var obj: IType = {};
obj['code1'] = {
    prop1: 'prop 1 value',
    prop2: 'prop 2 value'
};

ContentLicense: CC BY-SA 4.0


问:
Inconsistency between $ and ^ in regex when using start/end arguments to re.search?
From what I've read, ^ should match the start of a string, and $ the end. However, with re.search(), it looks like the behavior of ^ continues to work fine, while $ 'breaks'. Example:

```<code>>>> a = re.compile( "^a" )
>>> print a.search( "cat", 1, 3 )
None
</code>```

This seems correct to me -- 'a' is not at the start of the string, even if it is at the start of the search.

```<code>>>> a = re.compile( "a$" )
>>> print a.search( "cat", 0, 2 )
<_sre.SRE_Match object at 0x7f41df2334a8>
</code>```

This seems wrong to me, or inconsistent at least.

The documentation on the re module explicitly mentions that the behavior of ^ does not change due to start/end arguments to re.search, but no change in behavior is mentioned for $ (that I've seen).

Can anyone explain why things were designed this way, and/or suggest a convenient workaround?

By workaround, I would like to compose a regex which always matches the end of the string, even when someone uses the end argument to re.search.

And why was re.search designed such that:

```<code>s.search( string, endPos=len(string) - 1 )
</code>```

is the same as

```<code>s.search( string[:-1] )
</code>```

when

```<code>s.search( string, startPos=1 )
</code>```

is explicitly and intentionally not the same as

```<code>s.search( string[1:] )
</code>```

It seems to be less an issue of inconsistency between ^ and $, and more of an inconsistency within the re.search function.

答:
According to the search() documentation here:

The optional parameter endpos limits how far the string will be searched; it will be as if the string is endpos characters long, so only the characters from pos to endpos - 1 will be searched for a match.

So your syntax, a.search("cat", 0, 2) is equivalent to a.search("ca"), which does match the pattern a$.

Body:
From what I've read, ^ should match the start of a string, and $ the end. However, with re.search(), it looks like the behavior of ^ continues to work fine, while $ 'breaks'. Example:

>>> a = re.compile( "^a" )
>>> print a.search( "cat", 1, 3 )
None

This seems correct to me -- 'a' is not at the start of the string, even if it is at the start of the search.

>>> a = re.compile( "a$" )
>>> print a.search( "cat", 0, 2 )
<_sre.SRE_Match object at 0x7f41df2334a8>

This seems wrong to me, or inconsistent at least.

The documentation on the re module explicitly mentions that the behavior of ^ does not change due to start/end arguments to re.search, but no change in behavior is mentioned for $ (that I've seen).

Can anyone explain why things were designed this way, and/or suggest a convenient workaround?

By workaround, I would like to compose a regex which always matches the end of the string, even when someone uses the end argument to re.search.

And why was re.search designed such that:

s.search( string, endPos=len(string) - 1 )

is the same as

s.search( string[:-1] )

when

s.search( string, startPos=1 )

is explicitly and intentionally not the same as

s.search( string[1:] )

It seems to be less an issue of inconsistency between ^ and $, and more of an inconsistency within the re.search function.


问:
Parentheses pairing ({}[]()<>) issue
I want to be able to pair up all parentheses in a string, if they aren't paired then then they get their index number and False. It seems like it is repeating some values over and over, i.e cl == pop[1]. I have tried to see where the problem is but I can't see it no matter how hard I try. So I'm asking if anyone help me to locate the error and maybe even improve my code ;)</p>

```<code>def check_parentheses(string):
    pending = 0
    brackets = []
    '''Checks if parens are paired, otherwise they are bad.'''
    parenstack = collections.deque()
    for ch in string:
        if ch in lrmap:
            try:
                cl = string.index(ch, pending)
                pending = cl + 1

            except:
                cl = False

        if ch in lparens:
            parenstack.append([ch, cl])
            print parenstack

        elif ch in rparens:
            try:
                pop = parenstack.pop()

                if lrmap[pop[0]] != ch:
                    print 'wrong type of parenthesis popped from stack',\
                    pop[0], ch, pop[1], cl

                    brackets.append([pop[1], False])
                    brackets.append([cl, False])
                else:
                    brackets.append([pop[1], cl])

            except IndexError:
                print 'no opening parenthesis left in stack'
                brackets.append([cl, False])

    # if we are not out of opening parentheses, we have a mismatch
    for p in parenstack:
        brackets.append([p[1],False])
    return brackets
</code>```

答:
The below code will display the missing parentheses and the no of times missing in the given string.</p>

```<code>from collections import Counter

def find_missing(str):
    stack1 = []
    stack2 = []
    result = []
    res_dict = {}
    open_set = '<[{('
    closed_set = '>]})'
    a = list(str)
    for i in a:
        if i in open_set:
            stack1.append(i)
        elif i in closed_set:
            stack2.append(i)
    dict1 = Counter(stack1)
    dict2 = Counter(stack2)
    print(dict1)
    print(dict2)
    for i in open_set:
        if dict1[i] > dict2[closed_set[open_set.index(i)]]:
            res_dict[closed_set[open_set.index(i)]] = dict1[i] - dict2[closed_set[open_set.index(i)]]
            result.append(closed_set[open_set.index(i)])
    for i in closed_set:
        if dict2[i] > dict1[open_set[closed_set.index(i)]]:
            res_dict[open_set[closed_set.index(i)]] = dict2[i] - dict1[open_set[closed_set.index(i)]]
            result.append(open_set[closed_set.index(i)])
    return res_dict
    # return result

if __name__ == '__main__':
    str1 = '{This ((()bracket {[function]} <<going> crazy}'
    x = find_missing(str1)
    if len(x) > 0:
        print("Imbalanced")
        print(x)
    else:
        print("Balanced")
</code>```

Title: Parentheses pairing ({}[]()<>) issue

Body:
I want to be able to pair up all parentheses in a string, if they aren't paired then then they get their index number and False. It seems like it is repeating some values over and over, i.e cl == pop[1]. I have tried to see where the problem is but I can't see it no matter how hard I try. So I'm asking if anyone help me to locate the error and maybe even improve my code ;)

def check_parentheses(string):
    pending = 0
    brackets = []
    '''Checks if parens are paired, otherwise they are bad.'''
    parenstack = collections.deque()
    for ch in string:
        if ch in lrmap:
            try:
                cl = string.index(ch, pending)
                pending = cl + 1

            except:
                cl = False

        if ch in lparens:
            parenstack.append([ch, cl])
            print parenstack

        elif ch in rparens:
            try:
                pop = parenstack.pop()

                if lrmap[pop[0]] != ch:
                    print 'wrong type of parenthesis popped from stack',\
                    pop[0], ch, pop[1], cl

                    brackets.append([pop[1], False])
                    brackets.append([cl, False])
                else:
                    brackets.append([pop[1], cl])

            except IndexError:
                print 'no opening parenthesis left in stack'
                brackets.append([cl, False])

    # if we are not out of opening parentheses, we have a mismatch
    for p in parenstack:
        brackets.append([p[1],False])
    return brackets

Body:
The below code will display the missing parentheses and the no of times missing in the given string.

from collections import Counter

def find_missing(str):
    stack1 = []
    stack2 = []
    result = []
    res_dict = {}
    open_set = '<[{('
    closed_set = '>]})'
    a = list(str)
    for i in a:
        if i in open_set:
            stack1.append(i)
        elif i in closed_set:
            stack2.append(i)
    dict1 = Counter(stack1)
    dict2 = Counter(stack2)
    print(dict1)
    print(dict2)
    for i in open_set:
        if dict1[i] > dict2[closed_set[open_set.index(i)]]:
            res_dict[closed_set[open_set.index(i)]] = dict1[i] - dict2[closed_set[open_set.index(i)]]
            result.append(closed_set[open_set.index(i)])
    for i in closed_set:
        if dict2[i] > dict1[open_set[closed_set.index(i)]]:
            res_dict[open_set[closed_set.index(i)]] = dict2[i] - dict1[open_set[closed_set.index(i)]]
            result.append(open_set[closed_set.index(i)])
    return res_dict
    # return result

if __name__ == '__main__':
    str1 = '{This ((()bracket {[function]} <<going> crazy}'
    x = find_missing(str1)
    if len(x) > 0:
        print("Imbalanced")
        print(x)
    else:
        print("Balanced")


问:
how to add class for parent div with selected radio button in angulajs2?
I have four div with radi button inside filterbystar div. if user select the radio button the radi button should be selected and filterbystar div should be add active  class and radio button should not be visible. How to do that in angulajs2?.

My code is here.

```<code>        <div class="box_cont">
        <div class="box_1 filterbystar" >
            <p class="box_1_text">Any</p>
            <input type="radio" name="starvalue" value="any" class="" (click)="userTypeSelect($event)">
        </div>
        <div class="box_2 filterbystar" (click)="userTypeSelect($event)">
            <p class="box_2_text">2 Stars</p>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <input type="radio" name="starvalue" value="2" class="" (click)="userTypeSelect($event)">
        </div>
        <div class="box_2 filterbystar" (click)="userTypeSelect($event)">
            <p class="box_2_text">3 Stars</p>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <input type="radio" name="starvalue" value="3" class="" (click)="userTypeSelect($event)">
        </div>
        <div class="box_2 filterbystar" (click)="userTypeSelect($event)">
            <p class="box_2_text">4 Stars</p>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <input type="radio" name="starvalue" value="4" class="" (click)="userTypeSelect($event)">
        </div>
    </div>

    export class ExploreListComponent implements OnInit {

        userTypeSelect(event:any){
            event.preventDefault();
            //this.render.
            this.StarSelected= true;
            this.render.setElementClass(event.target,"active",true);
        }
    }
</code>```

答:
Template Side:

```<code><div class="box_cont">
        <div class="box_1 filterbystar" [ngClass]="{'active':(selectedValue === '1')}" >
            <p class="box_1_text">Any</p>
            <input type="radio" name="starvalue" value="1" class="" (click)="userTypeSelect($event.target.value)"
            [hidden]='selectedValue === "1"'>
        </div>
        <div class="box_2 filterbystar" [ngClass]='{"active":selectedValue === "2"}'>
            <p class="box_2_text">2 Stars</p>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <input type="radio" name="starvalue" value="2" class="" (click)="userTypeSelect($event.target.value)"
            [hidden]='selectedValue === "2"'>
        </div>
        <div class="box_2 filterbystar" [ngClass]='{"active":selectedValue === "3"}'>
            <p class="box_2_text">3 Stars</p>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <input type="radio" name="starvalue" value="3" class="" (click)="userTypeSelect($event.target.value)"
            [hidden]='selectedValue === "3"'>
        </div>
        <div class="box_2 filterbystar" [ngClass]='{"active":selectedValue === "4"}'>
            <p class="box_2_text">4 Stars</p>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <input type="radio" name="starvalue" value="4" class="" (click)="userTypeSelect($event.target.value)"
            [hidden]='selectedValue === "4"'>
        </div>
    </div>
</code>```

Component Side :

```<code>public selectedValue = 0;
userTypeSelect(value)
{
    this.selectedValue = value;
}
</code>```

By this , your condition will be full filled

```<code>if user select the radio button the radi button should be selected and filterbystar div should be add active class and radio button should not be visible.
</code>```

Body:
I have four div with radi button inside filterbystar div. if user select the radio button the radi button should be selected and filterbystar div should be add active  class and radio button should not be visible. How to do that in angulajs2?.

My code is here.

Any

            <input type="radio" name="starvalue" value="any" class="" (click)="userTypeSelect($event)">

2 Stars

            <input type="radio" name="starvalue" value="2" class="" (click)="userTypeSelect($event)">

3 Stars

            <input type="radio" name="starvalue" value="3" class="" (click)="userTypeSelect($event)">

4 Stars

            <input type="radio" name="starvalue" value="4" class="" (click)="userTypeSelect($event)">

    export class ExploreListComponent implements OnInit {

        userTypeSelect(event:any){
            event.preventDefault();
            //this.render.
            this.StarSelected= true;
            this.render.setElementClass(event.target,"active",true);
        }
    }

Body:
Template Side:

<div class="box_cont">
        <div class="box_1 filterbystar" [ngClass]="{'active':(selectedValue === '1')}" >
            <p class="box_1_text">Any</p>
            <input type="radio" name="starvalue" value="1" class="" (click)="userTypeSelect($event.target.value)"
            [hidden]='selectedValue === "1"'>
        </div>
        <div class="box_2 filterbystar" [ngClass]='{"active":selectedValue === "2"}'>
            <p class="box_2_text">2 Stars</p>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <input type="radio" name="starvalue" value="2" class="" (click)="userTypeSelect($event.target.value)"
            [hidden]='selectedValue === "2"'>
        </div>
        <div class="box_2 filterbystar" [ngClass]='{"active":selectedValue === "3"}'>
            <p class="box_2_text">3 Stars</p>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <input type="radio" name="starvalue" value="3" class="" (click)="userTypeSelect($event.target.value)"
            [hidden]='selectedValue === "3"'>
        </div>
        <div class="box_2 filterbystar" [ngClass]='{"active":selectedValue === "4"}'>
            <p class="box_2_text">4 Stars</p>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <i class="fa fa-star star_size" aria-hidden="true"></i>
            <input type="radio" name="starvalue" value="4" class="" (click)="userTypeSelect($event.target.value)"
            [hidden]='selectedValue === "4"'>
        </div>
    </div>

Component Side :

public selectedValue = 0;
userTypeSelect(value)
{
    this.selectedValue = value;
}

By this , your condition will be full filled

if user select the radio button the radi button should be selected and filterbystar div should be add active class and radio button should not be visible.


问:
My Maps project stops with "Method 'Android.Gms.Maps.MapView.get_Map' not found."
I am trying to run a simple map page on Xamarin Forms but I'm getting this error:

System.MissingMethodException
Method 'Android.Gms.Maps.MapView.get_Map' not found.

I saw this topic in https://forums.xamarin.com/discussion/88135/xamarin-forms-map-error-on-andriod-after-updating-xamarin-forms-and-maps-to-2-3-3-193 but got no help.

My environment is Xamarin Studio Community on a Macbook and the Xamarin.Forms.Maps package version is 2.3.3.193.

Thanks in advance.

答:
The latest nuget for Xamarin.GooglePlayServices.Maps (v42.1001.0 as of right now) does not work with the latest version of Xamarin.Forms.Maps 2.3.3.193. Try backing off to a slightly older release.

Xamarin.GooglePlayServices.Maps v29.0.0.2 seems to work just fine with it.

This happens from time to time when you update packages to the latest releases, and usually simply backing off a version or two of dependent packages like this will fix it.


问:
how to include currency convertor?
Is There any free API for currency convertor for iphone.  So I can get live updates for currency convertor for my application.</p>

答:
Yahoo Finance has a simple one:

http://freeapis.blogspot.com/2010/05/yahoo-api-for-currency-exchange-rate.html

ContentLicense: CC BY-SA 2.5

Title: how to include currency convertor?


问:
Duplicate libraries in two different project modules
I have project with two modules.
I'm using SalesforceSDK which is included as separate module and inside SalesforceSDK I have Cordova which is using okhttp.
In second module I have retrofit library which is using okhttp too and when I try to build the project I get

duplicate dex files error

I tried to delete okhttp dependency from SalesforceSDK and include it from my second module but I'm getting

symbols not found error

Only thing left to do is to include okhttp as different module but before I do that I want to ask you if there is another way to fix this problem ?

EDIT:

I tried solution proposed by Aayushi but still I get errors :

Error:Execution failed for task
':app:packageAllDebugClassesForMultiDex'.

java.util.zip.ZipException: duplicate entry: com/squareup/okhttp/Address.class

答:
I also have another solution for this issue.
Firstly, I run this command line:

and this is result:

I saw that Paypal also use okhttp library.So, I added this line to gradlew:

```<code>compile('com.paypal.sdk:paypal-android-sdk:2.13.3')
        {
            exclude group: 'com.squareup.okhttp3', module: 'okhttp'
        }
</code>```

And It aslo works fine for me.

Body:
I also have another solution for this issue.
Firstly, I run this command line:

and this is result:

I saw that Paypal also use okhttp library.So, I added this line to gradlew:

compile('com.paypal.sdk:paypal-android-sdk:2.13.3')
        {
            exclude group: 'com.squareup.okhttp3', module: 'okhttp'
        }

And It aslo works fine for me.


问:
How to use ADB Shell when Multiple Devices are connected? Fails with "error: more than one device and emulator"
```<code>$ adb --help
</code>```

```<code>-s SERIAL  use device with given serial (overrides $ANDROID_SERIAL)
</code>```

```<code>$ adb devices
List of devices attached
emulator-5554   device
7f1c864e    device
</code>```

```<code>$ adb shell -s 7f1c864e
error: more than one device and emulator
</code>```

答:
Create a Bash (tools.sh) to select a serial from devices (or emulator):

```<code>clear;
echo "====================================================================================================";
echo " ADB DEVICES";
echo "====================================================================================================";
echo "";

adb_devices=( $(adb devices | grep -v devices | grep device | cut -f 1)#$(adb devices | grep -v devices | grep device | cut -f 2) );

if [ $((${#adb_devices[@]})) -eq "1" ] && [ "${adb_devices[0]}" == "#" ]
then
    echo "No device found";
    echo "";
    echo "====================================================================================================";
    device=""
    // Call Main Menu function fxMenu;
else
    read -p "$(
        f=0
        for dev in "${adb_devices[@]}"; do
            nm="$(echo ${dev} | cut -f1 -d#)";
            tp="$(echo ${dev} | cut -f2 -d#)";
            echo " $((++f)). ${nm} [${tp}]";
        done

        echo "";
        echo " 0. Quit"
        echo "";

        echo "====================================================================================================";
        echo "";
        echo ' Please select a device: '
    )" selection

    error="You think it's over just because I am dead. It's not over. The games have just begun.";
    // Call Validation Numbers fxValidationNumberMenu ${#adb_devices[@]} ${selection} "${error}"
    case "${selection}" in
        0)
            // Call Main Menu function fxMenu;
        *)
            device="$(echo ${adb_devices[$((selection-1))]} | cut -f1 -d#)";
            // Call Main Menu function fxMenu;
    esac
fi
</code>```

Then in another option can use adb -s (global option -s use device with given serial number that overrides $ANDROID_SERIAL):

```<code>adb -s ${device} <command>
</code>```

I tested this code on MacOS terminal, but I think it can be used on windows across Git Bash Terminal.

Also remember configure environmental variables and Android SDK paths on .bash_profile file:

```<code>export ANDROID_HOME="/usr/local/opt/android-sdk/"
export PATH="$ANDROID_HOME/platform-tools:$PATH"
export PATH="$ANDROID_HOME/tools:$PATH"
</code>```

Body:
$ adb --help

-s SERIAL  use device with given serial (overrides $ANDROID_SERIAL)

$ adb devices
List of devices attached
emulator-5554   device
7f1c864e    device

$ adb shell -s 7f1c864e
error: more than one device and emulator

Body:
Create a Bash (tools.sh) to select a serial from devices (or emulator):

clear;
echo "====================================================================================================";
echo " ADB DEVICES";
echo "====================================================================================================";
echo "";

adb_devices=( $(adb devices | grep -v devices | grep device | cut -f 1)#$(adb devices | grep -v devices | grep device | cut -f 2) );

if [ $((${#adb_devices[@]})) -eq "1" ] && [ "${adb_devices[0]}" == "#" ]
then
    echo "No device found";
    echo "";
    echo "====================================================================================================";
    device=""
    // Call Main Menu function fxMenu;
else
    read -p "$(
        f=0
        for dev in "${adb_devices[@]}"; do
            nm="$(echo ${dev} | cut -f1 -d#)";
            tp="$(echo ${dev} | cut -f2 -d#)";
            echo " $((++f)). ${nm} [${tp}]";
        done

        echo "";
        echo " 0. Quit"
        echo "";

        echo "====================================================================================================";
        echo "";
        echo ' Please select a device: '
    )" selection

    error="You think it's over just because I am dead. It's not over. The games have just begun.";
    // Call Validation Numbers fxValidationNumberMenu ${#adb_devices[@]} ${selection} "${error}"
    case "${selection}" in
        0)
            // Call Main Menu function fxMenu;
        *)
            device="$(echo ${adb_devices[$((selection-1))]} | cut -f1 -d#)";
            // Call Main Menu function fxMenu;
    esac
fi

Then in another option can use adb -s (global option -s use device with given serial number that overrides $ANDROID_SERIAL):

adb -s ${device} <command>

I tested this code on MacOS terminal, but I think it can be used on windows across Git Bash Terminal.

Also remember configure environmental variables and Android SDK paths on .bash_profile file:

export ANDROID_HOME="/usr/local/opt/android-sdk/"
export PATH="$ANDROID_HOME/platform-tools:$PATH"
export PATH="$ANDROID_HOME/tools:$PATH"


问:
javac error: package com.myproject.planets does not exist
Lets consider such catalog structure:

```<code>C:\Tests>tree /F
C:.
│   GreetingsUniverse.java
│
└───planets
        Earth.java
        Jupiter.java
</code>```

Earth and Jupiter has com.myproject.planets package, GreetingsUniverse has com.myproject package.

Javac fails to compile GreetingsUniverse.java

```<code>C:\Tests>javac -cp "C:\Tests\planets"  GreetingsUniverse.java
GreetingsUniverse.java:3: error: package com.myproject.planets does not exist
import com.myproject.planets.Earth;
                            ^
GreetingsUniverse.java:4: error: package com.myproject.planets does not exist
import com.myproject.planets.Jupiter;
                            ^
GreetingsUniverse.java:19: error: cannot find symbol
        new Earth();
            ^
  symbol:   class Earth
  location: class GreetingsUniverse
GreetingsUniverse.java:20: error: cannot find symbol
        new Jupiter();
            ^
  symbol:   class Jupiter
  location: class GreetingsUniverse
4 errors
</code>```

And another try:

```<code>C:\Tests>javac -cp "C:\Tests\planets\"  GreetingsUniverse.java
javac: no source files
Usage: javac <options> <source files>
use -help for a list of possible options
</code>```

Why it doesnt compile? Do classes must be placed in catalogs structure same as package? So Jupiter should be placed in C:\Tests\com\myproject\planets\Jupiter.java or there is some other problem?

答:
```<code>c:\javac -cp c:\;c:\Tests\;c:\Tests\planets GreetingsUniverse.java
</code>```

Body:
Lets consider such catalog structure:

C:\Tests>tree /F
C:.
│   GreetingsUniverse.java
│
└───planets
        Earth.java
        Jupiter.java

Earth and Jupiter has com.myproject.planets package, GreetingsUniverse has com.myproject package.

Javac fails to compile GreetingsUniverse.java

C:\Tests>javac -cp "C:\Tests\planets"  GreetingsUniverse.java
GreetingsUniverse.java:3: error: package com.myproject.planets does not exist
import com.myproject.planets.Earth;
                            ^
GreetingsUniverse.java:4: error: package com.myproject.planets does not exist
import com.myproject.planets.Jupiter;
                            ^
GreetingsUniverse.java:19: error: cannot find symbol
        new Earth();
            ^
  symbol:   class Earth
  location: class GreetingsUniverse
GreetingsUniverse.java:20: error: cannot find symbol
        new Jupiter();
            ^
  symbol:   class Jupiter
  location: class GreetingsUniverse
4 errors

And another try:

C:\Tests>javac -cp "C:\Tests\planets\"  GreetingsUniverse.java
javac: no source files
Usage: javac <options> <source files>
use -help for a list of possible options

Why it doesnt compile? Do classes must be placed in catalogs structure same as package? So Jupiter should be placed in C:\Tests\com\myproject\planets\Jupiter.java or there is some other problem?


问:
Need Help in send news letter using PHP mail function
Need your help in over coming the following issues.

i need to send opt-in newsletters to the user. But using "gmail SMTP", i will not be able to send more than 400 mails per day.

Even if i use the mail option given in the shared server, i will not be able to send mails more than 300 mails per day.

Can you please suggest any other way i can handle this issue. Is it possible to use PHP mail functions? are there any limitations in sending the number of mails to the users.

can a server control the mails sent using PHP mail function.

Thanks for reading.

thanks a lot

答:
Yuou should check this link http://www.emailaddressmanager.com/tips/server-smtp-limit.html

Every server comes with its own smtp/mail limit, usually 300-500 for shared and between 500 and 2k for dedicated. This is by ICAN regulations i believe to control spam as much as possible.

Most of the dedicated servers out there will increase your mail/smtp relay limit on a request mentioning why you need to increase,etc. You will also need to include an unsubscribe link in the newsletter so that users who recieve the mail can opt out from future mails.

Increasing the mail limit is sequential usually and it can be upto 100,000 on a godaddy dedicated server from what i got from chat support @go daddy.

As for gmail smtps, you can't send more than 500 a day and 2000 for business/educational google apps account.


问:
What datatype should I use for Aadhaar card number in MySql server database for JAVA application?
I have used BIGINT and it accepts only 10 digits.  Aadhaar id has 12 digits and hence I am getting an error. Help me out on this.</p>

答:
MySQL BIGINT uses 8 bytes. It should be big enough to hold 12-digit number:

```<code>A BIGINT uses 8 bytes, so it can store the numbers:
Signed: -9223372036854775808 to 9223372036854775808
Unsigned: 0 to 18446744073709551615
</code>```

Can you post error you are getting? We might help you better in that case.

Body:
MySQL BIGINT uses 8 bytes. It should be big enough to hold 12-digit number:

A BIGINT uses 8 bytes, so it can store the numbers:
Signed: -9223372036854775808 to 9223372036854775808
Unsigned: 0 to 18446744073709551615

Can you post error you are getting? We might help you better in that case.


问:
WordCloud from data frame with frequency python
i have a dataframe as bellow

```<code>Int64Index: 14830 entries, 25791 to 10668
Data columns (total 2 columns):
word    14830 non-null object
coef    14830 non-null float64
dtypes: float64(1), object(1)
</code>```

i try to make word cloud with coef as a frequency instead count
for ample

```<code>text = df['word']
WordCloud.generate_from_text(text)
TypeError: generate_from_text() missing 1 required positional argument: 'text'
</code>```

or

```<code>text = np.array(df['word'])
WordCloud.generate_from_text(text)
TypeError: generate_from_text() missing 1 required positional argument: 'text'
</code>```

How can i improve this code & made word cloud like this

```<code>from wordcloud import WordCloud
wordcloud = WordCloud( ranks_only= frequency).generate(text)
plt.imshow(wordcloud)
plt.axis('off')
plt.show()
</code>```

thanks

答:
For me it worked creating a dictionary, like this:

```<code>d = {}
for a, x in bag.values:
    d[a] = x

import matplotlib.pyplot as plt
from wordcloud import WordCloud

wordcloud = WordCloud()
wordcloud.generate_from_frequencies(frequencies=d)
plt.figure()
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()
</code>```

where bag is a pandas DataFrame with columns words and counts

Body:
i have a dataframe as bellow

Int64Index: 14830 entries, 25791 to 10668
Data columns (total 2 columns):
word    14830 non-null object
coef    14830 non-null float64
dtypes: float64(1), object(1)

i try to make word cloud with coef as a frequency instead count
for ample

text = df['word']
WordCloud.generate_from_text(text)
TypeError: generate_from_text() missing 1 required positional argument: 'text'

or

text = np.array(df['word'])
WordCloud.generate_from_text(text)
TypeError: generate_from_text() missing 1 required positional argument: 'text'

How can i improve this code & made word cloud like this

from wordcloud import WordCloud
wordcloud = WordCloud( ranks_only= frequency).generate(text)
plt.imshow(wordcloud)
plt.axis('off')
plt.show()

thanks

Body:
For me it worked creating a dictionary, like this:

d = {}
for a, x in bag.values:
    d[a] = x

import matplotlib.pyplot as plt
from wordcloud import WordCloud

wordcloud = WordCloud()
wordcloud.generate_from_frequencies(frequencies=d)
plt.figure()
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()

where bag is a pandas DataFrame with columns words and counts


问:
Set Shadow on Bottom UIView only
I want to create bottom only shadow on UIView. Right now with this function, will create shadow in top, bottom, left, and right.

```<code>func setCardView(view : UIView){
    view.layer.masksToBounds = false
    view.layer.shadowOffset = CGSize(width: 0, height: 0)
    view.layer.shadowRadius = 2
    view.layer.shadowOpacity = 0.5
}
</code>```

Is there anyway to only create shadow in the bottom?
Any help would be appreciated. Thank you!

答:
I think the proper way of thinking of shadow is, the shadow belongs to the object, which is the button, the uiview, not just part of the side. Imagining there is a virtual light source. You can't really just create a shadow for one side.

With that being said, the shadow will always be the shadow of the view as a whole. However, you can change the shadow offset to make it towards to the bottom.

```<code>view.layer.shadowOffset = CGSize(width: 0, height: 3)
</code>```

This means you want the light source shoot the light from top to make the shadow to the bottom. The reason you still see some shadow at the top is the shadow radius. which is to simulate the diffuse of the light. The more diffuse the light is, the softer the shadow will be so you will see top shadow still.

```<code>view.layer.shadowRadius = 1 or 0.5
</code>```

try to reduce the radius also. it will give you a better visual result.

To understand umbra, penumbra and antumbra if you need, check out https://en.wikipedia.org/wiki/Umbra,_penumbra_and_antumbra

Title: Set Shadow on Bottom UIView only

Body:
I want to create bottom only shadow on UIView. Right now with this function, will create shadow in top, bottom, left, and right.

func setCardView(view : UIView){
    view.layer.masksToBounds = false
    view.layer.shadowOffset = CGSize(width: 0, height: 0)
    view.layer.shadowRadius = 2
    view.layer.shadowOpacity = 0.5
}

Is there anyway to only create shadow in the bottom?
Any help would be appreciated. Thank you!

Body:
I think the proper way of thinking of shadow is, the shadow belongs to the object, which is the button, the uiview, not just part of the side. Imagining there is a virtual light source. You can't really just create a shadow for one side.

With that being said, the shadow will always be the shadow of the view as a whole. However, you can change the shadow offset to make it towards to the bottom.

view.layer.shadowOffset = CGSize(width: 0, height: 3)

This means you want the light source shoot the light from top to make the shadow to the bottom. The reason you still see some shadow at the top is the shadow radius. which is to simulate the diffuse of the light. The more diffuse the light is, the softer the shadow will be so you will see top shadow still.

view.layer.shadowRadius = 1 or 0.5

try to reduce the radius also. it will give you a better visual result.

To understand umbra, penumbra and antumbra if you need, check out https://en.wikipedia.org/wiki/Umbra,_penumbra_and_antumbra


问:
Prevent user from selecting a value less than a scale before
I have a scale (radio buttons) in a form that allows the user to select a value from 0 to 10.

I have a second scale (radio buttons) below it, which also allows the user to select a value from 0 to 10.

Using jQuery ideally.. how would I go about preventing the user from selecting a value in the second scale that is less than the value in the first scale?

The markup looks something like below (although this is stripped back for the sake of the example)

```<code><div class="scale_a">

    <div class="frm_scale">
        <label for="field_a">
        <input type="radio" id="field_a_1" value="0">0</label>
    </div>

    <div class="frm_scale">
        <label for="field_a">
        <input type="radio" id="field_a_2" value="1">1</label>
    </div>

</div>
</code>```

答: On select of first radio get the value and and disable all other radio in second radio less than the selected value.</p>

Body:
I have a scale (radio buttons) in a form that allows the user to select a value from 0 to 10.

I have a second scale (radio buttons) below it, which also allows the user to select a value from 0 to 10.

Using jQuery ideally.. how would I go about preventing the user from selecting a value in the second scale that is less than the value in the first scale?

The markup looks something like below (although this is stripped back for the sake of the example)

        <input type="radio" id="field_a_1" value="0">0

        <input type="radio" id="field_a_2" value="1">1


问:
Color Dodge Blend Bitmap
I have two bitmaps topBitmap and bottomBitmap and I need to blend the two bitmaps using color dodge in android. I could not find color dodge in PorterDuffXfermode. Is there any way to do it with ot without the use of a Canvas?

Kindly let me know how to blend two bitmaps using color dodge mode in android.Thanks in advance.

答:
Put this code for pencil sketch ,this work for me</p>

```<code>public Bitmap Changetosketch(Bitmap bmp) {
    Bitmap Copy, Invert, Result;
    Copy = toGrayscale(bmp);
    Invert = createInvertedBitmap(Copy);
    Invert = Blur.blur(this, Invert);
    Result = ColorDodgeBlend(Invert, Copy);
    return Result;
}
public static Bitmap toGrayscale(Bitmap src)
{
    final double GS_RED = 0.299;
    final double GS_GREEN = 0.587;
    final double GS_BLUE = 0.114;

    // create output bitmap
    Bitmap bmOut = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
    // pixel information
    int A, R, G, B;
    int pixel;

    // get image size
    int width = src.getWidth();
    int height = src.getHeight();

    // scan through every single pixel
    for (int x = 0; x < width; ++x) {
        for (int y = 0; y < height; ++y) {
            // get one pixel color
            pixel = src.getPixel(x, y);
            // retrieve color of all channels
            A = Color.alpha(pixel);
            R = Color.red(pixel);
            G = Color.green(pixel);
            B = Color.blue(pixel);
            // take conversion up to one single value
            R = G = B = (int) (GS_RED * R + GS_GREEN * G + GS_BLUE * B);
            // set new pixel color to output bitmap
            bmOut.setPixel(x, y, Color.argb(A, R, G, B));
        }
    }

    // return final image
    return bmOut;
}

public static Bitmap createInvertedBitmap(Bitmap src) {
    Bitmap bmOut = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
    // color info
    int A, R, G, B;
    int pixelColor;
    // image size
    int height = src.getHeight();
    int width = src.getWidth();

    // scan through every pixel
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            // get one pixel
            pixelColor = src.getPixel(x, y);
            // saving alpha channel
            A = Color.alpha(pixelColor);
            // inverting byte for each R/G/B channel
            R = 255 - Color.red(pixelColor);
            G = 255 - Color.green(pixelColor);
            B = 255 - Color.blue(pixelColor);
            // set newly-inverted pixel to output image
            bmOut.setPixel(x, y, Color.argb(A, R, G, B));
        }
    }
    return bmOut;
}
public Bitmap ColorDodgeBlend(Bitmap source, Bitmap layer) {
    Bitmap base = source.copy(Bitmap.Config.ARGB_8888, true);
    Bitmap blend = layer.copy(Bitmap.Config.ARGB_8888, false);

    IntBuffer buffBase = IntBuffer.allocate(base.getWidth() * base.getHeight());
    base.copyPixelsToBuffer(buffBase);
    buffBase.rewind();

    IntBuffer buffBlend = IntBuffer.allocate(blend.getWidth() * blend.getHeight());
    blend.copyPixelsToBuffer(buffBlend);
    buffBlend.rewind();

    IntBuffer buffOut = IntBuffer.allocate(base.getWidth() * base.getHeight());
    buffOut.rewind();

    while (buffOut.position() < buffOut.limit()) {

        int filterInt = buffBlend.get();
        int srcInt = buffBase.get();

        int redValueFilter = Color.red(filterInt);
        int greenValueFilter = Color.green(filterInt);
        int blueValueFilter = Color.blue(filterInt);

        int redValueSrc = Color.red(srcInt);
        int greenValueSrc = Color.green(srcInt);
        int blueValueSrc = Color.blue(srcInt);

        int redValueFinal = colordodge(redValueFilter, redValueSrc);
        int greenValueFinal = colordodge(greenValueFilter, greenValueSrc);
        int blueValueFinal = colordodge(blueValueFilter, blueValueSrc);

        int pixel = Color.argb(255, redValueFinal, greenValueFinal, blueValueFinal);

        buffOut.put(pixel);
    }

    buffOut.rewind();

    base.copyPixelsFromBuffer(buffOut);
    blend.recycle();

    return base;
}

private int colordodge(int in1, int in2) {
    float image = (float)in2;
    float mask = (float)in1;
    return ((int) ((image == 255) ? image:Math.min(255, (((long)mask << 8 ) / (255 - image)))));
}
</code>```

Title: Color Dodge Blend Bitmap

Body:
Put this code for pencil sketch ,this work for me

public Bitmap Changetosketch(Bitmap bmp) {
    Bitmap Copy, Invert, Result;
    Copy = toGrayscale(bmp);
    Invert = createInvertedBitmap(Copy);
    Invert = Blur.blur(this, Invert);
    Result = ColorDodgeBlend(Invert, Copy);
    return Result;
}
public static Bitmap toGrayscale(Bitmap src)
{
    final double GS_RED = 0.299;
    final double GS_GREEN = 0.587;
    final double GS_BLUE = 0.114;

    // create output bitmap
    Bitmap bmOut = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
    // pixel information
    int A, R, G, B;
    int pixel;

    // get image size
    int width = src.getWidth();
    int height = src.getHeight();

    // scan through every single pixel
    for (int x = 0; x < width; ++x) {
        for (int y = 0; y < height; ++y) {
            // get one pixel color
            pixel = src.getPixel(x, y);
            // retrieve color of all channels
            A = Color.alpha(pixel);
            R = Color.red(pixel);
            G = Color.green(pixel);
            B = Color.blue(pixel);
            // take conversion up to one single value
            R = G = B = (int) (GS_RED * R + GS_GREEN * G + GS_BLUE * B);
            // set new pixel color to output bitmap
            bmOut.setPixel(x, y, Color.argb(A, R, G, B));
        }
    }

    // return final image
    return bmOut;
}

public static Bitmap createInvertedBitmap(Bitmap src) {
    Bitmap bmOut = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
    // color info
    int A, R, G, B;
    int pixelColor;
    // image size
    int height = src.getHeight();
    int width = src.getWidth();

    // scan through every pixel
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            // get one pixel
            pixelColor = src.getPixel(x, y);
            // saving alpha channel
            A = Color.alpha(pixelColor);
            // inverting byte for each R/G/B channel
            R = 255 - Color.red(pixelColor);
            G = 255 - Color.green(pixelColor);
            B = 255 - Color.blue(pixelColor);
            // set newly-inverted pixel to output image
            bmOut.setPixel(x, y, Color.argb(A, R, G, B));
        }
    }
    return bmOut;
}
public Bitmap ColorDodgeBlend(Bitmap source, Bitmap layer) {
    Bitmap base = source.copy(Bitmap.Config.ARGB_8888, true);
    Bitmap blend = layer.copy(Bitmap.Config.ARGB_8888, false);

    IntBuffer buffBase = IntBuffer.allocate(base.getWidth() * base.getHeight());
    base.copyPixelsToBuffer(buffBase);
    buffBase.rewind();

    IntBuffer buffBlend = IntBuffer.allocate(blend.getWidth() * blend.getHeight());
    blend.copyPixelsToBuffer(buffBlend);
    buffBlend.rewind();

    IntBuffer buffOut = IntBuffer.allocate(base.getWidth() * base.getHeight());
    buffOut.rewind();

    while (buffOut.position() < buffOut.limit()) {

        int filterInt = buffBlend.get();
        int srcInt = buffBase.get();

        int redValueFilter = Color.red(filterInt);
        int greenValueFilter = Color.green(filterInt);
        int blueValueFilter = Color.blue(filterInt);

        int redValueSrc = Color.red(srcInt);
        int greenValueSrc = Color.green(srcInt);
        int blueValueSrc = Color.blue(srcInt);

        int redValueFinal = colordodge(redValueFilter, redValueSrc);
        int greenValueFinal = colordodge(greenValueFilter, greenValueSrc);
        int blueValueFinal = colordodge(blueValueFilter, blueValueSrc);

        int pixel = Color.argb(255, redValueFinal, greenValueFinal, blueValueFinal);

        buffOut.put(pixel);
    }

    buffOut.rewind();

    base.copyPixelsFromBuffer(buffOut);
    blend.recycle();

    return base;
}

private int colordodge(int in1, int in2) {
    float image = (float)in2;
    float mask = (float)in1;
    return ((int) ((image == 255) ? image:Math.min(255, (((long)mask << 8 ) / (255 - image)))));
}


问:
change Full Calendar event height ONLY in dayView
Full Calendar dayView height adjustments seem impossible.  I have looked and tried just about everything. I can get the height adjustments but the events overlap? I have seen several posts on stackoverflow but none that fix my issue.

```<code>eventAfterRender: function(event, element, view) {
                console.log($(view));
                //$('div.fc-day-content').css({"height":"50px"});
                $('.fc-event').css({"height":"50px"});

             },
</code>```

here is the CSS it spits out.

```<code>element.style {
    background-color: #2E3436;
    border-color: #2E3436;
    color: #FFFFFF;
    height: 50px;
    left: 3px;
    position: absolute;
    top: 36px;
    width: 1439px;
    }
</code>```

答:
yes , you can do it in event render option</p>

```<code> eventRender: function (event, element,view) {
                 debugger;
             if(view.type == "agendaDay"){
                 $('.fc-time-grid .fc-slats td').css('height','2.8em');}
             else
                 $('.fc-time-grid .fc-slats td').css('height','1.8em');}
</code>```

Body:
Full Calendar dayView height adjustments seem impossible.  I have looked and tried just about everything. I can get the height adjustments but the events overlap? I have seen several posts on stackoverflow but none that fix my issue.

eventAfterRender: function(event, element, view) {
                console.log($(view));
                //$('div.fc-day-content').css({"height":"50px"});
                $('.fc-event').css({"height":"50px"});

             },

here is the CSS it spits out.

element.style {
    background-color: #2E3436;
    border-color: #2E3436;
    color: #FFFFFF;
    height: 50px;
    left: 3px;
    position: absolute;
    top: 36px;
    width: 1439px;
    }

Body:
yes , you can do it in event render option

 eventRender: function (event, element,view) {
                 debugger;
             if(view.type == "agendaDay"){
                 $('.fc-time-grid .fc-slats td').css('height','2.8em');}
             else
                 $('.fc-time-grid .fc-slats td').css('height','1.8em');}


问:
How find minimum in a array recursive method works?
```<code>public static int findMin(int[] numbers, int startIndex, int endIndex) {
    if (startIndex == endIndex){
        return numbers[startIndex];
    }
    else {
        int midIndex = (startIndex + endIndex) / 2;
        int leftMin = findMin(numbers, startIndex, midIndex);
        int rightMin = findMin(numbers, midIndex + 1, endIndex);
        if (leftMin < rightMin)
            return leftMin;
        else
            return rightMin;
    }
}
</code>```

I really have trouble understanding this find min recursion. This recursive method finds the minimum number in an array.

This is how I understand it.

Suppose I have a array 5, 3 , -5, 8, and startIndex is 0, endIndex is 3

First time, midIndex = (0+3)/2 =1. So it divided between 3 and -5.

And then it goes to findMin, so it passes Array, 0, 1 back to findMin.

Then, the midIndex = (0+1)/2 = 0. And passes Array, 0, 0 back to findMin.

Since startIndex 0 = endIndex 0, return numbers[startIndex](which is 5?).

I can't really figure out how this method finds the minimum number. Since the startIndex is alway 0, why does it need to return numbers[startIndex]?

答:
Your function is basically splitting your array in half to make the search each time.

Let's go step by step into a very simple input:

array: [5, 3]

startIndex: 0

endIndex: 1

The first call is going to be

findMin([5,3], 0, 1) -> (we are here)

Since startIndex and endIndex are not the same, the array will be split into two parts: [5] and [3], respectively. Although there is only one value inside each array is still an array, remember that. First, the leftMin variable is resolved, so the stack will look like this:

findMin([5,3], 0, 1) -> (pending result)

leftMin = findMin([5], 0, 0) -> (we are here)

As we can see both startIndex and endIndex are the same, so returns our number. Next step is to verify the rightMin. Let's update our stack:

findMin([5,3], 0, 1) -> (pending result)

leftMin = 5

rightMin = findMin([3], 1, 1) -> (we are here)

The same thing that happened to leftMin happens here: we have the same index value, so the number is returned in the first if condition. Now the stack looks like this:

findMin([5,3], 0, 1) -> (we are here)

leftMin = 5

rightMin = 3

Now we went back to the top of our stack and we have the values for leftMin and rightMin of our firstCall. rightMin is going to be returned, since it holds the minimum value between them.

Event though we just when to the second level of recursion, the same logic applies to each new level: the method is going to split the array in half until it has only one value and them it will return this value. After that, both the left and the right value will be compared, and each level will return the min value, until there the very first one, that will define the min value for the entire array.

Body:
public static int findMin(int[] numbers, int startIndex, int endIndex) {
    if (startIndex == endIndex){
        return numbers[startIndex];
    }
    else {
        int midIndex = (startIndex + endIndex) / 2;
        int leftMin = findMin(numbers, startIndex, midIndex);
        int rightMin = findMin(numbers, midIndex + 1, endIndex);
        if (leftMin < rightMin)
            return leftMin;
        else
            return rightMin;
    }
}

I really have trouble understanding this find min recursion. This recursive method finds the minimum number in an array.

This is how I understand it.

Suppose I have a array 5, 3 , -5, 8, and startIndex is 0, endIndex is 3

First time, midIndex = (0+3)/2 =1. So it divided between 3 and -5.

And then it goes to findMin, so it passes Array, 0, 1 back to findMin.

Then, the midIndex = (0+1)/2 = 0. And passes Array, 0, 0 back to findMin.

Since startIndex 0 = endIndex 0, return numbers[startIndex](which is 5?).

I can't really figure out how this method finds the minimum number. Since the startIndex is alway 0, why does it need to return numbers[startIndex]?


问:
WSO2 IoT: Creating a new device type
I am creating the new device from the documentation provided in this link (https://github.com/wso2/carbon-device-mgt-maven-plugin.git).

I performed the following  steps

Step 1: Installing the Maven Archetype. Everything went okay! The maven archtype installed was

```<code>git clone -b v1.0.0 --single-branch https://github.com/wso2/carbon-device-mgt-maven-plugin.git
</code>```

In Step 2: Creating a new device type, when I perform the command mvn archetype: generate -DarchetypeCatalog = local. The output does not show me the archetype for me to choose. Look at the output of this command:

```<code>C:\Users\eliazar.carvalho\Documents\Tools\WSO2\wso2iot-3.0.0\samples>mvn archetype:generate -DarchetypeCatalog=local
[INFO] Scanning for projects...
[INFO]
[INFO] ---------------------------------------------------------------------    ---
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:3.0.0:generate (default-cli) > generate-sources @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:3.0.0:generate (default-cli) < generate-sources @ standalone-pom <<<
[INFO]
[INFO] --- maven-archetype-plugin:3.0.0:generate (default-cli) @ standalone-pom ---
[INFO] Generating project in Interactive mode
[INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0)
Choose archetype:
Your filter doesn't match any archetype (hint: enter to return to initial list)
Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): :
</code>```

What could be going wrong?

I am using WSO2 IoT Server 3.0
and OS: Ubuntu 14.04 LTS

答:
I also faced the same issue. This is how I fixed it.

```<code>mvn archetype:generate -DarchetypeCatalog=local -X
</code>```

Will give you the exact local catalog file path it is being read. For me it was ~/.m2/repository/archetype-catalog.xml.

But actualy my local repo catalog file is on ~/.m2/archetype-catalog.xml. So I copied archetype-catalog.xml into the correct path with following command.

```<code>cp ~/.m2/archetype-catalog.xml ~/.m2/repository/
</code>```

Now it works fine. It seems we need to update maven-archetype-plugin version in mentioned repository.

Title: WSO2 IoT: Creating a new device type

Body:
I am creating the new device from the documentation provided in this link (https://github.com/wso2/carbon-device-mgt-maven-plugin.git).

I performed the following  steps

Step 1: Installing the Maven Archetype. Everything went okay! The maven archtype installed was

git clone -b v1.0.0 --single-branch https://github.com/wso2/carbon-device-mgt-maven-plugin.git

In Step 2: Creating a new device type, when I perform the command mvn archetype: generate -DarchetypeCatalog = local. The output does not show me the archetype for me to choose. Look at the output of this command:

C:\Users\eliazar.carvalho\Documents\Tools\WSO2\wso2iot-3.0.0\samples>mvn archetype:generate -DarchetypeCatalog=local
[INFO] Scanning for projects...
[INFO]
[INFO] ---------------------------------------------------------------------    ---
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:3.0.0:generate (default-cli) > generate-sources @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:3.0.0:generate (default-cli) < generate-sources @ standalone-pom <<<
[INFO]
[INFO] --- maven-archetype-plugin:3.0.0:generate (default-cli) @ standalone-pom ---
[INFO] Generating project in Interactive mode
[INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0)
Choose archetype:
Your filter doesn't match any archetype (hint: enter to return to initial list)
Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): :

What could be going wrong?

I am using WSO2 IoT Server 3.0
and OS: Ubuntu 14.04 LTS

Body:
I also faced the same issue. This is how I fixed it.

mvn archetype:generate -DarchetypeCatalog=local -X

Will give you the exact local catalog file path it is being read. For me it was ~/.m2/repository/archetype-catalog.xml.

But actualy my local repo catalog file is on ~/.m2/archetype-catalog.xml. So I copied archetype-catalog.xml into the correct path with following command.

cp ~/.m2/archetype-catalog.xml ~/.m2/repository/

Now it works fine. It seems we need to update maven-archetype-plugin version in mentioned repository.


问:
Extracting nested values in a Javascript object
I have the following object:

```<code>var result = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}];
</code>```

This is a snippet from a larger object that I'm trying to push into a MySQL table.
What I'm trying to achieve is extract just the values into their own array, which would return this:

```<code>[ '89304', '102524', '9' ]
</code>```

This way, I can easily push the values to the DB.

I have tried doing the following which works fine without nesting:

obKeys = Object.keys(result);
console.log(obKeys);

However, with the nesting, the result I am getting is the following:

[ '0' ]

Can anyone let me know where I am going wrong, or suggest an alternative (better) way of doing this?

Thanks.

答:
```<code>var multiArr =[];
var arr = [];
function deepTraverse(obj) {
    if( typeof obj == "object" ) {
        $.each(obj, function(k,v) {
           deepTraverse(v);
        });
    }
    else {
        arr.push(obj);
    }
}

$.each(result,function(k,v){
deepTraverse(v);
multiArr.push(arr);
arr = [];
});

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

multiArr will contain array of arrays. I hope this helps.

Body:
I have the following object:

var result = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}];

This is a snippet from a larger object that I'm trying to push into a MySQL table.
What I'm trying to achieve is extract just the values into their own array, which would return this:

[ '89304', '102524', '9' ]

This way, I can easily push the values to the DB.

I have tried doing the following which works fine without nesting:

obKeys = Object.keys(result);
console.log(obKeys);

However, with the nesting, the result I am getting is the following:

[ '0' ]

Can anyone let me know where I am going wrong, or suggest an alternative (better) way of doing this?

Thanks.

Body:
var multiArr =[];
var arr = [];
function deepTraverse(obj) {
    if( typeof obj == "object" ) {
        $.each(obj, function(k,v) {
           deepTraverse(v);
        });
    }
    else {
        arr.push(obj);
    }
}

$.each(result,function(k,v){
deepTraverse(v);
multiArr.push(arr);
arr = [];
});

console.log(multiArr);

multiArr will contain array of arrays. I hope this helps.


问:
how to pass ID in a link using jquery
I have a book now button, when a user clicks on book now he should be redirected to a order confirmation page. I want to pass type and id in a url using jquery.
want to pass this kind of url - http://localhost/company/order-confirmation?type=course&id=35

How can I do that in jquery.

html:

```<code> <a href="" class="book_now" batch-id="">Book Now</a>
</code>```

Jquery:

```<code>  $('.book_now',template).attr('batch-id', val['batch_id']);
</code>```

答:
Please have a look on this , its same what you want</p>

```<code><!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <title></title>
</head>

<body>
  <a href="/abc" class="book_now" batch-id="123">Book Now</a>
</body>
<script type="text/javascript">
$(".book_now").click(function(e) {
  e.target.href += "?id=" + $(this).attr('batch-id');
})
</script>

</html>
</code>```

Title: how to pass ID in a link using jquery

Body:
I have a book now button, when a user clicks on book now he should be redirected to a order confirmation page. I want to pass type and id in a url using jquery.
want to pass this kind of url - http://localhost/company/order-confirmation?type=course&id=35

How can I do that in jquery.

html:

 Book Now

Jquery:

  $('.book_now',template).attr('batch-id', val['batch_id']);

Body:
Please have a look on this , its same what you want

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <title></title>
</head>

<body>
  <a href="/abc" class="book_now" batch-id="123">Book Now</a>
</body>
<script type="text/javascript">
$(".book_now").click(function(e) {
  e.target.href += "?id=" + $(this).attr('batch-id');
})
</script>

</html>


问:
Java process dies "Out of swap space" during major GC, with plenty of memory left on machine
So I was monitoring a process using VisualVM and I clicked on "Perform GC", the process then died with error:

```<code>#
# A fatal error has been detected by the Java Runtime Environment:
#
# java.lang.OutOfMemoryError: requested 4088 bytes for char in /BUILD_AREA/jdk6_24/hotspot/src/share/vm/utilities/stack.inline.hpp. Out of swap space?
#
#  Internal Error (allocation.inline.hpp:39), pid=1148, tid=1082808672
#  Error: char in /BUILD_AREA/jdk6_24/hotspot/src/share/vm/utilities/stack.inline.hpp
#
# JRE version: 6.0_24-b07
# Java VM: Java HotSpot(TM) 64-Bit Server VM (19.1-b02 mixed mode linux-amd64 )
# An error report file with more information is saved as:
# /net/bsrs78.pit.twosigma.com/d-1/local/eaMemory2-yao-bsrs78.pit.twosigma.com-db8rsnyc9-head-20110622-130721-31729-0/hs_err_pid1148.log
#
# If you would like to submit a bug report, please visit:
#   http://java.sun.com/webapps/bugreport/crash.jsp
#
</code>```

But not long before I did that, I checked the machine and it seems like there's plenty of memory left (numbers shown in MB):

```<code>free -m
             total       used       free     shared    buffers     cached
Mem:         96869      60999      35869          0        363       4590
-/+ buffers/cache:      56045      40823
Swap:        10243         40      10203
</code>```

It doesn't seem likely to me that GC will take up all the memory.

This is a problem because if I just let the program continue to run, at some point it will max out its allocated heap and then try to do a major GC and die the same way. Minor GC seems fine though.

So what is going on here? Why does it die with the swap space message? Please let me know if there's anything I can do to provide more information or diagnose this problem further. I will greatly appreciate all help!

Thanks!

Edit1: I've uploaded the error log at http://www.mediafire.com/?kw0meup9mw5de9c, and for what it's worth, it's using PS Scavenge for minor GC and PS MarkSweep for major GC.

Edit2: Also, this problem has happened multiple times, consistently dying in the middle of a major garbage collection -- whether induced by me via visualVM or running out of heap and being triggered by jvm itself.

答:
You can see that swap space is exhausted and there is a crash due to OOM (OutOfMemoryError)
This issue has been addressed in JDK-6302804 in 6u25
Upgrading JVM could avoid this issue.</p>

Body:
So I was monitoring a process using VisualVM and I clicked on "Perform GC", the process then died with error:

#
# A fatal error has been detected by the Java Runtime Environment:
#
# java.lang.OutOfMemoryError: requested 4088 bytes for char in /BUILD_AREA/jdk6_24/hotspot/src/share/vm/utilities/stack.inline.hpp. Out of swap space?
#
#  Internal Error (allocation.inline.hpp:39), pid=1148, tid=1082808672
#  Error: char in /BUILD_AREA/jdk6_24/hotspot/src/share/vm/utilities/stack.inline.hpp
#
# JRE version: 6.0_24-b07
# Java VM: Java HotSpot(TM) 64-Bit Server VM (19.1-b02 mixed mode linux-amd64 )
# An error report file with more information is saved as:
# /net/bsrs78.pit.twosigma.com/d-1/local/eaMemory2-yao-bsrs78.pit.twosigma.com-db8rsnyc9-head-20110622-130721-31729-0/hs_err_pid1148.log
#
# If you would like to submit a bug report, please visit:
#   http://java.sun.com/webapps/bugreport/crash.jsp
#

But not long before I did that, I checked the machine and it seems like there's plenty of memory left (numbers shown in MB):

free -m
             total       used       free     shared    buffers     cached
Mem:         96869      60999      35869          0        363       4590
-/+ buffers/cache:      56045      40823
Swap:        10243         40      10203

It doesn't seem likely to me that GC will take up all the memory.

This is a problem because if I just let the program continue to run, at some point it will max out its allocated heap and then try to do a major GC and die the same way. Minor GC seems fine though.

So what is going on here? Why does it die with the swap space message? Please let me know if there's anything I can do to provide more information or diagnose this problem further. I will greatly appreciate all help!

Thanks!

Edit1: I've uploaded the error log at http://www.mediafire.com/?kw0meup9mw5de9c, and for what it's worth, it's using PS Scavenge for minor GC and PS MarkSweep for major GC.

Edit2: Also, this problem has happened multiple times, consistently dying in the middle of a major garbage collection -- whether induced by me via visualVM or running out of heap and being triggered by jvm itself.


问:
Chrome Webix .setValue() not working consistently
On Chrome, .setValue("") doesn't always clear the visible value.

With webix:

```<code>webix.ui({
    cols:[
        { view:"text", id:"message", placeholder:"Type chat here..."},
        { view:"button", value: "Send", click:send_message, width:75 }
    ]
});

function send_message(){
    var text = $$("message").getValue();
    if (text)
    {
        //send text to chat
    }
    $$("message").setValue(""); //Should set text field data to blank.
    $$("message").refresh();
    $$("message").focus();
}
</code>```

On Firefox, when I hit [Enter] after typing a message, send_message posts the message to the chat and clears the text field. In Chrome, the text field does not always clear. The old message text lingers in the field. The cursor, however, jumps to the start of the text.

I can't figure out why Chrome is acting this way.

答:
Found a fix. Not sure why, but setting a hotkey for the button fixed the issue.

```<code> { view:"button", value: "Send", click:send_message, width:75, hotkey:"enter" }
</code>```

Now hitting enter works as well as clicking the button in both Firefox and Chrome.

Body:
On Chrome, .setValue("") doesn't always clear the visible value.

With webix:

webix.ui({
    cols:[
        { view:"text", id:"message", placeholder:"Type chat here..."},
        { view:"button", value: "Send", click:send_message, width:75 }
    ]
});

function send_message(){
    var text = $$("message").getValue();
    if (text)
    {
        //send text to chat
    }
    $$("message").setValue(""); //Should set text field data to blank.
    $$("message").refresh();
    $$("message").focus();
}

On Firefox, when I hit [Enter] after typing a message, send_message posts the message to the chat and clears the text field. In Chrome, the text field does not always clear. The old message text lingers in the field. The cursor, however, jumps to the start of the text.

I can't figure out why Chrome is acting this way.

Body:
Found a fix. Not sure why, but setting a hotkey for the button fixed the issue.

 { view:"button", value: "Send", click:send_message, width:75, hotkey:"enter" }

Now hitting enter works as well as clicking the button in both Firefox and Chrome.


问:
First display list according to HTML selection, then direct to particular page based on selection after clicking HTML button
index page

First I am trying to list elements according to the option selected from drop down menu, then open a particular page related to a particular category after clicking Go To Related Page Button. For example if a user selects Fruits, then first it should list fruit items, then fruits.html page should be opened after clicking Go To Related Page button. Another example would be if a user selects Vegetables, then first it should list vegetable items, then vegetables.html page should be opened after clicking Go To Related Page button.

I have successfully accomplished first part, but stuck in second part. I have pasted my codes below. I was trying to accomplish second part with the help of a function named goToPage(), but don't know what to do. It does not have to be this function, any other way that would work are most welcome.

// JavaScript
'use strict';

var category = ["Fruits", "Vegetables"];
var fruits = ["Apple", "Banana", "Orange"];
var fruitsLen = fruits.length;
var vegetables = ["Cauliflower", "Brinjal", "Potato"];
var vegLen = vegetables.length;

var i;
var listToDisplay = "";

//function to display contents accroding to the category selected
function displayContents(v){
  switch(v){
    case "fruits":
      for(i=0; i<fruitsLen; i++){
        listToDisplay += "
" + fruits[i];
      }
      document.getElementById('displayDiv').innerHTML = listToDisplay;
      break;
    case "vegetables":
      for(i=0; i<vegLen; i++){
        listToDisplay += "
" + vegetables[i];
      }
      document.getElementById('displayDiv').innerHTML = listToDisplay;
      break;
    default:
      document.getElementById('displayDiv').innerHTML = "Invalid Selection.";
  }
}

//function to go to particular page
function goToPage(){

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <script src="script.js"></script>
</head>
<body>

<div id="categoryDiv">
Select Category:
<select id="categorySelect" onChange="displayContents(this.value)">
 <option value="first">Please select a category</option>
  <option value="fruits">Fruits</option>
  <option value="vegetables">Vegetables</option>
</select>
<br>
</div>

<div id="displayDiv">

</div>

<div id="buttonDiv">
 <br>
 <input type="button" value="Go to Related Page" onclick="goToPage()">
</div>

</body>
</html></code>```

答:
By this you can redirect to a desired page based on the selected option

Create two pages fruits.html and vegetables.html in the same directory

```<code>// JavaScript
'use strict';

var category = ["Fruits", "Vegetables"];
var fruits = ["Apple", "Banana", "Orange"];
var fruitsLen = fruits.length;
var vegetables = ["Cauliflower", "Brinjal", "Potato"];
var vegLen = vegetables.length;
var optionSelected = "";       //Changed Here

var i;
var listToDisplay = "";

//function to display contents accroding to the category selected
function displayContents(v){
  listToDisplay = "";               // Changed Here
  optionSelected = v;               // Changed Here
  switch(v){
    case "fruits":
      for(i=0; i<fruitsLen; i++){
        listToDisplay += "<br>" + fruits[i];
      }
      document.getElementById('displayDiv').innerHTML = listToDisplay;
      break;
    case "vegetables":
      for(i=0; i<vegLen; i++){
        listToDisplay += "<br>" + vegetables[i];
      }
      document.getElementById('displayDiv').innerHTML = listToDisplay;
      break;
    default:
      document.getElementById('displayDiv').innerHTML = "Invalid Selection.";
  }
}

//function to go to particular page

function goToPage(){
    if(optionSelected === "fruits")              //Changed Here
        window.location = "fruits.html";
    else if(optionSelected === "vegetables")
        window.location = "vegetables.html";
}
</code>```

HTML Code

```<code><!DOCTYPE html>
<html>
<head>
  <script src="script.js"></script>
</head>
<body>

<div id="categoryDiv">
Select Category:
<select id="categorySelect" onChange="displayContents(this.value)">
    <option value="first">Please select a category</option>
  <option value="fruits">Fruits</option>
  <option value="vegetables">Vegetables</option>
</select>
<br>
</div>

<div id="displayDiv">

</div>

<div id="buttonDiv">
    <br>
    <input type="button" value="Go to Related Page" onclick="goToPage()">
</div>

</body>
</html>
</code>```

Body:
index page

First I am trying to list elements according to the option selected from drop down menu, then open a particular page related to a particular category after clicking Go To Related Page Button. For example if a user selects Fruits, then first it should list fruit items, then fruits.html page should be opened after clicking Go To Related Page button. Another example would be if a user selects Vegetables, then first it should list vegetable items, then vegetables.html page should be opened after clicking Go To Related Page button.

I have successfully accomplished first part, but stuck in second part. I have pasted my codes below. I was trying to accomplish second part with the help of a function named goToPage(), but don't know what to do. It does not have to be this function, any other way that would work are most welcome.

// JavaScript
'use strict';

var category = ["Fruits", "Vegetables"];
var fruits = ["Apple", "Banana", "Orange"];
var fruitsLen = fruits.length;
var vegetables = ["Cauliflower", "Brinjal", "Potato"];
var vegLen = vegetables.length;

var i;
var listToDisplay = "";

//function to display contents accroding to the category selected
function displayContents(v){
  switch(v){
    case "fruits":
      for(i=0; i<fruitsLen; i++){
        listToDisplay += "
" + fruits[i];
      }
      document.getElementById('displayDiv').innerHTML = listToDisplay;
      break;
    case "vegetables":
      for(i=0; i<vegLen; i++){
        listToDisplay += "
" + vegetables[i];
      }
      document.getElementById('displayDiv').innerHTML = listToDisplay;
      break;
    default:
      document.getElementById('displayDiv').innerHTML = "Invalid Selection.";
  }
}

//function to go to particular page
function goToPage(){

}

<!DOCTYPE html>

Select Category:
<select id="categorySelect" onChange="displayContents(this.value)">
 <option value="first">Please select a category</option>
  <option value="fruits">Fruits</option>
  <option value="vegetables">Vegetables</option>
</select>

 <input type="button" value="Go to Related Page" onclick="goToPage()">

Body:
By this you can redirect to a desired page based on the selected option

Create two pages fruits.html and vegetables.html in the same directory

// JavaScript
'use strict';

var category = ["Fruits", "Vegetables"];
var fruits = ["Apple", "Banana", "Orange"];
var fruitsLen = fruits.length;
var vegetables = ["Cauliflower", "Brinjal", "Potato"];
var vegLen = vegetables.length;
var optionSelected = "";       //Changed Here

var i;
var listToDisplay = "";

//function to display contents accroding to the category selected
function displayContents(v){
  listToDisplay = "";               // Changed Here
  optionSelected = v;               // Changed Here
  switch(v){
    case "fruits":
      for(i=0; i<fruitsLen; i++){
        listToDisplay += "<br>" + fruits[i];
      }
      document.getElementById('displayDiv').innerHTML = listToDisplay;
      break;
    case "vegetables":
      for(i=0; i<vegLen; i++){
        listToDisplay += "<br>" + vegetables[i];
      }
      document.getElementById('displayDiv').innerHTML = listToDisplay;
      break;
    default:
      document.getElementById('displayDiv').innerHTML = "Invalid Selection.";
  }
}

//function to go to particular page

function goToPage(){
    if(optionSelected === "fruits")              //Changed Here
        window.location = "fruits.html";
    else if(optionSelected === "vegetables")
        window.location = "vegetables.html";
}

HTML Code

<!DOCTYPE html>
<html>
<head>
  <script src="script.js"></script>
</head>
<body>

<div id="categoryDiv">
Select Category:
<select id="categorySelect" onChange="displayContents(this.value)">
    <option value="first">Please select a category</option>
  <option value="fruits">Fruits</option>
  <option value="vegetables">Vegetables</option>
</select>
<br>
</div>

<div id="displayDiv">

</div>

<div id="buttonDiv">
    <br>
    <input type="button" value="Go to Related Page" onclick="goToPage()">
</div>

</body>
</html>


问:
Auth state change listener being fired twice?
When my page loads I need to know whether the user is logged in and perform different tasks based on that. The first thing I do is check if the they are logged in, but for some reason the if statement to check that is being validated twice. Here is my code:

```<code>override func viewDidAppear(_ animated: Bool) {
    FIRAuth.auth()?.addStateDidChangeListener { auth, user in
        if let user = user {
           print("User is logged in")
        }
</code>```

"User is logged in" gets printed out twice to the console when the page loads instead of just once. Am I doing something incorrectly?

答:
i faced same problem. and it is not for logged in . it can be faced flowing option
 https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseAuth.AuthStateListener

Right after the listener has been registered

When a user is signed in

When the current user is signed out

When the current user changes

When there is a change in the current user's token

so just crate a flag then check that one . or check response nil or not

Try this way :

```<code>override func viewDidAppear(_ animated: Bool) {
    FIRAuth.auth()?.addStateDidChangeListener { auth, user in
        if let user = user {
            if user != nil {
               print("User is logged in")
           }
        }
</code>```

Note : try to use both  flag and check user =! nil

Body:
When my page loads I need to know whether the user is logged in and perform different tasks based on that. The first thing I do is check if the they are logged in, but for some reason the if statement to check that is being validated twice. Here is my code:

override func viewDidAppear(_ animated: Bool) {
    FIRAuth.auth()?.addStateDidChangeListener { auth, user in
        if let user = user {
           print("User is logged in")
        }

"User is logged in" gets printed out twice to the console when the page loads instead of just once. Am I doing something incorrectly?

Body:
i faced same problem. and it is not for logged in . it can be faced flowing option
 https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseAuth.AuthStateListener

Right after the listener has been registered

When a user is signed in

When the current user is signed out

When the current user changes

When there is a change in the current user's token

so just crate a flag then check that one . or check response nil or not

Try this way :

override func viewDidAppear(_ animated: Bool) {
    FIRAuth.auth()?.addStateDidChangeListener { auth, user in
        if let user = user {
            if user != nil {
               print("User is logged in")
           }
        }

Note : try to use both  flag and check user =! nil


问:
Application stopped working unexpectedly. Please try again
I am trying to display the name and number of a contact from android phone book, i have one contact stored in my AVD. can anyone tell me whats wrong with this code please...it is showing application stopped working Please try again...thanks in advance...</p>

```<code>public class get extends Activity {
        private void getColumnData(Cursor cur)
    {
        if(cur.moveToFirst())
        {
            int numi=cur.getColumnIndex(People.NUMBER);
            int namei=cur.getColumnIndex(People.NAME);
            String name,num;
            do{
                name=cur.getString(namei);
                num=cur.getString(numi);

            }while(cur.moveToNext());
        }
    }
    @Override

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Uri u=People.CONTENT_URI;
        String[] proj=new String[]{People.NAME,People.NUMBER};
        Cursor cur=managedQuery(u, proj, null, null, null);
        getColumnData(cur);
        TextView tv=new TextView(this);
        tv.setText("First step");
        setContentView(tv);
    }
}
</code>```

答:
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;

ListView lv=(ListView)findViewById(R.id.list_view);

```<code>Uri uri=Contacts.CONTENT_URI;

String [] projection=new String[]{ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME};
Cursor c=managedQuery(uri,null, null, null, null);
String[] from=new String[]{ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME};
int[] to=new int[]{android.R.id.text1,android.R.id.text2};
SimpleCursorAdapter sAdapter=new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2, c, from, to);
lv.setAdapter(sAdapter);
</code>```

Also put

in the manifest file

Body:
I am trying to display the name and number of a contact from android phone book, i have one contact stored in my AVD. can anyone tell me whats wrong with this code please...it is showing application stopped working Please try again...thanks in advance...

public class get extends Activity {
        private void getColumnData(Cursor cur)
    {
        if(cur.moveToFirst())
        {
            int numi=cur.getColumnIndex(People.NUMBER);
            int namei=cur.getColumnIndex(People.NAME);
            String name,num;
            do{
                name=cur.getString(namei);
                num=cur.getString(numi);

            }while(cur.moveToNext());
        }
    }
    @Override

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Uri u=People.CONTENT_URI;
        String[] proj=new String[]{People.NAME,People.NUMBER};
        Cursor cur=managedQuery(u, proj, null, null, null);
        getColumnData(cur);
        TextView tv=new TextView(this);
        tv.setText("First step");
        setContentView(tv);
    }
}

Body:
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;

ListView lv=(ListView)findViewById(R.id.list_view);

Uri uri=Contacts.CONTENT_URI;

String [] projection=new String[]{ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME};
Cursor c=managedQuery(uri,null, null, null, null);
String[] from=new String[]{ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME};
int[] to=new int[]{android.R.id.text1,android.R.id.text2};
SimpleCursorAdapter sAdapter=new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2, c, from, to);
lv.setAdapter(sAdapter);

Also put

in the manifest file


问:
jquery update total based on checkboxes
I have a form where based on checkbox total value will be updated

Here is my form

```<code><label class="checkbox">
        <input type="checkbox" class="check" value="23">SEO
    </label>
    <label class="checkbox">
        <input type="checkbox" class="check" value="34">XYZ
    </label>
    <label class="checkbox">
            <input type="checkbox" class="check" value="45">Logo Design
    </label>

    <span class="product-price" id="total" >45</span>
</code>```

jQuery I have used

```<code>  $('input[type=checkbox]').change(function () {
        var val = parseFloat(this.value),
            totalVal = parseFloat($('#total').val());
        if (this.checked) {
            $('#total').val((totalVal + val).toFixed(2));
        } else {
            $('#total').val((totalVal - val).toFixed(2));
        }
    });
</code>```

But nothing get updated.What could be the possible Error?
Any solution please

答:
Change it:

```<code>if (this.checked) {
            $('#total').val((totalVal + val).toFixed(2));
        } else {
            $('#total').val((totalVal - val).toFixed(2));
        }
</code>```

to

```<code>if (this.checked) {
            $('#total').text((totalVal + val).toFixed(2));
        } else {
            $('#total').text((totalVal - val).toFixed(2));
        }
</code>```

as span do not have a value attribute, the text you see is the text attribute associated with that.

Title: jquery update total based on checkboxes

Body:
I have a form where based on checkbox total value will be updated

Here is my form

        <input type="checkbox" class="check" value="23">SEO

        <input type="checkbox" class="check" value="34">XYZ

            <input type="checkbox" class="check" value="45">Logo Design

    45

jQuery I have used

  $('input[type=checkbox]').change(function () {
        var val = parseFloat(this.value),
            totalVal = parseFloat($('#total').val());
        if (this.checked) {
            $('#total').val((totalVal + val).toFixed(2));
        } else {
            $('#total').val((totalVal - val).toFixed(2));
        }
    });

But nothing get updated.What could be the possible Error?
Any solution please

Body:
Change it:

if (this.checked) {
            $('#total').val((totalVal + val).toFixed(2));
        } else {
            $('#total').val((totalVal - val).toFixed(2));
        }

to

if (this.checked) {
            $('#total').text((totalVal + val).toFixed(2));
        } else {
            $('#total').text((totalVal - val).toFixed(2));
        }

as span do not have a value attribute, the text you see is the text attribute associated with that.


问:
Mouseenter only fires on first mouseenter attempt
I'm trying to slide each ul > li down when hovering over it's parent li and then slide it back up on the mouseleave event

The code works great on the first mouseenter and mouseleave. But when I hover my mouse back over a panel that has already fired once, the mouseenter function doesn't fire a second time  I'm know I'm close but not sure where I went wrong

Fiddle away here:
http://jsfiddle.net/k2b5a62j/1/

I've tried the fiddle with hover as well with no luck

**I've updated the fiddle a bit for simplicity

答:
I am pretty sure what you mean is, you want, on hover, to be able to view all the items rather than them immediately disappearing.  I slightly changed your DOM and jQuery selectors to achieve this:

//Per comment of the original poster:
$('ul li div').on("mouseenter", function(event){
    $(this).find('ul').slideDown('fast', function(){
        // Done.
    });
    event.preventDefault();
}).on("mouseleave",function (event) {
    $(this).find('ul').slideUp('fast', function(){
        // Done.
    });
    event.preventDefault();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul li ul {
    display: none;
}</code>```

        Product1

Item1

Item2

Item3

Item4

Product2

Item product 2

Item product 2

Item product 2

Product3

Item product 2

Item product 2

```
</div>
</div>
</p>

<p>Reply to the asker's comment as to have each li display one at a time:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>jQuery(document).ready(function($) {

  $('.inner-link').hide();

  $('.link').mouseenter(function() {
    $(this)
     .find('ul')
      .find('li')
      .stop(true,true)
      .each(function(index) {
       $(this)
         .delay(500 * index)
          .slideDown(500);
     });
  });

  $('.link').mouseleave(function() {
    $(this)
     .find('ul')
      .find('li')
      .stop(true,true)
      .each(function(index) {
       $(this)
         .delay(500 * index)
          .slideUp(500);
     });
  });

});</code>```

.link {
  position: relative;
  right: 0%;
  width: 8%;
  list-style-type: none;
  vertical-align: middle;
  display: table-cell;
  outline: none;
  height: 100%;
  text-align: center;
  margin: 0px 11px;
}

.inner-list {
  position: absolute;
  width: 100%;
  margin: 0px auto;
  left: 0px;
}

.inner-link {
  list-style-type: none;
  width: 100%;
  margin: 0px 0px 0px -40px;
  border-bottom: 1px black solid;
}

.inner-link:first-child {
  padding-top: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="nav-container">
  <li class="link">Panel 1
    <ul class="inner-list">
      <li class="inner-link">Link #1</li>
      <li class="inner-link">Link #2</li>
      <li class="inner-link">Link #3</li>
      <li class="inner-link">Link #4</li>
      <li class="inner-link">Link #5</li>
    </ul>
  </li>
  <li class="link">Panel 2
    <ul class="inner-list">
      <li class="inner-link">Link #1</li>
      <li class="inner-link">Link #2</li>
      <li class="inner-link">Link #3</li>
      <li class="inner-link">Link #4</li>
      <li class="inner-link">Link #5</li>
    </ul>
  </li>
  <li class="link">Panel 3
    <ul class="inner-list">
      <li class="inner-link">Link #1</li>
      <li class="inner-link">Link #2</li>
      <li class="inner-link">Linnk #3</li>
      <li class="inner-link">Link #4</li>
      <li class="inner-link">Link #5</li>
    </ul>
  </li>
  <li class="link">Panel 4
    <ul class="inner-list">
      <li class="inner-link">Link #1</li>
      <li class="inner-link">Link #2</li>
      <li class="inner-link">Linnk #3</li>
      <li class="inner-link">Link #4</li>
      <li class="inner-link">Link #5</li>
    </ul>
  </li>

</ul></code>```

Body:
I am pretty sure what you mean is, you want, on hover, to be able to view all the items rather than them immediately disappearing.  I slightly changed your DOM and jQuery selectors to achieve this:

//Per comment of the original poster:
$('ul li div').on("mouseenter", function(event){
    $(this).find('ul').slideDown('fast', function(){
        // Done.
    });
    event.preventDefault();
}).on("mouseleave",function (event) {
    $(this).find('ul').slideUp('fast', function(){
        // Done.
    });
    event.preventDefault();
});

ul li ul {
    display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <ul>
        <li><div>
        <a href="#">Product1</a>
            <ul id="test">
                <li>Item1</li>
                <li>Item2</li>
                <li>Item3</li>
                <li>Item4</li>
            </ul>
        </div></li>
        <li><div><a href="#">Product2</a>
            <ul>
                <li>Item product 2</li>
                <li>Item product 2</li>
                <li>Item product 2</li>
            </ul>
        </div></li>
        <li><div><a href="#">Product3</a>
            <ul>
                <li>Item product 2</li>
                <li>Item product 2</li>
            </ul>
        </div></li>
    </ul>
</div>

Reply to the asker's comment as to have each li display one at a time:

jQuery(document).ready(function($) {

  $('.inner-link').hide();

  $('.link').mouseenter(function() {
    $(this)
     .find('ul')
      .find('li')
      .stop(true,true)
      .each(function(index) {
       $(this)
         .delay(500 * index)
          .slideDown(500);
     });
  });

  $('.link').mouseleave(function() {
    $(this)
     .find('ul')
      .find('li')
      .stop(true,true)
      .each(function(index) {
       $(this)
         .delay(500 * index)
          .slideUp(500);
     });
  });

});

.link {
  position: relative;
  right: 0%;
  width: 8%;
  list-style-type: none;
  vertical-align: middle;
  display: table-cell;
  outline: none;
  height: 100%;
  text-align: center;
  margin: 0px 11px;
}

.inner-list {
  position: absolute;
  width: 100%;
  margin: 0px auto;
  left: 0px;
}

.inner-link {
  list-style-type: none;
  width: 100%;
  margin: 0px 0px 0px -40px;
  border-bottom: 1px black solid;
}

.inner-link:first-child {
  padding-top: 20px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="nav-container">
  <li class="link"><a href="">Panel 1</a>
    <ul class="inner-list">
      <li class="inner-link">Link #1</li>
      <li class="inner-link">Link #2</li>
      <li class="inner-link">Link #3</li>
      <li class="inner-link">Link #4</li>
      <li class="inner-link">Link #5</li>
    </ul>
  </li>
  <li class="link"><a href="">Panel 2</a>
    <ul class="inner-list">
      <li class="inner-link">Link #1</li>
      <li class="inner-link">Link #2</li>
      <li class="inner-link">Link #3</li>
      <li class="inner-link">Link #4</li>
      <li class="inner-link">Link #5</li>
    </ul>
  </li>
  <li class="link"><a href="">Panel 3</a>
    <ul class="inner-list">
      <li class="inner-link">Link #1</li>
      <li class="inner-link">Link #2</li>
      <li class="inner-link">Linnk #3</li>
      <li class="inner-link">Link #4</li>
      <li class="inner-link">Link #5</li>
    </ul>
  </li>
  <li class="link"><a href="">Panel 4</a>
    <ul class="inner-list">
      <li class="inner-link">Link #1</li>
      <li class="inner-link">Link #2</li>
      <li class="inner-link">Linnk #3</li>
      <li class="inner-link">Link #4</li>
      <li class="inner-link">Link #5</li>
    </ul>
  </li>

</ul>