问:
How to use standard evaluation in dplyr for nested functions
In a data frame I want to have a column with a number extracted from another column which name is only given as a variable:

```<code>> name <- 'x'
> df <- data.frame(x = '01abc78')
> mutate_(df, number = as.numeric(substr(name, 6, 7)))
</code>```

But it puts 'NA' values in the new column:

```<code>        x number
1 01abc78     NA
</code>```

Curiously enough

```<code>> mutate_(df, number = substr(name, 6, 7))
</code>```

throws an error:

```<code>Error in parse(text = x)[[1]] : subscript out of bounds
</code>```

Only

```<code>> mutate_(df, number = name)
</code>```

works but does a different thing. Also get() is no solution:

```<code>> mutate(df, number = as.numeric(substr(get(name), 6, 7)))
Error: object 'x' not found
</code>```

Of course I could do

```<code>mutate_(df, number = name) %>% mutate(number = as.numeric(substr(number, 6, 7)
</code>```

but it sure isn't pretty.

How can I fix this to use either only mutate_ or get()?

答:
We could use rlang::sym to convert it to symbol and then use !! to get it evaluated

```<code>df %>%
   mutate(number = substr(!! rlang::sym(name), 6, 7))
#        x number
#1 01abc78     78
</code>```

Body:
In a data frame I want to have a column with a number extracted from another column which name is only given as a variable:

> name <- 'x'
> df <- data.frame(x = '01abc78')
> mutate_(df, number = as.numeric(substr(name, 6, 7)))

But it puts 'NA' values in the new column:

        x number
1 01abc78     NA

Curiously enough

> mutate_(df, number = substr(name, 6, 7))

throws an error:

Error in parse(text = x)[[1]] : subscript out of bounds

Only

> mutate_(df, number = name)

works but does a different thing. Also get() is no solution:

> mutate(df, number = as.numeric(substr(get(name), 6, 7)))
Error: object 'x' not found

Of course I could do

mutate_(df, number = name) %>% mutate(number = as.numeric(substr(number, 6, 7)

but it sure isn't pretty.

How can I fix this to use either only mutate_ or get()?

Body:
We could use rlang::sym to convert it to symbol and then use !! to get it evaluated

df %>%
   mutate(number = substr(!! rlang::sym(name), 6, 7))
#        x number
#1 01abc78     78


来源: stackexchange

问:
asp.net mvc how to manage urls/links and routing centrally (c# + js)
I keep running into problems with URLs and routing.

Couldn't find an answer on SO.

I would like to manage all of my urls/links in a single place.

This is for my C# MVC code and the js/jquery ajax code.

These urls are scattered throughout my application.

Moving to a production server needs some fixes and I don't like the fact that I need to look for all of the occurrences in the application.

I don't mind fixing this once - but I would like to do it only once.

Any ideas how to manage all of these links/urls as a group will be very appreciated.

Be happy ad enjoy life, Julian

答:
Urls should be managed in a single place: the RegisterRoutes static method in Global.asax. In absolutely every other part of your application you should use Html helpers when dealing/generating urls. This way you will never have problems because helpers take into account your routing system.

So instead of writing:

```<code>$('#foo').click(function() {
    $('#result').load('/mycontroller/myaction');
    return false;
});
</code>```

you use an HTML helper to generate this foo:

```<code><%: Html.Action("foo", "myaction", "mycontroller") %>
</code>```

and then:

```<code>$('#foo').click(function() {
    $('#result').load(this.href);
    return false;
});
</code>```

Never hardcode a single url in your application except of course in global.asax which is the only centralized place urls should be defined. So basically every time you find yourself writing something of the form /foo/bar in some other part than global.asax you are doing it wrong.

ContentLicense: CC BY-SA 2.5

Body:
Urls should be managed in a single place: the RegisterRoutes static method in Global.asax. In absolutely every other part of your application you should use Html helpers when dealing/generating urls. This way you will never have problems because helpers take into account your routing system.

So instead of writing:

$('#foo').click(function() {
    $('#result').load('/mycontroller/myaction');
    return false;
});

you use an HTML helper to generate this foo:

<%: Html.Action("foo", "myaction", "mycontroller") %>

and then:

$('#foo').click(function() {
    $('#result').load(this.href);
    return false;
});

Never hardcode a single url in your application except of course in global.asax which is the only centralized place urls should be defined. So basically every time you find yourself writing something of the form /foo/bar in some other part than global.asax you are doing it wrong.


问:
Python - Calling Multiple Functions (Unresolved Reference). When to use a global variable?
I've just started learning functions and I understand the basics, however I don't understand how to call them in more complex scripts (such as below).

The example script below is attempting to pull football results from a MySQL db, extract to CSV, then import from CSV and place into a HTML table and send as an email. The issue I am having is that I need to compile the output of each function (e.g. Premier League, League One, League Two) into a report table - which I achieve using 'report':

```<code>report = ""
report += htmlpremleague
report += "<br><br>"
report += htmlleagueone
report += "<br><br>"
return report
</code>```

Which is joining the table so I can send all the results in one email as a HTML table. The issue I am having is that 'report' can't locate the HTML's e.g. 'htmlpremleague' due to it being in a function. But I can't simply replace it with "report += premier_league()"as there is other stuff in that function, not just the html. Ideally i'd like to get functions working because (a) it's fun learning them! and (b) it would be cool to be able to run each individual league on their own, e.g. generate a report solely on premier league. The example script below runs fine, however this is due to the report html part being global and sitting outside of the functions. Ideally i'd like them inside so I can achieve the above.

I'm new here and i've tried to stick to the guidelines but please let me know if i've done anything incorrect, or I can provide anything further.

To reiterate, the desired output would be for everything to be in a callable function e.g. Alternatively, would I just place 'report' / each table as a global variable?

```<code>def league_one():

    query = "SELECT footballteam as ftt, goals, points FROM
    footballdbl_league_one plfdb ORDER BY point desc"
    leagueonecursor.execute(query)
    leagueonerows = leagueonecursor.fetchall()

    with open('league_one.csv', 'wb') as file2:
        wr = csv.writer(file2, quoting=csv.QUOTE_ALL)
        wr.writerow(["Team", "Goals", "Points"])
        wr.writerows(leagueonerows)
        print ("csv2 created")

        textleagueone = """
        """
        htmlleagueone = """
        <html><body><p><u><h3><b>Highest Run Time</b></h3></u></p>
        {table2}
        <br><br>
        </body></html>
        """

        with open('league_one.csv') as input_file2:
            reader = csv.reader(input_file2)
            leagueonereader = list(reader)

            textleagueone =
            textleagueone.format(table2=tabulate(leagueonereader,
            headers="firstrow", tablefmt="grid"))
            htmlleagueone =
            htmlleagueone.format(table2=tabulate(leagueonereader,
            headers="firstrow", tablefmt="html"))
</code>```

/Main Example Football Script:

```<code>con = pymysql.connect(user='',password='',host='',database='')
cursor = con.cursor()

# probably not necessary
premleaguecursor = con.cursor()
leagueonecursor = con.cursor()

def premier_league():
    query = "SELECT footballteam as ftt, goals, points FROM footballdbl_prem_league plfdb ORDER BY point desc"
    premleaguecursor.execute(query)
    premleaguerows = premleaguecursor.fetchall()

    with open('prem_league.csv', 'wb') as file1:
        wr = csv.writer(file1, quoting=csv.QUOTE_ALL)
        wr.writerow(["Team", "Goals", "Points"])
        wr.writerows(premleaguerows)
        print ("premier league csv created")

textpremleague = """
"""

htmlpremleague = """
<html><body><p><font size="+1"><u><h3><b>Premier League</b></h3></u></font></p>
{table1}
</body></html>
    """

with open('prem_league.csv') as input_file1:
    reader = csv.reader(input_file1)
    premleaguereader = list(reader)

textpremleague = textpremleague.format(table1=tabulate(premleaguereader, headers="firstrow", tablefmt="grid"))
htmlpremleague = htmlpremleague.format(table1=tabulate(premleaguereader, headers="firstrow", tablefmt="html"))

def league_one():

    query = "SELECT footballteam as ftt, goals, points FROM footballdbl_league_one plfdb ORDER BY point desc"
    leagueonecursor.execute(query)
    leagueonerows = leagueonecursor.fetchall()

    with open('league_one.csv', 'wb') as file2:
        wr = csv.writer(file2, quoting=csv.QUOTE_ALL)
        wr.writerow(["Team", "Goals", "Points"])
        wr.writerows(leagueonerows)
        print ("csv2 created")

textleagueone = """
"""

htmlleagueone = """
<html><body><p><u><h3><b>Highest Run Time</b></h3></u></p>
{table2}
<br><br>
</body></html>
"""

with open('league_one.csv') as input_file2:
    reader = csv.reader(input_file2)
    leagueonereader = list(reader)

textleagueone = textleagueone.format(table2=tabulate(leagueonereader, headers="firstrow", tablefmt="grid"))
htmlleagueone = htmlleagueone.format(table2=tabulate(leagueonereader, headers="firstrow", tablefmt="html"))

# def league_two():

# def league_three():

def report():
    report = ""
    report += htmlpremleague
    report += "<br><br>"
    report += htmlleagueone
    report += "<br><br>"
    return report

def send_email():

    report()
    me = ''
    password = ''
    server = ''
    you = ''

    message = MIMEMultipart(
        "alternative", None, [MIMEText(report, 'html')])

    message['Subject'] = "FOOTBALL REPORT"
    message['From'] = me
    message['To'] = you
    server = smtplib.SMTP(server)
    server.ehlo()
    server.starttls()
    server.login(me, password)
    server.sendmail(me, you, message.as_string())
    server.quit()

def main():
    premier_league()
    league_one()
    report()
    send_email()
</code>```

答:
Simply provide the data you need in your def to it - I choose to do it as list, you could also pass it serarately like this def report2(myOne, myTwo): ... and call it as report2(one,two) - no need to use globals for that.

```<code>def leageOne():
    # do stuff
    stuff = "MyLeageOneResult"
    return stuff

def leageTwo():
    # do otherstuff
    otherstuff = "MyOtherResult"
    return otherstuff

def report(myInputList):
    return '<br/>'.join(myInputList)

one = leageOne()
two = leageTwo()

email = report([one , two])

print email
</code>```

Output:

```<code>MyLeageOneResult<br/>MyOtherResult
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've just started learning functions and I understand the basics, however I don't understand how to call them in more complex scripts (such as below).

The example script below is attempting to pull football results from a MySQL db, extract to CSV, then import from CSV and place into a HTML table and send as an email. The issue I am having is that I need to compile the output of each function (e.g. Premier League, League One, League Two) into a report table - which I achieve using 'report':

report = ""
report += htmlpremleague
report += "

"
report += htmlleagueone
report += "

"
return report

Which is joining the table so I can send all the results in one email as a HTML table. The issue I am having is that 'report' can't locate the HTML's e.g. 'htmlpremleague' due to it being in a function. But I can't simply replace it with "report += premier_league()"as there is other stuff in that function, not just the html. Ideally i'd like to get functions working because (a) it's fun learning them! and (b) it would be cool to be able to run each individual league on their own, e.g. generate a report solely on premier league. The example script below runs fine, however this is due to the report html part being global and sitting outside of the functions. Ideally i'd like them inside so I can achieve the above.

I'm new here and i've tried to stick to the guidelines but please let me know if i've done anything incorrect, or I can provide anything further.

To reiterate, the desired output would be for everything to be in a callable function e.g. Alternatively, would I just place 'report' / each table as a global variable?

def league_one():

    query = "SELECT footballteam as ftt, goals, points FROM
    footballdbl_league_one plfdb ORDER BY point desc"
    leagueonecursor.execute(query)
    leagueonerows = leagueonecursor.fetchall()

    with open('league_one.csv', 'wb') as file2:
        wr = csv.writer(file2, quoting=csv.QUOTE_ALL)
        wr.writerow(["Team", "Goals", "Points"])
        wr.writerows(leagueonerows)
        print ("csv2 created")

        textleagueone = """
        """
        htmlleagueone = """

Highest Run Time

        {table2}

        """

        with open('league_one.csv') as input_file2:
            reader = csv.reader(input_file2)
            leagueonereader = list(reader)

            textleagueone =
            textleagueone.format(table2=tabulate(leagueonereader,
            headers="firstrow", tablefmt="grid"))
            htmlleagueone =
            htmlleagueone.format(table2=tabulate(leagueonereader,
            headers="firstrow", tablefmt="html"))

/Main Example Football Script:

con = pymysql.connect(user='',password='',host='',database='')
cursor = con.cursor()

# probably not necessary
premleaguecursor = con.cursor()
leagueonecursor = con.cursor()

def premier_league():
    query = "SELECT footballteam as ftt, goals, points FROM footballdbl_prem_league plfdb ORDER BY point desc"
    premleaguecursor.execute(query)
    premleaguerows = premleaguecursor.fetchall()

    with open('prem_league.csv', 'wb') as file1:
        wr = csv.writer(file1, quoting=csv.QUOTE_ALL)
        wr.writerow(["Team", "Goals", "Points"])
        wr.writerows(premleaguerows)
        print ("premier league csv created")

textpremleague = """
"""

htmlpremleague = """

Premier League

{table1}

    """

with open('prem_league.csv') as input_file1:
    reader = csv.reader(input_file1)
    premleaguereader = list(reader)

textpremleague = textpremleague.format(table1=tabulate(premleaguereader, headers="firstrow", tablefmt="grid"))
htmlpremleague = htmlpremleague.format(table1=tabulate(premleaguereader, headers="firstrow", tablefmt="html"))

def league_one():

    query = "SELECT footballteam as ftt, goals, points FROM footballdbl_league_one plfdb ORDER BY point desc"
    leagueonecursor.execute(query)
    leagueonerows = leagueonecursor.fetchall()

    with open('league_one.csv', 'wb') as file2:
        wr = csv.writer(file2, quoting=csv.QUOTE_ALL)
        wr.writerow(["Team", "Goals", "Points"])
        wr.writerows(leagueonerows)
        print ("csv2 created")

textleagueone = """
"""

htmlleagueone = """

Highest Run Time

{table2}

"""

with open('league_one.csv') as input_file2:
    reader = csv.reader(input_file2)
    leagueonereader = list(reader)

textleagueone = textleagueone.format(table2=tabulate(leagueonereader, headers="firstrow", tablefmt="grid"))
htmlleagueone = htmlleagueone.format(table2=tabulate(leagueonereader, headers="firstrow", tablefmt="html"))

# def league_two():

# def league_three():

def report():
    report = ""
    report += htmlpremleague
    report += "

"
    report += htmlleagueone
    report += "

"
    return report

def send_email():

    report()
    me = ''
    password = ''
    server = ''
    you = ''

    message = MIMEMultipart(
        "alternative", None, [MIMEText(report, 'html')])

    message['Subject'] = "FOOTBALL REPORT"
    message['From'] = me
    message['To'] = you
    server = smtplib.SMTP(server)
    server.ehlo()
    server.starttls()
    server.login(me, password)
    server.sendmail(me, you, message.as_string())
    server.quit()

def main():
    premier_league()
    league_one()
    report()
    send_email()

Body:
Simply provide the data you need in your def to it - I choose to do it as list, you could also pass it serarately like this def report2(myOne, myTwo): ... and call it as report2(one,two) - no need to use globals for that.

def leageOne():
    # do stuff
    stuff = "MyLeageOneResult"
    return stuff

def leageTwo():
    # do otherstuff
    otherstuff = "MyOtherResult"
    return otherstuff

def report(myInputList):
    return '<br/>'.join(myInputList)

one = leageOne()
two = leageTwo()

email = report([one , two])

print email

Output:

MyLeageOneResult<br/>MyOtherResult


问:
How to increase or decrease textbox value using page object Model
I have to input the numeric value in this textbox, I tried using xpath but id is keep on changing everytime,I added the picture and source code below.

Here is the source code i managed to select using Xpath but id is keep on changing

```<code><input class="t-input" data-val="true" data-val-number="The field Amount must be a number." id="CaseTypes_64b4d9c0-c574-40bd-a450-0c6f94844a2e__Amount" name="CaseTypes[64b4d9c0-c574-40bd-a450-0c6f94844a2e].Amount" style="width: 110px; color: rgb(255, 255, 255);" type="text">
</code>```

答:
The id in your example is

CaseTypes_64b4d9c0-c574-40bd-a450-0c6f94844a2e__Amount

I'm guessing the part between CaseTypes and Amount is random.

You can use the following to select the textbox:

```<code>driver.FindElement(By.CssSelector("*[id^='CaseTypes'][id$='Amount']"));
</code>```

id^='' means: value should start with
id$='' means: value should end with

Combining these two allows you to search for the textbox even when the part between CaseTypes and Amount changes.

After that you can call.SendKeys("Enter your text here") to send text to the textbox

Body:
I have to input the numeric value in this textbox, I tried using xpath but id is keep on changing everytime,I added the picture and source code below.

Here is the source code i managed to select using Xpath but id is keep on changing

<input class="t-input" data-val="true" data-val-number="The field Amount must be a number." id="CaseTypes_64b4d9c0-c574-40bd-a450-0c6f94844a2e__Amount" name="CaseTypes[64b4d9c0-c574-40bd-a450-0c6f94844a2e].Amount" style="width: 110px; color: rgb(255, 255, 255);" type="text">

Body:
The id in your example is

CaseTypes_64b4d9c0-c574-40bd-a450-0c6f94844a2e__Amount

I'm guessing the part between CaseTypes and Amount is random.

You can use the following to select the textbox:

driver.FindElement(By.CssSelector("*[id^='CaseTypes'][id$='Amount']"));

id^='' means: value should start with
id$='' means: value should end with

Combining these two allows you to search for the textbox even when the part between CaseTypes and Amount changes.

After that you can call.SendKeys("Enter your text here") to send text to the textbox


问:
LDAP query filter by member count in Active Directory
Super new to Active directory and creating LDAP queries.

I want to try and pull distribution groups with only 1 member. I was trying to edit a query I used to find groups with no members, but have had no luck. I've been searching for a solution, but haven't been able to find any information. I was just curious if this was even possible.

```<code>(&(&(&(objectCategory=group)(member=1)(objectClass=group)(proxyAddresses=*@domain.com))))
</code>```

答:
No, you can't just with a single LDAP query.

The (member=1) filter does not work because it just try to match an invalid dn ('1'). By the way the whole filter is wrong, you don't need to nest the conditions nor to add & operators for each. However you can still add (!(member=*)) to exclude groups that don't have any member. So in your situation, a correct filter should look like this :

```<code>(&(objectCategory=group)(objectClass=group)(proxyAddresses=*@domain.com)(!(member=*)))
</code>```

To filter groups having only one member, you would have in a first step to search for the groups using the filter above, then iterate over each group entries, read the member attribute to get the count manually and exclude groups with more than one member.

You can also add a custom attribute to group objects so that you can store member count in it and finally be able to apply filters as you intended first (e.g.  memberCount=1), that is in a single query. BUT this of course also requires to maintain the attribute.

Body:
Super new to Active directory and creating LDAP queries.

I want to try and pull distribution groups with only 1 member. I was trying to edit a query I used to find groups with no members, but have had no luck. I've been searching for a solution, but haven't been able to find any information. I was just curious if this was even possible.

(&(&(&(objectCategory=group)(member=1)(objectClass=group)(proxyAddresses=*@domain.com))))

Body:
No, you can't just with a single LDAP query.

The (member=1) filter does not work because it just try to match an invalid dn ('1'). By the way the whole filter is wrong, you don't need to nest the conditions nor to add & operators for each. However you can still add (!(member=*)) to exclude groups that don't have any member. So in your situation, a correct filter should look like this :

(&(objectCategory=group)(objectClass=group)(proxyAddresses=*@domain.com)(!(member=*)))

To filter groups having only one member, you would have in a first step to search for the groups using the filter above, then iterate over each group entries, read the member attribute to get the count manually and exclude groups with more than one member.

You can also add a custom attribute to group objects so that you can store member count in it and finally be able to apply filters as you intended first (e.g.  memberCount=1), that is in a single query. BUT this of course also requires to maintain the attribute.


问:
How to set a Multiline-TextView non-editable
I have a TextView which is from inputType="textMultiLine". The problem is, when I click (and hold) in a free part of the TextView (a part where is no text), it presents me the option of pasting text in. And when I do so, it overwrites the existing text with the text in the clipboard.
I don't want this behavior. What can I do to make the TextView non-editable?

this is the xml-Code:

```<code><TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1. Hello, Dies ist ein Beispielsatz. \n2. Dies ist der zweite Satz."
        android:textSize="20dp"
        android:inputType="textMultiLine"
        />
</code>```

Note:
If I remove the inputType="textMultiLine", the option of pasting text is no longer presented. But I want the TextView to be multiline.

答:
Try this make you TextView to android:longClickable="false"

```<code><TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1. Hello, Dies ist ein Beispielsatz. \n2. Dies ist der zweite Satz."
        android:longClickable="false"
        android:textSize="20dp"
        android:inputType="textMultiLine"
        />
</code>```

Body:
I have a TextView which is from inputType="textMultiLine". The problem is, when I click (and hold) in a free part of the TextView (a part where is no text), it presents me the option of pasting text in. And when I do so, it overwrites the existing text with the text in the clipboard.
I don't want this behavior. What can I do to make the TextView non-editable?

this is the xml-Code:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1. Hello, Dies ist ein Beispielsatz. \n2. Dies ist der zweite Satz."
        android:textSize="20dp"
        android:inputType="textMultiLine"
        />

Note:
If I remove the inputType="textMultiLine", the option of pasting text is no longer presented. But I want the TextView to be multiline.

Body:
Try this make you TextView to android:longClickable="false"

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1. Hello, Dies ist ein Beispielsatz. \n2. Dies ist der zweite Satz."
        android:longClickable="false"
        android:textSize="20dp"
        android:inputType="textMultiLine"
        />


问:
Close all other sub-menus on click
Hello everyone,
Thank you for taking the time to view this post.

I have the following problem I am trying to create a menu with sub-menus.

Menu should:

Open sub-menus on click. (working)

Sub-menus stay open on selected menu. (working)

3. Once clicked in other menus the previous sub-menus should close. (not working)

HTML

```<code>      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <ul class="bottom-menu">
      <li class="drop"><a>Hyperlink 1</a></li>
      <li class="drop"><a>Hyperlink 2</a>
      <ul id="m1" class="bottom-menu-sub">
        <li><a href="#">Hyperlink Sub</a></li>
        <li><a href="#">Hyperlink Sub</a></li>
        <li><a href="#">Hyperlink Sub</a></li>
      </ul>
    </li>
    <li class="drop"><a>Hyperlink 3</a>
      <ul id="m2">
        <li><a href="#">Hyperlink Sub</a></li>
        <li><a href="#">Hyperlink Sub</a></li>
      </ul>
    </li>
    <li class="drop"><a>Hyperlink 4</a>
      <ul id="m3">
        <li><a href="#">Hyperlink Sub</a></li>
        <li><a href="#">Hyperlink Sub</a></li>
      </ul>
    </li>
</ul>
</code>```

CSS:

```<code>      .bottom-menu li ul {
      display:none;
      }
</code>```

JS:

```<code>jQuery(function ($) {
    // jQuery code in here can safely use $
    $('.bottom-menu li')
        .css({
        cursor: "pointer"
    });

    $(".drop>a").on('click', function (eventData) {
        var $listItem = $(this).closest('li');

        $listItem.find('ul').toggle();
        $listItem.toggleClass('open');

        $.cookie('open_items', 'the_value');
        openItems = new Array();
        $("li.drop").each(function (index, item) {
            if ($(item).hasClass('open')) {
                openItems.push(index);
            }
        });
        $.cookie('open_items', openItems.join(','));
    });

    if ($.cookie('open_items') && $.cookie('open_items').length > 0) {
        previouslyOpenItems = $.cookie('open_items');
        openItemIndexes = previouslyOpenItems.split(',');
        $(openItemIndexes).each(function (index, item) {
            $("li.drop").eq(item).addClass('open').find('ul').toggle();
        });
    }
});
</code>```

jsFiddle

答:
Add This Line $(".bottom-menu li").removeClass('open');

add this css

```<code>.bottom-menu li ul {
    display:none;
}
.bottom-menu li.open ul{
  display:block;
}

jQuery(function ($) {
        // jQuery code in here can safely use $
        $('.bottom-menu li')
            .css({
            cursor: "pointer"
        });

        $(".drop>a").on('click', function (eventData) {
        $(".bottom-menu li").removeClass('open');// Add This Line
            var $listItem = $(this).closest('li');

            $listItem.toggleClass('open');

            $.cookie('open_items', 'the_value');
            openItems = new Array();
            $("li.drop").each(function (index, item) {
                if ($(item).hasClass('open')) {
                    openItems.push(index);
                }
            });
            $.cookie('open_items', openItems.join(','));
        });

        if ($.cookie('open_items') && $.cookie('open_items').length > 0) {
            previouslyOpenItems = $.cookie('open_items');
            openItemIndexes = previouslyOpenItems.split(',');
            $(openItemIndexes).each(function (index, item) {
                $("li.drop").eq(item).addClass('open');
            });
        }
    });
</code>```

https://jsfiddle.net/rb2wxurL/2/

Title: Close all other sub-menus on click

Body:
Hello everyone,
Thank you for taking the time to view this post.

I have the following problem I am trying to create a menu with sub-menus.

Menu should:

Open sub-menus on click. (working)

Sub-menus stay open on selected menu. (working)

3. Once clicked in other menus the previous sub-menus should close. (not working)

HTML

Hyperlink 1

Hyperlink 2

Hyperlink Sub

Hyperlink Sub

Hyperlink Sub

Hyperlink 3

Hyperlink Sub

Hyperlink Sub

Hyperlink 4

Hyperlink Sub

Hyperlink Sub

CSS:

      .bottom-menu li ul {
      display:none;
      }

JS:

jQuery(function ($) {
    // jQuery code in here can safely use $
    $('.bottom-menu li')
        .css({
        cursor: "pointer"
    });

    $(".drop>a").on('click', function (eventData) {
        var $listItem = $(this).closest('li');

        $listItem.find('ul').toggle();
        $listItem.toggleClass('open');

        $.cookie('open_items', 'the_value');
        openItems = new Array();
        $("li.drop").each(function (index, item) {
            if ($(item).hasClass('open')) {
                openItems.push(index);
            }
        });
        $.cookie('open_items', openItems.join(','));
    });

    if ($.cookie('open_items') && $.cookie('open_items').length > 0) {
        previouslyOpenItems = $.cookie('open_items');
        openItemIndexes = previouslyOpenItems.split(',');
        $(openItemIndexes).each(function (index, item) {
            $("li.drop").eq(item).addClass('open').find('ul').toggle();
        });
    }
});

jsFiddle

Body:
Add This Line $(".bottom-menu li").removeClass('open');

add this css

.bottom-menu li ul {
    display:none;
}
.bottom-menu li.open ul{
  display:block;
}

jQuery(function ($) {
        // jQuery code in here can safely use $
        $('.bottom-menu li')
            .css({
            cursor: "pointer"
        });

        $(".drop>a").on('click', function (eventData) {
        $(".bottom-menu li").removeClass('open');// Add This Line
            var $listItem = $(this).closest('li');

            $listItem.toggleClass('open');

            $.cookie('open_items', 'the_value');
            openItems = new Array();
            $("li.drop").each(function (index, item) {
                if ($(item).hasClass('open')) {
                    openItems.push(index);
                }
            });
            $.cookie('open_items', openItems.join(','));
        });

        if ($.cookie('open_items') && $.cookie('open_items').length > 0) {
            previouslyOpenItems = $.cookie('open_items');
            openItemIndexes = previouslyOpenItems.split(',');
            $(openItemIndexes).each(function (index, item) {
                $("li.drop").eq(item).addClass('open');
            });
        }
    });

https://jsfiddle.net/rb2wxurL/2/


问:
How do mx.graphics.codec.JPEGEncoder and com.adobe.images.JPGEncoder relate to each other?
Basically that's the question - how do mx.graphics.codec.JPEGEncoder and com.adobe.images.JPGEncoder relate to each other?

答:
The former is included in the Flash Player 10.1 ActionScript core library, while the latter is part of as3corelib, an open source ActionScript library.

Both are developed and distributed by Adobe, and the API seems to be identical (at least at first glance) so my guess is they compiled the functionality of the as3corelib class into the core library.  Have a look at this demo project comparing both classes (and some more codecs)


问:
how to implement a jruby authentication script for ZAP security proxy
my question is about script based authentication in ZAP security proxy.
I try to use ZAP security proxy for testing a hybris application. Unfortunately, I am not able to login into the application by using the default authentication methods or the zest scripting. I found the ruby extension to implement ruby code, but I am not sure how this works.
I created a new login script as you see here:
add_login_script
Afterwards a get predefined jruby code, but I don't get to work with that. There is a helper class definition in the authenticate method. Where can I find this? Where do I get the params from?
If I like to load the script to the session properties, I get the following error:load_error

Even if I declare a method called getLoggedInIndicator(), I get this error message.

Any help would be awesome.

答:
We have some example scripts here: https://github.com/zaproxy/community-scripts/tree/master/authentication

They are all javascript ones, but the classes will be the same. If you have updated your ZAP add-ons then you'll get code completion on the main parameters.

For more help I'd suggest using the ZAP Scripts group: http://groups.google.com/group/zaproxy-scripts


问:
Migrate only published with images in Wordpress
I would like to migrate my Wordpress, but I would only want the posts and the images. Nothing about the configuration, nor pluggins, nor the pages.</p>

答: Export posts with images. Install new wordpress and import export-xml file. http://take.ms/vAQoI</p>


问:
Find active TCP servers on a network without looping through IPs
From my TCP client, how can I find all the active TCP servers listening on a particular port, without needing to loop through all the IP addresses in the network? Or is there a faster way to loop through all the IP addresses? </p>

答:
No, there isn't.

You can listen for broadcasts (e.g. ARP) to find out which IP addresses are actually used and if there are any services advertising themselves, but this is not reliable and there is no standard, catch-all way.

You can't even query a given host which services have listening ports open because there's no general service for that.


问:
@ManyToMany mapping doesn't update the corresponding Tables
My Course class

```<code>@Entity
public class Course {

    @Column
    @Id
    private String courseCode;

    ...

    @ManyToMany(fetch = FetchType.EAGER )
    @JoinTable(
            name = "Students_RegisteredCourse",
            joinColumns = {@JoinColumn(name = "courseCode")},
            inverseJoinColumns = {@JoinColumn(name = "email")}
    )
    private Set<Student> registeredStudents = new HashSet<>();

..
..
..
}
</code>```

My Students class

```<code>@Entity
public class Student extends User {
...
@ManyToMany(mappedBy = "registeredStudents")
private List<Course> registeredCourse = new ArrayList<>();
...
}
</code>```

The user class is a usually Entity.

I'm trying to add courses to registeredCourses while creating new Students. But it is not working out. Course.getCourseByName("Discrete Mathematics") works fine. No new rows are added to Students_RegisteredCourse table on successfully executing this code.

```<code>    session.beginTransaction();

    Student temp = new Student();
    temp.setName("Siddharth Yadav");
    temp.setEmail("siddharth16268@iiitd.ac.in");
    temp.setRollNumber("2016268");
    temp.setPassword("[{Sid@123}]");

    List<Course> cse = new ArrayList<>();
    cse.add(Course.getCourseByName("Discrete Mathematics"));
    cse.add(Course.getCourseByName("Advanced Programming"));
    temp.setRegisteredCourse(cse);

    session.update(temp);
    session.getTransaction().commit();
</code>```

`

答:
You have to make sure that each of the Courses also has the registeredStudents filled with the new student:

```<code>List<Course> cse = new ArrayList<>();
cse.add(Course.getCourseByName("Discrete Mathematics"));
cse.add(Course.getCourseByName("Advanced Programming"));
temp.setRegisteredCourse(cse);

for(Course course: cse){
    cse.getRegisteredStudents().add(temp);
}
</code>```

Now the persistence provider will know that there is the mutual manytomany dependency here and perform an insert to the link table.

Also as the Student is created anew here .. you should use persist instead of update:

```<code>session.persist(temp);
</code>```

Body:
My Course class

@Entity
public class Course {

    @Column
    @Id
    private String courseCode;

    ...

    @ManyToMany(fetch = FetchType.EAGER )
    @JoinTable(
            name = "Students_RegisteredCourse",
            joinColumns = {@JoinColumn(name = "courseCode")},
            inverseJoinColumns = {@JoinColumn(name = "email")}
    )
    private Set<Student> registeredStudents = new HashSet<>();

..
..
..
}

My Students class

@Entity
public class Student extends User {
...
@ManyToMany(mappedBy = "registeredStudents")
private List<Course> registeredCourse = new ArrayList<>();
...
}

The user class is a usually Entity.

I'm trying to add courses to registeredCourses while creating new Students. But it is not working out. Course.getCourseByName("Discrete Mathematics") works fine. No new rows are added to Students_RegisteredCourse table on successfully executing this code.

    session.beginTransaction();

    Student temp = new Student();
    temp.setName("Siddharth Yadav");
    temp.setEmail("siddharth16268@iiitd.ac.in");
    temp.setRollNumber("2016268");
    temp.setPassword("[{Sid@123}]");

    List<Course> cse = new ArrayList<>();
    cse.add(Course.getCourseByName("Discrete Mathematics"));
    cse.add(Course.getCourseByName("Advanced Programming"));
    temp.setRegisteredCourse(cse);

    session.update(temp);
    session.getTransaction().commit();

`

Body:
You have to make sure that each of the Courses also has the registeredStudents filled with the new student:

List<Course> cse = new ArrayList<>();
cse.add(Course.getCourseByName("Discrete Mathematics"));
cse.add(Course.getCourseByName("Advanced Programming"));
temp.setRegisteredCourse(cse);

for(Course course: cse){
    cse.getRegisteredStudents().add(temp);
}

Now the persistence provider will know that there is the mutual manytomany dependency here and perform an insert to the link table.

Also as the Student is created anew here .. you should use persist instead of update:

session.persist(temp);


问:
How to set expiration time of PhoneNumberTokenProvider in Microsoft.AspNet.Identity
I am working on an Project in which I need to validate user phone number by SMS.

I am using AspNet.Identity.PhoneNumberTokenProvider for the same. I want to set expiration time of the generated PhoneNumberToken .

How can I achieve this?

答:
The PhoneNumberTokenProvider class implements TotpSecurityStampBasedTokenProvider which internally uses Rfc6238AuthenticationService to generate the sms validation code. The default expiration time for the validation code is 3 minutes with a variance of 9 minutes. Unfortunately I don't think you can modify the lifespan of the token.

You can check for yourself the classes I mentioned above on Microsoft.AspNet.Identity git repo.

ContentLicense: CC BY-SA 4.0


问:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException when trying to execute Javascript
I am trying to execute Javascript function called "returnAllLinkTexts()" on the DOM html page loaded via my Java application. Below line is executed by a Swing Buton.

```<code>myscript = browser.executeJavascript("returnAllLinkTexts()").toString(); //Line 407
</code>```

Once in a while I get the following exception. The Java application does not terminate or crash.

```<code>Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException com.demo.Main$BigButtonListener.actionPerformed(Main.java:407)
</code>```

I have tried the following to keep retrying about 20 times but it doesn't even reach this point. Exception is raised immediately @ 407.

```<code>int st = 0;
while (myscript == null){
 myscript = browser.executeJavascript("gogo()").toString();                              if (myscript != null) break;
 if (shit == 20) break;
 sht++;
}
</code>```

UPDATE:

This is the Javascript function returnAllLinkTexts();

```<code>function returnAllLinkTexts(){
var mydata = new Array();

$('a', document).each(function() {
    mydata.push($(this).text());
});

return mydata;
}
</code>```

答:
You're calling toString() on a potentially null object.

-> Firstly, I would surround with a try-catch block

But the question is why is the return value a possible-null?
Check your return value in the function..

Nur

Body:
I am trying to execute Javascript function called "returnAllLinkTexts()" on the DOM html page loaded via my Java application. Below line is executed by a Swing Buton.

myscript = browser.executeJavascript("returnAllLinkTexts()").toString(); //Line 407

Once in a while I get the following exception. The Java application does not terminate or crash.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException com.demo.Main$BigButtonListener.actionPerformed(Main.java:407)

I have tried the following to keep retrying about 20 times but it doesn't even reach this point. Exception is raised immediately @ 407.

int st = 0;
while (myscript == null){
 myscript = browser.executeJavascript("gogo()").toString();                              if (myscript != null) break;
 if (shit == 20) break;
 sht++;
}

UPDATE:

This is the Javascript function returnAllLinkTexts();

function returnAllLinkTexts(){
var mydata = new Array();

$('a', document).each(function() {
    mydata.push($(this).text());
});

return mydata;
}


问:
How to unpivot columns and GROUP BY based on values in SQL Server?
I want to calculate distinct PID and VID counts per year.

Condition:

```<code>1. Separate count for column A or B or C or D  having value 1  ( A_to_D)
2. Separate count for column E  having value 1  (E)
3. Separate count for column F  having value 1   (F)
4. Separate count for ALL A to F column are NULL  (ALL_NULL)
</code>```

In the output I want a separate new column Alpha with the following values:

```<code>A_to_D, E, F and ALL_Null
</code>```

Current output of table:

```<code>PID VID Flag    Date        A       B       C       D       E       F
1   A1  0       10/17/2013  NULL    NULL    NULL    NULL    NULL    NULL
2   A2  1       5/27/2014   1       NULL    NULL    1       NULL    NULL
3   A3  NULL    2/23/2015   NULL    NULL    NULL    NULL    1       NULL
4   A4  NULL    12/6/2013   NULL    0       NULL    NULL    NULL    NULL
5   A5  NULL    7/14/2016   NULL    NULL    NULL    NULL    NULL    1
6   A6  NULL    4/29/2015   NULL    1       1       NULL    NULL    NULL
7   A7  1       9/30/2016   1       NULL    NULL    NULL    NULL    NULL
8   A8  NULL    6/28/2016   NULL    NULL    NULL    NULL    NULL    NULL
9   A9  1       11/20/2013  NULL    NULL    NULL    NULL    NULL    NULL
10  A10 2       10/8/2015   NULL    1       NULL    NULL    NULL    NULL
</code>```

Here:

```<code>select datepart(Year,date) ,Count(distinct PID) ,Count( distinct VID)
from table
where A is not null or B is Not NUll or C is not null
   or D is not null or E is not Null or F is not null
group by datepart(Year,date)
</code>```

Expected output:

```<code>Year        Count_PID       Count_VID       Alpha
2013                                        A_to_D
2013                                        E
2013                                        F
2013            2               2           ALL_NULL
2014            1               1           A_to_D
2014                                        E
2014                                        F
2014                                        ALL_NULL
2015            2               2           A_to_D
2015            1               1           E
2015                                        F
2015                                        ALL_NULL
2016            2               2           A_to_D
2016                                        E
2016            1                           F
2016            1                           ALL_NULL
</code>```

答:
You can reach this output using a simple UNION query,

```<code>SELECT  YEAR([Date])    AS  [Year]
    ,NULLIF(COUNT(CASE WHEN A = 1 OR B = 1 OR C = 1 OR D = 1 THEN [PID] END),0) AS [Count_PID]
    ,NULLIF(COUNT(CASE WHEN A = 1 OR B = 1 OR C = 1 OR D = 1 THEN [VID] END),0) AS [Count_VID]
    ,'A_to_D'       AS  [alpha]
    ,1              AS  [sl_no]
FROM    @Table1
GROUP BY YEAR([Date])
UNION ALL
SELECT  YEAR([Date])
    ,NULLIF(COUNT(CASE WHEN E = 1 THEN [PID] END),0)
    ,NULLIF(COUNT(CASE WHEN E = 1 THEN [VID] END),0)
    ,'E'
        ,2
FROM    @Table1
GROUP BY YEAR([Date])
UNION ALL
SELECT  YEAR([Date])
    ,NULLIF(COUNT(CASE WHEN F = 1 THEN [PID] END),0)
    ,NULLIF(COUNT(CASE WHEN F = 1 THEN [VID] END),0)
    ,'F'
    ,3
FROM    @Table1
GROUP BY YEAR([Date])
UNION ALL
SELECT  YEAR([Date])
    ,NULLIF(COUNT(CASE WHEN COALESCE([A], [B], [C], [D], [E], [F]) IS NULL THEN [PID] END),0)
    ,NULLIF(COUNT(CASE WHEN COALESCE([A], [B], [C], [D], [E], [F]) IS NULL THEN [VID] END),0)
    ,'ALL_NULL'
    ,4
FROM    @Table1
GROUP BY YEAR([Date])
ORDER BY YEAR([Date]),[sl_no]
</code>```

Output :-

```<code>Year    Count_PID   Count_VID   alpha       sl_no
-------------------------------------------------
2013    NULL        NULL        A_to_D      1
2013    NULL        NULL        E           2
2013    NULL        NULL        F           3
2013    2           2           ALL_NULL    4
2014    1           1           A_to_D      1
2014    NULL        NULL        E           2
2014    NULL        NULL        F           3
2014    NULL        NULL        ALL_NULL    4
2015    2           2           A_to_D      1
2015    1           1           E           2
2015    NULL        NULL        F           3
2015    NULL        NULL        ALL_NULL    4
2016    1           1           A_to_D      1
2016    NULL        NULL        E           2
2016    1           1           F           3
2016    1           1           ALL_NULL    4
</code>```

Body:
I want to calculate distinct PID and VID counts per year.

Condition:

1. Separate count for column A or B or C or D  having value 1  ( A_to_D)
2. Separate count for column E  having value 1  (E)
3. Separate count for column F  having value 1   (F)
4. Separate count for ALL A to F column are NULL  (ALL_NULL)

In the output I want a separate new column Alpha with the following values:

A_to_D, E, F and ALL_Null

Current output of table:

PID VID Flag    Date        A       B       C       D       E       F
1   A1  0       10/17/2013  NULL    NULL    NULL    NULL    NULL    NULL
2   A2  1       5/27/2014   1       NULL    NULL    1       NULL    NULL
3   A3  NULL    2/23/2015   NULL    NULL    NULL    NULL    1       NULL
4   A4  NULL    12/6/2013   NULL    0       NULL    NULL    NULL    NULL
5   A5  NULL    7/14/2016   NULL    NULL    NULL    NULL    NULL    1
6   A6  NULL    4/29/2015   NULL    1       1       NULL    NULL    NULL
7   A7  1       9/30/2016   1       NULL    NULL    NULL    NULL    NULL
8   A8  NULL    6/28/2016   NULL    NULL    NULL    NULL    NULL    NULL
9   A9  1       11/20/2013  NULL    NULL    NULL    NULL    NULL    NULL
10  A10 2       10/8/2015   NULL    1       NULL    NULL    NULL    NULL

Here:

select datepart(Year,date) ,Count(distinct PID) ,Count( distinct VID)
from table
where A is not null or B is Not NUll or C is not null
   or D is not null or E is not Null or F is not null
group by datepart(Year,date)

Expected output:

Year        Count_PID       Count_VID       Alpha
2013                                        A_to_D
2013                                        E
2013                                        F
2013            2               2           ALL_NULL
2014            1               1           A_to_D
2014                                        E
2014                                        F
2014                                        ALL_NULL
2015            2               2           A_to_D
2015            1               1           E
2015                                        F
2015                                        ALL_NULL
2016            2               2           A_to_D
2016                                        E
2016            1                           F
2016            1                           ALL_NULL

Body:
You can reach this output using a simple UNION query,

SELECT  YEAR([Date])    AS  [Year]
    ,NULLIF(COUNT(CASE WHEN A = 1 OR B = 1 OR C = 1 OR D = 1 THEN [PID] END),0) AS [Count_PID]
    ,NULLIF(COUNT(CASE WHEN A = 1 OR B = 1 OR C = 1 OR D = 1 THEN [VID] END),0) AS [Count_VID]
    ,'A_to_D'       AS  [alpha]
    ,1              AS  [sl_no]
FROM    @Table1
GROUP BY YEAR([Date])
UNION ALL
SELECT  YEAR([Date])
    ,NULLIF(COUNT(CASE WHEN E = 1 THEN [PID] END),0)
    ,NULLIF(COUNT(CASE WHEN E = 1 THEN [VID] END),0)
    ,'E'
        ,2
FROM    @Table1
GROUP BY YEAR([Date])
UNION ALL
SELECT  YEAR([Date])
    ,NULLIF(COUNT(CASE WHEN F = 1 THEN [PID] END),0)
    ,NULLIF(COUNT(CASE WHEN F = 1 THEN [VID] END),0)
    ,'F'
    ,3
FROM    @Table1
GROUP BY YEAR([Date])
UNION ALL
SELECT  YEAR([Date])
    ,NULLIF(COUNT(CASE WHEN COALESCE([A], [B], [C], [D], [E], [F]) IS NULL THEN [PID] END),0)
    ,NULLIF(COUNT(CASE WHEN COALESCE([A], [B], [C], [D], [E], [F]) IS NULL THEN [VID] END),0)
    ,'ALL_NULL'
    ,4
FROM    @Table1
GROUP BY YEAR([Date])
ORDER BY YEAR([Date]),[sl_no]

Output :-

Year    Count_PID   Count_VID   alpha       sl_no
-------------------------------------------------
2013    NULL        NULL        A_to_D      1
2013    NULL        NULL        E           2
2013    NULL        NULL        F           3
2013    2           2           ALL_NULL    4
2014    1           1           A_to_D      1
2014    NULL        NULL        E           2
2014    NULL        NULL        F           3
2014    NULL        NULL        ALL_NULL    4
2015    2           2           A_to_D      1
2015    1           1           E           2
2015    NULL        NULL        F           3
2015    NULL        NULL        ALL_NULL    4
2016    1           1           A_to_D      1
2016    NULL        NULL        E           2
2016    1           1           F           3
2016    1           1           ALL_NULL    4


问:
Put values inside multiple columns in same family in Hbase
I am looking for a Hbase put command that can insert values into multiple columns in same column family for a same rowkey in Hbase table.
Let's say I have a hbase table named 'employee' with 1 column family 'data'

I am applying below command but it throws error.

```<code>PUT 'employee' 'data:column1', 'column1_val', 'data:column2', 'column_val2'
ERROR: no method 'add' for arguments (org.jruby.java.proxies.ArrayJavaProxy,org.jruby.RubyNil,org.jruby.RubyString,org.jruby.java.proxies.ArrayJavaProxy) on Java::OrgApacheHadoopHbaseClient::Put available overloads:
</code>```

However if i try separate put commands for each column value insertion, it works fine.

```<code>PUT 'employee' 'data:column1', 'column1_val'
PUT 'employee' 'data:column2', 'column2_val'
</code>```

Is there a way to insert values into multiple columns belonging to same column family in a single put command?

答:
HBase shell does not support multiple columns in one statement

```<code>hbase(main):002:0> help "put"
Put a cell 'value' at specified table/row/column and optionally
timestamp coordinates.  To put a cell value into table 'ns1:t1' or 't1'
at row 'r1' under column 'c1' marked with the time 'ts1', do:

  hbase> put 'ns1:t1', 'r1', 'c1', 'value'
  hbase> put 't1', 'r1', 'c1', 'value'
  hbase> put 't1', 'r1', 'c1', 'value', ts1
  hbase> put 't1', 'r1', 'c1', 'value', {ATTRIBUTES=>{'mykey'=>'myvalue'}}
  hbase> put 't1', 'r1', 'c1', 'value', ts1, {ATTRIBUTES=>{'mykey'=>'myvalue'}}
  hbase> put 't1', 'r1', 'c1', 'value', ts1, {VISIBILITY=>'PRIVATE|SECRET'}

The same commands also can be run on a table reference. Suppose you had a reference
t to table 't1', the corresponding command would be:

  hbase> t.put 'r1', 'c1', 'value', ts1, {ATTRIBUTES=>{'mykey'=>'myvalue'}}
</code>```

You can create multiple puts with same timestamps though, it is fine.

Body:
I am looking for a Hbase put command that can insert values into multiple columns in same column family for a same rowkey in Hbase table.
Let's say I have a hbase table named 'employee' with 1 column family 'data'

I am applying below command but it throws error.

PUT 'employee' 'data:column1', 'column1_val', 'data:column2', 'column_val2'
ERROR: no method 'add' for arguments (org.jruby.java.proxies.ArrayJavaProxy,org.jruby.RubyNil,org.jruby.RubyString,org.jruby.java.proxies.ArrayJavaProxy) on Java::OrgApacheHadoopHbaseClient::Put available overloads:

However if i try separate put commands for each column value insertion, it works fine.

PUT 'employee' 'data:column1', 'column1_val'
PUT 'employee' 'data:column2', 'column2_val'

Is there a way to insert values into multiple columns belonging to same column family in a single put command?

Body:
HBase shell does not support multiple columns in one statement

hbase(main):002:0> help "put"
Put a cell 'value' at specified table/row/column and optionally
timestamp coordinates.  To put a cell value into table 'ns1:t1' or 't1'
at row 'r1' under column 'c1' marked with the time 'ts1', do:

  hbase> put 'ns1:t1', 'r1', 'c1', 'value'
  hbase> put 't1', 'r1', 'c1', 'value'
  hbase> put 't1', 'r1', 'c1', 'value', ts1
  hbase> put 't1', 'r1', 'c1', 'value', {ATTRIBUTES=>{'mykey'=>'myvalue'}}
  hbase> put 't1', 'r1', 'c1', 'value', ts1, {ATTRIBUTES=>{'mykey'=>'myvalue'}}
  hbase> put 't1', 'r1', 'c1', 'value', ts1, {VISIBILITY=>'PRIVATE|SECRET'}

The same commands also can be run on a table reference. Suppose you had a reference
t to table 't1', the corresponding command would be:

  hbase> t.put 'r1', 'c1', 'value', ts1, {ATTRIBUTES=>{'mykey'=>'myvalue'}}

You can create multiple puts with same timestamps though, it is fine.


问:
How to remove margin-left and margin-right of col class in bootstrap?
I am new to bootstrap. I put 3 images side by side but they are not adjacent. There is a margin between them. This is picture

I want to eliminate the margins so that the images are adjacent. The center image size is 1200x400 and both left and right images size is 600x400. And also I've used img-responsive class. what is the actual problem?
Here is the code

```<code><div class="container">
    <div class="row">
        <div class="col-sm-3">
            <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />
        </div>
        <div class="col-sm-6">
            <asp:Image CssClass="img-responsive" ImageUrl="images/center1.jpg" runat="server" />
        </div>
        <div class="col-sm-3">
            <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />
        </div>
    </div>
</div>
</code>```

Also you notice in picture, these pictures are not vertically aligned properly how to fix it.

Thanks!

答:
this is css code</p>

```<code>body {
    background-color: #D8BFD8;
}

.navbar-default {
  background-color: #4c1f36;
  border-color: #63304a;
}
.navbar-default .navbar-brand {
  color: #eeeeee;
}
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
  color: #dddddd;
}
.navbar-default .navbar-text {
  color: #eeeeee;
}
.navbar-default .navbar-nav > li > a {
  color: #eeeeee;
}
.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
  color: #dddddd;
  background-color: #63304a;
}
.navbar-default .navbar-nav > li > .dropdown-menu {
  background-color: #4c1f36;
}
.navbar-default .navbar-nav > li > .dropdown-menu > li > a {
  color: #eeeeee;
}
.navbar-default .navbar-nav > li > .dropdown-menu > li > a:hover,
.navbar-default .navbar-nav > li > .dropdown-menu > li > a:focus {
  color: #dddddd;
  background-color: #63304a;
}
.navbar-default .navbar-nav > li > .dropdown-menu > li.divider {
  background-color: #63304a;
}
.navbar-default .navbar-nav .open .dropdown-menu > .active > a,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
  color: #dddddd;
  background-color: #63304a;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
  color: #dddddd;
  background-color: #63304a;
}
.navbar-default .navbar-nav > .open > a,
.navbar-default .navbar-nav > .open > a:hover,
.navbar-default .navbar-nav > .open > a:focus {
  color: #dddddd;
  background-color: #63304a;
}
.navbar-default .navbar-toggle {
  border-color: #63304a;
}
.navbar-default .navbar-toggle:hover,
.navbar-default .navbar-toggle:focus {
  background-color: #63304a;
}
.navbar-default .navbar-toggle .icon-bar {
  background-color: #eeeeee;
}
.navbar-default .navbar-collapse,
.navbar-default .navbar-form {
  border-color: #eeeeee;
}
.navbar-default .navbar-link {
  color: #eeeeee;
}
.navbar-default .navbar-link:hover {
  color: #dddddd;
}

@media (max-width: 768px) {
  .navbar-default .navbar-nav .open .dropdown-menu > li > a {
    color: #eeeeee;
  }
  .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
  .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
    color: #dddddd;
    background-color: #63304a;
  }
  .navbar-default .navbar-nav .open .dropdown-menu > .active > a,
  .navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
  .navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
    color: #dddddd;
    background-color: #63304a;
  }
}

@media (min-width: 768px) {

    .horizontal-menu {
        width: 700px;
        float: left;
        opacity: 0.95;
    }

    .left {
        float: left;
        padding: 10px;
    }

    .dropdown:hover > .dropdown-menu {
        display: block;
    }
}

.row-with-full-width {
    margin-left: 0 !important;
    margin-right: 0 !important;
}
</code>```

Body:
I am new to bootstrap. I put 3 images side by side but they are not adjacent. There is a margin between them. This is picture

I want to eliminate the margins so that the images are adjacent. The center image size is 1200x400 and both left and right images size is 600x400. And also I've used img-responsive class. what is the actual problem?
Here is the code

            <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />

            <asp:Image CssClass="img-responsive" ImageUrl="images/center1.jpg" runat="server" />

            <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />

Also you notice in picture, these pictures are not vertically aligned properly how to fix it.

Thanks!

Body:
this is css code

body {
    background-color: #D8BFD8;
}

.navbar-default {
  background-color: #4c1f36;
  border-color: #63304a;
}
.navbar-default .navbar-brand {
  color: #eeeeee;
}
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
  color: #dddddd;
}
.navbar-default .navbar-text {
  color: #eeeeee;
}
.navbar-default .navbar-nav > li > a {
  color: #eeeeee;
}
.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
  color: #dddddd;
  background-color: #63304a;
}
.navbar-default .navbar-nav > li > .dropdown-menu {
  background-color: #4c1f36;
}
.navbar-default .navbar-nav > li > .dropdown-menu > li > a {
  color: #eeeeee;
}
.navbar-default .navbar-nav > li > .dropdown-menu > li > a:hover,
.navbar-default .navbar-nav > li > .dropdown-menu > li > a:focus {
  color: #dddddd;
  background-color: #63304a;
}
.navbar-default .navbar-nav > li > .dropdown-menu > li.divider {
  background-color: #63304a;
}
.navbar-default .navbar-nav .open .dropdown-menu > .active > a,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
  color: #dddddd;
  background-color: #63304a;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
  color: #dddddd;
  background-color: #63304a;
}
.navbar-default .navbar-nav > .open > a,
.navbar-default .navbar-nav > .open > a:hover,
.navbar-default .navbar-nav > .open > a:focus {
  color: #dddddd;
  background-color: #63304a;
}
.navbar-default .navbar-toggle {
  border-color: #63304a;
}
.navbar-default .navbar-toggle:hover,
.navbar-default .navbar-toggle:focus {
  background-color: #63304a;
}
.navbar-default .navbar-toggle .icon-bar {
  background-color: #eeeeee;
}
.navbar-default .navbar-collapse,
.navbar-default .navbar-form {
  border-color: #eeeeee;
}
.navbar-default .navbar-link {
  color: #eeeeee;
}
.navbar-default .navbar-link:hover {
  color: #dddddd;
}

@media (max-width: 768px) {
  .navbar-default .navbar-nav .open .dropdown-menu > li > a {
    color: #eeeeee;
  }
  .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
  .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
    color: #dddddd;
    background-color: #63304a;
  }
  .navbar-default .navbar-nav .open .dropdown-menu > .active > a,
  .navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
  .navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
    color: #dddddd;
    background-color: #63304a;
  }
}

@media (min-width: 768px) {

    .horizontal-menu {
        width: 700px;
        float: left;
        opacity: 0.95;
    }

    .left {
        float: left;
        padding: 10px;
    }

    .dropdown:hover > .dropdown-menu {
        display: block;
    }
}

.row-with-full-width {
    margin-left: 0 !important;
    margin-right: 0 !important;
}


问:
Why does "import PIL; PIL.Image" not work, but "from PIL import Image" does?
In a python interpreter:

```<code>>>> import PIL
>>> PIL.Image
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Image'
>>> from PIL import Image
>>> PIL.Image
<module 'PIL.Image' from '/usr/lib/python2.7/site-packages/PIL/Image.pyc'>
</code>```

Why do I have to make the import as "from PIL import Image"? I'm interested in both "what is the underlying working in python imports that makes this behaviour possible?" and "Why was the PIL package designed to work like this?"

Also, I really like to keep a clean namespace when programming. If I want to use PIL.Image in my code, should I import like this:

```<code>>>> import PIL
>>> from PIL import Image
>>> del Image
</code>```

or is there a better way?

答:
You could import PIL.Image:

```<code>import PIL.Image
PIL.Image.open('my_pic.jpg')
</code>```

I think that Pillow is structured this way because of the history of the package. The original package PIL allowed you to do import Image. Pillow, the fork of PIL which supports Python 3, moved Image to the PIL namespace. The suggested import from PIL import Image makes it easy to switch from PIL to Pillow. See the porting docs for more info.

Body:
In a python interpreter:

>>> import PIL
>>> PIL.Image
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Image'
>>> from PIL import Image
>>> PIL.Image
<module 'PIL.Image' from '/usr/lib/python2.7/site-packages/PIL/Image.pyc'>

Why do I have to make the import as "from PIL import Image"? I'm interested in both "what is the underlying working in python imports that makes this behaviour possible?" and "Why was the PIL package designed to work like this?"

Also, I really like to keep a clean namespace when programming. If I want to use PIL.Image in my code, should I import like this:

>>> import PIL
>>> from PIL import Image
>>> del Image

or is there a better way?

Body:
You could import PIL.Image:

import PIL.Image
PIL.Image.open('my_pic.jpg')

I think that Pillow is structured this way because of the history of the package. The original package PIL allowed you to do import Image. Pillow, the fork of PIL which supports Python 3, moved Image to the PIL namespace. The suggested import from PIL import Image makes it easy to switch from PIL to Pillow. See the porting docs for more info.


问:
Maximum path cost in matrix
Can anyone tell the algorithm for finding the maximum path cost in a NxM matrix starting from top left corner and ending with bottom right corner with left ,right , down  movement is allowed in a matrix and contains negative cost. A cell can be visited any number of times and after visiting a cell its cost is replaced with 0

Constraints

1 <= nxm <= 4x10^6

INPUT

```<code>4 5
1 2 3 -1 -2
-5 -8 -1 2 -150
1 2 3 -250 100
1 1 1 1 20
</code>```

OUTPUT

```<code>37
</code>```

Explanation is given in the image
Explanation of Output

答:
Since you have also negative costs then use bellman-ford. What you do is that you change sign of all the costs(convert negative signs to positive and positive to negative) then find the shortest path and this path will be the longest because you have changed the signs.

If the sign is never becoms negative then use dijkstra shrtest-path but before that make all values negative and this will return you the longest path with it's cost.

You matrix is a direct graph. In your image you are trying to find a path(max or min) from index (0,0) to (n-1,n-1).

You need these things to represent it as a graph.

You need a linkedlist and in each node you have a first_Node, second_Node,Cost to move from first node to second.

An array of linkedlist. In each array index you save a linkedlist.If for example there is a path from 0 to 5 and 0 to 1(it's an undirected graph) then your graph will look like this.

If you want a direct-graph then simply add in adj[0] = 5 and do not add in adj[5] = 0 , this means that there is path from 0 to 5 but not from 5 to zero.

Here linkedlist represents only nodes which are connected not there cost. You have to add extra variable there which keep cost for each two nodes and it will look like this.

Now instead of first linkedlist put this linkedlist in your array and you have a graph now to run shortest or longest path algorithm.

If you want an intellgent algorithm then you can use A* with heuristic, i guess manhattan will be best.

If cost of your edges is not negative then use Dijkstra.

If cost is negative then use bellman-ford algorithm.

You can always find the longest path by converting the minus sign to plus and plus to minus and then run shortest path algorithm. Path founded will be longest.

I answered this question and as you said in comments to look at point two. If that's a task then main idea of this assignment is ensure the Monotonocity.

h stands for heuristic cost.

A  stands for accumulated cost.

Which says that each node the h(A) =< h(A) + A(A,B). Means if you want to move from A to B then cost should not be decreasing(can you do something with your values such that this property will hold) but increasing and once you satisfy this condition then everyone node which A* chooses , that node will be part of your path from source to Goal because this is the path with shortest/longest value.

pathMax You can enforece monotonicity. If there is path from A to B such that f(S...AB) < f(S ..B) then set cost of the  f(S...AB) = Max(f(S...AB) , f(S...A)) where S means source.

Title: Maximum path cost in matrix

Body:
Can anyone tell the algorithm for finding the maximum path cost in a NxM matrix starting from top left corner and ending with bottom right corner with left ,right , down  movement is allowed in a matrix and contains negative cost. A cell can be visited any number of times and after visiting a cell its cost is replaced with 0

Constraints

1 <= nxm <= 4x10^6

INPUT

4 5
1 2 3 -1 -2
-5 -8 -1 2 -150
1 2 3 -250 100
1 1 1 1 20

OUTPUT

37

Explanation is given in the image
Explanation of Output


问:
How to change the icon from the executable generated from an E4 RCP product?
I have a standalone application in Eclipse 4 RCP.

When exporting it as a product, as shown below:

The following structure is generated:

How to change the icon of the executable aplicacao.exe?

I already tried to put images in the Launching tab of the .product file, but without success.

答:
With this icon file you can find out if the problem is caused by the icon file or by the *.product file:

If it doesn't work even with this icon file, try to create a new *.product file from scratch.

If it works, make sure in your ICO file, the 256×256-pixel image is stored uncompressed, not as compressed PNG.

OBS: Maybe it's a icon cache problem. Change the Launcher Name in the .product Launching tab or rebuild the OS's icon cache can solve the problem.


问:
NestedScrollView with 5 multiple recyclerview dont show any value
This is my code for the RecyclerViews Page:

```<code>public class MenuActivity extends AppCompatActivity {

     private RecyclerView firstRecyclerView;

     JsonArrayRequest jsonArrayRequest ;

     RequestQueue requestQueue;

     NestedScrollView nsv;

     private ArrayList<Recipes>GetDataAdapter1;

     RecyclerView.Adapter adapter;

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

         firstRecyclerView = (RecyclerView)findViewById(R.id.recycler);

         //create and set layout manager for each RecyclerView
         RecyclerView.LayoutManager firstLayoutManager = new LinearLayoutManager(this);

         firstRecyclerView.setLayoutManager(firstLayoutManager);

         firstRecyclerView.setHasFixedSize(true);

         GetDataAdapter1 =  new ArrayList<>();

         JSON_DATA_WEB_CALL_VIEWS();

     }
</code>```

This is my RecyclerView AdapterList to call the inflate view for the list elements:

```<code>public RecyclerViewAdapterList(List<Recipes> getDataAdapter, Context
 context){

         super();
         this.itemList = getDataAdapter;

         this.context = context;
     }

     @Override
     public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {

         View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.inflate_pagecountry,
 parent, false);
         RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
         return rcv;
     }
     @Override
     public void onBindViewHolder(RecyclerViewHolders holder, int position) {
         holder.NameCategory.setText(itemList.get(position).getTitle());
         Picasso.with(context).load(itemList.get(position).getImage()).into(holder.CategoryLogo);
     }
</code>```

I´m getting but logcat says

15:25:53.476 E/RecyclerView﹕ No adapter attached; skipping layout

Can you help me??

答:
You can try this</p>

```<code> @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.search);

         nsv = (NestedScrollView) findViewById(R.id.activity_main);
         firstRecyclerView = (RecyclerView)findViewById(R.id.recycler);
         secondRecyclerView = (RecyclerView)findViewById(R.id.recycler_2);
         thirdRecyclerView = (RecyclerView) findViewById(R.id.recycler_3);
         fourthRecyclerView = (RecyclerView) findViewById(R.id.recycler_s);
         fifhtRecyclerView = (RecyclerView) findViewById(R.id.recycler_);

         //create and set layout manager for each RecyclerView

        firstRecyclerView.setNestedScrollingEnabled(false);
         RecyclerView.LayoutManager firstLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
         //RecyclerView.LayoutManager secondLayoutManager = new LinearLayoutManager(this);
         //RecyclerView.LayoutManager thirdLayoutManager = new LinearLayoutManager(this);
         //RecyclerView.LayoutManager fourthLayoutManager = new LinearLayoutManager(this);
         //RecyclerView.LayoutManager fiveLayoutManager = new LinearLayoutManager(this);

         firstRecyclerView.setLayoutManager(firstLayoutManager);
         //secondRecyclerView.setLayoutManager(secondLayoutManager);
         //thirdRecyclerView.setLayoutManager(thirdLayoutManager);
         //fourthRecyclerView.setLayoutManager(fourthLayoutManager);
         //fifhtRecyclerView.setLayoutManager(fiveLayoutManager);

         firstRecyclerView.setHasFixedSize(true);
         //secondRecyclerView.setHasFixedSize(true);
         //thirdRecyclerView.setHasFixedSize(true);
         //fourthRecyclerView.setHasFixedSize(true);
         //fifhtRecyclerView.setHasFixedSize(true);

         GetDataAdapter1 =  new ArrayList<>();
         //GetDataAdapter2 =  new ArrayList<>();
         //GetDataAdapter3 =  new ArrayList<>();
         //GetDataAdapter4 =  new ArrayList<>();
         //GetDataAdapter5 =  new ArrayList<>();

         JSON_DATA_WEB_CALL_VIEWS();
         //JSON_DATA_WEB_CALL_DONES();
         //JSON_DATA_WEB_CALL_LIKES();
         //JSON_DATA_WEB_CALL_IDS();
         //JSON_DATA_WEB_CALL_RANDOM();

     }
</code>```

Body:
This is my code for the RecyclerViews Page:

public class MenuActivity extends AppCompatActivity {

     private RecyclerView firstRecyclerView;

     JsonArrayRequest jsonArrayRequest ;

     RequestQueue requestQueue;

     NestedScrollView nsv;

     private ArrayList<Recipes>GetDataAdapter1;

     RecyclerView.Adapter adapter;

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

         firstRecyclerView = (RecyclerView)findViewById(R.id.recycler);

         //create and set layout manager for each RecyclerView
         RecyclerView.LayoutManager firstLayoutManager = new LinearLayoutManager(this);

         firstRecyclerView.setLayoutManager(firstLayoutManager);

         firstRecyclerView.setHasFixedSize(true);

         GetDataAdapter1 =  new ArrayList<>();

         JSON_DATA_WEB_CALL_VIEWS();

     }

This is my RecyclerView AdapterList to call the inflate view for the list elements:

public RecyclerViewAdapterList(List<Recipes> getDataAdapter, Context
 context){

         super();
         this.itemList = getDataAdapter;

         this.context = context;
     }

     @Override
     public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {

         View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.inflate_pagecountry,
 parent, false);
         RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
         return rcv;
     }
     @Override
     public void onBindViewHolder(RecyclerViewHolders holder, int position) {
         holder.NameCategory.setText(itemList.get(position).getTitle());
         Picasso.with(context).load(itemList.get(position).getImage()).into(holder.CategoryLogo);
     }

I´m getting but logcat says

15:25:53.476 E/RecyclerView﹕ No adapter attached; skipping layout

Can you help me??

Body:
You can try this

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

         nsv = (NestedScrollView) findViewById(R.id.activity_main);
         firstRecyclerView = (RecyclerView)findViewById(R.id.recycler);
         secondRecyclerView = (RecyclerView)findViewById(R.id.recycler_2);
         thirdRecyclerView = (RecyclerView) findViewById(R.id.recycler_3);
         fourthRecyclerView = (RecyclerView) findViewById(R.id.recycler_s);
         fifhtRecyclerView = (RecyclerView) findViewById(R.id.recycler_);

         //create and set layout manager for each RecyclerView

        firstRecyclerView.setNestedScrollingEnabled(false);
         RecyclerView.LayoutManager firstLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
         //RecyclerView.LayoutManager secondLayoutManager = new LinearLayoutManager(this);
         //RecyclerView.LayoutManager thirdLayoutManager = new LinearLayoutManager(this);
         //RecyclerView.LayoutManager fourthLayoutManager = new LinearLayoutManager(this);
         //RecyclerView.LayoutManager fiveLayoutManager = new LinearLayoutManager(this);

         firstRecyclerView.setLayoutManager(firstLayoutManager);
         //secondRecyclerView.setLayoutManager(secondLayoutManager);
         //thirdRecyclerView.setLayoutManager(thirdLayoutManager);
         //fourthRecyclerView.setLayoutManager(fourthLayoutManager);
         //fifhtRecyclerView.setLayoutManager(fiveLayoutManager);

         firstRecyclerView.setHasFixedSize(true);
         //secondRecyclerView.setHasFixedSize(true);
         //thirdRecyclerView.setHasFixedSize(true);
         //fourthRecyclerView.setHasFixedSize(true);
         //fifhtRecyclerView.setHasFixedSize(true);

         GetDataAdapter1 =  new ArrayList<>();
         //GetDataAdapter2 =  new ArrayList<>();
         //GetDataAdapter3 =  new ArrayList<>();
         //GetDataAdapter4 =  new ArrayList<>();
         //GetDataAdapter5 =  new ArrayList<>();

         JSON_DATA_WEB_CALL_VIEWS();
         //JSON_DATA_WEB_CALL_DONES();
         //JSON_DATA_WEB_CALL_LIKES();
         //JSON_DATA_WEB_CALL_IDS();
         //JSON_DATA_WEB_CALL_RANDOM();

     }


问:
Passing csv file as command like argument in nodeJs
I can't for the life of me think of a way to do this. I've previously worked with importing csv files into js files, but for this challenge I've got to create a js file that executable from a shell with the data file passed as input.

Any ideas how can this be done?

~The challenge description~

The program must be executable from a shell and take the CSV file as input. For example:

```<code>node score_calculator.js data.csv
</code>```

答:
You can take the file path as command line argument when running your nodejs app like

```<code>node myScript.js pathToCsvFile
</code>```

Now you'll have to get this path in your code as

```<code>var filePath = process.argv[2];
</code>```

Now you can use this path to read your file as

```<code>   fs.readFile(filePath, (err, data) => {
     if (err) throw err;
    console.log(data);
 });
</code>```

Read more about file handling in nodejs here

Hope this helps

Body:
I can't for the life of me think of a way to do this. I've previously worked with importing csv files into js files, but for this challenge I've got to create a js file that executable from a shell with the data file passed as input.

Any ideas how can this be done?

~The challenge description~

The program must be executable from a shell and take the CSV file as input. For example:

node score_calculator.js data.csv

Body:
You can take the file path as command line argument when running your nodejs app like

node myScript.js pathToCsvFile

Now you'll have to get this path in your code as

var filePath = process.argv[2];

Now you can use this path to read your file as

   fs.readFile(filePath, (err, data) => {
     if (err) throw err;
    console.log(data);
 });

Read more about file handling in nodejs here

Hope this helps


问:
Android Studio 3.0 Warning: Using incompatible plugins for the annotation processing
After update Android Studio to 3.0 version I have warning:

```<code>Error:android-apt plugin is incompatible with the Android Gradle plugin.  Please use 'annotationProcessor' configuration instead.
</code>```

I tried to rewrite my gradle source ,but I still have a warning.
Here is a source

```<code>buildscript {
repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0'
    classpath 'io.realm:realm-gradle-plugin:0.89.+'
}
}
allprojects {
repositories {
    google()
    jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.syncapp"
    minSdkVersion 21
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

 buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.11'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support:support-v4:27.0.1'
implementation 'com.android.support:appcompat-v7:27.0.1'
implementation 'com.android.support:design:27.0.1'
compile 'org.greenrobot:eventbus:3.1.1'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

compile 'com.squareup.okhttp:okhttp:2.7.5'
compile 'com.squareup.okhttp:mockwebserver:2.7.5'

compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

compile 'com.google.dagger:dagger:2.4'
annotationProcessor 'com.google.dagger:dagger-compiler:2.4'

}
apply plugin: 'realm-android'
</code>```

As you can see,in my project I'm using butterknife,dagger,okhttp,retrofit2 and     eventbus support libraries

Any solution? I can't run my app
Thanks

答:
Did you have a look at this link?

Basically:

If you are experiencing issues migrating to the new dependency resolution >strategy, you can restore behavior to that of Android plugin 2.3.0 by setting >includeCompileClasspath true.

```<code>android {
...
defaultConfig {
    ...
    javaCompileOptions {
        annotationProcessorOptions {
            includeCompileClasspath false
        }
    }
}
}
</code>```

then you can opt to remove the Apt plugin to make the project cleaner but consider that should not affect according to the official documentation

android-apt plugin users: This behavior change currently does not affect the >android-apt plugin. However, the plugin will not be compatible with future >versions of the Android plugin for Gradle
  Also when yuo migrate to Android Studio 3.0 you should not use compile but implementation for every dependency

What also you should do is to try to upgrade or downgrade the annotation processor dependecies you have with Dagger or Butterknife, if does not work try to remove Butterknife(but I am not sure about that if the Dagger one is enough, anyway you should not need).

Body:
After update Android Studio to 3.0 version I have warning:

Error:android-apt plugin is incompatible with the Android Gradle plugin.  Please use 'annotationProcessor' configuration instead.

I tried to rewrite my gradle source ,but I still have a warning.
Here is a source

buildscript {
repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0'
    classpath 'io.realm:realm-gradle-plugin:0.89.+'
}
}
allprojects {
repositories {
    google()
    jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
    applicationId "com.syncapp"
    minSdkVersion 21
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

 buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.11'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support:support-v4:27.0.1'
implementation 'com.android.support:appcompat-v7:27.0.1'
implementation 'com.android.support:design:27.0.1'
compile 'org.greenrobot:eventbus:3.1.1'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

compile 'com.squareup.okhttp:okhttp:2.7.5'
compile 'com.squareup.okhttp:mockwebserver:2.7.5'

compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

compile 'com.google.dagger:dagger:2.4'
annotationProcessor 'com.google.dagger:dagger-compiler:2.4'

}
apply plugin: 'realm-android'

As you can see,in my project I'm using butterknife,dagger,okhttp,retrofit2 and     eventbus support libraries

Any solution? I can't run my app
Thanks

Body:
Did you have a look at this link?

Basically:

If you are experiencing issues migrating to the new dependency resolution >strategy, you can restore behavior to that of Android plugin 2.3.0 by setting >includeCompileClasspath true.

android {
...
defaultConfig {
    ...
    javaCompileOptions {
        annotationProcessorOptions {
            includeCompileClasspath false
        }
    }
}
}

then you can opt to remove the Apt plugin to make the project cleaner but consider that should not affect according to the official documentation

android-apt plugin users: This behavior change currently does not affect the >android-apt plugin. However, the plugin will not be compatible with future >versions of the Android plugin for Gradle
  Also when yuo migrate to Android Studio 3.0 you should not use compile but implementation for every dependency

What also you should do is to try to upgrade or downgrade the annotation processor dependecies you have with Dagger or Butterknife, if does not work try to remove Butterknife(but I am not sure about that if the Dagger one is enough, anyway you should not need).


问:
How to set multiple date in the calendar with mvvm?
How to set multiple date in the calendar with mvvm.

I have my calendar :

```<code><div id="calendar1" data-role="calendar"
          data-bind="value: Cvalue,
          dates: Csource,
          events:{change: ConChange}">
</div>
</code>```

JS, view model:

```<code>Cvalue:null,
Csource:[],
Conchange:function(){
}
</code>```

Csource contains:

```<code>[
 {"nome":"1"},{"data":"21/112017"},
 {"nome":"2"},{"data":"22/112017"},
 {"nome":"3"},{"data":"26/112017"},
 {"nome":"4"},{"data":"28/112017"},
 {"nome":"5"},{"data":"29/112017"}
 ]
</code>```

Cain i see this dates with different color in the calendar?

and at onChange of day, i'd like to print the name of date;
something like this attached image:

答:
A plugin called multiDatesPicker will meet your requirement

$('#mdp-demo').multiDatesPicker();```
<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>
<link href="https://cdn.rawgit.com/dubrox/Multiple-Dates-Picker-for-jQuery-UI/master/jquery-ui.multidatespicker.css" rel="stylesheet"/>
<link href="https://code.jquery.com/ui/1.12.1/themes/pepper-grinder/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdn.rawgit.com/dubrox/Multiple-Dates-Picker-for-jQuery-UI/master/jquery-ui.multidatespicker.js"></script>
<input id="mdp-demo"></code>```

Body:
How to set multiple date in the calendar with mvvm.

I have my calendar :

JS, view model:

Cvalue:null,
Csource:[],
Conchange:function(){
}

Csource contains:

[
 {"nome":"1"},{"data":"21/112017"},
 {"nome":"2"},{"data":"22/112017"},
 {"nome":"3"},{"data":"26/112017"},
 {"nome":"4"},{"data":"28/112017"},
 {"nome":"5"},{"data":"29/112017"}
 ]

Cain i see this dates with different color in the calendar?

and at onChange of day, i'd like to print the name of date;
something like this attached image:

Body:
A plugin called multiDatesPicker will meet your requirement

$('#mdp-demo').multiDatesPicker();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.rawgit.com/dubrox/Multiple-Dates-Picker-for-jQuery-UI/master/jquery-ui.multidatespicker.css" rel="stylesheet"/>
<link href="https://code.jquery.com/ui/1.12.1/themes/pepper-grinder/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdn.rawgit.com/dubrox/Multiple-Dates-Picker-for-jQuery-UI/master/jquery-ui.multidatespicker.js"></script>
<input id="mdp-demo">


问:
NoClassDefFoundError
I am using eclipse to develop my application. In my application i have few projects and those projects have reference in EAR project.

In one of project i have created a interface and impementation for that interface.

I am trying to craete object for that class

```<code>MyInterface myObj = new MyClass();
</code>```

It was not working so i started server in debug mode. I am getting NoClassDefFoundError.

Any idea why i am getting this error. I have already added new project in my project build path. If i write

```<code>MyInterface myObj = null;
</code>```

i do not get any error.

答:
Check the classpath used by the runtime configuration you're running in Eclipse, which is normally defined by the project libraries and source folders.

Since you're working with an EAR, you probably use an app server, and you need to know that most of them work with one parent classloader and a child classloader per ear or war. That means that if a class loaded by a parent classloader tries to instantiate a class which is only in a child classloader you get a NoClassDefinedError (the other way around you don't).

Title: NoClassDefFoundError

Body:
I am using eclipse to develop my application. In my application i have few projects and those projects have reference in EAR project.

In one of project i have created a interface and impementation for that interface.

I am trying to craete object for that class

MyInterface myObj = new MyClass();

It was not working so i started server in debug mode. I am getting NoClassDefFoundError.

Any idea why i am getting this error. I have already added new project in my project build path. If i write

MyInterface myObj = null;

i do not get any error.


问:
c# deleting the 0s of an int, but not if it is 20
In my string start can be all sorts of numbers (1 until 99), but when the numbers get generated, 1 always get shown like 01. Is there an way to remove that 0, without if the number is 20 that the number get changed to 2?

答:
You can use the String.TrimStart method:

```<code>string num = "0001";
num = num.TrimStart('0');
</code>```

Body:
You can use the String.TrimStart method:

string num = "0001";
num = num.TrimStart('0');


问:
How to increase or decrease textbox value using page object Model
I have to input the numeric value in this textbox, I tried using xpath but id is keep on changing everytime,I added the picture and source code below.

Here is the source code i managed to select using Xpath but id is keep on changing

```<code><input class="t-input" data-val="true" data-val-number="The field Amount must be a number." id="CaseTypes_64b4d9c0-c574-40bd-a450-0c6f94844a2e__Amount" name="CaseTypes[64b4d9c0-c574-40bd-a450-0c6f94844a2e].Amount" style="width: 110px; color: rgb(255, 255, 255);" type="text">
</code>```

答:
As per the HTML you have shared you can use any of the following options :

XPath :

```<code>driver.FindElement(By.XPath("//input[@class='t-input'][starts-with(@id, 'CaseTypes_')][starts-with(@name, 'CaseTypes[')]")).Click();
</code>```

CssSelector :

```<code>driver.FindElement(By.CssSelector("input[class='t-input'][id^='CaseTypes_'][name^='CaseTypes[']")).Click();
</code>```

Body:
I have to input the numeric value in this textbox, I tried using xpath but id is keep on changing everytime,I added the picture and source code below.

Here is the source code i managed to select using Xpath but id is keep on changing

<input class="t-input" data-val="true" data-val-number="The field Amount must be a number." id="CaseTypes_64b4d9c0-c574-40bd-a450-0c6f94844a2e__Amount" name="CaseTypes[64b4d9c0-c574-40bd-a450-0c6f94844a2e].Amount" style="width: 110px; color: rgb(255, 255, 255);" type="text">

Body:
As per the HTML you have shared you can use any of the following options :

XPath :

driver.FindElement(By.XPath("//input[@class='t-input'][starts-with(@id, 'CaseTypes_')][starts-with(@name, 'CaseTypes[')]")).Click();

CssSelector :

driver.FindElement(By.CssSelector("input[class='t-input'][id^='CaseTypes_'][name^='CaseTypes[']")).Click();