text:
Q: Solving system of PDEs with NDSolve I am trying to solve a system of coupled PDEs with zero-flux boundary conditions on a large domain.
I have two problems:
1) Is there a possibility to use results of NDSolve as inititial conditions? As the results are given by an interpolating function, I guess this could be difficult. However, my RAM is not sufficient for long evaluations and evaluation using {t,0,10} and then {t,10,20} (for instance) does not seem to match.
2) If I use my initial conditions (see following code), I think the evaluation is wrong. A stationary bump in z emerges. I think the reason for this is the error
NDSolve::mxsst: Using maximum number of grid points 100 allowed by the MaxPoints or MinStepSize options for independent variable x.
How can I solve the system anyway?
The code:
(* Parameters *)
eps = 1.4434; m = 0.3; c11 = 0.1732;
(* PDEs *)
pde1 := D[pp[t, x, y], t] == 0.05*Laplacian[pp[t, x, y], {x, y}] + pp[t, x, y]*(1 - c11*pp[t, x, y] - z[t, x, y]/(1 + pp[t, x, y]^2));
pde2 := D[z[t, x, y], t] == 0.05*Laplacian[z[t, x, y], {x, y}] + z[t, x, y]*(eps*pp[t, x, y]/(1 + pp[t, x, y]^2) - m);
(* Initial conditions *)
ic1[x_, y_] := Which[Sqrt[(x - 50)^2 + (y - 50)^2] < 1, 6, True, 0];
ic2[x_, y_] :=
Which[Sqrt[(x - 50)^2 + (y - 50)^2] < 1, 0.5, True, 1/c11];
(* Numerical approximation using NDSolve with zero-flux boundary conditions*)
soln2d = NDSolve[{pde1, pde2,
 (D[pp[t, x, y], x] /. x -> 0) == 0,
 (D[pp[t, x, y], y] /. y -> 0) == 0,
 (D[z[t, x, y], x] /. x -> 0) == 0,
 (D[z[t, x, y], y] /. y -> 0) == 0,
 (D[pp[t, x, y], x] /. x -> 100) == 0,
 (D[pp[t, x, y], y] /. y -> 100) == 0,
 (D[z[t, x, y], x] /. x -> 100) == 0,
 (D[z[t, x, y], y] /. y -> 100) == 0,
 z[0, x, y] == ic1[x, y],
 pp[0, x, y] == ic2[x, y]},
 {pp, z}, {t, 0, 500}, {x, 0, 100}, {y, 0, 100}];

Thank you for your help!

A: Your description on how to check the solution was a bit vague, so I did not do it. Try this, though:
(*Parameters*)
eps = 1.4434; m = 0.3; c11 = 0.1732;
(*PDEs*)
pde1 :=
  D[pp[t, x, y], t] ==
   0.05*Laplacian[pp[t, x, y], {x, y}] +
    pp[t, x, y]*(1 - c11*pp[t, x, y] - z[t, x, y]/(1 + pp[t, x, y]^2));
pde2 := D[z[t, x, y], t] ==
   0.05*Laplacian[z[t, x, y], {x, y}] +
    z[t, x, y]*(eps*pp[t, x, y]/(1 + pp[t, x, y]^2) - m);
(*Initial conditions*)

ic1[x_, y_] := Which[Sqrt[(x - 50)^2 + (y - 50)^2] < 1, 6, True, 0];
ic2[x_, y_] :=
  Which[Sqrt[(x - 50)^2 + (y - 50)^2] < 1, 0.5, True, 1/c11];
(*Numerical approximation using NDSolve with zero-flux boundary \
conditions*)
soln2d =
 Monitor[NDSolveValue[{pde1, pde2, z[0, x, y] == ic1[x, y],
    pp[0, x, y] == ic2[x, y]}, {pp, z}, {t, 0,
    500}, {x, y} \[Element] Rectangle[{0, 0}, {100, 100}],
   EvaluationMonitor :> (monitor = Row[{"t = ", CForm[t]}])]
  , monitor]

This uses the finite element method to solve the PDEs.
To your firs question: Yes you can use an InterpolatingFunction as an initial condition, just like any other function. Being able to do so is a strong point of Mathematica.


text:
Q: couldn't connect to host - wp-cron.php?doing_wp_cron I've moved my wordpress website to new dedicated server. Website is running few cron jobs setup by wp-cron. As soon as i moved the website to new server cron jobs stopped running. I've debug bar installed, the HTTP Request bar turns red and showing this error:

couldn't connect to host

Complete screenshot is attached.

Any assistance in resolving this issue will be highly appreciated.

A: You should open a support ticket with your host, as it's probably related to their environment. From the error, it sounds to me like they might be blocking curl in their environment, probably for security reasons. They may be able to unblock it, or you may need to find an alternative.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Normalized integrals over shrinking tubular neighbourhoods converge to an integral on the limit submanifold $\renewcommand{\S}{\mathcal{S}}$
$\newcommand{\M}{{\mathcal{M}}}$
$\newcommand{\TM}{{T\mathcal{M}}}$
$\newcommand{\TS}{{T\mathcal{S}}}$
$\newcommand{\NS}{{\mathcal{NS}}}$
$\newcommand{\N}{\mathcal{N}}$
$\newcommand{\g}{\mathcal{g}}$
$\newcommand{\Volg}{\text{Vol}_\g}$
$\newcommand{\Vol}{\text{Vol}}$
$\newcommand{\VolgS}{\text{Vol}_{\g|_\S}}$
Let $(\M,\g)$ be a smooth $d$-dimensional Riemannian manifold, and let $\S\subset\M$ be a smooth compact $k$-dimensional oriented submanifold. Let $\NS$ be the normal bundle of $\S$ in $\M$.
For a sufficiently small $h>0$, define
$\S_h := \{ \exp_p(v) : p\in \S, v\in \NS, |v|\le h \}.$
Let $f:\M \to \mathbb{R}$ be a continuous function. I am trying to prove the following:
$$ \lim_{h \to 0} \frac{\int_{\S_h} f}{\Volg(\S_h)}=\frac{\int_{\S} f}{\VolgS(\S)},$$
where the integrals are w.r.t the Riemannian volume forms on $\S_h$,$S$ defined by $\g,\g|_{\S}$ respectively.
(Recall $\S$ is oriented).
Edit:
Let's start with the case of a $k$-cube embedded in $\mathbb{R}^d$ in the standard way. The general case should follow by an approximation argument, since "locally, everything is Euclidean".
Here is a proof for the Euclidean case:
Let's use Fubini theorem:
Suppose $\S \subseteq \mathbb{R}^k \times \{\bar 0^{d-k}\} \subseteq \mathbb{R}^d$, where $S$ is a product of $k$ intervals. Then $\S_h=S \times [-h,h]^{d-k}$.
Let $\epsilon >0$, and let $(x,y)\in S\times [-h,h]^{d-k}$.
$$\frac{\int_{\S_h} f}{\Vol(\S_h)}= \frac{\int_{[-h,-h]^{d-k}}\big(\int_{S} f(x,y) dx\big)dy }{(2h)^{d-k}\Vol(S)} =\frac{\int_{[-h,-h]^{d-k}} g(y) dy }{\Vol([-h,-h]^{d-k})} ,$$
where $g:[-h,-h]^{d-k} \to \mathbb{R}$ is defined by
$$ g(y)=\frac{\int_{x \in S} f(x,y)dx}{\Vol(S)}.$$
Since the domain is compact, $f$ is uniformly continuous, so $g$ is continuous. This implies
$$ \lim_{h \to 0} \frac{\int_{[-h,-h]^{d-k}} g(y) dy }{\Vol([-h,-h]^{d-k})}  =g(\bar 0)=\frac{\int_{x \in S} f(x,0)dx}{\Vol(S)}=\frac{\int_{\S} f}{\Volg(\S)}.$$

A: We will consider the following case :
(1) If $p:=(x,h)\in [0,l]\times [-1,1]$, then prove that
$$ \lim_r\ \frac{\int_{[0,l]}\int_{[-r,r]} f dhdx }{2rl} =\frac{T}{l},\ T:=
\int_{[0,l]} f(x,0)\ dx
$$
Proof :
Since $f$ is uniform continuous, then
for $\varepsilon$ there is $\delta$ s.t. $d(p,q)<\delta$ implies
$|f(p)-f(q)|<\varepsilon$.
Hence \begin{align*}  \frac{\int_{[0,l]}\int_{[-r,r]}
f(x,0)-\varepsilon\ dhdx }{2r}
 &<\frac{\int_{[0,l]}\int_{[-r,r]} f dhdx }{2r}
 \\&<\frac{\int_{[0,l]}\int_{[-r,r]} f(x,0)+\varepsilon\ dhdx }{2r}
\end{align*}
so that $$T-\varepsilon l <\frac{\int_{[0,l]}\int_{[-r,r]} f dhdx
}{2r} < T+\varepsilon l $$
(2) Assume that there is a cover $\{E_i\}$ for $S$ s.t.
(i) $E_i\subset S,\ 1\leq i\leq N$ is homeomorphic to closed ball,
(ii) $E_i\cap E_j$ has measure $0$, and (iii) $E_i$ have same
volumes.
(3) If $V_i(r):=\{\exp_pv|p\in E_i,\ v\perp T_pS,\ |v|\leq r\}$, then $$ \lim_r\ \frac{\int_{V_i(r)} f}{{\rm vol}\
V_i(r)} =\frac{\int_{E_i} \ T}{{\rm vol}\ E_1} $$
Note that $$ t_i(r){\rm vol}\ V_i(r) :={\rm vol}\ V_1(r) $$
 and $$ \lim_r\ t_i(r)=1$$
(4) So \begin{align*}\frac{\sum_i \ \int_{V_i(r)} f
}{\sum_i V_i(r)} &=\frac{\sum_i \ \int_{V_i(r)} f }{[\sum_i \
1/t_i(r) ]V_1(r)}\\& = \frac{1}{\sum_i \ 1/t_i(r)} \sum_i \ \frac{
\int_{V_i(r)} f }{ t_iV_i(r) }
\\&\rightarrow  \frac{1}{N} \sum_i
\ \frac{\int_{E_i} f}{{\rm vol}\ E_i }
\end{align*}
(5) More explanation on (3) : A Riemannian metric $g$ on $X:=V_i(r)$ is close to $g'=g|S +
    g_0$ where $g_0$ is a canonical metric on $\mathbb{R}^{n-k}$
    where ${\rm dim}\ S=k$.
Given $\varepsilon$ there is $r$ s.t. $$ (1-\varepsilon )d_{g'}
 \leq d_g\leq (1+\varepsilon ) d_{g'}$$
so that $$ (1-\varepsilon)^n \leq \frac{ H^n(X,d_g) }{H^n(X,d_{g'} )}
   \leq (1+\varepsilon )^n $$
   where $H^n(X,d_g)$ is a $n$-dimensional Hausdorff measure wrt a distance
  $d_g$
So
$$ \frac{\int_{(X,d_{g'} )} f  +O(\varepsilon ) \int_{
(X,d_{g'} )} f }{ {\rm vol}\ (X,d_{g'}) +O(\varepsilon ){\rm vol}\
(X,d_{g'}) } =  \frac{ \int_{(X,d_g)} f }{{\rm vol}\ (X,d_g)} $$


text:
Q: Cannot create ESXi storage on second NVMe I'm really searching all over for a solution for hours. I do not have physical access to the datacenter, I have KVM and SSH access. Server is a Supermicro X11 model.
The server has 2 NVMe disks. I have installed ESXi 6.7u3 on one of them (both were visible during setup). Now in ESX Web client there is a single storage as expected, and I can see both drives;
Datastore view screenshot
Devices view screenshot
If I click "New Datastore", during the wizard it says there is not any available device to create a datastore. When I click the first drive details, as you can see "New Datastore" is grayed out and looking at the partitioning, this is the drive I chose during installation and I can assume that this drive is attached to the default datastore1.
Device 1 details
If I click the second drive, you can see that the "New Datastore" button is active, so I assume this is the other drive that ESXi is not installed on, so I should be able to create a datastore on it. But if you look at the partitioning, it's exactly same as the first drive. Although it says "there are no available devices" if I click the "New Datastore" button from the main Storage screen (remember above), I can click the button in the below screenshot and continue to the end. I did not create the datastore on this drive because I'm afraid something will break.
Device 2 details
So why are these 2 drives have exact same partitioning on them if I installed ESXi on only first drive and why is the difference between two "New Datastore" buttons, one is working other does not allow me? Is there some raid setup here that I cannot see? I have rebooted the server, checked BIOS, looked for some "press this combination to enter raid setup" message during boot but there are no indications that the disks are in a RAID array. How can I determine this?
Any help or directions appreciated. Thanks if you read this far.


text:
Q: NXlog cant writes/read to cache for "savePos" I can't configure NXlog to send Windows Event Logon logs. the logs are created before NXlog starts, so NXlog needs to remember When was the last time that he grabbed the Event logs.
The problem occurs when I try to use the "savePos" directive in my configuration:

This directive takes a boolean value of TRUE or FALSE and specifies whether the file position should be saved when nxlog exits. The file position will be read from the cache file upon startup. The file position is saved by default if this directive is not specified in the configuration. Even if SavePos is enabled, it can be explicitly turned off with the NoCache directive.
(from the doc).

But NXlog never writes the position (or anything else) to the cache.
I'm not using the noCache, and I didn't find anything on the web.
My NXlog configuration (generated by Graylog2):
define ROOT C:\Program Files (x86)\nxlog
<Extension gelf>
Module xm_gelf
</Extension>

<Extension syslog>
  Module xm_syslog
</Extension>

Moduledir %ROOT%\modules
CacheDir %ROOT%\data
Pidfile %ROOT%\data\nxlog.pid
SpoolDir %ROOT%\data
LogFile %ROOT%\data\nxlog.log

LogLevel INFO

<Extension logrotate>
    Module  xm_fileop
    <Schedule>
        When    @daily
        Exec    file_cycle('%ROOT%\data\nxlog.log', 7);
    </Schedule>
</Extension>

<Input 57849fe093a38e030db3e1d7>
    Module im_msvistalog
    PollInterval 2
    SavePos True
    ReadFromLast True

</Input>

<Output 57849aa293a38e030db3dc55>
    Module om_udp
    Host 10.200.68.102
    Port 12201
    OutputType  GELF
    Exec $short_message = $raw_event;
# Avoids truncation of the short_message field.
    Exec $gl2_source_collector = '8d8925b7-f1c0-40ae-a1ed-e918432e2125';
    Exec $Hostname = hostname_fqdn();
</Output>

<Route route-0>
  Path 57849fe093a38e030db3e1d7 => 57849aa293a38e030db3dc55
</Route>


text:
Q: PHP exploding url from text, possible? i need to explode youtube url from this line:
[embed]https://www.youtube.com/watch?v=L3HQMbQAWRc[/embed]

It is possible? I need to delete [embed] & [/embed].

A: preg_match is what you need.
<?php

$str = "[embed]https://www.youtube.com/watch?v=L3HQMbQAWRc[/embed]";
preg_match("/\[embed\](.*)\[\/embed\]/", $str, $matches);
echo $matches[1]; //https://www.youtube.com/watch?v=L3HQMbQAWRc

A: $string = '[embed]https://www.youtube.com/watch?v=L3HQMbQAWRc[/embed]';
$string = str_replace(['[embed]', '[/embed]'], '', $string);

See str_replace

A: why not use str_replace? :) Quick & Easy
http://php.net/manual/de/function.str-replace.php

A: Just for good measure, you can also use positive lookbehind's and lookahead's in your regular expressions:
(?<=\[embed\])(.*)(?=\[\/embed\])

You'd use it like this:
$string = "[embed]https://www.youtube.com/watch?v=L3HQMbQAWRc[/embed]";
$pattern = '/(?<=\[embed\])(.*)(?=\[\/embed\])/';
preg_match($pattern, $string, $matches);
echo $match[1];

Here is an explanation of the regex:
(?<=\[embed\]) is a Positive Lookbehind - matches something that follows something else.
(.*) is a Capturing Group - . matches any character (except a newline) with the Quantifier: * which provides matches between zero and unlimited times, as many times as possible. This is what is matched between the groups prior to and after. This are the droids you're looking for.
(?=\[\/embed\]) is a Positive Lookahead - matches things that come before it.


text:
Q: How can I transform a graphql request with two arguments to one with one argument? I have a graphql mutation that looks like this:
mutation ($entityId: ID!, $reviewId: ID!) {
  removeReview (entityId: $entityId, reviewId: $reviewId) {
    ...
  }
}

Which delegates to another schema to remove an associated entity
input RemovePostInput {
  id
}

mutation ($input: RemovePostInput) {
  removePost (input: $input) {
     id
  }
}

And in my resolver, I'm using delegateToSchema but I can't get my transforms right. I'm able to wrap the fieldname, and add my own selectionset as well as the new input argument, but I can't get rid of the incoming two arguments.
Is there a built-in transformer to remove arguments, or if not, how can I make a transformRequest transformer to convert two arguments into one. If I had one named type transformed to another named type, I would just use a RenameTypes transformer, but the number of arguments is different, which I can't figure out.
delegateToSchema({
  schema: remoteSchema,
  operation: 'mutation',
  fieldName: 'deletePost',
  args: { input: { id: postId } },
  transforms: [
    new WrapQuery(['deletePost'], POST_WITH_REPLIES_SELECTIONSET, (result) => result)
  ],
  context,
  info
});


text:
Q: how to make the cursor work and to fill in the list , the values in a row of the only parameter of the procedure I have a procedure that uses a cursor.
It looks in a table for an ID and a value.
The procedure works but only with a single value is entered.
I prepared a temporary table and also a variable where I concatenated the values from the temporary table.
How can I make it work by entering the concatenated values?
The table that looks like this:
(id_ct, no_ct, no_gr, no_per, zone_ID_zone) values
(1, CT31781, 0101, 1, 888888),
(2, CT31781, 0101, 2, 888888),
(3, CT31781, 0101, 3, 789),
(4, CT31780, 0101, 4, 888888),
(5, CT31780, 0101, 5, 888888),
(6, CT31780, 0101, 6, 788);

CREATE PROCEDURE `find_proo88` (in CTS varchar(255))
    begin
    Declare a int default 0;
    Declare i int default 0;
    DEClare b int default 0;
    declare c decimal  (4.2);
    DECLARE V_LISTA  VARCHAR(65000);
    declare v_user int;
    declare v_status varchar(20);
    declare ok int;

    DECLARE CURS cursor for
            SELECT CT.ID_CT, CT.zone_id_zone
            FROM  CT
        where CT.NO_CT = CTS ;

        declare continue handler for not found
        begin
        set ok=1;
        end;

    open curs;
    START TRANSACTION;
        bucla :loop
            fetch curs into v_user , v_status;
            if ok=1 then leave bucla;
            end if;
            if v_status = "888888" then
            set a=a+1;
            else set i=i+1;
            end if;
        end loop bucla;
      COMMIT;
      close curs;

        SET  b = a+i;
        set  c = (b-a)/b*100;
        SELECT  CONCAT_WS(" " , v_lista ,cts,"        Perechi Libere " , a ,  "           Perechi Ocupate ", i ,"        Total Perechi " , b  , "          Full ", CONCAT_WS("", c ," % ")) INTO V_LISTA;
    SELECT V_LISTA as "cutii terminale";

end;

A: I solved my problem with a simple view.
   I didn't use the cursor.
create OR REPLACE view find_proo88 as
select id_ct,no_ct as "Numar Cutie Terminala" , no_gr as "Numar Grup", b.bl_name as "Bloc" , b.bl_sc as "Scara", b.bl_et_ct as "Etajul Cutiei Terminale", s.str_name as "Strada", s.str_no as "No",cl.Rank as Rank,
    count(*) Total,
        sum(case when CT.zone_id_zone = '888888' then 1 else 0 end) 'Perechi libere',
        sum(case when CT.zone_id_zone != '888888' then 1 else 0 end) 'Perechi Ocupate',
        CONCAT_WS(" " ,(TRUNCATE(avg((case when CT.zone_id_zone = '888888' then 1 else 0 end)*100),0) ),"%") 'Grup Liber',
        CONCAT_WS(" " ,(TRUNCATE(avg((case when CT.zone_id_zone != '888888' then 1 else 0 end)*100),0) ),"%") 'Grup Ocupat',
        sum(case when CL.Rank = 'Activ' then 1 else 0 end) 'Rank Activ',
        sum(case when CL.Rank != 'Activ' then 1 else 0 end) 'Rank Inactiv',
        CONCAT_WS(" " ,(TRUNCATE(avg((case when Rank = 'Activ' then 1 else 0 end)*100),0) ),"%") 'R Activ',
        CONCAT_WS(" " ,(TRUNCATE(avg((case when Rank != 'Activ' then 1 else 0 end)*100),0) ),"%")  'R Inactiv'
    from ct
join building b on b.id_build=ct.building_Id_build
join street s on s.id_str=b.street_id_str
join client cl on cl.street_id_str = s.id_str
group by no_ct


text:
Q: How to pass ssh password asked on terminal while using subclipse Our internal svn repository's URI looks like svn+ssh://svn/hogehoge/svnroot/. Using subclipse on eclipse that is run from a terminal, eclipse freezes when I try to access repository and never return. I found on terminal ssh password is asked but looks like it's just printed there and doesn't accept my input (password I enter is interpreted as command on terminal). Any idea is appreciated.
Environment:

*

*Ubuntu 10.04

*Eclipse Indigo SP2

*Subclipse (Required) 1.6.18

*Subversion Client Adapter (Required) 1.6.12

*Subversion JavaHL Native Library Adapter (Required) 1.6.17

A: I would recommend you install SVNKit and change to using it instead of JavaHL.  SVNKit includes a pure Java SSH client so it is able to provide a GUI prompt within Eclipse.  There are two alternatives if you want to use JavaHL:

*

*Start Eclipse from a Terminal window.  SSH prompts will then appear within that window.

*Run ssh-agent.  Your SSH client will then fetch the keys from ssh-agent and will not need the terminal prompt.
Usually users are already using ssh-agent, in which case I would recommend just using JavaHL.  Since you are apparently not using it, I would suggest to just use SVNKit.


text:
Q: How to call new web usercontrol on click of a button I have a button added to the aspx page and i want new web user control on click of that button.For eg. if a person has multiple address he can click the button and can add address1, address2, address3
<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">

                <asp:Label ID="Lbl_name" runat="server" Text="Name"></asp:Label>

                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

                <asp:Label ID="Lbl_age" runat="server" Text="Age"></asp:Label>

                 <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

<WebUserControl:WebTag id="MyControl" runat="server"/>
        <asp:Button ID="Btn_add" runat="server" Text="Add" />

                <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />

    </form>

A: You can accomplish your functionality with JQuery as in this jsFiddle
HTML

         <input id="txt1" name="txt1" type="text"></input><input id="cmdAdd1" type="button" value="Add"></input>

Javascript
var itemCount = 1;
$('#cmdAdd1').click(function(){addNewItem();});

function addNewItem(){
    var thisItem = itemCount;
    // Make last text box readonly
    $('#txt' + itemCount).attr('readonly', 'readonly');
    // Change button to Remove button
    $('#cmdAdd' + itemCount).attr('value', 'Remove');
    $('#cmdAdd' + itemCount).unbind();
    $('#cmdAdd' + itemCount).click(function(){removeItem(thisItem );});

    // Add new line with text field and button
    itemCount++;
    var newItem = '
'
    newItem += '<input id="txt' + itemCount + '" name="txt' + itemCount + '" type="text"></input>';
    newItem += '<input id="cmdAdd' + itemCount + '" type="button" value="Add"></input>';
    newItem += "
";

    $('#myDiv').append(newItem);
    $('#cmdAdd' + itemCount).click(function(){addNewItem();});
}

function removeItem(i){
    $('#item' + i).remove();
}

Once your form has posted back to the server, you can iterate through the fields by walking the Form controls.
C#
int n=1;
while (Request["txt" + n] != null)
{
    Console.WriteLine(Request["txt" + n]);
    n++;
}


text:
Q: get Google search suggestions while entering text so i want to experiment with Google's search suggestion feature for word/phrase completion.
I.e. stick the functionality of typing a search on their home page into a text editor for starters.
is it possible to request these Google search suggestions with their REST API? Or somehow?

A: You could use one of the following URLs to get search suggestions from Google:
1. URL used by the suggestion box on the home page
http://www.google.com/complete/search?hl=en&js=true&qu=sugge

The query part is the qu parameter. A sample response would be:
window.google.ac.h(["sugge",[["suggest","200,000,000 results","0"],["suggestion box","27,500,000 results","1"],["suggestion","84,300,000 results","2"],["suggest friends on facebook","73,100,000 results","3"],["suggested calorie intake","1,940,000 results","4"],["suggestive","12,400,000 results","5"],["suggestion boxes","997,000 results","6"],["suggested weight for height and age","72,600,000 results","7"],["suggest synonym","2,490,000 results","8"],["suggestopedia","79,300 results","9"]]])

2. URL used by the Google toolbar
http://toolbarqueries.google.com/complete/search?q=sugge&output=toolbar&hl=en

The query is obviously the q parameter. This has the advantage of returning XML data, that is easier and more portable in terms of parsing the result:
<?xml version="1.0"?>
<toplevel>
    <CompleteSuggestion><suggestion data="suggest"/><num_queries int="200000000"/></CompleteSuggestion>
    <CompleteSuggestion><suggestion data="suggestion box"/><num_queries int="27500000"/></CompleteSuggestion>
    <CompleteSuggestion><suggestion data="suggestion"/><num_queries int="84300000"/></CompleteSuggestion>
    <CompleteSuggestion><suggestion data="suggest friends on facebook"/><num_queries int="73100000"/></CompleteSuggestion>
    <CompleteSuggestion><suggestion data="suggested calorie intake"/><num_queries int="1940000"/></CompleteSuggestion>
    <CompleteSuggestion><suggestion data="suggestive"/><num_queries int="12400000"/></CompleteSuggestion>
    <CompleteSuggestion><suggestion data="suggestion boxes"/><num_queries int="997000"/></CompleteSuggestion>
    <CompleteSuggestion><suggestion data="suggested weight for height and age"/><num_queries int="72600000"/></CompleteSuggestion>
    <CompleteSuggestion><suggestion data="suggest synonym"/><num_queries int="2490000"/></CompleteSuggestion>
    <CompleteSuggestion><suggestion data="suggestopedia"/><num_queries int="79300"/></CompleteSuggestion>
</toplevel>


text:
Q: Ruby Strings - difference between << and += Running the method fizzbuzz1 yields a 100 member list of numbers 1 to 100, where each multiple of 3 is replaced by "fizz", each multiple of 5 by "buzz", and each multiple of both 3 and 5 by "fizzbuzz":
def fizzbuzz1()
  result = Array.new(100, "")
  result.each_index do |index|
    value = index + 1
    result[index] += "fizz" if value % 3 == 0
    result[index] += "buzz" if value % 5 == 0
    result[index] = "#{value}" if result[index].size == 0
  end
end

2.0.0-p195 :055 > fizzbuzz1
 => ["1", "2", "fizz", "4", "buzz", "fizz", "7", "8", "fizz", ...and so on.

BUT, switching each += for a << yields something unexpected:
def fizzbuzz2()
  result = Array.new(100, "")
  result.each_index do |index|
    value = index + 1
    result[index] << "fizz" if value % 3 == 0
    result[index] << "buzz" if value % 5 == 0
    result[index] = "#{value}" if result[index].size == 0
  end
end

2.0.0-p195 :057 > entire_fizzbuzz2_result = fizzbuzz2
2.0.0-p195 :058 > entire_fizzbuzz2_result[5]
 => "fizzbuzzfizzfizzbuzzfizzfizzbuzzfizzbuzzfizzfizzbuzzfizzfizzbuzzfizzbuzzfizzfizzbuzzfizzfizzbuzzfizzbuzzfizzfizzbuzzfizzfizzbuzzfizzbuzzfizzfizzbuzzfizzfizzbuzzfizzbuzzfizzfizzbuzzfizzfizzbuzzfizzbuzzfizzfizzbuzz"

Most peculiarly, I also notice that if I take out the line: result[index] = "#{value}" if result[index].size == 0 to give:
def fizzbuzz3()
  result = Array.new(100, "")
  result.each_index do |index|
    value = index + 1
    result[index] << "fizz" if value % 3 == 0
    result[index] << "buzz" if value % 5 == 0
  end
end

2.0.0-p195 :062 > store_fizzbuzz3 = fizzbuzz3
2.0.0-p195 :063 > store_fizzbuzz3.reject { |each| store_fizzbuzz3[0] == each }
 => []

Which must mean that fizzbuzz3 returns a 100 member array where each element is the same, and has the characteristics:
2.0.0-p195 :066 > store_fizzbuzz3[1]
 => "fizzbuzzfizzfizzbuzzfizzfizzbuzzfizzbuzzfizzfizzbuzzfizzfizzbuzzfizzbuzzfizzfizzbuzzfizzfizzbuzzfizzbuzzfizzfizzbuzzfizzfizzbuzzfizzbuzzfizzfizzbuzzfizzfizzbuzzfizzbuzzfizzfizzbuzzfizzfizzbuzzfizzbuzzfizzfizzbuzz"
2.0.0-p195 :067 > store_fizzbuzz3[1].size
 => 212
2.0.0-p195 :068 > store_fizzbuzz3[1].size / 4
 => 53

And 53 is a sort of interesting number in that it is the number of integers between 1 and 100 that are not divisible by 3 or 5...i.e. the number of "numbers" in the result of the fully functioning fizzbuzz1 up top.
What is going on here with the <<, could someone give me a little walkthrough?

A: There are two interacting matters here:

*

*The form of Array.new(), and

*The style of string concatenation.

In the form you use, Array.new(100, "") creates an Array with 100 elements, each pointing to the same empty string.  += returns a new string, so that doesn't matter.  << appends to the existing string, so it does matter that they're all the same.
If you initialize result with this form of Array.new():
result = Array.new(100){""}

then fizzbuzz2 will work as expected, because you have 100 different empty strings.


text:
Q: Problems inserting elements into XML fragment The basic problem is actually pretty simple:  I can't get a Nokogiri DocumentFragment to behave as expected.  It has two nodes instead of the one it would have if it were an actual document, and it doesn't recognize that node as an element, whereas the document does.
I need a fragment instead of a document, because I want to insert the resulting XML into another document (or fragment) as an element. It looks like I may have used the wrong fragment method.
I'm trying to build an XML representation for objects in our Ruby on Rails app, in a method called build_xml.  Since I have a hierarchy of nested objects, I'm making it a generic method that will be shared between classes, and use a class constant in each class to deal with class-specific info.  Each object creates a Nokogiri DocumentFragment instead of a full document, so that any returned XML string can be inserted into a containing object's XML as an element.
My problem is that I can't get the fragment to show me its elements.  So, I have:
xml_string = self.to_xml({skip_types:true, skip_instruct: true})  # Use default to_xml method to get started
xml_fragment = Nokogiri::XML::DocumentFragment.parse(xml_string)  # Create Nokogiri doc fragment

And at this point, I want to loop over each nested object and add it as a sub-element of the fragment's only element.  However, the fragment's element_children() method returns an empty array, while it's children() method returns an array of two items, the first of which is the element I want, and the second of which is some text object, only containing a linefeed.
Example:
df = Datafile.first
xml_string = df.to_xml({skip_types:true, skip_instruct: true})
frag = Nokogiri::XML::DocumentFragment.parse(xml_string)
frag.element_children  # => returns []
frag.children  # => returns array of two children, one of which is datafile element, the other of which is just a linefeed.

If I create an actual XML document instead of just a fragment, then the document has the element_children populated as expected, and furthermore, doc.children has only the one element, without the second, superfluous node.  I could try to do my work with a document, then just convert it to a fragment before returning it, but I don't know if resulting fragment will still have problems, and I'd prefer to understand what's going on, so I can just do it right, instead.
So...

*

*Why doesn't the fragment recognize its only real node as an element?  Is there something I should do to force this?  The Nokogiri documentation doesn't describe much about element nodes, but it looks like they have no accessible properties to differentiate them from generic nodes.

*Why does this second, empty node show up when I parse a fragment?

*Do I just have to go through full documents?  Is there an easy way to cast a document to a fragment?

*Should I be doing this some other way entirely?

A: You're passing in the whole XML string to parse, it just takes the tags as an argument.
According to their docs, you should be doing something like this:
xml_fragment = Nokogiri::XML.fragment(xml_string)

Not sure if this is actually what's causing the problem, but it might be a place to start.

A: While the question isn't clear, perhaps this little overview of inserting and removing nodes will help:
require 'nokogiri'

inserted_text = 'hello world!'

This parses the fragment:
doc = Nokogiri::XML::DocumentFragment.parse('<foo><bar></bar></foo>')
doc.to_xml # => "<foo>\n  <bar/>\n</foo>"

Compare it to a full parse, which adds the XML declaration:
doc = Nokogiri::XML('<foo><bar></bar></foo>')
doc.to_xml # => "<?xml version=\"1.0\"?>\n<foo>\n  <bar/>\n</foo>\n"

Find the <bar> node and add a child node:
bar = doc.at('bar')
bar.children = "<baz a='1'>#{ inserted_text }</baz>"

doc.to_xml # => "<foo>\n  <bar>\n    <baz a=\"1\">hello world!</baz>\n  </bar>\n</foo>"

I'm using the at method, which finds the first matching node. It's more specific than search which returns all matching nodes as a NodeSet, which is akin to an array of Nodes. Both methods take either CSS or XPath selectors; CSS is easier to read usually, but XPath has a lot more power so pick and choose between them based on ease of reading first, then the power. Nokogiri's perfectly happy to use both in the same script. There are CSS/XPath specific equivalents for at and search: at_css, at_xpath and css and xpath respectively. at('some_selector') is equivalent to search('some_selector').first.
Also, notice that Nokogiri is happy to take a string containing the XML or HTML you want to add. It will parse it into a fragment, allowing you to more easily define what you want to use.
This is how to easily remove a node:
baz = doc.at('baz').remove

To change an attribute of the node:
baz['a'] = 'hiya!'

And to move the node somewhere else:
doc.at('foo').add_child(baz)

This lets us see the node as XML:
doc.to_xml # => "<foo>\n  <bar/>\n  <baz a=\"hiya!\">hello world!</baz>\n</foo>"

This lets us see the XML as if we were looking at a file:
puts doc.to_xml
# >> <foo>
# >>   <bar/>
# >>   <baz a="hiya!">hello world!</baz>
# >> </foo>

A: Well, the solution was just to update the version of Nokogiri.  Presumably, this was a bug that was fixed between versions 1.6.3.1 and 1.6.6.2.


text:
Q: Most suitable way to read keyboard input in C++ I'm trying to write a Keyboard class that can read in the keyboard buttons. I have looked at this link - http://www.daniweb.com/software-development/cpp/code/216732/reading-scan-codes-from-the-keyboard But as stated on there, it is not very accurate for all computers (I don't know if this is even true). Therefore, my question is whats the best method in implementing my keyboard class? This will be used for Windows
Many thanks

A: There are three ways to read keyboard input:

*

*By reading input from a console window as described in your link. It's true that it's hard to get this to work correctly, for starters because it's reading ANSI characters and not Unicode characters, but there are other issues. Console input/output is kind of obscure, as is the documentation for it

*By handling UI events associated with a normal window. In this case you would handle the WM_KEYDOWN message in a window procedure

*By going deep into the Win32 API with functions like SetWindowsHookEx. In this case you don't even need a window (normal or console), and you can read keystrokes pressed in any application or in the desktop

It's hard to suggest which one to use without knowing how you intend to use this Keyboard class.


text:
Q: misunderstanding of Boolean result Can somebody help me a bit? I have trouble understanding why Boolean here doesn't work the way I want to. The idea is when i(firstnum) is odd, l(lastnum) to be equal and vice verse. Some help with how to use Boolean also will be a help, I can't understand it.
Input 3 and 5.
Expected output : 4333 4353 4443 4533 4553 5334 5354 5444 5534 5554
Actual output: 4333 4353 4443 4533 4553 5333 5334 5353 5354 5443 5444 5533 5534 5553 5554
int startNum = Integer.parseInt(scan.nextLine());
int endNum = Integer.parseInt(scan.nextLine());

boolean isItEqual = false;
boolean isItOdd= false;

int countDebugOperations = 0;
for (int i = startNum; i <=endNum ; i++) {

    if (i % 2==0){
        isItEqual =true;
    }
    for (int j = startNum; j <=endNum ; j++) {
        for (int k = startNum; k <=endNum ; k++) {
            for (int l = startNum; l <=endNum ; l++) {
                if (l % 2 == 1){
                    isItOdd = true;
                }
                boolean flag =(i > l) && (j+k) % 2 ==0;

                if(!isItEqual && (!isItOdd) && flag){

                        countDebugOperations+=1;
                        System.out.printf("%d%d%d%d ",i,j,k,l);

                }
                if (isItEqual && isItOdd && flag) {
                    countDebugOperations += 1;
                    System.out.printf("%d%d%d%d ", i, j, k, l);

                }

A: You are trying to print numbers i, j, k and l in exactly two cases:

*

*When i is even AND l is odd

*When l is even AND i is odd

If we translate those cases to code (boolean expressions), we get:

*

*i % 2 == 0 && l % 2 == 1

*l % 2 == 0 && i % 2 == 1
Now, when we iterate through for loops, we can ask if our "number state" matches one of those 2 cases (first case OR second case).
int startNum = Integer.parseInt(scan.nextLine());
int endNum = Integer.parseInt(scan.nextLine());

for (int i = startNum; i <= endNum; i++) {
    for (int j = startNum; j <= endNum; j++) {
        for (int k = startNum; k <= endNum; k++) {
            for (int l = startNum; l <= endNum; l++) {

                boolean firstCase = i % 2 == 0 && l % 2 == 1;
                boolean secondCase = l % 2 == 0 && i % 2 == 1;

                // now when we print, we can ask if we are in the first OR the second case
                if (firstCase || secondCase) {
                    System.out.printf("%d%d%d%d ",i,j,k,l);
                }
            }
        }
    }
}


text:
Q: Fetch distinct receivers from message model while preserving order I'm trying to build a messaging app. Here's my model:
class Message(models.Model):
    sender = models.ForeignKey(User, related_name="sender")
    receiver = models.ForeignKey(User, related_name="receiver")
    msg_content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

This is what I tried in the view:
data = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).order_by('-created_at')

In the template:
{% for abc in data %}
    {{ abc.receiver }} <br/>
{% endfor %}

Here I want to filter the distinct receivers and re-order them based upon the fact that to whom request.user sent new message recently (as we see on social media platforms).
How can I do that?

A: Filter messages sent by request.user, order by receiver_id and  -created_at then use distinct on receiver_id
Message.objects.filter(sender=request.user).order_by('receiver_id','-created_at').distinct('receiver_id')


text:
Q: Eclipse JDK 8 Configuration I configured jdk1.8.0_65 and when I try to build a project using maven, I get an strange error in console.
The same project was successfully build with my old jdk (jdk 7)
Below is the error.

I'm using the following Spring Tool Suite, Version: 3.6.4.RELEASE
and below is my jre configuration in Eclipse.

Any help is appreciated.

A: Please check you java installation because backward compatibility is always present in java releases.Some methods might be deprecated but are still supported.
If your project was compilable on Java 7, it would be surely compilable on java8.

A: I have configured the jdk 64 bit version for my 32 bit operating system. This was the issue.


text:
Q: Xubuntu: xscreensaver crashes on lock screen I'm running 16.04 on a Dell Inspiron 5567.
I removed lightdm so my screen locker is xscreensaver. I did so because I was having trouble with bringing back the system after suspension with lightdm: the screensaver was static and I couldn't type in my password.
An hour ago I was doing a backup of my home folder (around 400GB) and I closed the lid; I went away for about an hour and when I opened the lid the screensaver was static and I couldn't type in my password; I had to hard reboot the machine by keeping the power button pressed. When I could log in I checked the logs Xorg.0.log and Xorg.0.log.old but there was no report of an error.
Any ideas on what this could be? Thanks in advance.


text:
Q: Error: Rank mismatch between actual argument at (1) and actual argument at (2) (scalar and rank-1) in PyOpt I am attempting to install pyOpt and have run into an error where the Mingw64 gfortran compiler throws an error.  It appears that the variable 'g' is held in a common block in an include file while 'dum' is locally declared. What can be done to overcome these errors?
Warning: 'rhoc' may be used uninitialized in this function [-Wmaybe-uninitialized]
pyOpt\pyALGENCAN\source\evalal.f:408:35:

  408 |               call sevalgjacp(n,xp,gp,m,dpdcp,nalp,'T',gotj,inform)
      |                                   1
......
  802 |           call sevalgjacp(n,x,dum,m,ap,ptmp,'j',gotj,inform)
      |                              2
Error: Rank mismatch between actual argument at (1) and actual argument at (2) (scalar and rank-1)
pyOpt\pyALGENCAN\source\evalal.f:112:34:

  112 |               call sevalgjacp(n,x,g,m,p,nl,'T',gotj,inform)
      |                                  1
......
  802 |           call sevalgjacp(n,x,dum,m,ap,ptmp,'j',gotj,inform)
      |                              2
Error: Rank mismatch between actual argument at (1) and actual argument at (2) (scalar and rank-1)
gfortran.exe:f77: pyOpt\pyALGENCAN\source\fparam.f
pyOpt\pyALGENCAN\source\extrap.f:183:10:


text:
Q: iOS - How to check if an NSOperation is in an NSOperationQueue? From the docs:

An operation object can be in at most one operation queue at a time and this method throws an NSInvalidArgumentException exception if the operation is already in another queue. Similarly, this method throws an NSInvalidArgumentException exception if the operation is currently executing or has already finished executing.

So how do I check if I can safely add an NSOperation into a queue?
The only way I know is add the operation and then try to catch the exception if the operation is already in a queue or executed before.

A: When you add an NSOperation object to a NSOperationQueue, the NSOperationQueue retains the object, so the creator of the NSOperation can release it. If you keep with this strategy, NSOperationQueues will always be the only owner of their NSOperation objects, so you won't be able to add an NSOperation object to any other queue.
If you still want to reference individual NSOperation objects after they've been added to the queue, you can do so using the NSOperationQueue's - (NSArray *)operations method.

A: NSOperationQueue objects have a property called operations.
If you have a reference to you queues it is easy to check.
You can check if the NSArray of operations contains your NSOperation like this:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];

NSOperation *operation = [[NSOperation alloc] init];

[queue addOperation:operation];

if([queue operations] containsObject:operation])
    NSLog(@"Operation is in the queue");
else
    NSLog(@"Operation is not in the queue");

Or you can iterate on all the objects:
for(NSOperation *op in [queue operations])
    if (op==operation) {
        NSLog(@"Operation is in the queue");
    }
    else {
        NSLog(@"Operation is not in the queue");
    }

Tell me if this is what you are looking for.
Alternatively, NSOperation objects have several properties that allow you to check their state; such as: isExecuting, isFinished, isCancelled, etc...


text:
Q: cmake does not run the StepTargets of an external project I am using cmake with some projects added via ExternalProject_add and when i add a target with
ExternalProject_Add_StepTargets(SubProject doc)
ExternalProject_Add_Step(SubProject doc)

I get a new target SubProject-doc, but when I build it, the doc target of SubProject is not executed.
The external projects are added like this:
ExternalProject_add(subproject
    SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/subproject
    BINARY_DIR ${subproject_DIR}
    CMAKE_ARGS ${CMAKE_ARGS}
    INSTALL_DIR ${CMAKE_BINARY_DIR}/install
    DEPENDS subproject2
)

A: There is no implicit relation between steps of ExternalProject and targets of the subproject it represents. CMake only knows how to generate some predefined steps, like "download", "configure", "build". For create other steps you need to explicitely specify commands for them:
ExternalProject_Add_Step(Subproject doc
    # Equivalent to 'make doc' but in platform-independent manner
    COMMAND ${CMAKE_COMMAND} --build . --target doc
    # Use automatically-replaced token for refer to binary dir
    WORKING_DIRECTORY <BINARY_DIR>
    # When requested, step is always run.
    # (It is 'make doc' behavior who should care to not generate
    # documentation if it has already been generated.)
    ALWAYS 1
    # This step is not a part of normal build of external project.
    EXCLUDE_FROM_MAIN 1
    # However, this step requires some other steps to be performed
    DEPENDEES configure
    )

After that you may create a target in the main project, which will perform given step:
ExternalProject_Add_StepTargets(SubProject doc)

See more in ExternalProject module's documentation.


text:
Q: mat-side-nav bar does not stretch to the entire width of the window I am currently at intermediate level at understanding Angular (Angular - Version 5). I have been trying to build a sample application of my own and I also intend to use the angular material components for the UX.
When I use mat-side-nav, the navigation content does not stretch to the entire browser/window height. Instead it just extends to a very minimal height.
Following is the piece of code that I am currently have in my project.
Header.component.html

  <mat-toolbar color="primary">
    <button mat-icon-button (click)="snav.toggle()"><mat-icon>menu</mat-icon></button>

Agile Center

    <button mat-icon-button><mat-icon>dashboard</mat-icon></button>
    <button mat-icon-button><mat-icon>settings</mat-icon></button>

        <button mat-icon-button><mat-icon>power_settings_new</mat-icon></button>

  </mat-toolbar>

  <mat-sidenav-container class="example-sidenav-container">
    <mat-sidenav #snav mode="over" fixedTopGap="56">
      <mat-nav-list>
        Backlog
        Active Sprints
        Releases
        Reports
        Issues
        Administration
      </mat-nav-list>
    </mat-sidenav>
    <mat-sidenav-content>
        <router-outlet></router-outlet>
    </mat-sidenav-content>
  </mat-sidenav-container>

Header.component.css
.example-container {
    display: flex;
    flex-direction: column;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: 5px;
}

.example-sidenav-container {
    /* When the sidenav is not fixed, stretch the sidenav container to fill the available space. This
       causes `<mat-sidenav-content>` to act as our scrolling element for desktop layouts. */
    flex: 1;
}

.example-spacer {
    flex: 1 1 auto;
}

No code yet in header.component.ts
Code in app.component.html

  <app-header></app-header>

Screenshot of the side navigation bar

Can anyone help where I am going wrong here?
Thanks to one and all!


text:
Q: Using selection strategies with a cache in Curator The page on Service Discovery using apache curator (https://github.com/Netflix/curator/wiki/Service-Discovery) introduces the following concepts:

*

*
The main abstraction class is ServiceProvider. It encapsulates the discovery service for a particular named service along with a provider strategy. A provider strategy is a scheme for selecting one instance from a set of instances for a given service. There are three bundled strategies: Round Robin, Random and Sticky (always selects the same one). ServiceProviders are allocated by using a ServiceProviderBuilder.

*
Each of the above query methods calls ZooKeeper directly. If you need more than occasional querying of services you can use the ServiceCache. It caches in memory the list of instances for a particular service. It uses a Watcher to keep the list up to date. You allocate a ServiceCache via the builder returned by ServiceDiscovery.serviceCacheBuilder().

I can see how to use the Provider strategies with a ServiceProviderBuilder, but there's no equivalent method on the ServiceCacheBuilder, and the only relevant method available on the ServiceCache class itself is getInstances(), which gets all instances.
How can I use a provider strategy with a ServiceCache?

A: Frankly, the docs on this are really bad. It would be fantastic if someone could give a pull request with better docs...
Notice that ServiceCache implements InstanceProvider. Also notice that ProviderStrategy.getInstance() has as its argument InstanceProvider. Therefore, you can pass a ServiceCache instance to whichever ProviderStrategy you want to use.
I hope this helps.

A: @simonalexander2005 I was just looking in the code and it turns out that ServiceProvider internally already uses a serviceCacheBuilder. TBH - I've either forgotten about this or it got put in by another committer - I'm not sure. Anyway, I'm very sorry about the runaround here. Also, the documentation must be updated to reflect this - I'll open an issue for this today. I'm sure this be maddening to you, again sorry for this. The good news, though, is that with ServiceProvider you automatically get caching.


text:
Q: how do i find out duration/total play time of an mp3 file using java? I am developing an application in Java. Part of it includes playing an mp3 file via another application. I need to find the duration (total play time) of the mp3 file. How do I do that?

A: You can do this very easily using JAudioTagger:
Tag tag;
java.util.logging.Logger.getLogger("org.jaudiotagger").setLevel(Level.OFF);
audioFile = AudioFileIO.read(new File(filePath));
System.out.println("Track length = " + audioFile.getAudioHeader().getTrackLength());

That will print out the track length of the file at filePath. The logger line is to remove a lot of (probably) unwanted info/debugging logging from JAudioTagger. Besides this, JAudioTagger supports getting all sorts of metadata tags from different audio file types (MP3, MP4, WMA, FLAC, Ogg Vorbis), both from file-embedded tags. You can even get MusicBrainz info easily, but I haven't tried that yet. For more info:
http://www.jthink.net/jaudiotagger/examples_read.jsp
You can get the jar files for it here:
http://download.java.net/maven/2/org/jaudiotagger/

A: For small .mp3 files you can use:
AudioFile audioFile = AudioFileIO.read(MyFileChooser.fileName);
int duration= audioFile.getAudioHeader().getTrackLength();
System.out.println(duration);

This will give a string containing the minute and second duration in it. eg: 316 for 3:16.
Note that This method is not suitable with larger files.


text:
Q: Java How to call a method from another mock method Is it possible to call some method from another mock method instead of returning a value using Mockito or PowerMock ?
Here is example to make in clear:
I have a query in production class:
session.createQuery("update clause")
                    .setParameter("")
                    .executeUpdate();
session.flush();

And in my test class I mock it this way:
Query q = mock(Query.class, "q");
when(session.createQuery("update lalala")).thenReturn(q);
when(q.executeUpdate()).thenReturn(something);

Now instead of doing thenReturn(something) I need to call a void method that's situated in my test class too that mocks database behaviour.
i.e.
public void doSomething()
{
  // do smth
}

So that in my test when q.executeUpdate is called then doSomething() is then called too.
I googled for any possible ideas but just can't seem to figure it out.

A: You can use the thenAnswer function. See the documentation
when(q.executeUpdate()).thenAnswer( new Answer<Foo>() {
    @Override
    public Foo answer(InvocationOnMock invocation) throws Throwable {
      callYourOtherMethodHere();
      return something;
    }
} );

A: You can do something like this with EasyMock (maybe with other mocking tools too).
Query q = createMock(Query.class)
expect(q.createQuery("update lalala")).andDelegateTo(anObjectThatCalls_doSomething);
...


text:
Q: Dynamic combo chart that changes via month selector I'm trying to build a dashboard that can update detailed information based on the "Month Selector." I have a named range with the formula:
=OFFSET('Labor Data'!$B$1,MATCH(MATCH(Dashboard!$T$3,Dashboard!$C$3:$N$3,0)-1,'Labor Data'!$A:$A),0,MAX(IF('Labor Data'!$A:$A=MATCH(Dashboard!$T$3,Dashboard!$C$3:$N$3,0),ROW('Labor Data'!$A:$A)))-MATCH(MATCH(Dashboard!$T$3,Dashboard!$C$3:$N$3,0),'Labor Data'!$A:$A,0)+1,5)

I know it works. It properly highlights the range I would expect in the data worksheet. But when I plug the name of the range into the Chart Data Range field, the Horizontal Axis Labels resolve and doesn't change when I change the month. Is there any way to keep the Horizontal axis dynamic?

A: I gave up on the named range and wrote the solution into VBA that triggers when the dropdown box's value is changed.
Private Sub Worksheet_Change(ByVal monthSel As Range)
Set dash = Worksheets("Dashboard")
Set labor = Worksheets("Labor Data")

setMonth = dash.Range("T3").Value

If Not Intersect(monthSel, Range("T3")) Is Nothing Then

    monthNum = Application.WorksheetFunction.Match(setMonth, dash.Range("C3:N3"), 0)

    Set dynRangeTop = labor.Range("A:A").Find(monthNum, LookIn:=xlValues, LookAt:=xlWhole)
    Set dynRangeBot = labor.Range("A:A").Find(monthNum, LookIn:=xlValues, LookAt:=xlWhole, SearchDirection:=xlPrevious)
    Set chartRng = labor.Range("C" & dynRangeTop.Row & ":" & "G" & dynRangeBot.Row)

    dash.ChartObjects("MonthSum").Chart.SetSourceData Source:=chartRng, PlotBy:=xlColumns
End If

End Sub


text:
Q: Run regex rule for outlook 365 I want to run a regex based rule for outlook 365.
I saw that I can do this for outlook 2007
But is it possible to do this also for outlook 365?

A: The link you are referring to is based on the VBA macro call where regular expressions are used. You can do the same for any offline Office edition, but not the web one. So, you can implement the same for Outlook 2013.


text:
Q: Verilog Error: System task finish is always executed I'm using a Mimas V2 with a Spartan 6 CSG324 LX9. Trying to teach myself to use Verilog and I've been using this tutorial. I've had no issues running VHDL modules and running just this code Verilog code (which appears towards of the problematic chunk further down) seems to work:
module myModule(A, B);
    input wire A;
    output wire B;
    assign B = !A;
endmodule

Doesn't really do much though, as the inputs and outputs aren't set up to do anything though.
It seems to be having a problem with line 15 here:
module myModule_tb();
    wire out;
    reg clock;

    always begin
        #1 clock =!clock;
    end

    initial begin
        //Initialize clock
        clock = 0;

        //End simulation
        #10
        $finish;  //<-------this line here
    end

    myModule notGate(clock, out);
endmodule

module myModule(A, B);
    input wire A;
    output wire B;
    assign B = !A;
endmodule

The error message I get when I try to implement is

HDLCompiler:1689 - "C:\Xilinx\Projects\Test2\myModule_sim.v" Line 15: System task finish is always executed.

Now as best as I could tell, I followed all the steps correctly. I even went so far as to download the example files provided (the Mimas version) at the bottom of that tutorial, and it does the same thing. I understand roughly what the $finish task does, but I'm not sure why it's causing a problem here. Seems like it's fussing at me for expecting finish to do what it's supposed to do here.
I've tried a semi colon after the #10 on the preceeding line, putting them on the same line, commenting out #10, commenting out both #10 and $finish and I always get the same or an error related to not having $finish
Help! I'm not sure why ISE is rejecting that line!

A: So I installed ModelSim and that somehow convinced ISE to stop complaining about $finish. The weird thing is that I'm still not using a ModelSim simulator, it's using ISim. So I don't know what was wrong, but it works now :/ not totally helpful to future folks, sorry!

A: I was getting this problem too, the thing that was causing it for me was I was clicking the green arrow rather than right clicking "Simulate Behavioral Model" and selecting Run. The green arrow implements the top module, which wasn't correct. Right clicking runs iSim properly with the test module.


text:
Q: Cambiar letras por numeros en kotlin Por ejemplo quiero cambiar un string nombre:
val Nombre = "Julian"

y se transforme a "Jul14n"

A: esto funciona:
import java.util.*;

public class Main {

    public static void main(String[] args) throws Exception {

        System.out.println(changeChars("Julian"));
    }

    private static String changeChars(String inputWord){
        String resp = "";
        for (int i = 0; i < inputWord.length(); i++) {

            resp = resp + changeOneChar(inputWord.charAt(i));
        }
        return resp;
    }

    private static char changeOneChar(char aChar){
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("i", "1");
        map.put("a", "4");

        String key = String.valueOf(aChar);
        String resp = "";

        resp = map.get(key);
        if (resp == null){
            resp = key;
        }

        return resp.charAt(0);
    }

}

Fijate que tenes una funcion changeChars que recorre cada letra y la manda a cambiar, y la funcion changeOneChar que busca en el diccionario si la letra está, y la cambia, sino la deja como está.
Podes agregar todas las letras que quieras a ese diccionnario.
Podrás criticar la solución diciendo que se instancia el map cada vez que se quiere cambiar un char, es un tema con static talvez puedas dejarla como variable global. No dudes en consultar.
Saludos
JP


text:
Q: C# and Data Hiding I'm new to C# and .Net in general so this may be a naive thing to ask. But anyway, consider this C# code:
class A {
    public int Data {get; set;}
}

class B {
    public A Aval {get; set;}
}

The B.Aval property above is returning a reference to its internal A object. As a former C++ programmer, I find this dangerous because by exposing reference to an member object class B violates the principle of data hiding. Nonetheless, this seems to be the normal practice in the C# world.
My question is, if it is at all, why is such a design the usual approach as opposed to returning copies of internal members, which will be much safer in so many ways (including the case of thread safety)?
I understand that even in C++ sometimes good design demands that you do expose class members directly (a Car class with Engine and Stereo objects inside it comes to mind), but it is not the norm as seems to be in C#.

A: You're absolutely right - you should only return objects from properties where either the object is immutable, or you're happy for the caller to modify it to whatever extent they can. A classic example of this is returning collections - often it's much better to return a read-only wrapper round a collection than to return the "real" collection directly.
On the other hand, pragmatism sometimes calls for just documenting this as "please don't change the returned object" - particularly when it's an API which is only used within a company.
Hopefully there'll be more support for immutability in future versions of C# and .NET, which will make this easier to cope with - but it's likely to remain a knotty problem in many cases.

A: This isn't encapsulation - it's an act of abstraction through object composition or aggregation depending on how the internal object lifetimes are created/managed.
In composition patterns it is perfectly acceptable to access composite state e.g. the instance of A in the instance of B.

http://en.wikipedia.org/wiki/Object_composition

As you point out the semantics of encapsulation are very different - to completely hide the internal implementation of A e.g. by inheriting B from A.

A: This is maybe related to the Law of Demeter... are you talking only about getters and setters that have no extra logic (and thus effectively directly expose the member), or any get-set pairs?  In any case, if this portion of the outer object's state doesn't participate in meaninful invariants on the outer object, I don't think it's necessarily unreasonable to do this.


text:
Q: Exception in thread "main" org.openqa.selenium.WebDriverException: element not interactable (Session info: chrome=91.0.4472.114) why I try to send key but can't send any key in webview
i got this erorr massega
what i can do
Exception in thread "main" org.openqa.selenium.WebDriverException: element not interactable
  (Session info: chrome=91.0.4472.114)


text:
Q: Solr Index using Avro files I have build large inverted index and I have stored my inverted index in avro format not I want to expose this as a service. I was wondering is there a way to load avro files to solr so solr can index the inverted index that I have built.
Here is how my inverted-index looks like:
{"key":"10.08","bucket":0,"itemIds":[161049555960]}
{"key":"100-1000-pcs","bucket":0,"itemIds":[590143038066]}
{"key":"11-2972","bucket":0,"itemIds":[130941586664]}
{"key":"1106200","bucket":0,"itemIds":[111132254095]}
{"key":"1370","bucket":0,"itemIds":[380680582645]}

A: You may be able to use Apache Flume to process the Avro source, and use the Solr Sink to index them. (Tho I'm not very familiar with Flume.)


text:
Q: Intellij version of Emacs' Meta-X Emacs has the nice property of being able to access any command using Meta-X and typing the name of the command (with completion).  Does IntelliJ have such a feature?  For example, I installed the line sorter plugin, but I keep forgetting what keybinding I set for it because I use it rarely.  In Emacs I'd do M-x sort-lines.

A: Try
Ctrl-Shift A

It searches through commands as you type, showing the keyboard shortcuts as well.


text:
Q: Why laravel route must precedence order, otherwise page not found? I'm learning how to use Redis in Laravel, and found a strange things like this:
when Route articles/trending above on the Route articles/{article}, Route article/trending can work fine:
My Router code picture
And When articles/{article} above on articles/trending, Route articles/trending cannot be found?
Who can tell me the reason? and Thank you very much!

A: Because the {article} statement in your route is nothing more than a placeholder.
If you put
Route::get('articles/{article}')

above the other routes that have the structure
Route::get('articles/...')

then the {article} statement will just catch everything you put after the /.
This is because Laravel's Router (and AFAIK, every router for whatever langauge or framework) seeks for the first possible match between URL and defined routes.
{article} is a placeholder, and if defined first, will always be the first possible match.


text:
Q: Bash variable expansion I'm getting stuck on something that surely has a simple solution. I'm using mail from GNU mailutils to periodically send a log file to relevant people.
mail -s "The Subject" someone@example.com <<< "Message body"

Now I want to incorporate that in a script that performs a bunch of tasks, but I'm getting stuck with the expansion and the quotes.
This is what I'm trying:
subject="The Subject"
sender=From:Sender\<someone@example.com\>
recipient_list=me@example.com,another@example.com,yetanother@example.com

report="mail -s "$subject" -a $sender $recipient_list"

...
$report <<< "A log message from a section of script"
...
$report <<< "A different log message"

The trouble is with $subject.
Calling mail -s "$subject" -a $sender $recipient_list <<< "My Message" works nicely, but wrapping it into a variable as I've done above ends up sending the email with only the first word of "The Subject" getting sent, not the whole string.
I'm going to go the proper function route, but now I'm curious.
I'm sure some escape/expansion trick will do it, but I have not been able to find the correct one (or reason it out).
Thanks!

A: The answer, of course, is use an array.
report=(mail -s "$subject" -a "$sender" "$recipient_list")

 ...

"${report[@]}" <<< "A log message from a section of script"


text:
Q: Apple push notification service, when device is off line My push notification service in sandbox development phase works well when the device is online. It keeps getting push messages.
However if a message is sent from te provider (server) when the device is offline (no 3g or wifi), the device is not receiving the push message when it gets online.
Any thoughts on this?

A: UPDATE New rephrased documentation is here
Thanks AL
After going through Apple's Quality of Service https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html
It retains only one notification per application on a device:

Apple Push Notification Service includes a default Quality of Service (QoS) component that performs a store-and-forward function. If APNs attempts to deliver a notification but the device is offline, the QoS stores the notification. It retains only one notification per application on a device: the last notification received from a provider for that application. When the offline device later reconnects, the QoS forwards the stored notification to the device. The QoS retains a notification for a limited period before deleting it.


text:
Q: How to use the data CRC of SD cards in SPI mode? I am interfacing an SD card through SPI using an AVR microcontroller (more specifically it is the Uzebox console).
I can successfully initialize the card with turning CRC check ON with CMD59 (so I have a proven working CRC7 algorithm), and can read sectors from it (dumping the data read by CMD17 gives correct results: I see what is on the card proper).
What I can't seem to get working is a CRC check for the data sectors using the CRC bytes received from the card.
I currently have three SDSC cards which I verified to behave in the following manner with my algorithm:

*

*Two of the cards give the same value for both CRC bytes, neither corresponding the result of CRC-CCITT with either 0x0000 or 0xFFFF start value (tested with multiple sectors, the values change according to the data of the sector, but the two bytes are always the same).

*The third card seems to have no CRC at all, providing 0x0000 on these bytes.
The SPI transmission code for those final bytes seem correct, I did some steps to verify that I indeed read what I want to including that I really do two SPI transactions for the two bytes.
Anyone have any idea what could be happening there? Or should I just forget about those CRC bytes? (maybe the cards just not implement them or do it incorrectly in SPI mode)

A: So, regarding the two "CRC-delivering cards": It's kind of hard to debug this without any example data and CRC, but the most common problem one encounters is that the generator polynomials are "meant" the other way around, ie. whether \$x^0\$ corresponds to the first or the last bit.
Checking is easy: just have test data that you have both in original and reversed bit order, and see what makes sense.
Now, you've tested with 0xFFFF and 0x0000 already, which are symmetrical. At least for 0x0000, the result of a polynomial should definitely be zero, shouldn't it? What are you expecting, what are you getting?
Reference:
http://users.ece.utexas.edu/~valvano/EE345M/SD_Physical_Layer_Spec.pdf , p. 54f

A: Here are algorithms which I found correctly calculating CRCs.
The SD Command CRC:
/* CRC7 table (for SD commands) */
static unsigned int sd_crc7_table[256];

(...)

/* Running CRC7 calculation for a byte. */
static unsigned int sd_crc7_byte(unsigned int crcval, unsigned int byte)
{
 return sd_crc7_table[(byte ^ (crcval << 1)) & 0xFFU];
}

(...)

/* Generate CRC7 table */
for (byt = 0U; byt < 256U; byt ++){
 crc = byt;
 if ((crc & 0x80U) != 0U){ crc ^= 0x89U; }
 for (bit = 1U; bit < 8U; bit ++){
  crc <<= 1;
  if ((crc & 0x80U) != 0U){ crc ^= 0x89U; }
 }
 sd_crc7_table[byt] = (crc & 0x7FU);
}

(...)

crcval = 0x00U;
crcval = sd_crc7_byte(crcval, first_byte);
(...)
crcval = sd_crc7_byte(crcval, last_byte);
crc_byte = (crcval << 1) | 0x01U;

The SD Data CRC:
/* CRC16 table (for SD data) */
static unsigned int sd_crc16_table[256];

(...)

/* Running CRC16 calculation for a byte. */
static unsigned int sd_crc16_byte(unsigned int crcval, unsigned int byte)
{
 return (sd_crc16_table[(byte ^ (crcval >> 8)) & 0xFFU] ^ (crcval << 8)) & 0xFFFFU;
}

(...)

/* Generate CRC16 table */
for (byt = 0U; byt < 256U; byt ++){
 crc = byt << 8;
 for (bit = 0U; bit < 8U; bit ++){
  crc <<= 1;
  if ((crc & 0x10000U) != 0U){ crc ^= 0x1021U; }
 }
 sd_crc16_table[byt] = (crc & 0xFFFFU);
}

(...)

crcval = 0x0000U;
crcval = sd_crc16_byte(crcval, first_byte);
(...)
crcval = sd_crc16_byte(crcval, last_byte);
crc_byte_0 = crcval >> 8;
crc_byte_1 = crcval & 0xFFU;

The crc_byte and crc_byte_0 and crc_byte_1 values may be used to provide the necessary CRC data towards the card or for comparison when reading (data sectors). For the data sectors, crc_byte_0 comes first (so CRC is Big Endian on the card).


text:
Q: Why can't both args and keyword only arguments be mixed with *args and **kwargs simultaneously The usage of *args and **kwargs in python is clear to me and there are many questions out there in SO (eg Use of *args and **kwargs and What does ** (double star/asterisk) and * (star/asterisk) do for parameters?).
But one thing I would like to understand is: why is it not possible to simultaneously define mandatory positional args, mandatory kwarg arguments and eventually still allow catching other args and kwargs as in cant_do_that below?
def one_kwarg_is_mandatory(*, b, **kwargs):
    print(b)
    for key, value in kwargs.items():
        print(key, value)

def one_pos_arg_and_one_kwarg_are_mandatory(a, *, b, **kwargs):
    print(a, b)
    for key, value in kwargs.items():
        print(key, value)

# I wanted a mandatory arg (a) and possibly parse other args (*args),
# then a mandatory kwarg (b) and eventually other kwargs (**kwargs)
def cant_do_that(a, *args, *, b, **kwargs):
    print(a, b)
    print(args)
    for key, value in kwargs.items():
        print(key, value)

# not really interested on this because "b" must be a kwarg and hiding
# it under **kwargs would not be explicit enough for my customer (sometimes myself ;))
def could_do_this_but(a, b, *args, **kwargs):
    print(a, b)
    print(args)
    print(kwargs)

Yes one could get rid of b in the could_do_this_but function's signature, perform (for instance) a kwargs.get("b", None) at the top of the function and raise some appropriate error if found None... but having "b" directly on the function signature would allow faster and more explicit code development employing the function down the road.

A: The correct syntax is def cant_do_that(a, *args, b, **kwargs):. Note that * is used only once, both to mark the end of positional arguments and to set the name for variadic positional arguments.

The * in a function definition is syntactically unique at the separation between positional-or-keyword and keyword-only arguments:
parameter_list_starargs   ::=  "*" [parameter] ("," defparameter)* ["," ["**" parameter [","]]]
                               | "**" parameter [","]

In short, the grammar "*" [parameter] means * and *args are syntactically the same thing – a literal * and optional name – which may occur only once. Use a bare * to start keyword-only arguments without taking variadic positional arguments, and use a named *args to start keyword-only arguments with taking variadic positional arguments.

If the form "*identifier" is present, it is initialized to a tuple
receiving any excess positional parameters, defaulting to the empty
tuple. [...] Parameters after "*" or "*identifier" are keyword-only
parameters and may only be passed used keyword arguments.


text:
Q: React hook useEffect always re-render on React Navigation When using functional components, that are the default "page" on createSwitchNavigator, after navigating to the bottomTabNavigator, if the state is changed (not only when the conditional trigger is changed), the whole component will re-render, causing the useEffect code to be executed again.
I have the navigation routed like this:
const Routes = createAppContainer(
  createSwitchNavigator({
    Sign: createSwitchNavigator({
      Preload,
      SignIn,
    }),
    App: createBottomTabNavigator(
      {
        Home,
        Employees,
      },
    ),
  }),
);

and the functional component which makes navigation between SignIn and Home:
const Preload = ({navigation, logged}) => {
    useEffect(() => {
        if (logged) {
            navigation.navigate({routeName: 'Home'});
        } else {
            navigation.navigate({routeName: 'SignIn'});
        }
    }, [logged]);

    return (
        <Container>
            <ActivityIndicator color="#1199DD" size={50}/>
        </Container>
    );
}

also noting that there is a container/page connector for flux action dispatcher using the hooks:
const mapDispatchToProps = dispatch => ({
    actions: {
        ...appActions(dispatch),
        dispatch
    },
})

const mapStateToProps = state => ({
    ...state.app
})

export default connect(mapStateToProps, mapDispatchToProps)(Preload)

the connect function mainly creates a consumer passing props, dispatch and my store state:
const isFunction = target => typeof target === 'function'
const defaultMapStateToProps = () => ({})
const defaultMapDispatchToProps = () => ({})

export default appContext => (originalMapStateToProps, originalMapDispatchToProps) => {

    const { Consumer } = appContext

    const mapStateToProps = isFunction(originalMapStateToProps)
        ? originalMapStateToProps
        : defaultMapStateToProps
    const mapDispatchToProps = isFunction(originalMapDispatchToProps)
        ? originalMapDispatchToProps
        : defaultMapDispatchToProps

    return Component => (props) => (
        <Consumer>
            {store => (
                <Component
                    {...props}
                    {...mapStateToProps(store.getState())}
                    {...mapDispatchToProps(store.dispatch)}
                />
            )}
        </Consumer>
    )
}

I've tried using hook useRef to consider the last value, but since it re-renders everything, the last value is not trusted, since it will always recreate this variable.
What is really triggering everything to re-render? And how would be the best approach to bypass it?

A: The solution was to abandon connect/container which inits a Consumer, since I'm using React Hooks its best to send actions and state that was previously hooked with dispatch when initializing useReducer.
Following this example:
const [useContext, Provider] = createRootContext();

function createRootContext() {
    const RootContext = createContext(initialStateCombined);

    function useContext() {
        const c = React.useContext(RootContext);
        if (!c) throw new Error('');
        return c;
    }
    return [useContext, RootContext.Provider];
}

function RootProvider(props) {
    const [state, dispatch] = useReducer(appReducer, appInitialState);

    const actions = {
        app: {...appActions(dispatch)},
    };

    return <Provider value={{ state, actions }}>{props.children}</Provider>;
}

export { useContext, RootProvider };

This being my Provider (as the highest Parent of the App) I can access anything from the state by importing useContext from it, like so:
const Preload = ({navigation}) => {
    const { state: { app } } = useContext();

    useEffect(() => {
        if (app.logged) {
            navigation.navigate('Home');
        } else {
            navigation.navigate('SignIn');
        }
    }, [app.logged])

    return (
        <Container>
            <ActivityIndicator color="#1199DD" size={50}/>
        </Container>
    )
}


text:
Q: Creating a new probabilistic matrix from two existing ones according to prespecified rules in MATLAB I have a problem in my MATLAB code. Let me first give you some explanation about the issue. I have two matrices which represent probabilities of specific outcomes of events. The first one is called DemandProbabilityMatrix or in short DemandP. Entry (i,j) shows the probability that item i is demanded j many times. Similarly, we have a ReturnProbabilityMatrix, i.e. ReturnP. An element of type (i,j) stores the probability that item i is returned j many times.
We want to compute the net demand probability out of these two matrices. For an example:

DemandP=[ .4 .5 .1]
  ReturnP=[ .2 .3 .5]

In this case we have 1 item and it can be demanded or returned either 1,2 or 3 times with the given probabilities. To be more specific That item will be demanded just for once with probability .4 .
Then we need to compute the net demand. In this case, net demand can be -2,-1,0,1 or 2. For instance in order to get a net demand of -1 we can either have a demand of 1 and return of 2 or demand of 2 and return of 3. Thus we have

NetDemandP(1,2)= DemandP(1,1)*ReturnP(1,2)+DemandP(1,2)*ReturnP(1,3).

Thus the NetDemandP should look as:

NetDemandP=[.20 .37 .28 .13 .02]

I can do this with nested for loops but I'm trying to come up with a faster way. In case it helps I have the following for loops solutions where I denotes the number of rows in ReturnP and DemandP, J+1 denotes the number of columns in those matrices.
NetDemandP=zeros(I,2*J+1);
    for i=1:I
        for j=1:J+1
            for k=1:J+1
                NetDemandP(i,j-k+J+1)=NetDemandP(i,j-k+J+1)+DemandP(i,j)*ReturnP(i,k);
            end
        end
    end

Thanks in advance

A: What you want is the convolution of your probability density functions. Or, more specifically, you want the convolution of the demand density with the reverse of the return density. This is easily achieved in Matlab. For example:
DemandP = [.4 .5 .1];
ReturnP = [.2 .3 .5];
NetDemandP = conv(DemandP,fliplr(ReturnP))

If you have matrices instead of vectors, then just iterate through the rows:
for i = 1:size(DemandP,1)
    NetDemandP(i,:) = conv(DemandP(i,:),fliplr(ReturnP(i,:)))
end


text:
Q: What is the largest number we can get using $n$ ones, addition, multiplication and brackets? Let's say we have $n$ ones, i.e. $1,1,\dots,1$ $n$ times and are allowed to add them, multiply and insert brackets wherever we want.
What is the largest number we can get for a particular $n$? Is there a closed form or at least an OEIS sequence?
For $n=5$ it appears to be $(1+1)(1+1+1)=6$, for $n=6$ it appears to be $(1+1+1)(1+1+1)=9$, for $n=9$ I found $(1+1+1)(1+1+1)(1+1+1)=27$ to be the largest number.
But I don't see a way to find a general formula. I guess it would make sense to start from the other end - for each number $N$ find a factorization with the least sum of factors or something like that.

A: Since
1) it doesn't make sense to create any 1+1+1+... terms with more than 3 1's, since 1+1+1+1+1 is 'worse' than (1+1) times (1+1+1),  and for more 1's it will be even 'better' to multiply several 1+1+.. Terms rather than have one long one, and with 4 1s 1+1+1+1 is just as good as (1+1) times (1+1),
and
2) two 1+1+1 terms is better than three 1+1 terms,
your basic strategy is to get as many 1+1+1 terms as possible. So:
If n mod 3 = 0, the best you can do is $3^{n/3}$
If n mod 3 = 1, get two 1+1 terms, and otherwise 1+1+1 terms, so you get $4*3^{(n-4)/3}$
If n mod 3 = 2, get one 1+1 term in addition to 1+1+1 terms, so $2*3^{(n-2)/3}$

A: Don't know if this could be an "approximate" solution or anything. But try the following.
If the final expression consists of $x_1 \times ... \times x_k$ where $x_1+...+x_k=n$, with $k<n$, Holding n,k fixed, and suppose the $x$'s need not be integers for the moment, the max is $(n/k)^k$. Taking derivative wrt k and get $(n/k)^k ( \ln(n/k)-1)=0)$ to obtain the best $k$ which is about $n/e$, with optimally each term being approx $x \approx 2.7$, which can be as good as $3$ in the case of integers

A: Obviously the problem reduces to finding the maximum of $a_1 \cdot a_2 \cdot ... \cdot a_t$, when $a_1 + a_2 + ... + a_t = n$. Now let's increase $a_1$ by one and decrease $a_2$ by one. Then the value of $a_1 \cdot a_2 \cdot ... \cdot a_t$ will increase if $a_1 \ge a_2+2$. Eventually this leads to concluding that for a "fixed" $t$ the maximum will occur when $a$'s are as close as possible.
Now let's find the optimal $t$. As previously concluded assume that $a_1 = \cdots = a_t = a$. Then we have $a = \frac nt$. Now $a_1 \cdot a_2 \cdot ... \cdot a_t = \left(\frac nt \right)^t$. This function obtains a maximum at $t=e$, so therefore the maximum is obtained for $t = \frac ne$
As all the variables are integers and as the functions are continuous we have that the we need to choose $t = \left\lfloor \frac ne \right\rfloor$ or $\left\lfloor \frac ne \right\rfloor + 1$. In each case we choose $a_i = \left\lfloor \frac nt \right\rfloor$ or $\left\lfloor \frac nt \right\rfloor + 1$ accordingly, s.t. the sum is $n$. This reduces the problem to few cases, which can be easily checked.


text:
Q: Função para formartar horas Montei a função abaixo que me retorna horas nesse formato 4:5:3 (hora, minuto, segundo).
Gostaria de retornar nesse formato 04:05:03(hora, minuto, segundo).
function converter($time)
{

    if (is_int($time)) {

        $horas    = floor($time / 3600);
        $minutos  = floor(($time - ($horas * 3600)) / 60);
        $segundos = floor($time % 60);

        $newtime = $horas . ":" . $minutos . ":" . $segundos;

    } else {

        echo "o valor deve ser um inteiro";

    }

    return $newtime;

}

A: Você pode formatar da seguinte forma se $time for um timestamp:
$horaFormatada = date('H:i:s', $time);

A: Tens de apresentar no formato de DateTime, senão ele tira o zero, porque um zero à esquerda não conta.
function converter($time)
{

if (is_int($time)) {

    $horas    = floor($time / 3600);
    $minutos  = floor(($time - ($horas * 3600)) / 60);
    $segundos = floor($time % 60);

    $newtime= new DateTime();
    $newtime->setTime($horas, $minutos, $segundos);

} else {

    echo "o valor deve ser um inteiro";

}

return $newtime;

}


text:
Q: ObservableCollection does not update UI On startup i bind an ObservableCollection to a menu:
Menu.ItemsSource = _manager.Selection;

This menu correctly displays all objects from the collection.
Now i want to update the collection and add/remove some of the items in it:
private void OnBoxClick(object sender, RoutedEventArgs e)
    {
        _manager.Selection = _manager.GetNewSelection();
        PropertyChanged?.Invoke(this, new CollectionChangeEventArgs(CollectionChangeAction.Refresh, _manager.Selection));
    }

    public event CollectionChangeEventHandler PropertyChanged;

But the ui is still displaying how it was before..
What is missing?

A: You should either re-set the Menu.ItemsSource property (to _manager.GetNewSelection()) or add or remove items from _manager.Selection. Setting the _manager.Selection field to another instance of an ObservableCollection<T> won't affect the menu's ItemsSource property.
If you get a completely new collection from the _manager.GetNewSelection(), you might as well just do this:
private void OnBoxClick(object sender, RoutedEventArgs e)
{
    Menu.ItemsSource = _manager.GetNewSelection();
}

And then it doesn't matter whether _manager.GetNewSelection returns an ObservableCollection or any other kind of IEnumerable that doesn't provide notifications when items are added or removed.


text:
Q: How to reshape a multi-column dataframe by index? Following from here . The solution works for only one column. How to improve the solution for multiple columns. i.e  If I have a dataframe like
df= pd.DataFrame([['a','b'],['b','c'],['c','z'],['d','b']],index=[0,0,1,1])

   0  1
0  a  b
0  b  c
1  c  z
1  d  b

How to reshape them like

  0   1  2  3
0  a  b  b  c
1  c  z  d  b

If df is

   0  1
0  a  b
1  c  z
1  d  b

Then

   0  1   2  3
0  a  b NaN  NaN
1  c  z   d  b

A: Use flatten/ravel
In [4401]: df.groupby(level=0).apply(lambda x: pd.Series(x.values.flatten()))
Out[4401]:
   0  1  2  3
0  a  b  b  c
1  c  z  d  b

Or, stack
In [4413]: df.groupby(level=0).apply(lambda x: pd.Series(x.stack().values))
Out[4413]:
   0  1  2  3
0  a  b  b  c
1  c  z  d  b

Also, with unequal indices
In [4435]: df.groupby(level=0).apply(lambda x: x.values.ravel()).apply(pd.Series)
Out[4435]:
   0  1    2    3
0  a  b  NaN  NaN
1  c  z    d    b

A: Use groupby + pd.Series + np.reshape:
df.groupby(level=0).apply(lambda x: pd.Series(x.values.reshape(-1, )))

   0  1  2  3
0  a  b  b  c
1  c  z  d  b

Solution for unequal number of indices - call the pd.DataFrame constructor instead.
df

   0  1
0  a  b
1  c  z
1  d  b

df.groupby(level=0).apply(lambda x: \
      pd.DataFrame(x.values.reshape(1, -1))).reset_index(drop=True)

   0  1    2    3
0  a  b  NaN  NaN
1  c  z    d    b

A: pd.DataFrame({n: g.values.ravel() for n, g in df.groupby(level=0)}).T

   0  1  2  3
0  a  b  b  c
1  c  z  d  b

This is all over the place and I'm too tired to make it pretty
v = df.values
cc = df.groupby(level=0).cumcount().values
i0, r = pd.factorize(df.index.values)
n, m = v.shape
j0 = np.tile(np.arange(m), n)
j = np.arange(r.size * m).reshape(-1, m)[cc].ravel()
i = i0.repeat(m)

e = np.empty((r.size, m * r.size), dtype=object)

e[i, j] = v.ravel()

pd.DataFrame(e, r)

   0  1     2     3
0  a  b  None  None
1  c  z     d     b

A: Let's try
df1 = df.set_index(df.groupby(level=0).cumcount(), append=True).unstack()
df1.set_axis(labels=pd.np.arange(len(df1.columns)), axis=1)

Output:
   0  1  2  3
0  a  b  b  c
1  c  d  z  b

Output for df with NaN:
   0     1  2     3
0  a  None  b  None
1  c     d  z     b


text:
Q: Excel Macro to cut after "," and paste into another cell Hi I am trying to create a macro that will cut text from a cell after a comma, and then paste into another cell.
What i have tried to come up with
Sub Macro3()
'
' Macro3 Macro
'
' Keyboard Shortcut: Ctrl+e
'
    ActiveCell.Offset(4, 0).Rows("1:1").EntireRow.Select
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    ActiveCell.Offset(0, 2).Range("A1").Select
    ActiveCell.FormulaR1C1 = "40000"
    ActiveCell.Offset(-1, 1).Range("A1").Select
    Selection.Copy
    ActiveCell.Offset(1, 0).Range("A1").Select
    ActiveSheet.Paste
    ActiveCell.Offset(-3, 1).Range("A1:A3").Select
    Application.CutCopyMode = False
    Selection.Cut
    ActiveCell.Offset(1, 0).Range("A1").Select
    ActiveSheet.Paste
    ActiveCell.Offset(-2, -3).Range("A1").Select
    Selection.Copy
    ActiveCell.Offset(1, 3).Range("A1").Select
    ActiveSheet.Paste
    ActiveCell.Select
    Application.CutCopyMode = False
    ActiveCell.FormulaR1C1 = _
        " Copied Text, "
    ActiveCell.Offset(-1, -3).Range("A1").Select
    ActiveCell.FormulaR1C1 = "Remaining.Text"
    ActiveCell.Offset(5, 0).Range("A1").Select
End Sub

A: You could use the following
Function POP_To_Delimiter(strInput As String, Optional strDelimiter As String = ",", Optional PopToDelimiter As Integer = 1) As String

Dim a() As String
a = Split(strInput, strDelimiter)
ReDim Preserve a(PopToDelimiter - 1)
POP_To_Delimiter = Trim(Join(a, strDelimiter))

End Function

Function POP_From_Delimiter(strInput As String, Optional strDelimiter As String = ",", Optional PopFromDelimiter As Integer = 1) As String

Dim a() As String
a = Split(StrReverse(strInput), strDelimiter)
ReDim Preserve a(UBound(a) - PopFromDelimiter)
POP_From_Delimiter = Trim(StrReverse(Join(a, strDelimiter)))

End Function

Using like so
POP_From_Delimiter("F110F1A3EER.TACA, Los, Ex d, Light , RT66.") = Los, Ex d, Light , RT66.
and
POP_to_Delimiter("F110F1A3EER.TACA, Los, Ex d, Light , RT66.") = F110F1A3EER.TACA


text:
Q: How to highlight current child page on custom sidebar menu? I have a sidebar menu on a WordPress site that simply outputs all the child pages under that parent. I'm trying to highlight (or hopefully add an arrow) the current child page that is selected. I've run into a wall with my limited PHP experience to figure out how to do that.
Any help would be greatly appreciated. The relevant code is below:
 <?php

                /* if the current pages has a parent, i.e. we are on a subpage */
                if($post->post_parent){
                    /* $children = wp_list_pages("title_li=&include=".$post->post_parent."&echo=0"); // list the parent page */
                    $children .= wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0"); // append the list of children pages to the same $children variable
                }

                /* else if the current page does not have a parent, i.e. this is a top level page */
                else {
                    //$children = wp_list_pages("title_li=&include=".$post->ID."&echo=0");    // include the parent page as well
                    $children .= wp_list_pages("title_li=&child_of=".$post->ID."&echo=0&");   // form a list of the children of the current page
                }

                /* if we ended up with any pages from the queries above */
                if ($children) { ?>

                <?php echo $children; /*print list of pages*/ ?>

            <?php } ?>

I'm assuming it would be in the  output section, but I simply don't know how to target the current child page that's being browsed and highlight that accordingly.

A: I had a little fun with this one. And my result might not be exactly what you were looking for, but I think it might be better. In short, the below snippet allows you to easily identify the page hierarchy (parent/children) for the current page. As such, you can then do all sorts of wonderful things to your heart's desire. For the purposes of your specific request, I made the custom function "custom_list_child_pages(...)" return a full list of links from the page hierarchy related to the "current page".
There is tons of logic, all related to the key situations you were trying to tackle. You should be able to identify when you are in a sub-page or parent page, you should be able to call out that little function and modify it to make it do whatever you need it to do with all the relevant players (current, parent [or self if no other], child pages, etc).
Let me know if this helps you and if you get stuck with the code or any other aspects regarding what you are trying to achieve let me know as well and I will see how I can assist you further.
Code:
<?php

//die(var_dump($foo)); // Quickly check a variable value.

function custom_list_child_pages($the_current_page_id, $the_parent_page_id, $child_pages){
   $html_page_listing = '';

   // Get creative with the parent page.
   $the_parent_page = get_page( $the_parent_page_id );
   $html_page_listing .= "
" . "guid'>$the_parent_page->post_title" . "
";

   // Get creative with the child pages.
   $html_page_listing .= "
" . "Child pages:" . "
";

   $html_page_listing .= "
";

   // Iterate through child pages as desired.
   foreach ($child_pages as $key => $page) {
      $current_page = get_page_by_title( $page->post_title );
      $current_page_id = $page->ID;

      if ($current_page_id == $the_current_page_id) {
         // Do something great.
         $html_page_listing .= "
 ->" . "guid'>$page->post_title" . "
";
      } else {
         $html_page_listing .= "
" . "guid'>$page->post_title" . "
";
      }
   }
   $html_page_listing .= "
";
   return $html_page_listing;
}

global $post; // If outside the loop.

// Set up the objects needed.
$my_wp_query = new WP_Query();
$all_wp_pages = $my_wp_query->query(array('post_type' => 'page', 'posts_per_page' => '-1'));

if ( is_page() && $post->post_parent ) {
   // This is a subpage.
   $the_current_page_id = $page_id;
   $the_parent_page_id = wp_get_post_parent_id( $post_ID );

   $the_child_pages = get_page_children( $the_parent_page_id, $all_wp_pages ); // Form a list of the children of the current page.
   $the_parent_page_id = wp_get_post_parent_id( $post_ID ); // Include the parent page as well.

   $menu = custom_list_child_pages($the_current_page_id, $the_parent_page_id, $the_child_pages); // ~append the list of children pages to the same $children variable
   echo $menu; // Print list of pages.

} else {
   // This is not a subpage.
   $the_current_page_id = $page_id;
   $the_parent_page_id = $page_id;

   $the_child_pages = get_page_children( $page_id, $all_wp_pages ); // Form a list of the children of the current page.
   $the_parent_page_id = $page_id; // Include the parent page as well.

   $menu = custom_list_child_pages($the_current_page_id, $the_parent_page_id, $the_child_pages);
   echo $menu; // Print list of pages.
}

?>

Regards,
Arty


text:
Q: Validate an input field of a form in Jquery i have this function in jquery that verify if ALL the fields have at least one character inputed, i mean, if they are not empty, as you can see in the code below:
function validateStep(step){
    if(step == fieldsetCount) return;

    var error = 1;
    var hasError = false;
    $('#formElem').children(':nth-child('+ parseInt(step) +')').find(':input:not(button)').each(function(){
        var $this       = $(this);
        var valueLength = jQuery.trim($this.val()).length;

        if(valueLength == ''){
            hasError = true;
        }

    });
    var $link = $('#navigation_form li:nth-child(' + parseInt(step) + ') a');
    $link.parent().find('.error,.checked').remove();

    var valclass = 'checked';
    if(hasError){
        error = -1;
        valclass = 'error';
    }
    $('').insertAfter($link);

    return error;
}

it happens that in such a big form i have, there is one field that is not required. I still have some difficult in implementing jquery code and i don't see what if i can insert in the middle of this function to say that specific field is not required.
Can anyone give me a little help?
Thanks in advance!

A: Try checking to see if the ID of the current element doesn't match the ID of the element you wish to exclude:
var $this = $(this);
if($this.attr('id') != 'SOMEID'){
  // Validate
}

A: you could tag your required fields with a specific class and iterate trough the fields which have this class 'required', this makes it easy to change your decision which fields you want to check
i suggest the jQuery validation plugin from http://bassistance.de/jquery-plugins/jquery-plugin-validation/ by Jörn Zaefferer, it uses this technique to validate forms

A: I suggest you use a jquery plugin
eg.
http://docs.jquery.com/Plugins/Validation#demo
http://bassistance.de/2011/05/14/release-validation-plugin-1-8-1/
it will make your work easy.

A: Why not just add an attribute - isRequired=true || isRequired=false and then gather up and validate the elements you need by the attribute value?


text:
Q: Select determined rows from mysql with determined word SELECT * FROM `table` WHERE `column`='System'

and this select 'SYSTEM' too. I want to select only and accurately  `column`='System' without 'SYSTEM'.
I'm try this:
SELECT * FROM `table` WHERE `column` REGEXP [[:<:]]'System'[[:>:]]

but again I have 'SYSTEM' too.


text:
Q: No errors but celery task not sending email as expected I am trying to learn how to perform asynchronous tasks using Celery.
My app.py file:
from flask import Flask, render_template
from celery import Celery
from flask_mail import Mail, Message
from flask_wtf import FlaskForm
from wtforms import StringField
import os
from dotenv import load_dotenv
load_dotenv()

app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
app.config['MAIL_SERVER'] = 'smtp.googlemail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = os.getenv('MAIL_USERNAME', default='')
app.config['MAIL_PASSWORD'] = os.getenv('MAIL_PASSWORD', default='')
app.config['MAIL_DEFAULT_SENDER'] = os.getenv('MAIL_USERNAME', default='')
app.config['MAIL_SUPPRESS_SEND'] = False
app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'

celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])

mail = Mail(app)

@celery.task
def send_celery_email(message_data):
    with app.app_context():
        message = Message(subject=message_data['subject'], recipients= [message_data['recipients']], body= message_data['body'])
        mail.send(message)

@celery.task
def hello():
    print('Hello')

class MyForm(FlaskForm):
    email = StringField('email')

@app.route('/', methods=['GET', 'POST'])
def index():
    form = MyForm()

    if form.validate_on_submit():
        email = form.email.data
        message_data = {
            'subject': 'Hi from Flask app',
            'recipients': email,
            'body': 'This is an email sent from the flask app'
        }

        send_celery_email.delay(message_data)
        hello.delay()

        return 'Email sent!'
    return render_template('index.html', form=form)

if __name__ == '__main__':

    app.run()

my docker-compose.yml file:
version: "3.7"

services:
    redis:
        image: redis
        ports:
            - 6379:6379

I have done the following:

*

*Opened up a powershell terminal with my virtual environment and ran a redis server in docker

(env) PS C:\projects-directory\simpleceleryproj> docker-compose up -d

I checked that the server was up and running using the telnet command. When the blank screen appeared i typed "PING" and it returned "PONG".
(env) PS C:\projects-directory\simpleceleryproj> telnet localhost 6379

*Opened another powershell terminal with my virtual environment active and started the celery worker

(env) PS C:\projects-directory\simpleceleryproj> celery -A app.celery worker

This is what appears on the screen:
(env) PS C:\projects-directory\simpleceleryproj> celery -A app.celery worker

 -------------- celery@LAPTOP-MKMU5ESC v5.0.5 (singularity)
--- ***** -----
-- ******* ---- Windows-10-10.0.18362-SP0 2021-04-08 10:42:51
- *** --- * ---
- ** ---------- [config]
- ** ---------- .> app:         app:0x35dac28
- ** ---------- .> transport:   redis://localhost:6379/0
- ** ---------- .> results:     disabled://
- *** --- * --- .> concurrency: 8 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
 -------------- [queues]
                .> celery           exchange=celery(direct) key=celery

I then started the flask app, filled in the form and submitted it.
I get redirected to the 'Email sent!' page, but nothing actually happens. I dont receive an email in my inbox as I should.
I know the code is working because when I call the celery task function on its own directly I get an email as expected:
send_celery_email(message_data)

I really don't know why it's not working.
Any help would be appreciated!
Upate:
I ran the celery worker with logging enabled and see the following output:
[2021-04-08 11:31:55,080: INFO/MainProcess] celery@LAPTOP-MKMU5ESC ready.
[2021-04-08 11:32:10,707: INFO/MainProcess] Received task: app.send_celery_email[3798423c-eff9-4b9f-9024-550e905d167b]
[2021-04-08 11:32:10,714: INFO/MainProcess] Received task: app.hello[46dc45bb-603d-48ce-af35-62d99c523db2]
[2021-04-08 11:32:11,392: INFO/SpawnPoolWorker-10] child process 18348 calling self.run()
[2021-04-08 11:32:11,392: INFO/SpawnPoolWorker-9] child process 9472 calling self.run()
[2021-04-08 11:32:11,397: INFO/SpawnPoolWorker-11] child process 16932 calling self.run()
[2021-04-08 11:32:11,404: INFO/SpawnPoolWorker-12] child process 17932 calling self.run()
[2021-04-08 11:32:12,993: INFO/SpawnPoolWorker-13] child process 13416 calling self.run()
[2021-04-08 11:32:12,993: INFO/SpawnPoolWorker-14] child process 5680 calling self.run()
[2021-04-08 11:32:13,022: INFO/SpawnPoolWorker-15] child process 17024 calling self.run()
[2021-04-08 11:32:14,586: INFO/SpawnPoolWorker-16] child process 6484 calling self.run()

So celery actually does receive the tasks, it just doesnt execute them and I cant understand why.

A: I solved this issue by calling the worker with this command:
celery -A app.celery worker --pool=solo --loglevel=info
For more info on this:
https://www.distributedpython.com/2018/10/26/celery-execution-pool/


text:
Q: Eclipse Package/Project Explorer Filters: Show dirty files Is there a way to filter files in Eclipse's Project/Package Explorer views based on the state of a file according to Git (or SVN)? Ideally, I'd only like to see files that are marked dirty, select, and right-click on them as a group so I can access this context menu.

Eclipse has a "Git Staging" view which gives me the same list. But right-clicking on the files from this view gives a different context menu that I don't want: