问:
create fixed size List of non-repeating permutations from list of elements
I have a list of objects M := [A, B, C, ... Z] and I want to create a new list N containing non-repeating fixed size "f" permutations of these objects.

So N would be (for f = 2) [[A, B], [A, C], ...] but should not contain repetitions like [A, A] and if [A, B] is set [B, A] should be ignored.

I have found things like Guavas "PowerSet" but this wont help me as it can not be "cropped" to a fixed size.

I hope i have stated my problem correctly.

f should always be 2

Based on http://algorithms.tutorialhorizon.com/print-all-combinations-of-subset-of-size-k-from-given-array/ i've done the following:

```<code>private Set<List<Object>> combineObjects(List<Object> M) {
    boolean[] used = new boolean[M.size()];
    return generateObjectCombinations(M, 0, 0, used);
}

private Set<List<Object>> generateObjectCombinations(
    List<Object> M,
    int start,
    int curLen,
    boolean[] used
) {
    Set<List<Object>> returnSet = new HashSet<>();
    if (curLen == 2) {
        List<Object> data = newArrayList();
        for (int i = 0; i < M.size(); i++) {
            if (used[i]) {
                data.add(M.get(i));
            }
        }
        returnSet.add(data);
        return returnSet;
    }
    if (start == M.size()) {
        return Collections.emptySet();
    }
    used[start] = true;
    returnSet.addAll(generateObjectCombinations(M, start + 1, curLen + 1, used));
    used[start] = false;
    returnSet.addAll(generateObjectCombinations(M, start + 1, curLen, used));
    return returnSet;
}
</code>```

It is working but I wonder if there is a "cleaner" solution. I want to eliminate the bool-array.

And no, it's not my homework. Maybe i am just to tired and should take vacation.

EDIT
Based on @azro's answer i restructured the code like this:

```<code>List<List<Object>> combinations = new ArrayList<>();
List<Object> M = new ArrayList<>();

for (int i = 0; i < M.size(); i++) {
    Object outerM = M.get(i);

    for (int j = i; j < M.size(); j++) {
        Object innerM = M.get(j);
        if (innerM.equals(outerM)) {
            continue;
        }
        combinations.add(Lists.newArrayList(outerM, innerM));
    }
}
</code>```

or even better

```<code>List<List<Object>> combinations = new ArrayList<>();
List<Object> M = new ArrayList<>();

for (int i = 0; i < M.size(); i++) {
    Object outerM = M.get(i);

    for (int j = (i + 1); j < M.size(); j++) {
        Object innerM = M.get(j);
        combinations.add(Lists.newArrayList(outerM, innerM));
    }
}
</code>```

I should really take a loooong vacation. Thanks @azro!!

答:
I'm not sure if it's the best solution but here you are:

```<code>static HashSet<HashSet<String>> getCombinations(HashSet<HashSet<String>> s, int f)
{
    if(f == 1)
        return s;
    HashSet<HashSet<String>> newSet = new HashSet<HashSet<String>>();
    for (HashSet<String> ss : s)
    {
        for(String elm : A)
        {
            if(ss.contains(elm))
                continue;
            HashSet<String> sss = (HashSet<String>)ss.clone();
            sss.add(elm);
            newSet.add(sss);
        }
    }
    return getCombinations(newSet, f-1);
}
</code>```

Usage:

```<code>String[] A = {"A", "B", "C", "D", "E"};
public static void main(String[] args)
{
    int f = 3;
    HashSet<HashSet<String>> set = new HashSet<>();
    for(String s : A)
    {
        HashSet<String> ss = new HashSet<>();
        ss.add(s);
        set.add(ss);
    }
    System.out.println(getCombinations(set, f));
}
</code>```

Body:
I have a list of objects M := [A, B, C, ... Z] and I want to create a new list N containing non-repeating fixed size "f" permutations of these objects.

So N would be (for f = 2) [[A, B], [A, C], ...] but should not contain repetitions like [A, A] and if [A, B] is set [B, A] should be ignored.

I have found things like Guavas "PowerSet" but this wont help me as it can not be "cropped" to a fixed size.

I hope i have stated my problem correctly.

f should always be 2

Based on http://algorithms.tutorialhorizon.com/print-all-combinations-of-subset-of-size-k-from-given-array/ i've done the following:

private Set<List<Object>> combineObjects(List<Object> M) {
    boolean[] used = new boolean[M.size()];
    return generateObjectCombinations(M, 0, 0, used);
}

private Set<List<Object>> generateObjectCombinations(
    List<Object> M,
    int start,
    int curLen,
    boolean[] used
) {
    Set<List<Object>> returnSet = new HashSet<>();
    if (curLen == 2) {
        List<Object> data = newArrayList();
        for (int i = 0; i < M.size(); i++) {
            if (used[i]) {
                data.add(M.get(i));
            }
        }
        returnSet.add(data);
        return returnSet;
    }
    if (start == M.size()) {
        return Collections.emptySet();
    }
    used[start] = true;
    returnSet.addAll(generateObjectCombinations(M, start + 1, curLen + 1, used));
    used[start] = false;
    returnSet.addAll(generateObjectCombinations(M, start + 1, curLen, used));
    return returnSet;
}

It is working but I wonder if there is a "cleaner" solution. I want to eliminate the bool-array.

And no, it's not my homework. Maybe i am just to tired and should take vacation.

EDIT
Based on @azro's answer i restructured the code like this:

List<List<Object>> combinations = new ArrayList<>();
List<Object> M = new ArrayList<>();

for (int i = 0; i < M.size(); i++) {
    Object outerM = M.get(i);

    for (int j = i; j < M.size(); j++) {
        Object innerM = M.get(j);
        if (innerM.equals(outerM)) {
            continue;
        }
        combinations.add(Lists.newArrayList(outerM, innerM));
    }
}

or even better

List<List<Object>> combinations = new ArrayList<>();
List<Object> M = new ArrayList<>();

for (int i = 0; i < M.size(); i++) {
    Object outerM = M.get(i);

    for (int j = (i + 1); j < M.size(); j++) {
        Object innerM = M.get(j);
        combinations.add(Lists.newArrayList(outerM, innerM));
    }
}

I should really take a loooong vacation. Thanks @azro!!

Body:
I'm not sure if it's the best solution but here you are:

static HashSet<HashSet<String>> getCombinations(HashSet<HashSet<String>> s, int f)
{
    if(f == 1)
        return s;
    HashSet<HashSet<String>> newSet = new HashSet<HashSet<String>>();
    for (HashSet<String> ss : s)
    {
        for(String elm : A)
        {
            if(ss.contains(elm))
                continue;
            HashSet<String> sss = (HashSet<String>)ss.clone();
            sss.add(elm);
            newSet.add(sss);
        }
    }
    return getCombinations(newSet, f-1);
}

Usage:

String[] A = {"A", "B", "C", "D", "E"};
public static void main(String[] args)
{
    int f = 3;
    HashSet<HashSet<String>> set = new HashSet<>();
    for(String s : A)
    {
        HashSet<String> ss = new HashSet<>();
        ss.add(s);
        set.add(ss);
    }
    System.out.println(getCombinations(set, f));
}


来源: stackexchange

问:
sqlcmd runs fine and cmd line but will not produce output as a exec cmd step in a SQL Agent job
I am pulling my hair out and have tried every posting suggest.

I have a tsql script called C:\DBAReports\testsql.sql.  If I go to a command logged prompt on my server, and run: sqlcmd -S localhost -i C:\DBAReports\testsql.sql -o C:\DBAReports\testout.txt

But if I create an new agent job with 1 step of type Operating system (CmdExec) to run as a SQL Server Agent Service Account, On Success Quit the job reporting success and on Failure Quit the job reporting failure. with the owner my same admin windows login as when I run the cmd prompt, right click on the agent job and start at step 1, I get the job succeeded (Job was invoked by my windows login), and the Step 1 is Executed as user is-sql "The step did not generate any output.  Process Exit Code 0.  The step was successful".

But it doesn't write the output file.

Any ideas?

The reason I want to do this is I am getting periodic Error: 18057, Severity: 20, State: 2 Failed to set up execution content in my sql server log.  What I hope to do is kick off this job when this occurs to try and find out what are the SPIDs, status, SQL running, etc and write it to an output file.

My testsql.sql script contains.

```<code>SELECT
    SPID                = er.session_id
    ,STATUS             = ses.STATUS
    ,[Login]            = ses.login_name
    ,Host               = ses.host_name
    ,BlkBy              = er.blocking_session_id
    ,DBName             = DB_Name(er.database_id)
,CommandType        = er.command
,SQLStatement       = st.text
,ObjectName         = OBJECT_NAME(st.objectid)
,ElapsedMS          = er.total_elapsed_time
,CPUTime            = er.cpu_time
,IOReads            = er.logical_reads + er.reads
,IOWrites           = er.writes
,LastWaitType       = er.last_wait_type
,StartTime          = er.start_time
,Protocol           = con.net_transport
,ConnectionWrites   = con.num_writes
,ConnectionReads    = con.num_reads
,ClientAddress      = con.client_net_address
,Authentication     = con.auth_scheme
FROM sys.dm_exec_requests er
OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) st
LEFT JOIN sys.dm_exec_sessions ses
ON ses.session_id = er.session_id
LEFT JOIN sys.dm_exec_connections con
ON con.session_id = ses.session_id
</code>```

Thanks in advance for any help.  I have tried so many suggestions, and either get syntax errors on the command, and when I don't get any syntax error on the sqlcmd, it just generates no output.

答:
An alternate way - try modifying the job step as Type: T-SQL script and the command as:

```<code>EXEC master..xp_CMDShell 'C:\Work\temp\test3.bat'
</code>```

Please replace the bat file path with yours.

ContentLicense: CC BY-SA 3.0

Body:
I am pulling my hair out and have tried every posting suggest.

I have a tsql script called C:\DBAReports\testsql.sql.  If I go to a command logged prompt on my server, and run: sqlcmd -S localhost -i C:\DBAReports\testsql.sql -o C:\DBAReports\testout.txt

But if I create an new agent job with 1 step of type Operating system (CmdExec) to run as a SQL Server Agent Service Account, On Success Quit the job reporting success and on Failure Quit the job reporting failure. with the owner my same admin windows login as when I run the cmd prompt, right click on the agent job and start at step 1, I get the job succeeded (Job was invoked by my windows login), and the Step 1 is Executed as user is-sql "The step did not generate any output.  Process Exit Code 0.  The step was successful".

But it doesn't write the output file.

Any ideas?

The reason I want to do this is I am getting periodic Error: 18057, Severity: 20, State: 2 Failed to set up execution content in my sql server log.  What I hope to do is kick off this job when this occurs to try and find out what are the SPIDs, status, SQL running, etc and write it to an output file.

My testsql.sql script contains.

SELECT
    SPID                = er.session_id
    ,STATUS             = ses.STATUS
    ,[Login]            = ses.login_name
    ,Host               = ses.host_name
    ,BlkBy              = er.blocking_session_id
    ,DBName             = DB_Name(er.database_id)
,CommandType        = er.command
,SQLStatement       = st.text
,ObjectName         = OBJECT_NAME(st.objectid)
,ElapsedMS          = er.total_elapsed_time
,CPUTime            = er.cpu_time
,IOReads            = er.logical_reads + er.reads
,IOWrites           = er.writes
,LastWaitType       = er.last_wait_type
,StartTime          = er.start_time
,Protocol           = con.net_transport
,ConnectionWrites   = con.num_writes
,ConnectionReads    = con.num_reads
,ClientAddress      = con.client_net_address
,Authentication     = con.auth_scheme
FROM sys.dm_exec_requests er
OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) st
LEFT JOIN sys.dm_exec_sessions ses
ON ses.session_id = er.session_id
LEFT JOIN sys.dm_exec_connections con
ON con.session_id = ses.session_id

Thanks in advance for any help.  I have tried so many suggestions, and either get syntax errors on the command, and when I don't get any syntax error on the sqlcmd, it just generates no output.

Body:
An alternate way - try modifying the job step as Type: T-SQL script and the command as:

EXEC master..xp_CMDShell 'C:\Work\temp\test3.bat'

Please replace the bat file path with yours.


问:
Android instance app feature module fails to find a layout resource in the same module
I have the following project structure which I want to convert to a instant apps. The installed project works fine, but when I want to runt the instant app version, the base feature module loads perfectly, but when it comes to the feature module, then it fails to find the resources from its module. When I move the resources from feature module to base module, then it recognizes them with the full package name of the base feature module.

The project structure is the following:
 - app module
 - instant app module

 - base feature module  - com.app.base.feature
 - feature module       - com.app.feature.

in feature module when the resource is located in feature module itself the resources are not found, but they are found when I move the resource into the base feature module and reference them as following com.app.base.feature.R.layout.sample_layout.

EDIT: No known package when getting value for resource number 0x80060009.

Any kind of help would be appreciated :)

答:
It is actually a bug of the canary version.
We already discussed it here: stackoverflow question

We opened a bug on the official Android Studio tracker in which I provided more informations: bug tracker

Please do not hesitate to star it to make Google prioritize the fix (currently P2).

With further experimentation I noticed that:
So if we have a project with 4 modules:

```<code>base
f1
f2
f3
</code>```

f3 instant module (the last one in alphabetical order) will works correctly and will link all of its own resources correctly.
f1 and f2, on the other hand, will use resources from f3 module instead of their own and hence either they crash or their layout / images / strings got really messed up.

Finally problem occurs only for resources to resources references trough XML (i.e. reference a drawable from a layout or establish a constraint between two elements of a layout).
Hence:

<ImageView android:src="@drawable/icon"/>  --> will shows the
problem

But in java image.setDrawable(R.drawable.icon) --> will work
correctly

ALSO, concerning your EDIT 1:
there is a second bug that I also reported in a second tracker here: bug tracker. In this case if you add a  XML tag in your layout or a fragment that use an  XML TAG in their layout. Instant app will crash. Please star the bug if you find out this is also the cause for you.

Body:
It is actually a bug of the canary version.
We already discussed it here: stackoverflow question

We opened a bug on the official Android Studio tracker in which I provided more informations: bug tracker

Please do not hesitate to star it to make Google prioritize the fix (currently P2).

With further experimentation I noticed that:
So if we have a project with 4 modules:

base
f1
f2
f3

f3 instant module (the last one in alphabetical order) will works correctly and will link all of its own resources correctly.
f1 and f2, on the other hand, will use resources from f3 module instead of their own and hence either they crash or their layout / images / strings got really messed up.

Finally problem occurs only for resources to resources references trough XML (i.e. reference a drawable from a layout or establish a constraint between two elements of a layout).
Hence:

<ImageView android:src="@drawable/icon"/>  --> will shows the
problem

But in java image.setDrawable(R.drawable.icon) --> will work
correctly

ALSO, concerning your EDIT 1:
there is a second bug that I also reported in a second tracker here: bug tracker. In this case if you add a  XML tag in your layout or a fragment that use an  XML TAG in their layout. Instant app will crash. Please star the bug if you find out this is also the cause for you.


问:
How insert with no duplicates?
I'm trying to insert some records in my product table, I need to insert products where are no repeating model code, I use the query:

```<code>INSERT IGNORE INTO erp_product
  (erp_model, erp_ean, erp_cstid, erp_quantity,
  erp_brand_erp_brandid, erp_price, erp_cost,
  erp_weight, erp_lenght, erp_width, erp_height,
  erp_status, erp_distributor, erp_registerdate)
VALUES(
       '020-113_24','7897712061589',1,0,
       '1','22.85','17.58',
       '0.03','13','14','5',
       0,'OP','06/07/2017 10:32:47');
</code>```

I need use WHERE NOT IN or WHERE NOT EXISTS? What is the difference?
The insert not works, any suggestion? Thanks in advance!

答:
I need to insert products where are no repeating model code

Well then why not define a UNIQUE constraint on erp_model column. like

```<code>ALTER TABLE erp_product ADD CONSTRAINT constr_unq UNIQUE (erp_model)
</code>```

Title: How insert with no duplicates?

Body:
I'm trying to insert some records in my product table, I need to insert products where are no repeating model code, I use the query:

INSERT IGNORE INTO erp_product
  (erp_model, erp_ean, erp_cstid, erp_quantity,
  erp_brand_erp_brandid, erp_price, erp_cost,
  erp_weight, erp_lenght, erp_width, erp_height,
  erp_status, erp_distributor, erp_registerdate)
VALUES(
       '020-113_24','7897712061589',1,0,
       '1','22.85','17.58',
       '0.03','13','14','5',
       0,'OP','06/07/2017 10:32:47');

I need use WHERE NOT IN or WHERE NOT EXISTS? What is the difference?
The insert not works, any suggestion? Thanks in advance!

Body:
I need to insert products where are no repeating model code

Well then why not define a UNIQUE constraint on erp_model column. like

ALTER TABLE erp_product ADD CONSTRAINT constr_unq UNIQUE (erp_model)


问:
Processing huge CSV file using Python and multithreading
I have a function that yields lines from a huge CSV file lazily:

```<code>def get_next_line():
    with open(sample_csv,'r') as f:
        for line in f:
            yield line

def do_long_operation(row):
    print('Do some operation that takes a long time')
</code>```

I need to use threads such that each record I get from the above function I can call do_long_operation.

Most places on Internet have examples like this, and I am not very sure if I am on the right path.

```<code>import threading
thread_list = []
for i in range(8):
   t = threading.Thread(target=do_long_operation, args=(get_next_row from get_next_line))
   thread_list.append(t)

for thread in thread_list:
    thread.start()

for thread in thread_list:
    thread.join()
</code>```

My questions are:

How do I start only a finite number of threads, say 8?

How do I make sure that each of the threads will get a row from get_next_line?

答:
You could use a thread pool from multiprocessing and map your tasks to a pool of workers:

```<code>from multiprocessing.pool import ThreadPool as Pool
# from multiprocessing import Pool
from random import randint
from time import sleep

def process_line(l):
    print l, "started"
    sleep(randint(0, 3))
    print l, "done"

def get_next_line():
    with open("sample.csv", 'r') as f:
        for line in f:
            yield line

f = get_next_line()

t = Pool(processes=8)

for i in f:
    t.map(process_line, (i,))
t.close()
t.join()
</code>```

This will create eight workers and submit your lines to them, one by one. As soon as a process is "free", it will be allocated a new task.

There is a commented out import statement, too. If you comment out the ThreadPool and import Pool from multiprocessing instead, you will get subprocesses instead of threads, which may be more efficient in your case.

ContentLicense: CC BY-SA 4.0

Body:
I have a function that yields lines from a huge CSV file lazily:

def get_next_line():
    with open(sample_csv,'r') as f:
        for line in f:
            yield line

def do_long_operation(row):
    print('Do some operation that takes a long time')

I need to use threads such that each record I get from the above function I can call do_long_operation.

Most places on Internet have examples like this, and I am not very sure if I am on the right path.

import threading
thread_list = []
for i in range(8):
   t = threading.Thread(target=do_long_operation, args=(get_next_row from get_next_line))
   thread_list.append(t)

for thread in thread_list:
    thread.start()

for thread in thread_list:
    thread.join()

My questions are:

How do I start only a finite number of threads, say 8?

How do I make sure that each of the threads will get a row from get_next_line?

Body:
You could use a thread pool from multiprocessing and map your tasks to a pool of workers:

from multiprocessing.pool import ThreadPool as Pool
# from multiprocessing import Pool
from random import randint
from time import sleep

def process_line(l):
    print l, "started"
    sleep(randint(0, 3))
    print l, "done"

def get_next_line():
    with open("sample.csv", 'r') as f:
        for line in f:
            yield line

f = get_next_line()

t = Pool(processes=8)

for i in f:
    t.map(process_line, (i,))
t.close()
t.join()

This will create eight workers and submit your lines to them, one by one. As soon as a process is "free", it will be allocated a new task.

There is a commented out import statement, too. If you comment out the ThreadPool and import Pool from multiprocessing instead, you will get subprocesses instead of threads, which may be more efficient in your case.


问:
adding column values in one dataset from another dataset in R based on condition - different length
I have two data sets. One has duplicate location names, another one has location name and its lat long. I want to add lat long to first data set where the location name matches in second data set.

df1

```<code> Code   Station Name
 BNC    BANGALORE CANT
 BNC    BANGALORE CANT
 BNC    BANGALORE CANT
 BBS    BHUBANESWAR
 BBS    BHUBANESWAR
</code>```

df2

```<code>Station Name     lat       lon
BANGALORE CANT  12.993690  77.59814
BHUBANESWAR     20.296059  85.82454
</code>```

expected result
df1

```<code> Code   Station Name        lat        lon
 BNC    BANGALORE CANT     12.993690  77.59814
 BNC    BANGALORE CANT     12.993690  77.59814
 BNC    BANGALORE CANT     12.993690  77.59814
 BBS    BHUBANESWAR        20.296059  85.82454
 BBS    BHUBANESWAR        20.296059  85.82454
</code>```

It is obvious that object length differs. And I need the df1 duplicate entry. cbind won't work as length differs. same for ifelse and if with sapply. Getting lat long for df1 using geocode fails as the list is long (query max exceeded).  Any thoughts?

答:
It looks like a SQL problem. So in R the library dplyr is the best choice.
Here a working example, the name of the column has to be equal for the join

```<code>library(dplyr)
iris
iris2<-data.frame("Species"=unique(iris$Species),"n"=c(1,2,3))
iris %>% inner_join(iris2)
</code>```

PS you can share your db use dput(dataframename) command, It is really easier  to help with relevant examples

Body:
I have two data sets. One has duplicate location names, another one has location name and its lat long. I want to add lat long to first data set where the location name matches in second data set.

df1

 Code   Station Name
 BNC    BANGALORE CANT
 BNC    BANGALORE CANT
 BNC    BANGALORE CANT
 BBS    BHUBANESWAR
 BBS    BHUBANESWAR

df2

Station Name     lat       lon
BANGALORE CANT  12.993690  77.59814
BHUBANESWAR     20.296059  85.82454

expected result
df1

 Code   Station Name        lat        lon
 BNC    BANGALORE CANT     12.993690  77.59814
 BNC    BANGALORE CANT     12.993690  77.59814
 BNC    BANGALORE CANT     12.993690  77.59814
 BBS    BHUBANESWAR        20.296059  85.82454
 BBS    BHUBANESWAR        20.296059  85.82454

It is obvious that object length differs. And I need the df1 duplicate entry. cbind won't work as length differs. same for ifelse and if with sapply. Getting lat long for df1 using geocode fails as the list is long (query max exceeded).  Any thoughts?

Body:
It looks like a SQL problem. So in R the library dplyr is the best choice.
Here a working example, the name of the column has to be equal for the join

library(dplyr)
iris
iris2<-data.frame("Species"=unique(iris$Species),"n"=c(1,2,3))
iris %>% inner_join(iris2)

PS you can share your db use dput(dataframename) command, It is really easier  to help with relevant examples


问:
shell script to get year, date and month from YYYY-MM-DD format
I am running a shell script which accepts date in "YYYY-MM-DD" format. from this date input, how can i get year, month and day separately?

Thanks for replies in advance.

答:
I didn't want to use date command, so I got the following code. It uses awk, which I feel is more appropriate for this task. I assumed you want to store results in variables.

```<code>inputDate=2017-07-06

year=`echo $inputDate | awk -F\- '{print $1}'`
month=`echo $inputDate | awk -F\- '{print $2}'`
day=`echo $inputDate | awk -F\- '{print $3}'`
</code>```

Body:
I didn't want to use date command, so I got the following code. It uses awk, which I feel is more appropriate for this task. I assumed you want to store results in variables.

inputDate=2017-07-06

year=`echo $inputDate | awk -F\- '{print $1}'`
month=`echo $inputDate | awk -F\- '{print $2}'`
day=`echo $inputDate | awk -F\- '{print $3}'`


问:
python : the selenium webscraping script not working through module
whenever I am running the following script through shell its working but whenever i am running the same script through python module or pycharm its not working, its not fetching the data. Can anyone please help in that ?</p>

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser = webdriver.Firefox()
site = browser.get("https://www.flipkart.com/")
searchInput = browser.find_element_by_class_name("LM6RPg")
searchInput.send_keys('Laptop')
searchInput.send_keys(Keys.ENTER)
titleResults = browser.find_elements_by_xpath("//div[@class='_3wU53n']")
for title in titleResults:
    print(title.text)
</code>```

答:
You should set implicitly_wait after browser = webdriver.Firefox() because when you run in shell the page will have time to load completely and when you run it like a module you are not waiting for the page to load at all so it should be:

```<code>browser = webdriver.Firefox()
browser.implicitly_wait(10)
</code>```

This will wait for a maximum of 10 seconds to find the element before an exception will be thrown.

Alternatives are:

```<code>browser.explicitly_wait(10)
</code>```

which will wait 10 seconds and after that it will search the element

or

```<code>sleep(5)
</code>```

before searching for element after clicking a button. You can adjust the the seconds to see which fits. And don't forget to import sleep from time module : from time import sleep

Let me know if this helps you.

Body:
whenever I am running the following script through shell its working but whenever i am running the same script through python module or pycharm its not working, its not fetching the data. Can anyone please help in that ?

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser = webdriver.Firefox()
site = browser.get("https://www.flipkart.com/")
searchInput = browser.find_element_by_class_name("LM6RPg")
searchInput.send_keys('Laptop')
searchInput.send_keys(Keys.ENTER)
titleResults = browser.find_elements_by_xpath("//div[@class='_3wU53n']")
for title in titleResults:
    print(title.text)

Body:
You should set implicitly_wait after browser = webdriver.Firefox() because when you run in shell the page will have time to load completely and when you run it like a module you are not waiting for the page to load at all so it should be:

browser = webdriver.Firefox()
browser.implicitly_wait(10)

This will wait for a maximum of 10 seconds to find the element before an exception will be thrown.

Alternatives are:

browser.explicitly_wait(10)

which will wait 10 seconds and after that it will search the element

or

sleep(5)

before searching for element after clicking a button. You can adjust the the seconds to see which fits. And don't forget to import sleep from time module : from time import sleep

Let me know if this helps you.


问:
How to do concat or group by in linq? I am getting multiples values want to concat the data by ','
my Query:

```<code>var s = entities.Doctors.SingleOrDefault(x => x.AreaId == id);
                    var z = (from x in entities.Doctors
                             join y in entities.Areas on x.AreaId equals y.AreaId
                             join s1 in entities.Availabilties on s.D_Id equals s1.DoctorId
                             join s2 in entities.Eductions on s.D_Id equals s2.DoctorId
                             join s3 in entities.DoctorSpecialities on s.D_Id equals s3.DoctorId
                             join s4 in entities.Specialities on s3.SpecialityId equals s4.SpecialityId
                             join s5 in entities.DaysDetails on s1.DaysId equals s5.DaysId
                             join s6 in entities.Degrees on s2.DegreeId equals s6.DegreeId
                             where x.AreaId.Equals(id)
                             select new DoctorDisplay
                             {
                                 D_name = x.D_Name,
                                 D_address = x.D_Address,
                                 D_Area = y.AreaName,
                                 D_Contact1 = x.D_Contactone,
                                 D_Contact2 = x.D_Contacttwo,
                                 D_fax = x.D_Faxno,
                                 D_SpecialityName = s4.SpecialityName,
                                 D_Availstarttime = s1.StartTime,
                                 D_Availlasttime = s1.LastTime,
                                 D_Availday= s5.DaysName,
                                 D_DegreeName = s6.DegreeName,
                                 D_Awards = x.D_Address,
                                 D_Status = x.D_Status
                              }).ToList();
</code>```

****Getting Output****

```<code>[{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Dietician","D_Availstarttime":"9PM","D_Availlasttime":"11PM","D_Availday":"Sunday","D_DegreeName":"MBBS","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Dietician","D_Availstarttime":"9PM","D_Availlasttime":"11PM","D_Availday":"Sunday","D_DegreeName":"Dentistdegree","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Ayurveda","D_Availstarttime":"9PM","D_Availlasttime":"11PM","D_Availday":"Sunday","D_DegreeName":"MBBS","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Ayurveda","D_Availstarttime":"9PM","D_Availlasttime":"11PM","D_Availday":"Sunday","D_DegreeName":"Dentistdegree","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Dietician","D_Availstarttime":"4AM","D_Availlasttime":"11AM","D_Availday":"Monday","D_DegreeName":"MBBS","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Dietician","D_Availstarttime":"4AM","D_Availlasttime":"11AM","D_Availday":"Monday","D_DegreeName":"Dentistdegree","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Ayurveda","D_Availstarttime":"4AM","D_Availlasttime":"11AM","D_Availday":"Monday","D_DegreeName":"MBBS","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Ayurveda","D_Availstarttime":"4AM","D_Availlasttime":"11AM","D_Availday":"Monday","D_DegreeName":"Dentistdegree","D_Awards":"block123","D_Status":"Available"}]
</code>```

Group_concat on the basis of Education Id, DoctorspecialitiesID, Avaibilities Id,
Image of Input and desire Output

答:
Looking at you example output, it looks less like you want to "concat the data by ','" as much as you want to convert it to JSON.

Inwhichcase, you'd probably be better off using a tool like Newtonsoft's JSON.NET

UPDATE (based on comments):
Assume doctors is the result of the query given in question.

```<code>var output =
    from d in doctors
     group d by new { d.D_NAME, d.D_Area } into dg
     select new DoctorDisplay
     {
        D_NAME = dg.Key.D_NAME,
        D_Area = dg.Key.D_Area,
        D_SpecialityName = String.Join(",", dg.Select(d => d.D_SpecialityName).Distinct()),
        D_DegreeName = String.Join(",", dg.Select(d => d.D_DegreeName).Distinct())
    };
</code>```

Body:
my Query:

var s = entities.Doctors.SingleOrDefault(x => x.AreaId == id);
                    var z = (from x in entities.Doctors
                             join y in entities.Areas on x.AreaId equals y.AreaId
                             join s1 in entities.Availabilties on s.D_Id equals s1.DoctorId
                             join s2 in entities.Eductions on s.D_Id equals s2.DoctorId
                             join s3 in entities.DoctorSpecialities on s.D_Id equals s3.DoctorId
                             join s4 in entities.Specialities on s3.SpecialityId equals s4.SpecialityId
                             join s5 in entities.DaysDetails on s1.DaysId equals s5.DaysId
                             join s6 in entities.Degrees on s2.DegreeId equals s6.DegreeId
                             where x.AreaId.Equals(id)
                             select new DoctorDisplay
                             {
                                 D_name = x.D_Name,
                                 D_address = x.D_Address,
                                 D_Area = y.AreaName,
                                 D_Contact1 = x.D_Contactone,
                                 D_Contact2 = x.D_Contacttwo,
                                 D_fax = x.D_Faxno,
                                 D_SpecialityName = s4.SpecialityName,
                                 D_Availstarttime = s1.StartTime,
                                 D_Availlasttime = s1.LastTime,
                                 D_Availday= s5.DaysName,
                                 D_DegreeName = s6.DegreeName,
                                 D_Awards = x.D_Address,
                                 D_Status = x.D_Status
                              }).ToList();

****Getting Output****

[{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Dietician","D_Availstarttime":"9PM","D_Availlasttime":"11PM","D_Availday":"Sunday","D_DegreeName":"MBBS","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Dietician","D_Availstarttime":"9PM","D_Availlasttime":"11PM","D_Availday":"Sunday","D_DegreeName":"Dentistdegree","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Ayurveda","D_Availstarttime":"9PM","D_Availlasttime":"11PM","D_Availday":"Sunday","D_DegreeName":"MBBS","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Ayurveda","D_Availstarttime":"9PM","D_Availlasttime":"11PM","D_Availday":"Sunday","D_DegreeName":"Dentistdegree","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Dietician","D_Availstarttime":"4AM","D_Availlasttime":"11AM","D_Availday":"Monday","D_DegreeName":"MBBS","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Dietician","D_Availstarttime":"4AM","D_Availlasttime":"11AM","D_Availday":"Monday","D_DegreeName":"Dentistdegree","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Ayurveda","D_Availstarttime":"4AM","D_Availlasttime":"11AM","D_Availday":"Monday","D_DegreeName":"MBBS","D_Awards":"block123","D_Status":"Available"},{"D_name":"Shanu","D_address":"block123","D_Area":"Manama","D_Contact1":"123","D_Contact2":"456","D_fax":"789","D_SpecialityName":"Ayurveda","D_Availstarttime":"4AM","D_Availlasttime":"11AM","D_Availday":"Monday","D_DegreeName":"Dentistdegree","D_Awards":"block123","D_Status":"Available"}]

Group_concat on the basis of Education Id, DoctorspecialitiesID, Avaibilities Id,
Image of Input and desire Output

Body:
Looking at you example output, it looks less like you want to "concat the data by ','" as much as you want to convert it to JSON.

Inwhichcase, you'd probably be better off using a tool like Newtonsoft's JSON.NET

UPDATE (based on comments):
Assume doctors is the result of the query given in question.

var output =
    from d in doctors
     group d by new { d.D_NAME, d.D_Area } into dg
     select new DoctorDisplay
     {
        D_NAME = dg.Key.D_NAME,
        D_Area = dg.Key.D_Area,
        D_SpecialityName = String.Join(",", dg.Select(d => d.D_SpecialityName).Distinct()),
        D_DegreeName = String.Join(",", dg.Select(d => d.D_DegreeName).Distinct())
    };


Title: Pair IP addresses in a list pulled from xlrd

Body:
I have used xlrd to pull data from a column (Data Below). I need to group together the ip addressess. So ip address that appear next together in the output belong to the same pool and single ones are in a pool of their own. For example (10.100.33.183,10.100.33.184) belong to (pool1). (Pool6 =10.100.33.89)

How do I go about achieving this all help welcome.

['', '', '', '', '', '', '', 'Pool Member IP', '', '10.100.33.184 (S56723FR6VL01)', '10.100.33.183 (S56723FR6VL02)', '', '', '', '', '', '', '', '10.101.33.182 (S56723FR6VL03)', '10.100.33.181 (S56723FR6VL04)', '', '', '', '', '', '', '', '10.100.33.180 (S56723FR6VL05)', '10.100.33.179 (S56723FR6VL06)', '', '', '', '', '', '', '', '10.100.33.178 (S56723FR6VL07)', '10.100.33.177 (S56723FR6VL08)', '', '', '', '', '', '', '', '10.100.33.90 (S56723FR6VL09)', '', '', '', '', '', '', '', '', '10.100.33.89 (S56723FR6VL0A)', '', '', '', '', '', '', '', '', '10.100.33.91 (S56723FR6VW01)', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']

Body:
May i play a bit with itertools for an answer?

test = ['', '', '', '', '', '', '', 'Pool Member IP', '', '10.100.33.184 (S56723FR6VL01)', '10.100.33.183 (S56723FR6VL02)', '', '', '', '', '', '', '', '10.101.33.182 (S56723FR6VL03)', '10.100.33.181 (S56723FR6VL04)', '', '', '', '', '', '', '', '10.100.33.180 (S56723FR6VL05)', '10.100.33.179 (S56723FR6VL06)', '', '', '', '', '', '', '', '10.100.33.178 (S56723FR6VL07)', '10.100.33.177 (S56723FR6VL08)', '', '', '', '', '', '', '', '10.100.33.90 (S56723FR6VL09)', '', '', '', '', '', '', '', '', '10.100.33.89 (S56723FR6VL0A)', '', '', '', '', '', '', '', '', '10.100.33.91 (S56723FR6VW01)', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
import itertools
def isplit(iterable,splitters):
    return [list(g) for k,g in itertools.groupby(iterable,lambda x:x in splitters) if not k]
test.remove('Pool Member IP')
pool = 0
for list in isplit(test,''):
    if len(list):
        pool+=1
    print(pool, list)

Prints out:

1 ['10.100.33.184 (S56723FR6VL01)', '10.100.33.183 (S56723FR6VL02)']
2 ['10.101.33.182 (S56723FR6VL03)', '10.100.33.181 (S56723FR6VL04)']
3 ['10.100.33.180 (S56723FR6VL05)', '10.100.33.179 (S56723FR6VL06)']
4 ['10.100.33.178 (S56723FR6VL07)', '10.100.33.177 (S56723FR6VL08)']
5 ['10.100.33.90 (S56723FR6VL09)']
6 ['10.100.33.89 (S56723FR6VL0A)']
7 ['10.100.33.91 (S56723FR6VW01)']

Kudos to Split a list into nested lists on a value and google-fu


问:
How can I hide the text box in jquery for initial loading?
I am working in this project where I face this issue. My code works when I click after loading.
I have used id for each user. This is the code for active/inactive users. I passed the id to each textbox and span. It is not working. Give some ideas on how to fix this issue.
PHP Code:

```<code>    <!--top section start-->
<?php $this->load->view("header");?>
    <div id="wrapper" style="height: auto;">
         <div class="user_intro">
            <table  width="600" height="300">
             <th style="text-align:left;">First Name</th>
             <th style="text-align:left;">Email</th>
             <th style="text-align:center;">Active Status </th>
         <?php
        foreach($result as $user)
        {?>
             <tr>
                 <td style="text-align:left;"><a href="<?php echo base_url()?>siteadmin/home/userdetail?userid=<?php echo $user->user_id; ?>"><?php echo $user->first_name;?></a></td>
                 <td style="text-align:left;"><a href="<?php echo base_url()?>siteadmin/home/userdetail?userid=<?php echo $user->user_id; ?>"><?php echo $user->email;?></a></td>
                 <?php if ($user->status == 1) { ?>
                 <td style="text-align:center;"><input type="button" id="<?php echo $user->user_id; ?>" value="" class="on" onclick="togglestyle(this,this.id)" /> </td>
                 <td><span id="reason_<?php echo $user->user_id; ?>"><input type="text" value="<?php echo $user->reason; ?>" /> </span></td>
                <?php }
                else {?>
                 <td style="text-align:center;"><input type="button" id="<?php echo $user->user_id; ?>" value="" class="off" onclick="togglestyle(this,this.id)" /> </td>
                 <td><span id="reason_<?php echo $user->user_id; ?>"><input type="text" value="<?php echo $user->reason; ?>" /> </span></td>
                 <?php } ?>
             </tr>
        <?php }
        ?>
        </table>

        </div>
    </div>

    <!--fotter section start-->

</div> <?php $this->load->view("footer"); ?>
</code>```

javascript code i have added in header file.:

```<code><script type="text/javascript">
function togglestyle(el, id) {
    if (el.className == "on") {
        $("#reason_" + id).show();
        $.ajax({
            type: "POST",
            url: "statuson",
            data: "userid=" + id,
            success: function (html) {
                if (html == 'true') {
                    el.className = "off";

                }
            },
        });
    } else {
        $("#reason_" + id).hide();
        $.ajax({
            type: "POST",
            url: "statusoff",
            data: "userid=" + id,
            success: function (html) {
                if (html == 'true') {
                    el.className = "on";
                }
            },
        });
    }
}
</script>
</code>```

答:
```<code>jQuery("input[name='multiple_location']").on('change', function () {
    if (jQuery('input[name="multiple_location"]:checked').val()=='yes') {
    jQuery("#primary_location_text").css('visibility', '');
    } else {

    jQuery("#primary_location_text").css('visibility', 'hidden');
    }
});
</code>```

Body:
I am working in this project where I face this issue. My code works when I click after loading.
I have used id for each user. This is the code for active/inactive users. I passed the id to each textbox and span. It is not working. Give some ideas on how to fix this issue.
PHP Code:

<?php $this->load->view("header");?>

             First Name
             Email
             Active Status
         <?php
        foreach($result as $user)
        {?>

                 <a href="<?php echo base_url()?>siteadmin/home/userdetail?userid=<?php echo $user->user_id; ?>"><?php echo $user->first_name;?>
                 <a href="<?php echo base_url()?>siteadmin/home/userdetail?userid=<?php echo $user->user_id; ?>"><?php echo $user->email;?>
                 <?php if ($user->status == 1) { ?>
                 <input type="button" id="<?php echo $user->user_id; ?>" value="" class="on" onclick="togglestyle(this,this.id)" />
                 <span id="reason_<?php echo $user->user_id; ?>"><input type="text" value="<?php echo $user->reason; ?>" />
                <?php }
                else {?>
                 <input type="button" id="<?php echo $user->user_id; ?>" value="" class="off" onclick="togglestyle(this,this.id)" />
                 <span id="reason_<?php echo $user->user_id; ?>"><input type="text" value="<?php echo $user->reason; ?>" />
                 <?php } ?>

        <?php }
        ?>

 <?php $this->load->view("footer"); ?>

javascript code i have added in header file.:


问:
Context.Request.Files is empty when uploading bigger files
AjaxHandler.ashx

```<code>public void ProcessRequest(HttpContext context)
{
        context.Response.ContentType = "text/plain";
        int filesCount = context.Request.Files.Count; // is empty !!!
}
</code>```

I'm using Ajax File Uploader called "RealUploader" to upload images, audio and video to Server side..

The strange thing was when sending files like images with small size all work done and correctly, but when i tried to upload bigger files like videos then
context.Request.Files was empty, i don't know Why?

Client Side Code

```<code>var uploader = new RealUploader("#targetElement", {
            accept: "video/*",
            allowedExtensions: ['mp4'],
            language: 'ar_AR',
            chunkSize: 104857600,
            maxFiles: 3,
            maxFileSize: 104857600,
            url: 'AjaxHandler.ashx',
....
....
});
</code>```

WebConfig File// to ensure accepting big files with 100MB

```<code><httpRuntime maxRequestLength="10240" executionTimeout="3600" />
<security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="104857600"  />
      </requestFiltering>
</security>
</code>```

答:
As per the docs, maxRequestLength is:

The maximum request size in kilobytes. The default size is 4096 KB (4
  MB).

If you have a value of 10240 then you have specified the limit as 10MB rather than 100MB. You should increase that number to 102400.

Body:
AjaxHandler.ashx

public void ProcessRequest(HttpContext context)
{
        context.Response.ContentType = "text/plain";
        int filesCount = context.Request.Files.Count; // is empty !!!
}

I'm using Ajax File Uploader called "RealUploader" to upload images, audio and video to Server side..

The strange thing was when sending files like images with small size all work done and correctly, but when i tried to upload bigger files like videos then
context.Request.Files was empty, i don't know Why?

Client Side Code

var uploader = new RealUploader("#targetElement", {
            accept: "video/*",
            allowedExtensions: ['mp4'],
            language: 'ar_AR',
            chunkSize: 104857600,
            maxFiles: 3,
            maxFileSize: 104857600,
            url: 'AjaxHandler.ashx',
....
....
});

WebConfig File// to ensure accepting big files with 100MB

<httpRuntime maxRequestLength="10240" executionTimeout="3600" />
<security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="104857600"  />
      </requestFiltering>
</security>


问:
How to implement class constants?
In TypeScript, the const keyword cannot be used to declare class properties. Doing so causes the compiler to an error with "A class member cannot have the 'const' keyword."

I find myself in need to clearly indicate in code that a property should not be changed.  I want the IDE or compiler to error if I attempt to assign a new value to the property once it has been declared. How do you guys achieve this?

I'm currently using a read-only property, but I wonder if there is a better way:

```<code>get MY_CONSTANT():number {return 10};
</code>```

I'm using typescript 1.8. Suggestions?

PS: I'm now using typescript 2.0.3, so I've accepted David's answer

答:
You can mark properties with readonly modifier in your declaration:

```<code>export class MyClass {
  public static readonly MY_PUBLIC_CONSTANT = 10;
  private static readonly myPrivateConstant = 5;
}
</code>```

@see TypeScript Deep Dive book - Readonly

Title: How to implement class constants?

Body:
In TypeScript, the const keyword cannot be used to declare class properties. Doing so causes the compiler to an error with "A class member cannot have the 'const' keyword."

I find myself in need to clearly indicate in code that a property should not be changed.  I want the IDE or compiler to error if I attempt to assign a new value to the property once it has been declared. How do you guys achieve this?

I'm currently using a read-only property, but I wonder if there is a better way:

get MY_CONSTANT():number {return 10};

I'm using typescript 1.8. Suggestions?

PS: I'm now using typescript 2.0.3, so I've accepted David's answer

Body:
You can mark properties with readonly modifier in your declaration:

export class MyClass {
  public static readonly MY_PUBLIC_CONSTANT = 10;
  private static readonly myPrivateConstant = 5;
}

@see TypeScript Deep Dive book - Readonly


问:
Applying CSS to Label and Input Elements Using Values in jQuery
Edit :
I am aware that their is a question mark in the jQuery, CSS and HTML. Due to it being generated automatically by Yii I cannot remove it.

Using jQuery I am attempting to add and remove styling to an input and label within my HTML. I get no response when I am trying this, I believe it is due to the abnormal for="" and/or val= values of the elements generated by Yii.

Can't seem to get it working with the if else statement. When removed it applies the CSS.

It should do as follows; select Yes, with the value "Yes", and the second label and input appear.

I have created a CodePen for this as I am having issues with JSFiddle.
https://codepen.io/CallumRocks/pen/rwrrvE

I have also included the relevant code below.

$(document).ready(function(){
    $('#event_Do_you_require_any_accessibility_assistance?').on('change',function(){
    if($(this).val() == 'Yes'){
        $("label[for='event_Please specify']").css('display', 'block');
        $("input#event_Please_specify").css('display', 'block');
    }
    else {
        $("label[for='event_Please specify']").css('display', 'none');
        $("#event_Please_specify").css('display', 'none');
    }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>label[for="event_Would you like to stay informed about updates and changes to this event?"] {
    width: 100% !important;
    line-height: 20px;
}
label[for="event_Please specify"] {
    display: none;
}
input#event_Please_specify{
    display: none;
}</code>```

  Do you require any accessibility assistance? *
  <select class="form-control user-success" required="required" name="event_Do you require any accessibility assistance?" id="event_Do_you_require_any_accessibility_assistance?">
    <option value="">Please choose</option>
    <option value="Yes">Yes</option>
    <option value="No"> No</option>
  </select>

  Please specify
  <input class="col-md-5 form-control" placeholder="Please specify" autocomplete="off" type="text" value="" name="event_Please specify" id="event_Please_specify">

```

答:
If you don't want to delete or escape the '?' in your id, you can opt for the jQuery 'starts with selector' like this:

```<code>$("[id^='event_Do_you_require_any_accessibility_assistance']")
</code>```

$(document).ready(function(){
    $("[id^='event_Do_you_require_any_accessibility_assistance']").on('change',function(){
    debugger;
    if($(this).val() == 'Yes'){
        $("label[for='event_Please specify']").css('display', 'block');
        $("input#event_Please_specify").css('display', 'block');
    }
    else {
        $("label[for='event_Please specify']").css('display', 'none');
        $("#event_Please_specify").css('display', 'none');
    }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>label[for="event_Would you like to stay informed about updates and changes to this event?"] {
    width: 100% !important;
    line-height: 20px;
}
label[for="event_Please specify"] {
    display: none;
}
input#event_Please_specify{
    display: none;
}</code>```

  Do you require any accessibility assistance? *
  <select class="form-control user-success" required="required" name="event_Do you require any accessibility assistance?" id="event_Do_you_require_any_accessibility_assistance?">
    <option value="">Please choose</option>
    <option value="Yes">Yes</option>
    <option value="No"> No</option>
  </select>

  Please specify
  <input class="col-md-5 form-control" placeholder="Please specify" autocomplete="off" type="text" value="" name="event_Please specify" id="event_Please_specify">

```

Body:
Edit :
I am aware that their is a question mark in the jQuery, CSS and HTML. Due to it being generated automatically by Yii I cannot remove it.

Using jQuery I am attempting to add and remove styling to an input and label within my HTML. I get no response when I am trying this, I believe it is due to the abnormal for="" and/or val= values of the elements generated by Yii.

Can't seem to get it working with the if else statement. When removed it applies the CSS.

It should do as follows; select Yes, with the value "Yes", and the second label and input appear.

I have created a CodePen for this as I am having issues with JSFiddle.
https://codepen.io/CallumRocks/pen/rwrrvE

I have also included the relevant code below.

$(document).ready(function(){
    $('#event_Do_you_require_any_accessibility_assistance?').on('change',function(){
    if($(this).val() == 'Yes'){
        $("label[for='event_Please specify']").css('display', 'block');
        $("input#event_Please_specify").css('display', 'block');
    }
    else {
        $("label[for='event_Please specify']").css('display', 'none');
        $("#event_Please_specify").css('display', 'none');
    }
    });
});

label[for="event_Would you like to stay informed about updates and changes to this event?"] {
    width: 100% !important;
    line-height: 20px;
}
label[for="event_Please specify"] {
    display: none;
}
input#event_Please_specify{
    display: none;
}

  Do you require any accessibility assistance? *
  <select class="form-control user-success" required="required" name="event_Do you require any accessibility assistance?" id="event_Do_you_require_any_accessibility_assistance?">
    <option value="">Please choose</option>
    <option value="Yes">Yes</option>
    <option value="No"> No</option>
  </select>

  Please specify
  <input class="col-md-5 form-control" placeholder="Please specify" autocomplete="off" type="text" value="" name="event_Please specify" id="event_Please_specify">

Body:
If you don't want to delete or escape the '?' in your id, you can opt for the jQuery 'starts with selector' like this:

$("[id^='event_Do_you_require_any_accessibility_assistance']")

$(document).ready(function(){
    $("[id^='event_Do_you_require_any_accessibility_assistance']").on('change',function(){
    debugger;
    if($(this).val() == 'Yes'){
        $("label[for='event_Please specify']").css('display', 'block');
        $("input#event_Please_specify").css('display', 'block');
    }
    else {
        $("label[for='event_Please specify']").css('display', 'none');
        $("#event_Please_specify").css('display', 'none');
    }
    });
});

label[for="event_Would you like to stay informed about updates and changes to this event?"] {
    width: 100% !important;
    line-height: 20px;
}
label[for="event_Please specify"] {
    display: none;
}
input#event_Please_specify{
    display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<div class="form-group">
  <label class="required-label required" for="event_Do you require any accessibility assistance?">Do you require any accessibility assistance? <span class="required">*</span></label>
  <select class="form-control user-success" required="required" name="event_Do you require any accessibility assistance?" id="event_Do_you_require_any_accessibility_assistance?">
    <option value="">Please choose</option>
    <option value="Yes">Yes</option>
    <option value="No"> No</option>
  </select>
</div>

<div class="form-group">
  <label for="event_Please specify">Please specify</label>
  <input class="col-md-5 form-control" placeholder="Please specify" autocomplete="off" type="text" value="" name="event_Please specify" id="event_Please_specify">
</div>


问:
Mqtt connection failed with exception 'Not authorized to connect (5)' android
Hi I am trying to connect to mqtt with my android device that I just registered but it I keep getting the error

```<code>Not authorized to connect (5)
</code>```

This is some of my code

```<code>        client = new MqttAndroidClient(context, connectionURI, clientID);
        client.setCallback(callbacks);

        String username = IOT_DEVICE_USERNAME;
        char[] password = this.getAuthorizationToken().toCharArray();

        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        options.setUserName(username);
        options.setPassword(password);

        Log.d(TAG, "Connecting to server: " + connectionURI);
        try {
            // connect
            return client.connect(options, context, listener);
        } catch (MqttException e) {
            Log.e(TAG, "Exception caught while attempting to connect to server", e.getCause());
            throw e;
        }
</code>```

where IOT_DEVICE_USERNAME is a string "use-token-auth"
and connectionUri is "tcp://<"organization">.messaging.internetofthings.ibmcloud.com:8883"

Something else that is interesting is that right before this error I get this log

```<code>Unregister alarmreceiver to MqttServiced:<"organisation">:<"DeviceType">:<"deviceId">
</code>```

Here is the stackTrace of the error

```<code>07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err: Not authorized to connect (5)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:28)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ClientState.notifyReceivedAck(ClientState.java:988)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:140)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.lang.Thread.run(Thread.java:818)
</code>```

答:
I found this error:

Token auth failed (Device/gateway not found in database): ClientID='d:4rxa4d:AndroidDevice:1c39476b8dd0'

Have you created a device type for AndroidDevice and registered the ID 1c39476b8dd0 to your org in the Watson IoT Platform?

This tutorial shows how to register devices.

Body:
Hi I am trying to connect to mqtt with my android device that I just registered but it I keep getting the error

Not authorized to connect (5)

This is some of my code

        client = new MqttAndroidClient(context, connectionURI, clientID);
        client.setCallback(callbacks);

        String username = IOT_DEVICE_USERNAME;
        char[] password = this.getAuthorizationToken().toCharArray();

        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        options.setUserName(username);
        options.setPassword(password);

        Log.d(TAG, "Connecting to server: " + connectionURI);
        try {
            // connect
            return client.connect(options, context, listener);
        } catch (MqttException e) {
            Log.e(TAG, "Exception caught while attempting to connect to server", e.getCause());
            throw e;
        }

where IOT_DEVICE_USERNAME is a string "use-token-auth"
and connectionUri is "tcp://<"organization">.messaging.internetofthings.ibmcloud.com:8883"

Something else that is interesting is that right before this error I get this log

Unregister alarmreceiver to MqttServiced:<"organisation">:<"DeviceType">:<"deviceId">

Here is the stackTrace of the error

07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err: Not authorized to connect (5)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:28)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at org.eclipse.paho.client.mqttv3.internal.ClientState.notifyReceivedAck(ClientState.java:988)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:140)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:152)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:265)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-06 12:27:24.214 9009-9009/wibicom.wibeacon3 W/System.err:     at java.lang.Thread.run(Thread.java:818)


问:
how to recode (and reverse code) variables in columns with dplyr
I am picking up R again after last using it in 2013. I am getting used to using dplyr, but I am running into a problem with a simple task.
I  have a table that looks like

```<code>Participant Q1       Q2      Q3     Q4       Q5
1           agree  neutral   NA    Disagree  Agree
2           neutral agree    NA     NA       NA
</code>```

My goal

```<code>   Participant Q1       Q2      Q3     Q4       Q5
    1           3       2       NA      1       3
    2           2       1       NA     NA       NA
</code>```

I want to be able to change the categorical value to a numerical value for columns Q1:Q5, but all the examples that I see of using recode for dplyr work for rows and no columns. (I might be missing something in the examples). I then want to be able to pick column Q1 and Q2 and reverse code it.

I am trying to learn to do this in dplyr if possible

Thanks

答:
This is fairly straightforward now thanks to dplyr's recode function. Here's one way to do it:

```<code># Generate a dataframe to match yours

df <- data.frame(
  participant = c(1,2),
  Q1 = c("agree", "neutral"),
  Q2 = c("neutral", "agree"),
  Q3 = c(NA,NA),
  Q4 = c("Disagree", NA),
  Q5 = c("Agree", NA)
)

# Use recode to recode the data

df_recode <- df %>%
  mutate(Q1 = recode(Q1, "agree" = 3, "neutral" = 2),
         Q2 = recode(Q2, "neutral" = 2, "agree" = 1),
         Q4 = recode(Q4, "Disagree" = 1),
         Q5 = recode(Q5, "Agree" = 3)
  )
</code>```

You'll also want to read about the .default and .missing arguments in the help file to be sure you aren't introducing NAs when you don't mean to.

Body:
I am picking up R again after last using it in 2013. I am getting used to using dplyr, but I am running into a problem with a simple task.
I  have a table that looks like

Participant Q1       Q2      Q3     Q4       Q5
1           agree  neutral   NA    Disagree  Agree
2           neutral agree    NA     NA       NA

My goal

   Participant Q1       Q2      Q3     Q4       Q5
    1           3       2       NA      1       3
    2           2       1       NA     NA       NA

I want to be able to change the categorical value to a numerical value for columns Q1:Q5, but all the examples that I see of using recode for dplyr work for rows and no columns. (I might be missing something in the examples). I then want to be able to pick column Q1 and Q2 and reverse code it.

I am trying to learn to do this in dplyr if possible

Thanks

Body:
This is fairly straightforward now thanks to dplyr's recode function. Here's one way to do it:

# Generate a dataframe to match yours

df <- data.frame(
  participant = c(1,2),
  Q1 = c("agree", "neutral"),
  Q2 = c("neutral", "agree"),
  Q3 = c(NA,NA),
  Q4 = c("Disagree", NA),
  Q5 = c("Agree", NA)
)

# Use recode to recode the data

df_recode <- df %>%
  mutate(Q1 = recode(Q1, "agree" = 3, "neutral" = 2),
         Q2 = recode(Q2, "neutral" = 2, "agree" = 1),
         Q4 = recode(Q4, "Disagree" = 1),
         Q5 = recode(Q5, "Agree" = 3)
  )

You'll also want to read about the .default and .missing arguments in the help file to be sure you aren't introducing NAs when you don't mean to.


问:
Custom federated web service authenticators
I need to authenticate users against a corporate web service in WSO2 Identity Server. I have found this blog:

http://techreadme.blogspot.com.es/2015/08/wso2-identity-server-use-case.html

and download the code from git. I need to implement a custom federated authenticator.
The sample code doesn`t work, maven does not look for the correct urls and the POM.xml does not seem to be correct.
¿Did someone get the code working?. Thank you.

答:
You need to write a custom federated authenticator

https://docs.wso2.com/display/IS510/Writing+a+Custom+Federated+Authenticator


问:
Laravel Queue start a second job after first job
In my Laravel 5.1 project I want to start my second job when first will finished.

Here is my logic.

```<code>\Queue::push(new MyJob())
</code>```

and when this job finish I want to start this job

```<code>\Queue::push(new ClearJob())
</code>```

How can i realize this?

答:
If you want this, you just should define 1 Queue.

A queue is just a list/line of things waiting to be handled in order,
  starting from the beginning. When I say things, I mean jobs. - https://toniperic.com/2015/12/01/laravel-queues-demystified

To get the opposite of what you want: async executed Jobs, you should define a new Queue for every Job.

Multiple Queues and Workers

You can have different queues/lists for
  storing the jobs. You can name them however you want, such as “images”
  for pushing image processing tasks, or “emails” for queue that holds
  jobs specific to sending emails. You can also have multiple workers,
  each working on a different queue if you want. You can even have
  multiple workers per queue, thus having more than one job being worked
  on simultaneously. Bear in mind having multiple workers comes with a
  CPU and memory cost. Look it up in the official docs, it’s pretty
  straightforward.

Body:
In my Laravel 5.1 project I want to start my second job when first will finished.

Here is my logic.

\Queue::push(new MyJob())

and when this job finish I want to start this job

\Queue::push(new ClearJob())

How can i realize this?


答:
You can use dplyr::left_join for exactly this kind of problem. dplyr has a useful vignette that covers joins or you can check out this general backgrounder on different kinds of joins.

```<code># Load dplyr and other useful packages
library(tidyverse)

# Generate demo dataset
df1 <-
  tibble(
    Code = c("BNC", "BNC", "BNC", "BBS", "BBS"),
    "Station Name" = c(
      "BANGALORE CANT",
      "BANGALORE CANT",
      "BANGALORE CANT",
      "BHUBANESWAR",
      "BHUBANESWAR"
    )
  )

df2 <- tibble("Station Name" = c("BANGALORE CANT", "BHUBANESWAR"),
              lat = c(12.993690, 20.296059),
              lon = c(77.59814, 85.82454))

# Join df1 and df2
left_join(df1, df2)
</code>```

This assumes that both datasets share a column with exactly the same name. You can use the by= argument if you want to exercise more control over how the two datasets are combined with each other.

Title: adding column values in one dataset from another dataset in R based on condition - different length

Body:
I have two data sets. One has duplicate location names, another one has location name and its lat long. I want to add lat long to first data set where the location name matches in second data set.

df1

 Code   Station Name
 BNC    BANGALORE CANT
 BNC    BANGALORE CANT
 BNC    BANGALORE CANT
 BBS    BHUBANESWAR
 BBS    BHUBANESWAR

df2

Station Name     lat       lon
BANGALORE CANT  12.993690  77.59814
BHUBANESWAR     20.296059  85.82454

expected result
df1

 Code   Station Name        lat        lon
 BNC    BANGALORE CANT     12.993690  77.59814
 BNC    BANGALORE CANT     12.993690  77.59814
 BNC    BANGALORE CANT     12.993690  77.59814
 BBS    BHUBANESWAR        20.296059  85.82454
 BBS    BHUBANESWAR        20.296059  85.82454

It is obvious that object length differs. And I need the df1 duplicate entry. cbind won't work as length differs. same for ifelse and if with sapply. Getting lat long for df1 using geocode fails as the list is long (query max exceeded).  Any thoughts?

Body:
You can use dplyr::left_join for exactly this kind of problem. dplyr has a useful vignette that covers joins or you can check out this general backgrounder on different kinds of joins.

# Load dplyr and other useful packages
library(tidyverse)

# Generate demo dataset
df1 <-
  tibble(
    Code = c("BNC", "BNC", "BNC", "BBS", "BBS"),
    "Station Name" = c(
      "BANGALORE CANT",
      "BANGALORE CANT",
      "BANGALORE CANT",
      "BHUBANESWAR",
      "BHUBANESWAR"
    )
  )

df2 <- tibble("Station Name" = c("BANGALORE CANT", "BHUBANESWAR"),
              lat = c(12.993690, 20.296059),
              lon = c(77.59814, 85.82454))

# Join df1 and df2
left_join(df1, df2)

This assumes that both datasets share a column with exactly the same name. You can use the by= argument if you want to exercise more control over how the two datasets are combined with each other.


问:
How to checked if Bootstrap toggle checked or not in jQuery
I'm trying to use Bootstrap Toggle, but I don't know how to check when a user check it on or off  in order to send it using ajax.

how can I do that ?

```<code><div class="checkbox">
    <label data-label-id="<?= $data->id; ?>" id="message_status">
        <input id="check_toogle" type="checkbox" data-toggle="toggle">
    </label>
    <div class="delete_message">
        ❌
    </div>
</div>
</code>```

http://www.bootstraptoggle.com/

答:
I guess

```<code>$('#bsfdsf').is(':checked')
</code>```

is a way to go. This should return true if checkbox is checked and false otherwise.

Body:
I'm trying to use Bootstrap Toggle, but I don't know how to check when a user check it on or off  in order to send it using ajax.

how can I do that ?

    <label data-label-id="<?= $data->id; ?>" id="message_status">
        <input id="check_toogle" type="checkbox" data-toggle="toggle">

        ❌

http://www.bootstraptoggle.com/

Body:
I guess

$('#bsfdsf').is(':checked')

is a way to go. This should return true if checkbox is checked and false otherwise.


问:
Subquery within Subquery is not working in hive
I have a complexed query, I am giving the simplified version of it here. Would like to know why it is not working.

```<code>select * from ((select 1) t1 union (select 2) t2);
</code>```

Getting the below error

```<code>NoViableAltException(290@[147:5: ( ( Identifier LPAREN )=> partitionedTableFunction | tableSource | subQuerySource | virtualTableSource )])
at org.antlr.runtime.DFA.noViableAlt(DFA.java:158)
at org.antlr.runtime.DFA.predict(DFA.java:144)
at org.apache.hadoop.hive.ql.parse.HiveParser_FromClauseParser.fromSource(HiveParser_FromClauseParser.java:3654)
at org.apache.hadoop.hive.ql.parse.HiveParser_FromClauseParser.joinSource(HiveParser_FromClauseParser.java:1836)
at org.apache.hadoop.hive.ql.parse.HiveParser_FromClauseParser.fromClause(HiveParser_FromClauseParser.java:1488)
at org.apache.hadoop.hive.ql.parse.HiveParser.fromClause(HiveParser.java:44869)
at org.apache.hadoop.hive.ql.parse.HiveParser.singleSelectStatement(HiveParser.java:42035)
at org.apache.hadoop.hive.ql.parse.HiveParser.selectStatement(HiveParser.java:41720)
at org.apache.hadoop.hive.ql.parse.HiveParser.regularBody(HiveParser.java:41657)
at org.apache.hadoop.hive.ql.parse.HiveParser.queryStatementExpressionBody(HiveParser.java:40710)
at org.apache.hadoop.hive.ql.parse.HiveParser.queryStatementExpression(HiveParser.java:40586)
at org.apache.hadoop.hive.ql.parse.HiveParser.execStatement(HiveParser.java:1529)
at org.apache.hadoop.hive.ql.parse.HiveParser.statement(HiveParser.java:1065)
at org.apache.hadoop.hive.ql.parse.ParseDriver.parse(ParseDriver.java:201)
at org.apache.hadoop.hive.ql.parse.ParseDriver.parse(ParseDriver.java:166)
at org.apache.hadoop.hive.ql.Driver.compile(Driver.java:418)
at org.apache.hadoop.hive.ql.Driver.compile(Driver.java:312)
at org.apache.hadoop.hive.ql.Driver.compileInternal(Driver.java:1201)
at org.apache.hadoop.hive.ql.Driver.runInternal(Driver.java:1296)
at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1127)
at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1115)
at org.apache.hadoop.hive.cli.CliDriver.processLocalCmd(CliDriver.java:220)
at org.apache.hadoop.hive.cli.CliDriver.processCmd(CliDriver.java:172)
at org.apache.hadoop.hive.cli.CliDriver.processLine(CliDriver.java:383)
at org.apache.hadoop.hive.cli.CliDriver.executeDriver(CliDriver.java:775)
at org.apache.hadoop.hive.cli.CliDriver.run(CliDriver.java:693)
at org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:628)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
</code>```

FAILED: ParseException line 1:15 cannot recognize input near '(' '(' 'select' in from source

答:
1

Unlike some databases, Hive does not accept brackets around a query.

E.g. select 1 is a valid query In hive, but not (select 1).

P.s.

Even databases that accept brackets around queries, do not accept aliases for these queries when combined by UNION.

E.g. (select 1) union (select 2) is a valid query in some databases, but not (select 1) t1 union (select 2) t2

2

Unlike some databases, Hive requires an alias for a sub-query.

E.g. select * from (select 1) t is a valid query In hive, but not select * from (select 1)

The right way to write the OP query would be -

select * from (select 1 union select 2) t;

```<code>+-----+
| _c0 |
+-----+
|   1 |
|   2 |
+-----+
</code>```

Body:
I have a complexed query, I am giving the simplified version of it here. Would like to know why it is not working.

select * from ((select 1) t1 union (select 2) t2);

Getting the below error

NoViableAltException(290@[147:5: ( ( Identifier LPAREN )=> partitionedTableFunction | tableSource | subQuerySource | virtualTableSource )])
at org.antlr.runtime.DFA.noViableAlt(DFA.java:158)
at org.antlr.runtime.DFA.predict(DFA.java:144)
at org.apache.hadoop.hive.ql.parse.HiveParser_FromClauseParser.fromSource(HiveParser_FromClauseParser.java:3654)
at org.apache.hadoop.hive.ql.parse.HiveParser_FromClauseParser.joinSource(HiveParser_FromClauseParser.java:1836)
at org.apache.hadoop.hive.ql.parse.HiveParser_FromClauseParser.fromClause(HiveParser_FromClauseParser.java:1488)
at org.apache.hadoop.hive.ql.parse.HiveParser.fromClause(HiveParser.java:44869)
at org.apache.hadoop.hive.ql.parse.HiveParser.singleSelectStatement(HiveParser.java:42035)
at org.apache.hadoop.hive.ql.parse.HiveParser.selectStatement(HiveParser.java:41720)
at org.apache.hadoop.hive.ql.parse.HiveParser.regularBody(HiveParser.java:41657)
at org.apache.hadoop.hive.ql.parse.HiveParser.queryStatementExpressionBody(HiveParser.java:40710)
at org.apache.hadoop.hive.ql.parse.HiveParser.queryStatementExpression(HiveParser.java:40586)
at org.apache.hadoop.hive.ql.parse.HiveParser.execStatement(HiveParser.java:1529)
at org.apache.hadoop.hive.ql.parse.HiveParser.statement(HiveParser.java:1065)
at org.apache.hadoop.hive.ql.parse.ParseDriver.parse(ParseDriver.java:201)
at org.apache.hadoop.hive.ql.parse.ParseDriver.parse(ParseDriver.java:166)
at org.apache.hadoop.hive.ql.Driver.compile(Driver.java:418)
at org.apache.hadoop.hive.ql.Driver.compile(Driver.java:312)
at org.apache.hadoop.hive.ql.Driver.compileInternal(Driver.java:1201)
at org.apache.hadoop.hive.ql.Driver.runInternal(Driver.java:1296)
at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1127)
at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1115)
at org.apache.hadoop.hive.cli.CliDriver.processLocalCmd(CliDriver.java:220)
at org.apache.hadoop.hive.cli.CliDriver.processCmd(CliDriver.java:172)
at org.apache.hadoop.hive.cli.CliDriver.processLine(CliDriver.java:383)
at org.apache.hadoop.hive.cli.CliDriver.executeDriver(CliDriver.java:775)
at org.apache.hadoop.hive.cli.CliDriver.run(CliDriver.java:693)
at org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:628)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
at org.apache.hadoop.util.RunJar.main(RunJar.java:136)

FAILED: ParseException line 1:15 cannot recognize input near '(' '(' 'select' in from source

Body:
1

Unlike some databases, Hive does not accept brackets around a query.

E.g. select 1 is a valid query In hive, but not (select 1).

P.s.

Even databases that accept brackets around queries, do not accept aliases for these queries when combined by UNION.

E.g. (select 1) union (select 2) is a valid query in some databases, but not (select 1) t1 union (select 2) t2

2

Unlike some databases, Hive requires an alias for a sub-query.

E.g. select * from (select 1) t is a valid query In hive, but not select * from (select 1)

The right way to write the OP query would be -

select * from (select 1 union select 2) t;

+-----+
| _c0 |
+-----+
|   1 |
|   2 |
+-----+


问:
Bug when unit testing Google Analytics tracker in XCode 6
I'm writing a unit test to check that the string I pass to the GAITracker class is being returned as the kGAIScreenName property for each screen.

However when I try to pass a sharedInstance to the GAI class to initialize the WNGoogleAnalyticsService instance I am getting the error Thread 1: EXC_BAD_ACCESS (code=1, address=0x20) as if it has not been allocated to the memory. No matter where I try to declare the sharedInstance won't initialize in the test class although it works fine in the AppDelegate.m.

WNGoogleAnlayticsServiceTest.m:

```<code>-(void)testIfNoScreenNameExists {
   NSString *screenName = @"Screen";
   Class builder = [GAIDictionaryBuilder class];
   GAI *gai = [GAI sharedInstance];

WNGoogleAnalyticsService *s = [[WNGoogleAnalyticsService alloc] initWithGAInstance:gai
                                                             gaKey:@"test"
                                          gaDictionaryBuilderClass:builder
                                                         debugging:NO];

id<GAITracker> tracker = [s trackerForScreen:screenName];

XCTAssertEqualObjects([tracker get:kGAIScreenName], screenName);
}
</code>```

AppDelegate.m:

```<code>Add Google Analytics as analytics service
WNGoogleAnalyticsService *googleAnalyticsService = [[WNGoogleAnalyticsService alloc] initWithGAInstance:[GAI sharedInstance]
                                                                                gaKey:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"WNGoogleKey"]
                                                                               gaDictionaryBuilderClass:[GAIDictionaryBuilder class]
                                                                                debugging:analyticsDebugging];
</code>```

I'm at a loss as to how to even go about fixing this bug so any help would be appreciated.

答:
In line with the comment I left underneath my question, I feel I should formally answer this with my solution.

In the case of this unit test, I was trying to re-use a singleton by reusing the [GAI SharedInstance] method in both my WNGoogleAnlayticsServiceTest and in my AppDelegate.m file which, by definition, it cannot do.

So if you want to test the Google Analytics methods, you must use a tool like OCMock to do so as you can't initialise the sharedInstance twice.

Body:
I'm writing a unit test to check that the string I pass to the GAITracker class is being returned as the kGAIScreenName property for each screen.

However when I try to pass a sharedInstance to the GAI class to initialize the WNGoogleAnalyticsService instance I am getting the error Thread 1: EXC_BAD_ACCESS (code=1, address=0x20) as if it has not been allocated to the memory. No matter where I try to declare the sharedInstance won't initialize in the test class although it works fine in the AppDelegate.m.

WNGoogleAnlayticsServiceTest.m:

-(void)testIfNoScreenNameExists {
   NSString *screenName = @"Screen";
   Class builder = [GAIDictionaryBuilder class];
   GAI *gai = [GAI sharedInstance];

WNGoogleAnalyticsService *s = [[WNGoogleAnalyticsService alloc] initWithGAInstance:gai
                                                             gaKey:@"test"
                                          gaDictionaryBuilderClass:builder
                                                         debugging:NO];

id<GAITracker> tracker = [s trackerForScreen:screenName];

XCTAssertEqualObjects([tracker get:kGAIScreenName], screenName);
}

AppDelegate.m:

Add Google Analytics as analytics service
WNGoogleAnalyticsService *googleAnalyticsService = [[WNGoogleAnalyticsService alloc] initWithGAInstance:[GAI sharedInstance]
                                                                                gaKey:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"WNGoogleKey"]
                                                                               gaDictionaryBuilderClass:[GAIDictionaryBuilder class]
                                                                                debugging:analyticsDebugging];

I'm at a loss as to how to even go about fixing this bug so any help would be appreciated.


问:
What are the units of wavelet?
I'm using the continuous wavelet transform on EEG data (originally in micoVolt) as follows:

```<code>coef, freqs = pywt.cwt(EEG_data, np.arange(0.5, 50, 0.5),'morl',
sampling_period=sampling_period)
</code>```

I know that the freqs's unit is Hz. What about coef?

答: According to this page: pywavelets.readthedocs.io/en/latest/ref/cwt.html. The frequency as you suggested is in Hz. but the coef it says is simply the 'Continous wavelet transform of the input signal for the given scales and wavelet'. I hope it helps.</p>

Title: What are the units of wavelet?

Body:
I'm using the continuous wavelet transform on EEG data (originally in micoVolt) as follows:

coef, freqs = pywt.cwt(EEG_data, np.arange(0.5, 50, 0.5),'morl',
sampling_period=sampling_period)

I know that the freqs's unit is Hz. What about coef?


问:
Open method in ajax call not responding
I am new to JSON and AJAX,
SO i tried this piece of code to get JSON data from the url mentioned and then using a AJAX call i tried to print it on console, however nothing gets printed on the console.

Please someone correct what is it that i am doing wrong here, below is the code snippet.

var req = new XMLHttpRequest();
var btn = document.getElementById("btn");
var display = document.getElementById("display");
req.open("GET", "http://www.filltext.com/?rows=10&id={index}&email={email}&username={username}&password={randomString|5}&pretty=true", true);
btn.addEventListener("click",function(){
req.onreadystatechange = function() {
  var res = req.responseText;
  Console.log(res);
};
});
req.send();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Hello</h1>
<Button id= 'btn'>click me</Button>
<div id = 'display'></div>

<script>"Test.js"</script>

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

答:
When you set req.onreadystatechange inside btn event you only add the callback to request. The problem is the request has already been made. You need to make request on btn click, then you call send() inside the btn action.

console instead of Console

var req = new XMLHttpRequest();
var btn = document.getElementById("btn");
var display = document.getElementById("display");

req.open("GET", "http://www.filltext.com/?rows=10&id={index}&email={email}&username={username}&password={randomString|5}&pretty=true", true);
req.onreadystatechange = function() {
    var res = req.responseText;
    console.log(res);
};

btn.addEventListener("click",function(){
    req.send();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Hello</h1>
<Button id= 'btn'>click me</Button>
<div id = 'display'></div>

<script>"Test.js"</script>

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

Title: Open method in ajax call not responding

Body:
I am new to JSON and AJAX,
SO i tried this piece of code to get JSON data from the url mentioned and then using a AJAX call i tried to print it on console, however nothing gets printed on the console.

Please someone correct what is it that i am doing wrong here, below is the code snippet.

var req = new XMLHttpRequest();
var btn = document.getElementById("btn");
var display = document.getElementById("display");
req.open("GET", "http://www.filltext.com/?rows=10&id={index}&email={email}&username={username}&password={randomString|5}&pretty=true", true);
btn.addEventListener("click",function(){
req.onreadystatechange = function() {
  var res = req.responseText;
  Console.log(res);
};
});
req.send();

<!DOCTYPE html>

<meta charset="ISO-8859-1">
<title>Insert title here</title>

Hello

<Button id= 'btn'>click me</Button>

Body:
When you set req.onreadystatechange inside btn event you only add the callback to request. The problem is the request has already been made. You need to make request on btn click, then you call send() inside the btn action.

console instead of Console

var req = new XMLHttpRequest();
var btn = document.getElementById("btn");
var display = document.getElementById("display");

req.open("GET", "http://www.filltext.com/?rows=10&id={index}&email={email}&username={username}&password={randomString|5}&pretty=true", true);
req.onreadystatechange = function() {
    var res = req.responseText;
    console.log(res);
};

btn.addEventListener("click",function(){
    req.send();
});

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Hello</h1>
<Button id= 'btn'>click me</Button>
<div id = 'display'></div>

<script>"Test.js"</script>

</body>
</html>