text:
Q: How to get row index in JXLS 2.3.0 I can use varStatus property in jxls 1.X to get the row index while using foreach to traverse a list, But jxls 2.3.0 does not support this, how can output the row index in EXCEL with jxls 2.3.0 ?

A: As I understand in current version of JXLS rowStatus doesn't work.
You may use one of these options:
1) You can add row index in index-attribute in your data before place in to JXLS and print in row-template as ${row.index}
2) You can use excel formula like =ROW()-ROW(HEADER_CELL). So if your table-headers end on A4, so in template you need write $[ROW()-ROW(A4)]

A: Since JXLS 2.7.0, you can specify varIndex="foo" in your jx:each comment, then refer to it as ${foo}
Ref: https://bitbucket.org/leonate/jxls/issues/173/how-can-i-get-index-in-jx-each

A: For JXLS example :jx:each(items="yourList", var="currentValue", lastCell="N7")
You can using ${yourList.indexOf(currentValue)} to get index.

A: use ROW()-ROW(HEADER_CELL) works,

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change base url in Laravel Is there anyway to change base url in laravel from controller?
I have two modules in my website one is normal browsing and another is subscription browsing. What i want is , when a user comes to my website first, they get to choose what they want to browse. For example if they want to do normal browsing, then i want to redirect to normal browsing and the url should be www.example.com/normal  and i want to make this base url. so what ever link he click there after will be like www.example.com/normal/somelink . Simillarly for subscription  it will be like www.example.com/subscription/somelink.
If it is possible how can check in the route that he is in subscription browsing/ normal browsing ?
As of now i am adding prefix in the route . But sometime some url such as login,user/profile etc are becoming exception.
So how can i do so, if it possible. Any advice. ty.
My route as of now
/**
 * NORMAL BROWSING
 */
Route::group(['middleware' => ['web', 'activity'],'namespace' => 'Frontend'], function () {
    Route::prefix('normal')->group(function () {
      .......
     .......
    });
});

/**
 * SUBSCRIPTION BROWSING
 */
Route::group(['middleware' => ['web', 'activity'],'namespace' => 'Frontend'],function(){
    Route::prefix('subscription')->group(function () {
       ........
      ........
    });

});

A: Little change to your code shall make it work. Assuming auth and web are middlewares
Route::group(['prefix' => 'normal',  'middleware' => ['auth', 'web'], 'namespace' => 'Frontend'], function()
{
    Route::get('/', function() {} );
    Route::get('/page2', function() {} );
});

This should give take your application home page to website.com/normal and page 2 should be website.com/normal/page2
You can mention other routes outside of the group.
If you want to check if a user is a normal user or a subscription user. you can create a new middleware and use that middleware in the route.
I see that you have already made two middlewares web and activity. Why are you using both the middlewares on a single group route?


text:
Q: Why is my zipline schedule_function not working for monthly schedule? backtest is always running on a daily basis I am trying to schedule my rebalance function in zipline 1.4.1, however instead of running on a monthly schedule my backtest is running daily.
Actual code:
#%%
import zipline.api as zapi
from zipline import run_algorithm
import pandas as pd

#%%
def initialize(context):
    zapi.schedule_function(
        rebalance,
        algo.date_rules.month_start(),
        algo.time_rules.market_open(hours=2)
    )

def rebalance(context, data):
    print(f"rebalancing at {zapi.get_datetime()}")

def analyze(context, perf):
    print('We are now analyzing')

#%%
start_date = pd.Timestamp('2010-1-3', tz='UTC')
end_date = pd.Timestamp('2010-4-3', tz='UTC')

result = run_algorithm(
        start = start_date,
        end = end_date,
        initialize=initialize,
        handle_data=rebalance,
        # benchmark_returns=benchmarkReturns,
        capital_base= 10000,
        analyze=analyze,
        data_frequency='daily',
        bundle='csv-bundle')

backtest result:
rebalancing at 2010-01-04 21:00:00+00:00
rebalancing at 2010-01-04 21:00:00+00:00
rebalancing at 2010-01-05 21:00:00+00:00
rebalancing at 2010-01-06 21:00:00+00:00
rebalancing at 2010-01-07 21:00:00+00:00
rebalancing at 2010-01-08 21:00:00+00:00
rebalancing at 2010-01-11 21:00:00+00:00
rebalancing at 2010-01-12 21:00:00+00:00
rebalancing at 2010-01-13 21:00:00+00:00
rebalancing at 2010-01-14 21:00:00+00:00
rebalancing at 2010-01-15 21:00:00+00:00
rebalancing at 2010-01-19 21:00:00+00:00
rebalancing at 2010-01-20 21:00:00+00:00
rebalancing at 2010-01-21 21:00:00+00:00
rebalancing at 2010-01-22 21:00:00+00:00
rebalancing at 2010-01-25 21:00:00+00:00
rebalancing at 2010-01-26 21:00:00+00:00
rebalancing at 2010-01-27 21:00:00+00:00
rebalancing at 2010-01-28 21:00:00+00:00
rebalancing at 2010-01-29 21:00:00+00:00
rebalancing at 2010-02-01 21:00:00+00:00
rebalancing at 2010-02-01 21:00:00+00:00
rebalancing at 2010-02-02 21:00:00+00:00
rebalancing at 2010-02-03 21:00:00+00:00
rebalancing at 2010-02-04 21:00:00+00:00
rebalancing at 2010-02-05 21:00:00+00:00
rebalancing at 2010-02-08 21:00:00+00:00

I tried to downgrade zipline to version 1.3.0 and got the same result. Does anyone got the same issue? and is there is any fix for this? your kind reply is appreciated.

A: I have the same issue. I don't think schedule_function works with zipline. run_algorithm
I worked around it by creating a function:
def monthly_cal(cal_name,start,end):
xnys=get_calendar(cal_name)
xnys_cal= xnys.sessions_in_range(start,end)
df=pd.DataFrame(index=xnys_cal)
df['month']=pd.DatetimeIndex(df.index).month
trading_days=df['month'][df['month'] != df['month'].shift(-1)].index
return trading_days

and load it in the initialize
context.available_dates=monthly_cal('XNYS',start,end)

and check this condition in handle_data
if context.get_datetime().date() in context.available_dates:


text:
Q: Oracle job queue Есть job, который запускает процедуру с входящими параметрами через программу. Как запустить  job вовремя ее выполнения чтобы она стала в очередь и начала отрабатывать после завершения первой, но уже с другими параметрами?
job запускаю след образом
dbms_scheduler.set_job_argument_value('GPIMS.JOB_UPD_GP_ADDR_MAPP',1,IN_GP_ID);
dbms_scheduler.set_job_argument_value('GPIMS.JOB_UPD_GP_ADDR_MAPP',2,to_char(P_GP_STATUS_DATE));
dbms_scheduler.enable('GPIMS.JOB_UPD_GP_ADDR_MAPP');

Создание job
begin
  dbms_scheduler.create_job('GPIMS.JOB_UPD_GP_ADDR_MAPP',
                            program_name                => 'GPIMS.PROGRAM_UPD_GP_ADDR_MAPP',
                            auto_drop                   => FALSE);
end;

Создание программы
begin
  sys.dbms_scheduler.create_program(program_name        => 'GPIMS.PROGRAM_UPD_GP_ADDR_MAPP',
                                    program_type        => 'STORED_PROCEDURE',
                                    program_action      => 'GPIMS.PKG_GLOBAL_PROBLEM.UPD_GP_ADDR_MAPP',
                                    number_of_arguments => 3,
                                    enabled             => false,
                                    comments            => '');
  sys.dbms_scheduler.define_program_argument(program_name        => 'GPIMS.PROGRAM_UPD_GP_ADDR_MAPP',
                                             argument_position   => 1,
                                             argument_name       => 'IN_GP_ID',
                                             argument_type       => 'VARCHAR2',
                                             default_value       => '');
  sys.dbms_scheduler.define_program_argument(program_name        => 'GPIMS.PROGRAM_UPD_GP_ADDR_MAPP',
                                             argument_position   => 2,
                                             argument_name       => 'P_GP_STATUS_DATE',
                                             argument_type       => 'DATE',
                                             default_value       => '');
  sys.dbms_scheduler.define_program_argument(program_name        => 'GPIMS.PROGRAM_UPD_GP_ADDR_MAPP',
                                             argument_position   => 3,
                                             argument_name       => 'OUT_MSG',
                                             argument_type       => 'VARCHAR2',
                                             default_value       => '');
  sys.dbms_scheduler.enable(name => 'GPIMS.PROGRAM_UPD_GP_ADDR_MAPP');
end;

A: Так нельзя делать. Невозможно запустить once Job, который уже выполняется.
Для этого есть цепочки (job chains), но передать к каждому звену цепочки свои параметры также не представляется возможным.
Можно передать каждому звену мета данные, например: job_name, job_subname, как формальные параметры. Они будут замещены актуальными значениями для выполняемой задачи и соответственно звена задачи. Далее определить эти же данные как ключ в таблице для параметров.
Подготовим схему:
create table myJobInfo (beg timestamp, end timestamp, info varchar2 (256));
create or replace type myJobArgs as object (
    jobName varchar2 (32), jobStepName varchar2 (32), argChar varchar2 (64), argDate date);
/
create table myJobArgsTab of myJobArgs;
insert into myJobArgsTab
    select myJobArgs (
        'myJob', 'chainStep'||rownum, 'arg char '||rownum, date'2018-07-01'+(rownum-1))
    from xmlTable ('1 to 3');

Создадим программу и цепочку выполненения, которая будет запускать эту программу в каждом звене:
begin
    sys.dbms_scheduler.create_program (
        program_name=>'myJobProg',
        program_type=>'stored_procedure',
        program_action=>'myJobProc',
        number_of_arguments=>2,
        enabled=>false,
        comments=>'test job')
        ;
    dbms_scheduler.define_metadata_argument (
        program_name=>'myJobProg',
        metadata_attribute=>'job_name',
        argument_position=>1
        );
    dbms_scheduler.define_metadata_argument (
        program_name=>'myJobProg',
        metadata_attribute=>'job_subname',
        argument_position=>2
        );
    sys.dbms_scheduler.enable ('myJobProg');
    -- create chain/steps
    dbms_scheduler.create_chain ('myJobChain');
    dbms_scheduler.define_chain_step ('myJobChain', 'chainStep1', 'myJobProg');
    dbms_scheduler.define_chain_step ('myJobChain', 'chainStep2', 'myJobProg');
    dbms_scheduler.define_chain_step ('myJobChain', 'chainStep3', 'myJobProg');
    -- rules
    dbms_scheduler.define_chain_rule ('myJobChain', condition=>'true', action=>'start chainStep1');
    dbms_scheduler.define_chain_rule ('myJobChain', condition=>'chainStep1 completed', action=>'start chainStep2');
    dbms_scheduler.define_chain_rule ('myJobChain', condition=>'chainStep2 completed', action=>'start chainStep3');
    dbms_scheduler.define_chain_rule ('myJobChain', condition=>'chainStep3 completed', action=>'end');
    dbms_scheduler.enable ('myJobChain');
end;
/

Тест процедура:
create or replace procedure myJobProc (jobName varchar2, jobStepName varchar2) is
    rowid_ rowid;
    args myJobArgs;
begin
    begin
        select value (t) into args
        from myJobargsTab t
        where upper (t.jobName)     = myJobProc.jobName
        and   upper (t.jobStepName) = myJobProc.jobStepName
        for update
        ;
    exception when others then
        dbms_output.put_line ('ERROR: '||jobName||'.'||JobStepName||': sqlerrm:'||sqlerrm);
    end;
    insert into myJobInfo (beg, info) values (
        systimestamp, jobName||'.'||JobStepName||': args='||args.argChar||'/'||to_char (args.argDate,'yyyy-mm-dd'))
    returning rowid into rowid_
    ;
    sys.dbms_lock.sleep (3);
    update myJobInfo set end=systimestamp where rowid=rowid_;
end;
/

Запустим всю цепочку и посмотрим, что получилось:
exec dbms_scheduler.run_chain (chain_name=>'myJobChain', start_steps=>null, job_name=>'myJob');

select * from myJobInfo order by beg desc;

BEG          END          INFO
------------ ------------ ----------------------------------------------------------------
10:52:24.246 10:52:27.246 MYJOB.CHAINSTEP3: args=arg char 3/2018-07-03
10:52:21.202 10:52:24.202 MYJOB.CHAINSTEP2: args=arg char 2/2018-07-02
10:52:18.154 10:52:21.154 MYJOB.CHAINSTEP1: args=arg char 1/2018-07-01

Для дальнейшей информации читаем оф. документацию тут и тут.

A: Спасибо за ответ https://ru.stackoverflow.com/a/857555/201383, но все оказалось немного проще. Получилось сделать с помощью dbms_job.submit. Все работает как надо.
dbms_job.submit(l_jobno, 'declare OUT_MSG varchar2(50); BEGIN gpims.pkg_global_problem.UPD_GP_ADDR_MAPP('''||IN_GP_ID||''', '''||P_GP_STATUS_DATE||''', OUT_MSG); END;');


text:
Q: How to find proper phrasal verbs or idioms for the sentence you're translating? Let's assume you're translating a sentence. You can translate everything in English but sometimes there are idioms and phrasal verbs that you can use to make your sentnce more clear and compact. e.g., for this sentence:

I want to seperate it into pieces.

You can use "break up". i.e.,

I want to break it up.

But the point is that finding such phrasal verbs is difficult. I mean you don't know if such phrasal verb exist or how to search to find such phrasal verb. You non-native, How do you know that if such phrasal verb exist? How do you find them?
For example, I use https://www.thefreedictionary.com/break to find the meaning of phrasal verbs but it appears that we cannot use it in reverse direction as I said. Do you use any specific dictionary?

A: This is obviously where experience and knowledge starts to really help!
One practical way that even native speakers are advised to use to get that knowledge is a decent thesaurus, and then under synonyms or antonyms there should be some useful alternatives - including phrasal verbs.
Here is thesaurus.com  I have put in 'separate' already. Notice the tabs where you can look through the various meanings of 'separate'.
Finally, be aware that phrasal verbs are only the best option when they are the best option, just using them because they are phrasal verbs is not always best. It is as always with vocabulary case dependent!

A: You're so right that translation is far more than simply substituting words. To translate well from one language to another you need to have a reasonable idiomatic understanding of both. My favourite example of how you can't translate with a bilingual dictionary alone is that if you were asked to translate the German term "schraube and mutter" into English that way you would get "screw and mother", which means nothing at all in English. A dictionary is not enough - to convey the meaning of the original you need to know that is what Germans call a nut and bolt.
My suggestion would be to use a good online thesaurus. They don't just offer synonymous words, but phrases too.
Thesaurus.com associates "Break up" with words like dismantle, disassemble, or disperse, so if you had looked up any of these words you would have been brought to this idiomatic phrase "break up".
Interestingly, not all senses of "break up" are synonymous with "separate". This word can sometimes mean to break apart just two things, and not always break things down into many pieces. This website helps by offering various tabs with different senses of the word or phrase you searched for.

A: Native speakers looking for this kind of thing use a thesaurus (wikipedia), most often one descended from Roget's 1805 work.
An online version of that gives

separate
10 Irrelation: Adj. disrelated, disconnected, dissociated, detached, removed, separated, separate, segregate, apart, independent,
  independent.
15 Difference: Vb. separate, sever, severalize, segregate, divide -- distinct, distinguished, separate, widely apart.
44 Disjunction: Vb. separate, divide, part, dispart, divorce, detach, remove -- part, separate, split up, split out, break up, break it
  up, leave, take leave, quit, go away, go separate ways, part company
  -- separate, distinct, discrete.

A non-native speaker might also want a dictionary of phrasal verbs -- many are available -- to understand the sense of the phrases.  Native speakers reading such dictionaries are always surprised at how many meanings there are, and that usually we know every single one.


text:
Q: Raspberry Pi - HTML forms not submitting I have a Raspberry Pi that is effectively being used as a kiosk display. It auto starts Chromium and goes to a webpage which displays some data. There is a form on this page and a barcode reader attached to the Pi which, when a barcode is scanned dumps the contents of the barcode into the textbox and simulates a carriage return (enter).
This works in console on the Pi and on other machines which have no problem with the webpage however, on the Pi it will generally dump the contents of the barcode and won't submit the form - if you attach the keyboard and hit enter nothing happens; change the focus onto the button and hit enter - nothing happens!

My HTML code for the form:

      <?php echo date( "d/m/Y - H:i:s", time()); ?>

      <form action='board_update.php' id="id" method='post'><input type='text' name='id' autofocus='autofocus'/><input type="submit " value="Submit " /></form>

The page has a meta tag which causes it to refresh at 5 minute intervals (which it does).
I'm wondering what the problem is? The form or the Pi?

A: It appears that after much troubleshooting and replicating the setup on another Pi, that it is indeed the Raspberry Pi at fault. Something is either wrong with the OS or hardware but I've replaced the entire set up and so far, so good.


text:
Q: Overlapping Gershgorin disks We all know Gershgorin's Circle Theorem, which I will summarise for convenience.  Let $A=(a_{ij})$ be an $n\times n$ complex matrix. Define the disks $D_1,\ldots,D_n$ by $$D_i = \Bigl\{ z : |z-a_{ii}|\le \sum_{j\ne i} |a_{ij}|\Bigr\}.$$  Then each eigenvalue of $A$ lies in one of the disks.  Moreover, if a connected component of the union of the disks contains $k$ disks, then exactly $k$ eigenvalues of $A$ lie in that union.
My question is when a stronger statement is true.  When is it possible to list the eignvalues $\lambda_1,\ldots,\lambda_n$ in such an order that $\lambda_i\in D_i$ for all $i$?
What is a small counterexample for general matrices?  Is there a counterexample for real symmetric matrices?  Is there a nice family of matrices for which there is no counterexample?
Note that by Hall's marriage theorem, the stronger statement is equivalent to saying that for each $k$, the union of any $k$ disks includes at least $k$ eigenvalues.

A: Let $A$ be a Hermitian matrix.  Let $c$ be column $j$ of $A$, but with element $j$ set to zero, and let $E = ce_j^T + e_j c^T$, where $e_j$ is a standard basis vector.  Note that $A-E$ has $a_{jj}$ as an eigenvalue, and a straightforward computation gives that
$$\|E\|_2 = \|c\|_2 \leq \|c\|_1$$
Because $A$ and $A-E$ are both Hermitian, we know that there is an eigenvalue of $A$ within $\|E\|$ of each eigenvalue of $A-E$.  In particular, there is an eigenvalue $\lambda$ of $A$ such that $|\lambda - a_{jj}| < \|c\|_1$ -- that is, there is an eigenvalue of $A$ in the $j$th Gerschgorin disk.


text:
Q: How to implement Linked List Recursion in KOtlin I am learning linked list and came across a problem where you are required to reverse a linked list using recursion. Here is the code I wrote:
fun reverseRecurseTraverse1(firstNode: Node<Int>?): Node<Int>? {
    if (firstNode?.next == null) {
        return firstNode
    } else {
        val finalNode = reverseRecurseTraverse1(firstNode.next)
        finalNode?.next = firstNode
        firstNode.next = null
        return finalNode
    }
}

Input:
01234

Output:
40

I get the desired output If I change the line from
finalNode?.next = firstNode

to
firstNode.next!!.next = firstNode

What am I doing wrong here?
When I try to whiteboard finalNode?.next = firstNode makes perfect sense to me and based on my understanding those two lines are essentially doing the same thing.
Kindly help me understand this.

A: It would be useful if you share your "whiteboard logic" and why do you assume finalNode?.next = firstNode is correct and functionally the same as firstNode.next!!.next = firstNode.
Let's get your example: 01234. In the first step firstNode is 0 and after reversing of the remaining sublist, we get 4321. finalNode points at the first element of this reversed sublist, so at 4. Then you add 0 after 4 which is wrong. You should add 0 after 1.
On the other hand, firstNode.next is still pointing at the item that was next to 0 in the original list. It points at 1. By assigning to its next we add 0 where it should be - after 1.

A: You are almost there, but one line is wrong.
What you are doing is:
If your item is null, return it. That seems okay.
If your item is already the last item, return it as first item. Also looks okay.
If your item is not the last item, reverse the rest of the list. Okay.
Take the old last and now first item, and append your old first now last item to it? That doesn't seem right. Don't you want to append your old first and now last item to the last item of the reversed rest?
It would probably help to write a function
fun Node.last(): Node? = if(next == null) this else next!!.last()

that provides the last item of a linked list.
You could use that to append your previously first item to the last item of the reversed rest.
Considering a call reverseRecurseTraverse1(x), can we maybe always tell what reverseRecurseTraverse1(x).last() is without calculating it?


text:
Q: How to add case statement to add break after every record? There should be a break after every row LIKE 'A%' when find next records of LIKE 'B%'.
$stmt = $con->prepare("SELECT * FROM fistevent WHERE Event_Id=? AND TicketType=? AND row_name REGEXP '^[A-Z]' ORDER BY row_name ASC");

$stmt->bind_param("ss", $_POST['EventId'],$_POST['TicketType']);
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if($numRows > 0) {
    echo '
';
    while($r = $result->fetch_assoc()) {
        $EvntId = $r['Event_Id'];
        $RowName = $r['row_name'];

        echo '
';
            if($r['seats'] == null){
                echo '

';
            }elseif($r['Status'] == 'Y' || $r['Status'] == 'Hold'){
                echo '

';
            }else{
                echo '

';
            }
        echo "
";
   }
   echo '
';

I am getting the following output, but I want after `LIKE 'A%'` the next `LIKE 'B%'` should be in the next row.

Updated code is here
$stmt = $con->prepare("SELECT * FROM fistevent WHERE Event_Id=? AND TicketType=? AND row_name REGEXP '^[A-Z]' ORDER BY row_name ASC");
$stmt->bind_param("ss", $_POST['EventId'],$_POST['TicketType']);
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if($numRows > 0) {
    echo '
';
    $prev='A';
    while($r = $result->fetch_assoc()) {
        $EvntId = $r['Event_Id'];
        $RowName = $r['row_name'];
        if($prev!=$RowName){
            echo "
";
            $prev=$RowName;
        }
        echo '
';
            if($r['seats'] == null){
                echo '

';
            }elseif($r['Status'] == 'Y' || $r['Status'] == 'Hold'){
                echo '

';
            }else{
                echo '

';
            }
        echo "
";
    }
    echo '
';
}else{
    echo "No seats Available";
}

**in responsive**

A: Since you order by row_name you only need to check if the new value is different from the previous value.
//setting firstLetter
$firstLetter = '1';
  while($r = $result->fetch_assoc()) {
        $EvntId = $r['Event_Id'];
        $RowName = $r['row_name'];

       echo '
';
        if($r['seats'] == null)
        {
        echo '

';
        }
        else if($r['Status'] == 'Y' || $r['Status'] == 'Hold')
        {
        echo '

';
        }
        else
        {
         echo '

';
        }
        //comparing current first letter with previous first letter,also skipping the break if it is the first row
         if($RowName[0] != $firstLetter &&  $firstLetter !='1'  ){
         echo "
";
        }
        $firstLetter = $RowName[0];

       echo "
";
       }

A: You can use this function for like in php
function like_match($pattern, $subject)
{
    $pattern = str_replace('%', '.*', preg_quote($pattern, '/'));
    return (bool) preg_match("/^{$pattern}$/i", $subject);
}

Example
like_match('%A','Apple'); //TRUE
like_match('%c', 'coop'); //TRUE
like_match('%l', 'deke'); //FALSE
like_match('%m', 'flip-flop'); //FALSE

A: This should add line breaks between (not before the first) each unique row, and add the row_name letter to the start of each unique row.
$prev='';
while($r=$result->fetch_assoc()) {
    if($prev!=$r['row_name']){
        if($prev!=''){echo "
";}                             // add breaks between rows
        echo "
{$r['row_name']} ";            // label the row
        $prev=$r['row_name'];                                 // store new row_name letter
    }else{
        echo "
";   // not a new row_name, extend existing row
    }
        if($r['seats']==null){
            echo "

";
        }elseif($r['Status']=='Y' || $r['Status']=='Hold'){
            echo "

";
        }else{
            echo "

";
        }
    echo "
";
}

To overcome the OP's li {float:left} styling, he has made this adjustment in the css:
ul{display: table-cell; }

Old answer starts here:
I don't know how Bijender's answer helped you, and I don't know why you need a function call.  I also don't know what you mean by "add break after LIKE 'A%".
Since row_name is a single letter value, and you want to only return rows with the value A, B, C, D, E, F, G, H, I, or J, then you will want this simpler / more refined query:
SELECT *
FROM fistevent
WHERE Event_Id=? AND TicketType=? AND row_name IN ('A','B','C','D','E','F','G','H','I','J')
ORDER BY row_name ASC

The error that I found in your post is that your table column is either EventId or Event_Id.  You should fix this typo for clarity.


text:
Q: how to click all buttons with same class (java) i've been trying to click all buttons with the same class.
For example: i want to click all  buttons on the page which have the same class.  I'm not sure if this is the emulator or is there some java code I can put that will allow me to click any button at random? Thanks.

A: You can follow below code--
List<WebElement> list=driver.findElements(By.className("NameofTheClass"));
    for(WebElement element: list)
    {
         element.click();

    }


text:
Q: Coin Flipping with Bias This is a question on basic probability, and I wonder if my approach is correct. Moreover, if my answer is correct, I wonder if there is another way to do it without using the law of total probability (simply use counting method for example):
Question:
A bag contains 6 coins, 5 fair coins, and one which has heads on both sides. Suppose you grab 2 of the 6 coins, and flip them both. What is the probability that you get exactly one head and one tail?
My Attempt so far:
Let $A$ be the event that we get exactly one head and one tail and $B$ be the event that the coin is biased. Then
$$
P(A) = P(HT) + P(TH) = P(H)P(T) + P(T) P(H) = 2P(T)P(H)
$$
Now
$$
P(H) = P(H \cap B) + P(H \cap B^c) = P(H | B) P(B) + P(H|B^c) P(B^c) = 1 \times \frac{1}{6} + \frac{1}{2} \times \frac{5}{6} = \frac{1}{6} + \frac{5}{12} = \frac{7}{12}.
$$
Similarly,
$$
P(T) = P(T \cap B) + P(T \cap B^c) = P(T| B) P(B) + P(T|B^c) P(B^c) = 0 \times \frac{1}{6} + \frac{1}{2} \times \frac{5}{6} = \frac{5}{12}.
$$
Then we have
$$
P(A) = 2P(T)P(H) = 2 \times \frac{7}{12} \times \frac{5}{12} = \frac{35}{72} \approx 48.61\%.
$$
(This seems like a pretty high probability, which makes me think this reasoning invalid.)

A: Here is a much more direct way, which works whenever we have $n\geq2$ fair coins, and one biased HH coin.

*

*If we don't pick the biased coin, clearly the probability of one H
one T is $1/2$.

*If we do pick the biased coin, then we are guaranteed one H. So we
need the other (fair) coin to land T, which has probability $1/2$.

So in any case the probability of one H one T is $1/2$.

A:
Why is coin 1 lands H and coin 2 lands T not independent? Intuitively, they are not correlated, right?

I will answer that question in the addendum, after attacking the original problem.
Let event $E_1$ denote the event that both coins selected are fair coins.
Let event $E_2$ denote the event that one of the coins selected is the biased coin.
Let $F$ denote the event that whichever coins are selected, you get one Heads and one Tails.

Then, the desired computation is $S + T$ where

*

*$S = p(E_1) \times p(F|E_1)$.

*$T = p(E_2) \times p(F|E_2)$.
$\displaystyle p(E_1) = \frac{\binom{5}{2}}{\binom{6}{2}} = \frac{10}{15} = \frac{2}{3} \implies $
$\displaystyle p(E_2) = 1 - p(E_1) = \frac{1}{3}$.
$\displaystyle p(F|E_1) = \left[\frac{1}{2} \times \frac{1}{2}\right] + \left[\frac{1}{2} \times \frac{1}{2}\right] = \frac{1}{2}.$
The above computation represents the combined probabilities of $HT$ and $TH$, where one of the coins is arbitrarily designated as the first coin to be flipped.
$\displaystyle p(F|E_2) = \left[1 \times \frac{1}{2}\right] + \left[0 \times \frac{1}{2}\right] = \frac{1}{2}.$
The above computation represents the combined probabilities of $HT$ and $TH$, where the biased coin is arbitrarily designated as the first coin to be flipped.
So,
$$S = \frac{2}{3} \times \frac{1}{2} = \frac{1}{3}, ~~T = \frac{1}{3} \times \frac{1}{2} = \frac{1}{6} \implies S + T = \frac{1}{2}.$$

The shortcut is in realizing that $p(F|E_1) = p(F|E_2)$, which implies that the event $F$ is independent of event $E_1$.  So, since all that you are actually interested in is $p(F)$, you can use your intuition to reason that $p(F)$ must be $(1/2)$, since it does not matter what the relative probabilities are of $p(E_1)$ vs $p(E_2)$.

Addendum

Why is coin 1 lands H and coin 2 lands T not independent? Intuitively, they are not correlated, right?

This is a totally different question from the question of whether events $F$ and $E_1$ are independent events.  The easiest way to answer this question is with intuition.
If the first coin lands H, then the probability of the first coin being the biased coin is slightly greater than normal.  To demonstrate this, use Bayes Theorem.
The chance of the first coin landing Heads is
$\displaystyle \left[\frac{1}{6} \times 1\right] + \left[\frac{5}{6} \times \frac{1}{2}\right] = \frac{7}{12}$.
This implies that the probability that the first coin is biased, given that it lands Heads is
$\displaystyle \frac{(1/6)}{7/12} = \frac{2}{7}$, rather than $\displaystyle \frac{1}{6}.$
So, once you realize that the probability of the first coin being biased is slightly greater than normal, given that the first coin lands Heads, this must imply that the probability that the second coin is biased must be less than normal.
So, if you have the implication that there is a smaller chance than normal that the second coin is biased, this means that there is a greater chance than normal that the second coin comes up Tails.
Thus, the event of the first coin flip being Heads and the second coin flip being Tails are not independent events.

A: The way I see it is that there are two 'experiments': Firstly which two coins you grab and secondly which sides they land on.
Grabbing two coins:

First coin
p
second coin
p
overall p

normal
5/6
normal
4/5
4/6=2/3

both heads
1/5
1/6

----------
-
-----------
-
---------

both heads
1/6
normal
1
1/6

So 2/3 of the time we have two normal coins and 1/3 of the time we have one normal coin and one coin with two heads.
Which side they land on:

coins
p
sides
p
overall p

both normal
2/3
hh
1/4
1/6

ht or th
1/2
1/3

tt
1/4
1/6

----------
-
--------
-
---------

one biased
1/3
ht or th
1/2
1/6

hh
1/2
1/6

So the probability that we have one heads and one tails is 1/3+1/6=1/2. I hope that I explained it clearly enough.


text:
Q: Java 8 for Minecraft Forge Error (Debian 10) I tried to install Java 8 in addition to Java 11 on my VPS. Apparently that was only moderately successful. It is displayed under "java -version". And also with "sudo update-alternatives --config java", but the vServer still does not want to start.
https://pastebin.com/jzp4CeGi

A: You're running a 32-bit JRE ("linux-x86") on a 64-bit kernel:
# JRE version: Java(TM) SE Runtime Environment (8.0_261-b12) (build 1.8.0_261-b12)
# Java VM: Java HotSpot(TM) Server VM (25.261-b12 mixed mode linux-x86 )

A 64-bit JRE/JDK should resolve the issue, java -version should show 64-Bit Server VM in the output. This seems to be related to JDK-8023956.


text:
Q: Form-data parameters IBM API Connect error I'm using this gateway script, in IBM API Connect 5, to pass form-data parameters to a backend API.
All I'm getting is this 500 error code
{
"httpCode": "500",
"httpMessage": "Internal Server Error",
"moreInformation": "Invalid or unexpected token"
}
If someone could someone point me the right direction here please. I appreciate your time and help, thank you.
Here is the script:
var apim = require('./apim.custom.js');

apim.setvariable('message.headers.Content-Type','multipart/form-data; boundary=&&&&&&&&&&');
apim.setvariable('message.headers.accept','application/json;odata=verbose');

var grant_type = apim.getvariable('api.properties.property4');
var client_id = apim.getvariable('api.properties.property1');
var client_secret = apim.getvariable('api.properties.property2');
var resource = apim.getvariable('api.properties.property3');

var paramAsBlob = '--&&&&&&&&&&'+'\n'+'Content-Disposition: form-data; name="grant_type"'+'\n'+'\n'+grant_type+'\n'+'--&&&&&&&&&&'+'\n'+'Content-Disposition: form-data; name="client_id"'+'\n'+'\n'+client_id+'\n'+'--&&&&&&&&&&'+'\n'+'Content-Disposition: form-data; name="client_secret"'+'\n'+'\n'+client_secret+'\n'+'--&&&&&&&&&&'+'\n'+'Content-Disposition: form-data; name="resource"'+'\n'+'\n'+resource+'\n'+'--&&&&&&&&&&--' ;

var paramAsString = paramAsBlob.toString();

var longitud = paramAsString.length;

apim.setvariable('message.headers.Content-Length',longitud);

apim.setvariable('message.body', paramAsString);


text:
Q: Автоматическая корректировка ширины Label под Content На форме в определенном месте есть Label, которая показывает уведомления. Текст уведомления может быть разной длины. Поэтому надо корректировать ширину Label под длину текста.
Схема:

A: Пример верстки по указанной в вопросе схеме (Независимо от размера текста уведомление будет находиться снизу и по центру, но при этом над DataGrid):
<Window x:Class="WpfApp5.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp5"
        mc:Ignorable="d"
        Title="MainWindow" Height="200" Width="525">
    <Grid>
        <DataGrid>
            <DataGrid.Columns>
                <DataGridTextColumn Header="Колонка 1"/>
                <DataGridTextColumn Header="Колонка 2"/>
                <DataGridTextColumn Header="Колонка 3"/>
                <DataGridTextColumn Header="Колонка 4"/>
            </DataGrid.Columns>
        </DataGrid>
        <Border Margin="10" BorderThickness="1" BorderBrush="Orange" HorizontalAlignment="Center" VerticalAlignment="Bottom">
            <TextBlock Margin="5" Foreground="Red" TextWrapping="Wrap" Text="Тут находиться ваше уведомление с очень, ну прям очень, длинным текстом"></TextBlock>
        </Border>
    </Grid>
</Window>

Так выглядит разметка при таком XAML коде:

Дополнительно
Очень хороший сайт "professorweb.ru" с довольно понятным описанием работы с XAML и вообще WPF. Очень рекомендую почитать про верстку.


text:
Q: Binding event listeners multiple times in JavaScript I'm trying to get the directory list, level by level, using JavaScript.
I have this paths array as input.
var _paths = [];
_paths.push("meta1/meta2/test/home/myself/hi.jpg");
_paths.push("meta1/meta2/test/home/myself/hi1.jpg");
_paths.push("meta1/meta2/test/home/myself/hi2.jpg");
_paths.push("meta1/meta2/test/work/she/100.jpg");
_paths.push("meta1/meta2/test/work/she/110.jpg");
_paths.push("meta1/meta2/test/work/she/120.jpg");
_paths.push("meta1/meta2/test/work/hard/soft/she/120.jpg");
_paths.push("meta1/meta2/test/work/hard/soft/she/121.jpg");
_paths.push("meta1/meta2/test/work/she/220.jpg");

and I want to have a "test" as output, which will be clickable. After click "test", it should be replaced by "home" and "work". After click on "home" - "myself", on "work" - "hard" and "she".
I wrote this:
CodepenCode
and it works only once, only when clicking on "test".

A: Simply rebind the listeners after the directories have been drawn. You bind them only once, thus they work only once.
Wrap the binding function into a named function:
function bindListeners(){
  $('.sub').click(function() {
    word = $(this).text();
    filteredArr = findString(_paths, word);
    drawList(filteredArr, word);
  });
}

And call it at the end of drawList:
var drawList = function (paths, word) {
  var folders = getFolders(paths, word);
  if (folders.length > 0) {
    $('.canvas').html('');
    for (i = 0; i < folders.length; i++) {
      $('.canvas').append("
" + folders[i] + "

");
    }
  }
  bindListeners();
}

Demo.

A: If anyone is curious about building out the data structure:
(function iteratePaths() {
  var dirs = [];
  for(var i = 0; i < _paths.length; i++) {
    buildDirectories(dirs, _paths[i].split('/'));
  }
})();

function findDir(dir, obj) {
  for(var i = 0; i < dir.length; i++) {
    if(dir[i].name === obj.name) {
      return dir[i];
    }
  }
  return undefined;
}

function buildDirectories(dir, subs) {
  if(subs.length === 0) return;
  var obj = {name: subs.shift(), dirs: []};

  var existingDir = findDir(dir, obj);
  if(!existingDir) {
    dir.push(obj);
  }
  buildDirectories((existingDir || obj).dirs, subs);
}


text:
Q: Azure data studio will not reconnect to a locally hosted database I recently set up a docker container to host SQL server 2017 on my Mac. I am using Azure data studio as the GUI for the connection. Below you will find a link to see exactly how I setup this connection. Upon establishing the connection everything works great. I can even disconnect and reconnect to the locally hosted database.
When I restart my computer I cannot seem to reconnect to the local host. I open terminal and see that I my sql server studio database is running. I open Azure data studio and it will not automatically connect. I go into Azure connection and I specify local host, username "sa", the password and the port number. Azure will not connect to the docker container and locally hosted database.
I receive the following error message:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 40 - Could not open a connection to SQL Server)
If someone could help me out I would really appreciate it. I do not have to rebuild what I have currently done for school each time I restart my machine. Thank you.
Setup link:
https://adamwilbert.com/blog/2018/3/26/get-started-with-sql-server-on-macos-complete-with-a-native-gui

A: You'll have to re-start the docker container before connecting to the server using Azure Data Studio.
Open a terminal window and execute the command to start the SQL server on docker
sudo docker run -e 'ACCEPT_EULA=Y' -e 'MSSQL_SA_PASSWORD=YourStrong!Passw0rd' -p 1401:1433 --name sqlserver1 -d microsoft/mssql-server-linux:2017-latest

Next go to Azure Data Studio and connect to the database.


text:
Q: Media files exist in upload folder but not showing up In my wordpress, I tried to upload my images by media uploader but it says "couldn't create directory wp-content/uploads/2016/09". Then I create the folders correctly. And now when I tried to upload my files by media uploader, it says "couldn't move to directory wp-content/uploads/2016/09". Finally I uploaded my images in the folder and then checked the media library and the media library saying "no media founds".
Why is it happening?

A: You can use Media Sync for new updated plugin for the year 2020.
The plugin description reads

You can scan all files that are in "uploads" directory and see which
  ones are actually in Media Library and which ones are just sitting
  there. Then you can select those that you want to import to database
  and therefore make them available in Media Library.

A: Just by uploading files into the wp-content/uploads won't show up in the Media Library , those media ID's needs to be there in the database to show up in the Media Library.
If you already have files in the uploads folder and want to add them into the database, you can use this plugin to add files from server.
But this is not the correct solution instead fix the permissions issue for that uploads folder.

A: Media files exist in upload folder but not showing up
Simply Paste this code in wpconfig.php and save it all is done :)
but exactly where to paste?
define( 'UPLOADS', 'wp-content/'.'uploads' );


text:
Q: Debugging issue. Getting first 3 correct values and all others after are wrong Can someone explain to me why in my vector is returning wrong values? First 3 values are correct but after that I get some wrong values into. I tried to save the values of the shortest variable from Function findWaitingTime . by pushing this value into my order vector. This should save the process Id so later on I can print it. For some reason after 3rd saved value all next are wrong.
#include <bits/stdc++.h>
#include<vector>
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;

int count1=0;
vector<int>burstT;
vector<int>Order;

struct Process {
    int pid; // Process ID
    int bt; // Burst Time
    int art; // Arrival Time
};

// Function to find the waiting time for all
// processes
void findWaitingTime(Process proc[], int n,
                                int wt[])
{
    int rt[n];

    // Copy the burst time into rt[]
    for (int i = 0; i < n; i++)
        rt[i] = proc[i].bt;

    int complete = 0, t = 0, minm = INT_MAX;
    int shortest = 0, finish_time;
    bool check = false;

    // Process until all processes gets
    // completed
    while (complete != n) {

        // Find process with minimum
        // remaining time among the
        // processes that arrives till the
        // current time`
           for (int j = 0; j < n; j++) {
            if ((proc[j].art <= t) &&
            (rt[j] < minm) && rt[j] > 0) {
                minm = rt[j];
                shortest = j;
                check = true;

            }

        }

        if (check == false) {
            t++;
            continue;
        }
        Order.push_back(shortest);
        // Reduce remaining time by one
        rt[shortest]--;
        // Update minimum
        minm = rt[shortest];
        if (minm == 0)
            minm = INT_MAX;

        // If a process gets completely
        // executed
        if (rt[shortest] == 0) {

            // Increment complete
            complete++;
            check = false;

            // Find finish time of current
            // process
            finish_time = t + 1;

            // Calculate waiting time
            wt[shortest] = finish_time -
                        proc[shortest].bt -
                        proc[shortest].art;

            if (wt[shortest] < 0)
                wt[shortest] = 0;

        }
        // Increment time
        t++;

    }
}

// Function to calculate turn around time
void findTurnAroundTime(Process proc[], int n,
                        int wt[], int tat[])
{
    // calculating turnaround time by adding
    // bt[i] + wt[i]
    for (int i = 0; i < n; i++){
        tat[i] = proc[i].bt + wt[i];

        burstT.push_back(proc[i].bt);
    }
}

// Function to calculate average time
void findavgTime(Process proc[], int n)
{
    int wt[n], tat[n], total_wt = 0,
                    total_tat = 0;

    // Function to find waiting time of all
    // processes
    findWaitingTime(proc, n, wt);

    // Function to find turn0 around time for
    // all processes
    findTurnAroundTime(proc, n, wt, tat);

    // Display processes along with all
    // details
    cout << "Processes "
        << " Burst time "
        << " Waiting time "
        << " Turn around time\n";

    // Calculate total waiting time and
    // total turnaround time
    for (int i = 0; i < n; i++) {

        total_wt = total_wt + wt[i];
        total_tat = total_tat + tat[i];
        cout << " " << proc[i].pid << "\t\t"
            << proc[i].bt << "\t\t " << wt[i]
            << "\t\t " << tat[i] << endl;

    }

    cout << "\nAverage waiting time = "
        << (float)total_wt / (float)n;
    cout << "\nAverage turn around time = "
        << (float)total_tat / (float)n;
}

int main(int argc, char * argv)
{
    int arrSize=0;
    vector<Process> procs;
    vector<Process> proc;
        int element1, element2, element3;
        char comma;
        ifstream infile("jobs.txt");

if (!infile.is_open()) {
    cerr << "Can't open file" << endl;
}
else {
    while (infile >> element1 >> comma >> element2 >> comma >> element3)
    {
        Process proc{element1, element2, element3};
        procs.push_back(proc);
    }
}
    arrSize=procs.size();
cout << procs.size() << endl;

    int n = sizeof(proc) / sizeof(proc[0]);

  findavgTime(procs.data(), static_cast<int>(procs.size()));
int arrivalT=0;

cout<<endl;
     for(int i=0;i<arrSize;i++){
         sort(burstT.begin(), burstT.end());
         arrivalT=arrivalT+burstT[i];
         cout << Order[i]+1<< "(" << arrivalT <<  "),";

    }
    return 0;
}

Input file :
1,18,3
2,5,1
3,14,5
4,1,1
5,17,0
6,2,6
7,6,2
8,15,7
9,20,0
10,6,8
11,18,0
12,2,1
13,3,5
14,2,3
15,2,0
16,7,3
17,20,4
18,4,4
19,17,9
20,1,0

Printing vector Output:
20(1),4(2),12(4),12(6),14(8),14(10),6(13),6(17),15(22),15(28),13(34),13(41),
13(55),18(70),18(87),18(104),18(122),2(140),2(160),2(180),

How the output should be:
20(1),4(2),12(4),14(6),6(8),15(10),13(13),18(17),2(22),7(28),10(34),16(41),
3(55),8(70),5(87),19(104),1(122),11(140),9(160),17(180)


text:
Q: SSH doesn't work through mikrotik I have Mikrotik RB952Ui-5ac2nD. Everything is working fine.
But now, I found little problem.
I can not connect from LAN to any SSH in internet, but, when I'm connected without mikrotik, i havent any problem.
If I'm conecting to SSH in internet from mikrotik terminal, I will connect without probelms. But If I want connect from pc behind mikrotik I haven't got any response-
I have configured only nat masquarade in firewall.
Do you know, what I need to solve that, please?
Thank you


text:
Q: What happened to Dark Helmet, Colonel Sandurz and President Skroob? After they landed on the Planet of the Apes, what happened to Dark Helmet, Colonel Sandurz and President Skroob?
Were they captured and forced into ape slavery? Was there ever a description of their ultimate fate?

A: They went on to further adventures in Spaceballs: the Animated Series.
Including opening casinos, playing video games and cloning dinosaurs.

A: We don't have enough information to come to any conclusions, but the apes themselves clearly assume that the Spaceballs will have the upper hand:

1ST APE
  Dear me, what are those things coming out of her nose?
The 2ND APE looks through binoculars. He sees COL SANDURZ on the ground, DARK HELMET is climbing down a rope, followed by SKROOB. SKROOB steps on DARK HELMET'S helmet.
DARK HELMET
  (mask up) Hey, hey, watch my helmet.
The 2ND APE stops looking in the binoculars.
2ND APE
  Spaceballs?
1ST APE
Oh shit, there goes the planet.

Being experienced bureaucrats, it seems likely that the Spaceballs will soon be destroying their new planet.

A: According to an interview with George Wyner (the actor who portrayed Colonel Sandurz), there was in fact some additional ending material that was filmed but never made it into the final cut:

Q. ...What do you think happened to Colonel Sandurz when he found
  himself on a planet of apes?
George Wyner: We actually filmed an ending that was never used. After the escape pod lands, and President Scroob, Dark Helmet, and
  Colonel Sandurz climb safely out, the three of them march down the
  beach together. President Scroob asks, "Where are we?" Colonel Sandurz
  answers, "California," and President Scroob barks out, "Let's pollute
  it!".
Scroob, along with his trusted aides Dark Helmet and Colonel Sandurz,
  made a fortune polluting California, and is now considering running
  for president.


text:
Q: R - Passing a vector argument to reference columns of a data frame in a function Here is an example of the problem I am trying to solve.
I have a data frame
x<-matrix(1:9, nrow= 3, ncol= 3)
y<-c(1,100,2)
z<-c("A","B","C","D")
df<-cbind(x,y)
colnames(df)<-z

     A B C  D
[1,] 1 4 7 1
[2,] 2 5 8 100
[3,] 3 6 9 2

For each row, I want to calculate distance between each of the values in A,B, and C with D to find the two values from A, B and C closest to D.
This was my latest attempt.
test<-function(x,y,z){
  d<-abs(x-y)
  df<-data.frame(z,d)
  df<-df[order(d),]
  d<-c(df[1:2,1])
  d<-paste(d[1],"-",d[2],sep="")
}

results<adply(test, 1, transform, res = test(
  c("A","B","C"),D,1:3]))

This is the error I am getting
Error in splitter_a(.data, .margins, .expand, .id) : Invalid margin

I am wanting the result to be a data frame like this:
     A B C  D res
[1,] 1 4 7 25 A-B
[2,] 2 5 8 26 C-B
[3,] 3 6 9 27 A-B

Any help provided is greatly appreciated.
NT
Edit - The suggested answer worked in my test case, but does not work when translated to me real scenario. Here is a sample of the DF
    0%      25%     50%      75%   100% target
1 350.00 350.0000 380.610 380.6100 416.25  425.0
2 350.00 350.0000 350.000 350.0000 350.00  425.0
3 223.83 383.6800 414.890 472.3050 529.20  425.0
4 442.36 442.9625 443.565 444.1675 444.77  472.8
5 466.00 525.4800 529.200 529.2000 529.20  465.6
6 350.00 357.1650 364.330 371.4950 378.66  513.6

This is how the script translates to me scenario
apply(DF, 1, function(x){
  paste(c("0%","25%","50%","75%","100%")[order(abs(x[c(columns[1:5])] - x["target"]))][1:2], collapse = "-")
})

I am getting the following error:
Error in x[c(columns[5:9])] - x[target] :
  non-numeric argument to binary operator

I have confirmed the data values are numeric

A: apply(df, 1, function(x){
    paste(c("A", "B", "C")[order(abs(x[c("A", "B", "C")] - x["D"]))][1:2], collapse = "-")
})
#[1] "A-B" "C-B" "A-B"

UPDATE
#DATA
df = read.table(strip.white = TRUE,
                stringsAsFactors = FALSE,
                header = TRUE,
                check.names = FALSE,
                text = "0%      25%     50%      75%   100% target
                1 350.00 350.0000 380.610 380.6100 416.25  425.0
                2 350.00 350.0000 350.000 350.0000 350.00  425.0
                3 223.83 383.6800 414.890 472.3050 529.20  425.0
                4 442.36 442.9625 443.565 444.1675 444.77  472.8
                5 466.00 525.4800 529.200 529.2000 529.20  465.6
                6 350.00 357.1650 364.330 371.4950 378.66  513.6")

apply(df, 1, function(x){
    paste(names(x)[order(abs(x[1:5] - x[6]))][1:2], collapse = "-")
})
#         1          2          3          4          5          6
#"100%-50%"   "0%-25%"  "50%-25%" "100%-75%"   "0%-25%" "100%-75%"


text:
Q: ZF2 - Record not existing I try to use the zf2 db validator to check if a record does not exist.
I set the follow code in my controller:
$validator = new NoRecordExists(
                array(
                    'table'   => 'topics',
                    'field'   => 'topic',
                )
            );

after this configuration I try to validate but I got 'an error occurred', can't find any other error output who can tell me more about this error.
var_dump($validator->isValid('test'));

If someone can give me some tips, would be great :)
thx

A: Have you set the DB Adapter?
You can pass it in the contructor or called setAdapter();
validator->setAdapter(
    $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter')
);

You could set this up in your service config to automatically inject the adapter for you.


text:
Q: Updating cell values for selected rows in a DataGridView with value from drop down box I have a DataGridView and I want to change the value in cells of selected rows to the value selected in a drop-down box. It is always the cells in the 3rd column.
My code is:
private void updateSelected_Click(object sender, EventArgs e)
{
     foreach (DataGridViewRow i in dataGridView1.SelectedRows)
     {
          dataGridView1[2, i].Value = Combo.Text;
     }
     this.BindingContext[dataGridView1.DataSource].EndCurrentEdit();
}

However, I am getting the following error:

CS1503 Argument 2: cannot convert from 'System.Windows.Forms.DataGridViewRow' to 'int'

I have it working to update ALL rows:
    private void updateExcel_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < dataGridView1.RowCount - 1; i++)
        {
            if (!RowIsEmpty(i))
            {
                dataGridView1[2, i].Value = Combo.Text;
            }
        }
    }

A: i is a DataGridViewRow not a row-number:
 foreach (DataGridViewRow i in dataGridView1.SelectedRows)
 {
      i.Cells[2].Value = Combo.Text;
 }


text: Q: How to put datagridview data into datatable? C# I have datagridview but i want to put the datagridview data to datatable which will be accessed by crystal report using dataset. the datatable is inside the dataset.


text:
Q: MediaPlayer crashes on setDataSource with R.raw audio I'm making an Audio Player app that will load some predefined audios from inside its raw resource folder.
I've sent the test APK for some people to test it, and it worked on 99% of the cases. But then, I started to get some crash reports on Crashlytics for a single device, the OnePlus A5000, running Android 8.1.0.
The stacktrace on crashlytics is as follows:
Fatal Exception: java.lang.IllegalStateException
       at android.media.MediaPlayer._setDataSource(MediaPlayer.java)
       at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1270)
       at com.example.home.MediaPlayerHolder.loadMedia(MediaPlayerHolder.kt:56)
       at com.example.home.HomePresenter.playSound(HomePresenter.kt:26)
       at com.example.home.HomeFragment.onPlaySelected(HomeFragment.kt:178)
       at com.example.home.SoundItemAdapter$ViewHolder$bind$1.onClick(SoundItemAdapter.kt:30)

package names were changed for privacy reasons
This is happening almost every time he clicks on the sound item play button. It also happens on the first time he clicks on any sound item.
I've tried to reproduce this crash on some devices, all of then have API <= 25, but I had no success doing so. All of them ran without an issue. I'm clueless of the probable cause of this error, or even if it's an edge case problem, or if there's indeed something wrong with my code.
This is how I'm loading the audio on the MediaPlayer:
if (mediaPlayer?.isPlaying == true) {
    mediaPlayer?.release()
    mediaPlayer = null
}
if (mediaPlayer == null) {
    mediaPlayer = MediaPlayer()
}

val fileDescriptor = context.resources.openRawResourceFd(resource)
mediaPlayer?.setDataSource(fileDescriptor.fileDescriptor, fileDescriptor.startOffset, fileDescriptor.length)
fileDescriptor.close()
mediaPlayer?.prepare()
mediaPlayer?.start()

A: The reason was you can't start services in the background anymore after API 26. So you have to start ForegroundService above API 26.


text:
Q: Can you purposely delay the sound inside the Windows OS backwards? I got a pair of google max speakers which are hooked up via a 3.5 mm jack but they stream the audio input to each other and split it into a right and left channel which introduces a delay of 1 to 1.5 seconds when for example clicking the windows soundbar in the taskbar when changing the volume. Same thing when I brows the web and watch videos etc.
My question is if it is possible for windows to somehow compensate and put the audio that is getting played about 1 second back in time? Think of a video editing software where you slide the audio track to the left side to compensate for the audio delay so that the video syncs up with the sound.
I would loose those first second/s in the beginning but I can live with that. That is a lot better than a audio track which is painfully behind the video track.
Or is it possible to do this in for example Ubuntu?
Thanks in advance for the input!

A: First, there is a Bluetooth cache delay setting for the speakers, "You have to change this in developer settings. It can be unlocked by clicking the build number several times."
There are also media players such as MPC-HC, which works well in wine, Snap or built for Ubuntu, which can delay audio or video to resync them. That said, a one-second delay is a bit much to fix, and if the cache delay varies, then it will be impossible to sync well.


text:
Q: Turning a result from a query into a PHP variable The query below is on a page where there is only one value for $submissionid.  Thus, the field points has only one value.
How can I turn the points from the query below into a regular PHP variable?
  $sqlStra = "SELECT points, submissionid
               FROM submission
              WHERE submissionid = '$submissionid'";

EDIT: This is pulling from a MySQL database.
EDIT II: I want to points to equal a variable on the entire page, not just inside of a while loop.

A: In this way you can read all the points returned by your query.
while ($row = mysql_fetch_array($sqlStra, MYSQL_ASSOC)) {
    $points = $row["points"]);
}

A: I would use an ORM library (I use the one that comes bundled with Kohana) to eliminate the possibility of SQL injections. However, assuming a database connection is already established, this code will do what you are looking for.
$resource = mysql_query("SELECT points, submissionid FROM submission WHERE submissionid = '$submissionid'");
$result = mysql_fetch_assoc($resource);
echo $result["points"];

If you don't have a MySQL database connection established, check out mysql_connect.

A: Well, you'll want to get a resource from that query and then give it to mysql_fetch_assoc, like so:
$res = mysql_query($sqlStra);

// If you **Know for sure** you'll only have one row:
$row = mysql_fetch_assoc($res);
$points = $row['points'];

//Otherwise, you're going to need to loop.
$array_of_all_points = array();

while ($row = mysql_fetch_assoc($res)) {
    // $row['points'] now has what you want. You can assign it normally, or can use
    // extract($row) to turn it into $points, which I would advise against personally.
    $points = $row['points'];
    $array_of_all_points[$row['submissionid']] = $row['points'];
}

echo $points; // This will be the last $row['points'] that was executed.
echo $array_of_all_points['thatsubmissionid']; // Will output the points for the given session id.

Also, that query isn't safe (if $submissionid comes from user input, it is vulnerable to SQL injection), you should use an ORM library as iloveitaly mentions. (I use Zend DB, though it's not technically ORM by itself)
Edit:
As the comments point out, this depends on if you're actually using Mysql. If you're not, you can use the PDO library to do your querying.

A: $sqlStra = "SELECT points FROM submission WHERE submissionid = ?";

$statement = $connection->prepare($sqlStra);
$statement->bind_param('i', $submissionid);
$statement->bind_result($points);
$statement->execute();
$statement->fetch(); // this will create / populate $points


text: Q: What does the series expansion look like when $\ln(1+x)$ is $x>1$? I know that $\ln(1+x)$ can be expanded by Taylor at $x\in(-1,1)$, and the expanded sequence diverges. However, according to the definition, as long as the function is analytic at a certain point and its neighborhood, then it can be expanded at this point, and $\ln(1+x)$ is indeed non-analytic when $x\le -1$ cannot be expanded, but when $x\ge1$, the function is analytic. What does the series expansion expression of this function look like? If it cannot be expanded, why?


text:
Q: Skip initial scan for tailable cursor queries with awaitdata=true and storage engine wiredTiger I am using the mongodb oplog.$main collection in a single master instance for even streaming in my app. When my app starts, it queries the oplog collection with a tailable cursor waiting for new data, but mongo cpu spikes because this query scans the full oplog collection (which in my case is 25GB). From mongodb documentation:

*

*Because tailable cursors do not use indexes, the initial scan for the query may be expensive; but, after initially exhausting the cursor, subsequent retrievals of the newly added documents are inexpensive.

Is there any way to skip the initial scan of the query? I am only interested in new documents added to oplog.
I have tried with {oplogReplay: true} and the filter {ts: {$gt: lastOplogTime}}, but the mongo CPU still spikes. I am using mongo 3.0.3 with storage engine wiredTiger. Also, using sort({$natural: -1}) does not work since I get this error from mongo:

*

*invalid sort specified for tailable cursor: { $natural: -1 }.

Looks like the sort error is due to be using wiredTiger.
Any help is much appreciated. Thanks!


text:
Q: MySQL save error without error <?php
include("pass.php");
session_start();

if(isset($_SESSION["login"])) {
    require_once ('connect.php');

    $not = $_POST["not"];

    if($not=="") {
        header("location:mybbeklents/admin/dashboard.php?cmd=1");
    } else {
        mysql_query("INSERT INTO notlar (not,) VALUES ('$not')");
        header("location:mybbeklents/admin/dashboard.php?cmd=2");
    }
}
?>

This code doesn't work. They don't get saved into MySQL.

A: query should be
mysql_query("INSERT INTO notlar (`not`) VALUES ('$not')");

A: Try
mysql_query("INSERT INTO notlar (`not`) VALUES ('$not')")
OR die('MySQL error: '.mysql-error());

That echoes the error, if any occurs.
Note: Your query in insecure. Use mysqli or PHP PDO or at least unescape your variables before passing them to the query.

A: Change
$not = mysql_real_escape_string($_POST["not"]);

and
mysql_query("INSERT INTO notlar (not) VALUES ('$not')");

If this works, take your time and read a bit on sql injection and the outdated mysql extension. It is really easy to drop your database the way your code looks right now.
You can solve both issues in your code using PDO. you'll find more information on PDO here:
http://www.phptherightway.com/#security


text:
Q: Time difference in Javascript I have a textbox where I get the time as HH:MM AM/PM (like 5:30 PM). I want to validate the time: whether it is 1 hour greater than the current time or not. How can I do this using JavaScript?

A: First of all, I'd suggest using an existing date-handling library like Datejs. You will have the benefit if a time-tested library with a comprehensive set of methods.
With Datejs, your answer is as simple as:
Date.parse(timeText).isAfter((new Date()).addHours(1));

If you'd rather not use Datejs, you can use regular expressions to parse the time before validating it. I've written a set of functions, along with unit tests which run in the Firebug console, that do just that:
function isOneHourGreater(timeText, time) {
  var parsedTime = parseTime(timeText);
  if (parsedTime === null) { return null; }
  return (parsedTime.getTime() - time.getTime()) > (1 * 60 * 60 * 1000);
}

function parseTime(timeText) {
  timeText = timeText.replace(/^\s+|\s$/g, '');
  var regex = /^(\d{1,2}):(\d{1,2})\s*(am|pm)$/i;

  if (!regex.test(timeText)) { return null; }

  var
    timeParts = regex.exec(timeText)
    , hours = parseInt(timeParts[1])
    , ampm = timeParts[3].toLowerCase()
    , hoursOffset = (ampm === 'pm' && hours !== 12) ? 12 : 0;

  hoursOffset = (ampm === 'am' && hours === 12) ? -12 : hoursOffset;

  return getTodayWithTime(
    hours + hoursOffset
    , parseInt(timeParts[2])
  );
}

function getTodayWithTime(hours, minutes) {
  var today = new Date();
  today.setHours(hours);
  today.setMinutes(minutes);
  today.setSeconds(0);
  today.setMilliseconds(0);
  return today;
}

function parseTimeTests() {
  var now = new Date();

  var tests = [
    {target: "12:00 am", expected: getTodayWithTime(0, 00)}
    , {target: "12:01 am", expected: getTodayWithTime(0, 01)}
    , {target: "12:00 pm", expected: getTodayWithTime(12, 00)}
    , {target: "12:01 pm", expected: getTodayWithTime(12, 01)}
    , {target: "1:30 Pm", expected: getTodayWithTime(13, 30)}
    , {target: "10:59 Pm", expected: getTodayWithTime(22, 59)}
    , {target: "0:30 Pm", expected: getTodayWithTime(12, 30)}
    , {target: "1:40 aM", expected: getTodayWithTime(1, 40)}
    , {target: " 6:15  am ", expected: getTodayWithTime(6, 15)}
    , {target: " 6:15am ", expected: getTodayWithTime(6, 15)}

    , {target: "006:15am", expected: null}
    , {target: "06:015am ", expected: null}
    , {target: "06:15amm ", expected: null}
    , {target: "a6:15am ", expected: null}
    , {target: "6: 15am", expected: null}
    , {target: "6:15", expected: null}
  ];

  for (var ii = 0; ii < tests.length; ii++) {
    var test = tests[ii];

    var actual = parseTime(test.target);

    console.assert(
      (actual === null && actual === test.expected)
      || (actual && test.expected && actual.getTime() === test.expected.getTime())
      , ii + 1 + " Failed"
      , test.target, test.expected, actual
    );
  }

  console.log('done');
}
parseTimeTests()

function isOneHourGreaterTests() {
  var mockTime = getTodayWithTime(14, 00);

  var tests = [
    {target: "3:01 pm", expected: true}
    , {target: "3:30 pm", expected: true}
    , {target: "11:59 pm", expected: true}
    , {target: "10:30 pm", expected: true}

    , {target: "2:59 pm", expected: false}
    , {target: "2:01 pm", expected: false}
    , {target: "2:30 pm", expected: false}
    , {target: "2:00 pm", expected: false}
    , {target: "10:30 am", expected: false}
    , {target: "1:40 pm", expected: false}
    , {target: "1:15 pm", expected: false}
    , {target: "6:15 am", expected: false}

    , {target: "a6:15 am", expected: null}
  ];

  for (var ii = 0; ii < tests.length; ii++) {
    var test = tests[ii];

    var actual = isOneHourGreater(test.target, mockTime);

    console.assert(
      (actual === null && actual === test.expected)
      || (actual === test.expected)
      , ii + 1 + " Failed"
      , test.target, test.expected, actual
    );
  }

  mockTime = getTodayWithTime(23, 00);

  tests = [
    {target: "1:01 am", expected: false}
    , {target: "12:01 am", expected: false}
    , {target: "2:30 am", expected: false}

    , {target: "11:59 pm", expected: false}
    , {target: "11:00 pm", expected: false}
    , {target: "11:01 pm", expected: false}

    , {target: "2:30 pm", expected: false}
    , {target: "2:00 pm", expected: false}
    , {target: "10:30 am", expected: false}
    , {target: "1:40 pm", expected: false}
    , {target: "1:15 pm", expected: false}
    , {target: "6:15 am", expected: false}

    , {target: "a6:15 am", expected: null}
  ];

  for (var ii = 0; ii < tests.length; ii++) {
    var test = tests[ii];

    var actual = isOneHourGreater(test.target, mockTime);

    console.assert(
      (actual === null && actual === test.expected)
      || (actual === test.expected)
      , ii + 1 + " Failed"
      , test.target, test.expected, actual
    );
  }

  console.log('done');
}
isOneHourGreaterTests();


text:
Q: Creating table when using in-memory database I am using Hibernate for connecting to derby . i am using derby as an in-memory database for my application. I am completely new to hibernate and derby stuff. I have two xml files, sample.cfg.xml and sample.hbm.xml. The sample.hbm.xml contains the mapping between the table and the bean class. I am setting the in-memory db as follows:
       Dialect = org.hibernate.dialect.DerbyDialect
       DriverClassName = org.apache.derby.jdbc.EmbeddedDriver
       Url= jdbc:derby:unitTestDB;create=true
       UserName = ""
       Password=""

My question is , will the table be automatically created ? (by using the sample.hbm.xml as a reference) or do i need to create the table separately ? Pardon my ignorance as i am completely new to this.

A: By default tables are not automatically created. Tables will be created if you advice Hibernate to do so by giving needed value for hibernate.hbm2ddl.auto attribute in configuration (properties in same place where you have other properties that you listed in query).
Most likely for development create-drop is best options in general, every time you deploy you will start with fresh database. For in-memory it is of course always fresh. Other options are: validate, update and create.


text:
Q: Ensemble of custom and pre-trained model gives run-time error I'm attempting to create an ensemble of a custom CNN and pre-trained VGG16 for a medical image classification task using Keras with Tensorflow backend (TF: 1.9.0 and Keras: 2.1.6). The code is as given below:
#load libraries
from keras.models import Model, Input
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D, Activation, Average, Dense
from load_data import load_resized_training_data, load_resized_validation_data
from load_data import load_resized_test_data
from keras.losses import categorical_crossentropy
from keras.callbacks import ModelCheckpoint, TensorBoard
from keras.optimizers import Adam
from keras.applications.vgg16 import VGG16
import numpy as np
################################################################################
#load data
batch_size = 8
num_epochs = 1
img_rows= 224
img_cols = 224
num_channels = 3
num_classes = 2

X_train, Y_train = load_resized_training_data(img_rows, img_cols)
X_valid, Y_valid = load_resized_validation_data(img_rows, img_cols)
X_test, Y_test = load_resized_test_data(img_rows, img_cols)
print(X_train.shape, Y_train.shape, X_valid.shape, Y_valid.shape,X_test.shape, Y_test.shape)
X_train = X_train.astype('float32')
X_valid = X_valid.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_valid /= 255
X_test /= 255
###############################################################################
'''Since the two models work with the data of the same shape,
it makes sense to define a single input layer that will be used by every model.'''
input_shape = X_train[0,:,:,:].shape
print(input_shape) # 224, 224, 3
model_input = Input(shape=input_shape)
print(model_input) # Tensor("input_1:0", shape=(?, 224, 224, 3), dtype=float32)

###############################################################################
'''define the first model: a simple sequential model in the form of functional api'''

x = Conv2D(16, kernel_size=(3, 3), activation='relu')(model_input)
x = MaxPooling2D((2, 2))(x)
x = Conv2D(32, (3, 3), activation='relu')(x)
x = MaxPooling2D((2, 2))(x)
x = Conv2D(64, (3, 3), activation='relu')(x)
x = MaxPooling2D((2, 2))(x)
x = Conv2D(128, (3, 3), activation='relu')(x)
x = MaxPooling2D((2, 2))(x)
x = Conv2D(256, (3, 3), activation='relu')(x)
x = MaxPooling2D((2, 2))(x)
x = Conv2D(512, (3, 3), activation='relu')(x)
x = Conv2D(2, (1, 1))(x)
x = GlobalAveragePooling2D()(x)
x = Activation(activation='softmax')(x)

custom_model = Model(inputs=model_input, outputs=x, name='custom_cnn')
###############################################################################
def compile_and_train(model, num_epochs):

    model.compile(loss=categorical_crossentropy, optimizer=Adam(), metrics=['acc'])
    filepath = 'weights/' + model.name + '.{epoch:02d}-{val_acc:.2f}.hdf5'
    checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_weights_only=True, save_best_only=True, mode='auto', period=1)
    tensor_board = TensorBoard(log_dir='logs/', histogram_freq=0, batch_size=batch_size)
    history = model.fit(X_train, Y_train, batch_size=batch_size, epochs=num_epochs, verbose=1, callbacks=[checkpoint, tensor_board], validation_data=(X_valid, Y_valid))
    return history

#compile and train the model
_ = compile_and_train(custom_model, num_epochs=num_epochs)
###############################################################################
def evaluate_error(model):
    pred = model.predict(X_test, batch_size = batch_size)
    pred = np.argmax(pred, axis=1)
    pred = np.expand_dims(pred, axis=1) # make same shape as y_test
    error = np.sum(np.not_equal(pred, Y_test)) / Y_test.shape[0]

    return error

evaluate_error(custom_model)
###############################################################################
'''second model is a pretrained vgg16 model initialized with imagenet weights and going to be trained from the first layer'''

vgg16_model = VGG16(weights='imagenet', include_top=False, input_shape=(img_rows, img_cols, 3))
x = vgg16_model.output
x = GlobalAveragePooling2D()(x)
predictions = Dense(num_classes, activation='softmax')(x)
vgg16_custom_model = Model(inputs=vgg16_model.input, outputs=predictions, name='vgg16_cnn')

#compile and train the model
_ = compile_and_train(vgg16_custom_model, num_epochs=num_epochs)

#Evaluate the model by calculating the error on the test set
evaluate_error(vgg16_custom_model)
###############################################################################
custom_model.load_weights('weights/custom_cnn.01-0.60.hdf5')
vgg16_custom_model.load_weights('weights/vgg16_cnn.01-0.50.hdf5')

models = [custom_model, vgg16_custom_model]
###############################################################################
def ensemble(models, model_input):

    outputs = [model.outputs[0] for model in models]
    y = Average()(outputs)

    model = Model(inputs=model_input, outputs=y, name='ensemble')

    return model

ensemble_model = ensemble(models, model_input)
evaluate_error(ensemble_model)
###############################################################################

The code works all fine until the creation of the ensemble definition. When defining the ensemble I get the following error:
RuntimeError: Graph disconnected: cannot obtain value for tensor Tensor("input_7:0", shape=(?, 224, 224, 3), dtype=float32) at layer "input_7". The following previous layers were accessed without issue: []

I am not sure whether I can pass model_input to the pre-trained VGG16 in this manner. How the ensemble definition needs to be modified?

A: The problem is that the input of VGG model is not being fed by the input layer of ensemble_model. To resolve this issue, you need to modify the definition of ensemble_model and create a new input layer which is then passed to the two models:
def ensemble(models):
    input_img = Input(shape=input_shape)

    outputs = [model(input_img) for model in models] # get the output of model given the input image
    y = Average()(outputs)

    model = Model(inputs=input_img, outputs=y, name='ensemble')
    return model

ensemble_model = ensemble(models)


text:
Q: limiting distribution of Xbar considering an autoregressive process Here is the question:
Consider the stationary Gaussian autoregressive process of order 1,
$X_{i+1} − μ = ρ(X_i − μ) + \sigma Z_i$, where $Z_i$ are iid N(0, 1). Find the
limiting distribution of $\overline{X}$ assuming |ρ| < 1.
Here is what I have so far:
$X_{i+1} − μ = ρ(X_i − μ) + \sigma Z_i$
$\sum (X_{i+1} − μ) = \sum (ρ(X_i − μ) + \sigma Z_i)$
$\sum(X_{i+1}) − nμ = ρ\sum(X_i) − n\rhoμ+ \sigma \sum(Z_i)$
$(X_1-X_1+X_2+X_3+...+X_{i+1} − nμ =ρ\sum(X_i) − n\rhoμ+ \sigma \sum(Z_i)$
by expanding sum
$\sum X_i+X_{i+1}-X_1-n\mu=ρ\sum(X_i) − n\rhoμ+ \sigma \sum(Z_i)$
dividing both sides by n
$\overline{X}+\frac{X_{i+1}-X_1}{n}-\mu=ρ\overline{X} − \rhoμ+ \sigma \overline{Z}$
$\overline{X}-\rho\overline{X}= \mu -\rho \mu +\sigma \overline{Z}-\frac{X_{i+1}-X_1}{n}$
$\overline{X}(1-\rho)=\mu(1-\rho)+\sigma \overline{Z}-\frac{X_{i+1}-X_1}{n}$
$\overline{X}= \mu+\frac{\sigma \overline{Z}-\frac{X_{i+1}-X_1}{n}}{1-\rho}$
But now I am stuck... I know that $\overline{Z}$ converges to N(0,1) but I am not sure what to do now.
Any help is appreciated!

A: Correction: sorry, my previous explanation was wrong.
Something is not right in your computation as the final term converges to zero and not to a random variable. I guess you want to consider $\sqrt{n}(\bar{X}-\mu)$ to get a CLT. Again, using Slutskys Theorem should work, but please clarify your intention first.


text:
Q: Migrating up to Rails 3.1.3, all images inaccessible in production All my images are inaccessible on production env after upgraded to rails 3.1.3 from 3.0.3. Even if I manually go to http://localhost:3000/rails.png and put the image file to public/ I get Routing Error. Same thing if I moved it to public/images when accessing to localhost:3000/images/rails.png.
I'm not sure it's misconfigured asset settings. I tried following similar thread in Stack overflow with no luck. Here are my Gemfile and my config files.
The Gemfile
source 'http://rubygems.org'
gem "rails", "3.1.3"
gem "pg", :require => "pg"
gem "devise", "~> 1.5.2"
gem "cancan"
gem "hoptoad_notifier", '2.4.11'
gem "friendly_id", "~> 3.1"
gem "will_paginate", "~> 3.0.2"
gem "haml", "~> 3.1.3"
gem "haml-rails"
gem "yard"
gem "bluecloth"
gem "simple_form", '~> 1.3.1'
gem "paperclip"
gem "jquery-rails"
gem 'twitter-bootstrap-rails'
gem 'thin'

group :assets do
  gem 'sass-rails', " ~> 3.1.5"
  gem 'coffee-rails', " ~> 3.1.0"
  gem 'uglifier'
end

group :development, :test do
  gem "rspec-rails", "~> 2.7.0"
  # gem 'remarkable_activerecord', '~> 4.0.0.alpha4'
  gem "maksar-remarkable_activerecord", "~> 4.0.0.alpha6"
  gem "faker"
  gem "evergreen", :require => "evergreen/rails"
  gem 'pry'
end

group :development do
  gem "rails3-generators"
  gem "hpricot"
  gem "ruby_parser"
end

group :test, :cucumber do
  gem "factory_girl_rails"
  gem "database_cleaner"
  gem "timecop"
  gem "pickle"
  gem "spork", "~> 0.9.0.rc2"
end

group :cucumber do
  gem "cucumber"
  gem "cucumber-rails"
  gem "capybara", "~> 0.4.0"
  gem "launchy"
end

group :test do
  gem "mocha"
  gem "autotest"
  gem "autotest-rails"
end

application.rb
module MyTutorial
  class Application < Rails::Application
    # ... other config...
    # Enable the asset pipeline
    config.assets.enabled = true

    # Version of your assets, change this if you want to expire all your assets
    config.assets.version = '1.0'
    config.assets.initialize_on_precompile = false
  end
end

production.rb
MyTutorial::Application.configure do
  # Settings specified here will take precedence over those in config/application.rb

  # The production environment is meant for finished, "live" apps.
  # Code is not reloaded between requests
  config.cache_classes = true

  # Full error reports are disabled and caching is turned on
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  # Disable Rails's static asset server (Apache or nginx will already do this)
  config.serve_static_assets = false

  # Compress JavaScripts and CSS
  config.assets.compress = true

  # Don't fallback to assets pipeline
  config.assets.compile = true

  # Generate digests for assets URLs
  config.assets.digest = false

  # Specify the default JavaScript compressor
  config.assets.js_compressor  = :uglifier

  # Specifies the header that your server uses for sending files
  config.action_dispatch.x_sendfile_header = "X-Sendfile"
end

A: You are probably getting a routing error because when the pipeline is enabled it is assumed that all assets are in the pipeline. You will have image tag helpers somewhere that cannot find the required asset.
With the setting you have (compile = true) all requests for assets are passed to Sprockets.
All assets appear in the path /assets by default. You should also change these two lines:

config.assets.compile = true
config.assets.digest = false

to this:

config.assets.compile = false
config.assets.digest = true

And run the precompile task before testing.
You should also remove the x_sendfile_header option. Production servers need to be specially set up to use this, and some servers don't support it (giving you blank images).
You can check your settings against those shown in the last section of the asset pipeline guide.
Once you have the settings above fixed, delete the sprockets cache in tmp/cache/assets/ and restart your server.

A: Open your to production.rb and then,
config.serve_static_assets = true


text:
Q: This JSON string won't get deserialized We're trying to deserialize the following JSON string:
string responseData = "{\"status\":\"2000\",\"data\":[{\"response\":{\"TrxId\":4972783,\"result\":1,\"accruedPoints\":null}}],\"error\":null}";

var dic = JsonConvert.DeserializeObject<Dictionary<object, object>>(responseData);
object value, error, oData;

dic.TryGetValue("status", out value);
dic.TryGetValue("data", out oData);
string status = Convert.ToString(value);
string data = Convert.ToString(oData);
Dictionary<string, string> result = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);

We're facing problems deserializing data. Following is the exception:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.Object,System.Object]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

Is there a better way to deserialize this JSON object?
We need the accruedPoints value.


text:
Q: Bandwidth 'silverman' or 'scott' in sklearn.neighbors.KernelDensity causes TypeError: '<=' not supported between instances of 'str' and 'int' I am using sklearn's KernelDensity Estimator on a simple series.
When I try to fit a KDE, I get the "TypeError: '<=' not supported between instances of 'str' and 'int'" if I use 'silverman' or 'scott' as bandwidth instead of a float.
From the documentation I can see however that both 'silverman' and 'scott' are supported.
Any input is greatly appreciated :)
Below my code:
from sklearn.neighbors import KernelDensity

#a random Series that I want to fit a KDE on
X = pd.Series([0,1,1,4,5,8])

#reformat the Series
X = X.to_numpy().reshape(-1,1)

#fit KDE
kde = KernelDensity(kernel = 'epanechnikov', bandwidth = 'silverman').fit(X)

returns TypeError: '<=' not supported between instances of 'str' and 'int'
If I use a float for the bandwith, everything works just fine.

A: Solved: Updating sklearn to version 1.2 did the trick


text:
Q: Error in SQL Server while updating data Create Table #tempTbl
(
 [AssID] [int],
 [dt] [datetime]
)

insert into #tempTbl
select distinct(AssignmentID), (case when isdate(substring(NoteText,len('Vehicle picked-up was completed on')+1,len(NoteText)))=1 then
        substring(NoteText,len('Vehicle picked-up was completed on')+1,len(NoteText)) else '01/01/1900' end) as dop
from dbo.Assignment_Notes
where
    AssignmentID in(Select AssignmentID from dbo.Assignment_ClaimInfo
        where InsuranceComp='Access General')
and
    AssignmentID in (Select AssignmentID from dbo.Assignment_BuyerInfo where PickupDate is null)
and
    NoteTypeID=5

update dbo.Assignment_BuyerInfo
set PickupDate=#tempTbl.dt
where AssignmentID=#tempTbl.AssID

A: change your update statement to the following:
update dbo.Assignment_BuyerInfo
   set PickupDate=#tempTbl.dt
  from dbo.Assignment_BuyerInfo, #tempTbl
 where AssignmentID=#tempTbl.AssID

You have to include your extra table in a from clause just like you would if you were doing a select statement.


text:
Q: Rank and unrank increasing arrangements i want to rank and to unrank increasing Arrangements. See following example:
n := 3 (permutation elements: 1-n)
b := 2 (barriers: 0s)

valid:
rank 0: 0,0,1,2,3
rank 1: 0,1,0,2,3
rank 2: 0,1,2,0,3
rank 3: 0,1,2,3,0
rank 4: 0,1,3,0,2
....

invalid:
0,3,2,1,0
0,3,0,2,1
...

You can see that 0 is a barrier and between 2 barriers the permutation elements are must be increasing.
How many arrangements exists with n permutation elements and b barriers?
How to rank/unrank such an arrangement? (the rank of an arrangement is the index number of all valid arrangements, written in some order)
Currently I do bruteforce but usually my b is 3-255 so its not an option to bruteforce.
Thanks in advance.

A: I don't have a solution for rank/unrank, but I do have a quick algorithm for your first question ("How many arrangements exists with n permutation elements and b barriers?"), which will hopefully help someone create a fast algorithm for rank/unrank.
from math import comb, factorial
from functools import lru_cache

@lru_cache
def stirling(n, k):
    if n == k:
        return 1
    if n == 0 or k == 0:
        return 0
    if k == 2:
        return 2**(n-1) - 1
    if n == k - 1:
        return comb(n, 2)
    return k * stirling(n-1, k) + stirling(n-1, k-1)

def star_and_bar(stars, bars):
    return comb(stars+1, bars)

def count_valid(n, b):
    return sum(factorial(groups)*stirling(n, groups)*star_and_bar(b, groups)
            for groups in range(min(b+1, n)+1))

I count the number of ways to partition the n numbers into k unordered sets (stirling numbers of the second kind). I multiply this by the number of ways to order these sets (factorial groups) and multiply by the number of ways to intersperse barrier 0's (modified stars and bars problem, where bars can exist on the outside, but not adjacent to each other). Note that I'm treating the set of numbers as the bar, not the 0's. I then sum these products over all valid k.
-- Update --
I had shared the problem with a friend of mine, @ForgotMyName, who was able to offer further mathematical insight. He noted that there's an even more elegant solution for counting arrangements- merely (barriers+1) ** elements, or in python:
def count_valid(n, b):
    return (n + 1) ** b

Much more elegant than my solution.


text: Q: Get the code to build an existing layout I was just wondering if there was any software to basically take an existing android xml layout and generate the java Activity class that'd create this very specific activity?


text:
Q: Grouping multi-dimensional arrays in PHP I can't focus right now and my mind keeps playing tricks on me with the solution to this.
I've tried a multitude of options but they keep not working.. Sigh.
Say I have a string as such; a.b.c|a.b.d|a.b.e|f|f.g|f.h|i, I want to create a new array (or object) as the following
A > B > C, D, E
F > G, H
I

With > being a nested array, , being an element in the parent array.
These should be able to continue nesting a multitude of times, e.g. A > B > C > D > E > F, D
Any guidance? I've tried exploding the string and then those strings to an array - this array holds A > B > C, A > B > D, A > B > E etc., I just can't get my head around to how to combine them efficiently.
I started with just looping over each element in the array and checking if the parents' key exists, but that was failing. Any help is appreciated as I'm incredibly tired, quite shocking I can do such a simple task.

A: <?php

// read line from standard input
$line = trim(fgets(STDIN));

echo "Line: $line\n"; // debug

// split lines by |
$segments = explode('|', $line);

print_r($segments); // debug

// prepare output array
$md_array = array();

// walk through the segments
foreach($segments as $segment) {
    // set pointer to output array
    $current = &$md_array;
    // split segment by .
    $tokens = explode('.', $segment);

    print_r($tokens); // debug

    foreach($tokens as $token) {
        echo "working on $token\n";

        // if key is not included in the array, create empty array
        if( ! array_key_exists($token, $current) ) {
            $current[$token] = array();
        }
        // pass the pointer to following sub-section
        $current = &$current[$token];
    }
}

// print out the output
print_r($md_array);

?>

Testing the script
echo "a.b.c|a.b.d|a.b.e|f|f.g|f.h|i" | php test.php

Output
Array
(
    [a] => Array
        (
            [b] => Array
                (
                    [c] => Array
                        (
                        )

                    [d] => Array
                        (
                        )

                    [e] => Array
                        (
                        )

                )

        )

    [f] => Array
        (
            [g] => Array
                (
                )

            [h] => Array
                (
                )

        )

    [i] => Array
        (
        )

)

A: Want to thank Richard for his solution, which allowed me  to achieve my aim.
See the code below:
public static function permissions($permList) {
    $segments = explode('|', $permList);
    $md_array = array();
    foreach($segments as $segment) {
        $current = &$md_array;
        $tokens = explode('.', $segment);
        $x = 0;
        foreach($tokens as $token) {
            if(!array_key_exists($token, $current) ) {
                if(count($tokens) > $x+1)
                    $current[$token] = array();
                else
                    $current[] = $token;
            }
            if(count($tokens) > $x+1)
                $current = &$current[$token];
            $x++;
        }
    }
    return $md_array;
}

If I input a.b.c|a.b.d|a.b.e|f|f.g|f.h|i, I am returned with the expected output above.
Many thanks.


text:
Q: I want to use Windows7 visual style in my C# projects I want to make lists in a WinForms project like this one:

Is there an easy way to do it? or I have to code it by my self??

A: Would depend on whether or not you re using WinForms or WPF. In WPF, you could use list box templates:
http://msdn.microsoft.com/en-us/library/cc189093(v=vs.95).aspx. I think it would be harder in WinForms and I'm not aware of any controls that match the appearance you are looking for although you might check out the Telerik and DevExpress WinForm controls.


text:
Q: RecyclerView with different activities What I have: A RecyclerView with pictures of places like bars, coffee stores, etc.
What I want: That when you click on one of these images I show you the info of the selected place
My question: How can i set the OnCLickListener for the third picture for example
Please, if you can explain with code it would be great, I am not good programming yet, so I would really appreciate
My adapter
    public class AdapterDatos extends RecyclerView.Adapter<AdapterDatos.ViewHolder> implements View.OnClickListener {

    ArrayList<ClaseNueva> listalugares;
    private View.OnClickListener listener;

    public AdapterDatos(ArrayList<ClaseNueva> listaLugares) {
        listalugares = listaLugares;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {//esto es lo que hacereferencia al xml donde vamos a meter la info
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list,null,false);//aqui le asignamos el valor del view al viewHolder
        view.setOnClickListener(this);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {// este metodo es el que se encarga de establecer la conexion entre el adaptador y la clase Viewholder ( a la cual le asignamos el xml)
        holder.etiLugares.setText(listalugares.get(position).getLugares());// asi se asignan los textos
        holder.Foto.setImageResource(listalugares.get(position).getFoto());//asi se asignan las fotos

    }

    @Override
    public int getItemCount() {//este metodo va a decir el tamaño del viewHolder, en este caso de tamaño del array listalugares
        return listalugares.size();//se hace asi
    }

    public void setOnClickListener(View.OnClickListener listener){
        this.listener = listener;
    }

    @Override
    public void onClick(View view) {

        if(listener!= null){
            listener.onClick(view);
       }
  }

    public class ViewHolder extends RecyclerView.ViewHolder{

        TextView etiLugares;
        ImageView Foto;
        Context context;

        public ViewHolder(View itemView) {
            super(itemView);
            etiLugares = (TextView) itemView.findViewById(R.id.idNombre);//esto hace referencia a los elementos donde queremos meter la info
            Foto = (ImageView) itemView.findViewById(R.id.idImagen);

        }
    }
}

My java class
    public class foodAndGo extends Activity {

    ArrayList<ClaseNueva> listalugares;
    RecyclerView recyclerLugares;

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

        listalugares = new ArrayList<>();
        recyclerLugares = (RecyclerView) findViewById(R.id.RecyclerID);
        recyclerLugares.setLayoutManager(new LinearLayoutManager(this));

        llenarNombres();

        AdapterDatos adapter = new AdapterDatos(listalugares);
        adapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(),"Seleccion"+listalugares.get(recyclerLugares.getChildAdapterPosition(v)).getLugares(),Toast.LENGTH_SHORT).show();
                Intent myIntent = new Intent(foodAndGo.this, MapsActivity.class);
                startActivity(myIntent);
            }
        });
      recyclerLugares.setAdapter(adapter);

    }

    private void llenarNombres() {
        listalugares.add(new ClaseNueva("Restaurantes", R.drawable.carnemejor));
        listalugares.add(new ClaseNueva("Bares", R.drawable.beers));
        listalugares.add(new ClaseNueva("Cafeterías",R.drawable.desayunosmejor));
        listalugares.add(new ClaseNueva("Pizzerias",R.drawable.pizzaamejor));
        listalugares.add(new ClaseNueva("Favoritos",R.drawable.favoritosmejo));

    }
}

A:
Attach a click listener on view

 holder.imgView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                          //Do Something
          }

A: If you need to set onClick only for the third position from the List
Remove your  view.setOnClickListener(this); from onCreateViewHolder
@Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {//esto es lo que hacereferencia al xml donde vamos a meter la info
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list,null,false);//aqui le asignamos el valor del view al viewHolder

        return new ViewHolder(view);
    }

set OnClick inside the OnBindViewHolder only for the Third position using if Statement
 @Override
        public void onBindViewHolder(ViewHolder holder, int position) {// este metodo es el que se encarga de establecer la conexion entre el adaptador y la clase Viewholder ( a la cual le asignamos el xml)
            holder.etiLugares.setText(listalugares.get(position).getLugares());// asi se asignan los textos
            holder.Foto.setImageResource(listalugares.get(position).getFoto());//asi se asignan las fotos
               if(holder.getAdapterPosition() == 3)
         holder.itemView.setOnClickListener(this); // Parent ID

        }

A: In your adapter's onBindViewHolder try this code:
holder.Foto.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
            if(position==0){
              Intent intent = new Intent(context,MapsActivity.class) // You can get context from onCreateViewHolder, initialize one from parent.getContext() or pass one in constructor of adapter
              startActivity(intent)

            }else if(position==1){
             // open Second Activity
            }else{
             // open Third Activity
            }

        });

A:      @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {//esto es lo que hacereferencia al xml donde vamos a meter la info
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list,null,false);//aqui le asignamos el valor del view al viewHolder

            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {// este metodo es el que se encarga de establecer la conexion entre el adaptador y la clase Viewholder ( a la cual le asignamos el xml)
            holder.etiLugares.setText(listalugares.get(position).getLugares());// asi se asignan los textos
            holder.Foto.setImageResource(listalugares.get(position).getFoto());//asi se asignan las fotos
            if(position%3==0)
            holder.Foto.setOnClickListener(this);

        }


text:
Q: Why is this text running outside of the li element? Hope somebody can see what's going on with this, it's got me beat.
I have an issue with the  tag text elements inside a drop-down menu extending beyond the li element for the mobile version of the navigation in the footer. The li element has a width restriction (is shaded orange to see clearly), you can see the problem on this page when browser is mobile width wide https://www.mcveaghfleming.co.nz/nav-issues.html There are some long link names and instead of flowing under the line above they are extending past the end of the li element.

Here's the relevent html

Business & Corporate

Business & Corporate

Anti-Money Laundering and Countering Financing of Terrorism Act 2009 Compliance and Advice

A: Be sure to set position:relative or anything different than the static default to the UL.
Adding up, this is to prevent the 100% width to be referring to an upper parent. My guess is that a lack of position declaration on the parent is scaling up the DOM to the entire body width. A quick inspect on the code should give you a hint about this, but is hard without seeing the actual code in action.