text:
Q: Oracle SQL: Using intervals to specify ranges of hours I have power meter data stored in table MeterData:
    create table MeterData (
    MeterID VARCHAR2(10), DownloadCycle VARCHAR2(6), DateHour Date,
    KWH Number(22,6), KW Number(22,6), KVA Number(22,6), KVAR Number(22,6),
    CONSTRAINT UniqueDownload UNIQUE(MeterID, DownloadCycle, DateHour))

The data looks like this:

MeterID
DownloadCycle
DateHour
KWH
KW
KVA
KVAR

2319927
202206
13/06/2022 00:00
0.138
0.552
0.552
0

2500350
202206
13/06/2022 00:15
0.612
2.448
2.916
1.584

2500351
202206
13/06/2022 01:30
0.8
3.2
3.2358
0.48

2500352
202206
13/06/2022 04:00
0.288
1.152
1.44
0.864

2500353
202206
13/06/2022 05:30
0.90808
3.63232
4.32456
0

2500396
202206
13/06/2022 12:00
68.09
272.36
277.101157
51.04

2500446
202206
13/06/2022 18:15
0
0
0
0

2500453
202206
13/06/2022 21:00
2.772
11.088
11.088
0

2500472
202206
13/06/2022 23:30
64.8
259.2
305.788256
162.24

2500490
202206
14/06/2022 00:30
2.4
9.6
9.6
0

2501352
202206
14/06/2022 01:45
11.64
46.56
46.56
0

5187222
202206
14/06/2022 06:30
1.452
5.808
7.392
0

5284288
202206
14/06/2022 11:00
66.792
267.168
267.447334
149.336

5516997
202206
14/06/2022 18:30
0.384
1.536
8.112
0

I need to assign every record in table MeterData to a range of hours stored in table HourlyBlocks, in which I'm using intervals as the starting and ending hours:
    create table HourlyBlocks (
    HourlyBlock VARCHAR2(6) UNIQUE, BlockStart INTERVAL DAY(1) TO SECOND(0),
    BlockEnd INTERVAL DAY(1) TO SECOND(0));
    insert into HourlyBlocks values (
    'Rest', interval '0 05:00:00' day to second, interval '0 18:00:00' day to second);
    insert into HourlyBlocks values (
    'Peak', interval '0 18:00:00' day to second, interval '0 23:00:00' day to second);
    insert into HourlyBlocks values (
    'Valley', interval '0 23:00:00' day to second, interval '1 05:00:00' day to second);

(HourlyBlock 'Valley' begins at 23:00:00 and ends at 05:00:00 of the following day).
To test to which HourlyBlock every record in MeterData belongs, I extract the record's hour, minute and second information as an interval with the following, adding 1 day to the interval if it is less than 05:00:00 and thus belongs to HourlyBlock 'Valley':
    select distinct m.MeterID, m.DateHour, m.kwh,
    NUMTODSINTERVAL(m.DateHour - trunc(m.DateHour), 'DAY') + case when
      NUMTODSINTERVAL(m.DateHour - trunc(m.DateHour), 'DAY') <= interval '00 05:00:00'
      day to second then interval '1' day else interval '0' day end as intval,
    h.HourlyBlock
    from MeterData m, HourlyBlocks h
    where (NUMTODSINTERVAL(m.DateHour - trunc(m.DateHour ), 'DAY') > h.BlockStart
    and NUMTODSINTERVAL(m.DateHour - trunc(m.DateHour ), 'DAY') + case when
      NUMTODSINTERVAL(m.DateHour - trunc(m.DateHour ), 'DAY') <= interval '00 05:00:00'
      day to second then interval '1' day else interval '0' day end <= h.BlockEnd)

The HourlyBlock are correctly assigned, except for records where DateHour is between 00:00:00 and 05:00:00!
What am I doing wrong?
The expected output for the sample data provided would be:
|MeterID|DateHour        |KWH   |intval             |HourlyBlock|
|-------|----------------|------|-------------------|-----------|
|2319927|13/06/2022 00:00|0.138 |+00 00:00:00.000000|Valley     |
|2500350|13/06/2022 00:15|0.612 |+01 00:15:00.000000|Valley     |
|2500351|13/06/2022 01:30|0.8   |+01 01:30:00.000000|Valley     |
|2500352|13/06/2022 04:00|0.288 |+01 04:00:00.000000|Valley     |
|2500353|13/06/2022 05:30|0.908 |+00 05:30:00.000000|Rest       |
|2500396|13/06/2022 12:00|68.09 |+00 12:00:00.000000|Rest       |
|2500446|13/06/2022 18:15|0     |+00 18:15:00.000000|Peak       |
|2500453|13/06/2022 21:00|2.772 |+00 21:00:00.000000|Peak       |
|2500472|13/06/2022 23:30|64.8  |+00 23:30:00.000000|Valley     |
|2500490|14/06/2022 00:30|2.4   |+01 00:30:00.000000|Valley     |
|2501352|14/06/2022 01:45|11.64 |+01 01:45:00.000000|Valley     |
|5187222|14/06/2022 06:30|1.452 |+00 06:30:00.000000|Rest       |
|5284288|14/06/2022 11:00|66.792|+00 11:00:00.000000|Rest       |
|5516997|14/06/2022 18:30|0.384 |+00 18:30:00.000000|Peak       |

(I'm sorry I had to format the output as code. It was the only way around that pesky "Your post appears to contain code that is not properly formatted as code" error.)

A: I found the fix, and simplified my WHERE clause:
    select distinct m.MeterID, m.DateHour, m.kwh,
    NUMTODSINTERVAL(m.DateHour - trunc(m.DateHour), 'DAY') + case when
      NUMTODSINTERVAL(m.DateHour - trunc(m.DateHour), 'DAY') <= interval '00 05:00:00'
      day to second then interval '1' day else interval '0' day end as intval, h.HourlyBlock
    from MeterData m, HourlyBlocks h
    where NUMTODSINTERVAL(m.DateHour - trunc(m.DateHour), 'DAY') +
      case when NUMTODSINTERVAL(m.DateHour - trunc(m.DateHour), 'DAY')
      <= interval '00 05:00:00' day to second then interval '1' day else
      interval '0' day end between h.BlockStart + interval '1' second and h.BlockStart


text:
Q: HTML Not Rendering as Expected I am trying to replicate the 'Services Tab' section on this page, and here is the source code.
I want it to appear like this:

I have managed to get this to display:

Below is my ASPX:
 <asp:Repeater ID="rptGroupDescriptions" runat="server" OnItemDataBound="rptGroupDescriptions_ItemDataBound" OnItemCommand="rptGroupDescriptions_ItemCommand">
                    <ItemTemplate>

                                <a href="#service-<%#Eval("Group_Id") %>" data-toggle="tab"><%#Eval("Group_Name")%>

                            <div class="tab-pane fade active in" id="service-<%#Eval("Group_Id") %>">

<%#Eval("Group_Name")%>

<%#Eval("Group_Desc")%>

                    </ItemTemplate>
                </asp:Repeater>

And here is the sample code which I have used:

 Service One

 Service Two

 Service Three

 Service Four

Service One

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae repudiandae fugiat illo cupiditate excepturi esse officiis consectetur, laudantium qui voluptatem. Ad necessitatibus velit, accusantium expedita debitis impedit rerum totam id. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus quibusdam recusandae illum, nesciunt, architecto, saepe facere, voluptas eum incidunt dolores magni itaque autem neque velit in. At quia quaerat asperiores.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae repudiandae fugiat illo cupiditate excepturi esse officiis consectetur, laudantium qui voluptatem. Ad necessitatibus velit, accusantium expedita debitis impedit rerum totam id. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus quibusdam recusandae illum, nesciunt, architecto, saepe facere, voluptas eum incidunt dolores magni itaque autem neque velit in. At quia quaerat asperiores.

Service Two

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae repudiandae fugiat illo cupiditate excepturi esse officiis consectetur, laudantium qui voluptatem. Ad necessitatibus velit, accusantium expedita debitis impedit rerum totam id. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus quibusdam recusandae illum, nesciunt, architecto, saepe facere, voluptas eum incidunt dolores magni itaque autem neque velit in. At quia quaerat asperiores.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae repudiandae fugiat illo cupiditate excepturi esse officiis consectetur, laudantium qui voluptatem. Ad necessitatibus velit, accusantium expedita debitis impedit rerum totam id. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus quibusdam recusandae illum, nesciunt, architecto, saepe facere, voluptas eum incidunt dolores magni itaque autem neque velit in. At quia quaerat asperiores.

Service Three

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae repudiandae fugiat illo cupiditate excepturi esse officiis consectetur, laudantium qui voluptatem. Ad necessitatibus velit, accusantium expedita debitis impedit rerum totam id. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus quibusdam recusandae illum, nesciunt, architecto, saepe facere, voluptas eum incidunt dolores magni itaque autem neque velit in. At quia quaerat asperiores.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae repudiandae fugiat illo cupiditate excepturi esse officiis consectetur, laudantium qui voluptatem. Ad necessitatibus velit, accusantium expedita debitis impedit rerum totam id. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus quibusdam recusandae illum, nesciunt, architecto, saepe facere, voluptas eum incidunt dolores magni itaque autem neque velit in. At quia quaerat asperiores.

Service Four

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae repudiandae fugiat illo cupiditate excepturi esse officiis consectetur, laudantium qui voluptatem. Ad necessitatibus velit, accusantium expedita debitis impedit rerum totam id. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus quibusdam recusandae illum, nesciunt, architecto, saepe facere, voluptas eum incidunt dolores magni itaque autem neque velit in. At quia quaerat asperiores.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae repudiandae fugiat illo cupiditate excepturi esse officiis consectetur, laudantium qui voluptatem. Ad necessitatibus velit, accusantium expedita debitis impedit rerum totam id. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus quibusdam recusandae illum, nesciunt, architecto, saepe facere, voluptas eum incidunt dolores magni itaque autem neque velit in. At quia quaerat asperiores.

I assume that one problem may be the fact that I have not added class="Active" to the list item, but I couldn't because then each list item would have that class.
So here is my Code Behind code also:
//Trying to display group descriptions using repeater
    SqlConnection connGroupDesc;
    string connStringGroupDesc = ConfigurationManager.ConnectionStrings[
        "BallinoraDBConnectionString1"].ConnectionString;
    connGroupDesc = new SqlConnection(connStringGroupDesc);
    SqlDataAdapter sdaGroupDesc = new SqlDataAdapter("SELECT * FROM Groups", connGroupDesc);
    DataTable dtGroupDesc = new DataTable();
    sdaGroupDesc.Fill(dtGroupDesc);
    rptGroupDescriptions.DataSource = dtGroupDesc;
    rptGroupDescriptions.DataBind();

Can anyone advise me how to improve my above code to go about this?

A: You can use a ternary operator in your ItemTemplate which uses the ItemIndex
<ul id="myTab" class="nav nav-tabs nav-justified" <%# Container.ItemIndex == 0 ? "class=\"Active\"" : string.Empty %>>

This way only the first
 will have a Active class.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to change td content after ajax update I need to update the content of my td which have unique id after an ajax update.
However my approach doesnt work, the ajax is succesful but td will only update after page reload.
$(document).ready(function(){
        $('body').on('click', '.editButton', function(e){

            var postID = $(this).val();
            var postURL = "../Controller/update.php";
            var postNama = $("#nama"+postID).val();
            var postMSISDN = $("#msisdn"+postID).val();
            var postSMS = $("#sms"+postID).val();

            $.ajax({
                type: "POST",
                url: postURL,
                data:
                {
                    nama: postNama,
                    msisdn: postMSISDN,
                    sms: postSMS,
                    id: postID
                },
                success: function(data){
                    $("#nama"+postID).html(postNama);
                    $("#msisdn"+postID).html(postMSISDN);
                    $("#sms"+postID).html(postSMS);
                }
            });
            e.preventDefault();

        });
    });

the html i echoed :

                            ".$data['id']."
                            ".$data['nama']."
                            ".$data['msisdn']."
                            ".$data['sms']."
                            <button type='button' class='btn btn-default' data-toggle='modal' data-target='#editModal".$data['id']."'>Edit</button>
                            <button type='button' class='btn btn-danger' data-toggle='modal' data-target='#deleteModal".$data['id']."'>Delete</button>

update.php :
<?php
require_once "../Model/Model.php";

$nama = $_POST["nama"];
$msisdn = $_POST["msisdn"];
$sms = $_POST["sms"];
$id = $_POST["id"];

updateData($nama, $msisdn, $sms, $id);
?>

model.php :
    function updateData($nama, $msisdn, $sms, $id){
    try{
        $conn = new PDO('mysql:host=localhost; dbname=crud', 'root', '');

        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PDOException $e){
        echo 'ERROR: ' . $e->getMessage();
    }
    $conn->prepare("UPDATE data SET nama = ?, msisdn = ?, sms = ? WHERE id = ?")->execute([$nama, $msisdn, $sms, $id]);
}

A: Perhaps you need to pass return data in the td like this,as the data paramter is used to send the data to the server.
success: function(data){
   $("#nama"+postID).html(data);
   $("#msisdn"+postID).html(data);
   $("#sms"+postID).html(data);
 }

A: Based on your comment I think the problem is that you are using the same id for inputs you are taking the data from and the element you are trying to fill the data in. So you just need to change the ids for the td elements and edit the script according to that. Like:
$(document).ready(function(){
    $('body').on('click', '.editButton', function(e){

        var postID = $(this).val();
        var postURL = "../Controller/update.php";
        var postNama = $("#nama"+postID).val(); //there are ids of the inputs
        var postMSISDN = $("#msisdn"+postID).val();
        var postSMS = $("#sms"+postID).val();

        $.ajax({
            type: "POST",
            url: postURL,
            data:
            {
                nama: postNama,
                msisdn: postMSISDN,
                sms: postSMS,
                id: postID
            },
            success: function(data){
                $("#nama-td-"+postID).html(postNama); //and there for the td elements
                $("#msisdn-td-"+postID).html(postMSISDN);
                $("#sms-td-"+postID).html(postSMS);
            }
        });
        e.preventDefault();

    });
});

And of course change the html according to that:
                        ".$data['nama']."
                        ".$data['msisdn']."
                        ".$data['sms']."

I also would recommend you to check on the server if there is no error saving the data print the error and donnt change the values if there was.

A: If your server returns a JSON then you can use the following technique:
Let us assume your serve returns JSON data like so:
{name:"somename",msisdn:"9898989898",sms:"some_sms"}

Then you can apply the following:
success: function(data){
$("#nama"+postID).html(data.name);
$("#msisdn"+postID).html(data.msisdn);
$("#sms"+postID).html(data.sms);
}

Remember if your server does not send the content type :application/json headers with the data then you need to parse the response first like so:
success: function(data){
var parsedData = JSON.parse(data);
$("#nama"+postID).html(parsedData.name);
$("#msisdn"+postID).html(parsedData.msisdn);
$("#sms"+postID).html(parsedData.postSMS);
}


text:
Q: Very easy question: How Do I understand the language of basic Mathematics operations? Yes. So Even though I understand Calculus and I'm Undergraduate Physics student, I can't wrap my head around simple mathematics conundrums,
like x=something, basically making one number equal to something else, which by this logic is the same thing as the number in question. e.g:
$$ 27= \sqrt[4]{531441} $$ - so here I don't understand how does one's mind come up with it? Sure, I understand that $$ 531441=27*27*27*27 $$
But what does one's mind need to have programmed inside of it to have this magical number/ math operations skills to be so obvious and instant? - I think here about instantanenous ability to transform simple numbers in to these weird expressions, which sure are logical, but SO much not INTUITIVE and Over the top???
Have a look:
$$ 6= \log_5(15625)\ $$
sure, If I were to think about it I could've eventually come up with derivation of this, using some basic logarithm properties, but how come I do these operations at an instant inside of my head, without much of thinking, if at all?

A: Are you referring to some real-life situations where you've been stumped by people's ability to quickly do calculations in their heads? (Not that this has much to do with mathematics as such - calculators can do it even faster!) I can assure you that, at the most basic level, people who either like the mathematics as a subject, or have had a lot of experience with calculation, probably have remembered a lot of (sort-of curious) results. In other words, for some people, it is just joy (rather than a chore) to remember and play with various numbers.
For example, powers of two ($1, 2, 4, 8, 16, ...$ and maybe even up to $2^{64}=18,446,744,073,709,551,616$ because of curious stories such as https://en.wikipedia.org/wiki/Wheat_and_chessboard_problem), powers of three ($1, 3, 9, 27, 81$ etc.) or of five ($1, 5, 25, 125, 625$ etc.), digits of $\pi$ ($3.14159265358979323846...$) etc.
With your example, people may recognise that $15625=5^6$ is one of powers of $5$, and that $531441=3^{12}$ is one of powers of $3$ (so $\sqrt[4]{531441}=\sqrt[4]{3^{12}}=3^{12/4}=3^3=27$ - another power of $3$).

A: Let's deal with the first example of finding $\sqrt[4]{531{,}441}$. Few people know that $27^4 = 531{,}441$, so the rest of us usually resort to divisibility rules. noting that the sum of the digits of $531{,}441$ is a multiple of nine [which implies that $531{,}441$ is a multiple of nine as well], we have $513{,}411 = 9\times 59{,}049$. Similarly noting that the sum of the digits of $59{,}049$ is also a multiple of nine, we have $531{,}441 = 9\times9\times6561$. Continuing this process we eventually end up with $$531{,}441 = 9^6 = (3^2)^6 = 3^{12} = (3^3)^4 = 27^4$$
The second example also uses divisibility rules, but with fives instead of nines. Using a similar method we eventually come up with $15{,}625 = 5^6$. But a leaner approach may be to split $15{,}625$ into $15{,}000 + 625$, and note that one number is a multiple of $5{,}000$ [which is a multiple of $5^4$ because $5{,}000= 5\cdot 1000 = 5 \cdot (2\cdot5)^3$], and the other is equal to $25^2 = 5^4$. So dividing we have $\frac{15{,}625}{625}=25$, which implies that $$15{,}625 = 625\cdot 25 = 25^3=5^6$$
Of course this happens mentally much faster than I can type, and with fewer words. If I were to vocalize my mental explanation to myself it would sound more like "da ding, da ding, da ding, cha-ching. Okay, got it."
One way at becoming skilled at mathematizing is to take some practice problems and not solve them in the same way all the time, but instead to develop multiple approaches. This way you will give yourself multiple strategies to choose from, which, over time, and with practice, you eventually earn a sense of which ones are most efficient in particular situations.
I'm saying all of this, noting that there are some quantities [as other commentators have already pointed out] that are just known and memorized ... numbers like $\sqrt 2, \pi, e, \phi$, and of course who could forget $625=25\times25$ (it even rhymes .... which begs the question, can a word rhyme with itself? ... but maybe I'll save that one for social media.).


text:
Q: TCL Freeing up memory I have a basic question regarding memory management in TCL.

*

*Suppose I have a Tcl procedure. Inside the procedure I declare an array and add some data in it. I do some number crunching on that array. My question is before the procedure returns do I need to manually delete the array? Using:
unset <array_name>

My answer is no. But I am not sure since I don't know if there is a garbage collector in Tcl. Can anyone comment on this please.

*Is using array in Tcl bad? I want to create Array of lists and while reading discussions on stack overflow people told to use dict for these kind of stuff but since I have Tcl 8.4 I can't. What is the problem with arrays in Tcl?

A:

*

*Suppose I have a Tcl procedure. Inside the procedure I declare an array and add some data in it. I do some number crunching on that array. My question is before the procedure returns do I need to manually delete the array?

No. It will be deleted when the procedure returns (i.e., its lifespan is bounded to that of the stack frame). You may unset it earlier if you wish, which will free up its memory then, but you don't need to do that.

*

*Is using array in Tcl bad? I want to create Array of lists and while reading discussions on stack overflow people told to use dict for these kind of stuff but since I have Tcl 8.4 I can't. What is the problem with arrays in Tcl?

Arrays are absolutely fine in 8.4, so long as you remember that they are a collection that implements a map from arbitrary string keys to variables. Dicts are for cases where you want a value that holds a map from strings to arbitrary values. (There's a dict extension for 8.4 somewhere about.) You can use arrays to model matrices by choosing some character as a separator between the sub-indices (e.g., a comma) and this technique has been used by many people to great effect.
However it is more efficient to model them as lists of lists; the lset and multi-index lindex permit efficient update and lookup of elements of the resulting matrix. (It is a bit verbose though.) If you're dealing with a lot of data, the improved efficiency can be very useful. (Sparse matrices may be better done as a Tcl array despite that.) Also note that if you can upgrade to 8.5, a number of operations there are significantly faster (notably including testing for the presence of an element of an array with info exists).

A: Tcl does have garbage collection (the exact implementation is undefined, whether it's reference counting or some other method). So no, you don't have to use unset to avoid memory leaks.
I'm not sure why arrays would be considered bad. You will have to provide references to such discussions to get specific comments.

A: No, you do not need to free your local vars when you exit a procedure.  They are automatically freed.  This is the case most of the time, but there are exceptions (some extensions may require you to free things explicitly, and some packages, notably http, create tokens that need to be cleaned up)
If you create large arrays in the global namespace, these will not be freed, because they can still be accessed.
There is no problem using arrays in tcl, but make sure you are using the right tool. In tcl an array is an "associative array", that is it is indexed by string.  If you need a c-style array indexed by integer a plain old list may be better (you can pass it around by value) but you might consider it a little clumsier (subscripting is a command rather than a variable reference with a subkey)


text:
Q: Example of length structure with Euclidian intrinsic metric but different path lengths This is an exercise from "A course in metric geometry" by Burago and Ivanov I am having some troubles with.
Give an example of length structure on the plane for which all continuous curves are admissible, the resulting intrinsic metric is the standard Euclidian one, but lengths of some curves differ from their euclidian lengths.
I have an example for $C^2$ paths but struggling to do this for continuous curves. Thank you.

A: A hint: Define the length $L(c)$ of every piecewise-linear path $c$ to be its Euclidean length. Define the length $L(c)$ to be $\infty$ for all other continuous paths $c$. Now, go through the list of axioms of a length structure (see e.g.here) that this is indeed a length structure. Lastly, think  of a path $c$ such that $L(c)$ differs from the Euclidean length of $c$.
Edit. Suppose, in addition to the usual axioms of a length space you want the set of paths of finite length to be the same as in the Euclidean case. Here is a modification of my construction above:
Let $A$ be the subset of rectifiable (from Eucldiean viewpoint) continuous curves (maps from finite intervals to $R^2$). Let's define a length structure on $A$ as follows. For each $f:[a,b]\to R^2$ which belongs to $A$, let $S_f\subset [a,b]$ be the union of all open  intervals $I\subset [a,b]$ such that $f$ restricted to these intervals is smooth (say, $C^1$). Then the Euclidean length $L(f)$ of $f$ equals
$$
L(f)=\int_{S_f}|f'(t)|dt + R_f.
$$
Furthermore, let $G_f$ be the union of all open subintervals of $S_f$ such that the restriction of $f$ to each of these subintervals is linear (more precisely, affine). Lastly, let $H_f:= S_f - G_f$. Now, set
$$
L'(f):= \int_{G_f}|f'(t)|dt + 2\int_{H_f}|f'(t)|dt + R_f.
$$
Hence, for each piecewise-linear path $f$, $L'(f)=L(f)$ but, in general, $L'(f)\ne L(f)$. For each nonrectifiable path $f$ set $L'(f)=\infty$.
I will leave you to check that $L'$ satisfies all the axioms of a length structure and defines the usual (Euclidean) distance on $R^2$ (since we did not change lengths of linear paths).


text:
Q: how to use quad core CPU in application For using all the cores of a quad core processor what do I need to change in my code is it about adding support of multi threading or is it which is taken care by OS itself. I am having FreeBSD and language I am using is C++. I want to give complete CPU cycles to my application at least 90%.

A: I think your only option is to run several threads. If your application is single-threaded, then it will only run on one of the cores (at a time), but if you have more threads, they can run simultaneously.

A: You need some form of parallelism. Multi-threading or multi-processing would be fine.
Usually, multiple threads are easier to handle (since they can access shared data) than multiple processes. However, usually, multiple threads are harder to handle (since they access shared data) than multiple processes.
And, yes, I wrote this deliberately.
If you have a SIMD scenario, Ninefingers' suggestion to look at OpenMP is also very good. (If you don't know what SIMD means, see Ninefingers' helpful comment below.)

A: You need to add support to your application for parallelism through the use of Threading.
Once you have support for parallelism, it's up to the OS to assign your threads to CPU cores.

A: For multi-threaded applications in C++ may I suggest Boost.Thread which should help you access the full potential of your quad-core machine.
As for changing your code, you might want to consider making things as immutable as possible.  State transitions between threads are much more difficult to debug.  There a plethora of things that could potentially happen in unexpected ways.  See this SO thread.

A: Another option not mentioned here, threading aside, is the use of OpenMP available via the -fopenmp and the libgomp library, both of which I have installed on my FreeBSD 8 system.
These give you #pragma directives to parallelise certain loops, while statements etc i.e. the bits you can parallelise. It takes care of threading and cpu association for you. Note it is a general solution and therefore might not be the optimum way to parallelise, but it will allow you to parallelise certain routines.
Take a look at this: https://computing.llnl.gov/tutorials/openMP/
As for using threads/processes themselves, certain routines and ways of working lend themselves to it. Can you break tasks out into such a way? Does it make sense to fork() your process or create a thread? If so, do so, but if not, don't try to force your application to be multi-threaded just because. An example I usually give is the greatest common divisor algorithm - it relies on the step before all the time in the traditional implementation therefore is difficult to make parallel.
Also note it is well known that for certain algorithms, parallelisation is actually slower for small values of whatever you are doing in parallel, because although the jobs complete more quickly, the associated time cost of forking and joining (be that threads or processes) actually pushes the time above that of a serial implementation.

A: The first thing I think you should look at is whether your application and its algorithms are suited to be executed in parellel (or possibly as a set of serial tasks that can be processed independently). If this is not the case, it will be difficult to multithread it or break it up into parallel processes, and you may need to look into modifying the way it works.
Once you have established that you will be able to benefit from parallel processing you have the option to either use several processes or threads. The choice depends a lot on the nature of your application and how independent the parallel processes can be. It is easier to coordinate and share data between threads since they are in the same process, but also quite a bit more challenging to develop and debug.
Boost.Thread is a good library if you decide to go down the multi-threaded route.

A:
I want to give complete CPU cycles to my application at least 90%.

Why?  Your chip's not hot enough?
Seriously, it takes world experts dozens if not hundreds of hours to parallelize and load-balance an application so that it uses 90% of all four cores.  Your CPU is already paid for and it costs the same whether you use it or not.  (Actually, it costs slightly less to run, electrically speaking, if you don't use it.)  How much is your time worth?  How many hours are you willing to invest in order to make more effective use of a resource that may have cost you $300 and is probably sitting idle most of the time anyway?
It's possible to get speedups through parallelism, but it's expensive in human time.  You need a good reason to justify it.  (Learning how is a good enough reason.)
All the good books I know on parallel programming are for languages other than C++, and for good reason.  If you want interesting stuff on parallelism check out Implicit Parallel Programmin in pH or Concurrent Programming in ML or the Fortress Project.


text:
Q: Why my carObject move to z-axis?
Hi, I just made a script to move a car around Unity.
But I see my car moving not only on the x-axis, but also slightly on the z-axis. Is this normal?
And I don't know how to upload pictures, but did I post them correctly?
CarMove.cs
public class CarMove : MonoBehaviour {

    public float speed = 10.0f;

    void Update () {
        this.transform.Translate(Vector3.forward * speed);
    }
}

A: Unity Vector3.froward
Because simply, Unity Vector3.forward is an abbreviation of Vector3(0, 0, 1) which adds 1 unit to the z axis.
You can check here as well :
https://docs.unity3d.com/ScriptReference/Vector3.html
Happy coding!


text:
Q: How to Convert ROW/COL to Lat/Long in Python/NetCDF4 I'm relatively new to NetCDF and working with a CMAQ model output in NetCDF format.  There is no explicit lat/long variable, rather each variable is stored with a ROW/COL.  I assume the Global attributes contain what I need to convert to long/lat or Northings and Eastings but I have not found a way to do it with the netCDF4 package or Xarray.
The files are 20GB so I'll just include the start of the metadata
print (nc_f)
<class 'netCDF4._netCDF4.Dataset'>
root group (NETCDF3_CLASSIC data model, file format NETCDF3):
    IOAPI_VERSION: $Id: @(#) ioapi library version 3.1 $
    EXEC_ID: CCTM_v521.exe
    FTYPE: 1
    CDATE: 2018111
    CTIME: 95359
    WDATE: 2018111
    WTIME: 95359
    SDATE: 2013001
    STIME: 10000
    TSTEP: 10000
    NTHIK: 1
    NCOLS: 201
    NROWS: 306
    NLAYS: 1
    NVARS: 112
    GDTYP: 2
    P_ALP: 30.0
    P_BET: 60.0
    P_GAM: -121.0
    XCENT: -121.0
    YCENT: 49.0
    XORIG: 12000.0
    YORIG: 24000.0
    XCELL: 4000.0
    YCELL: 4000.0
    VGTYP: 7
    VGTOP: 10000.0
    VGLVLS: [1.     0.9975]
    GDNAM: 04km
    UPNAM: M3CPLE
    VAR-LIST: NO2             NO              O3              NO3             N2O5            HNO3            HONO            H2O2            NTROH           NTRALK          ROOH            ALD2            ALDX            ISOPX           IEPOX           FORM            FACD            CO              AACD            MEPX            MEOH            PAN             PACD            PANX            CRPX            OPAN            NTRM            NTRI            SO2             SULF            CL2             HOCL            FMCL            HCL             CLNO2           MAPAN           NTRCN           NTRCNOH         NTRPX           FORM_PRIMARY    ALD2_PRIMARY    HG              HGIIGAS         ASO4J           ASO4I           ANH4J           ANH4I           ANO3J           ANO3I           AALK1J          AALK2J          AXYL1J          AXYL2J          AXYL3J          ATOL1J          ATOL2J          ATOL3J          ABNZ1J          ABNZ2J          ABNZ3J          APAH1J          APAH2J          APAH3J          ATRP1J          ATRP2J          AISO1J          AISO2J          ASQTJ           AORGCJ          APOCJ           APOCI           APNCOMJ         APNCOMI         AECJ            AECI            AOTHRJ          AFEJ            AALJ            ASIJ            ATIJ            ACAJ            AMGJ            AKJ             AMNJ            ACORS           ASOIL           ANAJ            ACLJ            ASEACAT         ACLK            ASO4K           ANH4K           ANO3K           AISO3J          AOLGAJ          AOLGBJ          NH3             SV_ALK1         SV_ALK2         SV_XYL1         SV_XYL2         SV_TOL1         SV_TOL2         SV_BNZ1         SV_BNZ2         SV_PAH1         SV_PAH2         SV_TRP1         SV_TRP2         SV_ISO1         SV_ISO2         SV_SQT
    FILEDESC: hourly 1-layer cross-point RADM dry deposition data
    HISTORY:
    dimensions(sizes): TSTEP(744), DATE-TIME(2), LAY(1), VAR(112), ROW(306), COL(201)
    variables(dimensions): int32 TFLAG(TSTEP,VAR,DATE-TIME), float32 NO2(TSTEP,LAY,ROW,COL)

It's a 4km square grid that appears to start at 121W and 49N, It's not parallel to latitudes and I assume that "VGLVLS: [1.     0.9975]" would contain the angle but I have no idea what python functions to use to convert.
Looking at other questions it seemed there was a built in function as below but there is of course no longitude_in key in my dataset.
    # Read variables from ncdf
    lon = nc.variables['longitude_in'][:]
    lat = nc.variables['latitude_in'][:]

That's from this solution but it doesn't work on this dataset:  Longitude/Latitude from NetCDF with (row,column)
Ideally I'd like to get LAT and LONG of the center of each square (although knowing how to get the four corners would be good too) each in a similar 2D array so I can output a .csv file with ROW, COL, LAT, LONG, NO2, SO2, O3, NO3.....after reducing the parameter count and summing the variable data over the month (I have the rest of it figured out I think).

A: I'm going to do this in R because that's easiest for me. But if it works then this should be translatable to Python, and its possible that all you need is the PROJ string that I'm going to construct...
From those data I'd construct a proj string that looks like this:
projstring = "+ellps=WGS84  +proj=lcc +units=m +x_0=12000 +y_0=24000   +lat_1=30 +lat_2=60 +lon_0=-121 +lat_0=49.0"
###            earth shape     GDTYP2          x and y false origin    standard parallels  projection centre
### https://proj-tmp.readthedocs.io/en/docs/operations/projections/lcc.html

individual parts are annotated in the second line and the descriptions of the parameters are in the link. Now I'm not sure if the false origins are correct and your grid coordinates start at (0,0), or if your grid starts at 12000,24000 and the false origins should be 0 and 0. Things should end up in more or less the same place but that's one thing that might not be right.
Also, the LCC projection requires two latitudes and a lat-long centre, but you've got two longitudes (P_GAM=-121.0 and XCENT=-121.0). They're the same value, but it might indicate that something else is going on. Not sure.
Anyway, now we have that string we can construct a grid of (NCOLSxNROWS) points with separation XCELL, YCELL (4000 x 4000) starting at (0,0):
grid = expand.grid(x = seq(0, by=XCELL, len=NCOLS),
                   y = seq(0, by=YCELL, len=NROWS))

> head(grid)
      x y
1     0 0
2  4000 0
3  8000 0

Then make that an R spatial object with the coordinate system given by that proj string:
library(sf)
gridsf = st_as_sf(grid, coords=1:2, crs=projstring)

and transform to lat-long (epsg coordinate code 4326):
gridll = st_transform(gridsf, "epsg:4326")

That produces a set of points that form this grid over Canada:

If you know where this grid should be then this might be correct. Or it might be that the offsets are off and you should try it the other way round.
Also, this might be the grid centre points or the grid cell bottom-left coordinates.
Also also, my assumption of the WGS84 ellipse might be wrong. If you can find out that your data comes from a model that assumes a spherical earth of radius 6300000m then you can make the proj string say that with some other parameters.
Ideally you should be able to go back to the community that generated this data and get precise information about the coordinate system used and perhaps a ready-computed grid of lat-long point coordinates. But hey, back in the real world...
Anyway, that proj string should be usable in a Python package that does PROJ transformations, like pyproj or GDAL, or PyQGIS, to transform from your grid to lat-long.


text:
Q: Linux shell: how to add prefix string to stderr message? I am running several tasks simultaneously at background.
command_a | tee > command_a.log &
command_b | tee > command_b.log &

If everything is fine, then messages will be saved to log files.
If something wrong, it will print errors on screen.
But command_a and command_b are quite similar, it's hard to tell which error message is generated by which command.
Can I add prefix string to error messages, like:
command_a: error 123
command_b: error 456
command_a: error 256
command_a: error 555
command_b: error 333

A: bash process substitutions:
command_a 2> >(sed 's/^/command_a: /' >&2) > command_a.log &
command_b 2> >(sed 's/^/command_b: /' >&2) > command_b.log &

You don't need to pipe to tee if you just redirect it's stdout to a file.
You can even do fancy stuff like print a timestamp:
$ {
  date
  echo stdout
  sleep 3
  echo stderr >&2
} 2> >(gawk '{print "foobar:", strftime("[%F %T]", systime()), $0}' >&2) > file.log

foobar: [2015-02-24 11:43:32] stderr

$ cat file.log

Tue Feb 24 11:43:29 EST 2015
stdout

Stick it in a function for re-use:
log_stderr() {
    gawk -v pref="$1" '{print pref":", strftime("%F %T", systime()), $0}' >&2
}

command_a > command_a.log 2> >(log_stderr "command_a")


text:
Q: Uncaught TypeError: Cannot read property 'location' of undefined vue I get this error:
vue-router.esm-bundler.js?6c02:3265 Uncaught TypeError: Cannot read property 'location' of undefined
at Object.install (vue-router.esm-bundler.js?6c02:3265)
at Object.use (runtime-core.esm-bundler.js?5c40:2948)
at eval (main.js?56d7:7)
at Module../src/main.js (app.js:1088)
at __webpack_require__ (app.js:854)
at fn (app.js:151)
at Object.1 (app.js:1113)
at __webpack_require__ (app.js:854)
at checkDeferredModules (app.js:46)
at app.js:994

File router.js:
import {createRouter, createWebHistory} from 'vue-router'

const routerHistory = createWebHistory()

const router = createRouter({
  mode: routerHistory,
  routes: [
    {
      path: '/',
      component: () => import('./views/Home.vue')
    },
    {
      path: '/todos',
      component: () => import('./views/Todos.vue')
    }
  ]
})

export default router;

File main.js
import { createApp } from 'vue'
import App from './App.vue'
import router  from './router.js'

const app = createApp(App)

app.use(router)
app.mount('#app')

File App.vue
<template>

    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link>

  <router-view/>
</template>

File Todos.vue:
<template>

Todo application

    <router-link to="/">Home</router-link>

    <AddTodo
        @add-todo="addTodo"
    />
    <select v-model="filter">
      <option value="all">All</option>
      <option value="completed">Completed</option>
      <option value="not-completed">Not Completed</option>
    </select>

    <Loader v-if="loading" />
    <TodoList
        v-else-if="filteredTodos.length"
        v-bind:todos="filteredTodos"
        @remove-todo="removeTodo"
    />

No todos!

</template>

File Home.vue
<template>

Home page

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cum dignissimos eveniet excepturi expedita impedit numquam quae quas tenetur velit voluptas!

    <router-link to="/todos">Todos</router-link>

</template>

File index.html:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= htmlWebpackPlugin.options.title %></title>

      We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.

File package.json
{
  "name": "web-ui",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build"
  },
  "dependencies": {
    "core-js": "^3.6.5",
    "vue": "^3.0.0",
    "vue-router": "^4.0.0-0"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-router": "^4.5.9",
    "@vue/cli-service": "~4.5.0",
    "@vue/compiler-sfc": "^3.0.0"
  }
}

A: With vue-router v4, createRouter expects history param.
Please refer docs
router.js
import {createRouter, createWebHistory} from 'vue-router'

const routerHistory = createWebHistory()

const router = createRouter({
  history: routerHistory,
  routes: [
    {
      path: '/',
      component: () => import('./views/Home.vue')
    },
    {
      path: '/todos',
      component: () => import('./views/Todos.vue')
    }
  ]
})

export default router;


text:
Q: Broadcasting Proof of Concept on android I am doing an hackaton and I want to broadcast the proof of concept of my android application to the jury. The problem is : I want it super easy to install my application and I don't want to pay 25$ for launching something that will target at most 20 people.
For instance it would be great if we could provide an url, and if someone click on it, it goes to a webpage with a download button and you click on it and it install it on your smartphone. That easy !

A:
For instance it would be great if we could provide an url, and if someone click on it, it goes to a webpage with a download button and you click on it and it install it on your smartphone.

Then do just that. So long as the Web server is set to serve up APK files with the appropriate MIME type (application/vnd.android.package-archive), and so long as the device is set to allow installation from arbitrary sources (in Settings > Security), this works just fine.


text:
Q: Usage of $\epsilon$ in Naive Set Theory by Paul R. Halmos I am currently learning Set Theory from Paul Halmos' Naive Set Theory. In the section about the axiom of specification, while dealing with Russell's Paradox, the author defined the set $B$ as:

$B=\{x  \epsilon  A: S (x)\}$

with $S(x)$ as

not$(x\epsilon x)$

How is $\epsilon$ used here? If it symbolises the relation 'belongs to' then how can an element belong to itself? It also proceeds, in the proof, to use such statements as:

...if $B \epsilon A$, then either $B \epsilon B$ also or else $B \epsilon' B$...

How can this set $B$ 'belong' to $A?$ $B$ can be is a subset of $A$, and it had been previously made clear that '$\epsilon$' and '$\subset$' are very different relations between elements and sets, or along sets.
Any help is appreciated. Thank You!

A: In most formulations of set theory, all elements of sets are themselves sets. This is called the hereditary property. Without axioms to prevent it, it is totally possible for sets to contain themselves. In ZFC this is prevented by the axiom of well-foundedness. In particular, when unrestricted comprehension is allowed over all sets, it is possible to define a set which is the collection of all sets that do not contain themselves.


text:
Q: What's the velocity unit in scrollViewWillEndDragging:withVelocity:targetContentOffset:? The documentation states it's points (per second, I'm assuming)? However, the values I get for it are in the (.5, 3.5) range. The scroll view then travels several hundred points before coming to a halt. The actual initial velocity should be different by orders of magnitude.

A: It is points/millisecond. From UIScrollView.h:
// called on finger up if the user dragged. velocity is in points/millisecond. targetContentOffset may be changed to adjust where the scroll view comes to rest
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset NS_AVAILABLE_IOS(5_0);

This is from iOS 7 SDK, which seemed more plausible given the very low values they've been returning in velocity.

A: From Docs

called on finger up if the user dragged. velocity is in points/millisecond. targetContentOffset may be changed to adjust where the scroll view comes to rest


text:
Q: Join UTF-8 strings I want to join some UTF-8 strings together, Any ideas?
e.g:

Input: س + ل + ا + م
Output: سلام

A: In Javascript you can do var output = 'س + ل + ا + م'.split(' + ').join('');. Just replace what is separating the characters in the split function.


text:
Q: How to trigger commit programmaticaly on Spring Webflow 2 with Flow Managed Persistence Context i have upgraded our application to SWF 2 and have implemented FMPC pattern. majority of our existing flow definitions doesn't have end-state, now using FMPC as described here, you can trigger commit by putting commit=true to your end-state. Example of our flow:

*

*get form object

*save details to db (we want to commit here)

*fetch the same object with refreshed data

*display to view

its currently working with previous SWF and just using Open Session in View pattern. but we imlemented FMPC to avoid any LazyInitializationException. Now what's happening is steps 1-4 is happening except that changes are not committed, so in the view, we don't see any changes. it seems difficult to add end-state at the middle just to commit to DB and also this means we need to add so many end-state, so my question is how to tell (SWF/FMPC) to commit "programmaticaly" without having to add the end-state tag. If you know better approach, please tell also. Thanks!

A: Spring Web Flows can have inheritance, so you can implement the end-state in your parent flow and then have it as a parent for all your flows.

A: I resolved my issue. I finally found out that indeed Hibernate is auto-committing all my read-write operations. The problem is when refreshing the object concerned which gave me the impression that there is no read-write done while in fact there is. Doing sessioFactory.refresh(object) instead of plain find() effectively fetched the updated data from the DB. I guess its because the hibernate session is still alive (due to FMPC) that's why doing "find" will retrieve from the hibernate cache while "refresh" means re-reading the data directly from underlying database. Please correct my analysis as necessary.


text:
Q: Understanding Output of ur.df Test: What Do the z.diff.lag# Indicate? When reading the output of summary(ur.df(ts)) in R, what do the z.diff.lag# coefficients indicate?
Are they error terms for "at" in the Dickey-Fuller regression expression? For example:

To help with instruction, I'll generate some stationary data and run the ur.df function with summary wrapped around it.
# generate white noise
n <- 200
x <- rnorm(n,
           mean = 0,
           sd = 1)
# make into time series object
y <- ts(x)

Now, for example, I run an ADF test to check if my time series is not a random walk masquerading as stationary data.
For the ADF test, because the data is white noise (with no drift or trend), I leave the ur.df test type="none".
To generate lots of z.diff.lag# coefficients, I will run the ADF test at 5 lags:
summary(ur.df(y,
              type = c("none"),
              lags = 5))

And here is the output:
##
## ###############################################
## # Augmented Dickey-Fuller Test Unit Root Test #
## ###############################################
##
## Test regression none
##
##
## Call:
## lm(formula = z.diff ~ z.lag.1 - 1 + z.diff.lag)
##
## Residuals:
##      Min       1Q   Median       3Q      Max
## -1.82322 -0.81705 -0.08905  0.62597  2.30963
##
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)
## z.lag.1     -1.04664    0.17779  -5.887 1.78e-08 ***
## z.diff.lag1  0.02807    0.15987   0.176    0.861
## z.diff.lag2  0.11422    0.14319   0.798    0.426
## z.diff.lag3  0.06688    0.12474   0.536    0.593
## z.diff.lag4  0.07115    0.10538   0.675    0.500
## z.diff.lag5 -0.01979    0.07381  -0.268    0.789
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.9941 on 188 degrees of freedom
## Multiple R-squared:  0.5251, Adjusted R-squared:   0.51
## F-statistic: 34.65 on 6 and 188 DF,  p-value: < 2.2e-16
##
##
## Value of test-statistic is: -5.8871
##
## Critical values for test statistics:
##       1pct  5pct 10pct
## tau1 -2.58 -1.95 -1.62

Lo-and-behold, the data is stationary. No surprises.
In the summary(ur.df(ts)) results, I understand the t value for z.lag.1 is the test-statistic value at lag 5. I also understand the p-value for this coefficient and what it means for the Critical values.
But what I do not understand is the series of five z.diff.lag# coefficients. My only thought is these are error terms (the "at" values) for the Dickey-Fuller algebraic equation. But again, I do not understand what the p-value means for these five z.diff.lag# indicate.
Any insight is much appreciated.

A: In an augmented Dickey-Fuller test, the model equation (for type=trend specification) is
$$
\Delta y_t = \alpha + \beta t + \gamma y_{t-1} + \delta_1\Delta y_{t-1} + \dots + \delta_{p-1}\Delta y_{t-p+1} + \varepsilon_t
$$
(I used the notation from Wikipedia) where you may set $\beta=0$ (type=drift) and also $\alpha=0$ (type=0). The lagged first differences of $y_t$ are there to account for any autocorrelation in $\Delta y_t$, as $\Delta y_t$ could be e.g. an ARMA process. ur.df uses z instead of $y$, so z.diff.lagj corresponds to $\Delta y_{t-j}$. The corresponding coefficients, $p$-values and such characterize these lagged first difference terms in the model.


text:
Q: ruby list ancestors which are not mixins Best explained in code....
>> String.ancestors
=> [String, Comparable, Object, Kernel, BasicObject]
>> Comparable.ancestors
=> [Comparable]
>> Object.ancestors
=> [Object, Kernel, BasicObject]
>> Kernel.ancestors
=> [Kernel]
>> BasicObject.ancestors
=> [BasicObject]

So I suspect the inheritance chain is String < Object < BasicObject... and Comparable and Kernel are mixins...
Is there a function 'foobar' which can show the inheritance:
>> String.foobar
=> [Object, BasicObject]

And if possible with the hidden metaclasses storing the singleton methods be included as well?

A: String.ancestors.grep(Class)

......................

A: You can do:
class Class
  def foobar
    ancestors - included_modules - [self]
  end
end


text:
Q: Macports and Rubygems issues on Snow Leopard I've installed Snow Leopard over Leopard with macports and rubygems already installed. This was regular install, not a clean "archive and erase" install.
It turned out, that SL has 64bit versions of shared libraries and many development utilities do not work. For example, "port" command complains on incompatible tcl library, or ruby cannot load 32bit bundles.
What is the easiest way to solve these issues?

A: I was googling for the answer for about 4 days already and finally came up with a step-by-step manual on fixing macports and rubygems:
http://oleganza.tumblr.com/post/127709563/snow-leopard-with-legacy-macports-and-rubygems
In short: for proper use of macports and rubygems you would have to:

*

*Install trunk macports from source (or use 1.8 version when it is released)

*Add alias for "gem install with 64bit architecture"

*Reinstall all ports (not automated yet)

*Reinstall all gems (100% automated)
This would take 10-20 minutes of your personal time and another 20
minutes of machine time in order to build and install stuff.
I would be glad to get more answers in order to fix other issues we might meet later.

A: Since it's really hard to force MacPorts to recompile all ports (in the proper order), I just did:
mv /opt /opt.old

Then install MacPorts 1.8, and bring back any configs you need from /opt.old/local/etc/
Otherwise, you'll get assorted errors complaining about your existing libs' architecture, (e.g. "Command output: ld: warning: in /opt/local/lib/libz.dylib, file is not of required architecture").
This isn't as clean as 'port uninstall installed' but works fast and good enough for me.

A: Richard Dooling's MacPorts On Snow Leopard explains that to fix the older install of MacPorts, which is broken after the upgrade to Snow Leopard, you should just download and install the new compatible version over the old one and then simply follow the migration instructions - which also say the same.


text:
Q: react-native: image not show when not set width or height rn version : 0.38
just specify the image style using flex, no width and height, but Image will not show on mobile screen. How to do this.
<View style={styles.container}>
    <Image style={styles.image} source={{uri : 'https://www.baidu.com/img/bd_logo1.png'}}>
    </Image>
</View>

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  image: {
     flex: 1,
    resizeMode: 'contain'
  },
});

A: Network images require you to set height/width style props.
React Native Documentation.

Many of the images you will display in your app will not be available
  at compile time, or you will want to load some dynamically to keep the
  binary size down. Unlike with static resources, you will need to
  manually specify the dimensions of your image.

// GOOD
<Image source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}}
       style={{width: 400, height: 400}} />

// BAD
<Image source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} />

A: You can use flexGrow: 1 or flex: 1 on your Image without specifying the size, but you will need to set the container width and height either using percentage or a fixed size:
<View style={{ width: "100%", height: "100%" }}>
  <Image
    source={{
      uri: "https://github.githubassets.com/images/modules/logos_page/GitHub-Logo.png",
    }}
    style={{ flex: 1 }}
    resizeMode="contain"
  />
</View>

checkout this snack example


text:
Q: jQuery use $(document).click event as a 'cancel selection' event I'm building an app.net page using jQuery for DOM manipulation (JS Fiddle here). When I click a certain <td> on the table it becomes target for future manipulation. I want to add code, so that a click anywhere outside the table will un-target that <td> (meaning a click in the background should act as a cancel selection event).
The answers to this question did not help me, because:
A. I don't want to use stopPropagation() because of this article plus I have many click event handlers in my code that I will have to stop from propagating).
B. I have other elements on the page (buttons, text-input fields) which should NOT act as a cancel selection event).

A: Without more specifics it seems like toggling an active class on target cells would do what you are suggesting.
var $table = $('#myTable').on('click', 'td', function(){
    $table.find('.active').removeClass('active');
     $(this).addClass('active');
});

Then for removing using events outside table just check if target is in the table
$(document).click(function(e){
  if(!$(e.target).closest('#myTable').length){
      $table.find('active').removeClass('active');
  }
});


text:
Q: .NET Core reverse proxy middleware and signalR I need to do a reverse proxy middleware in ASP.NET Core. I have something like this. But it doesn't work with SignalR.
Reverse proxy has address 192.168.187.72:5000; SignalR 192.168.187.62:5000. Client connects to proxy, proxy changes the url to SignalR hub url, but in client I always get this error:

The server disconnected before the handshake could be started

Code:
public ReverseProxyMiddleware(RequestDelegate nextMiddleware,ILogger<ReverseProxyMiddleware> logger)
{
    _nextMiddleware = nextMiddleware;
    _logger = logger;
}

public async Task Invoke(HttpContext context)
{
     var targetUri = BuildTargetUri(context.Request);

     if (targetUri != null)
     {
         var targetRequestMessage = CreateTargetMessage(context, targetUri);

         using (var responseMessage = await _httpClient.SendAsync(targetRequestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
         {
             context.Response.StatusCode = (int)responseMessage.StatusCode;

             CopyFromTargetResponseHeaders(context, responseMessage);
             await responseMessage.Content.CopyToAsync(context.Response.Body);
         }

         return;
    }

    await _nextMiddleware(context);
}

private HttpRequestMessage CreateTargetMessage(HttpContext context, Uri targetUri)
{
    var requestMessage = new HttpRequestMessage();

    CopyFromOriginalRequestContentAndHeaders(context, requestMessage);

    requestMessage.RequestUri = targetUri;
    requestMessage.Headers.Host = targetUri.Host;
    requestMessage.Method = GetMethod(context.Request.Method);

    return requestMessage;
}

private void CopyFromOriginalRequestContentAndHeaders(HttpContext context, HttpRequestMessage requestMessage)
{
    var requestMethod = context.Request.Method;

    var streamContent = new StreamContent(context.Request.Body);
    requestMessage.Content = streamContent;

    foreach (var header in context.Request.Headers)
    {
        requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
    }
}

private void CopyFromTargetResponseHeaders(HttpContext context, HttpResponseMessage responseMessage)
{
    foreach (var header in responseMessage.Headers)
    {
        context.Response.Headers[header.Key] = header.Value.ToArray();
    }

    foreach (var header in responseMessage.Content.Headers)
    {
        context.Response.Headers[header.Key] = header.Value.ToArray();
    }

    context.Response.Headers.Remove("transfer-encoding");
}

private static HttpMethod GetMethod(string method)
{
    if (HttpMethods.IsDelete(method)) return HttpMethod.Delete;
    if (HttpMethods.IsGet(method)) return HttpMethod.Get;
    if (HttpMethods.IsHead(method)) return HttpMethod.Head;
    if (HttpMethods.IsOptions(method)) return HttpMethod.Options;
    if (HttpMethods.IsPost(method)) return HttpMethod.Post;
    if (HttpMethods.IsPut(method)) return HttpMethod.Put;
    if (HttpMethods.IsTrace(method)) return HttpMethod.Trace;

    return new HttpMethod(method);
}

private Uri BuildTargetUri(HttpRequest request)
{
    Uri targetUri = null;
    StringValues clientId = string.Empty;

    targetUri = new Uri($"http://192.168.187.62:5000{request.Path}{request.QueryString}");

    _logger.LogInformation($"Request URL {request.Host + request.Path + request.QueryString} Target URL {targetUri.ToString()}");

    return targetUri;
}

A: Are you sure you want to create such functionality manually?
There are many great libraries for reverse proxying, Microsoft has a new project called YARP (https://microsoft.github.io/reverse-proxy/) which is an open source reverse proxy told to be high performance and highly customizable.
If you like I can show you a sample how you can use yarp in an ASP.NET Core app.


text:
Q: VBA to click on web link i want to click on link which have onclick javascript code

Claim Status

my tried code =
Document.getElementById("Document.getElementById("j_id40").Click").Click

so please help.

A: Maybe you should add more data like what you're trying to do or the site itself. Also check out if you absolutely need to use VBA, there are a lot of browser automation software out there.
Cheers,
Sujoy

A: CSS selector and .querySelector method:
You could try the querySelector method of HTMLDocument to apply a CSS selector. For the HTML shown you can use a full
a[onclick*="if(typeof jsfcljs == 'function'){jsfcljs(document.forms['SideForm'],{'SideForm:j_id40':'SideForm:j_id40'},'');}return false"]

or shorten to:
a[onclick*="if(typeof jsfcljs == 'function')"]

Whether you can shorten depends on whether there are any other elements which match the pattern and come before the one of interest.
Explanation:
The CSS pattern is an a tag, with an onclick attribute containing the string either if(typeof jsfcljs == 'function'), for the short version, or if(typeof jsfcljs == 'function'){jsfcljs(document.forms['SideForm'],{'SideForm:j_id40':'SideForm:j_id40'},'');}return false =, for the longer version

Example CSS selection using selector:

VBA:
To apply this with VBA you use:
IE.document.querySelector("a[onclick*='if(typeof jsfcljs == 'function')']")

I have replaced the inner " with ' to save on having to double up on " to escape " with a string.
Otherwise it would look like:
IE.document.querySelector("a[onclick*=""if(typeof jsfcljs == 'function')""]")


text:
Q: Can't send sms using a PHP code through Ozeki sms server I'm trying to send an sms using PHP code through Ozeki sms server. I can properly send an sms by direclty using the interface provided by Ozeki. But this piece of php code doesn't do the same thing as I expected. I have connected to : 127.0.0.1:9333(admin).
It shows Fatal error: Maximum execution time of 30 seconds exceeded in C:\wamp\...\sendsms.php on line 32 which has the code $greeting = trim(fgets($ozekiSMSSocket,1000)); What will be the wrong?
This is the code:
<?php
include("sendsms.php");
$credits = sms_connect('127.0.0.1','9333','admin');

if ($credits>1) {
echo "Sending messages...
";
sms_send('+36203105366','Send SMS messages from a PHP client!');
}

echo "Receiving messages...
";
$inbox = sms_receive();
echo "$inbox";

sms_disconnect();
?>

This is the code in sendsms.php
<?php
$ozekiSMSSocket = '';
$ozekiSMSCredit = 0;
function sms_connect($serverIP,$serverPort,$account) {
global $ozekiSMSSocket;
global $ozekiSMSCredit;
$ret = true;
$ozekiSMSSocket = fsockopen($serverIP, $serverPort, $errno, $errstr, "60");

if ($errno) {
    echo $errstr;
    $ozekiSMSCredit = 0;
}

//$greeting = fgets($ozekiSMSSocket,1000);

$greeting = trim(fgets($ozekiSMSSocket,1000));
$randomstring = trim(fgets($ozekiSMSSocket,1000));

if (strlen($randomstring)) {
    $reply = md5($randomstring.$account).chr(13).chr(10);
    fputs($ozekiSMSSocket,$reply);
    $ozekiSMSCredit = trim(fgets($ozekiSMSSocket,1000));
}
return $ozekiSMSCredit;
}

function sms_send($msisdn,$msg) {
global $ozekiSMSSocket;
global $ozekiSMSCredit;
if ((isset($ozekiSMSSocket)) && ($ozekiSMSCredit>0)) {
    $msg=$msisdn.' '.$msg.chr(13).chr(10);
    fputs($ozekiSMSSocket,$msg);
} else {
    $ozekiSMSCredit = 0;
}
return $ozekiSMSCredit;
}

function sms_receive() {
global $ozekiSMSSocket;
$received = '';
if (isset($ozekiSMSSocket)) {
    $msg='OZEKI_INBOX'.chr(13).chr(10).'GET'.chr(13).chr(10);
    fputs($ozekiSMSSocket,$msg);
    $count = trim(fgets($ozekiSMSSocket,1000));
    for ($x=0;$x<$count;$x++) {
        $line = fgets($ozekiSMSSocket,1000);
        $received .= trim($line).chr(13).chr(10);
    }
}
return $received;
}

function sms_disconnect() {
global $ozekiSMSSocket;
if (isSet($ozekiSMSSocket)) fclose($ozekiSMSSocket);
}
?>

A: The reason for the timeout is, that you're trying to read 1000 bytes from the socket, but the server isn't sending anything.
As to why the "Ozeki sms server" isn't sending anything, I don't know. But you should check the documentation if you really should expect a greeting message right after connecting. Normally you would expect the client to initiate communication by sending a request.


text:
Q: libgit2 treebuilder API and on-the-fly packing We're developing a tool that needs to create very large git trees containing lots of objects (~10k - 100k). The I/O for the many files corresponding to these objects is going to be a bottleneck, so we're wondering if it would be possible to do a sort of on-the-fly re-packing.
I imagine this done either when doing git_blob_create_frombuffer() or when doing git_treebuilder_insert().
Do you think this would be meaningful and feasible?
In case this wouldn't be feasible, do you have any suggestions on how to handle this use case with libgit2?

A: It looks like there might be some misunderstanding in what a tree is and how it's created.
Creating a tree should never cause a re-pack. When you create a tree, you already have the objects in the database. Thus the fastest way to create the tree is to leave that data which already exists alone. Creating a pack out of the blobs would mean reading them all in and comparing them. Leaving them be is by definition the fastest thing you can do, as it doesn't involve any work.
At some point it may make sense to expose a way to write objects directly to a packfile, but this is not currently possible.
You speak in the future, which suggests you have not measured or implemented this yet. Until you do so, any other advice would be rather useless as it would have no bearing on what you are doing with your code.


text:
Q: How to implement iAds in Xcode 3.2.5 I am new to iPhone SDK. My project is working with Xcode 3.2.4 in simulator 4.1 successfully worked with iAds concept but same project installed Xcode 3.2.5 in simulator 4.2 project working Successfully But iAds are not came. In console also they no errors. When ever change the Xcode version any changes is compulsorily please tell me what is the problem.
My error is Xcode 3.2.4 iAds working but Xcode 3.2.5 iAds not working.

A: If u want to run any application of previous version of xcode in new version then click on project tab and select edit project settings. You get new window in which u change the base sdk type and select latest know ios. After that you again click on project tab then click on edit target settings and again change base sdk settings and set as latest known ios. After that in editor windoe change base sdk simulator.
It will work .
if u don't get any solution from this then use this linksame question and see answer


text:
Q: Why doesn't my code work without this alert box? On one of the edit views of my Grails application I have several chained drop down boxes.  When the edit view is called all the values for the object being edited populate correctly, but none of the drop down boxes are populated because they populate via AJAX through jQuery's change function.
To fix this I used the code below, but there is one strange thing.  I used an alert box to see what the value was when I was writing the code.  With the alert box there everything happens as I expect it to, but as soon as I remove the alert box the line of code that re-selects the previously cleared value stops working.
<g:javascript>
  $(document).ready(function() {
    cargoDestinationValue = $("#cargoDestination\\.id").val(); //Gets value shown in the selection box. This box is second in the chain.
    $("#account\\.id ").trigger('change'); //Triggers a change.  This box is first in the chain. when a change is detected an AJAX call is made via some other JavaScript and that populates the second selection box in the chain, but doing so clears the selected value.
    alert(cargoDestinationValue); //If this is not here the next line does not seem to be doing what it is supposed to do.
    $("#cargoDestination\\.id").val(cargoDestinationValue); //This re-selects the value that was previously cleared.
  })
</g:javascript>

What is the deal here?

A: The event that you trigger is queued, so if you don't have the alert, the event is not handled until you exit the function.
Even if you would call the code directly without using an event to trigger it, it has an AJAX call where the response is handled by an event, so that event would be queued.
You should handle the part after the alert in the code that recieves the data from the AJAX call, which of course means that you have to store the selected value somewhere so that the code can get to it.

A: Could it be that #cargoDestination does not exist at the moment you try to set the value (without the alert box), but will be loaded/inserted while you click "ok" if the alert box is on screen?
I had a similar problem some days ago...


text:
Q: How can I left-align the text in a TikZ node How can I left align the text "Mi" inside the node? I assumed that align=left would work however the text is still centered.
\documentclass[fontsize=6pt]{article}
\usepackage{tikz}
\usepackage[right]{showlabels}
\usetikzlibrary{positioning}

\begin{document}
\begin{tikzpicture}[x=23mm,y=6mm,%
    mybox/.style={rectangle,rounded corners,minimum width=23mm, minimum height=6mm, align=left},%
    workday/.style={mybox,draw=black,align=left}]%

\node at (0,-1) [workday] {Mi};

\end{tikzpicture}
\end{document}

A: You could add an option specifying the text width. It's automatically left justified then:

\documentclass[fontsize=6pt]{article}
\usepackage{tikz}
\usepackage[right]{showlabels}
\usetikzlibrary{positioning}

\begin{document}
\begin{tikzpicture}[x=23mm,y=6mm,%
    mybox/.style={rectangle,rounded corners,minimum width=23mm, minimum height=6mm, align=left,text width=2cm},%
    workday/.style={mybox,draw=black,align=left}]%
\node at (0,-1) [workday] {Mi};

\end{tikzpicture}
\end{document}

as cited--https://tex.stackexchange.com/a/12976/197451
--https://tex.stackexchange.com/a/347625/197451


text:
Q: Forcefully make element go to another line in FlexBox I have a page which I have to split into 2 pages. Initially, I had done it using ordinary table with 2 td tags. But later realised that formatting I want to do there is impossible using table. So I decided to use FlexBox instead. And it works so well, except of flex-wrap: wrap; tag. It only make 2nd row if zoom is very big.
Usual zoom
Zoom 1.5x
Well, the way I want to be 'sticked' is like this whatever zoom size is
I know that flexbox makes everything in one row when display: flex is declared. But how can I avoid it? And what is the proper way to adjust location of div elements in this case? For example when I declare
.chooseWord
{
    position: relative;
    padding-left: 300px;
}

I want ONLY the word 'Choose' to go left for 300px. Instead whole leftSide goes left...
Here's my code:

.flex-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
}

.leftSide {
  padding-top: 30px;
  /* flex-basis: 50%; */
  height: auto;
  overflow: auto;
  border: 2px solid #05788D;
}

.rightSide {
 /* flex-basis: 50%; */
  height: auto;
  overflow: auto;
  border: 2px solid #05788D;
  border-left-style: none;
}

.SSRSSObjectCostTableTest {
  border: 3px solid #05788D;
  border-collapse: collapse;
}

.sideForSSRSSTables {
  border: 3px solid #05788D;
}

.partsTable {
  border-collapse: collapse;
}

.sideForPartsTable {
  border: 3px solid #05788D;
}

.chooseSRSS {
  display: flex;
  justify-content: space-between;
}

.chooseWord {
  position: relative;
  padding-left: 300px;
}

      Choose

          1st option
          2nd option

          Here's that table

          <input type="text" size="40" id="estCost_tsnb_title" value="Here's that table" width="25%">

          Here's that table
          300
          $

          Here's that table
          300
          $

          Here's that table
          300
          $

          Here's that table
          300
          $

          Here's that table
          300
          $

          Here's that table
          300
          $

          Here's that table
          300
          $

          Here's that table
          300
          $

          Here's that table
          300
          $

          Here's that table
          300
          $

          Here's that table
          300
          $

          Here's that table
          300
          $

          Here's that table
          300
          $

          Here's that table
          300
          $

      Parts
      <button type="button" class="addButton">+Add button</button>

          Expand button
          Title + sum1 + sum2
          edit
          remove

A: Please take a look at this and let me know if anything else is needed.

.flex-container {
  width: 100%;
  height: 100%;
  display: flex;
  text-align: center;
}

.leftSide {
  padding-top: 30px;
  border: 2px solid #05788D;
  width: 50%;
}

.rightSide {
  border: 2px solid #05788D;
  border-left-style: none;
  width: 50%;
}

.partsTable, .leftSize table {
  border-collapse: collapse;
}

.sideForPartsTable {
  border: 3px solid #05788D;
}

          Some text
          Some value
          Currency
          1st option
          2nd option

          Here's that table

          Here's that table
          300
          $

          Here's that table
          300
          $

          Here's that table
          300
          $

          Here's that table
          300
          $

          Here's that table
          300
          $

             Parts

              <button type="button" class="addButton">+Add button</button>

            Expand button
            Title + sum1 + sum2
            edit
            remove

              Some value

              Some value

              Some value

              Some value


text:
Q: Android JNI in C++ Builder I'm searching for using Android JNI on C++ Builder, and I saw this code:
   private void doPhotoPrint() {
       PrintHelper photoPrinter = new PrintHelper(getActivity());
       photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT);
       Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
               R.drawable.droids);
       photoPrinter.printBitmap("droids.jpg - test print", bitmap);
   }

That's a Java code to print (in a thermal printer) a bitmap and I need to use it in C++ Builder, but I don't have idea how to convert it. I saw doing other things by intents or even JNI. I don't want recommendations or something, neither a done code (saying this to avoid judgments that my question is for recommendations), but I want something like this code to help create a function.
PS: I didn't found any documentation about Android JNI.

A: It would look something like this:
_di_JPrintHelper photoPrinter = TJPrintHelper::JavaClass->init(TAndroidHelper::Activity);
photoPrinter->setScaleMode(TJPrintHelper::JavaClass->SCALE_MODE_FIT);
_di_JBitmap bitmap = TJBitmapFactory::JavaClass->decodeResource(TAndroidHelper::Context->getResources(), /*R.drawable.droids*/...);
photoPrinter->printBitmap(StringToJString("droids.jpg - test print"), bitmap);

I don't know if Embarcadero has already imported the TJPrintHelper and TJBitmapFactory classes (do a grep of Embarcadero's Androidapi... header files). If not, you can simply use Java2OP to import them manually.
I don't know how to translate R.drawable.droids to Embarcadero's JNI framework. decodeResource() wants the integer resource ID of the droids image.  You will have to track that one down yourself.


text:
Q: mapView:didAddAnnotationViews doesn't always pick up the annotations I have placed a number of annotations on a map, and when the user touches the location button, the view zooms in on the user location, which contains a number of annotations.
mapView:didAddAnnotationViews is called and should add all the annotations inside the current view into an NSArray.
Sometimes it adds all the annotations without any problems, but other times, it only adds the one annotation which is the user location (blue dot).
I suspect it may have to do with being called before the map has finished rendering, but i'm not sure.
Not sure if it's possible to link the function mapViewDidFinishRenderingMap to didAddAnnotationViews so that it will only load once the view has been completed loading (including all the annotations).
Would appreciate any advice regarding this, as I am relatively new to Swift.
Here's some of my code. I've got a timer that runs every second and prints out the size of the array in the console.
var timer = NSTimer()
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true)

func mapView (mapView: MKMapView!, didAddAnnotationViews views: [AnyObject]!) {

    pinannotationarray = views

}

func update() {

    if (pinannotationarray != nil && locationManager.location != nil)
     {
       println("pinannotationarray size \(pinannotationarray.count)")
     }
}

** Revised Code **
var annSet: AnyObject!

func mapView(mapView: MKMapView!, regionDidChangeAnimated animated: Bool) {

annSet = mapView.annotationsInMapRect(mapView.visibleMapRect)
println("regionDidChangeAnimate: annSet count = \(annSet.count)")

for (var i = 0; i < annSet.count; i++)
    {
    pinannotation = annSet.allObjects[i].annotation as? MyAnnotation

    //fatal error: unexpectedly found nil while unwrapping an Optional value
    println(pinannotation.title)
    }
}

A: The annotationsInMapRect method returns an NSSet containing the annotation model objects (eg. MKPointAnnotation) -- not the views (eg. MKAnnotationView).
That also means annSet.allObjects will be an NSArray containing the annotation model objects.
That means annSet.allObjects[i].annotation is invalid and will fail (annotation views have an annotation property and not the annotations themselves) which leaves pinannotation as nil resulting in the crash.
Change the assignment to:
pinannotation = annSet.allObjects[i] as? MyAnnotation
println(pinannotation.title)

or to be a little safer:
if let pa = annSet.allObjects[i] as? MyAnnotation {
    println(pa.title)
}

By the way, you don't even need to generate an NSArray from the NSSet.  You can iterate the NSSet directly:
for ann in annSet as NSSet {
    if let ma = ann as? MyAnnotation {
        println("ma.title = \(ma.title)")
    }
}


text:
Q: Regarding OCaml Pattern Matching Syntax I am following this OCaml tutorial.
They provided the two functions below and said that they are equivalent.
let string_of_int x = match x with
   | 0 -> "zero"
   | 1 -> "one"
   | 2 -> "two"
   | _ -> "many"

let string_of_int2 = function
    | 0 -> "zero"
    | 1 -> "one"
    | 2 -> "two"
    | _ -> "many"

My query is regarding the syntax of the above functions.

*

*I wrote the same function but instead of | 0 -> I simply did 0 -> and the function still works in the same way. Is there any particular reason that the tutorial added the extra | in their function?

*In the second function what is the use of the function keyword and why was this keyword absent in the first function?

A: *

*Some people think it looks nicer and more organized, and it allows you to change the order of cases using cut & paste without having to worry about which one didn't have the |.

*The function syntax is an abbreviation: function [CASES] is the same as fun x -> match x with [CASES]. There is a subtle difference, which is with function it is not possible to shadow another variable by the name of the parameter.
let string_of_int x = [EXP] is itself an abbreviation for let string_of_int = fun x -> [EXP].
So, to a close approximation, the "canonical" syntax uses fun and match, everything else is sugar. If you apply these two expansions to the two versions of the function, you will see that the same code results (modulo alpha-equivalence, of course :) ).


text:
Q: How to prove $a \lt b$ for all $a \in A, b \in B$ implies $\sup A \leq \inf B$? If $A, B$ are two non empty sets of real numbers and for every $a$ from $A$ and $b$ from $B$

$a < b$,

how can I prove that

$\sup A \leq \inf B$?

A: I don't think this is true. Let $A=(0,1)$ and $B=(1,2)$ then $\operatorname{sup}A=1$ and $\operatorname{inf}B=1$ but $A$ and $B$ satisfy your conditions.

A: With the edited problem: if $a\lt b$ for all $a\in A$ and $b\in B$, why is it that $\sup(A)\leq\inf(B)$? Is every element of $A$ a lower bound for $B$? If so, what does that tell you about the elements of $A$ relative to $\inf(B)$? And given that, what does that tell you about $\sup(A)$?

A: Here's the solution:
Let us suppose that $\sup(A) > \inf(B)$. So, there exists some $x∈A$, such that $\inf(B) < x$. Again, as $\inf(B)< x$, there exists $y∈B$, such that $y<x$. which is a contradiction as we have been given that $A<B$ (i.e, $x<y$ for all $x∈A$, $y∈B$). So, our assuption that $\sup(A) > \inf(B)$ is WRONG. So, $\sup(A) \leq \inf(B)$.
Hence Proved...... :)

A: Consider $b\in B$, by hypothesis is a upper bound of $A$, so by definition of sup (the least upper bound), $\sup A\leq b,$ $ \forall b\in B$. Now the $\sup A$ is a lower bound of $B$, so by defnition of inf(the grater lower bound), $\sup A\leq \inf B$ .


text:
Q: How to drop the caches on AIX? I am running a series of tests from a script that have a habit of running a box out of memory. The simple solution on other linux boxes is to echo "3" > /proc/sys/vm/drop_caches but this command doesn't work on AIX. Is there an AIX equivalent to this command?

A: There is no way to drop the caches in AIX.


text:
Q: How to mock a tensorflow model? I would like to test a function that takes a tf.keras model and performs some operations on it. Example function illustrating the problem:
def func(model, x):
    with tf.GradientTape() as tape:
        tape.watch(x)
        output = model(x)
        # do some additional stuff with output
        gradient = np.array(tape.gradient(output, x))
        # do some additional stuff with gradient
        return gradient

I wonder what the best idea to mock model is.
Possible solutions:

*

*Use a small network with set weights. This one is easiest to implement but
a) It takes a longer time to calculate than a simple mock.
b) It's hard to control what is returned by the model.

*Mock using unit test or pytest. This one will straight up fail because no computation graph is created which would link x and output.

*Move tape.gradient(output, x) to another function, then, during tests, mock this function and model(x) using unit test or pytest. I think this one is the best but it makes func less readable (especially if more tf specific elements have to be moved to various other functions).
Is there a better way? Ideally, I would like to:

*

*Express that this model for a given input x returns a given output y.

*Express that the gradient of a given output y w.r.t. a given input x is z.

*Express that the gradient of a given output y w.r.t. a given layer l is l'.

*Minimize necessary modifications to func.


text:
Q: Usage of send in a clause Which is correct:

*

*"Select a computer where you want us to send your file"

*"Select a computer that you want us to send your file to"
Is there any less wordy way to express the same thing?

A: If you need shortest form, try something like:
Select destination computer for your file
There is no word "send" in this phrase, but this word is implied by the word "destination".


text:
Q: Problem proving a trigonometric result. Question: If $\frac{\tan(\theta-\phi)}{\tan\theta}+\frac{\sin^2\alpha}{\sin^2\theta}=1$, show that $\tan\theta\tan\phi=\tan^2\alpha$.
My attempt:
$\frac{\tan(\theta-\phi)}{\tan\theta}+\frac{\sin^2\alpha}{\sin^2\theta}=1$
$\implies\frac{\frac{\sin(\theta-\phi)}{\cos(\theta-\phi)}}{\frac{\sin\theta}{\cos\theta}}+\frac{\sin^2\alpha}{\sin^2\theta}=1$
$\implies\frac{\frac{\sin\theta\cos\phi-\cos\theta\sin\phi}{\cos\theta\cos\phi+\sin\theta\sin\phi}}{\frac{\sin\theta}{\cos\theta}}+\frac{\sin^2\alpha}{\sin^2\theta}=1$
$\implies\frac{\cos\theta(\sin\theta\cos\phi-\cos\theta\sin\phi)}{\sin\theta(\cos\theta\cos\phi+\sin\theta\sin\phi)}+\frac{\sin^2\alpha}{\sin^2\theta}=1$
My problem: I am unable to figure out how to proceed further. Please help.

A: The condition gives $$\sin^2\alpha=\sin^2\theta-\sin\theta\cos\theta\tan(\theta-\phi)$$ and since $$\tan^2\alpha=\frac{\sin^2\alpha}{1-\sin^2\alpha},$$ we need to prove that
$$\tan\theta\tan\phi=\frac{\sin^2\theta-\sin\theta\cos\theta\tan(\theta-\phi)}{1-\sin^2\theta+\sin\theta\cos\theta\tan(\theta-\phi)}$$ or
$$\tan\phi=\frac{\sin\theta-\cos\theta\tan(\theta-\phi)}{\cos\theta+\sin\theta\tan(\theta-\phi)}$$ or
$$\tan\phi=\frac{\tan\theta-\tan(\theta-\phi)}{1+\tan\theta\tan(\theta-\phi)},$$
which is obvious.
Done!

A: $$\dfrac{\sin^2\alpha}{\sin^2\theta}=1-\dfrac{\tan(\theta-\phi)}{\tan\theta}=\dfrac{\sin\{\theta-(\theta-\phi)\}}{\cos(\theta-\phi)\sin\theta}=?$$
$$\implies\sin^2\alpha=\dfrac{\sin\theta\sin\phi}{\cos(\theta-\phi)}$$
$$\cos^2\alpha=?$$
$$\text{Now, }\tan\alpha=\dfrac{\sin\alpha}{\cos\alpha}$$

A: Put $\tan (\theta)=a,\tan (\phi)=b,\tan (\alpha)=c $ . And use $\tan (x-y)=\frac {\tan (x)-\tan (y)}{1+\tan (x)\tan (y)} $ so we have $\frac {a-b}{a (1+ab)}+\frac {(1+a^2)c^2}{(1+c^2)a^2}=1$ cross multilplying and simplifying we have $a^2+a^2c^2-ab-abc^2+c^2+a^2c^2+abc^2+a^3bc^2=a^2+a^2c^2+a^3bc^2+a^3b$ cancelling out we have $c^2 (1+a^2)=ab (1+a^2) $ as $a\in R $ so we can cancel $1+a^2$ thus $c^2=ab $


text:
Q: How to execute pre-database sql statements? How can we execute pre-database sqlite statements in Android?
I have created my own database layer. This layer will create the database and even the queries. It has a method that will create the table by providing the table name, column names and column types as parameters to it and the table will be generated without writing the full length query. So, to implement this I have created a test application and inside the onCreate method I have used my method that is going to generate the CREATE TABLE query and execute it. But as the database is not yet created it's throwing a NullPointerException.
So how can I fix this exception?

A: You need to use OpenHelper for this. Override it's OnOpen method to make actions on database open.
http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#onOpen%28android.database.sqlite.SQLiteDatabase%29
http://www.anotherandroidblog.com/2010/08/04/android-database-tutorial/


text:
Q: Using NULLIF with Psycopg2 type error I'm trying to use the NULLIF function to filter out some empty entries in an INSERT INTO command via psycopg2.
The problem is it won't work if the column expects a numeric, as the NULLIF function seems to be interpreted as text.
My table contains 5 columns:
cursor.execute(CREATE TABLE myDb.myTable (id serial PRIMARY KEY, name varchar, value_min decimal, value_max decimal, action_name varchar, nb_solutions integer);")

I insert some data from an array of strings using:
cursor.executemany("INSERT INTO myDb.myTable (name, value_min, value_max, action_name, nb_solutions) VALUES (%s, %s, %s, NULLIF(%s,'None'), %s)", myArray[1:len(myArray)])

In this case, the NULLIF is correctly processed and inserts the 4th string %s from myArray, or Null (depending on if the array contains 'None').
But when I try to apply NULLIF to the 5th column, which is integer, NULLIF is suddenly interpreted as text:
cursor.executemany("INSERT INTO myDb.myTable (name, value_min, value_max, action_name, nb_solutions) VALUES (%s, %s, %s, %s, NULLIF(%s,'None'))", myArray[1:len(myArray)])

And I get the following error:
ProgrammingError: column "nb_solutions" is of type integer but expression is of type text LINE 1: ...6085', ' 13.077', ' epsi', NULLIF(' 7... ^ HINT: You will need to rewrite or cast the expression.
  args = ('column "nb_solutions" is of type integer but exp...You will need to rewrite or cast the expression.\n',)
  cursor = <cursor object at 0x000000000578F3A8; closed: 0>
  diag = <psycopg2.extensions.Diagnostics object>
  pgcode = '42804'
  pgerror = 'ERROR: column "nb_solutions" is of type integer...You will need to rewrite or cast the expression.\n'
  with_traceback = <built-in method with_traceback of ProgrammingError object> Exported something to DB Mytable

Anyone know why this is happening?

A: Do not pass None as the 'None' string. Pass the real None value and Psycopg will adapt it correctly. And cast it to the intended type:
cursor.executemany('''
    INSERT INTO myDb.myTable (
        name, value_min, value_max, action_name, nb_solutions
    ) VALUES (%s, %s, %s, %s, %s::int)
''', myArray[1:len(myArray)])


text:
Q: VB.net web server I've got an Arduino MEGA 2560 and I am making a smart home. IT has no WiFi or Ethernet port so I wrote a vb.net program that reads the SerialPort. But I don't know how to make a website that would show the value of a temperature sensor.

A: You could try something like this.....
Simple HTML page with AJAX timer....
<!DOCTYPE html>

A script on this page starts this clock:

Status:

Status text:

Response:

Simple XML.....
<TempXML>
<DateTime>28\02\2016 22:10:00 :: </DateTime>
31 ºC :: 87 ºF
</TempXML>

Now, save the XML as 'TempXML.xml' in the SAME folder as your HTML page and then load the HTML it into you browser.... the timer in the HTML page will fire every second and read the XML, all you need to do is write\save the data coming in from your Arduino to the XML file and the HTML will update with the new data....
''''''''''''''''''''''
EDIT
''''''''''''''''''''''
Here is an example console application that writes to your XML file
Imports System.Xml

Module Module1

Sub Main()
    Dim NewTemp = New TempData

    ' Set you DateTime and Temp here
    NewTemp.DateTime = DateTime.Now
    NewTemp.fahrenheit = 80 ' Data from your Arduino
    NewTemp.celsius = 36    ' Data from your Arduino

    ' Create XmlWriterSettings.
    Dim settings As XmlWriterSettings = New XmlWriterSettings()
    settings.Indent = True

    Using writer As Xml.XmlWriter = Xml.XmlWriter.Create("<Path to your XML Temp file>\TempXML.xml", settings)
        ' Begin writing.
        writer.WriteStartDocument()
        writer.WriteStartElement("TempXML") ' Root.

        writer.WriteElementString("DateTime", NewTemp.DateTime.ToString)
        writer.WriteElementString("body", String.Format(" :: {0} °C :: {1} °F", NewTemp.celsius.ToString, NewTemp.fahrenheit.ToString))

        ' End document.
        writer.WriteEndElement()
        writer.WriteEndDocument()
    End Using
End Sub

End Module

Public Class TempData

Private _DateTime As DateTime
Public Property DateTime() As DateTime
    Get
        Return _DateTime
    End Get
    Set(ByVal value As DateTime)
        _DateTime = value
    End Set
End Property

Private _fahrenheit As Int32
Public Property fahrenheit() As Int32
    Get
        Return _fahrenheit
    End Get
    Set(ByVal value As Int32)
        _fahrenheit = value
    End Set
End Property

Private _celsius As Int32
Public Property celsius() As Int32
    Get
        Return _celsius
    End Get
    Set(ByVal value As Int32)
        _celsius = value
    End Set
End Property

End Class

Remember to change the Path to your XML file to suit the location on your PC in line 'Xml.XmlWriter.Create'....
Incidentally, to get the '°' degree symbol (that you see in the code above)... Position the cursor at the right location, press and hold the 'Alt' key and type 0176 and then let the 'Alt' go.....


text:
Q: oval validation to valid rest api queryparam and pathparam I am use the Oval validation in my project and i want to valid the parameter in the rest api. but Oval is a Object validation framework, i know it can valid java object, but how oval valid the queryparam and pathparam?
i have a rest api as follow:
@Get
public Response get(@QueryParam("id") String id) {
    return Response.ok().build();
}

when i add the annotation @NotNull String id, it seem that oval doesn`t valid the parameter. is there anyone know how to valid the parameter id?

A: Validating method parameters requires byte-code enhancement or usage of proxy objects.
You can use OVal's AspectJ based Programming-By-Contract features for this, see http://oval.sourceforge.net/userguide.html#programming-by-contract
If your application uses Spring-managed services you can also use the Spring integration to achieve service method parameter validation, see http://oval.sourceforge.net/userguide.html#spring-integration.
An example can be found at SpringAOPAllianceBeanValidationTest


text:
Q: Enter onkeyup not working in jsf2 I'm migrating an application from icefaces 1.8 to icefaces 3.2. It's a complex application and i'm having problems with the login page in JSF 2.
in the page we had something like:
<script type="text/javascript">

function onEnter(ev)
     {  if(ev==13)
        {
            document.getElementById('login:linkLogin').onclick();
        }
     }
</script>
.
.
.
<body onkeyup="onEnter(event.keyCode);">
.
.
.
<ice:commandLink id="linkLogin" action="#{loginBean.auth}" onclick=";encriptPass('#{login.rsaKeyMod}','#{login.rsaPubKey}');">
.
.
.

This works on jsf 1.2 + icefaces 1.8 withou problems.
But in jsf 2.1 + icefaces 3.2 I modified the code this way:
<script type="text/javascript">

    function onEnter(ev)
         {  if(ev==13)
            {
                document.getElementById('login:linkLogin').onclick();
            }
         }
    </script>
    .
    .
    .
 <h:body onkeyup="onEnter(event.keyCode);">
    .
    .
    .
    <ice:commandLink id="linkLogin" action="#{loginBean.auth}" onclick=";encriptPass('#{login.rsaKeyMod}','#{login.rsaPubKey}');">
    .
    .
    .

This code won't work this way. If I press enter, the form just resets and the bean.auth method is not even called.
What am I missing here. Does JS behaves differently in jsf2?.
EDIT:
I've found a solution in this thread:
Submit action by the enter key
The last post has the workaround.

A: If you are hitting enter while the form is in focus, it will submit the form (if you have a submit button) and go to the URL you have defined in the form action attribute.  You need to prevent this default behaviour by listening to the submit event of the form and running the preventDefault function.
$('#someform').submit(function(e) {
  e.preventDefault();
});