text:
Q: Getting MySQL error creating handler in an event I'm trying to create an Event in MySQL 5.6 and I'm getting an error whenever I try to DECLARE something, like a parameter or handler:

SQL Error [1064] [42000]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE CONTINUE HANDLER FOR SQLEXCEPTION            SET @rollMeBack = TRUE;

I'm a SQL Server guy and the syntax is giving me ulcers. I tried declaring a variable like in this question, but I still get the error at that line. Help me Obi Wan Kenobi: you're my only hope.
Entire (obfuscated) code:
DELIMITER ||

CREATE EVENT my_event
ON SCHEDULE EVERY 5 MINUTE
ON COMPLETION PRESERVE
ENABLE
COMMENT 'Fixes status'
DO IF EXISTS (
        SELECT NULL FROM [...problem records..]
    ) THEN
        -- =================================================================================================
        -- Get a complete list of bad records:
    SET @rollMeBack = FALSE ;

        SET @LogId = 0;
        CREATE TEMPORARY TABLE updateable
            SELECT DISTINCT e.id , (@LogId:=@LogId + 1) + (SELECT MAX(dsd.id) FROM LogTable dsd ) AS LogId
            FROM Table1 e
                INNER JOIN Table2 r
                    ON r.e_id = e.id
                    /*Waiting 5 minutes to not interfere with current operations:*/
                    AND r.rDateTime <= CURRENT_TIMESTAMP() - INTERVAL 5 MINUTE
            WHERE e.Status = 'Sent'
                AND NOT EXISTS(SELECT NULL FROM Table2 r2 WHERE r2.e_id = e.id and r2.rDateTime is null)
            LIMIT 100 ;

        -- =================================================================================================
        -- =================================================================================================
        DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
            SET @rollMeBack = TRUE;

        START TRANSACTION
            -- =================================================================================================
            UPDATE Table1 as e1
                INNER JOIN updateable AS u
                    ON e1.d=id = u.id
            SET e1.Status = 'Completed',
                e1.cDateTime = COALESCE (e1.cDateTime, (select max(rDateTime) from Table2 r5 where r5.e_id = e1.id));
            -- =================================================================================================
            -- Log updates:
            INSERT INTO Debug (ID, Message)
            SELECT u.LogId,
                'Record set to `Completed`'
            FROM updateable AS u;
            -- =================================================================================================
            -- Cleanup:
            DROP TABLE updateable;

        IF @rollMeBack = TRUE THEN
            ROLLBACK;
        ELSE
            COMMIT;
        END IF
        -- =================================================================================================
        -- =================================================================================================
    END IF; ||

DELIMITER ;

A: A couple of modifications render this operable.
Firstly, the handler must be declared in the correct place.  From the docs:

Handler declarations must appear after variable or condition
declarations.

Secondly, the DO IF EXISTS...END IF; should contain a BEGIN...END block after which you do your handler declaration:
...
COMMENT 'Fixes status'
DO IF EXISTS (
        SELECT NULL FROM [...problem records..]
    ) THEN
    BEGIN -- Note the added begin
        -- Moved the handler declaration to be the first statement of this block
        DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
            SET @rollMeBack = TRUE;

        -- =================================================================================================
        -- Get a complete list of bad records:
    SET @rollMeBack = FALSE ;
    ...

At the end of the code:
        ...
        -- =================================================================================================
    END; -- Note the added END
END IF; ||

DELIMITER ;

Incidentally, there is also a syntax error in the IF @rollMeBack = TRUE THEN...END IF block - the semi-colon is missing from the end of END IF.


text:
Q: Применение произвольной функции к строкам dataframe накопительным итогом У меня есть DataFrame с двумя столбцами 'total', 'cashflow'.
 timestamp   total   cashflow

2020-06-11  300.61   -300.61
2020-06-12  304.21      0.00
2020-06-15  307.05      0.00
2020-06-16  313.86      0.00

Есть функция, которую нужно применить к DataFrame[:1], DataFrame[:2], DataFrame[:3] ... DataFrame[:n], где n - количество строк в DataFrame. При этом в каждом вложенном DataFrame перед применением функции необходимо добавить к значению в последней строке столбца 'cashflow' значение столбца 'total' из той же строки и отфильтровать все нулевые значения.
В итоге нужно получить список значений функции для каждого из вложенных DataFrame.
Я дошел до реализации через цикл, но код работает очень долго.
data_xirr_1 = []
df_xirr_copy = data_cashflow['cashflow'].copy()
df_x0 = df_xirr_copy[:1]
for i in data_cashflow.index[1:]:
    df_x0 = df_x0.append(df_xirr_copy[df_xirr_copy.index == i])
    df_xirr = df_x0.copy()
    df_xirr[-1] += data_cashflow['total'][i]
    data_xirr_1 += [xirr_1(df_xirr.loc[np.abs(df_xirr) > 1E-10])]

Сама функция работает сравнительно быстро.
from scipy import optimize as op

def xnpv(rate, cashflows):
    chron_order = sorted(cashflows, key=lambda x: x[0])
    t0 = chron_order[0][0]  # t0 is the date of the first cash flow

    return sum(cf / (1 + rate) ** ((t - t0).days / 365.0) for (t, cf) in chron_order)

def xirr_1(cashflow, guess=0.001):

    return  op.newton(lambda r: xnpv(r, [(x, cashflow.loc[x]) for x in cashflow.index]), guess)

В результате получается список с n-1 значений, где n - количество строк в изначальном DataFrame
[76.10327236009363, 5.918598501439627, 22.306438719895517]

Есть какие-либо решения, которые могут ускорить применение функции накопительно ко всем вложенным dataframe?

A: Первый способ, который я нашел - векторизация.
Перевел данные в numpy и так же посчитал в цикле.
На длине массива в 2630 строк, получил выигрыш почти в 8 раз. Но все равно как то долго. Есть ли какие либо еще верхнеуровневые подходы к ускорению?
Pandas в цикле:
time_1 = time.time()
data_xirr_1 = []
df_xirr_copy = data_cashflow['cashflow'].copy()
df_x0 = df_xirr_copy[:1]
for i in data_cashflow.index[1:]:
    df_x0 = df_x0.append(df_xirr_copy[df_xirr_copy.index == i])
    df_xirr = df_x0.copy()
    df_xirr[-1] += data_cashflow['total'][i]
    data_xirr_1 += [xirr_1(df_xirr.loc[np.abs(df_xirr) > 1E-10])]

print(f'pandas {len(data_xirr_1)} {time.time() - time_1:.2f} сек.')

Numpy в цикле:
time_1 = time.time()
df_t = data_cashflow.copy()
df_t['date'] = data_cashflow.index
arr_cashflow = df_t[['cashflow', 'date']].to_numpy()
arr_xirr = []
for i in range(1,len(arr_cashflow)):
    arr_cf = arr_cashflow[:i+1].copy()
    arr_cf[i, 0] += data_cashflow['total'].iloc[i]
    arr_xirr += [xirr([(d,x) for x,d in arr_cf[np.abs(arr_cf[:, 0]) > 1E-10]])]

print(f'{len(arr_xirr)} {time.time() - time_1:.2f} сек')

Вывод:
pandas 2630 16.54 сек.
numpy 2630 2.52 сек

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find the conditional distribution ,which probably is binomial Sheila has a coin with $P(head)= p_1$ and betty has a coin with $P(head) = p_2$.Sheila tosses her coin $m$ times. Each time she obtains heads , betty tosses her coin(otherwise not). Find the distribution of the total number of heads obtained by betty.
If we let $N$ be the number of heads obtained by Sheila and $X$ the number of heads obtained by Betty, then we have the following model:
$X\mid N = n \enspace \in \enspace Bin(n,p_2)$, with $N \enspace \in \enspace Bin(m,p_1)$
Now the $E [X]$ i found to be $mp_1p_2$ and $Var[X] = mp_1p_2(1-p_1p_2)$ so this seem to be a binomial distribution $Bin(m,p_1p_2)$
however,
$P[X=k]  = \sum\limits_{n=k}^{m} P(x= k\mid N = n)P(N =n) = \sum\limits_{n=k}^{m} \binom{n}{k}p_2^kq_2^{n-k} \binom{m}{n}p_1^nq_1^{m-n}$
the question is how do you arrange the factors so that one can see that it is a $Bin(m,p_1p_2)$ distribution - assuming that is really the  distribution

A: Yes, it is binomial. For $i=1$ to $m$, let $X_i=1$ if Betty gets a head after the $i$-th toss by Sheila, anf let $X_i=0$ otherwise.
The probability that $X_i=1$ is $p_1p_2$. The total number $X$ of heads by Betty is the sum $X_1+X_2+\cdots+X_m$. This is a sum of independent Bernoulli random variables with probability of success $p_1p_2$, so it has binomial distribution with parameters $m$ and $p_1p_2$.
More informally, the probability of head by Betty after the toss by Sheila is $p_1p_2$, for Betty gets a head if and only if Sheila gets head on that throw and Betty succeeds on her then allowed throw. So on any of the $m$ trials, Betty's probability of success is $p_1p_2$, and there are $m$ independent trials.


text:
Q: Wordpress Vue Form Get current address I am working on a WordPress theme that uses Vue/PHP partials. On Submit I need an onclick event return gtag_report_conversion('current URL')".
How do I call the PHP for wordpresses current URL address in the vue form. As you can see I have tried a few things including {{ <?php get_permalink( get_the_ID() ); ?> }} but it shows nothing.
Basically, I need to know how to interpolate the PHP into the Vue form.
<form action="#" class="bg-light p-6" method="post" role="form">

Submit for Quotation

                            <template v-if="isFormSubmitted">

                                    Thank you for your inquiry!

One of our event planners will review your requests and get a quotation to you within 48 hours.

                            </template>

                            <template v-else>

{{ formErrors._ }}

                                    First Name*
                                    <input class="form-control" maxlength="40" placeholder="" type="text" v-model="formFields.name_first">

{{ formErrors.name_first }}

                                    Last Name*
                                    <input class="form-control" maxlength="40" placeholder="" type="text" v-model="formFields.name_last">

{{ formErrors.name_last }}

                                    Phone Number*
                                    <input class="form-control" maxlength="20" placeholder="" type="tel" v-model="formFields.phone">

{{ formErrors.phone }}

                                    Email
                                    <input class="form-control" maxlength="254" placeholder="" type="email" v-model="formFields.email">

{{ formErrors.email }}

                                    Date of Event
                                    <input class="form-control" maxlength="100" placeholder="" type="text" v-model="formFields.date">

{{ formErrors.date }}

                                    Location of Event / Suburb
                                    <input class="form-control" maxlength="100" placeholder="" type="text" v-model="formFields.location">

{{ formErrors.location }}

                                    Type of Event
                                    <input class="form-control" maxlength="100" placeholder="" type="text" v-model="formFields.type">

{{ formErrors.type }}

                                    Comments
                                    <textarea class="form-control" maxlength="500" placeholder="" v-model="formFields.comments"></textarea>

{{ formErrors.comments }}

                                <button
                                    class="btn btn-primary btn-sm btn-block text-white mt-4"
                                    type="button"
                                    onclick="return gtag_report_conversion('{{ <?php get_permalink( get_the_ID() ); ?> }}')"
                                    v-on:click="submit"
                                    v-bind:disabled="isFormSubmitting"
                                >
                                    <template v-if="isFormSubmitting"></template>
                                    <template v-else>Submit</template>
                                </button>

                            </template>

                        </form>

Update:
const CatalogItemsSaved=Vue.component("CatalogItemsSaved",{data:function(){return{formErrors:{},formFields:{comments:null,email:null,name_first:null,name_last:null,phone:null,date:null,location:null,type:null},items:[],isLoaded:!1,isLoading:!1,isFormSubmitted:!1,isFormSubmitting:!1}},computed:{},methods:{submit:function(){this.isFormSubmitted=!1,this.isFormSubmitting=!0,this.formErrors={};let t=this.formFields;t.action="catalog_quotation_submission",$.post(extraPath+"wp-admin/admin-ajax.php",t,(t=>{t.errors?this.formErrors=t.errors:this.isFormSubmitted=!0,this.isFormSubmitting=!1}),"json")},load:function(){this.isLoading=!0,$.post(extraPath+"wp-admin/admin-ajax.php",{action:"catalog_saved"},(t=>{this.items=t,this.isLoading=!1,this.isLoaded=!0}),"json")},reload:function(){this.isLoaded=!1,this.items=[],this.load()},remove:function(t,i){Vue.delete(this.items,i);let o=this.$cookies.get("catalog_saved"),s=[];if(o){s=JSON.parse(o);for(let i in s)s[i]==t.ID&&s.splice(i,1);this.$cookies.set("catalog_saved",JSON.stringify(s),"7d")}eventHub.$emit("catalog-item-removed",t)},updateQuantity:function(t){return this.$cookies.set("catalog_"+t.ID,t.qty,"7d")}},created:function(){eventHub.$on("catalog-item-saved",(t=>{this.reload()}))},mounted:function(){$("#modal-catalog-items-saved").on("show.bs.modal",(()=>{this.isLoaded||this.load()}))}});

A: You can use JavaScript to get this URL instead of PHP with window.location.href
Like this:
onclick="return gtag_report_conversion(window.location.href)"
Note that you should probable use the Vue click handler instead of adding another one that might not play nicely with the Vue one.
v-on:click="submit"
methods: {
  submit () {
    gtag_report_conversion(window.location.href) // add here ⭐
    // whatever your original submit code is
  }
}

Update:
const CatalogItemsSaved = Vue.component("CatalogItemsSaved", {
  data: function () {
    return {
      formErrors: {},
      formFields: {
        comments: null,
        email: null,
        name_first: null,
        name_last: null,
        phone: null,
        date: null,
        location: null,
        type: null
      },
      items: [],
      isLoaded: false,
      isLoading: false,
      isFormSubmitted: false,
      isFormSubmitting: false
    }
  },
  computed: {},
  methods: {
    submit: function () {
      gtag_report_conversion(window.location.href); // ⭐ Add this
      this.isFormSubmitted = false, this.isFormSubmitting = true, this.formErrors = {};
      let t = this.formFields;
      t.action = "catalog_quotation_submission", $.post(extraPath + "wp-admin/admin-ajax.php", t, (t => {
        t.errors ? this.formErrors = t.errors : this.isFormSubmitted = true, this.isFormSubmitting = false
      }), "json")
    },
    load: function () {
      this.isLoading = true, $.post(extraPath + "wp-admin/admin-ajax.php", {
        action: "catalog_saved"
      }, (t => {
        this.items = t, this.isLoading = false, this.isLoaded = true
      }), "json")
    },
    reload: function () {
      this.isLoaded = false, this.items = [], this.load()
    },
    remove: function (t, i) {
      Vue.delete(this.items, i);
      let o = this.$cookies.get("catalog_saved"),
        s = [];
      if (o) {
        s = JSON.parse(o);
        for (let i in s) s[i] == t.ID && s.splice(i, 1);
        this.$cookies.set("catalog_saved", JSON.stringify(s), "7d")
      }
      eventHub.$emit("catalog-item-removed", t)
    },
    updateQuantity: function (t) {
      return this.$cookies.set("catalog_" + t.ID, t.qty, "7d")
    }
  },
  created: function () {
    eventHub.$on("catalog-item-saved", (t => {
      this.reload()
    }))
  },
  mounted: function () {
    $("#modal-catalog-items-saved").on("show.bs.modal", (() => {
      this.isLoaded || this.load()
    }))
  }
});


text:
Q: Python packaging: how to handle extras? I have a networking python project which does not require a monitoring system to function. However, we added to the code a way to communicate data to different monitoring systems using clients from those monitoring systems.
Right now, in requirements.txt I have a dependency per potential client and when I install the project (pip setup.py install) all get installed. Nevertheless, I wonder if it would be possible to package the project in a way that when installing it, I can specify the client I want to use (or none) and then dependencies get installed accordingly.
For example, having an extra argument which specifies the monitoring system
python setup.py install monitor_system_1

And something in requirements.txt which does this logic:
SomeProject >=1.2
OtherProject == 4.0
if monitor_system_1 in xxxx:
    monitor_system_1_client
if monitor_system_2 in xxxx:
    monitor_system_2_client


text:
Q: Best practice since JavaFX setters/getters are final? In the process of converting a Windows application from Swing to JavaFX.  We had a lot of custom components that previously overrode the mutator methods of JTextField, for example.  In JavaFX these methods are declared final.  Should I just be creating wrapper methods that call the final methods and modify the values before and after?  I just want to make sure I go about doing it the right way from the beginning.
Edit:  I will also include the fact that some of this code is from much older versions of Java.  So it's possible certain things are no longer necessary.  This is an example of a setText method we had in a custom JFormattedTextField:
public void setText(String text) {
    String newString = "";
    if (mask == null) {
        newString = text;
        unformattedCurrent = newString;
    } else {
        newString = applyMask(text);
    }
    super.setText(newString);
    if (text.trim().length() == 0) {
        positionCaret(0);
        selectRange(0, 0);
    } else {
        int length = getFormattedText().length();
        if (isFocused() && length == getCaretPosition()) {
            super.selectAll();
        }
    }
}

A: Using Listeners to be notified of changes in mutated state
Almost everything exposed in the JavaFX public API is a property, so one way to hook into mutate operations is to add ChangeListeners (or InvalidationListeners).
See the JavaFX property documentation for more information (the following snippet is copied from there):
import javafx.beans.value.ObservableValue;
import javafx.beans.value.ChangeListener;

public class Main {
    public static void main(String[] args) {
        Bill electricBill = new Bill();

        electricBill.amountDueProperty().addListener(new ChangeListener() {
            @Override public void changed(
                 ObservableValue o,
                 Object oldVal,
                 Object newVal
            ) {
               System.out.println("Electric bill has changed!");
            }
        });

      electricBill.setAmountDue(100.00);
    }
}

For Java 8+, you could write:
Label billAmountDue = new Label();
billAmountDue.textProperty().addListener((observable, oldVal, newVal) ->
    System.out.println("Electric bill has changed!")
);

If you are subclassing, you can setup listeners in the constructor of your subclass.  These listeners can perform work similar to what you were doing in your Swing classes when you were overriding setter functions:
public class AmountLabel extends Label {
    public AmountLabel(String text) {
        super(text);

        textProperty().addListener(observable ->
            System.out.println("Amount invalidated.")
        );
    }
}

Answers to additional questions

So within the change listener I would then set the appropriate value after any mask is set?

Well you could and I've done it before.  I am not sure that it is a best practice to do so (though I don't know of another way to handle it in general).  I do recall the JavaFX property designer remarking on some forum that they didn't really design the property mechanism for updates within change listeners, so I guess it is not guaranteed.
I have run into issues where changing the location property of a WebView in a change listener caused threading issues, but I think that was an extremely unusual case due to the complex nature of WebView - I filed an accepted bug report on that particular case.
For other controls and properties you are probably fine using the "update in a listener" approach (though see the caveats in the answer to the next follow-up question).

Wouldn't setting the value within the listener create an infinite loop since it would keep going into the ChangeListener upon updating the value.

No, I dont think it creates an infinite loop.  I think there is something in the JavaFX listener implementation which stops it from looping indefinitely.  I haven't checked the source code to see what that is and if my recollection is incorrect you would need to implement specific logic to prevent recursion which would be completely undesirable as it would complicate things a lot unnecessarily.
Due to suspected the short circuiting logic to prevent the infinite recursion if you set the value of the property within the change listener, I don't really know if the changed value would propagate to all of the listeners or items bound to that property (you would need to examine the implementation or write some tests to check behavior).
So those are a few reasons why I stated that, while it will probably work in most cases, setting values in the change listener is probably not a best practice.

How about altering the getter?

This use case seems to occur less often than listening on set values.
I suggest to create a new property and setup a bidirectional binding with a string converter.  The use of a string convertor is optional, but it shows how you can listen on a transformed value.
Specific to formatted text fields
Your question is quite generic, but the problem you discuss in your post is quite specific to formatted text fields.  The generic case is what I attempted to answer previously.  For the specific case of formatted text fields there are specific solutions which may apply.
Richard recommends using a different API altogether, replaceText which is only available for TextInput:
field = new TextField() {
    @Override public void replaceText(int start, int end, String text) {
        // If the replaced text would end up being invalid, then simply
        // ignore this call!
        if (!text.matches("[a-z]")) {
            super.replaceText(start, end, text);
        }
    }

    @Override public void replaceSelection(String text) {
        if (!text.matches("[a-z]")) {
            super.replaceSelection(text);
        }
    }
};

Richard's post is quite old now.  For Java 8u40, the following feature will be included:

*

*RT-14000
Add Formatted TextField control
Another related open-jfx implementation item is:

*

*RT-37785
Provide some useful TextInputControl.Formatter implementations
That's not currently 9, but once implemented, might help provide some further concrete use cases for what you asking and a developer notes on the ticket "we believe that it is sufficient to provide example code for 8u40".
The third party JideFX library includes a FormattedTextField class.
Some background info on why things in the JavaFX API are final
Quote from Richard Bair, lead JavaFX developer:

Security for one. You can do evil things to non final classes! That is just a general rule (which is why generally we want to make everything final we can). In this particular case it may not matter.

A suggestion
What you might want to do instead of overriding a getter for something like text input formatter is to have different APIs for the format mask versus the unformatted value text versus the formatted value text.  I think this is probably what was done to add formatted JavaFX TextFields to Java 8u40.
Look at EasyBind
The third party EasyBind library may have some good recipes for dealing with the patterns you would like to implement.


text:
Q: Skip a part of the stream when it's stalled I have a situation where messages are passed through a component that could possibly delay them.
Under stress I'd like to skip this component, so that no more than X messages could be delayed simultaneously. Overflowing messages will skip this stage and move to the next stage of the steam.
Messages are stalled within this stage till their future is done, or up to one minute, whichever comes first.
I can probably implement a custom GraphStage similarly to this buffer example, or use divertTo with some counter to cause messages to skip the stalled component,
but it feels like there might be an easier approach in akka streams

A: I've been playing around your use case and came up with a solution based on an Akka Actor representing a counter and an asynchronous map stage:
The idea being that up to 3 elements can be processed at any given time and that based on a counter whose max capacity is 2 we'd only allow at most 2 of these elements to simultaneously be processed by the slow component.
This way, there's always one thread of processing reserved to upstream elements that would be branched out from the slow component and directly reach downstream.

Let's first define a basic Counter with a maximum capacity as an Akka Actor:
class Counter(max: Int) extends Actor {
  private var count: Int = 0

  override def receive: Receive = {
    case TryAndLock if count < max =>
      count += 1
      sender ! true
    case TryAndLock =>
      sender ! false
    case Release =>
      count -= 1
  }
}

sealed trait CounterAction
case object TryAndLock extends CounterAction
case object Release extends CounterAction

val counter = system.actorOf(Props(new Counter(max = 2)))

It holds a mutable count variable that can be incremented via a TryAndLock request, but only if the count hasn't yet reached the maximum capacity, and can be decremented via a Release request.
We're using an Actor so that concurrent lock and release operations from within the following mapAsync stage are correctly handled without race conditions.

Then, it's just a matter of using a mapAsyncUnordered stage with a parallelism just 1 unit above the counter's max capacity.
Any element passing through the asynchronous stage will query the Counter to try and lock a resource. If a resource's been locked, then the element will be thrown into the slow component. If not, it will skip it. Elements are passed into the slow component until we reach the counter's max capacity, at which point any new element will be skipped until an element exits the slow component and releases a resource from the counter.
We can't simply use a mapAsync because elements would keep their upstream's order when existing the stage, making skipped elements wait for elements processed by the slow component to finish before being produced downstream. Thus the necessity to use the mapAsyncUnordered instead.
Let's define an example with at most 2 elements processed at the same time by the slow component and an asynchronous map whose parallelism is 3:
Source(0 to 15)
  .throttle(1, 50.milliseconds)
  .mapAsyncUnordered(parallelism = 3) { i =>
    (counter ? TryAndLock).map {
      case locked: Boolean if locked =>
        val result = slowTask(i)
        counter ! Release
        result
      case _ =>
        skipTask(i)
    }
  }
  .runForeach(println)

with for instance these two functions that'll simulate the slow component (slowTask) and what to do when skipping the slow component (skipTask):
def slowTask(value: Int): String = {
  val start = Instant.now()
  Thread.sleep(250)
  s"$value - processed - $start - ${Instant.now()}"
}
def skipTask(value: Int): String =
  s"$value - skipped - ${Instant.now()}"

which results in something like:
2 - skipped - 2020-06-03T19:07:19.410Z
3 - skipped - 2020-06-03T19:07:19.468Z
4 - skipped - 2020-06-03T19:07:19.518Z
5 - skipped - 2020-06-03T19:07:19.569Z
1 - processed - 2020-06-03T19:07:19.356Z - 2020-06-03T19:07:19.611Z
0 - processed - 2020-06-03T19:07:19.356Z - 2020-06-03T19:07:19.611Z
8 - skipped - 2020-06-03T19:07:19.719Z
9 - skipped - 2020-06-03T19:07:19.769Z
10 - skipped - 2020-06-03T19:07:19.819Z
6 - processed - 2020-06-03T19:07:19.618Z - 2020-06-03T19:07:19.869Z
12 - skipped - 2020-06-03T19:07:19.919Z
7 - processed - 2020-06-03T19:07:19.669Z - 2020-06-03T19:07:19.921Z
14 - skipped - 2020-06-03T19:07:20.019Z
15 - skipped - 2020-06-03T19:07:20.070Z
11 - processed - 2020-06-03T19:07:19.869Z - 2020-06-03T19:07:20.122Z
13 - processed - 2020-06-03T19:07:19.968Z - 2020-06-03T19:07:20.219Z

where the first part is the index of the upstream element, the second part is the transformation the element's been applied on (either processed when entering the slow component or skipped) and the last part is a timestamp so that we visualise when things are happening.
The 2 first elements entering the stage (0 and 1) are processed by the slow component and a bunch of following elements (2, 3, 4 and 5) are skipping the slow stage until these 2 first elements complete and additional elements can enter the slow stage. And so on.
Gilfoyle


text:
Q: Using n2cms, How do I stop a div from automatically wrapped around my user controls I'm trying to create a part which is essentially a list

    <n2:DroppableZone ID="zoneSlideshowItems" ZoneName="SlideshowItems" AllowExternalManipulation="true" runat="server"></n2:DroppableZone>

I have another part that i drop multiple times onto the above zone:

    <a href="<%= CurrentItem.Link %>">
        <img src="<%=CurrentItem.ImageUrl %>" alt="<%= CurrentItem.Title %>" />

<%= CurrentItem.OverlayHeader %>

<%= CurrentItem.OverlayText %>

However when i look at the page source, its adding a div around each
* element that i drop onto the zone:

 <<<< That Guy!!

Anthony

im trying to tell you something

Does anyone know how to stop that div from being generated?
Cheers!


text:
Q: C# Class Library "Make assembly COM-Visible" grey or not available I want to write a DLL in C# to use in VB6. When I looked it up i found this. Sounds good to me, but i can't check the "Make assembly COM-Visible". I tried different Project types, but the "Assembly Information" button is either not there, or the "Make assembly COM-Visible" is greyed out. Any Ideas?
Im using:

*

*Visual Studio 2019 Community

*.Net Standard 2.0

*.Net Framework 4.8 SDK

A: These really is no magic.  COM-visible is an attribute you can add yourself:
https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.comvisibleattribute?view=netstandard-2.0
Registering your .NET dll can be done yourself as well, you don't need Visual Studio to do that for you:
https://learn.microsoft.com/en-us/dotnet/framework/tools/regasm-exe-assembly-registration-tool
If it is a private dll that doesn't need to be shared, you can use the /codebase option instead of putting it in the GAC.  The /tlb option can be used to generate the type library that the VB6 IDE will understand.


text:
Q: Detecting prohibited words within a string I have a function for checking bad words but it doesn't work how I want it to. For example test was a cuss word then if i said "testing" the function would count it as a cuss word. How would  i fix this so that it doesn't do that.
here is my code:
    function censor($message) {
        $badwords = $this->censor; //array with the cuss words.
        $message = @ereg_replace('[^A-Za-z0-9 ]','',strtolower(' '.$message.' '));
        foreach($badwords as $bad) {
            $bad = trim($bad);
            if(strpos($message.' ', $bad.' ')!==false) {
                if(strlen($bad)>=2) {
                    return true;
                }
            }
        }
    }

A: First, ereg_replace has been DEPRECATED as of PHP 5.3.0.
Now, to your question: you can use \b as a word boundary.

Simply put: \b allows you to perform a "whole words only" search using
  a regular expression in the form of \bword\b.

See this page for more details.

You could even use something like the code below which i copied from Example 2 of PHP's preg_replace documentation:
$string = 'The quickest brown fox jumped over the lazy dog.';
$patterns = array();
$patterns[0] = '/ quick /';
$patterns[1] = '/ brown /';
$patterns[2] = '/ fox /';

echo preg_replace($patterns, ' *** ', $string);

Output: The quickest *** *** jumped over the lazy dog.


text:
Q: Conditional existence of real numbers Are there such numbers $a$ and $b$ that if $a < b$, then $a > b$ ?
Thanks.

A: No.  The relation less than (as opposed to less than or equal to) is defined as strict, so $(a \lt b) \implies \neg (b \lt a)$

A: I don't really think so. The condition $a < b$ implies that $a \ngeq b$ because $<$ is a total order on $\mathbb{R}$. If you're not familiar with orderings, they are just relations that are reflexive, anti-simmetric and transitive (see  Wikipedia. A set is said to be totally ordered if every element of the set can be compared to another with the ordering given.

A: Yes. Take for instance a = 1, b = 0. (Or perhaps this isn't what you meant?)


text:
Q: nginx don't host on root host on root/somename How do I get nginx to ignore requests on http://127.0.0.1/ but hand out from my html directory on http://127.0.0.1/somename this will also need to be the same for the proxy for /data/

I have tried the below and only get a 404.
server {
    listen       80;
    server_name  localhost;

    location / {
        #Do I need something in here regardless?
    }

    location /somename {
        root   ../html;
        index  index.html index.htm;
    }

    #reverse proxy for ie support
    #
    location /somename/data {
        proxy_pass  http://localhost:8080/data/;
        proxy_set_header  host localhost;
    }

    # redirect error pages to the static pages /50x.html /40x.html
    error_page  404              /404.html;
    error_page   500 502 503 504  /50x.html;

    location = /50x.html {
        root   ../html;
    }

    location = /404.html {
        root   ../html;
    }

}

A: location / {
    return 404;
}

location /somename/ {
    alias  ../html/;
    index  index.html index.htm;
}

*

*http://nginx.org/en/docs/http/request_processing.html

*http://nginx.org/r/alias

*http://nginx.org/r/return

*http://nginx.org/r/index

*http://nginx.org/r/location

A: What do you mean by "ignore"? If you access http://127.0.0.1/, what behaviour do you want?
I think it reasonable that you get a 404 if you access a path for which your web server does not have a file to send back to the client.


text:
Q: Excluding all records with associated values There are multiple payment tags in the cnsmr_pymnt_tag table associated with every consumer in the cnsmr table.
If any of the consumer's payments have one of the tag ID's listed below (416,417,2823, etc.) then I don't want the the cnsmr_idntfr_id in the results.
My code below works if none of the consumer's payments have one of the tag_IDs, but if the consumer has a mixture of Tag_ID codes that are on and off my list, then I get incorrect results and the consumer number ends up in my results.
I understand it's doing exactly what I'm telling to but how do I change it so that the consumer number isn't in the results if it's associated with any of the tag_ID values?
SELECT DISTINCT
 cnsmr.cnsmr_idntfr_agncy_id
FROM
 cnsmr_pymnt_jrnl
 INNER JOIN
 cnsmr_pymnt_tag ON cnsmr_pymnt_jrnl.cnsmr_pymnt_jrnl_id = cnsmr_pymnt_tag.cnsmr_pymnt_jrnl_id
 INNER JOIN
 tag ON cnsmr_pymnt_tag.tag_id = tag.tag_id
 INNER JOIN
 cnsmr ON cnsmr_pymnt_jrnl.cnsmr_id = cnsmr.cnsmr_id
WHERE
 cnsmr_pymnt_tag.TAG_ID NOT IN
 (        416  -- VOLUNTARY
         ,417  -- VOLUNTARY
         ,2823 -- VOLUNTARY SPEED PAY
         ,583 -- SPEED PAY
         ,1130  -- VOLUNTARY TVOLCC
         ,581 -- VOLUNTARY LBXVOL TAG
 )

A: Try modifying your code like this
WHERE
 cnsmr_pymnt_tag.TAG_ID NOT IN
 (        416  -- VOLUNTARY
  )
and
 cnsmr_pymnt_tag.TAG_ID NOT IN  (471)

......and so on
Or,you also can try something like below..
;with cte(tag)
as
 (        416  -- VOLUNTARY
         ,417  -- VOLUNTARY
         ,2823 -- VOLUNTARY SPEED PAY
         ,583 -- SPEED PAY
         ,1130  -- VOLUNTARY TVOLCC
         ,581 -- VOLUNTARY LBXVOL TAG
 )
 (your whole query as in question) wq
join
cte c
on c.tag<>wq.tag

A: If I understand your requirement correctly, you are looking for a list of consumer IDs that have absolutely no payment journals with a tag of 416, 417, 581, 583, 1130, 2823. If that is correct, what you probably want is just a simple WHERE NOT EXISTS that will invalidate any consumer ids that have any of those tags on any payment journals
SELECT DISTINCT
C.cnsmr_idntfr_agncy_id
FROM cnsmr AS M
WHERE NOT EXISTS
(
    SELECT 1
    FROM tag AS T
        JOIN cnsmr_pymnt_tag AS CPT
            ON T.tag_id = CPT.tag_id
        JOIN cnsmr_pymnt_jrnl AS CPJ
            ON CPT.cnsmr_pymnt_jrnl_id = CPJ.cnsmr_pymnt_jrnl_id
        JOIN cnsmr AS C
            ON CPJ.cnsmr_id = C.cnsmr_id
    WHERE T.tag_id IN (416,417,581,583,1130,2823)
        AND C.cnsmr_id = M.cnsmr_id
)


text:
Q: Algorithm to Generate All Possible Black and White Pixel Images in 640 x 360 Dimensions? I have very minimal programming experience.
I would like to write a program that will generate and save as a gif image every possible image that can be created using only black and white pixels in 640 by 360 px dimensions.
In other words, each pixel can be either black or white. 640 x 360 = 230,400 pixels. So I believe total of 460,800 images are possible to be generated (230,400 x 2 for black/white).
I would like a program to do this automatically.
Please help!

A:
In other words, each pixel can be either black or white. 640 x 360 =
  230,400 pixels. So I believe total of 460,800 images are possible to
  be generated (230,400 x 2 for black/white).

There is a little flaw in your belief. You are right about the number of pixels: 230,400. Unfortunately, this means there are not 2 * 230,400, but 2 ^ 230,400 possible pictures, which is a number with more than 60,000 digits (longer than the allowed answer size, I am afraid). For comparison a particular number with 45 digits signifies the diameter of the observable universe in centimeters (roughly the width of a pinkie).
In order to understand why your computation of the number of pictures is wrong consider this example: if your pictures contained only three pixels, you could have 8 different pictures (2 ^ 3), rather than 6 (2 * 3). Here are all of them: BBB, BBW, BWB, BWW, WBB, WBW, WWB, WWW. Adding another pixel doubles the size of possible pictures because you can have it white for all the 3-pixel cases, or black for all the 3-pixel cases. Doubling 1 (which is the amount of pictures you can have with 0 pixels) 230,400 times gives you 2 ^ 230,400.
It's great that there is a bounty for the question, but it is rather distracting and counter-productive if it was just as an April's Fool joke.

A: I'm going to go ahead and pinch some code from a related question, just for fun.
from itertools import product
for matrix in product([0, 1], repeat=(math,pow(2,230400)):
    # render and save your .gif

As all the comments have already stated, good luck!
On a more serious note, if you didn't want to be absolutely sure that you had all permutations, you could generate a random 640x360 matrix and store it as an image.
Perform this action say 100k times, and you'll have at least an interesting set of pictures to look at, but it's unfeasible to get every possible permutation.
You could then delete all identical files to reduce the set to just the unique images.

A: First to answer your questions. Yes there will be writings on "some" pictures. Actually ever text written by human which fits in 640x360 pixels will show up. Also every other text (text not yet written or text that never will be written). Also you will see pictures of every human which is, was or will be alive. See Infinite Monkey Theorem for further information.
The code to create your wanted gif is fairly easy. I used Java for this. Note that you need an extra class: AnimatedGifEncoder. The Code is not memory-bound because the AanimatedGifEncoder will write each image to disk as soon it is computed. But make sure that you have enough disk space available.
import java.awt.Color;
import java.awt.image.BufferedImage;

public class BigPicture {
    private final int width;
    private final int height;

    private final int WHITE = Color.WHITE.getRGB();
    private final int BLACK = Color.BLACK.getRGB();

    public BigPicture(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public void process(String outFile) {
        AnimatedGifEncoder gif = new AnimatedGifEncoder();
        gif.setSize(width, height);
        gif.setTransparent(null); // no transparency
        gif.setRepeat(-1); // play only once
        gif.setDelay(0); // 0 ms delay between images,
                         // 'cause ain't nobody got time for that!
        gif.start(outFile);
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);

        // set the image to all white
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                bufferedImage.setRGB(x, y, WHITE);
            }
        }

        // add white image
        gif.addFrame(bufferedImage);

        // add all other combinations
        while (increase(bufferedImage)) {
            gif.addFrame(bufferedImage);
        }

        gif.finish();
    }

    /**
     * @param bufferedImage
     *            the image to increase
     * @return false if last pixel set to black => image is complete black
     */
    private boolean increase(BufferedImage bufferedImage) {
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (bufferedImage.getRGB(x, y) == WHITE) {
                    bufferedImage.setRGB(x, y, BLACK);
                    return true;
                }
                bufferedImage.setRGB(x, y, WHITE);
            }
        }
        return false;
    }

    public static void main(String[] args) {
        new BigPicture(640, 360).process("C:\\temp\\bigpicture.gif");
        System.out.println("finished.");
    }
}

Please be aware that this will take some time. So don't bother waiting and enjoy your life instead! ;)
EDIT: Since my solution is a bit unclear i will explain the algorithm.

*

*I have defined a method called increase. This method takes the BufferedImage and changes the bit pattern of the image so that the next bit pattern appears. The method is just a bit addition. The method will return false if the image encounters the last bit pattern (all pixels are set to black).

*As long as it is possible to increase the bit pattern (i.e. increase() returns true) we will save the image as new frame and increase the image again.

*How the increase() method works: The method runs over the image first in x-direction then in y-direction. I assume that white pixels are 0 and black pixels are 1. So, we want to take the bit pattern of the image and add 1. We inspect the first pixel: if it is white (0) we can add 1 without an overflow so we turn the pixel to black (0 + 1 = 1 => black pixel). After that we return from the method because we want to increase only one position. It returns true because an increase was possible. If we encounter a black pixel we have an overflow (1 + 1 = 2 or in binary 10). So we have to set the current pixel to white and add the 1 to the next pixel. This will continue until we find the first white pixel.

example:
first we create a print method: this method prints the image as binary number. Attention the number is reversed and the most significant bit is the bit on the right side.
public void print(BufferedImage bufferedImage) {
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            if (bufferedImage.getRGB(x, y) == WHITE) {
                System.out.print(0); // white pixel
            } else {
                System.out.print(1); // black pixel
            }
        }
    }
    System.out.println();
}

now we modify our main-while loop:
print(bufferedImage); // this one prints the empty image
while (increase(bufferedImage)) {
    print(bufferedImage);
}

and now set some short example to test:
new BigPicture(1, 5).process("C:\\temp\\bigpicture.gif");

and finally the output:
00000 // 0 this is the first print before the loop -> "white image"
10000 // 1 the first white pixel is set to black
01000 // 2 the first overflow, so the second pixel is set to black "2"
11000 // 3
00100 // 4
10100 // 5
01100
11100
00010 // 8
10010
01010
11010
00110
10110
01110
11110
00001 // 16
10001
01001
11001
00101
10101
01101
11101
00011
10011
01011
11011
00111
10111
01111
11111 // 31 == 2^5 - 1
finished.


text:
Q: win32 : Get the state of an event object I'm creating 3 events with the following function:
HANDLE WINAPI CreateEvent(...);

I'm waiting on all (bWaitAll is set to TRUE) event objects or a timeout with:
DWORD WINAPI WaitForMultipleObjects(...);

The return value is:
WAIT_TIMEOUT

Is there an easy way to check each event to find the one(s) that was(where) not set?
As an example :
HANDLE evt1 = ....
HANDLE evt2 = ....
HANDLE evt3 = ....

HANDLE evts[3] = ....

DWORD ret = ::WaitForMultipleObjects(3, evts, TRUE, 10000);

After 10 sec :

*

*'ret' is WAIT_TIMEOUT.

*evt1 is set

*evt2 is NOT set

*evt3 is set

The return value tells me "The time-out interval elapsed and the conditions specified by the bWaitAll parameter are not satisfied.", but not which one were signaled and which one were not.
Thanks,

A: Yes, after WaitForMultipleObjects() returned call WaitForSingleObject() for each event specifying zero timeout.
It will return WAIT_TIMEOUT for events that are not signalled and WAIT_OBJECT_0 for signalled events. Don't forget to check for WAIT_FAILED.
Surely each event state might have been changed compared to the states they had at the moment WaitFormultipleObjects() returned.

A: OK. Total rewrite after having the question explained to me better in the comments.
So if I'm understanding this right now, you are calling WaitForMultipleObjects with bWaitAll set to true, and when you get WAIT_TIMEOUT back from it, want to figure out which objects are holding up the works.
In that case, I'm with sharptooth, sort of. You can call WaitForSingleObject with a 0 timeout for each object. The problem with doing this is that it has side-effects for some objects. For example, if you do this on a mutex and it succeeds, you not only know it wasn't the culprit, but you now own the mutex. If that isn't what you want, you'll have to know to immediately release it.
Any apporach you take is going to be subject to race conditions. Since you are outside of the "atomic" wait call, you could go through the process and discover that now they are all ready. You could get back a set of ready/unready that isn't what you actually had inside the wait call.
Ick.

A: None of this work, as WaitForSingleObject() will trigger an auto-reset event even when timeout is 0.
(Contrary to what MSDN says).

A: If your call returns WAIT_TIMEOUT it means that NONE of the objects you waited for was signalled..


text:
Q: No data available using React Hook Form and EmailJS I'm trying to use this solution: TypeError: e.preventDefault is not a function on React Hook Form using EmailJs, but I'm getting another error. Even using the same code. Has anything changed lately with EmailJS?

Error: The 3rd parameter is expected to be the HTML form element

Could someone help me, please? This is driving me crazy.
EDIT: This solution is working for me.
sendEmail function:
const sendEmail = (formData, e) => {
  // Send email
  emailjs.sendForm("YOUR_SERVICE_ID", "YOUR_TEMPLATE_ID", e.target, "YOUR_USER_ID")
    .then((result) => {
        console.log(result.text);
    }, (error) => {
        console.log(error.text);
    });
    reset();
};

and my form (using styled-components):
                <Form onSubmit={handleSubmit(sendEmail)}>
                    <FormH1>Register your information</FormH1>
                    <FormLabel>Name</FormLabel>
                    <FormInput
                        {...register("name", {
                        required: true,
                        maxLength: 20,
                        pattern: /^[A-Za-z]+$/i
                    })} type="text" name="name"/>
                        {errors?.name?.type === "required" && <FormError>This field is required</FormError>}
                        {errors?.name?.type === "maxLength" && <FormError>First name cannot exceed 20 characters</FormError>}
                        {errors?.name?.type === "pattern" && <FormError>Alphabetical characters only</FormError>}
                    <FormLabel>Email</FormLabel>
                    <FormInput
                        {...register("email", {
                        required: true,
                        pattern: /\S+@\S+\.\S+/
                    })} type="email" name="email"/>
                        {errors?.email?.type === "required" && <FormError>This field is required</FormError>}
                        {errors?.email?.type === "pattern" && <FormError>Entered value does not match email format</FormError>}
                    <FormLabel>ORCID</FormLabel>
                    <FormInput {...register("orcid", {
                        required: true,
                        minLength: 16,
                        maxLength: 16,
                        pattern: /^[0-9\b]+$/
                    })} type="number" name="orcid"/>
                        {errors?.orcid?.type === "required" && <FormError>This field is required</FormError>}
                        {errors?.orcid?.type === "minLength" && <FormError>It must be a number of 16 digits</FormError> }
                        {errors?.orcid?.type === "maxLength" && <FormError>It must be a number of 16 digits</FormError> }
                        {errors?.orcid?.type === "pattern" && <FormError>Numerical characters only</FormError> }
                    <FormButton type="submit"/>
                </Form>

A: Since you have not specified the type of forms you are using, try this method using plain html forms.
The name tag you give to these input fields are extremely important as they are extracted as same as their name is and if your names in the EmailJS template does not match with the names, it will not work.
The submit method:
const sendEmail = (e) => {

  e.preventDefault(); //prevent default behaviour

  emailjs
  .sendForm(
    'your-emailjs-service-key',
    'your-emailjs-template-key',
    e.target,
    'your-emailjs-user-id'
  )
  .then(
    (result) => {
      console.log(result.text);
      });
    },
    (error) => {
      console.log(error)
      });
    }
  );

  e.target.reset(); //reset explicitly because default is prevented

};

The form:
<form onSubmit={sendEmail}>

   <input required type="text" placeholder="Name" name="name" />
   <input required type="email" placeholder="Email" name="email" />
   <input required type="number"  placeholder="ORCID" name="orcid" />

   <button>Submit</button>
 </form>


text:
Q: PIL- animating GIFs, but some frames are black I've been trying to animate images inside a chat program automatically using PIL and Tkinter in Python. Sometimes they work, but most of the time they don't. I will provide images that work and ones that don't
Basically, I am animating the images by calling ImageTk.PhotoImage on each image in the GIF sequence, and the animations are run by updating the label widgets with a root.after call. The animation works pretty smoothly
My problem is, though, that most animated GIFs I try running are corrupted, or something. usually the first frame is fine, but the rest are either completely black or full of artifacts.
These are the images:
This one is one of the few that works:
http://fc02.deviantart.net/fs42/f/2009/061/d/8/d856ba6223c66ce347c6c814f67d307b.gif
These ones flash black:
http://fc02.deviantart.net/fs70/f/2010/007/c/3/_mekolai__by_Pyritie.gif
http://e.deviantart.com/emoticons/s/shakefist.gif
EDIT: I see no one wants to help me. maybe it's because it's tl;dr. I'll try shortening it
some code:
def ExtHandler(self, widget, url): # sorts out what to do with each file extensions
    name = url.split('/')[-1].split('?')[0]
    path = './Storage/Temp/Images/'+name
    try:
        if name.endswith('.gif'):
            img = Image.open(path)
            animation = []
            x = 0
            print name
            while True:
                try:
                    img.seek(x)

                    newpath = './Storage/Temp/Images/{0}__{1}.png'.format(x, name.split('.', 1)[0])
                    img.save(newpath, transparency = img.info['transparency'], format='PNG')

                    newimg = Image.open(path)
                    newimg.load()
                    newimg = newimg.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)

                    dur = img.info['duration']
                    if dur < 50: dur = 50
                    newimg = Image.open(newpath)

                    animation.append((PhotoImage2(newimg), dur))
                    x += 1
                except EOFError:
                    break #no more images in the animation!
                except Exception as e:
                    print traceback.format_exc()
                    break
            if len(animation) > 1:
                self.animations[name] = animation

        elif name.endswith('.jpg'):
            img = Image.open(path)
            img = img.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)

        elif name.endswith('.png'):
            img = Image.open(path)
            img.load()
            try:
                alpha = img.split()[3]
                img = img.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)
                mask = Image.eval(alpha, lambda a: 255 if a <=128 else 0)
                img.paste(255, mask)
            except:
                img = img.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)

        height, width = img.size[0], img.size[1]
        if width > 100 or height > 100:
            img = maxSize(img, (100, 100), Image.ANTIALIAS) # resize thumbnails

        self.images[name] = PhotoImage2(img)
        if name in self.animations:
            self.animation(name)
        else:
            self.update_frames(name, self.images[name])
    except:
        print name
        traceback.print_exc()

def animation(self, name):
    if name not in self.animations:
        return
    x = self.animations[name].pop(0)
    self.animations[name].append(x)
    img, time = x

    self.images[name] = img
    self.update_frames(name, self.images[name])
    self.root.after(time, lambda: self.animation(name))

A: Interesting.. I see them all animated.
I've embedded your links in this answer, so that people don't have to click your links to see the animations.

Note that I'm using chrome as a browser. I'll save this message and see how it looks in Internet explorer and FireFox, and report the results.
...
update
Ok, here are the results:
I'm on Windows XP.

*

*Works with IE8

*Works with Chrome 10.0.648.205

*Works with Chrome 14.0.810.0

*Works with FireFox 5.0

So, I cannot reproduce your problem here. I think it's fairly safe to assume that these animations will work as expected in people's browsers.
Maybe you should add some more information about how you view the animations.
From a technical point of view I don't see a problem, but the animations look sort of cheap, so I'd think twice before adding them to a site, but that's a matter of taste.
update 2
Ah, I reread your question. You're not using a browser, but you're creating an application. I'm sure that the problem lies in the libraries that you use.
Maybe you can open the gifs in something like Gif animation workshop or some program like that, to see the difference.. maybe you can re-save them in such a way that they all work?
That's about all I can say to help you for now I'm afraid.

A: This is my working version (for converting the gifs to a series of pngs):
import traceback
import Image

class Test:

    def __init__(self):
        self.ExtHandler("", "http://fc02.deviantart.net/fs42/f/2009/061/d/8/d856ba6223c66ce347c6c814f67d307b.gif")
        self.ExtHandler("", "http://fc02.deviantart.net/fs70/f/2010/007/c/3/_mekolai__by_Pyritie.gif")
        self.ExtHandler("", "http://e.deviantart.com/emoticons/s/shakefist.gif")

    def ExtHandler(self, widget, url): # sorts out what to do with each file extensions
        name = url.split('/')[-1].split('?')[0]
        path = 'C:\\Temp\\'+name
        try:
            if name.endswith('.gif'):
                img = Image.open(path)
                print name
                while True:
                    try:
                        x = img.tell() + 1
                        img.seek(x)

                        newpath = 'C:\\Temp\\{1}_{0}.png'.format(x, name.split('.', 1)[0])
                        img.save(newpath, transparency = img.info['transparency'])
                    except EOFError:
                        break #no more images in the animation!
                    except Exception as e:
                        print traceback.format_exc()
                        break

            elif name.endswith('.jpg'):
                img = Image.open(path)
                img = img.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)

            elif name.endswith('.png'):
                img = Image.open(path)
                img.load()
                try:
                    alpha = img.split()[3]
                    img = img.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)
                    mask = Image.eval(alpha, lambda a: 255 if a <=128 else 0)
                    img.paste(255, mask)
                except:
                    img = img.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)
        except:
            print name
            traceback.print_exc()

Test()

I think the solution is
a) seeking with img.tell() + 1
b) saving without the format parameter
In your actual code you probably don't have to cache the gif frames as pngs. Just seek with img.tell() + 1 :)


text:
Q: Canvas, prevent to lose the progress on resizing I'm working on a simple app just for practice.
Link to the project, you can test it and you will find the soource in the GitHub's link.
It's a canvas app, here is my problem:
Every time that I resize the window the canvas will resize, but at the same time it will lose all the progress that the user did on it.
I'm looking a way to prevent the losing of the user's work, or a way to save the work and than re-draw it in the new canvas.
Any ideas?
Thank you all. Kisses.

A: Keep the canvas's width/height attributes the same, but change its size using CSS.

A: Solution, even if not perfect
This solution is not totally perfect, but it works mostly the times.
For a better solution you should keep track of the path every time there is a mouse event, saving it in an array an than, you will load it on the new canvas every time the window is resized.
HTML
<canvas id="mainCanvas" width="900" height="500"></canvas>

JavaScript
var $canvas = $("#mainCanvas"); //jquery mainCanvas
var context = $canvas[0].getContext("2d"); //jQuery Context

//function to cloneCanvas
function cloneCanvas(oldCanvas) {
  //create a new canvas
  var newCanvas = document.createElement('canvas');
  var contextCopy = newCanvas.getContext('2d');
  //set dimensions
  newCanvas.width = oldCanvas.width;
  newCanvas.height = oldCanvas.height;
  //apply the old canvas to the new one
  contextCopy.drawImage(oldCanvas, 0, 0);
  //return the new canvas
  return newCanvas;
}

//Function to resizes canvas on window resizing:
  function respondCanvas(){
  //creating a copy of the main canvas
  var copyMainCanvas = cloneCanvas(document.getElementById("mainCanvas"));
  //naming the parent of the mainCanvas
  var $container = $($canvas.parent());
  //Changnig the size of the canvas
  $canvas.prop('width', $container.width());
  $canvas.prop('height', $container.width() / 2);
  //redrawing the canvas resized with the copy just made
  context.drawImage(copyMainCanvas, 0, 0);
}


text:
Q: Inserting into 2 tables with foreign key in them into SQL Server with C# I'd like to know the query of C# where I want to insert 2 tables with foreign key in them. The current code that I use:
SqlConnection con = new SqlConnection(WindowsFormsApp1.Properties.Resources.connection.ToString());
con.Open();

SqlCommand com = new SqlCommand("Begin TRANSACTION INSERT INTO daftar_buku values('"+Code.Text+"','"+Judul.Text+"','"+Kategori.Text+"','"+Nomor.Text+"') insert into stock_buku(nama_buku, stok_buku) values ((select judul_buku from daftar_buku where judul_buku ='"+Judul.Text+"'),'"+Stock.Text+"') COMMIT ",con);

SqlDataAdapter da = new SqlDataAdapter("select judul_buku from daftar_buku where judul_buku = '"+Judul.Text+"'",con);

DataTable dt = new DataTable();
da.Fill(dt);

if (dt.Rows.ToString() == Judul.Text)
{
    MessageBox.Show("Data Added!");
    this.Hide();
    Refresh();
}
else
{
    MessageBox.Show("Failed To add Book!","Information");
}

But that code does not work...
Please help me


text:
Q: Backbone and Smart Time ago are not functioning together, any ideas? I am using backbone and:
https://github.com/pragmaticly/smart-time-ago
When I load the page there is nothing displayed where the time ago is supposed to be(but backbone is working).
Here is my backbone view:
class Voice.Views.PostsIndex extends Backbone.View

        template: JST['posts/index']

        initialize: ->
                @collection.on('reset', @render, this)

        render: ->
                $(@el).html(@template(posts: @collection)).timeago
                this

templates/posts/index.jst.eco
<% for post in @posts.models: %>

                <% if post.get('content').length > 140: %>
                        <%=post.get('content').substring(0, 140)+"\t\t"%>
                        ...<a href="show/<%= post.get('id') %>">see more
                <% else: %>
                        <%= post.get('content') %>
                <% end %>

        <%= post.get('agrees') %>
        <%= post.get('disagrees') %>
        0

            <time class="timeago" datetime="<%=post.get('created_at')%>">
            </time>

application.js
//= require jquery
//= require jquery_ujs
//= require timeago
//= require underscore
//= require backbone
//= require voice
//= require bootstrap.min
//= require_tree ../templates
//= require_tree ./models
//= require_tree ./collections
//= require_tree ./views
//= require_tree ./routers
//= require_tree .

Is there anyway to get this to work? Thanks in advance

A: This is not a function call:
$(@el).html(@template(posts: @collection)).timeago

That just looks up the timeago function on a jQuery object and, well, does nothing with it. You need to add parentheses (or an argument) to call timeago:
$(@el).html(@template(posts: @collection)).timeago()
# you need these ---------------------------------^^

If you were supplying some arguments, you wouldn't need the parentheses:
$(@el).html(@template(posts: @collection)).timeago selector: '.pancakes'

The presence of arguments is enough to tell CoffeeScript that you want to execute the function rather than get a reference to it.


text:
Q: Construct array by sampling over every n'th element along last axis Let a be some (not necessarily one-dimensional) NumPy array with n * m elements along its last axis. I wish to "split" this array along its last axis so that I take every n'th element starting from 0 up until n.
To be explicit let a have shape (k, n * m) then I wish to construct the array of shape (n, k, m)
np.array([a[:, i::n] for i in range(n)])

my problem is that though this indeed return the array that I seek, I still feel that there might be a more efficient and neat NumPy routine for this.
Cheers!

A: This is hard to write a faster Numpy implementation. One efficient solution is to use Numba so to speed this up. That being said, the memory access pattern can be the main reason why the code is slow on relatively large matrices. As a result, one need to care about the iteration order so the accesses can be relatively cache-friendly. Moreover, for large arrays, it can be a good idea to use multiple threads so to better mitigate the overhead coming from the relatively-high memory latency (due to the memory access pattern). Here is an implementation:
import numba as nb

# The first call is slower due to the build.
# Please consider specifying the signature of the function (ie. input types)
# to precompile the function ahead of time.
@nb.njit # Use nb.njit(parallel=True) for the parallel version
def compute(arr, n):
    k, m = arr.shape[0], arr.shape[1] // n
    assert arr.shape[1] == n * m

    out = np.empty((n, k, m), dtype=arr.dtype)

    # Use nb.prange for the parallel version
    for i2 in range(k):
        for i1 in range(n):
            outView = out[i1, i2]
            inView = a[i2]
            cur = i1
            for i3 in range(m):
                outView[i3] = inView[cur]
                cur += n

    return out

Here is the results on my machine with a i5-9600KF processor (6-cores) for k=37, n=42, m=53 and a.dtype=np.int32:
John Zwinck's solution:    986.1 µs
Initial implementation:     91.7 µs
Sequential Numba:           62.9 µs
Parallel Numba:             14.7 µs
Optimal lower-bound:        ~7.0 µs

A: I think this does what you want, without loops.  I tested for 2D inputs, it may need some adjustments for more dimensions.
indexes = np.arange(0, a.size*n, n) + np.repeat(np.arange(n), a.size/n)
np.take(a, indexes, mode='wrap').reshape(n, a.shape[0], -1)

In my testing it is a bit slower than your original list solution.

A: If I'm not mistaken this does what you expect, and fast:
a.reshape(k, m, n).swapaxes(1, 2).swapaxes(0, 1)

Example:
import numpy as np
k=5; n=3; m=4
a = np.arange(k*n*m).reshape(k, n*m)
a.reshape(k, m, n).swapaxes(1, 2).swapaxes(0, 1)
"""
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23],
       [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35],
       [36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47],
       [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]])

is transformed into:

array([[[ 0,  3,  6,  9],
        [12, 15, 18, 21],
        [24, 27, 30, 33],
        [36, 39, 42, 45],
        [48, 51, 54, 57]],

       [[ 1,  4,  7, 10],
        [13, 16, 19, 22],
        [25, 28, 31, 34],
        [37, 40, 43, 46],
        [49, 52, 55, 58]],

       [[ 2,  5,  8, 11],
        [14, 17, 20, 23],
        [26, 29, 32, 35],
        [38, 41, 44, 47],
        [50, 53, 56, 59]]])
"""

Timing:
from time import time
k=37; n=42; m=53
a = np.arange(k*n*m).reshape(k, n*m)

start = time()
for _ in range(1_000_000):
    res = a.reshape(k, m, n).swapaxes(1, 2).swapaxes(0,1)
time() - start

# 0.95 s per 1 mil repetitions


text:
Q: UIPopoverController with navigation bar inconsistent on device and simulator I have a simple popover for a UINavigationController that is anchored on the root views right bar button item. On the iPhone simulator (I tried it on various devices) the navigation bar of the popover aligns nicely with the navigation bar of the root view. I assume this is taken care of by UIKit. Here is a screenshot of the simulator.

However on my physical device there is a slight offset. This is a screenshot on my iPhone 6 physical device. It's weird because there's no offset for the iPhone 6 simulation. Notice they bottoms of the navigation bars are not aligned.

I couldn't find any stack overflow questions addressing this and I'm not sure how to fix it since all we're "supposed" to do is specify the popover anchor (as the plus button) and let UIKit take care of the rest. Is there any way to fix this programmatically? I'm not using storyboards or xibs. I also have touch assist enabled on my physical device.


text:
Q: How do I close a single tab in a Chrome browser? I am starting a PDF. It is being opened in a Chrome tab.
According to Jimis answer in my other question, the following happens:
The Process object that opened the PDF doesn't exist anymore after the main Chrome Process presents the PDF content in a tabbed Window. Find the Chrome Process and check the current title of its Window.

Now I want to close this PDF again.
I go through all windows to find the name of the PDF.
I find it by using the PDF's name and adding " - Google Chrome".
The following window is found:
"test.pdf - Google Chrome"

However, when I close this window, the entire browser window is closed, not only the one tab.
Does anybody know why and how to avoid that?


text:
Q: Callback works multithread but not multiprocess I have a tinker IMU and I'm using their library which is utilizing a callback to output data. I have implemented a multithread approach which works fine but now I want to make it multiprocess instead for better concurrency.  The multiprocess starts the startIMUData function fine but it won't call the myIMUCallback.
def myIMUCallback():
    print("callback called!")

# Function to start recording IMU dimport serialata via callback function above
def startIMUData(q):
    print("Starting IMU!")

    HOST = "localhost"
    PORT = 4223
    UID = "6Dcx3Y" # Change XXYYZZ to the UID of your IMU Brick 2.0

    ipcon = IPConnection() # Create IP connection
    imu = BrickIMUV2(UID, ipcon) # Create device object

    ipcon.connect(HOST, PORT)

    # myIMUCallback is NOT being called in process version
    imu.register_callback(imu.CALLBACK_ALL_DATA, myIMUCallback)

    imu.set_all_data_period(100)

if __name__ == "__main__":

    q = Queue()
    # This works
    threadIMU = Thread(target = startIMUData, args = (q, ))
    threadIMU.start()
    threadIMU.join()

    #This doesn't work, calls startIMUData fine but ignores myIMUCallback
    processIMU = multiprocessing.Process(target=startIMUData, args=(q, ))
    processIMU.start()
    processIMU.join()


text:
Q: Prove $F(F^{-1}(B)) = B$ for onto function Suppose that $f:X \to Y$ is an onto function. Prove that for all subsets $B$ subset of $Y$, $f(f^{-1}(B)) = B$. I don't know how to do this if the function is not also one to one, which it is not. Any help proving this would be greatly appreciated.

A: *

*$\exists$ is the symbol for "there exists."

*$\wedge$ is the symbol for "and."

*$f:X\twoheadrightarrow Y$ is notation for "$f$ is a surjective (onto) function from $X$ to $Y$."

*$\mathcal{P}(Y)$ is notation for "powerset of $Y$" or "the set of all subsets of $Y$."

*

*"$\subseteq$" becomes "$=$" for onto functions.

A: Note that:

*

*For any $y\in f(f^{-1}(B)$, there exists $x \in f^{-1}(B)$ satisfying $y=f(x)$. Clearly $y=f(x) \in B$.

*For any $y\in B$, since $f(x)$ is an onto function, there is $x\in X$ satisfying that $f(x)=y$, i.e.,$x\in f^{-1}(y)$. So $y=f(x)\subset f(f^{-1}(y)) \subset f(f^{-1}(B)).$

A: Given $f : X \to Y$, and $\forall y \in Y \exists x \in X (f(x) = y)$.
Want to show that $\forall B \subset Y, f(f^{-1}(B)) = B$
We know that $f^{-1}(B) = \{ b : f(b) \in B \}$. If this set is never empty, then we have our result. The set is never empty by our second assumption.

A: First, $f^{-1}(y) = \lbrace x \in X : f(x) = y)\rbrace $. If $y \in B$, so exist $x \in X$ that $f(x) = y$ (f is onto), then $f(f^{-1}(y)) \in B$, by definition, so $f(f^{-1}(y)) \subset B$. Now, $y \in  f(f^{-1}(B))$, how f is onto exist $x \in f^{-1}(B)$, such that $f(x) = y$, then $y \in B$, so $f(f^{-1}(B)) \subset B$.


text:
Q: Clonezilla/DRBL and UEFI I have been unable to PXE boot into Clonezilla/DRBL while in UEFI mode on a HP Notebook 15-ac180ca. While in Legacy mode I can boot into Clonezilla/DRBL (as long as I manually press the F12 (network boot) button. I, am, however, trying to do the network boot with UEFI enabled. Here is what I have done so far:

*

*Installed Ubuntu 16.10 on the imaging server (we do not want to use a live CD)

*As I only have one network card I removed network manager set up an virtual connection as eno1:0

*Added "deb http://free.nchc.org.tw/drbl-core drbl stable" to the repository

*Installed drbl/clonezilla using apt

*I ran drblsrv -i and drblpush -i (for some reason each time I run this it creates a new user account on the imaging server with an account name which is a combination of the prefix name I specified and an ip address. If anyone knows why please let me know).

*I ran dcs and started clonezilla

On the client, I boot up the machine. It initially connects over PXE boot. It says it successfully downloaded the NBP file. But then goes right into booting the OS on the client instead.
I read somewhere that I needed to modify the PATH in /tftpboot/nbi_img/pxelinux.cfg/default from bios/ to efi64/ I have done this, but it still does not seem to work.
What else do I need to do to get this to work under UEFI mode?
Additional Info:
This is what I see before it tries IPv6 and then proceeds to load the client OS:
>>Start PXE over IPv4, Press[ESC] to EXIT...
  Station IP address is 192.168.100.14

  Server IP address is 192.168.100.200
  NBP filename is bootx64.efi
  NBP filesize is 1019904 Bytes
 Downloading NBP file...

 Succeed to download NBP file


text:
Q: Закрывая доступ через htaccess, можно как то получить доступ по другому протоколу? Сделал я папку Cache, где хранятся кешированые файлы (с конфигамии приватными и прочими кешироваными файлми), закрыл доступ через .htaccess в этой папке
deny from all

Все работает, доступа нет к этой папке и вложенным через адресную строку.
Но вот вопрос, можно как то обойти это, и получить доступ к этим файлам еслии знать прямой путь, не через адресную строку?...


text:
Q: How to force quit Applescript app from terminal? I wrote an applescript that turns on my lights. I exported it as an application with the name "LightsOn", and it appears with that name in activity monitor.

Under certain circumstances, this app gets stuck. I can force quit it from Activity Monitor, but I want to be able to do so from a script. killall LightsOn doesn't work; I'm told that no matching processes belonging to you were found.
How can properly force quit this app from the terminal? Or, how can I discover the appropriate name for killall?

A: Try this:
ps auxwww | fgrep -v fgrep | fgrep -i LightsOn
That should show you the matching process information.
You can also try pkill which should work like this:
pgrep -fl LightsOn
If that shows you the PID, then you can move on to pkill:
pkill -9 -f LightsOn
When you run pkill -9, you're not telling the application to terminate itself, instead you're telling the OS to stop running the program, no matter what the program is doing.
When app gets stuck sending the kill without specifying the signal #, it will automatically assign to it the signal <15>, which means asking the app to terminate it self, it can not do that while stuck.

A: The reason killall LightsOn doesn't work is because all running AppleScript application's process name is applet. For example, the executable path is:
../LightsOn.app/Contents/MacOS/applet

In general and assuming the process(es) is(are) not hung, one could use killall applet however that will terminate all running AppleScript applications, and of course that may not be desirable.
When a process is hung, you'll need to use a KILL signal, e.g.:
killall -KILL applet

However, pkill is the way to go to easily target a specific AppleScript application and because it's hung... use a KILL signal, e.g.:
pkill -9 -f LightsOn

Or:
pkill -KILL -f LightsOn

Note in this instance, -9 is just another way of saying -KILL.
Now with pkill and using the -f option, one can use more of the full argument list, e.g.:
pkill -9 -f /Applications/LightsOn.app/Contents/MacOS/applet

Then there's no ambiguity as to which applet process one is targeting. One can use as much of the full argument list as one feels is necessary to target the correct process.
For example, pkill -9 -f LightsOn will terminate an AppleScript application named NoLightsOn, so always use enough of the full argument list to terminate the correct process.

For reference:
From the pkill man page:

 -f          Match against full argument lists.  The default is to match
             against process names.

From the killall man page:

 Some of the more commonly used signals:

 1       HUP (hang up)
 2       INT (interrupt)
 3       QUIT (quit)
 6       ABRT (abort)
 9       KILL (non-catchable, non-ignorable kill)
 14      ALRM (alarm clock)
 15      TERM (software termination signal)

Note that this is just a partial signal list and is used with many of the different utilities that can terminate a process. See the various manual pages of the utilities used for additional information.


text:
Q: Node.js socket.send( ) functions failing to complete before exit In some Node.js scripts that I have written, I notice that even if the last line is a synchronous call, sometimes it doesn't complete before Node.js exits.
I have never seen a console.log statement fail to run/complete before exiting, but I have seen some other statements fail to complete before exiting, and I believe they are all synchronous. I could see why the callback of an async function would fail to fire of course in this case.
The code in question is a ZeroMQ .send() call like so:
   var zmq = require('zmq');
   var pub = zmq.socket('pub');

   pub.bindSync('tcp://127.0.0.1:5555');

    setInterval(function(){
        pub.send('polyglot');
    },500);

The above code works as expected...but if I remove setInterval() and just call it like this:
   var zmq = require('zmq');
   var pub = zmq.socket('pub');

    pub.bindSync('tcp://127.0.0.1:5555');

    pub.send('polyglot');  //this message does not get delivered before exit
    process.exit(0);

...Then the message will not get delivered - the program will apparently exit before the pub.send() call completes.
What is the best way to ensure a statement completes before exiting in Node.js ? Shutdown hooks would work here, but I am afraid that would just be masking the problem since you can't put everything that you need to ensure runs in a shutdown hook.
This problem can also be demonstrated this way:
 if (typeof messageHandler[nameOfHandlerFunction] == 'function') {
          reply.send('Success');
          messageHandler[nameOfHandlerFunction](null, args);
         } else {
         reply.send('Failure'); //***this call might not complete before the error is thrown below.***
         throw new Error('SmartConnect error: no handler for ZMQ message sent from Redis CSV uploader.');
     }

I believe this is a legit/serious problem because a lot of programs just need to publish messages and then die, but how can we effectively ensure all messages get sent (though not necessarily received)?
EDIT:
One (potential) way to fix this is to do:
socket.send('xyz');
socket.close(); // supposedly this will block until the above message is sent
process.exit(0);

A: Diving into zeromq.node, you can see what Socket.send just pushes your data to _outgoing:
this._outgoing.push([msg, flags]);

... and then calls _flush iff zmq.ZMQ_SNDMORE is unset:
this._flush();

Looks like _flush is actually doing the socket write. If _flush() fails, it emits an error.
Edit:
I'm guessing calling pub.unbind() before exiting, will force the _flush() to be called:
pub.unbind('tcp://127.0.0.1:5555', function(err) {
  if (err) console.log(err);
  process.exit(0); // Probably not even needed
});

A: I think the simple answer is the the socket.send() method is in fact asynchronous and that is why we see the behavior I described in the OP.
The question then is - why does socket.send() have to be asynchronous - could there not be a blocking/synchronous version that we could use instead for the purpose intended in the OP? Could we please have socket.sendSync()?


text:
Q: What's the practical way of serializing an instance of subclass by using DataContractSerializer? What's the practical way of serializing an instance of subclass by using DataContractSerializer?
For example, here are the data types:
 [DataContract]
    public class Car
    {
        public Car()
        {
            Wheels = new Collection<Wheel>();
        }

        [DataMember]
        public Collection<Wheel> Wheels { get; set; }
    }

    [DataContract]
    public abstract class Wheel
    {
        [DataMember]
        public string Name { get; set; }
    }

    [DataContract]
    public class MichelinWheel : Wheel
    {
        [DataMember]
        public string Wheel1Test { get; set; }
    }

    [DataContract]
    public class BridgeStoneWheel : Wheel
    {
        [DataMember]
        public string Wheel2Test { get; set; }
    }

Then here is the code that creates a car with two differen wheels:
    Car car = new Car();

    MichelinWheel w1 = new MichelinWheel { Name = "o1", Wheel1Test = "o1 test" };
    BridgeStoneWheel w2 = new BridgeStoneWheel { Name = "o2", Wheel2Test = "o2 test" };

    car.Wheels.Add(w1);
    car.Wheels.Add(w2);

Now if I try to serialize the car by using DataContractSerializer, I will get an exception that says MichelinWheel is not expected. And I have to modify the Wheel class like this to make it work:
 [DataContract]
    [KnownType(typeof(MichelinWheel))]
    [KnownType(typeof(BridgeStoneWheel))]
    public abstract class Wheel
    {
        [DataMember]
        public string Name { get; set; }
    }

But this approach is not practical, because I am not able to list all kinds of wheels before they are created. And changing the Wheel class every time after a new brand of wheel is created is also not practical, because they might by created in third-party code.
So, what is the practical approach of serializing an instance of a subclass when using DataContractSerializer?
Thanks

A: Check this article using DataContractResolver from WCF 4. You can also use KnownTypeAttribute with passing name of a method that will use reflection to get all types. Anyway service requires that all types are known before it starts.

A: There are several ways to make known types available to the service.
The simplest you have outlined above, but obviously this requires you to recompile when new types are added, and depending on your configuration can make it awkward to avoid circular dependencies.
You can also configure the KnownTypes:

*

*through the service configuration file (service restart only required),

*add them as service known types provided through a static method on the service interface which you could get through reflection as Ladislav Mrnka has indicated (you could probably reflect over all loaded assemblies and return all types that have the DataContact attribute on them as known types, but I couldn't find an example of that.)

*implement your own way of getting them (perhaps through some bespoke configuration elements in the config file or just through a text file)


text:
Q: When is temporary lifetime extension useful in modern C++? In C++ you can bind return value of a function (which return value, not reference) to const reference and code will still be valid because lifetime of this temporary will be prolonged till the end of scope. For example
std::string get_string() {
    return "abc";
}

void f() {
    const std::string& str = get_string();
    std::cout << str; // valid, str is not dangling reference.
}

My question is, when is it useful, e.g. when is code like
A get_a();
const A& a = get_a();

better than the code
A get_a();
A a = get_a();

and in what way (e.g. faster, smaller binary size, etc)? What should be the implementations of A, get_a and code after calling get_a?
I've tested several cases by hand and in each case it seems to have the same number of copies and moves.
Let's restrict this question to current C++ standard, modern versions of compilers and builds with optimisation enabled (O2, O3 or equivalents for other compilers)

A: Deliberate lifetime extension of prvalues into named stack variables like this is not useful if you know exactly what's going on. Which means it is useful if you don't know exactly what's going on.
Say, you're in a template function. And the user is supposed to give you some object that has a get member function that returns some type that fits some expected behavior. Question: does get return a reference or a prvalue?
Answer: you don't care. It doesn't matter if it returns a prvalue or a reference; what matters is that what it returns can be manipulated in the fashion you expect. So you might expect obj.get() = 10; to work, for example.
Maybe get returns a reference to an object. Or maybe it returns a prvalue that is a proxy object that acts like a reference. In the above case, maybe it has an operator= overload, so that you can assign to it. You the user don't care.
So, what happens if you want to store what get returns for a (short) period of time? Well, you don't want to do auto x = obj.get();; if it returned an actual reference, you would get a copy of the reference, which is probably not what you wanted. So you do auto &&x = obj.get();. Lifetime extension allows this to work just as well with proxy prvalue objects as with actual references.


text:
Q: How to access servlet's method variable inside inner class I want to access a variable in my inner class which is declared in my base class method. My base class is a servlet, so I cannot declare this variable as a global variable.
The following code will give you an idea. I want to access variable sort in my inner class which is declared in my base class servlet method
public class AccessPointsListServlet extends Servlet  {

    protected void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String sort = null;
        sort = request.getParameter("Sort");

    }

    private class InnerClass {

        public int evaulate(String first){
            if (sort.equalsIgnoreCase("url")) {
            // some code
            }
        }
    }

}

Please help

A: i think this is what you are looking for.
public class AccessPointsListServlet extends HttpServlet //instead of Servlet
{
    String sort=null;
    protected void execute(HttpServletRequest request, HttpServletResponse response) throws   Exception
    {
        sort=request.getParameter("Sort");
    }
    private class InnerClass
    {
        public int evaulate(String first)
        {
            if (sort.equalsIgnoreCase("url"))
            {
                // some code
            }
            //return int value here
        }
    }
}


text:
Q: GetText() for a chipgroup (entry) I'm quite new in java/android and i need for a project to implement chip (entry). I followed a tutorial and the chip works. what i made
XML
<Button
    android:id="@+id/email_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="buttonClick"
    android:text="Ajouter"
    android:textSize="10sp"
    app:layout_constraintBottom_toTopOf="@+id/chip_group"
    app:layout_constraintLeft_toRightOf="@+id/fields_2_form"
    app:layout_constraintTop_toBottomOf="@+id/title_field_3">

</Button>
<com.google.android.material.chip.ChipGroup
    android:id="@+id/chip_group"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    app:layout_constraintTop_toBottomOf="@+id/fields_2_form">

</com.google.android.material.chip.ChipGroup>

Activity
  public void buttonClick(View view) {
    final EditText fieldForm2 = findViewById(R.id.fields_2_form);
    final ChipGroup chipGroup = findViewById(R.id.chip_group);
    final Button emailButton = findViewById(R.id.email_button);

    final Chip chip = new Chip(this);
    ChipDrawable drawable = ChipDrawable
    .createFromAttributes(this, null, 0, R.style.Widget_MaterialComponents_Chip_Entry);
    chip.setChipDrawable(drawable);
    chip.setCheckable(false);
    chip.setClickable(false);
    chip.setChipIconResource(R.drawable.ic_fingerprint_black_24dp);
    chip.setIconStartPadding(3f);
    chip.setPadding(60, 10, 60, 10);
    chip.setText(fieldForm2.getText().toString());

    // remove chip on click on the -
    chip.setOnCloseIconClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            chipGroup.removeView(chip);
        }
    });
    if (!EmailValid(fieldForm2.getText().toString())) {
        Toast.makeText(getApplicationContext(),
                "Veuillez rentrer un email valide",
                Toast.LENGTH_LONG).show();
        fieldForm2.setText("");
    } else {

        chipGroup.addView(chip);
        fieldForm2.setText("");
    }
}

Well but my problem is when i need to get all the typed emails from the chip for another activity.
I tried to do it in this method :
public Intent getFormInfos() {

    TextView mEditTextHour = findViewById(R.id.fields_1_form);
    final Spinner spin = (Spinner) findViewById(R.id.Spinner);
    final ChipGroup chipGroup = findViewById(R.id.chip_group);

    //FIXME
    String chiptext = chipGroup.INEEDTOGETCHIPTEXTHERE();

    String myEditedText1 = mEditTextHour.getText().toString();
    String spinnerText = spin.getSelectedItem().toString();

    Intent intent = new Intent(this, ActivityListMareu.class);
    ApiService.getmReunions().add(new Reunion(myEditedText1, spinnerText, chiptext));

    return intent;
}

I need to do something like chipgroup.getText() but it doesn't work i tried some stuff but i'm really confused with chip and actually i've no idea how to make it.
Does someone have an idea for this?
(sorry for my bad english)

A: Using this you can get all the text set over all Chip in that ChipGroup.
        ArrayList<String> emails = new ArrayList<>();

        for (int i = 0; i < chipGroup.getChildCount(); i++) {
            String email = ((Chip) chipGroup.getChildAt(i)).getText().toString();
            emails.add(email);
        }

In your case if you have only one chip in chipGroup you can directly :
        if (chipGroup.getChildCount() > 0) {
            CharSequence yourText = ((Chip) chipGroup.getChildAt(0)).getText();
        }

A: This is in Kotlin but you can essentially do a transform on the getChildren() just like any collection/sequence:
val emails = chipGroup.children.map {
  (it as Chip).text.toString()
}.toList()


text:
Q: How to handle the query when the Select columns are more than the Insert? How to handle this scenario where the funnel table has fewer columns (or fewer columns that I want to insert) when I need to select more columns from demoTable ?
I get this: Column count doesn't match count row
INSERT INTO funnel
            (
                        id,
                        visitor,
                        stage
            )
select b_id,
       visitor_name,
       visitor_stage',
       visitor_page,
       visitor_time
from demoTable

A: You can't insert by selection with a mismatching number of fields. Select the fields from the source table that match the ones in the destination table and write the query accordingly:
INSERT INTO funnel (id, visitor, stage)
SELECT b_id, visitor_name, visitor_stage FROM demoTable


text:
Q: Lie algebra of $SL_n(\mathbb{K})$ group I've started Lie algebras course this semester, so I already have some questions. Well, I need to find a $Lie(SL_n(\mathbb{K}))$ (Lie algebra). Field $\mathbb{K}$ is algebraically closed  and $char( \mathbb{K})=0$. Teacher gave me next piece of advice. This space is given by the equation $detg=1,\;g\in GL_n$. We have a formula for determinant of matrix $g$.
$$detg=\sum_{\sigma \in S_n}sgn(\sigma)a_{1\sigma (1)}...a_{n\sigma (n)}$$
So I need to differentiate this identity at E. But I thought that $a_{ij}$ are elements of out field, so $d(a_{ij})=0$. Anyway I know, that I need to get something like this:
$$d(detg)=\sum_{i=1}^nda_{ii}=0$$
So the Lie algebra of $SL_n$ is subspace of matrices with zero trace. Please, help me understand the differentiating part.
Thanks.

A: Well I'll try to answer my question on my own.
Let's differentiate first sum.
$$ d(detg)=\sum_{\sigma \in S_n} (-1)^\sigma\sum_{i=1}^nd(a_{i\sigma(i)})a_{1\sigma(1)}...\hat{a_{i\sigma(i)}}...a_{n\sigma(n)}=0$$
Now lets restrict it to the E. Members of this sum are not zero iff $\sigma=id$.
$$d(detg)\vert_E=\sum_{i=1}^nd(a_{ii})=0$$


text:
Q: Terminal vs induced voltage for a transformer with respect to the voltage rating Suppose we have a 2200/220 V non-ideal transformer.
Based on the image below of a non-ideal transformer, would 2200V be the primary terminal voltage (V1) or the primary induced voltage (E1)?
Similarly, is 220V the secondary induced voltage (E2) or the secondary terminal voltage (V2).
If neither, could someone explain what this rating is about?
I came across this explanation in my search, that this means that if 2200V is applied to the primary winding, then 220V is induced in the secondary. Now, my understanding of "applied to the primary winding" refers to the primary terminal voltage (V1) rather than the primary induced voltage.
I am really confused about this voltage rating for the transformers and any information is welcome.

A: A '2200/220 V' transformer rating is ambiguous. It might mean that is the transformation ratio at zero load current. It might mean that's the transformation ratio at the rated load current.
The difference between those two ratings is the voltage dropped at load current across the series R and X components, or the difference between En and Vn. In an ideal transformer of course they are the same.
A transformer is usually rated at the full load current, and the voltages specified are the terminal voltages.
Generally we don't get too hung-up about these loss terms, but roll them all up into a 'regulation' figure. If a transformer has 5% regulation, that means that at rated current, the output voltage drops to 95% of its no load value.

A: Given that what you have drawn is the equivalent circuit of a power transformer, the only nodes a user has access to physically are shown with the red dots below: -


text:
Q: cannot find symbol symbol : variable StringUtils I was trying to print the following statement in my jsp.
out.println("myBookIdStatus="+StringUtils.isEmpty(obj.getValue(0,"value")));

Even though I have imported <%@page import="org.apache.commons.lang.StringUtils"%> , I am getting following error. Why is it happening??
cannot find symbol symbol : variable StringUtils location: class....

A: Most probably you don't have the commons-lang jar file in your classpath, you have to add it in your application WEB-INF/lib.


text:
Q: Getting hyperlink URL and description in custom XSLT with Content Query Web part I'm having trouble getting the URL and description to show as separate items in SharePoint 2013.
I'm trying to display the description as the text of the Link and the URL as the HREF value in the a tag below.
My hyperlink column Name is "Read_x0020_More_x0020_Link"
This doesn't return anything
<xsl:value-of select="substring-after(@Read_x0020_More_x0020_Link,',')"/>

Here is my Full XSLT:
 <xsl:template name="TopStory" match="Row[@Style='TopStory']" mode="itemstyle">
    <xsl:variable name="SafeLinkUrl">
        <xsl:call-template name="OuterTemplate.GetSafeLink">
            <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
        </xsl:call-template>
    </xsl:variable>
    <xsl:variable name="SafeImageUrl">
        <xsl:call-template name="OuterTemplate.GetSafeStaticUrl">
            <xsl:with-param name="UrlColumnName" select="'ImageUrl'"/>
        </xsl:call-template>
    </xsl:variable>
    <xsl:variable name="DisplayTitle">
        <xsl:call-template name="OuterTemplate.GetTitle">
            <xsl:with-param name="Title" select="@Title"/>
            <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
        </xsl:call-template>
    </xsl:variable>

          <xsl:call-template name="OuterTemplate.CallPresenceStatusIconTemplate"/>

<xsl:value-of select="$DisplayTitle"/>

                <xsl:value-of select="@Description" />

              <xsl:value-of select="ddwrt:FormatDateTime(string(@Date) ,1033 ,'dd-MMM-yyyy')"/>

              <xsl:value-of select="substring-after(@Read_x0020_More_x0020_Link,',')"/>

</xsl:template>

A: Your first example of code just needs a slight change. You are using the internal name and need to use the XSL Field Name. Add "x005F_" before all "x0020" so your code will read:
  <xsl:value-of select="substring-after(@Read_x005F_x0020_More_x005F_x0020_Link,',')"/>

Reference: Customizing Content Query Web Part and Item
Don't know if you still need an answer to this but hopefully might help someone else.

A: Something like this could work as well...
Create two separate variables and use the following xslt functions to extract the link from the description:
<xsl:variable name="ReadMoreLink">
    <xsl:value-of select="substring-before(@Read_x0020_More_x0020_Link, ',')" />
</xsl:variable>
<xsl:variable name="ReadMoreDescription">
    <xsl:value-of select="substring-after(@Read_x0020_More_x0020_Link, ',')" />
</xsl:variable>

Then you could use this markup to display the results of both variables:

     <xsl:value-of disable-output-escaping="yes" select="$ReadMoreDescription"/>

If there is ever an instances where no description is entered, you can prevent errors by also including an if/else statements around your substring functions.


text:
Q: How to add a PHP variable into my Jquery image slider? I'm using a Jquery Image slider, and I want to add a couple of things to it.
When you load the full-size image, I want to show two divs, one with an image title and the other with a description of the picture but I'm new to javascript and can't work out how to do it.
I have tried adding document.write commands into the javascript code to test it, but this just outputs text on a blank page, where as I want it to appear when the image is loaded and then I can position the divs where I want them.
I would greatly appreciate some help, thanks in advance!

A: jQuery code:
   $("img.thumb").click(function(){
    $("#fp_gallery").append("<div/>").text("description");
    $("#fp_gallery").prepend("<div/>").text("title");
   }

Try something like this. This is based on their demo site.

A: You will be much better off to use jQuery for all of that sort of thing. Look into http://api.jquery.com/category/manipulation/ for what you're after. You may also want to do a bit of research on understanding how the HTML DOM works (http://w3schools.com/htmldom/default.asp) to better allow you to work with jQuery and the manipulation tools therein.