Search is not available for this dataset
qid
int64 1
74.7M
| question
stringlengths 1
70k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 0
115k
| response_k
stringlengths 0
60.5k
|
---|---|---|---|---|---|
3,702,859 | I am new to javascript/jquery .
I have a small question.
I have some thing like the following in the java script file.
```
<button id="button1" onclick=click() />
<button id="button2" onclick=click() />
<button id="button3" onclick=click() />
```
so the click function looks like the follwoing
```
click(id){
/do some thing
}
```
so my question is when ever the button is clicked how can we pass the button id to the function.
```
<button id="button1" onclick=click("how to pass the button id value to this function") />
```
how can we pass the button id like "button1" to the click function when ever the button is clicked..
I would really appreciate if some one can answer to my question..
Thanks,
Swati | 2010/09/13 | [
"https://Stackoverflow.com/questions/3702859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/436175/"
] | I advise the use of unobtrusive script as always, but if you *have* to have it inline use `this`, for example:
```
<button id="button1" onclick="click(this.id)" />
```
The unobtrusive way would look like this:
```
$("button").click(function() {
click(this.id);
});
``` | For starters: Don't use onclick(). [This is the way](http://www.quirksmode.org/js/introevents.html) to do it properly.
When you get your head around all this and think "boy that's a load of cowpat to write for a litte event!", turn towards jquery.
Doing the same in jquery is [simple](http://api.jquery.com/click/). |
3,702,859 | I am new to javascript/jquery .
I have a small question.
I have some thing like the following in the java script file.
```
<button id="button1" onclick=click() />
<button id="button2" onclick=click() />
<button id="button3" onclick=click() />
```
so the click function looks like the follwoing
```
click(id){
/do some thing
}
```
so my question is when ever the button is clicked how can we pass the button id to the function.
```
<button id="button1" onclick=click("how to pass the button id value to this function") />
```
how can we pass the button id like "button1" to the click function when ever the button is clicked..
I would really appreciate if some one can answer to my question..
Thanks,
Swati | 2010/09/13 | [
"https://Stackoverflow.com/questions/3702859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/436175/"
] | I advise the use of unobtrusive script as always, but if you *have* to have it inline use `this`, for example:
```
<button id="button1" onclick="click(this.id)" />
```
The unobtrusive way would look like this:
```
$("button").click(function() {
click(this.id);
});
``` | That not very jQuery-ish. You should rather use event listeners:
```
$(function() {
$('#button1,#button2,#button3').click(clicked);
function clicked() {
// "this" will refer to the clicked button inside the function
alert($(this).attr('id'));
}
});
``` |
3,702,859 | I am new to javascript/jquery .
I have a small question.
I have some thing like the following in the java script file.
```
<button id="button1" onclick=click() />
<button id="button2" onclick=click() />
<button id="button3" onclick=click() />
```
so the click function looks like the follwoing
```
click(id){
/do some thing
}
```
so my question is when ever the button is clicked how can we pass the button id to the function.
```
<button id="button1" onclick=click("how to pass the button id value to this function") />
```
how can we pass the button id like "button1" to the click function when ever the button is clicked..
I would really appreciate if some one can answer to my question..
Thanks,
Swati | 2010/09/13 | [
"https://Stackoverflow.com/questions/3702859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/436175/"
] | You don't need to.
```
function handleClick(){
//use $(this).attr("id");
//or $(this) to refer to the object being clicked
}
$(document).ready(function(){
$('#myButton').click(handleClick);
});
``` | For starters: Don't use onclick(). [This is the way](http://www.quirksmode.org/js/introevents.html) to do it properly.
When you get your head around all this and think "boy that's a load of cowpat to write for a litte event!", turn towards jquery.
Doing the same in jquery is [simple](http://api.jquery.com/click/). |
3,702,859 | I am new to javascript/jquery .
I have a small question.
I have some thing like the following in the java script file.
```
<button id="button1" onclick=click() />
<button id="button2" onclick=click() />
<button id="button3" onclick=click() />
```
so the click function looks like the follwoing
```
click(id){
/do some thing
}
```
so my question is when ever the button is clicked how can we pass the button id to the function.
```
<button id="button1" onclick=click("how to pass the button id value to this function") />
```
how can we pass the button id like "button1" to the click function when ever the button is clicked..
I would really appreciate if some one can answer to my question..
Thanks,
Swati | 2010/09/13 | [
"https://Stackoverflow.com/questions/3702859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/436175/"
] | That not very jQuery-ish. You should rather use event listeners:
```
$(function() {
$('#button1,#button2,#button3').click(clicked);
function clicked() {
// "this" will refer to the clicked button inside the function
alert($(this).attr('id'));
}
});
``` | For starters: Don't use onclick(). [This is the way](http://www.quirksmode.org/js/introevents.html) to do it properly.
When you get your head around all this and think "boy that's a load of cowpat to write for a litte event!", turn towards jquery.
Doing the same in jquery is [simple](http://api.jquery.com/click/). |
14,292,555 | I am using spring's BasicDataSource in my applicationContext.xml as following:
```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
default-autowire="byType">
<bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/school" />
<property name="username" value="root" />
<property name="password" value="" />
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</bean>
</beans>
```
and when i use this bean in controller as follows:
```
package admin.controller;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.inject.*;
@Controller
public class Welcome {
@Inject
BasicDataSource datasource;
private static final String WELCOME_PAGE = "welcome";
@RequestMapping("/")
public String welcome(ModelMap model){
Connection con=null;
PreparedStatement stmt =null;
String testQuery = "INSERT INTO ADMIN(ID,USER_NAME,PASSWORD,FIRST_NAME,LAST_NAME) VALUES(?,?,?,?,?)";
try {
con = datasource.getConnection();
stmt = con.prepareStatement(testQuery);
stmt.setInt(1, 4);
stmt.setString(2, "ij");
stmt.setString(3, "kl");
stmt.setString(4, "mn");
stmt.setString(5, "op");
stmt.execute();
//con.commit();
} catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
if(con!=null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return WELCOME_PAGE;
}
}
```
then it gives me a nullpointer exception at line: datasource.getConnection();
connection details are 100% correct because when i create a new instance of BasicDatasource inside the controller and add details using its setter methods(eg: datasource.setDriverClassName etc.) then it connects to the database and execute the query without any problem. but when i want to use the bean from application context then it is giving me a null pointer exception. | 2013/01/12 | [
"https://Stackoverflow.com/questions/14292555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/970255/"
] | They are all [unprintable control characters](http://en.wikipedia.org/wiki/C0_and_C1_control_codes), the box is just a way to print them. Another option is to not show them at all but then you wouldn't know about them as easily.
There's
* `0x1F` Unit separator
* `0x7F` Delete
* `0x01` Start of Heading
* `0x1C` File Separator
(You can read all of the above from the boxes already)
Since these are almost never used in text, you should probably not treat them as text. If you look at the meaning of them as control characters, they don't make sense even as control characters. | Open the file in a hex editor.
Hex editors normally show the value of each character in both binary and hexadecimal values. |
14,292,555 | I am using spring's BasicDataSource in my applicationContext.xml as following:
```
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
default-autowire="byType">
<bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/school" />
<property name="username" value="root" />
<property name="password" value="" />
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</bean>
</beans>
```
and when i use this bean in controller as follows:
```
package admin.controller;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.inject.*;
@Controller
public class Welcome {
@Inject
BasicDataSource datasource;
private static final String WELCOME_PAGE = "welcome";
@RequestMapping("/")
public String welcome(ModelMap model){
Connection con=null;
PreparedStatement stmt =null;
String testQuery = "INSERT INTO ADMIN(ID,USER_NAME,PASSWORD,FIRST_NAME,LAST_NAME) VALUES(?,?,?,?,?)";
try {
con = datasource.getConnection();
stmt = con.prepareStatement(testQuery);
stmt.setInt(1, 4);
stmt.setString(2, "ij");
stmt.setString(3, "kl");
stmt.setString(4, "mn");
stmt.setString(5, "op");
stmt.execute();
//con.commit();
} catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
if(con!=null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return WELCOME_PAGE;
}
}
```
then it gives me a nullpointer exception at line: datasource.getConnection();
connection details are 100% correct because when i create a new instance of BasicDatasource inside the controller and add details using its setter methods(eg: datasource.setDriverClassName etc.) then it connects to the database and execute the query without any problem. but when i want to use the bean from application context then it is giving me a null pointer exception. | 2013/01/12 | [
"https://Stackoverflow.com/questions/14292555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/970255/"
] | They are all [unprintable control characters](http://en.wikipedia.org/wiki/C0_and_C1_control_codes), the box is just a way to print them. Another option is to not show them at all but then you wouldn't know about them as easily.
There's
* `0x1F` Unit separator
* `0x7F` Delete
* `0x01` Start of Heading
* `0x1C` File Separator
(You can read all of the above from the boxes already)
Since these are almost never used in text, you should probably not treat them as text. If you look at the meaning of them as control characters, they don't make sense even as control characters. | Clearly, those are "non printable" characters (in your current language, but quite possibly in all languages). Use `fprintf("%02x, %02x, %02x, %02x", buf[0], buf[1], buf[2], buf[3]);` to show their actual value. |
34,491,004 | I have a database with a large set of email addresses.
Because of a bug in a script, the database is full of wrong email addresses. These addresses has a known pattern.
They are made of a true email address, concatenated with a string in the beginning.
This string is itself a part of the email address.
Example:
The correct email should be:
```
john.doe@example.com
```
Instead I have:
```
doejohn.doe@example.com
```
Or also:
```
johndoejohn.doe@example.com
```
How can I identify these addresses?
I thought about creating a regexp that finds repeating text inside a string, but I could find out how to do it.
Any ideas? | 2015/12/28 | [
"https://Stackoverflow.com/questions/34491004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2837813/"
] | You can use below query to take care of `LASTNAMEfirstname.lastname@something.com` pattern, This will first find the last\_name and then replace that with null in the first part before first `.`.
```
concat(replace(substr(email,1,locate('.',email)),substr(email,LOCATE('.',email)+1,locate('@',email)-LOCATE('.',email)-1),'')
,
substr(email,locate('.',email)+1,length(email))
)
```
**See SQL Fiddle example here**
<http://sqlfiddle.com/#!9/24fba/2>
But this will not take care of `FIRSTNAMElastnameFIRSTNAME.lastname@example.com` pattern. | Can't test right now but this might work:
`^([^@]{5,})[^@]{1,}\.\1@[^@]+$` |
54,878,621 | I have source code like the code below. I'm trying to scrape out the '11 tigers' string. I'm new to xpath, can anyone suggest how to get it using selenium or beatiful soup? I'm thinking `driver.find_element_by_xpath` or `soup.find_all`.
source:
```
<div class="count-box fixed_when_handheld s-vgLeft0_5 s-vgPullBottom1 s-vgRight0_5 u-colorGray6 u-fontSize18 u-fontWeight200" style="display: block;">
<div class="label-container u-floatLeft">11 tigers</div>
<div class="u-floatRight">
<div class="hide_when_tablet hide_when_desktop s-vgLeft0_5 s-vgRight0_5 u-textAlignCenter">
<div class="js-show-handheld-filters c-button c-button--md c-button--blue s-vgRight1">
Filter
</div>
<div class="js-save-handheld-filters c-button c-button--md c-button--transparent">
Save
</div>
</div>
</div>
<div class="cb"></div>
</div>
``` | 2019/02/26 | [
"https://Stackoverflow.com/questions/54878621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5978130/"
] | You can use same `.count-box .label-container` css selector for both BS and Selenium.
BS:
```
page = BeautifulSoup(yourhtml, "html.parser")
# if you need first one
label = page.select_one(".count-box .label-container").text
# if you need all
labels = page.select(".count-box .label-container")
for label in labels:
print(label.text)
```
Selenium:
```
labels = driver.find_elements_by_css_selector(".count-box .label-container")
for label in labels:
print(label.text)
``` | Variant of the answer given by Sers.
```
page = BeautifulSoup(html_text, "lxml")
# first one
label = page.find('div',{'class':'count-box label-container')).text
# for all
labels = page.find('div',{'class':'count-box label-container'))
for label in labels:
print(label.text)
```
Use `lxml` parser as it's faster. You need to install it explicitly via `pip install lxml` |
54,878,621 | I have source code like the code below. I'm trying to scrape out the '11 tigers' string. I'm new to xpath, can anyone suggest how to get it using selenium or beatiful soup? I'm thinking `driver.find_element_by_xpath` or `soup.find_all`.
source:
```
<div class="count-box fixed_when_handheld s-vgLeft0_5 s-vgPullBottom1 s-vgRight0_5 u-colorGray6 u-fontSize18 u-fontWeight200" style="display: block;">
<div class="label-container u-floatLeft">11 tigers</div>
<div class="u-floatRight">
<div class="hide_when_tablet hide_when_desktop s-vgLeft0_5 s-vgRight0_5 u-textAlignCenter">
<div class="js-show-handheld-filters c-button c-button--md c-button--blue s-vgRight1">
Filter
</div>
<div class="js-save-handheld-filters c-button c-button--md c-button--transparent">
Save
</div>
</div>
</div>
<div class="cb"></div>
</div>
``` | 2019/02/26 | [
"https://Stackoverflow.com/questions/54878621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5978130/"
] | You can use same `.count-box .label-container` css selector for both BS and Selenium.
BS:
```
page = BeautifulSoup(yourhtml, "html.parser")
# if you need first one
label = page.select_one(".count-box .label-container").text
# if you need all
labels = page.select(".count-box .label-container")
for label in labels:
print(label.text)
```
Selenium:
```
labels = driver.find_elements_by_css_selector(".count-box .label-container")
for label in labels:
print(label.text)
``` | To extract the text **11 tigers** you can use either of the following solution:
* Using `css_selector`:
```
my_text = driver.find_element_by_css_selector("div.count-box>div.label-container.u-floatLeft").get_attribute("innerHTML")
```
* Using `xpath`:
```
my_text = driver.find_element_by_xpath("//div[contains(@class, 'count-box')]/div[@class='label-container u-floatLeft']").get_attribute("innerHTML")
``` |
15,922,823 | I am implementing a file-based queue of serialized objects, using C#.
* `Push()` will serialize an object as binary and append it to the end of the file.
* `Pop()` should deserialize an object from the beginning of the file (this part I got working). Then, the deserialized part should be removed from the file, making the next object to be "first".
From the standpoint of file system, that would just mean copying file header several bytes further on the disk, and then moving the "beginning of the file" pointer. The question is how to implement this in C#? Is it at all possible? | 2013/04/10 | [
"https://Stackoverflow.com/questions/15922823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/236660/"
] | Yes see the log eip
<http://camel.apache.org/logeip.html>
This allows you to log human readable messages to the log. You could have spotted it, by the green tip box on the log component page: <http://camel.apache.org/log> | >
> **TL;DR**
>
>
> * DO NOT forget about `camel.springboot.main-run-controller=true` in `application.properties`
> * from("timer://scheduler?fixedRate=true&period=5s")
> .log("Hello World!");
>
>
>
Let me provide you the simplest example written in Java DSL. I will use the Spring Boot Camel starter to setup the simplest runnable piece of code. This example will help you to log the message `Hello World!` to your console every 5 seconds according to `quartz2` component `cron` expression.
>
> Documentation to look through:
>
>
> * Spring Boot & Apache Camel - <https://camel.apache.org/spring-boot>
> * Camel's Quartz2 component - <http://camel.apache.org/quartz2.html>
>
>
>
Here is your simplest Spring Boot demo application:
```
package com.lordnighton.camel.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
Here is the simplest route that logs the message `HelloWorld!` into console every 5 seconds:
```
package com.lordnighton.camel.demo.routes;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
@Component
public class LogMessageRoute extends RouteBuilder {
@Override
public void configure() throws Exception {
from("quartz2://logMessageGroup/logMessageTimer?cron=0/5+*+*+*+*+?")
.log("Hello World!");
}
}
``` |
3,802,669 | >
> $m^3-3m^2+2m$ is divisible by $79$ and $83$ where $m>2$. Find the
> lowest value of $m$
>
>
>
$m^3-3m^2+2m$ is the product of three consecutive integers. Both $79$ and $83$ are prime numbers. The product of three consecutive positive integers is divisible by $6$. So, $m^3-3m^2+2m$ is a multiple of $lcm(6,79,83)=39342$. But I can't go any further.
What would be the correct approach to solve problems like this? | 2020/08/25 | [
"https://math.stackexchange.com/questions/3802669",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/632797/"
] | The brute force method: as $m^3−3m^2+2m=m(m−1)(m−2)$, and $79,83$ are prime, you can just solve the following nine congruences: $m\equiv\alpha\pmod{79}$, $m\equiv\beta\pmod{83}$, where $\alpha,\beta\in\{0,1,2\}$. This is possible as per Chinese Remainder Theorem, and the smallest of the nine $m$'s you will get (greater than $2$) is the solution.
It is easy to solve all those congruences simultaneously: per [Wikipedia](https://en.wikipedia.org/wiki/Chinese_remainder_theorem#Existence_(direct_construction)), we first express $1$ as $1=79u+83v$, where $u,v$ can be found using Euclidean algorithm. In this case, as $4=83-79$ and $1=20\cdot 4-79$, we have $1=20\cdot 83-21\cdot 79$.
Now, $m\equiv\alpha\pmod{79}$ and $m\equiv\beta\pmod{83}$ resolves as $m\equiv 20\cdot 83\alpha-21\cdot 79\beta\pmod{79\cdot 83}$, i.e. $m\equiv 1660\alpha-1659\beta\pmod{6557}$. This gives us the following table:
$$\begin{array}{r|r|r|r}\alpha&\beta&m\pmod{6557}&\text{smallest }m\gt 2\\\hline0&0&0&6557\\0&1&4898&4898\\0&2&3239&3239\\1&0&1660&1660\\1&1&1&6558\\1&2&4899&4899\\2&0&3320&3320\\2&1&1661&1661\\2&2&2&6559\end{array}$$
so the smallest solution seems to be $m=1660$. | You computed some admissible number (if you take the correct value for $m$) in the comments. Now you can just let the computer test all the smaller cases
```
m=np.arange(5000)
x=m*(m-1)*(m-2)
m[(x%83==0) & (x%79==0)]
```
which gives the result
```
[ 0, 1, 2, 1660, 1661, 3239, 3320, 4898, 4899]
```
from where you see that there are indeed smaller admissible candidates, as $1660=20\cdot 83$ and $1659=21\cdot79$. |
66,196,249 | How do I increase the textarea height automatically so that the columns on the left and right are of the same height?
[![enter image description here](https://i.stack.imgur.com/zgJt2.png)](https://i.stack.imgur.com/zgJt2.png) | 2021/02/14 | [
"https://Stackoverflow.com/questions/66196249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14372041/"
] | The task is to split a string separated by '+'. In the below example, the delimiter ',' is used.
Splitting a string into tokens is a very old task. There are many many solutions available. All have different properties. Some are difficult to understand, some are hard to develop, some are more complex, slower or faster or more flexible or not.
Alternatives
1. Handcrafted, many variants, using pointers or iterators, maybe hard to develop and error prone.
2. Using old style `std::strtok` function. Maybe unsafe. Maybe should not be used any longer
3. `std::getline`. Most used implementation. But actually a "misuse" and not so flexible
4. Using dedicated modern function, specifically developed for this purpose, most flexible and good fitting into the STL environment and algortithm landscape. But slower.
Please see 4 examples in one piece of code.
```
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <regex>
#include <algorithm>
#include <iterator>
#include <cstring>
#include <forward_list>
#include <deque>
using Container = std::vector<std::string>;
std::regex delimiter{ "," };
int main() {
// Some function to print the contents of an STL container
auto print = [](const auto& container) -> void { std::copy(container.begin(), container.end(),
std::ostream_iterator<std::decay<decltype(*container.begin())>::type>(std::cout, " ")); std::cout << '\n'; };
// Example 1: Handcrafted -------------------------------------------------------------------------
{
// Our string that we want to split
std::string stringToSplit{ "aaa,bbb,ccc,ddd" };
Container c{};
// Search for comma, then take the part and add to the result
for (size_t i{ 0U }, startpos{ 0U }; i <= stringToSplit.size(); ++i) {
// So, if there is a comma or the end of the string
if ((stringToSplit[i] == ',') || (i == (stringToSplit.size()))) {
// Copy substring
c.push_back(stringToSplit.substr(startpos, i - startpos));
startpos = i + 1;
}
}
print(c);
}
// Example 2: Using very old strtok function ----------------------------------------------------------
{
// Our string that we want to split
std::string stringToSplit{ "aaa,bbb,ccc,ddd" };
Container c{};
// Split string into parts in a simple for loop
#pragma warning(suppress : 4996)
for (char* token = std::strtok(const_cast<char*>(stringToSplit.data()), ","); token != nullptr; token = std::strtok(nullptr, ",")) {
c.push_back(token);
}
print(c);
}
// Example 3: Very often used std::getline with additional istringstream ------------------------------------------------
{
// Our string that we want to split
std::string stringToSplit{ "aaa,bbb,ccc,ddd" };
Container c{};
// Put string in an std::istringstream
std::istringstream iss{ stringToSplit };
// Extract string parts in simple for loop
for (std::string part{}; std::getline(iss, part, ','); c.push_back(part))
;
print(c);
}
// Example 4: Most flexible iterator solution ------------------------------------------------
{
// Our string that we want to split
std::string stringToSplit{ "aaa,bbb,ccc,ddd" };
Container c(std::sregex_token_iterator(stringToSplit.begin(), stringToSplit.end(), delimiter, -1), {});
//
// Everything done already with range constructor. No additional code needed.
//
print(c);
// Works also with other containers in the same way
std::forward_list<std::string> c2(std::sregex_token_iterator(stringToSplit.begin(), stringToSplit.end(), delimiter, -1), {});
print(c2);
// And works with algorithms
std::deque<std::string> c3{};
std::copy(std::sregex_token_iterator(stringToSplit.begin(), stringToSplit.end(), delimiter, -1), {}, std::back_inserter(c3));
print(c3);
}
return 0;
}
``` | You can use an `std::vector<std::string>` instead of `char[]`, that way, it would work with more than one-digit numbers. Try this:
```
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
int main() {
using namespace std;
std::string str("1+2+3");
std::string buff;
std::stringstream ss(str);
std::vector<std::string> result;
while(getline(ss, buff, '+')){
result.push_back(buff);
}
for(std::string num : result){
std::cout << num << std::endl;
}
}
```
Here is a [coliru link](http://coliru.stacked-crooked.com/a/3fdb7324642ad722) to show it works with numbers having more than one digit. |
66,196,249 | How do I increase the textarea height automatically so that the columns on the left and right are of the same height?
[![enter image description here](https://i.stack.imgur.com/zgJt2.png)](https://i.stack.imgur.com/zgJt2.png) | 2021/02/14 | [
"https://Stackoverflow.com/questions/66196249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14372041/"
] | The task is to split a string separated by '+'. In the below example, the delimiter ',' is used.
Splitting a string into tokens is a very old task. There are many many solutions available. All have different properties. Some are difficult to understand, some are hard to develop, some are more complex, slower or faster or more flexible or not.
Alternatives
1. Handcrafted, many variants, using pointers or iterators, maybe hard to develop and error prone.
2. Using old style `std::strtok` function. Maybe unsafe. Maybe should not be used any longer
3. `std::getline`. Most used implementation. But actually a "misuse" and not so flexible
4. Using dedicated modern function, specifically developed for this purpose, most flexible and good fitting into the STL environment and algortithm landscape. But slower.
Please see 4 examples in one piece of code.
```
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <regex>
#include <algorithm>
#include <iterator>
#include <cstring>
#include <forward_list>
#include <deque>
using Container = std::vector<std::string>;
std::regex delimiter{ "," };
int main() {
// Some function to print the contents of an STL container
auto print = [](const auto& container) -> void { std::copy(container.begin(), container.end(),
std::ostream_iterator<std::decay<decltype(*container.begin())>::type>(std::cout, " ")); std::cout << '\n'; };
// Example 1: Handcrafted -------------------------------------------------------------------------
{
// Our string that we want to split
std::string stringToSplit{ "aaa,bbb,ccc,ddd" };
Container c{};
// Search for comma, then take the part and add to the result
for (size_t i{ 0U }, startpos{ 0U }; i <= stringToSplit.size(); ++i) {
// So, if there is a comma or the end of the string
if ((stringToSplit[i] == ',') || (i == (stringToSplit.size()))) {
// Copy substring
c.push_back(stringToSplit.substr(startpos, i - startpos));
startpos = i + 1;
}
}
print(c);
}
// Example 2: Using very old strtok function ----------------------------------------------------------
{
// Our string that we want to split
std::string stringToSplit{ "aaa,bbb,ccc,ddd" };
Container c{};
// Split string into parts in a simple for loop
#pragma warning(suppress : 4996)
for (char* token = std::strtok(const_cast<char*>(stringToSplit.data()), ","); token != nullptr; token = std::strtok(nullptr, ",")) {
c.push_back(token);
}
print(c);
}
// Example 3: Very often used std::getline with additional istringstream ------------------------------------------------
{
// Our string that we want to split
std::string stringToSplit{ "aaa,bbb,ccc,ddd" };
Container c{};
// Put string in an std::istringstream
std::istringstream iss{ stringToSplit };
// Extract string parts in simple for loop
for (std::string part{}; std::getline(iss, part, ','); c.push_back(part))
;
print(c);
}
// Example 4: Most flexible iterator solution ------------------------------------------------
{
// Our string that we want to split
std::string stringToSplit{ "aaa,bbb,ccc,ddd" };
Container c(std::sregex_token_iterator(stringToSplit.begin(), stringToSplit.end(), delimiter, -1), {});
//
// Everything done already with range constructor. No additional code needed.
//
print(c);
// Works also with other containers in the same way
std::forward_list<std::string> c2(std::sregex_token_iterator(stringToSplit.begin(), stringToSplit.end(), delimiter, -1), {});
print(c2);
// And works with algorithms
std::deque<std::string> c3{};
std::copy(std::sregex_token_iterator(stringToSplit.begin(), stringToSplit.end(), delimiter, -1), {}, std::back_inserter(c3));
print(c3);
}
return 0;
}
``` | Here are my steps:
* convert the original `string` into `char*`
* split the obtained `char*` with the delimiter `+` by using the function `strtok`. I store each token into a `vector<char>`
* convert this `vector<char>` into a C char array `char*`
```cpp
#include <iostream>
#include <string.h>
#include <vector>
using namespace std;
int main()
{
string line = "1+2+3";
std::vector<char> vectChar;
// convert the original string into a char array to allow splitting
char* input= (char*) malloc(sizeof(char)*line.size());
strcpy(input,line.data());
// splitting the string
char *token = strtok(input, "+");
int len=0;
while(token) {
std::cout << *token;
vectChar.push_back(*token);
token = strtok(NULL, "+");
}
// end of splitting step
std::cout << std::endl;
//test display the content of the vect<char>={'1', '2', ...}
for (int i=0; i< vectChar.size(); i++)
{
std::cout << vectChar[i];
}
// Now that the vector contains the needed list of char
// we need to convert it to char array (char*)
// first malloc
char* buffer = (char*) malloc(vectChar.size()*sizeof(char));
// then convert the vector into char*
std::copy(vectChar.begin(), vectChar.end(), buffer);
std::cout << std::endl;
//now buffer={'1', '2', ...}
// les ut stest by displaying
while ( *buffer != '\0')
{
printf("%c", *buffer);
buffer++;
}
}
``` |
66,196,249 | How do I increase the textarea height automatically so that the columns on the left and right are of the same height?
[![enter image description here](https://i.stack.imgur.com/zgJt2.png)](https://i.stack.imgur.com/zgJt2.png) | 2021/02/14 | [
"https://Stackoverflow.com/questions/66196249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14372041/"
] | The task is to split a string separated by '+'. In the below example, the delimiter ',' is used.
Splitting a string into tokens is a very old task. There are many many solutions available. All have different properties. Some are difficult to understand, some are hard to develop, some are more complex, slower or faster or more flexible or not.
Alternatives
1. Handcrafted, many variants, using pointers or iterators, maybe hard to develop and error prone.
2. Using old style `std::strtok` function. Maybe unsafe. Maybe should not be used any longer
3. `std::getline`. Most used implementation. But actually a "misuse" and not so flexible
4. Using dedicated modern function, specifically developed for this purpose, most flexible and good fitting into the STL environment and algortithm landscape. But slower.
Please see 4 examples in one piece of code.
```
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <regex>
#include <algorithm>
#include <iterator>
#include <cstring>
#include <forward_list>
#include <deque>
using Container = std::vector<std::string>;
std::regex delimiter{ "," };
int main() {
// Some function to print the contents of an STL container
auto print = [](const auto& container) -> void { std::copy(container.begin(), container.end(),
std::ostream_iterator<std::decay<decltype(*container.begin())>::type>(std::cout, " ")); std::cout << '\n'; };
// Example 1: Handcrafted -------------------------------------------------------------------------
{
// Our string that we want to split
std::string stringToSplit{ "aaa,bbb,ccc,ddd" };
Container c{};
// Search for comma, then take the part and add to the result
for (size_t i{ 0U }, startpos{ 0U }; i <= stringToSplit.size(); ++i) {
// So, if there is a comma or the end of the string
if ((stringToSplit[i] == ',') || (i == (stringToSplit.size()))) {
// Copy substring
c.push_back(stringToSplit.substr(startpos, i - startpos));
startpos = i + 1;
}
}
print(c);
}
// Example 2: Using very old strtok function ----------------------------------------------------------
{
// Our string that we want to split
std::string stringToSplit{ "aaa,bbb,ccc,ddd" };
Container c{};
// Split string into parts in a simple for loop
#pragma warning(suppress : 4996)
for (char* token = std::strtok(const_cast<char*>(stringToSplit.data()), ","); token != nullptr; token = std::strtok(nullptr, ",")) {
c.push_back(token);
}
print(c);
}
// Example 3: Very often used std::getline with additional istringstream ------------------------------------------------
{
// Our string that we want to split
std::string stringToSplit{ "aaa,bbb,ccc,ddd" };
Container c{};
// Put string in an std::istringstream
std::istringstream iss{ stringToSplit };
// Extract string parts in simple for loop
for (std::string part{}; std::getline(iss, part, ','); c.push_back(part))
;
print(c);
}
// Example 4: Most flexible iterator solution ------------------------------------------------
{
// Our string that we want to split
std::string stringToSplit{ "aaa,bbb,ccc,ddd" };
Container c(std::sregex_token_iterator(stringToSplit.begin(), stringToSplit.end(), delimiter, -1), {});
//
// Everything done already with range constructor. No additional code needed.
//
print(c);
// Works also with other containers in the same way
std::forward_list<std::string> c2(std::sregex_token_iterator(stringToSplit.begin(), stringToSplit.end(), delimiter, -1), {});
print(c2);
// And works with algorithms
std::deque<std::string> c3{};
std::copy(std::sregex_token_iterator(stringToSplit.begin(), stringToSplit.end(), delimiter, -1), {}, std::back_inserter(c3));
print(c3);
}
return 0;
}
``` | You can run/check this code in <https://repl.it/@JomaCorpFX/StringSplit#main.cpp>
**Code**
```
#include <iostream>
#include <vector>
std::vector<std::string> Split(const std::string &data, const std::string &toFind)
{
std::vector<std::string> v;
if (data.empty() || toFind.empty())
{
v.push_back(data);
return v;
}
size_t ini = 0;
size_t pos;
while ((pos = data.find(toFind, ini)) != std::string::npos)
{
std::string s = data.substr(ini, pos - ini);
if (!s.empty())
{
v.push_back(s);
}
ini = pos + toFind.length();
}
if (ini < data.length())
{
v.push_back(data.substr(ini));
}
return v;
}
int main()
{
std::string x = "1+2+3";
for (auto value : Split(x, u8"+"))
{
std::cout << "Value: " << value << std::endl;
}
std::cout << u8"Press enter to continue... ";
std::cin.get();
return EXIT_SUCCESS;
}
```
**Output**
```
Value: 1
Value: 2
Value: 3
Press enter to continue...
```
[![clang++](https://i.stack.imgur.com/2xTt2.png)](https://i.stack.imgur.com/2xTt2.png) |
66,196,249 | How do I increase the textarea height automatically so that the columns on the left and right are of the same height?
[![enter image description here](https://i.stack.imgur.com/zgJt2.png)](https://i.stack.imgur.com/zgJt2.png) | 2021/02/14 | [
"https://Stackoverflow.com/questions/66196249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14372041/"
] | You can use an `std::vector<std::string>` instead of `char[]`, that way, it would work with more than one-digit numbers. Try this:
```
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
int main() {
using namespace std;
std::string str("1+2+3");
std::string buff;
std::stringstream ss(str);
std::vector<std::string> result;
while(getline(ss, buff, '+')){
result.push_back(buff);
}
for(std::string num : result){
std::cout << num << std::endl;
}
}
```
Here is a [coliru link](http://coliru.stacked-crooked.com/a/3fdb7324642ad722) to show it works with numbers having more than one digit. | Here are my steps:
* convert the original `string` into `char*`
* split the obtained `char*` with the delimiter `+` by using the function `strtok`. I store each token into a `vector<char>`
* convert this `vector<char>` into a C char array `char*`
```cpp
#include <iostream>
#include <string.h>
#include <vector>
using namespace std;
int main()
{
string line = "1+2+3";
std::vector<char> vectChar;
// convert the original string into a char array to allow splitting
char* input= (char*) malloc(sizeof(char)*line.size());
strcpy(input,line.data());
// splitting the string
char *token = strtok(input, "+");
int len=0;
while(token) {
std::cout << *token;
vectChar.push_back(*token);
token = strtok(NULL, "+");
}
// end of splitting step
std::cout << std::endl;
//test display the content of the vect<char>={'1', '2', ...}
for (int i=0; i< vectChar.size(); i++)
{
std::cout << vectChar[i];
}
// Now that the vector contains the needed list of char
// we need to convert it to char array (char*)
// first malloc
char* buffer = (char*) malloc(vectChar.size()*sizeof(char));
// then convert the vector into char*
std::copy(vectChar.begin(), vectChar.end(), buffer);
std::cout << std::endl;
//now buffer={'1', '2', ...}
// les ut stest by displaying
while ( *buffer != '\0')
{
printf("%c", *buffer);
buffer++;
}
}
``` |
66,196,249 | How do I increase the textarea height automatically so that the columns on the left and right are of the same height?
[![enter image description here](https://i.stack.imgur.com/zgJt2.png)](https://i.stack.imgur.com/zgJt2.png) | 2021/02/14 | [
"https://Stackoverflow.com/questions/66196249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14372041/"
] | You can use an `std::vector<std::string>` instead of `char[]`, that way, it would work with more than one-digit numbers. Try this:
```
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
int main() {
using namespace std;
std::string str("1+2+3");
std::string buff;
std::stringstream ss(str);
std::vector<std::string> result;
while(getline(ss, buff, '+')){
result.push_back(buff);
}
for(std::string num : result){
std::cout << num << std::endl;
}
}
```
Here is a [coliru link](http://coliru.stacked-crooked.com/a/3fdb7324642ad722) to show it works with numbers having more than one digit. | You can run/check this code in <https://repl.it/@JomaCorpFX/StringSplit#main.cpp>
**Code**
```
#include <iostream>
#include <vector>
std::vector<std::string> Split(const std::string &data, const std::string &toFind)
{
std::vector<std::string> v;
if (data.empty() || toFind.empty())
{
v.push_back(data);
return v;
}
size_t ini = 0;
size_t pos;
while ((pos = data.find(toFind, ini)) != std::string::npos)
{
std::string s = data.substr(ini, pos - ini);
if (!s.empty())
{
v.push_back(s);
}
ini = pos + toFind.length();
}
if (ini < data.length())
{
v.push_back(data.substr(ini));
}
return v;
}
int main()
{
std::string x = "1+2+3";
for (auto value : Split(x, u8"+"))
{
std::cout << "Value: " << value << std::endl;
}
std::cout << u8"Press enter to continue... ";
std::cin.get();
return EXIT_SUCCESS;
}
```
**Output**
```
Value: 1
Value: 2
Value: 3
Press enter to continue...
```
[![clang++](https://i.stack.imgur.com/2xTt2.png)](https://i.stack.imgur.com/2xTt2.png) |
65,140,738 | We have a case like this.
```java
class A{
class foo{
//Map with a lot of entries
private HashMap<String,String> dataMap;
public updater(){
// updates dataMap
// takes several milliseconds
}
public someAction(){
// needs to perform read on dataMap
// several times, in a long process
// which takes several milliseconds
}
}
```
The issue is, both someAction and updater both can be called simultaneously, someAction is a more frequent method. If updater is called, it can replace a lot of values from dataMap. And we need consistency in readAction. If the method starts with old dataMap, then all reads should happen with old dataMap.
```java
class foo{
//Map with a lot of entries
private HashMap<String,String> dataMap;
public updater(){
var updateDataMap = clone(dataMap); // some way to clone data from map
// updates updateDataMap instead of dataMap
// takes several milliseconds
this.dataMap = updateDataMap;
}
public someAction(){
var readDataMap = dataMap;
// reads from readDataMap instead of dataMap
// several times, in a long process
// which takes several milliseconds
}
}
```
Will this ensure consistency? I believe that the clone method will allocate a different area in memory and new references will happen from there. And are there going to be any performance impacts? And will the memory of oldDataMap be released after it has been used?
If this is the correct way, are there are any other efficient way to achieve the same? | 2020/12/04 | [
"https://Stackoverflow.com/questions/65140738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14008598/"
] | You can use [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) API. In Angular you can write a directive for handle that:
```
@Directive({
selector: '[lazySrc]'
})
export class ImgDataDirective implements OnInit, OnChanges {
@Input('lazySrc') src: string;
constructor(
private _elRef: ElementRef,
private _renderer: Renderer2,
@Inject(PLATFORM_ID) private platformId: Object
) {}
ngOnChanges(changes: SimpleChanges): void {
this._loadImage();
}
ngOnInit(): void {
this._renderer.setAttribute(this._elRef.nativeElement, 'src', PLACEHOLDER);
if (isPlatformBrowser(this.platformId)) {
const obs = new IntersectionObserver(entries => {
entries.forEach(({ isIntersecting }) => {
if (isIntersecting) {
this._loadImage();
obs.unobserve(this._elRef.nativeElement);
}
});
});
obs.observe(this._elRef.nativeElement);
}
}
private _loadImage() {
this._renderer.setAttribute(this._elRef.nativeElement, 'src', this.src);
}
}
``` | Your objective is to load the images visible on the screen.
You can achieve this by adding an attribute to image tag.
```
<img loading=lazy>
```
Source:
* <https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-loading>
* <https://web.dev/browser-level-image-lazy-loading/>
Working Example:
<https://stackblitz.com/edit/angular-agkfuq?file=src/app/app.component.html> |
66,147,347 | I'm trying to create a new column, "condition\_any", in `df` with {data.table} that is TRUE if any of the of the 3 conditions are TRUE, per row.
I tried using `any(.SD)` with no luck:
```
library(data.table)
df <- data.table(id = 1:3,
date = Sys.Date() + 1:3,
condition1 = c(T, F, F),
condition2 = c(T, F, T),
condition3 = c(F, F, F))
df[, condition_any := any(.SD), .SDcols = patterns("^condition")]
Error in FUN(X[[i]], ...) :
only defined on a data frame with all numeric variables
```
Any ideas on how I can get this to work, I thought it would be an easy thing to do.
Thanks
Expected output:
```
id date condition1 condition2 condition3 condition_any
1: 1 2021-02-12 TRUE TRUE FALSE TRUE
2: 2 2021-02-13 FALSE FALSE FALSE FALSE
3: 3 2021-02-14 FALSE TRUE FALSE TRUE
``` | 2021/02/11 | [
"https://Stackoverflow.com/questions/66147347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8675075/"
] | This also doesn't use `any` but is a nice way to do it,
```
df[, condition_any := Reduce('|', .SD), .SDcols = patterns("^condition")]
``` | I believe the code below will give what you want. You can check [this post](https://stackoverflow.com/questions/38032814/trying-to-understand-r-error-error-in-funxi-only-defined-on-a-data) to see the explanation of the error.
```
df$condition_any <- apply(df[,3:5], 1, function(x) any(x))
``` |
66,147,347 | I'm trying to create a new column, "condition\_any", in `df` with {data.table} that is TRUE if any of the of the 3 conditions are TRUE, per row.
I tried using `any(.SD)` with no luck:
```
library(data.table)
df <- data.table(id = 1:3,
date = Sys.Date() + 1:3,
condition1 = c(T, F, F),
condition2 = c(T, F, T),
condition3 = c(F, F, F))
df[, condition_any := any(.SD), .SDcols = patterns("^condition")]
Error in FUN(X[[i]], ...) :
only defined on a data frame with all numeric variables
```
Any ideas on how I can get this to work, I thought it would be an easy thing to do.
Thanks
Expected output:
```
id date condition1 condition2 condition3 condition_any
1: 1 2021-02-12 TRUE TRUE FALSE TRUE
2: 2 2021-02-13 FALSE FALSE FALSE FALSE
3: 3 2021-02-14 FALSE TRUE FALSE TRUE
``` | 2021/02/11 | [
"https://Stackoverflow.com/questions/66147347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8675075/"
] | I believe the code below will give what you want. You can check [this post](https://stackoverflow.com/questions/38032814/trying-to-understand-r-error-error-in-funxi-only-defined-on-a-data) to see the explanation of the error.
```
df$condition_any <- apply(df[,3:5], 1, function(x) any(x))
``` | This uses `any` and works as intended but it would be slow since it is grouping the data rowwise.
```
library(data.table)
df[, condition_any := any(unlist(.SD)), .SDcols = patterns("^condition"),
1:nrow(df)]
df
# id date condition1 condition2 condition3 condition_any
#1: 1 2021-02-12 TRUE TRUE FALSE TRUE
#2: 2 2021-02-13 FALSE FALSE FALSE FALSE
#3: 3 2021-02-14 FALSE TRUE FALSE TRUE
``` |
66,147,347 | I'm trying to create a new column, "condition\_any", in `df` with {data.table} that is TRUE if any of the of the 3 conditions are TRUE, per row.
I tried using `any(.SD)` with no luck:
```
library(data.table)
df <- data.table(id = 1:3,
date = Sys.Date() + 1:3,
condition1 = c(T, F, F),
condition2 = c(T, F, T),
condition3 = c(F, F, F))
df[, condition_any := any(.SD), .SDcols = patterns("^condition")]
Error in FUN(X[[i]], ...) :
only defined on a data frame with all numeric variables
```
Any ideas on how I can get this to work, I thought it would be an easy thing to do.
Thanks
Expected output:
```
id date condition1 condition2 condition3 condition_any
1: 1 2021-02-12 TRUE TRUE FALSE TRUE
2: 2 2021-02-13 FALSE FALSE FALSE FALSE
3: 3 2021-02-14 FALSE TRUE FALSE TRUE
``` | 2021/02/11 | [
"https://Stackoverflow.com/questions/66147347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8675075/"
] | This also doesn't use `any` but is a nice way to do it,
```
df[, condition_any := Reduce('|', .SD), .SDcols = patterns("^condition")]
``` | This uses `any` and works as intended but it would be slow since it is grouping the data rowwise.
```
library(data.table)
df[, condition_any := any(unlist(.SD)), .SDcols = patterns("^condition"),
1:nrow(df)]
df
# id date condition1 condition2 condition3 condition_any
#1: 1 2021-02-12 TRUE TRUE FALSE TRUE
#2: 2 2021-02-13 FALSE FALSE FALSE FALSE
#3: 3 2021-02-14 FALSE TRUE FALSE TRUE
``` |
160,370 | I have been tasked with ensuring the CIS Bechmark on Amazon Linux 2016.09.
Does anyone know of an examination tool that will output the difference between the current and the benchmark?
Unfortunately I cannot use one of the existing marketplace AMI's. | 2017/05/25 | [
"https://security.stackexchange.com/questions/160370",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/149282/"
] | [Lynis](https://cisofy.com/lynis/) is the open source alternative which not only does CIS but few other compliance tests as well.
The ability to modify the code to generate custom reports is handy for large number of systems. | Although it's not free, one way of assessing systems against CIS benchmarks is to use [Temable Nessus](https://www.tenable.com/products/nessus-vulnerability-scanner)
Amongst other things, they have CIS audit files for Amazon Linux. |
9,626,995 | Ive been using the 'event' parameter for my KeyboardEvents and MouseEvents in a recent project ive been working on for my course (VERY BASIC).
Im not entirely sure on what the 'e' part of e:KeyboardEvent actually does, and ive been asked to find out what information the parameter 'e' can actually access when using it.
Im sorry if the questions badly written, its been a long night!
**EDIT: If A method takes the parameter (e:KeyboardEvent). what information could we access through the use of the parameter e?** | 2012/03/09 | [
"https://Stackoverflow.com/questions/9626995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1256106/"
] | I'm assuming you have some function like this
```
function someFunction(e:KeyboardEvent):void
{
// code
}
```
You can access any information from the [KeyboardEvent](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/KeyboardEvent.html) class, just the same as if the parameter were called "event". The name of the parameter doesn't affect what you can access through it; the type does.
Edit: "e" is just the *name* of the variable - it could be called `fred`, `banana`, or `tyrannosaurusRex`, and it would make no difference. The thing that determines what sort of information you can access through a variable is its *type* - in this case, `KeyboardEvent`. If you follow the `KeyboardEvent` link above, you will see documentation for the `KeyboardEvent` class, which will tell you all the things you can do with it. For example, one of the properties of `KeyboardEvent` is `keyCode`, which tells you which key was pressed:
```
if (e.keyCode == 32)
{
// 32 is the keyCode for spacebar, so spacebar was pressed
}
``` | You're naming the event that triggers the function, just like any other var it can be named anything. Then, depending on the type of event, you'll have access to a number of vars and function relating to whatever caused the event to trigger.
Edit: [Here's](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/MouseEvent.html) what's available to you with a MouseEvent (Public Properties) |
9,626,995 | Ive been using the 'event' parameter for my KeyboardEvents and MouseEvents in a recent project ive been working on for my course (VERY BASIC).
Im not entirely sure on what the 'e' part of e:KeyboardEvent actually does, and ive been asked to find out what information the parameter 'e' can actually access when using it.
Im sorry if the questions badly written, its been a long night!
**EDIT: If A method takes the parameter (e:KeyboardEvent). what information could we access through the use of the parameter e?** | 2012/03/09 | [
"https://Stackoverflow.com/questions/9626995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1256106/"
] | `e` represents an instance of `KeyboardEvent` (the instance being passed to your listening function).
The most important property of `KeyboardEvent` (referenced by `e` in your example) is `keyCode`.
This determines which key is being pressed/released.
eg:
```
stage.addEventListener(KeyboardEvent.KEY_DOWN, _keyDown);
function _keyDown(e:KeyboardEvent):void
{
trace(e.keyCode); // Will be 65 if you press 'a'.
}
``` | You're naming the event that triggers the function, just like any other var it can be named anything. Then, depending on the type of event, you'll have access to a number of vars and function relating to whatever caused the event to trigger.
Edit: [Here's](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/MouseEvent.html) what's available to you with a MouseEvent (Public Properties) |
9,626,995 | Ive been using the 'event' parameter for my KeyboardEvents and MouseEvents in a recent project ive been working on for my course (VERY BASIC).
Im not entirely sure on what the 'e' part of e:KeyboardEvent actually does, and ive been asked to find out what information the parameter 'e' can actually access when using it.
Im sorry if the questions badly written, its been a long night!
**EDIT: If A method takes the parameter (e:KeyboardEvent). what information could we access through the use of the parameter e?** | 2012/03/09 | [
"https://Stackoverflow.com/questions/9626995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1256106/"
] | ```
import flash.events.KeyboardEvent;
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyboardHandler);
function keyboardHandler(Jack:KeyboardEvent):void{
trace(Jack.keyCode);///----------see output pannel
}
/////////////////--------or
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyboardHandler2);
function keyboardHandler2(Banana:KeyboardEvent):void{
trace(Banana.keyCode);////////----see output pannel
}
```
You can type anything inside()including KeyboardEvent | You're naming the event that triggers the function, just like any other var it can be named anything. Then, depending on the type of event, you'll have access to a number of vars and function relating to whatever caused the event to trigger.
Edit: [Here's](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/MouseEvent.html) what's available to you with a MouseEvent (Public Properties) |
6,728,212 | This is the point, I have a WCF service, it is working now. So I begin to work on the client side. And when the application was running, then an exception showed up: timeout. So I began to read, there are many examples about how to keep the connection alive, but, also I found that the best way, is create channel, use it, and dispose it. And honestly, I liked that. So, now reading about the best way to close the channel, there are two links that could be useful to anybody who needs them:
[1. Clean up clients, the right way](http://geekswithblogs.net/SoftwareDoneRight/archive/2008/05/23/clean-up-wcf-clients--the-right-way.aspx)
[2. Using Func](http://www.atrevido.net/blog/2007/08/13/Practical+Functional+C+Part+II.aspx)
In the first link, this is the example:
```
IIdentityService _identitySvc;
...
if (_identitySvc != null)
{
((IClientChannel)_identitySvc).Close();
((IDisposable)_identitySvc).Dispose();
_identitySvc = null;
}
```
So, if the channel is not null, then is closed, disposed, and assign null. But I have a little question. In this example the channel has a .Close() method, but, in my case, intellisense is not showing a Close() method. It only exists in the factory object. So I believe I have to write it. But, in the interface that has the contracts or the class that implemets it??. And, what should be doing this method??.
Now, the next link, this has something I haven't try before. `Func<T>`. And after reading the goal, it's quite interesting. It creates a funcion that with lambdas creates the channel, uses it, closes it, and dipose it. This example implements that function like a `Using()` statement. It's really good, and a excellent improvement. But, I need a little help, to be honest, I can't understand the function, so, a little explanatino from an expert will be very useful. This is the function:
```
TReturn UseService<TChannel, TReturn>(Func<TChannel, TReturn> code)
{
var chanFactory = GetCachedFactory<TChannel>();
TChannel channel = chanFactory.CreateChannel();
bool error = true;
try {
TReturn result = code(channel);
((IClientChannel)channel).Close();
error = false;
return result;
}
finally {
if (error) {
((IClientChannel)channel).Abort();
}
}
}
```
And this is how is being used:
```
int a = 1;
int b = 2;
int sum = UseService((ICalculator calc) => calc.Add(a, b));
Console.WriteLine(sum);
```
Yep, I think is really, really good, I'd like to understand it to use it in the project I have.
And, like always, I hope this could be helpful to a lot of people. | 2011/07/18 | [
"https://Stackoverflow.com/questions/6728212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/818519/"
] | the UseService method accepts a delegate, which uses the channel to send request. The delegate has a parameter and a return value. You can put the call to WCF service in the delegate.
And in the UseService, it creates the channel and pass the channel to the delegate, which should be provided by you. After finishing the call, it closes the channel. | The proxy object implements more than just your contract - it also implements [IClientChannel](http://msdn.microsoft.com/en-us/library/system.servicemodel.iclientchannel.aspx) which allows control of the proxy lifetime
The code in the first example is not reliable - it will leak if the channel is already busted (e.g. the service has gone down in a session based interaction). As you can see in the second version, in the case of an error it calls Abort on the proxy which still cleans up the client side
You can also do this with an extension method as follows:
```
enum OnError
{
Throw,
DontThrow
}
static class ProxyExtensions
{
public static void CleanUp(this IClientChannel proxy, OnError errorBehavior)
{
try
{
proxy.Close();
}
catch
{
proxy.Abort();
if (errorBehavior == OnError.Throw)
{
throw;
}
}
}
}
```
However, the usage of this is a little cumbersome
```
((IClientChannel)proxy).CleanUp(OnError.DontThrow);
```
But you can make this more elegant if you make your own proxy interface that extends both your contract and IClientChannel
```
interface IPingProxy : IPing, IClientChannel
{
}
``` |
6,728,212 | This is the point, I have a WCF service, it is working now. So I begin to work on the client side. And when the application was running, then an exception showed up: timeout. So I began to read, there are many examples about how to keep the connection alive, but, also I found that the best way, is create channel, use it, and dispose it. And honestly, I liked that. So, now reading about the best way to close the channel, there are two links that could be useful to anybody who needs them:
[1. Clean up clients, the right way](http://geekswithblogs.net/SoftwareDoneRight/archive/2008/05/23/clean-up-wcf-clients--the-right-way.aspx)
[2. Using Func](http://www.atrevido.net/blog/2007/08/13/Practical+Functional+C+Part+II.aspx)
In the first link, this is the example:
```
IIdentityService _identitySvc;
...
if (_identitySvc != null)
{
((IClientChannel)_identitySvc).Close();
((IDisposable)_identitySvc).Dispose();
_identitySvc = null;
}
```
So, if the channel is not null, then is closed, disposed, and assign null. But I have a little question. In this example the channel has a .Close() method, but, in my case, intellisense is not showing a Close() method. It only exists in the factory object. So I believe I have to write it. But, in the interface that has the contracts or the class that implemets it??. And, what should be doing this method??.
Now, the next link, this has something I haven't try before. `Func<T>`. And after reading the goal, it's quite interesting. It creates a funcion that with lambdas creates the channel, uses it, closes it, and dipose it. This example implements that function like a `Using()` statement. It's really good, and a excellent improvement. But, I need a little help, to be honest, I can't understand the function, so, a little explanatino from an expert will be very useful. This is the function:
```
TReturn UseService<TChannel, TReturn>(Func<TChannel, TReturn> code)
{
var chanFactory = GetCachedFactory<TChannel>();
TChannel channel = chanFactory.CreateChannel();
bool error = true;
try {
TReturn result = code(channel);
((IClientChannel)channel).Close();
error = false;
return result;
}
finally {
if (error) {
((IClientChannel)channel).Abort();
}
}
}
```
And this is how is being used:
```
int a = 1;
int b = 2;
int sum = UseService((ICalculator calc) => calc.Add(a, b));
Console.WriteLine(sum);
```
Yep, I think is really, really good, I'd like to understand it to use it in the project I have.
And, like always, I hope this could be helpful to a lot of people. | 2011/07/18 | [
"https://Stackoverflow.com/questions/6728212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/818519/"
] | the UseService method accepts a delegate, which uses the channel to send request. The delegate has a parameter and a return value. You can put the call to WCF service in the delegate.
And in the UseService, it creates the channel and pass the channel to the delegate, which should be provided by you. After finishing the call, it closes the channel. | To answer the question left in the comment in Jason's answer, a simple example of GetCachedFactory may look like the below. The example looks up the endpoint to create by finding the endpoint in the config file with the "Contract" attribute equal to the ConfigurationName of the service the factory is to create.
```
ChannelFactory<T> GetCachedFactory<T>()
{
var endPointName = EndPointNameLookUp<T>();
return new ChannelFactory<T>(endPointName);
}
// Determines the name of the endpoint the factory will create by finding the endpoint in the config file which is the same as the type of the service the factory is to create
string EndPointNameLookUp<T>()
{
var contractName = LookUpContractName<T>();
foreach (ChannelEndpointElement serviceElement in ConfigFileEndPoints)
{
if (serviceElement.Contract == contractName) return serviceElement.Name;
}
return string.Empty;
}
// Retrieves the list of endpoints in the config file
ChannelEndpointElementCollection ConfigFileEndPoints
{
get
{
return ServiceModelSectionGroup.GetSectionGroup(
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None)).Client.Endpoints;
}
}
// Retrieves the ConfigurationName of the service being created by the factory
string LookUpContractName<T>()
{
var attributeNamedArguments = typeof (T).GetCustomAttributesData()
.Select(x => x.NamedArguments.SingleOrDefault(ConfigurationNameQuery));
var contractName = attributeNamedArguments.Single(ConfigurationNameQuery).TypedValue.Value.ToString();
return contractName;
}
Func<CustomAttributeNamedArgument, bool> ConfigurationNameQuery
{
get { return x => x.MemberInfo != null && x.MemberInfo.Name == "ConfigurationName"; }
}
```
A better solution though is to let an IoC container manage the creation of the client for you. For example, using [autofac](http://code.google.com/p/autofac/wiki/WcfIntegration) it would like the following. First you need to register the service like so:
```
var builder = new ContainerBuilder();
builder.Register(c => new ChannelFactory<ICalculator>("WSHttpBinding_ICalculator"))
.SingleInstance();
builder.Register(c => c.Resolve<ChannelFactory<ICalculator>>().CreateChannel())
.UseWcfSafeRelease();
container = builder.Build();
```
Where "WSHttpBinding\_ICalculator" is the name of the endpoint in the config file. Then later you can use the service like so:
```
using (var lifetime = container.BeginLifetimeScope())
{
var calc = lifetime.Resolve<IContentService>();
var sum = calc.Add(a, b);
Console.WriteLine(sum);
}
``` |
6,728,212 | This is the point, I have a WCF service, it is working now. So I begin to work on the client side. And when the application was running, then an exception showed up: timeout. So I began to read, there are many examples about how to keep the connection alive, but, also I found that the best way, is create channel, use it, and dispose it. And honestly, I liked that. So, now reading about the best way to close the channel, there are two links that could be useful to anybody who needs them:
[1. Clean up clients, the right way](http://geekswithblogs.net/SoftwareDoneRight/archive/2008/05/23/clean-up-wcf-clients--the-right-way.aspx)
[2. Using Func](http://www.atrevido.net/blog/2007/08/13/Practical+Functional+C+Part+II.aspx)
In the first link, this is the example:
```
IIdentityService _identitySvc;
...
if (_identitySvc != null)
{
((IClientChannel)_identitySvc).Close();
((IDisposable)_identitySvc).Dispose();
_identitySvc = null;
}
```
So, if the channel is not null, then is closed, disposed, and assign null. But I have a little question. In this example the channel has a .Close() method, but, in my case, intellisense is not showing a Close() method. It only exists in the factory object. So I believe I have to write it. But, in the interface that has the contracts or the class that implemets it??. And, what should be doing this method??.
Now, the next link, this has something I haven't try before. `Func<T>`. And after reading the goal, it's quite interesting. It creates a funcion that with lambdas creates the channel, uses it, closes it, and dipose it. This example implements that function like a `Using()` statement. It's really good, and a excellent improvement. But, I need a little help, to be honest, I can't understand the function, so, a little explanatino from an expert will be very useful. This is the function:
```
TReturn UseService<TChannel, TReturn>(Func<TChannel, TReturn> code)
{
var chanFactory = GetCachedFactory<TChannel>();
TChannel channel = chanFactory.CreateChannel();
bool error = true;
try {
TReturn result = code(channel);
((IClientChannel)channel).Close();
error = false;
return result;
}
finally {
if (error) {
((IClientChannel)channel).Abort();
}
}
}
```
And this is how is being used:
```
int a = 1;
int b = 2;
int sum = UseService((ICalculator calc) => calc.Add(a, b));
Console.WriteLine(sum);
```
Yep, I think is really, really good, I'd like to understand it to use it in the project I have.
And, like always, I hope this could be helpful to a lot of people. | 2011/07/18 | [
"https://Stackoverflow.com/questions/6728212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/818519/"
] | The proxy object implements more than just your contract - it also implements [IClientChannel](http://msdn.microsoft.com/en-us/library/system.servicemodel.iclientchannel.aspx) which allows control of the proxy lifetime
The code in the first example is not reliable - it will leak if the channel is already busted (e.g. the service has gone down in a session based interaction). As you can see in the second version, in the case of an error it calls Abort on the proxy which still cleans up the client side
You can also do this with an extension method as follows:
```
enum OnError
{
Throw,
DontThrow
}
static class ProxyExtensions
{
public static void CleanUp(this IClientChannel proxy, OnError errorBehavior)
{
try
{
proxy.Close();
}
catch
{
proxy.Abort();
if (errorBehavior == OnError.Throw)
{
throw;
}
}
}
}
```
However, the usage of this is a little cumbersome
```
((IClientChannel)proxy).CleanUp(OnError.DontThrow);
```
But you can make this more elegant if you make your own proxy interface that extends both your contract and IClientChannel
```
interface IPingProxy : IPing, IClientChannel
{
}
``` | To answer the question left in the comment in Jason's answer, a simple example of GetCachedFactory may look like the below. The example looks up the endpoint to create by finding the endpoint in the config file with the "Contract" attribute equal to the ConfigurationName of the service the factory is to create.
```
ChannelFactory<T> GetCachedFactory<T>()
{
var endPointName = EndPointNameLookUp<T>();
return new ChannelFactory<T>(endPointName);
}
// Determines the name of the endpoint the factory will create by finding the endpoint in the config file which is the same as the type of the service the factory is to create
string EndPointNameLookUp<T>()
{
var contractName = LookUpContractName<T>();
foreach (ChannelEndpointElement serviceElement in ConfigFileEndPoints)
{
if (serviceElement.Contract == contractName) return serviceElement.Name;
}
return string.Empty;
}
// Retrieves the list of endpoints in the config file
ChannelEndpointElementCollection ConfigFileEndPoints
{
get
{
return ServiceModelSectionGroup.GetSectionGroup(
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None)).Client.Endpoints;
}
}
// Retrieves the ConfigurationName of the service being created by the factory
string LookUpContractName<T>()
{
var attributeNamedArguments = typeof (T).GetCustomAttributesData()
.Select(x => x.NamedArguments.SingleOrDefault(ConfigurationNameQuery));
var contractName = attributeNamedArguments.Single(ConfigurationNameQuery).TypedValue.Value.ToString();
return contractName;
}
Func<CustomAttributeNamedArgument, bool> ConfigurationNameQuery
{
get { return x => x.MemberInfo != null && x.MemberInfo.Name == "ConfigurationName"; }
}
```
A better solution though is to let an IoC container manage the creation of the client for you. For example, using [autofac](http://code.google.com/p/autofac/wiki/WcfIntegration) it would like the following. First you need to register the service like so:
```
var builder = new ContainerBuilder();
builder.Register(c => new ChannelFactory<ICalculator>("WSHttpBinding_ICalculator"))
.SingleInstance();
builder.Register(c => c.Resolve<ChannelFactory<ICalculator>>().CreateChannel())
.UseWcfSafeRelease();
container = builder.Build();
```
Where "WSHttpBinding\_ICalculator" is the name of the endpoint in the config file. Then later you can use the service like so:
```
using (var lifetime = container.BeginLifetimeScope())
{
var calc = lifetime.Resolve<IContentService>();
var sum = calc.Add(a, b);
Console.WriteLine(sum);
}
``` |
37,945,115 | I am using Rfacebook to extract some content from Facebook's API through R. I somehow get sometimes posts two or three times back even though they only appear 1 time in facebook. Probably some problem with my crawler. I extracted already a lot of data and don't want to rerun the crawling. So I was thinking about cleaning the data I have.
Is there any handy way with dplyr to do that?
The data I got looks like the following:
```
Name message created_time id
Sam Hello World 2013-03-09T19:52:22+0000 26937808
Nicky Hello Sam 2013-03-09T19:53:16+0000 26930800
Nicky Hello Sam 2013-03-09T19:53:16+0000 26930800
Nicky Hello Sam 2013-03-09T19:53:16+0000 26930800
Sam Whats Up? 2013-03-09T19:53:22+0000 26937806
Sam Whats Up? 2013-03-09T19:53:22+0000 26937806
Florence Hi guys! 2013-03-09T19:55:16+0000 25688232
Steff How r u? 2013-03-09T19:59:16+0000 64552194
```
I would now like to have a new data frame in which every post only appears one time so that the three "double" posts from Nicky will be reduced to only one and the two double posts from Sam also get reduced to one post.
Any idea or suggestion how to do this in R? It seems like facebook is giving unique ids to posts and comments as well as that the time stamps are almost unique in my data. Both would be working for identification. However, it remains unclear to me how to best do the transformation...
Any help with this is highly appreciated!
Thanks! | 2016/06/21 | [
"https://Stackoverflow.com/questions/37945115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5223902/"
] | You just need a brief wait to wait until the `DIV` that contains the error message appears. The code below is working for me.
```
WebDriver driver = new FirefoxDriver();
driver.get("https://app.ghostinspector.com/account/create");
driver.findElement(By.id("input-firstName")).sendKeys("Johnny");
driver.findElement(By.id("input-lastName")).sendKeys("Smith");
driver.findElement(By.id("input-email")).sendKeys("abc@abc.com");
driver.findElement(By.id("input-password")).sendKeys("abc123");
driver.findElement(By.id("input-terms")).click();
driver.findElement(By.id("btn-create")).click();
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement e = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div[ng-show='errors']")));
System.out.println(e.getText());
``` | Try usinfg this to clear the text box
```
driver.switchTo().alert().getText();
``` |
37,945,115 | I am using Rfacebook to extract some content from Facebook's API through R. I somehow get sometimes posts two or three times back even though they only appear 1 time in facebook. Probably some problem with my crawler. I extracted already a lot of data and don't want to rerun the crawling. So I was thinking about cleaning the data I have.
Is there any handy way with dplyr to do that?
The data I got looks like the following:
```
Name message created_time id
Sam Hello World 2013-03-09T19:52:22+0000 26937808
Nicky Hello Sam 2013-03-09T19:53:16+0000 26930800
Nicky Hello Sam 2013-03-09T19:53:16+0000 26930800
Nicky Hello Sam 2013-03-09T19:53:16+0000 26930800
Sam Whats Up? 2013-03-09T19:53:22+0000 26937806
Sam Whats Up? 2013-03-09T19:53:22+0000 26937806
Florence Hi guys! 2013-03-09T19:55:16+0000 25688232
Steff How r u? 2013-03-09T19:59:16+0000 64552194
```
I would now like to have a new data frame in which every post only appears one time so that the three "double" posts from Nicky will be reduced to only one and the two double posts from Sam also get reduced to one post.
Any idea or suggestion how to do this in R? It seems like facebook is giving unique ids to posts and comments as well as that the time stamps are almost unique in my data. Both would be working for identification. However, it remains unclear to me how to best do the transformation...
Any help with this is highly appreciated!
Thanks! | 2016/06/21 | [
"https://Stackoverflow.com/questions/37945115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5223902/"
] | You just need a brief wait to wait until the `DIV` that contains the error message appears. The code below is working for me.
```
WebDriver driver = new FirefoxDriver();
driver.get("https://app.ghostinspector.com/account/create");
driver.findElement(By.id("input-firstName")).sendKeys("Johnny");
driver.findElement(By.id("input-lastName")).sendKeys("Smith");
driver.findElement(By.id("input-email")).sendKeys("abc@abc.com");
driver.findElement(By.id("input-password")).sendKeys("abc123");
driver.findElement(By.id("input-terms")).click();
driver.findElement(By.id("btn-create")).click();
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement e = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div[ng-show='errors']")));
System.out.println(e.getText());
``` | you are using getAttribute("value") to get the text from the div element. try using email\_in\_use.getText(). |
37,945,115 | I am using Rfacebook to extract some content from Facebook's API through R. I somehow get sometimes posts two or three times back even though they only appear 1 time in facebook. Probably some problem with my crawler. I extracted already a lot of data and don't want to rerun the crawling. So I was thinking about cleaning the data I have.
Is there any handy way with dplyr to do that?
The data I got looks like the following:
```
Name message created_time id
Sam Hello World 2013-03-09T19:52:22+0000 26937808
Nicky Hello Sam 2013-03-09T19:53:16+0000 26930800
Nicky Hello Sam 2013-03-09T19:53:16+0000 26930800
Nicky Hello Sam 2013-03-09T19:53:16+0000 26930800
Sam Whats Up? 2013-03-09T19:53:22+0000 26937806
Sam Whats Up? 2013-03-09T19:53:22+0000 26937806
Florence Hi guys! 2013-03-09T19:55:16+0000 25688232
Steff How r u? 2013-03-09T19:59:16+0000 64552194
```
I would now like to have a new data frame in which every post only appears one time so that the three "double" posts from Nicky will be reduced to only one and the two double posts from Sam also get reduced to one post.
Any idea or suggestion how to do this in R? It seems like facebook is giving unique ids to posts and comments as well as that the time stamps are almost unique in my data. Both would be working for identification. However, it remains unclear to me how to best do the transformation...
Any help with this is highly appreciated!
Thanks! | 2016/06/21 | [
"https://Stackoverflow.com/questions/37945115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5223902/"
] | You just need a brief wait to wait until the `DIV` that contains the error message appears. The code below is working for me.
```
WebDriver driver = new FirefoxDriver();
driver.get("https://app.ghostinspector.com/account/create");
driver.findElement(By.id("input-firstName")).sendKeys("Johnny");
driver.findElement(By.id("input-lastName")).sendKeys("Smith");
driver.findElement(By.id("input-email")).sendKeys("abc@abc.com");
driver.findElement(By.id("input-password")).sendKeys("abc123");
driver.findElement(By.id("input-terms")).click();
driver.findElement(By.id("btn-create")).click();
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement e = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div[ng-show='errors']")));
System.out.println(e.getText());
``` | You need to implement `WebDriverWait` here to `getText()` because the `error` element already present there without any text and it fill with text when any error occurred like **E-mail address is already in use.**
So you need to wait until `error` element has some text as like below :-
```
WebDriverWait wait = new WebDriverWait(driver, 100);
String message = wait.until(new ExpectedCondition<String>() {
public String apply(WebDriver d) {
WebElement el = d.findElement(By.xpath("/html/body/div[1]/div/div/div[2]/form/div/div[1]"));
if(el.getText().length() != 0) {
return el.getText();
}
}
});
System.out.println(message);
```
**Note** :- As your `xpath` is positional which is depends on element position, it's may be fail if there wiil be some element add during action, I suggest, you can be use this `xpath` also `By.xpath("//div[@ng-show='errors']")`.
You can also use as like below :-
```
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//div[@ng-show='errors']"), "E-mail address is already in use"));
WebElement email_in_use = driver.findElement(By.xpath("//div[@ng-show='errors']"));
String message = email_in_use.getText();
```
Hope it will work....:) |
37,945,115 | I am using Rfacebook to extract some content from Facebook's API through R. I somehow get sometimes posts two or three times back even though they only appear 1 time in facebook. Probably some problem with my crawler. I extracted already a lot of data and don't want to rerun the crawling. So I was thinking about cleaning the data I have.
Is there any handy way with dplyr to do that?
The data I got looks like the following:
```
Name message created_time id
Sam Hello World 2013-03-09T19:52:22+0000 26937808
Nicky Hello Sam 2013-03-09T19:53:16+0000 26930800
Nicky Hello Sam 2013-03-09T19:53:16+0000 26930800
Nicky Hello Sam 2013-03-09T19:53:16+0000 26930800
Sam Whats Up? 2013-03-09T19:53:22+0000 26937806
Sam Whats Up? 2013-03-09T19:53:22+0000 26937806
Florence Hi guys! 2013-03-09T19:55:16+0000 25688232
Steff How r u? 2013-03-09T19:59:16+0000 64552194
```
I would now like to have a new data frame in which every post only appears one time so that the three "double" posts from Nicky will be reduced to only one and the two double posts from Sam also get reduced to one post.
Any idea or suggestion how to do this in R? It seems like facebook is giving unique ids to posts and comments as well as that the time stamps are almost unique in my data. Both would be working for identification. However, it remains unclear to me how to best do the transformation...
Any help with this is highly appreciated!
Thanks! | 2016/06/21 | [
"https://Stackoverflow.com/questions/37945115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5223902/"
] | You just need a brief wait to wait until the `DIV` that contains the error message appears. The code below is working for me.
```
WebDriver driver = new FirefoxDriver();
driver.get("https://app.ghostinspector.com/account/create");
driver.findElement(By.id("input-firstName")).sendKeys("Johnny");
driver.findElement(By.id("input-lastName")).sendKeys("Smith");
driver.findElement(By.id("input-email")).sendKeys("abc@abc.com");
driver.findElement(By.id("input-password")).sendKeys("abc123");
driver.findElement(By.id("input-terms")).click();
driver.findElement(By.id("btn-create")).click();
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement e = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div[ng-show='errors']")));
System.out.println(e.getText());
``` | Have you tried `element.getAttribute('value')` ?
[src](https://github.com/angular/protractor/issues/1794) |
17,887,757 | I am using JQuery for autocompleting the search textbox with my database. The problem rises when I want to access the text of the search textbox in query string since I am using html textbox. To make it in context, either I have to use `runat="server"` or I can use `asp:Textbox` but in both the cases my autocompleting feature stops working.
Here is the aspx code:
```
<div id="search-location-wrapper">
<input type="text" id="txtSearch" class="autosuggest" />
<div id="search-submit-container">
<asp:Button ID="btnSearch" runat="server" Text="Search"
onclick="btnSearch_Click"></asp:Button>
</div>
</div>
```
C# Code:
```
protected void btnSearch_Click(object sender, EventArgs e)
{
string location = txtSearch.ToString(); /*Here is the error: txtSearch is not in current context */
int id = Convert.ToInt32(ddlCategory.SelectedValue);
string url = "SearchResults.aspx?Id="+id+"&location="+location;
Response.Redirect(url);
}
``` | 2013/07/26 | [
"https://Stackoverflow.com/questions/17887757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/550927/"
] | In short, yes - this will standardize the dummy variables, but there's a reason for doing so. The `glmnet` function takes a matrix as an input for its `X` parameter, not a data frame, so it doesn't make the distinction for `factor` columns which you may have if the parameter was a `data.frame`. If you take a look at the R function, glmnet codes the `standardize` parameter internally as
```
isd = as.integer(standardize)
```
Which converts the R boolean to a 0 or 1 integer to feed to any of the internal FORTRAN functions (elnet, lognet, et. al.)
If you go even further by examining the FORTRAN code (fixed width - old school!), you'll see the following block:
```
subroutine standard1 (no,ni,x,y,w,isd,intr,ju,xm,xs,ym,ys,xv,jerr) 989
real x(no,ni),y(no),w(no),xm(ni),xs(ni),xv(ni) 989
integer ju(ni) 990
real, dimension (:), allocatable :: v
allocate(v(1:no),stat=jerr) 993
if(jerr.ne.0) return 994
w=w/sum(w) 994
v=sqrt(w) 995
if(intr .ne. 0)goto 10651 995
ym=0.0 995
y=v*y 996
ys=sqrt(dot_product(y,y)-dot_product(v,y)**2) 996
y=y/ys 997
10660 do 10661 j=1,ni 997
if(ju(j).eq.0)goto 10661 997
xm(j)=0.0 997
x(:,j)=v*x(:,j) 998
xv(j)=dot_product(x(:,j),x(:,j)) 999
if(isd .eq. 0)goto 10681 999
xbq=dot_product(v,x(:,j))**2 999
vc=xv(j)-xbq 1000
xs(j)=sqrt(vc) 1000
x(:,j)=x(:,j)/xs(j) 1000
xv(j)=1.0+xbq/vc 1001
goto 10691 1002
```
Take a look at the lines marked 1000 - this is basically applying the standardization formula to the `X` matrix.
Now statistically speaking, one does not generally standardize categorical variables to retain the interpretability of the estimated regressors. However, as pointed out by Tibshirani [here](http://statweb.stanford.edu/~tibs/lasso/fulltext.pdf), "The lasso method requires initial standardization of the regressors, so that the penalization scheme is fair to all regressors. For categorical regressors, one codes the regressor with dummy variables and then standardizes the dummy variables" - so while this causes arbitrary scaling between continuous and categorical variables, it's done for equal penalization treatment. | `glmnet` doesn't know anything about dummy variables, because it doesn't have a formula interface (and hence doesn't touch `model.frame` and `model.matrix`.) If you want them to be treated specially, you'll have to do it yourself. |
13,376,682 | I have a BizTalk 2010 project containing an orchestration that needs to make an HTTP Post and then examine the Status Code and Body of the Response to determine the next course of action.
I can configure the orchestration and port to make the HTTP Post, but I am unable to receive a response.
Should I be using a send / receive port or correlation?
What schema should I be using for the response (I believe the response is the standard http response: <http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6>). | 2012/11/14 | [
"https://Stackoverflow.com/questions/13376682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1823305/"
] | If you are looking for a kind of notification ( not in content of the message) that the message has been successfully transmitted, you can set the logical send port property in the orchestration as follows:
```
"Delivery Notification" = Transmitted
```
And delivery failures can be handled using the Microsoft.XLANGs.BaseTypes.DeliveryFailureException | The Http Status Code should be available on the Response message as a Context Property, which you can access in an Expression shape.
```
statusCode = ResponseMessage(HTTP.ResponseStatusCode);
```
Your ResponseMessage should be of type System.Xml.XmlDocument, but as it won't be a real Xml Document, make sure the Request/Response port is configured to use the PassThruReceive pipeline on the Response side. |