text:
Q: Ehrenfest's theorem derivation I'm stuck at a question from Griffiths which ask to prove that:

$$\dfrac{d \left\langle p \right\rangle}{dt}=\left\langle -\dfrac{\partial  V}{\partial  x}\right\rangle.$$

What I did is the following:
$$\dfrac{d \left\langle p \right\rangle}{dt}=\dfrac{d}{dt}\int\psi^*\dfrac{h}{i}\dfrac{d\psi}{dx}=\dfrac{h}{i}\int\left(\dfrac{d\psi^*}{dt}\dfrac{d\psi}{dx}+\psi^*\dfrac{d}{dx}\dfrac{d\psi}{dt}\right)$$
And after inserting the time derivative of $\psi^*$ and $\psi$ and taking the integration I found the following equation:
$$-\dfrac{d\psi^*}{dx}\dfrac{d\psi}{dt}-\int \psi^*\dfrac{\partial V}{\partial x}\psi$$ First term is evaluated at infinity and minus inifnity.
My question is, can I say that derivative of wave function at inifinity always goes to zero ? Or am I making a mistake somewhere?

A: Lets start by deriving Ehrenfest's theorem. The expectation value is given as:
$$\left< A \right> = \left< \psi \left| \hat{A} \right| \psi \right>$$
We can now take the time derivative of the expectation value:
$$\frac{d}{dt}\left< A \right> = \frac{d}{dt}\left< \psi \left| \hat{A} \right| \psi \right>$$
Now by expanding the right hand side:
$$\frac{d}{dt}\left< A \right> =\left<  \frac{d}{dt}\psi \left| \hat{A} \right| \psi \right> + \left<  \psi \left| \frac{\partial}{\partial t}\hat{A} \right| \psi \right>+ \left<  \psi \left| \hat{A} \right| \frac{d}{dt}\psi \right>$$
Now we can see that the first and last term can be replaced directly by considering the time-depend Schrödinger equation:
$$i\hbar\frac{\partial}{\partial t}\left| \psi \right>=\hat{H}\left| \psi \right>$$
Now giving:
$$\frac{d}{dt}\left< A \right> =-\frac{1}{i\hbar}\left< \hat{H} \psi \left| \hat{A} \right| \psi \right> + \left<  \psi \left| \frac{\partial}{\partial t}\hat{A} \right| \psi \right>+ \frac{1}{i\hbar}\left<  \psi \left| \hat{A} \right| \hat{H}\psi \right>$$
By the definition of commutators this can be seen to reduce to:
$$\frac{d}{dt}\left< A \right> =\frac{i}{\hbar}\left< \psi \left| \left[ \hat{H} , \hat{A} \right] \right| \psi \right> + \left<  \psi \left| \frac{\partial}{\partial t}\hat{A} \right| \psi \right>$$
Note here that I have made no assumptions about the positional derivative of the wave function.
Lets now inspect the expectation value of the momentum:
$$\frac{d}{dt}\left< p \right> =\frac{i}{\hbar}\left< \psi \left| \left[ \hat{H} , \hat{p} \right] \right| \psi \right> + \left<  \psi \left| \frac{\partial}{\partial t}\hat{p} \right| \psi \right>$$
Since $\hat{p}$ is time-independent, the last term vanishes:
$$\frac{d}{dt}\left< p \right> =\frac{i}{\hbar}\left< \psi \left| \left[ \hat{H} , \hat{p} \right] \right| \psi \right>\tag{1}$$
Now we define our Hamiltonian operator as:
$$\hat{H}=\frac{1}{2m}\hat{p}^2 - \hat{V}$$
We there have that:
$$\left[ \hat{H} , \hat{p} \right] = \left[ \frac{1}{2m}\hat{p}^2 , \hat{p} \right] + \left[ \hat{V} , \hat{p} \right]$$
Clearly the first commutator is equal to zero. Now lets inspect the second commutator. Here we will let the commutator work on a function:
$$\left[ \hat{V} , \hat{p} \right]f = V(-i\hbar)\frac{\partial f}{\partial x} - (-i\hbar)\frac{\partial \left(V f\right)}{\partial x}$$
Now expanding the second term:
$$\left[ \hat{V} , \hat{p} \right]f = -i\hbar V\frac{\partial f}{\partial x} +i\hbar f\frac{\partial V}{\partial x} +i\hbar V\frac{df}{dx} = i\hbar f\frac{\partial V}{\partial x}$$
Thus:
$$\left[ \hat{V} , \hat{p} \right] = i\hbar \frac{\partial V}{\partial x}$$
Now by inserting in equation (1):
$$\frac{d}{dt}\left< p \right> =\frac{i}{\hbar}\left< \psi \left| i\hbar \frac{\partial V}{\partial x} \right| \psi \right> = -\left< \frac{\partial V}{\partial x} \right>$$
Which is the result we were looking for. I know that I didn't directly answer you what you were asking for. But I think that you can find use in this indirect answer also.


text:
Q: upload a file directly into S3 using python I want to download a file received from a http url, directly into an amazon s3 bucket, instead of local system.
I run python on a 64 bit windows os.
I tried providing the Amazon S3's bucket url as the second argument of urlretrieve function of python during the file extract.
urllib.request.urlretrieve(url, amazon s3 bucket url)

I expected it to upload the file directly to s3, however it fails with filenotFound error , which , after some thought makes sense.

A: It appears that you want to run a command on a Windows computer (either local or running on Amazon EC2) that will copy the contents of a page identified by a URL directly onto Amazon S3.
This is not possible. There is no API call for Amazon S3 that retrieves content from a different location.
You will need to download the file from the Internet and then upload it to Amazon S3. The code would look something like:
import boto3
import urllib.request

urllib.request.urlretrieve('http://example.com/hello.txt', '/tmp/hello.txt')

s3 = boto3.client('s3')
s3.upload_file('/tmp/hello.txt', 'mybucket', 'hello.txt')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Laravel only update if not null Is there a way of condensing the following code into a single update()?:
    $this->validate(request(), [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255|unique:users,email,'.$id,
        'password' => 'nullable|string|min:6|confirmed',
        'timezone' => 'required|timezone',
    ]);

    $user = User::findOrFail($id);
    $user->update(request()->all());
    if (!empty(request()->input('password'))) {
        $user->update(['password' => bcrypt(request()->input('password'))]);
    }

I want to get rid of the conditional statement for updating the password because I am using a mutator to bcrypt it automatically now. Is there a method like request()->allNotNull()?

A: You can try this. Password will be filtered out if password is empty.
$input = collect(request()->all())->filter()->all();

$user = User::where('id', $id)->update($input);

A: You can do this:
$user = User::where('id', $id)->update(request()->all());

Maybe you'll also want to add ->take(1).
Update
In comments you've said you want to get rid of empty fields. Use array_filter():
array_filter($request->all());

If no callback is supplied, all entries of array equal to false will be removed.


text:
Q: Is there an API for cron that allows it to know which days are school breaks? For a little project I am making a payday simulator for school. I would like it to only run on days when we actually have school for obvious reasons. So I was thinking maybe there's an API for cron that gives it this functionality, have you all heard of any?
I am using cron-job.org for cron
Apologies if this isn't worded well!
Thanks in Advance!

A: Can't you simply select all school days in this dropdown

?


text:
Q: Grouping datetime fields if speed data more than 60 km/h in a row I'm trying to group date_created and device_id column if the speed data more than 60 km/h,
I keep trying for a weeks still don't find any solution.
Here my data:
id    device_id        date_created              speed
1        34       2016-11-24 05:00:00.000         30
2        35       2016-11-24 05:00:00.000         45
3        34       2016-11-24 05:00:45.000         75
4        35       2016-11-24 05:00:45.000         56
5        34       2016-11-24 05:01:30.000         80
6        35       2016-11-24 05:01:30.000         63
7        34       2016-11-24 05:02:15.000         91
8        35       2016-11-24 05:02:15.000         65
9        34       2016-11-24 05:03:00.000         60
10       35       2016-11-24 05:03:00.000         50
11       34       2016-11-24 05:03:45.000         20
12       35       2016-11-24 05:03:45.000         50
13       34       2016-11-24 05:04:30.000         61
14       35       2016-11-24 05:04:30.000         65
15       34       2016-11-24 05:05:15.000         79
16       35       2016-11-24 05:05:15.000         70

After grouping (Desire Result):
arrayId    array_DevId                      arrayDateC                                                  arraySpeed
[3,5,7]    [34,34,34]   [2016-11-24 05:00:45.000, 2016-11-24 05:00:45.000, 2016-11-24 05:02:15.000]     [75,80,91]
[13,15]    [34,34]      [2016-11-24 05:04:30.000, 2016-11-24 05:05:15.000]                              [61,79]
[6,8]      [35,35]      [2016-11-24 05:01:30.000, 2016-11-24 05:02:15.000]                              [63,65]
[14,16]    [35,35]      [2016-11-24 05:04:30.000, 2016-11-24 05:05:15.000]                              [65,70]

What i already get is i can group by speed and device id, but still didn't have the clue to group by datetime in a row. what i get in my arrayDateC is like [2016-11-24 05:00:45.000, 2016-11-24 06:00:45.000, 2016-11-24 05:20:15.000]
Here my code:
SELECT array_agg(id) AS arrayid,
       array_agg(device_id) AS arraydevid,
       array_agg(date_created) AS arraydatec,
       array_agg(speed) AS arrayspeed
FROM speed_event
WHERE speed > 60
  AND date_created >= '2016-11-24' AND date_created <=  '2016-11-25'
GROUP BY speed > 60, date_created, device_id
ORDER BY date_created


text:
Q: How to delete the tableview cell without pressing delete button?  - (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView1 cellForRowAtIndexPath:indexPath];
    UITableViewRowAction *flagAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"Delete" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {

    [tableData removeObjectAtIndex:indexPath.row];
    NSLog(@"indexpath %ld",indexPath.row);
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}];
    return @[ flagAction];
}

A: you can add swipe gesture to table and delete row as shown following.
- (void)viewDidLoad {
    UISwipeGestureRecognizer *gestureDeleteRow = [[UISwipeGestureRecognizer alloc] initWithTarget:self          action:@selector(cellSwipe:)];
    gestureDeleteRow.direction = UISwipeGestureRecognizerDirectionRight;
    [tableView addGestureRecognizer:gestureDeleteRow];
}

//Swipe Handler Method
-(void)cellSwipe:(UISwipeGestureRecognizer *)gesture
{
    CGPoint location = [gesture locationInView:tableView];
    NSIndexPath *swipedIndexPath = [tableView indexPathForRowAtPoint:location];
    //Delete Row…
    [ARRAY removeObjectAtIndex: swipedIndexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:swipedIndexPath, nil] withRowAnimation:UITableViewRowAnimationLeft];
}

A: Check this Code with swipe table cell with animation
Github Code


text:
Q: How to use v-for and emitted values together? I have a table that shows a list of countries like so (also, full codesandbox link below):

When the "Review" button is pressed, a modal appears and the user can review some data about the country and then choose from the following options:
[mark as ready] [mark as reject] [mark as pending]
Based on his pick, I need to emit the country's id back to the parent component so we can now display the status for that specific country as either "Rejected",  "Ready" , or "Pending".
What I need help with is how I can logically make this as simple as possible without getting complicated (something I am terrible at).
I can successfully emit data back to the parent, but where I fail is how to handle the logic on the parent side.
Let me explain:
Here is my table displaying country data and buttons for review:
App.vue:
<template>

          Country
          Status

          {{ country.name }}

            <template v-if="ready">
              <button :href="`#modal_${country.id}`" data-bs-toggle="modal">
                Ready
              </button>
            </template>
            <template v-else-if="rejected">
              <button :href="`#modal_${country.id}`" data-bs-toggle="modal">
                Rejected
              </button>
            </template>
            <template v-else>
              <button :href="`#modal_${country.id}`" data-bs-toggle="modal">
                Review
              </button>
            </template>

          <AppModal :country="country" @set-as-ready="setAsReady"> </AppModal>

</template>

Here is the modal screen for each country detail view:
AppModal.vue:
<template>
  <section
    class="modal fade"
    :id="`modal_${country.id}`"
    tabindex="-1"
    aria-labelledby="appModal"
    aria-hidden="true"
  >

            <slot name="heading"></slot>

          <button
            type="button"
            class="btn-close"
            data-bs-dismiss="modal"
            aria-label="Close"
          ></button>

                Baseline Type
                <slot name="baselineType"></slot>

                  Submitter
                Doe, John

                  Submitted
                March 2, 2021

                Status
                Review Changes

                  Field/Entity
                  {{ country.name }}

                  Full Name

                    Original Value

                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        width="16"
                        height="16"
                        fill="currentColor"
                        class="bi bi-arrow-return-right"
                        viewBox="0 0 16 16"
                      >
                        <path
                          fill-rule="evenodd"
                          d="M1.5 1.5A.5.5 0 0 0 1 2v4.8a2.5 2.5 0 0 0 2.5 2.5h9.793l-3.347 3.346a.5.5 0 0 0 .708.708l4.2-4.2a.5.5 0 0 0 0-.708l-4-4a.5.5 0 0 0-.708.708L13.293 8.3H3.5A1.5 1.5 0 0 1 2 6.8V2a.5.5 0 0 0-.5-.5z"
                        />
                      </svg>
                      Updated Value

                  Local Short Name

                    Original Value

                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        width="16"
                        height="16"
                        fill="currentColor"
                        class="bi bi-arrow-return-right"
                        viewBox="0 0 16 16"
                      >
                        <path
                          fill-rule="evenodd"
                          d="M1.5 1.5A.5.5 0 0 0 1 2v4.8a2.5 2.5 0 0 0 2.5 2.5h9.793l-3.347 3.346a.5.5 0 0 0 .708.708l4.2-4.2a.5.5 0 0 0 0-.708l-4-4a.5.5 0 0 0-.708.708L13.293 8.3H3.5A1.5 1.5 0 0 1 2 6.8V2a.5.5 0 0 0-.5-.5z"
                        />
                      </svg>
                      Updated Value

          <button type="button" class="btn btn-link" data-bs-dismiss="modal">
            Close
          </button>
          <button
            type="button"
            class="btn btn-success"
            data-bs-dismiss="modal"
            @click="setAsReady(country)"
          >
            Mark as Ready
          </button>
          <button type="button" class="btn btn-danger">Mark as Reject</button>
          <button type="button" class="btn btn-warning">Mark as Pending</button>

</template>

If the "Mark as Ready" button is pressed, for example, I want to then show an updated button with status of "Ready" for that country  (in this example, Mexico) like so:

Anyone have advice on how I can do this logically and efficiently? I have a codesandbox demo available here: https://codesandbox.io/s/tender-black-zn9nt?file=/src/App.vue

A: The simplest approach is to manipulate the central state of data. Set a new property "status" on table items. Then toggle that value depending on the event emitted from table.
<template v-if="country.status === 1">
    <button :href="`#modal_${country.id}`" data-bs-toggle="modal">
       Ready
    </button>
</template>

 methods: {
    setAsReady(id) {
      let country = this.countryChanges.find((e) => e.id === id);
      country.status = 1;
    },
  },

See the working codesandbox: https://codesandbox.io/s/dry-water-gl2q9?file=/src/App.vue


text:
Q: checkbox value always save true even checkbox is not checked in mvc When i add new if checkbox is not checked then save button press value save in database true ,
and when i press edit button if value is checked  then checkbox checked is not show .
so what i want when checkbox checked save true in database , if checkbox is not checked save false .
and when i press edit if checkbox value true then show checkbox value checked , if not true then show unchecked.
 Similarly is problem radio button .
HTML

Update Purchase Order

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

                <form id="NewOrder">

                                    @Html.TextBoxFor(m=>m.PO_ID, new { @class = "form-control mr-sm-3", @id = "POUID", Required = true })

                                PO No.

                                    @Html.TextBoxFor(m=>m.PONo, new { @class = "form-control mr-sm-3", @id = "POUNO", Required = true })

                                 PO Date

                                    @Html.TextBoxFor(m => m.PODate, new { @class = "form-control", @id = "POUDate", Required = true, @Readonly=true })

                                 Requisition Date

                                    @Html.TextBoxFor(m => m.RequisitionDate, new { @class = "form-control", @id = "RequisitionUDate", Required = true, @Readonly = true })

                                 Delivery Date

                                    @Html.TextBoxFor(m => m.DeliveryDate, new { @class = "form-control", @id = "DeliveryUDate", Required = true, @Readonly = true })

                                    @Html.CheckBoxFor(m => m.IsCancelled, new { @class = "custom-control-input", @id = "IsUCancelled" })

                                    Cancel

                                    @Html.CheckBoxFor(m => m.IsClosed, new { @class = "custom-control-input", @id = "IsUClosed" })

                                    Closed

                                    @Html.CheckBoxFor(m => m.IsPending, new { @class = "custom-control-input", @id = "IsUPending" })

                                    Pending

                                    @Html.DropDownListFor(m => m.PartyCode, ViewBag.PartyCode as List<SelectListItem>, new { @class = "chosen-select", id = "PartyUCode", Required = true })

                                Seller Quot Ref No.

                                    @Html.TextBoxFor(m => m.SellerQuotRefNo, new { @class = "form-control", @id = "SellerUQuotRefNo", @placeholder = "SellerQuotRefNo", Required = true })

                                 Seller Quot Date

                                    @Html.TextBoxFor(m => m.SellerQuotDate, new { @class = "form-control", @id = "SellerUQuotDate", Required = true, @Readonly = true })

                                 Comparative RefNo

                                    @Html.TextBoxFor(m => m.ComparativeRefNo, new { @class = "form-control", @id = "ComparativeURefNo", @placeholder = "ComparativeRefNo", Required = true })

                                <fieldset>
                                    @Html.RadioButtonFor(e => e.WithItemCode, true, new { id = "RUtrue", @checked = true })
                                    @Html.Label("RUtrue", "With Item Code")

                                    @Html.RadioButtonFor(e => e.WithItemCode, false, new { id = "RUfalse" })
                                    @Html.Label("RUfalse", "With GL Code")
                                </fieldset>

                                    @Html.CheckBoxFor(m => m.ValidateQty, new { @class = "custom-control-input", @id = "ValidateUQty" })

                                    Validate Qty

                                 Terms Of Delivery

                                    @Html.TextAreaFor(m => m.TermsOfDelivery, new { @class = "form-control", @id = "UTermsOfDelivery", @placeholder = "TermsOfDelivery", Required = true })

                                 Terms Of Payment

                                    @Html.TextAreaFor(m => m.TermsOfPayment, new { @class = "form-control", @id = "UTermsOfPayment", @placeholder = "TermsOfPayment", Required = true })

                                Terms Of Conditions

                                    @Html.TextAreaFor(m => m.TermsOfConditions, new { @class = "form-control", @id = "UTermsOfConditions", @placeholder = "TermsOfConditions", Required = true })

                            <button type="reset" class="btn btn-primary" data-dismiss="modal">Close</button>
                            <button id="UpdatePO" type="submit" class="btn btn-primary">Update</button>

                </form>

Json Function
#region PO Main Select
        public JsonResult POMain_Select(Int64 PO_ID)
        {
            PurchaseOrder mPO = new PurchaseOrder();
            mPO = mPO_Select(PO_ID);
            return Json(mPO, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region Select PO for Edit
        public PurchaseOrder mPO_Select(Int64 PO_ID)
        {

            try
            {
                PurchaseOrder mPO = new PurchaseOrder();

                con = new SqlConnection(constring);
                SqlCommand cmd = new SqlCommand("Select PO_ID, PONo, PODate, Comp_ID, GL_Year, Party_Code, SellerQuotRefNo, SellerQuotDate, RequisitionDate, DeliveryDate, ComparativeRefNo, TermsOfDelivery, TermsOfPayment, TermsOfConditions, IsPending, IsClosed, IsCancelled, EntryDate, UserName, POAmount, PaidAmount, IsPaid, WithItemCode, ValidateQty from POMain where PO_ID ='"+ PO_ID + "' ", con);
                cmd.CommandType = CommandType.Text;
                con.Open();

                DataTable mDT = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(mDT);
                mPO.PO_ID = mDT.Rows[0]["PO_ID"].ToString();
                mPO.PONo = mDT.Rows[0]["PONo"].ToString();
                mPO.PODate = DateTime.Parse(mDT.Rows[0]["PODate"].ToString()).ToString("yyyy-MM-dd");
                mPO.Comp_ID = mDT.Rows[0]["Comp_ID"].ToString();
                mPO.GL_Year = mDT.Rows[0]["GL_Year"].ToString();
                mPO.PartyCode = mDT.Rows[0]["Party_Code"].ToString();
                mPO.SellerQuotRefNo = mDT.Rows[0]["SellerQuotRefNo"].ToString();
                mPO.SellerQuotDate = DateTime.Parse(mDT.Rows[0]["SellerQuotDate"].ToString()).ToString("yyyy-MM-dd");
                mPO.RequisitionDate = DateTime.Parse(mDT.Rows[0]["RequisitionDate"].ToString()).ToString("yyyy-MM-dd");
                mPO.DeliveryDate = DateTime.Parse(mDT.Rows[0]["DeliveryDate"].ToString()).ToString("yyyy-MM-dd");
                mPO.ComparativeRefNo = mDT.Rows[0]["ComparativeRefNo"].ToString();
                mPO.TermsOfDelivery = mDT.Rows[0]["TermsOfDelivery"].ToString();
                mPO.TermsOfPayment = mDT.Rows[0]["TermsOfPayment"].ToString();
                mPO.TermsOfConditions = mDT.Rows[0]["TermsOfConditions"].ToString();
                mPO.IsClosed = Convert.ToBoolean(mDT.Rows[0]["IsClosed"].ToString());
                mPO.IsCancelled = Convert.ToBoolean(mDT.Rows[0]["IsCancelled"].ToString());
                mPO.UserName = Session["AgentName"].ToString();
                mPO.WithItemCode =Convert.ToBoolean(mDT.Rows[0]["WithItemCode"].ToString());
                mPO.ValidateQty = Convert.ToBoolean(mDT.Rows[0]["ValidateQty"].ToString());

                con.Close();
                return mPO;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

Jqgrid


text:
Q: Why template chooses T equals int when implicity passed uint16_t? I have next snippet
class Mapper { //not templated!
...
template<class T>
static QList<quint16> toPduValue(T value)
{
    constexpr quint8 registersPerT = sizeof(T) / sizeof(quint16);

    return buildPduValue((registersPerT < 1) ? (quint16) value : value);
}

template<class T>
static QList<quint16> buildPduValue(T value)
{
...
}
...
}

But when to  toPduValue passed bool, and then to buildPduValue passed (quint16) value buildPduValue specializes like <int>?
callstack

debugger shows next expression

A: The type of your ternary expression is int.  You can verify this by trying to compile this code and looking carefully at the error message:
#include <stdint.h>
char * foo = (2 < 3) ? (uint16_t)2 : (bool)1;

The error message will be something like:

error: invalid conversion from 'int' to 'char*'

You could just apply a cast to your ternary expression to cast it to the specific type you want.
Or you could ensure that both possible values of the ternary expression have the same type, so that the overall expression will have the same type.
Or you could use a if statement instead of a ternary expression.
Note that your ternary expression can only have one type; it doesn't have a different type depending on which case was evaluated.


text:
Q: nodejs, cascade calls to asynchronous function until condition occurs I need to call several time an asynchronous function (here, to force motor speed), until maximum speed is reached.
But I don't know how to code "multiple calls" with no predefined number of call.
Here is the base of my code.
/* drive motor
        from initialSpeedPercent
        to finalSpeedPercent
        step by step with delay
    */
var initialSpeedPercent = 0;
var finalSpeedPercent = 80;
var duration = 2000;    // in millisecond
var accelerationStep = 5;

var stepSpeed = (finalSpeedPercent - initialSpeedPercent) / (accelerationStep - 1);
var stepDuration = duration / (accelerationStep - 1);

function setMotorSpeed( percentOfSpeed, funcWhenCompleted) {
    // send consign to motor then return
    console.log( `motorspeed set to ${percentOfSpeed}`);
    let err = undefined;    // depending of motor behavior
    if (err) {
        funcWhenCompleted( { cmd: 'setMotorSpeed', err: err }, undefined );
    }
    else {
        funcWhenCompleted( undefined, { cmd: 'setMotorSpeed', newSpeed: percentOfSpeed } );
    }
}

const promiseSpeed = new Promise( function ( resolve, reject ) {

    initialSpeedPercent += stepSpeed;
    setMotorSpeed( initialSpeedPercent, function (err, result) {
        if (err) {
            reject( err);
        } else {
            // resolve after step duration
            setTimeout( () => {
                resolve( result );
            }, stepDuration );
        }
    } );
} );

promiseSpeed
    .then( ( result ) => {
        console.log( 'promiseSpeed success:', result );

        ... how to call in cascade.... until result.newSpeed >= finalSpeedPercent ?

        promiseSpeed
            .then( ( result ) => {
                console.log( 'promiseSpeed success:', result );
            } );
    } )
    .catch( ( error ) => {
        console.log( 'promiseSpeed error:', error );
    } )
    .finally( () => {
        console.log('promiseSpeed() is done!');
    } );

How to do that ?

A: I have found this solution. But I suppose there is a more simple way to do that.
How to avoid a dangerous stack overflow if there are to much inside-call ?
/*  _testCascade.js

    - Drive motor speed principle, step by step
    */

Date.prototype.yyyymmddhhmmsslll = function() {
    var yyyy = this.getFullYear();
    var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based
    var dd  = this.getDate() < 10 ? "0" + this.getDate() : this.getDate();
    var hh = this.getHours() < 10 ? "0" + this.getHours() : this.getHours();
    var min = this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes();
    var ss = this.getSeconds() < 10 ? "0" + this.getSeconds() : this.getSeconds();
    var lll = this.getMilliseconds() < 10 ? "00" + this.getMilliseconds() :
        this.getMilliseconds() < 100 ? "0" + this.getMilliseconds() :
        this.getMilliseconds();
    return yyyy + '-' + mm + '-' + dd + ' ' + hh + ':' + min + ':' + ss + '.' + lll;
    };

/*  @params: { fromSpeed: -50, stepSpeed: +10, toSpeed: -12 }
        speed(s) in percent, from -100 to +100
    */
function driveMotor( params) {
    const funcName = "driveMotor";
    // console.log( `${new Date()} > ${funcName} > enter with params: ${JSON.stringify(params)}...`);
    return new Promise((successCallback,failureCallback) => {

        let objective = params.fromSpeed + params.stepSpeed;
        // TIMEOUT simulate asynchronous command of speed
        setTimeout( function() {
            const funcName = "asyncDriveMotor";

            // console.log( `${new Date()} > ${funcName} > command executed with objective: ${objective}...`);

            if (Math.random() > .2) {
            // if (true) {
                // console.log( `${new Date()} > ${funcName} > success with objective: ${objective}...`);
                let success = params;
                success.reachedSpeed = objective;
                successCallback( { err: undefined, success: success } );
            } else {
                // console.log( `${new Date()} > ${funcName} > Promise FAILS with objective: ${objective}...`);
                failureCallback( { err: true, success: undefined} );
            }
        }, 100);
    })
}

function progressiveDriveMotorSpeed( params) {

    if (params.stepSpeed == 0) {
        return;
    }
    if (params.fromSpeed < -100
        || params.fromSpeed > +100) return;
    if (params.toSpeed < -100
        || params.toSpeed > +100) return;

    let promise = driveMotor( params );

    promise.then( function(result) {
        const funcName = "driveMotor.then";

            let stop = false;

            console.log( `${new Date()} > ${funcName} > result: ${JSON.stringify(result)} `);
            if (result.err) {
                console.log( `${new Date()} > ${funcName} > err: ${result.err}...stop required`);
                stop = true;

            } else {
                // console.log( `${new Date()} > ${funcName} > success...`);

                if (result.success.stepSpeed > 0) {
                    if (result.success.reachedSpeed >= result.success.toSpeed) {
                     stop = true;
                    }
                }

                if (result.success.stepSpeed < 0) {
                    if (result.success.reachedSpeed <= result.success.toSpeed) {
                        stop = true;
                    }
                }

                // console.log( `${new Date()} > ${funcName} > success 2...stop: ${stop}`);
                if (stop == false) {
                    params.fromSpeed = result.success.reachedSpeed;
                    if ( (params.fromSpeed + params.stepSpeed) > params.toSpeed) {
                        params.fromSpeed = params.toSpeed - params.stepSpeed;
                        console.log( `${new Date()} > ${funcName} > adjust in order to reach exactly...params.fromSpeed: ${params.fromSpeed}`);
                    }
                    // recall
                    progressiveDriveMotorSpeed( params);
                }
            }

    })
    .catch( function( result) {
        const funcName = "catch";
        if (result.err) {
            console.log( `${new Date()} > ${funcName} > FAILURE...result: ${JSON.stringify(result)} with params: ${JSON.stringify( params)} `);
        } else {
            console.log( `${new Date()} > ${funcName} > COMPLETED...result: ${JSON.stringify(result)} with params: ${JSON.stringify( params)}`);
        }
    });
}

/* tests:
    progressiveDriveMotorSpeed( { fromSpeed: 0, stepSpeed: 10, toSpeed: 50 } );
    progressiveDriveMotorSpeed( { fromSpeed: 0, stepSpeed: 10, toSpeed: 48 } );
    progressiveDriveMotorSpeed( { fromSpeed: 50, stepSpeed: -10, toSpeed: 0 } );
    progressiveDriveMotorSpeed( { fromSpeed: -50, stepSpeed: +10, toSpeed: -12 } );
    */
progressiveDriveMotorSpeed( { fromSpeed: -50, stepSpeed: +10, toSpeed: -12 });


text:
Q: Move gridlines in WPF Charting toolkit Is it somehow possible to move gridlines in WPF Charting toolkit. I have following XAML code:
<chartingToolkit:Chart Name="lineChart"
                       Title="Statistik"
                       FontSize="16"
                       PlotAreaStyle="{StaticResource PlotAreaStyle}"
                       FontFamily="Comic Sans MS"
                       VerticalAlignment="Stretch"
                       Margin="73,10,10,80"
                       Background="White"
                       HorizontalAlignment="Stretch">
   <chartingToolkit:LineSeries Title="Solgt"
                               Name="seriesSolgt"
                               DependentValuePath="Value"
                               IndependentValuePath="Key"
                               IsSelectionEnabled="True">
      <chartingToolkit:LineSeries.DependentRangeAxis>
         <chartingToolkit:LinearAxis Orientation="Y"
                                     Title="Beløb"
                                     ShowGridLines="True" />
      </chartingToolkit:LineSeries.DependentRangeAxis>
   </chartingToolkit:LineSeries>
   <chartingToolkit:LineSeries Title="Betalt"
                               Name="seriesBetalt"
                               DependentValuePath="Value"
                               IndependentValuePath="Key"
                               IsSelectionEnabled="True" />
   <chartingToolkit:LineSeries Title="Skylder"
                               Name="seriesSkylder"
                               DependentValuePath="Value"
                               IndependentValuePath="Key"
                               IsSelectionEnabled="True" />
   <chartingToolkit:Chart.Axes>
      <chartingToolkit:CategoryAxis Orientation="X"
                                    Title="Dato"
                                    ShowGridLines="True"
                                    GridLineStyle="{StaticResource GridLineStyle}" />
   </chartingToolkit:Chart.Axes>
</chartingToolkit:Chart>

And my chart looks like this:

I want to shift my vertical gridlines to be on the dots.


text:
Q: "Remote Acknowledge failed: scp: ambiguous target" while uploading files using "scp" from Windows machine, while it works on Linux and Mac I am trying to run a test case which basically copies a file from my machine to a mock server running in docker. The same test works fine on Mac and Ubuntu. But on Windows it's getting failed with the following error:-
Exception while executing command on remote SSH server
java.lang.RuntimeException: Exception while executing command on remote SSH server
    at com.org.implementation.RemoteCommandWrapper.runSshCommandWithTimeout(RemoteCommandWrapper.java:53)
    at com.org.implementation.RemoteCommandWrapper.copyLocalToRemote(RemoteCommandWrapper.java:121)
...

Caused by: java.util.concurrent.ExecutionException: java.lang.RuntimeException: Remote Acknowledge failed: scp: ambiguous target

    at java.base/java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:395)
    at java.base/java.util.concurrent.CompletableFuture.get(CompletableFuture.java:2022)
    at com.org.implementation.cboserver.RemoteCommandWrapper.runSshCommandWithTimeout(RemoteCommandWrapper.java:49)
    ... 92 more
Caused by: java.lang.RuntimeException: Remote Acknowledge failed: scp: ambiguous target

    at com.org.implementation.RemoteCommandWrapper.checkAck(RemoteCommandWrapper.java:174)
    at com.org.implementation.RemoteCommandWrapper.waitForFileCopied(RemoteCommandWrapper.java:136)
    at com.org.implementation.RemoteCommandWrapper.lambda$copyLocalToRemote$1(RemoteCommandWrapper.java:124)
    at com.org.implementation.RemoteCommandWrapper.tryToExecuteCommand(RemoteCommandWrapper.java:68)
    at com.org.implementation.RemoteCommandWrapper.lambda$runSshCommandWithTimeout$0(RemoteCommandWrapper.java:45)
...

RemoteCommand.java:-
public void copyLocalToRemote(Session session, Path localPath, Path remotePath, String fileName) {
    log.info("localPath: {}",localPath); //localPath:C:\Users\myuser\project1\src\test\resources\5f9cce18-362e-4973-a26b-730131841d7b
    log.info("remotePath: {}",remotePath); // remotePath:\
    log.info("fileName: {}",fileName);// fileName: CustomFile.zip
    String copyCommand = createCopyCommand(remotePath);
    runSshCommandWithTimeout(session,
            copyCommand,
            (channel, in, out) -> {
                waitForFileCopied(channel, in, out, localPath, fileName);
                return null;
            });
}

private String createCopyCommand(Path remotePath) {
    return String.format("scp -p -t %s\n", remotePath);
}

private void waitForFileCopied(Channel channel, InputStream in, OutputStream out, Path localPath, String fileName) {
    Path from = localPath.resolve(fileName);
    try (FileInputStream fis = new FileInputStream(from.toString())) {
        checkAck(in);
        setFileAccess(from, out, in);
        fis.transferTo(out);

        // send '\0'
        out.write(new byte[]{0}, 0, 1);
        out.flush();
        checkAck(in);
    } catch (IOException e) {
        throw new RuntimeException("Error copying custom file", e);
    }
}

@SneakyThrows
private void checkAck(InputStream in){
    int b = in.read();
    if (b == 0) return;

    if (b < 0) throw new RuntimeException("Remote Acknowledge failed: " + Integer.valueOf(b));

    StringBuilder sb = new StringBuilder();
    int c;
    do {
        c = in.read();
        sb.append((char) c);
    }
    while (c != '\n');
    throw new RuntimeException("Remote Acknowledge failed: " + sb.toString());
}

<T> T runSshCommandWithTimeout(final Session session, String command, RemoteResultFactory<T> resultFactory) {
    CompletableFuture<T> future = CompletableFuture.supplyAsync(
            () -> tryToExecuteCommand(session, command, resultFactory)
    );

    try {
        return future.get(timeoutMs, TimeUnit.MILLISECONDS);
    } catch (TimeoutException e) {
        throw new RemoteTimeoutException(String.format("Timeout while executing command on remote SSH server: %d ms", timeoutMs));
    } catch (Exception e) {
        throw new RuntimeException("Exception while executing command on remote SSH server", e);
    }
}

private <T> T tryToExecuteCommand(Session session, String command, RemoteResultFactory<T> resultFactory) {
    Channel channel = null;
    try {
        channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);

        // TODO handle extInputStream (error stream)
        try (InputStream in = channel.getInputStream();
             OutputStream out = channel.getOutputStream()) {

            channel.connect();
            return resultFactory.getResult(channel, in, out);
        }
    } catch (JSchException | IOException e) {
        throw new RuntimeException("Exception while executing command on remote SSH server", e);
    } finally {
        if (channel != null) {
            channel.disconnect();
        }
        session.disconnect();
    }
}

While searching this error on Google I can understand that scp is not able to recognize the target destination and that is also should be problem with Window paths or may be because of "/" or "\" as the same test is working on Linux based filesystems (and in Mac).
I am not able to figure out the exact issue and how to resolve it.
Can anybody suggest something to recover from this?
Thanks

A: The remote path must be /, not \.
And the argument to createCopyCommand cannot be Path, as on Windows, that will translate the / to \.


text:
Q: Where should I store a default list of strings in an iOS app? I have an app that stores lists of strings.
I currently have a CoreData entity for a list and for a user; a user has a relationship to many lists. A user can create more lists.
But I would like to include some default lists. Where should I store these default lists?
The options that come to mind are:

*

*Prepopulate CoreData with some lists

*Store default lists in UserDefaults

*Store default lists in plist file

*Explicitly create default lists in code where they are needed

What is the best way to store a default array of strings for an iOS app?

A: IMO there is no one-answer to your question an these really depends on your use case.
In general, if your user shall have any interaction with the default lists (manipulating, hide, delete) i would put them in your CoreData.
I assume since you have an entity for the user, you allow multiple different users to use the app on the same device? So if you would store them in the userDefaults you would also have to keep track off the modifications for each user. In general the userDefaults should only be used for "small" data, cf. doc

The defaults system allows an app to customize its behavior to match a
  user's preferences. For example, you can allow users to specify their
  preferred units of measurement or media playback speed.


text:
Q: What does "he's looking between Charlie and Jules" mean here? I would like to know what "he's looking between Charlie and Jules" means in the following sentences:

'So Charlie boy,' Johnno says, 'tell us. How did you two first meet?'
I think at first he means Charlie and I. Then I realise
he's looking between Charlie and Jules. Right.
'A millions years ago . . .' Jules says. She and Charlie raise their
eyebrows at each other in perfect unison.
'I taught her to sail,' Charlie says. 'I lived in Cornwall. It was my
summer job.'

*

*Lucy Foley, The Guest List, Chapter 12

This is a thriller novel published in 2020 in the United Kingdom. One hundred and fifty guests would be gathering at some remote and deserted fictional islet called Inis an Amplóra off the coast of the island of Ireland to celebrate the wedding between Jules (a self-made woman running an online magazine called The Download) and Will (a celebrity appearing in a TV show program called Survive the Night). The day before the actual wedding day, Hannah, the wife of Charlie (Jules' friend), arrived at the island and is now at the dinner party for the rehearsal dinner with only some selected guests. And during the party, Johnno, Will's friend, asks Charlie and Jules as to how they came to meet each other in the first place. At first, Hannah thinks the question is directed to Charlie and herself, but soon realizes that it is for Jules and Charlie.
In this part, I wonder what "between" means in particular.
Does it mean that Johnno really saw the air between Jules and Charlie, or shall I say, looked towards the direction where the two were standing?
Or perhaps that, Johnno saw Jules, and then Charlie, in an alternating way? (These are just my guesses.)

A: Your guesses make sense.  In context I imagine looking at Jules, the Charlie, then back again.  But the others readings also make sense and are possible.
Its ambiguous, but only in an aspect that isn't critical to the meaning. The meaning is that Johnno indicates, without speaking (just by the direction that he is looking), that he is asking about Charlie and Jules. So there is no need to be confused by the ambiguity.


text:
Q: django rest framework no authentication no permission
I want to access api without any authentication or permission in django rest framework. To achieve this whenever I am having following setting I end up in error.
Setting:
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (),
    'DEFAULT_AUTHENTICATION_CLASSES': (),
    'PAGE_SIZE': 10
}

Error:
TypeError at /endpoints/

'many' is an invalid keyword argument for this function

Request Method:     GET
Request URL:    http://localhost:9900/endponint/?format=api
Django Version:     1.8.3
Exception Type:     TypeError
Exception Value:

'many' is an invalid keyword argument for this function

Exception Location:     /home/user/.virtualenvs/test/lib/python3.4/site-packages/django/db/models/base.py in __init__, line 480
Python Executable:  /home/user/.virtualenvs/test/bin/python
Python Version:     3.4.0
Python Path:

['/home/user/Projects/test/new',
 '/home/user/.virtualenvs/test/lib/python3.4',
 '/home/user/.virtualenvs/test/lib/python3.4/plat-x86_64-linux-gnu',
 '/home/user/.virtualenvs/test/lib/python3.4/lib-dynload',
 '/usr/lib/python3.4',
 '/usr/lib/python3.4/plat-x86_64-linux-gnu',
 '/home/user/.virtualenvs/test/lib/python3.4/site-packages']

Server time:    Wed, 5 Aug 2015 13:46:35 +0000

Endpoint:

Request Method: GET
Request URL: http://localhost:9900/endpoint/?format=api

Django Version: 1.8.3
Python Version: 3.4.0
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'app')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')

Traceback:
File "/home/user/.virtualenvs/test/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/user/.virtualenvs/test/lib/python3.4/site-packages/django/views/decorators/csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)
File "/home/user/.virtualenvs/test/lib/python3.4/site-packages/rest_framework/viewsets.py" in view
  85.             return self.dispatch(request, *args, **kwargs)
File "/home/user/.virtualenvs/test/lib/python3.4/site-packages/rest_framework/views.py" in dispatch
  456.             response = self.handle_exception(exc)
File "/home/user/.virtualenvs/test/lib/python3.4/site-packages/rest_framework/views.py" in dispatch
  453.             response = handler(request, *args, **kwargs)
File "/home/user/.virtualenvs/test/lib/python3.4/site-packages/rest_framework/mixins.py" in list
  43.             serializer = self.get_serializer(page, many=True)
File "/home/user/.virtualenvs/test/lib/python3.4/site-packages/rest_framework/generics.py" in get_serializer
  109.         return serializer_class(*args, **kwargs)
File "/home/user/.virtualenvs/test/lib/python3.4/site-packages/django/db/models/base.py" in __init__
  480.                 raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])

Exception Type: TypeError at /endpoints/
Exception Value: 'many' is an invalid keyword argument for this function

But when I am using following setting it works but asking for authentication credentials.
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
    'DEFAULT_AUTHENTICATION_CLASSES': (),
    'PAGE_SIZE': 10
}

Please let me know how to access rest apis without any credentials.
I am running with django 1.8 djangorestframework 3.1

A: You can use following settings for DJR:
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny',),
    'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework.authentication.SessionAuthentication',),
}

AllowAny permission isn't really need, but I think it'll good practice to explicitly define that behavior in configuration.

A: You can use AllowAny permission in the permission classes and keep  authentication classes as empty in the DRF settings.
Doing this will allow unrestricted access to the API without any authentication schemes.
As per DRF docs on AllowAny permission class:

The AllowAny permission class will allow unrestricted access,
  regardless of if the request was authenticated or unauthenticated.

REST_FRAMEWORK = {
    ...
    'DEFAULT_AUTHENTICATION_CLASSES': (), # no authentication classes
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny', # will allow unrestricted access
    ),
}

A: this error can happen when using a model class in your view when defining 'serializer_class' attribute


text:
Q: BeautifulSoup - replacing string not working I have a node of type NavigableString and I want to replace the contents. According to documentation, it should be like this:
node.string = 'new string'

however, if I inspect it doesn't work:
print unicode(node)        ---> prints 'old string'
node.string = 'new string'
print unicode(node)        ---> should print 'new string' but prints 'old string'

any ideas?

A: You need to use replace_with() method to replace string.
From official documentation, it says

You can't edit a string in place, but you can replace one string with another, using replace_with()

node.string.replace_with("new string")

You can check here.
EDIT
As you mentioned node is a NavigableString, you don't need to change its .string attribute. You should do -
node = "new string"

If node is a tag then you should change its .string attribute.


text:
Q: One repository/multiple projects without getting mixed up? After reading Joel's last article on Mercurial, I'm giving it a shot on XP as a single-user, single-computer source control system.
One thing I'd like to check, though, is: It'd be easier to just create a repository of all the tiny projects I keep in eg. C:\VB.Net\, but the result is that the changes I make to the different projects therein (C:\VB.Net\ProjectA\, C:\VB.Net\ProjectB\, etc.) will be mixed in a single changelog.
But if I use a single repository for all projects, when I do diff's or go through the change history, will I be able to filter data so that I only see changes pertaining to a given project? Otherwise, is creating repositories in each project directory the only solution?
Thank you.

A: I'd keep one repository for each single project. The overhead is minimal (just one hg init for each source code directory, or one right-click in Explorer), and you won't get confused. After all, why should a change to one program affect the version history of a completely unrelated one?
Of course, you can see the history of each file in the Repository Explorer, but I think it goes against the very concept of version control to mix unrelated stuff into one repository.

A: The right granularity for a DVCS (i.e. a repo where all the history can be cloned) is the project.
If you have several projects which have different development lifecycle (i.e. a change in one does not always affect the other), they should be in their own repo.

A: In case somebody uses bitbucket, they allow a only one private repository, so you can put all your projects in there if you want them to be private. I would like to hear comments about this scenario.

A: If you do go with one repository, and only have shallow projects:
cd C:\VB.Net\ProjectA\
hg log *.*

Otherwise, may have to specify specific file extensions to avoid too much recursion:
cd C:\VB.Net\ProjectA\
hg log **/*.cpp

It can be a little slow though...  And tags/branches might get confusing if the projects really are separate.
Note: I hardly think "Hello world!" deserves its own repository just because it may be "stand alone".


text:
Q: Viewing hostnames in network Is there Linux command equal to Net View in Windows, that shows hostnames in your network?
I am in a VPN network and want to see computer names in my network.

A: You can achieve this with the program nmap. If you specify an address in CIDR notation, it will scan all IPs in that block.
nmap -sP 192.168.1.0/24

The flag -sP will bypass port scanning and just indicate whether the host is up based on ping.


text:
Q: ORACLE ENGINEER TO RELATIONAL how do i control key names generated? Working on a school assignment, building databases. First I built my logical model of my database (Using Oracle SQL developer data modeler). There's this little blue arrow button (engineer to relational) which will take your logical model and attempt to create a relational model.
WHEN it does this, it will automatically generate names for your foreign keys. This part infuriates me because it creates these ridiculous named foreign keys, I'm simply looking for a way to turn this feature off (OR I'm open to whatever suave way they actually deal with it) Because so far, I have to go back and meticulously rename all my foreign keys throughout the database.
As a specific example, I have a Client entity, with a unique ID called Client_ID. After the modeler engineers the relational model, it automatically concatenates the name of the entity along with the attribute (for the other entities that have Client_ID as a foreign key).  So even though I'd like my foreign key to simply be Client_ID it creates Client_Client_ID. I've been googling for the better part of the day but I can't find anything related to this.

A: found the answer here: https://community.oracle.com/thread/4012092
rightclick the source file of your database (its this tree looking model in this window on the left of the modeler).
click settings
naming standard
templates
here you will see its format(s) for keys, constraints,etc where you can customize them
(found this right after i posted question, sorry. Swear it took me hours earlier though)


text:
Q: DAC Signal Generator stm32 I am programming DAC peripheral of stm32f2xx. I have an array of bytes (Sound) & I would like to generate signal with sample rate = 8K.
Now my question is:
How do I specify sample rate?
Note:
I googled alot. I am only getting trangle wave generation and sine wave generation using DMA. I dont want to use DMA.
Thanks in advance for help...
Regards,

A: It's not practical to play waveforms out of the DAC without using DMA.  You set up the DMA with your samples, and you set up the DAC to use a timer as the trigger.  Then you set up your timer to trigger at your desired sample rate.

A: I would agree with TJD that in general it is not practical to do so without DMA, however it is not impossible, particularly at a low sample rate.
One could use a timer set to trigger every 1/8000th of a second as the fixed time base. From there, the interrupt routine would need to load up the next sample into the DAC. The sample rate could be varied by changing the timer's time base.
It would be a similar effort to write the code to configure the DMA controller when compared to writing the code to move the correct sample into the buffer. However, the DMA approach would be more reliable, likely posses less jitter in the sample rate, and frees up the core to execute other code that may be needed. In fact, with the TIM/DMA/DACs setup, you may be able to halt the core or enter a sleep mode that keeps peripheral clocks running.

A: yes, i agree with TJD too.
using DMA is effecient as well as free up CPU for other task [good].
managing the timing in software(core with busy loop) [bad] will not produce good results. (so, use timer for timing [good]).
now for copying, you have to dedicate CPU to do the copying after a specific interval of time (from busy-loop or timer timeout) to DAC register.[bad]
at the end i recommend, connect DMA and timer, and on timeout, DMA will copy data to DAC register [good]. this solution only appear hard but actually much easier to work with when setup'd.
[note: written in pov of someone who is trying to understand/start on something like this]


text:
Q: Pass touch event from recycler to its parent LinearLayout I have something like this :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context="cntxt">

<LinearLayout
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <!-- Title -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:gravity="center"
        android:padding="20dp"
        android:text="@string/title"
        android:textColor="@android:color/white"
        android:textSize="17sp" />

        <!-- Recycler -->
        <CustomRecyclerView
            android:id="@+id/main_activity_rv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/white"
            android:scrollingCache="false" />
</LinearLayout>

When the layout is scrolled to top, when the user makes a similar to "swipe to refresh" move with his finger, I need to make a translate animation on Y axes. In other words, I need to follow the move of the finger the whole recycler if the recycler is on top.
I tried to attach an onTouch listener to the recycler but the inner scroll of the recycler makes the situation unclear.
Any ideas to achieve this animation?
If I attach the onTouchListener to the main_layout and do the fling from the iner textview, the animation plays normally. But when I touch the recycler nothing happens (except of recycler's inner scrolls)
Thank you in advance.

A: Make the outer most layer a
SwipeRefreshLayout

Instead of a relative layout. This will give you the pull to refresh functionality any way.
Also note, under the swipe layout mentioned, there can only be one direct child view so what ever you put... Make sure to put it in the linear layout you have.
You can attach an OnRefreshListener to listen to the pull of the refresh layout.


text:
Q: Getting GeoJSON properties to appear in popup on feature click in OpenLayers I am using OpenLayers 3.
I have a map with a base layer and a geojson cluster layer. I want to be able to click an individual feature on the map and have the contents of the properties be displayed in a popup. I currently have just the position working in the popup but I would like to get information like the name of the feature and various other things. This is my code that gets me a location popup:
var element = document.getElementById('popup');

var popup = new ol.Overlay({
element: element,
positioning: 'bottom-center',
stopEvent: false
});
map.addOverlay(popup);

// display popup on click
map.on('click', function(evt) {
var feature = map.forEachFeatureAtPixel(evt.pixel,
  function(feature, layer) {
    return feature;
  });
if (feature) {
var geometry = feature.getGeometry();
var coord = geometry.getCoordinates();
popup.setPosition(coord);
coord = ol.proj.transform(coord, 'EPSG:3857', 'EPSG:4326');
$(element).popover({
  'placement': 'top',
  'html': true,
  'content': ('
Location:
'+coord)
});
$(element).popover('show');
} else {
$(element).popover('destroy');
}
});

This works fine but I would like to get the other properties. I have tried feature.get('property here') instead of feature.getGeometry(); and geometry.getCoordinates(); but that made it so the popup never appeared and the only thing I was getting in firebug was an error in the ol.js b.slice() is not a function. So basically my question is: Is there a clear cut way to display all GeoJSON properties of a feature in a popup? I got my popup using the null island example here
And here is an example JSON feature:
 {"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[0.13138000,49.475577]},"properties":{"name":"227006760","speed":"55","Nav_Status":"5"}}]}

A: You can get -- feature.get('any') -- any geojson property and show in the popup. Take a look at this demo.
You mixed up some points. So, first, get the coordinate to position the popup:
var geometry = feature.getGeometry();
var coord = geometry.getCoordinates();

Note, there is no coordinate transformation.
Second, prepare the popup content:
var content = '
' + feature.get('property here') + '
';
content += '
' + feature.get('other property') + '
';

And finally, show it. Right?

A: try it
var geometry = feature.getGeometry();
var coord = geometry.getCoordinates();
var type = geometry.getType();


text:
Q: TypeError: Cannot read property 'width' of undefined - Nuxt JS and canvas I am trying to run a sketch on the canvas element in Nuxt JS but I am having some issues (I am completely new to Vue JS).
While I have no errors in VS Code, there is an error in the browser console:
client.js?06a0:84 TypeError: Cannot read property 'width' of undefined
at Blob.get (Blob_Point.js?a5e5:126)
at Blob.render (Blob_Point.js?a5e5:29)

below is the code for my Vue file:
<template>

Blob

    <canvas id="myCanvas" width="600" height="400"></canvas>

</template>

and below is the Blob_Point JS file that I am importing:
/* eslint-disable */

// Blob Class
export default class Blob {
  // setup function
  constructor(color) {
    //the objects setup
    // 'this' is a reference to the current class
    this.points = []
    this._color = color
  }
  init() {
    for (let i = 0; i < this.numPoints; i++) {
      let point = new Point(this.divisional * (i + 1), this)
      //point.acceleration = -1 + Math.random() * 2;
      this.push(point)
    }
  }
  render() {
    let canvas = this.canvas
    let ctx = this.ctx
    let position = this.position
    let pointsArray = this.points
    let radius = this.radius
    let points = this.numPoints
    let divisional = this.divisional
    let center = this.center
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    pointsArray[0].solveWith(pointsArray[points - 1], pointsArray[1])
    let p0 = pointsArray[points - 1].position
    let p1 = pointsArray[0].position
    let _p2 = p1
    // this is the draw
    ctx.beginPath()
    ctx.moveTo(center.x, center.y)
    ctx.moveTo((p0.x + p1.x) / 2, (p0.y + p1.y) / 2)
    for (let i = 1; i < points; i++) {
      pointsArray[i].solveWith(
        pointsArray[i - 1],
        pointsArray[i + 1] || pointsArray[0]
      )
      let p2 = pointsArray[i].position
      var xc = (p1.x + p2.x) / 2
      var yc = (p1.y + p2.y) / 2
      ctx.quadraticCurveTo(p1.x, p1.y, xc, yc)
      // ctx.lineTo(p2.x, p2.y);
      //ctx.fillStyle = this.color;
      // ctx.fillRect(p1.x-2.5, p1.y-2.5, 5, 5);
      p1 = p2
    }

    var xc = (p1.x + _p2.x) / 2
    var yc = (p1.y + _p2.y) / 2
    ctx.quadraticCurveTo(p1.x, p1.y, xc, yc)
    ctx.lineTo(_p2.x, _p2.y)

    ctx.closePath()
    ctx.fillStyle = this.color
    ctx.fill()
    ctx.strokeStyle = this.color
    // ctx.stroke();

    /*
    ctx.fillStyle = '#000000';
    if(this.mousePos) {
    let angle = Math.atan2(this.mousePos.y, this.mousePos.x) + Math.PI;
    }*/
    //requestAnimationFrame(this.render.bind(this))
  }

  push(item) {
    if (item instanceof Point) {
      this.points.push(item)
    }
  }
  set color(value) {
    this._color = value
  }
  get color() {
    return this._color
  }
  set canvas(value) {
    if (
      value instanceof HTMLElement &&
      value.tagName.toLowerCase() === "canvas"
    ) {
      this._canvas = canvas
      this.ctx = this._canvas.getContext("2d")
    }
  }
  get canvas() {
    return this._canvas
  }
  set numPoints(value) {
    if (value > 10) {
      this._points = value
    }
  }
  get numPoints() {
    return this._points || 32
  }
  set radius(value) {
    if (value > 0) {
      this._radius = value
    }
  }
  get radius() {
    return this._radius || 300
  }
  set position(value) {
    if (typeof value == "object" && value.x && value.y) {
      this._position = value
    }
  }
  get position() {
    return this._position || { x: 0.5, y: 0.5 }
  }
  get divisional() {
    return (Math.PI * 2) / this.numPoints
  }
  get center() {
    return {
      x: this.canvas.width * this.position.x,
      y: this.canvas.height * this.position.y,
    }
  }
  set running(value) {
    this._running = value === true
  }
  get running() {
    return this.running !== false
  }
}
// Point Class
export class Point {
  constructor(azimuth, parent) {
    this.parent = parent
    this.azimuth = Math.PI - azimuth
    this._components = {
      x: Math.cos(this.azimuth),
      y: Math.sin(this.azimuth),
    }
    this.acceleration = -0.3 + Math.random() * 0.6
  }
  solveWith(leftPoint, rightPoint) {
    this.acceleration =
      (-0.3 * this.radialEffect +
        (leftPoint.radialEffect - this.radialEffect) +
        (rightPoint.radialEffect - this.radialEffect)) *
        this.elasticity -
      this.speed * this.friction
  }
  set acceleration(value) {
    if (typeof value == "number") {
      this._acceleration = value
      this.speed += this._acceleration * 2
    }
  }
  get acceleration() {
    return this._acceleration || 0
  }
  set speed(value) {
    if (typeof value == "number") {
      this._speed = value
      this.radialEffect += this._speed * 3
    }
  }
  get speed() {
    return this._speed || 0
  }
  set radialEffect(value) {
    if (typeof value == "number") {
      this._radialEffect = value
    }
  }
  get radialEffect() {
    return this._radialEffect || 0
  }
  get position() {
    return {
      x:
        this.parent.center.x +
        this.components.x * (this.parent.radius + this.radialEffect),
      y:
        this.parent.center.y +
        this.components.y * (this.parent.radius + this.radialEffect),
    }
  }
  get components() {
    return this._components
  }
  set elasticity(value) {
    if (typeof value === "number") {
      this._elasticity = value
    }
  }
  get elasticity() {
    return this._elasticity || 0.001
  }
  set friction(value) {
    if (typeof value === "number") {
      this._friction = value
    }
  }
  get friction() {
    return this._friction || 0.0085
  }
}

Any ideas on the why lines 29 and 127 of the Blob_Point.js file are throwing errors?
I attached 2 screens of the developer tools in chrome to show the errors along with the JS its pointing to.

Thanks for any help!

A: The main issue I can identify is here. I have added comments to the code.
Blob_Point.js

render() {
  let canvas = this.canvas // this references the Blob Class (not the Vue instance) and there is no initialised property such as canvas in the class
}

To fix this main issue, you can do something like
Blob_Point.js

export default class Blob {
  constructor(color, canvas) {
    //the objects setup
    // 'this' is a reference to the current class
    this.points = []
    this._color = color;
    this.canvas = canvas
  }
}

And then in the .vue file
.Vue

mounted() {
  let canvas = document.getElementById("myCanvas");
  this.canvas = canvas.getContext("2d");
  blob = new Blob("#C09EFF", this.canvas); // now canvas in the Blob Class constructor will refer to the vue instance canvas
  blob.canvas = canvas;
  blob.init();
  blob.render();
},

I have identified another issue here.

set canvas(value) {
  if (
    value instanceof HTMLElement &&
    value.tagName.toLowerCase() === "canvas"
  ) {
    this._canvas = canvas // there is no initialised constructor property as _canvas
    this.ctx = this._canvas.getContext("2d") // there is no initialised constructor property such as _canvas
  }
}
get canvas() {
  return this._canvas // there is no initialised constructor property as _canvas
}


text:
Q: VBA: Generating Data that mimics specific parameters (Avg, StdDev..etc) I have modified a VBA array function given to me here: Excel Generate Normalized Data
That question will explain what I am after.

Download the excel I am using to completely understand:
http://www.mediafire.com/?smq5tl9poitdacc

I am using the following data (The left side are values I enter for the data to be based upon, the right side is the results of the generated data):

As you can see, the % Diff is very good for Avg Click, but Click/Time is off when there is a high Day StdDev (Day +/-). The difference when there is a low Day Stddev is close to 0.
I think this is because the var NoClickDaysPerClick_Running_Avg becomes inaccurate because the NoClickDays_Total (Which is used indirectly to determine the running avg) is "guessed" at the start, and needs to be reassessed each click because the high StdDev adds randomness and the original "guess" becomes more and more inaccurate.
I am not sure if this is the problem, or if it is how I can even solve it.
I am just looking for advice on the best way to do what it is I want. I am not sure why the stdDev are so far off either, but thats not a big deal. I'd rather have a more accurate Click/Time than anything else- reguardless what the Day StdDev is.

here is the function in my VBA:
Function ClickSpacer(Total_Days As Long, ClicksPerDay_Desired_Avg As Double, Clicks_Desired_Deviation As Double, Clicks_Min As Integer, Clicks_Max As Integer, TotalClicksOverTotalDays_Desired_Avg As Double, NoClickDays_Desired_Deviation As Double, NoClickDays_Min As Integer, NoClickDays_Max As Integer)

    Dim Day_Array() As Integer
    ReDim Day_Array(1 To Total_Days, 1 To 1)

    Dim NumDaysToGetClicks As Double
    Dim ClickOffset As Long

    Dim Clicks_Total As Long
    Dim Clicks_SoFar As Long
    Dim Clicks_Remaining As Long

    Dim NoClickDaysPerClick_Desired_Avg As Double

    ' Number of clicks that are needed to Achieved desired Avg of clicks over time
    Clicks_Total = Round(Total_Days * TotalClicksOverTotalDays_Desired_Avg, 0)

    ' Number of days in which the user has to click atleast once to achieve desired Avg. clicks per day
    NumDaysToGetClicks = Round(Clicks_Total / ClicksPerDay_Desired_Avg, 0)

    ' The number of non-click days in order fill out the total days
    NoClickDays_Total = Round(Total_Days - NumDaysToGetClicks, 0)

    ' The guessimated average of non-click days per click to fill out total non-click days
    ' This is never used, just used for comparsion of the running Avg
    NoClickDaysPerClick_Desired_Avg = NoClickDays_Total / NumDaysToGetClicks

    'This variable is here to achieved closer results to the desired StdDev.
    'a higher multiplyer will not limit the deviation but just give an average deviation
    'For example, if the Average was 3 with a +/- 2, then with a StdDevMulti of 1
    'ALL numbers will be 1 (3-2) through 5  (3+2) with an avg of 3 and stddev of 2, the numbers will NEVER exceed the StdDev.
    'With a StdDevMulti of 2, the numbers will be 0 through 6, but should still have an
    'Avg deviation of 2.
    StdDevMulti = 1

    NoClickDays_Desired_Deviation = NoClickDays_Desired_Deviation * StdDevMulti
    Clicks_Desired_Deviation = Clicks_Desired_Deviation * StdDevMulti

    'Set the obvious defaults
    ClickedDaysSoFar = 0
    Clicks_SoFar = 0
    NoClickDays_SoFar = 0

    'Give the ClickOffset a starting value
    ClickOffset = NoClickDaysPerClick_Desired_Avg

    Do

        'used to find the "running" average of days not clicked
        NoClickDays_Remaining = NoClickDays_Total - NoClickDays_SoFar

        'used to find the "running" average of clicks per day
        Clicks_Remaining = (Clicks_Total - Clicks_SoFar)

        'used in both "running" averages mentioned above and also will
        'mark the end of the while loop.
        RemainingClickedDays = (NumDaysToGetClicks - ClickedDaysSoFar)

        ' Find what the average num. click should be based on the remaining
        ' and then apply the deviation. Only accept a click below its max
        ' above its min.
        Do

            ' Generate a random number between -1 and 1
            SignChanger = Rnd() - Rnd()

            ' Apply the randomized StdDev
            Clicks_Deviation = Clicks_Desired_Deviation * SignChanger

            'Figure out the "running" average
            ClicksPerDay_Running_Avg = Clicks_Remaining / RemainingClickedDays

            'Figure out a click value and round to the nearest whole number
            Generated_Clicks = Round(ClicksPerDay_Running_Avg + Clicks_Deviation, 0)

        ' Make sure it meets the requirements, if not, try again
        Loop While Generated_Clicks < Clicks_Min Or Generated_Clicks > Clicks_Max

        ' Set the click value to the spaced-out array index
        Day_Array(ClickOffset, 1) = Generated_Clicks

         'Find a random space based upon the "running" avg. and desired deviation
         'Make sure it between the min and max required.
         Do
             ' Generate a random number between -1 and 1
            SignChanger = Rnd() - Rnd()

            ' Apply the randomized StdDev
            NoClickDays_Deviation = NoClickDays_Desired_Deviation * SignChanger

            'Figure out the "running" average
            NoClickDaysPerClick_Running_Avg = NoClickDays_Remaining / RemainingClickedDays

            'Figure out a space value and round to the nearest whole number
            Generated_NoClickDays = Round(NoClickDaysPerClick_Running_Avg + NoClickDays_Deviation, 0)

        ' Make sure it meets the requirements, if not, try again
        Loop While Generated_NoClickDays < NoClickDays_Min Or Generated_NoClickDays >= NoClickDays_Max

        'Define the array index based upon the spacing previously generated.
        ' Make sure to "add" upon the already known index. Add 1 because you
        'have to account for the index the click occupies
        ClickOffset = ClickOffset + Generated_NoClickDays + 1

        'These should be self-explaintory
        ClickedDaysSoFar = ClickedDaysSoFar + 1
        Clicks_SoFar = Clicks_SoFar + Generated_Clicks
        NoClickDays_SoFar = NoClickDays_SoFar + Generated_NoClickDays

    Loop While ClickOffset < Total_Days And RemainingClickedDays > 0

    'Set the array equal to the clicks so that it returns the array as
    'we want. Ideally this will be just replace Total_Days fields under
    'the base, so not to require a array-function. Neither of these work:
    'ClickSpacer = Range("P1:P" & UBound(Day_Array) + 1).Value
    'Range("P1:P" & UBound(Day_Array) + 1) = Application.Transpose(Day_Array)

    ClickSpacer = Day_Array

End Function

A: I think your assumption is correct. The "problem" with the code you have above is that it uses StdDev as the basis for generating random numbers, so the standard deviation will tend to be accurate and the mean will be less accurate.
If you want more accuracy with the mean and less with the standard deviation, then you'll have to "flip" how numbers are generated: they'll need to center around your desired mean and use the desired standard deviation as a guide, rather than the other way around.
I have an idea about how this can be done, but it will take more concentration than I can apply at work, so I'll have to come back and edit this later. I'll see what I can do.


text:
Q: Android problem drawing a bitmap with opengl es I'm using https://github.com/markfguerra/GLWallpaperService/ to make an android live wallpaper.
I'm trying to load a png file as fullscreen background, however currently all I get is a black screen.
I've searched for a few days now but still haven't found out the problem.
I'm doing the following:
public void onSurfaceCreated(GL10 gl, EGLConfig config)
{
        gl.glEnable(GL10.GL_TEXTURE_2D);
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
}

and every frame:
public void onDrawFrame(GL10 gl)
{
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.target00074);
        int[] textures = new int[1];
        gl.glGenTextures(1, textures, 0);
        gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);
        GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
}

A: I would really recommend to dive into the OpenGL basics as you don't seem to know what you are doing. The screen is black because you are just uploading a texture (something you should do at initialization instead of every frame) and not actually drawing anything. You will need to define some arrays defining vertex and texture positions for a start. Refer to http://blog.jayway.com/2009/12/04/opengl-es-tutorial-for-android-%E2%80%93-part-ii-building-a-polygon/
As for the fullscreen background, you would create a single polygon with your texture

A: I found my solution in: http://obviam.net/index.php/texture-mapping-opengl-android-displaying-images-using-opengl-and-squares/

A: Two basic mistakes for when textures don't work:

*

*Texture width/height should be a power of two, unless the device supports some extension that alleviates this requirement.

*Set the TEXTURE_MIN_FILTER to something like NEAREST or LINEAR, the default is mipmapped and this produces incomplete textures unless you provide mipmaps.

Also, the texture parameter state is not global, is per texture object, so set it after binding your texture.

A: I realize that this answer doesn't really address the question at hand. Downvote me if you must.
If all you want to do is draw a full-screen background image, you don't need OpenGL. You aren't working in 3D and a static background image doesn't need to be updated very often (especially not 30-60 times a second!) so using OpenGL will only kill the battery. A better solution is to have a look at the relevant code examples and documentation, where you will see that all you really need to do is copy-paste the CubeWallpaper example, but change drawFrame() to look like the following:
    void drawFrame() {
        final SurfaceHolder holder = getSurfaceHolder();

        Canvas c = null;
        try {
            c = holder.lockCanvas();
            if (c != null) {
                // draw something
                c.drawBitmap(myBitmap, myMatrix, myPaint);
            }
        } finally {
            if (c != null) holder.unlockCanvasAndPost(c);
        }

        // Reschedule the next redraw
        mHandler.removeCallbacks(mDrawCube);
        if (mVisible) {
            mHandler.postDelayed(mDrawCube, 1000 / 25);
        }
    }

where myBitmap, myMatrix, and myPaint are Bitmap, Matrix, and Paint objects that have been initialized previously.
Even if my initial assumption (your image is static) is false, this way can still be much more efficient if your image doesn't change terribly often, for example twice a second or slower.
Hope this helps


text:
Q: Evaluation order of let-in expressions with tuples My old notes on ML say that
let (₁, … , ₙ) = (₁, … , ₙ) in ′

is a syntactic sugar for
(λ ₙ. … (λ ₁. ′)₁ … )ₙ

and that
let (₁, ₂) =  ′ in ″

is equivalent to
let  =  ′ in
let ₂ = snd  in
let ₁ = fst  in
″

where

*

*each  (with or without a subscript) stands for a variable,

*each  (with or without a sub- or a superscript) stands for a term, and

*fst and snd deliver the first and second component of a pair, respectively.

I'm wondering whether I got the evaluation order right because I didn't note the original reference.  Could anyone ((confirm or reject) and (supply a reference))?

A: It shouldn't matter whether it's:
let  =  ′ in
let ₂ = snd  in
let ₁ = fst  in
″

Or:
let  =  ′ in
let ₁ = fst  in
let ₂ = snd  in
″

Since neither fst nor snd have any side-effects. Side-effects may exist in the evaluation of  ′ but that's done before the let binding takes place.
Additionally, as in:
let (₁, ₂) =  ′ in ″

Neither ₁ nor ₂ is reliant on the value bound to the other to determine its value, so the order in which they're bound is again seemingly irrelevant.
All of that said, there may be an authoritative answer from those with deeper knowledge of the SML standard or the inner workings of OCaml's implementation. I simply am uncertain of how knowing it will provide any practical benefit.
Practical test
As a practical test, running some code where we bind a tuple of multiple expressions with side-effects to observe order of evaluation. In OCaml (5.0.0) the order of evaluation is observed to be right-to-left. We observe tthe same when it comes to evaluating the contents of a list where those expressions have side-effects as well.
# let f () = print_endline "f"; 1 in
let g () = print_endline "g"; 2 in
let h () = print_endline "h"; 3 in
let (a, b, c) = (f (), g (), h ()) in a + b + c;;
h
g
f
- : int = 6
# let f () = print_endline "f"; 1 in
let g () = print_endline "g"; 2 in
let h () = print_endline "h"; 3 in
let (c, b, a) = (h (), g(), f ()) in a + b + c;;
f
g
h
- : int = 6
# let f _ = print_endline "f"; 1 in
let g () = print_endline "g"; 2 in
let h () = print_endline "h"; 3 in
let a () = print_endline "a" in
let b () = print_endline "b" in
let (c, d, e) = (f [a (); b ()], g (), h ()) in
c + d + e;;
h
g
b
a
f
- : int = 6

In SML (SML/NJ v110.99.3) we observe the opposite: left-to-right evaluation of expressions.
- let
=   fun f() = (print "f\n"; 1)
=   fun g() = (print "g\n"; 2)
=   fun h() = (print "h\n"; 3)
=   val (a, b, c) = (f(), g(), h())
= in
=  a + b + c
= end;
f
g
h
val it = 6 : int
- let
=   fun f() = (print "f\n"; 1)
=   fun g() = (print "g\n"; 2)
=   fun h() = (print "h\n"; 3)
=   val (c, b, a) = (h(), g(), f())
= in
=   a + b + c
= end;
h
g
f
val it = 6 : int
- let
=   fun f _ = (print "f\n"; 1)
=   fun g() = (print "g\n"; 2)
=   fun h() = (print "h\n"; 3)
=   fun a() = print "a\n"
=   fun b() = print "b\n"
=   val (c, d, e) = (f [a(), b()], g(), h())
= in
=   c + d + e
= end;
a
b
f
g
h
val it = 6 : int

A: Be aware that, in OCaml, due to the (relaxation of the) value restriction, let a = b in c is not equivalent to (fun a -> c)b. A counterexample is
# let id = fun x -> x in id 5, id 'a';;
- : int * char = (5, 'a')
# (fun id -> id 5, id 'a')(fun x -> x)
Error: This expression has type char but an expression was expected of type int
#

This means that they are semantically not the same construction (the let ... = ... in ... is strictly more general that the other).
This happens because, in general, the type system of OCaml doesn't allow types of the form (∀α.α→α) → int * char (because allowing them would make typing undecidable, which is not very practical), which would be the type of fun id -> id 5, id 'a'. Instead, it resorts to having the less general type ∀α.(α→α) → α * α, which doesn't make it typecheck, because you can't unify both α with char and with int.


text:
Q: How to Prevent Nancy From Caching Views I've started testing out Nancy in self-host mode. So far, so good apart from one issue that's irking me: How do I prevent it from caching my views while developing?
I did notice a comment that view caching is supposed to be disabled in Debug mode but it doesn't seem to be working for me - I have to restart my application whenever I make a change to the HTML.
I'm using Nancy 0.10 with the built-in super simple view engine and .html files.

A: Caching is disabled by default in debug-mode. The only thing I can think of is that there might be a bug on the debug-mode detection while running in a self-host (i.e a non web-project).
Could you please try the following

*

*Make sure your are building in debug-mode and check the value of
StaticConfiguration.DisableCaches and let me know if it is true or
false

*Explicitly try setting StaticConfiguration.DisableCaches to
true and see if it stops caching your view

If DisableCaches is true then it ignores to use the cache in the DefaultViewCache type https://github.com/NancyFx/Nancy/blob/master/src/Nancy/ViewEngines/DefaultViewCache.cs#L30

A: TheCodeJunkies answer works for version 1.x of Nancy.
For 2.x of Nancy the runtimeViewDiscovery and runtimeViewUpdates properties handle if views are cached or not. This can be changed in your NancyBootstrapper class, like so:
public class NancyBootstrapper : DefaultNancyBootstrapper
{
    public override void Configure(INancyEnvironment environment)
    {
        base.Configure(environment);
        environment.Views(runtimeViewDiscovery: true, runtimeViewUpdates: true);
    }
}


text:
Q: how to change the contents of TextView in realtime the UI is very simple, only having a button login and a scrollable TextView on it, when i press the button login, 100 lines of messages will add to the TextView, but they are added at the same time, and because i need do with the messages that will add to the TextView, which will cost a few time, sometimes the app looks like no response. i hope that the message could add to the TextView line by line. IOW i want the TextView displays the added line of message in each loop. how can i realize that? Here is the main code which has been simplified:
login.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        for(int i = 0; i < 100; i++) {
            mTextView.append("test\n");
        }
    }
}

A: login.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
       mTextView.setText("");
       for(int i = 0; i < 100; i++) {
            mTextView.setText(mTextView.getText()+"test\n");
        }
    }
}

Try this code it should work

A: Use this:
    login.setOnClickListener(new OnClickListener() {
       public void onClick(View v) {

       mTextView.setText("");
if (!isStopped) {

       Acitivut.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
        for(int i = 0; i < 100; i++) {
          mTextView.append("test\n");
         }
isStopped=true;
        }
        });
}
      }
    }

A: Anything that changes UI element, must run on UI thread. Since you are running long running loop, your app freezes. You should either change the design and avoid updating UI in loop or you can use run a background thread and append the text to StringBuilder and when loop is over, append the StringBuilder text to the mtextView.
Again, if your StringBuilder contains very large text, updating that to UI may freeze it again.

A: login.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
           i=0;
           Thread thread=new Thread(new SleepThread());
           thread.start();
    }
}

private class SleepThread implements Runnable
{
         public void run()
         {
              sleep(10);
              handler.sendEmptyMessage();
         }
}

Handler handler=new Handler()
{
     public void handleMessage(Message msg)
     {
         mTextView.append("test\n");
         i++;
         if(i<100)
         {
              Thread thread=new Thread(new SleepThread());
              thread.start();
         }
     }
}


text:
Q: Find product of integers at interval of X and update value at position 'i' in an array for N queries I have given an array of integers of length up to 10^5 & I want to do following operation on array.
1-> Update value of array at any position i . (1 <= i <= n)
2-> Get products of number at indexes 0, X, 2X, 3X, 4X.... (J * X <= n)
Number of operation will be up to 10^5.
Is there any log n approach to answer query and update values.

A: (Original thought is to use Segment Tree but I think that it is not needed...)
Let N = 10^5, A:= original array of size N
We use 0-based notation when we saying indexing below
Make a new array B of integers which of length up to M = NlgN :
First integer is equal to A[0];
Next N integers is of index 1,2,3...N of A;   I call it group 1
Next N/2 integers is of index 2,4,6....;  I call it group 2
Next N/3 integers 3,6,9....   I call it group 3
Here is an example of visualized B:
B = [A[0] | A[1], A[2], A[3], A[4] | A[2], A[4] | A[3] | A[4]]

I think the original thoughts can be used without even using Segment Tree..
(It is overkill when you think for operation 2, we always will query specific range on B instead of any range, i.e. we do not need that much flexibility and complexity to maintain the data structure)
You can create the new array B described above, also create another array C of length M, C[i] := products of Group i
For operation 1 simply use O(# factors of i) to see which Group(s) you need to update, and update the values in both B and C  (i.e.  C[x]/old B[y] *new B[y])
For operation 2 just output corresponding C[i]
Not sure if I was wrong but this should be even faster and should pass the judge, if the original idea is correct but got TLE

As OP has added a new condition: for operation 2, we need to multiply A[0] as well, so we can special handle it. Here is my thought:
Just declare a new variable z = A[0], for operation 1, if it is updating index 0, update this variable; for operation 2, query using the same method above, and multiply by z afterwards.
I have updated my answer so now I simply use the first element of B to represent A[0]
Example

A = {1,4,6,2,8,7}

B = {1 | 4,6,2,8,7 | 6,8 | 2 | 8 | 7 }  // O(N lg N)

C = {1 | 2688 | 48 | 2 | 8 | 7 } // O (Nlg N)

factorization for all possible index X (X is the index, so <= N) // O(N*sqrt(N))

opeartion 1:

update A[4] to 5: factors = 1,2,4  // Number of factors of index, ~ O(sqrt(N))
which means update Group 1,2,4   i.e. the corresponding elements in B & C

to locate the corresponding elements in B & C maybe a bit tricky,
but that should not increase the complexity

B = {1 | 4,6,2,5,7 | 6,5 | 2 | 5 | 7 }    // O(sqrt(N))
C = {1 | 2688 | 48/8*5 | 2 | 8/8*5 | 7 }  // O(sqrt(N))

update A[0] to 2:
B = {2 | 4,6,2,5,7 | 6,5 | 2 | 5 | 7 }  // O(1)
C = {2 | 2688/8*5 | 48/8*5 | 2 | 8/8*5 | 7 }  // O(1)

// Now A is actually {2,4,6,2,5,7}

operation 2:

X = 3
C[3] * C[0] = 2*2 = 4  // O(1)

X = 2
C[2] * C[0] = 30*2 = 60  // O(1)


text:
Q: Prove that honeycomb structures are the most geometrically efficient structure I was reading this paragraph and it got me thinking:

The closed ends of the honeycomb cells
  are also an example of geometric
  efficiency, albeit three-dimensional
  and little-noticed. The ends are
  trihedral (i.e., composed of three
  planes) sections of rhombic
  dodecahedra, with the dihedral angles
  of all adjacent surfaces measuring
  $120^o$, the angle that minimizes surface
  area for a given volume. (The angle
  formed by the edges at the pyramidal
  apex is approximately $109^\circ 28^\prime 16^{\prime\prime}$ $\left(=
180^\circ - \cos^{-1}\left(\frac13\right)\right)$

This is hardly intuitive; is there a proof of this somewhere?

A: It is called geometrically efficient because it is  densely packed.
Also read:

*

*Sphere Packing Wikipedia

A: If you want to divide space up into uniform volume cells with minimum surface area, the honeycomb is not optimal. Look at the Weaire–Phelan structure. While honeycombs are not quite optimal, they are certainly close enough for bees -- they're suboptimal by only 0.3%.

A: This question can be explained and understood with the aid of
the physics of soap bubbles. :=)
One problem when thinking on such questions is that one
often thinks the walls as "rubber sheets". For the surface
(and in arbtrary cross sections ways) minimisation the surface
tension has to be thought constant.
So always when three lamellae join in a common "corner"
the orthogonal cross section is 120 degrees. (thee identical
forces in one point) Excuse this "corner" and orthogonal,
I am not aware of geometry in English.


text:
Q: Idiomatic borrowing I'm new to Rust and have the following working code. But I don't think what I am doing is the best way. I'm looking for insights about this piece of simple code.
I have a simple struct that holds some data:
struct BlobRef {
    hashname: String,
}

impl BlobRef {
     fn hashname(self) -> String {
         self.hashname
     }
}

And a function call. Don't worry about the source: &[u8], it will have its time to shine.
fn write(bref: BlobRef, source: &[u8]) -> io::Result<String> {
    let hashname = bref.hashname();
    match fs::create_dir_all(&hashname) {
        Ok(_) => Ok(hashname),
        Err(e) => Err(e)
    }
}

I need to assign another scoped variable hashname to stop the compiler complaining about "use of moved variable". Is this idiomatic?

A: This is not a question whether this is idiomatic or not, I believe; what you need to write depends on what you want to achieve.
Using by-value self and moving String out of the struct, consuming it in process (this is what your example does) is perfectly legitimate thing in certain contexts and wholly depends on your use cases.
On the other hand, if you want only to get the value of the string to read it somewhere (as your example suggests), it is better to return a string slice:
impl BlobRef {
     fn hashname(&self) -> &str {
         &self.hashname
     }
}

Now your second piece code could look like this:
fn write(bref: &BlobRef, source: &[u8]) -> io::Result<String> {
    let hashname = bref.hashname();
    match fs::create_dir_all(hashname) {
        Ok(_) => Ok(hashname.into()),
        Err(e) => Err(e)
    }
}

This require additional allocation in order to get a String out of &str.
However, if the only purpose of BlobRef is to transfer the string to this function, then your original approach is perfectly fine.


text:
Q: UIWebView incl. content encoding/decoding My aim: to continue a web session across an app interruption (eg. incoming SMS that is read).
Approach A:
I have tried to store the contents of a UIWebView in NSUserDefaults, like this:
NSData *webViewData = [NSKeyedArchiver archivedDataWithRootObject:webView];
[[NSUserDefaults standardUserDefaults] setObject:webViewData forKey:kDefaultsWebViewObjectKey];

and then restore it like:
NSData *dta = [[NSUserDefaults standardUserDefaults] objectForKey:kDefaultsWebViewObjectKey];
webView = [NSKeyedUnarchiver unarchiveObjectWithData:dta];

but that does not include the contents.
Approach B:
I have also tried getting the contents of the UIWebView with:
NSString *content = [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML;"];

then storing it, and retrieving it again, and then trying to set it in the UIWebView with:
- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)encodingName baseURL:(NSURL *)baseURL
but the innerHTML javascript is not returning the whole content.
Any ideas, suggestions, etc.?

A: I ended up using NSURLRequests, and then storing the retrieved HTTP body and cookies to NSUserDefaults.
After the re-entry to the app I read these and set them again on a UIWebView and in the NSHTTPCookieStorage, and then clearing the NSUserDefaults for these keys.

A: If your document doesn't reference any resources (or does so explicitly), you should be able to restore the outerHTML:
NSString *content = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML;"];

For the smoothest experience you will have to also restore the scroll and zoom properties and show a cached representation while the webview is loading


text:
Q: How to handle retrofit socket timeout for uploading files in android kotlin?  var client = OkHttpClient()
            val builder = OkHttpClient.Builder()
            val gson = GsonBuilder()
                .setLenient()
                .create()

                builder.addInterceptor(AddCookiesInterceptor(mcontext))
                builder.addInterceptor(ReceivedCookiesInterceptor(mcontext))
                builder.callTimeout(100,TimeUnit.SECONDS)

            client = builder.build()
            retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
 //                   .addConverterFactory(ScalarsConverterFactory.create())
                .build()

This is my retrofit client service builder. For normal api functions with json response callback it works fine. Is there any modification required for an large file upload?
With current scenario, uploading 20 mb data, takes more time in slow network connection which returns a socket timeout exception.
Uploading as multipart body
 var fileBody : ProgressRequestBody? = null
   fileBody = ProgressRequestBody(file,"*/*",this@CaseFileUploadFragment)
        var fileToUpload: MultipartBody.Part =
   MultipartBody.Part.createFormData("image",file.name, fileBody)
        var filename : RequestBody =
    RequestBody.create(MediaType.parse("text/plain"),file.getName())

and following is the function used
 @Multipart
    @POST("{urlMpString}")
    fun uploadFile(
        @Path ("urlMpString") urlEndString : String, @Part file: MultipartBody.Part, @Part("file") requestBody: RequestBody,
        @Part("apiInfo") `object1`: JsonObject,  @Part("parameters") `object2`: JsonObject
    ): Call<JsonObject>

Everything works fine for small data files.
Any suggestions and help will be appreciated.
Thanks

A: Try below code for okHttpClient
OkHttpClient okHttpClient = new OkHttpClient.Builder()
    .connectTimeout(5, TimeUnit.MINUTES)
    .readTimeout(30, TimeUnit.SECONDS)
    .writeTimeout(15, TimeUnit.SECONDS)
    .build();


text:
Q: How do I open a local text file and display the contents in my browser? I intend to have a link in my webpage which will open a local text file and display its contents. This is what I have tried so far:

Summary

function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}

This is the error I am getting:

XMLHttpRequest cannot load file:///F:/folder1/abc.txt. Cross origin
  requests are only supported for protocol schemes: http, data, chrome,
  chrome-extension, https, chrome-extension-resource.

My webpage is running locally on a local server.
Is it even possible to open and read local files?Seems like something browsers should probably not allow.

A: new answer:
It is still possible.

*

*Use chrome

*Install tampermonkey extension

*Check the checkbox to make it can access local files.

*Add a script into it as below:

// ==UserScript==
// @name         read localfile
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  read localfile
// @author       blackmiaool
// @match        http://stackoverflow.com/*
// @match        https://stackoverflow.com/*
// @grant        GM_getResourceText
// @resource     b file://C:\Users\blackmiaool\the-path-of-the-file
// ==/UserScript==

(function() {
    'use strict';
    var a=GM_getResourceText("b");
    console.log("The file's content is ",a);
})();

Remember to correct the file path, and test it on this page.
old answer:
Sure it's possible. If your index.html file locates at "/some-path/index.html", just put your abc.txt at "/some-path/abc.txt". And change the "file:///F:/folder1/abc.txt" to "./abc.txt".

A: For HTML5 compliant websites you can use the new APIs available with HTML5.
HTML5 FileReader interface can be used to asynchronously read a file through familiar JavaScript event handling. It provides the following functions:

*

*readAsText

*readAsBinaryString

*readAsDataURL

*readAsArrayBuffer

Please follow this treehouse blog (contains demo too) and also this for your reference.

A: Simply "NO, You can't read any files from the server deployed locally on your machine." In order to access any resource, one must have the resource available on your sever. Where your current page is being served from.

A: The file need to be in your web application to link to it.  Allowing javascript to access your machine outside the application is a security risk and is not allowed.
A back end process can read the file then give you the results but you can not read directly from javascript to a file on your machine