text:
Q: How to have a view draggable until it becomes full height then make it scrollable? so I am having a bit of a predicament. I have created an activity which functions like a bottom sheet. One feature that many of my users have asked for is the ability to make it so once the bottom sheet is fully extended, the sheet will then scroll so they can view the rest of the items. I tried putting my linear layout inside of a nestedscrollview but that just caused a crash. Please do not recommend me to use the support bottom sheet class as that does not have everything I need for it to work. Thank you in advance!
Here is the layout for the bottom sheet:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/totalScreen"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignTop="@+id/fab"
    android:layout_gravity="bottom|center"
    android:gravity="bottom|center_vertical"
    android:orientation="vertical">

    <TextView
        android:id="@+id/sheetTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#424242"
        android:padding="12dp"
        android:text="Dummy Title"
        android:textSize="18sp" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignTop="@+id/sheetTitle"
        android:layout_marginEnd="20dp"
        android:layout_marginTop="-28dp"
        android:visibility="invisible"
        app:fabSize="normal" />

    <LinearLayout
        android:id="@+id/sheetScreen"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/sheetTitle"
        android:background="#424242"
        android:gravity="bottom|center_vertical"
        android:orientation="vertical"
        android:paddingBottom="8dp">

    </LinearLayout>

</RelativeLayout>

Here is the ontouch listener which allows the bottom sheet behavior:
ID:
protected LinearLayout main;
protected RelativeLayout full;

protected void setAdjustableTouchListener() {
        full.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getActionMasked()) {
                    case MotionEvent.ACTION_DOWN:
                        mDragStartY = event.getY();
                        mPointerOffset = event.getRawY() + main.getMeasuredHeight();
                        return true;
                    case MotionEvent.ACTION_UP:                        DisplayMetrics metrics = new DisplayMetrics();
                        getWindowManager().getDefaultDisplay().getMetrics(metrics);
                        int sheetHeight = (int) (metrics.heightPixels - event.getY());
                        if (mDragStartY < (event.getY() + TAP_DRIFT_TOLERANCE) && mDragStartY > (event.getY() - TAP_DRIFT_TOLERANCE)
                                && ((SystemClock.elapsedRealtime() - mDraggingStarted) < SINGLE_TAP_MAX_TIME)
                                && sheetHeight > (main.getMeasuredHeight() + findViewById(R.id.sheetTitle).getMeasuredHeight())) {
                            result = "Dismissed";
                            finish();
                        } else {
                            if (main.getMeasuredHeight() > (viewConversion + heightDifference)) {
                                ResizeAnimation a = new ResizeAnimation(main);
                                a.setDuration(500);
                                a.setParams(main.getMeasuredHeight(), extendedViewHeight);
                                main.startAnimation(a);
                                state = 2;
                            } else if (main.getMeasuredHeight() < (viewConversion + heightDifference)
                                    && main.getMeasuredHeight() > viewConversion) {
                                ResizeAnimation a = new ResizeAnimation(main);
                                a.setDuration(500);
                                a.setParams(main.getMeasuredHeight(), viewConversion);
                                main.startAnimation(a);
                                state = 1;
                            } else if (main.getMeasuredHeight() < viewConversion && main.getMeasuredHeight() > (viewConversion / 2)) {
                                ResizeAnimation a = new ResizeAnimation(main);
                                a.setDuration(500);
                                a.setParams(main.getMeasuredHeight(), viewConversion);
                                main.startAnimation(a);
                                state = 1;
                            } else if (main.getMeasuredHeight() < (viewConversion / 2)) {
                                result = "Dismissed";
                                finish();
                            }
                        }
                        return true;
                    case MotionEvent.ACTION_MOVE:
                        if (mPointerOffset - event.getRawY() < extendedViewHeight)
                            setPrimaryContentHeight((int) (mPointerOffset - event.getRawY()));
                        return true;
                    default:
                        return true;
                }
            }
        });
    }

Here is the method to actually set the new height of the sheet:
protected boolean setPrimaryContentHeight(int newHeight) {
    // the new primary content height should not be less than 0 to make the
    // handler always visible
    newHeight = Math.max(0, newHeight);
    // the new primary content height should not be more than the SplitView
    // height minus handler height to make the handler always visible
    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) main.getLayoutParams();
    if (newHeight >= 0) {
        params.height = newHeight;
        // set the primary content parameter to do not stretch anymore and
        // use the height specified in the layout params
    }
    main.setLayoutParams(params);
    return true;
}

Here is the crash that occurs when using the NestedScrollView:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nick.mowen.sceneplugin/com.nick.mowen.sceneplugin.ui.BottomSheetActivity}: android.view.InflateException: Binary XML file line #32: Binary XML file line #32: Error inflating class android.support.v4.widget.NestedScrollView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2450)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2520)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5466)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.InflateException: Binary XML file line #32: Binary XML file line #32: Error inflating class android.support.v4.widget.NestedScrollView
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:267)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:129)
at com.nick.mowen.sceneplugin.ui.BottomSheetActivity.onCreate(BottomSheetActivity.java:37)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2520)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5466)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.InflateException: Binary XML file line #32: Error inflating class android.support.v4.widget.NestedScrollView
at android.view.LayoutInflater.createView(LayoutInflater.java:645)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:267)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:129)
at com.nick.mowen.sceneplugin.ui.BottomSheetActivity.onCreate(BottomSheetActivity.java:37)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2520)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5466)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance(Native Method)
at android.view.LayoutInflater.createView(LayoutInflater.java:619)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:267)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:129)
at com.nick.mowen.sceneplugin.ui.BottomSheetActivity.onCreate(BottomSheetActivity.java:37)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2520)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5466)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.view.NestedScrollingChildHelper.setNestedScrollingEnabled(boolean)' on a null object reference
at android.support.v4.widget.NestedScrollView.setNestedScrollingEnabled(NestedScrollView.java:212)
at android.view.View.<init>(View.java:4256)
at android.view.ViewGroup.<init>(ViewGroup.java:573)
at android.widget.FrameLayout.<init>(FrameLayout.java:97)
at android.widget.FrameLayout.<init>(FrameLayout.java:92)
at android.support.v4.widget.NestedScrollView.<init>(NestedScrollView.java:189)
at android.support.v4.widget.NestedScrollView.<init>(NestedScrollView.java:185)
at java.lang.reflect.Constructor.newInstance(Native Method)
at android.view.LayoutInflater.createView(LayoutInflater.java:619)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:267)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:129)
at com.nick.mowen.sceneplugin.ui.BottomSheetActivity.onCreate(BottomSheetActivity.java:37)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2520)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1363)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5466)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

A: Ok, solved this, what I ended up doing was just adding a recyclerview in place of the linearlayout. Then I just made the LayoutManager overridden so it is only scrollable when I set it to be:
main.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return canScroll && super.canScrollVertically();
            }
        });


text:
Q: Can you substitute congruences into an expression if the conditions are right? When using a congruences can we substitute them into an expression. For example, when we look at Fermat's little theorem we notice that $a^p$ is congruent to $a\ (\text{mod}\ p)$ when $a$ is an integer and $p$ is prime, so where ever we see $a^p$ where $a$ is an integer and $p$ is prime, can we simply substitute $a\ (\text{mod}\ p)$ for $a^p$?

A: Yes in general using congruences all algebraic rules hold for for the sum and product and we can substitute them into an expression, notably for

*

*$A\equiv a \mod p$

*$B\equiv b \mod p$

we have that

*

*$A+B\equiv a+b \mod p$

*$A\cdot B\equiv a\cdot b \mod p$

A: No. It would be very bad notation in some cases.
For example, if you replace $a^p$ by $a\pmod p$ in the equation $$a^p\times5=5a^p$$ then you get $$a\pmod p\times5=5a\pmod p$$ so the RHS would be very ambiguous. Do you mean $5a\pmod p$ or $5\times[a\pmod p]$?

A: So, what about taking the Pythagorean triples as an example. We know for Pythagorean triples $x,y,$ and $z$ are integers in $x^2+y^2=z^2$. By Fermats little theorem, we know

*

*$a^2\equiv{a\ (\text{mod }2)}$ where $a\in{\mathbb{z}}$

So, $x^2+y^2=z^2$ yields,

*

*$x+y\equiv{z\ (\text{mod }2)}$

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL injection com PHP + SQLServer Como posso prevenir SQL injection vindo de um input via POST utilizando PHP + SQLServer. (Utizando Microsoft SQL Server => mmsql)
Estou fazendo a abstração de dados de um BD que roda MYSQLI e neste caso é feita desta maneira.

$Email= mysqli_real_escape_string($conexao, $_POST['Email']);
$Senha= mysqli_real_escape_string($conexao, $_POST['Senha']);

A: Existe dois drivers para fazer conexão com o SQL Server o PDO e o SQLSRV, Tem várias questões sobre o PDO especificas para o SQL Server, desde a a instação e configuração, criação da conexão e os demais aspectos da biblioteca.
Criação da conexão:
$servidor = 'ip ou servidor\instancia';
$db = 'test';
$usuario = 'user';
$senha = 'pass';

$conexao = sqlsrv_connect($servidor, array('Database' => $db, 'UID' => $usuario, 'PWD' => $senha));

Escapar caracteres não previne nem resolve o problema de sql injections como mostra essa resposta, a melhor forma de atacar esse problema é filtrar as entradas do usuário adequadamente e utilizar prepared statements.
Para DML(insert, update ou delete) faça esse código, isto é apenas um exemplo por favor não armazena senhas em formato de texto puro no banco.
$sql = "INSERT INTO usuarios(email, nome, senha) VALUES(?,?,?)";

$email = "doge@wow.com";
$nome = "Doge";
$senha = "wowsuchsecret";

$stmt = sqlsrv_prepare( $conexao, $sql, array($email, $nome, $senha));
if( !$stmt ) {
    die( print_r(sqlsrv_errors());
}

Para selects:
$sql = "SELECT * FROM usuarios";
$stmt = sqlsrv_query($conexao, $sql);
if( $stmt === false) {
    die(print_r(sqlsrv_errors()));
}

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
      echo $row['nome']." - ".$row['email']."<br />";
}


text:
Q: Counterexample for the reverse implication of Rice's theorem Here is the version of Rice's theorem I use:
Rice's first Theorem: For every non-trivial, language invariant property
$P$ of a set of Turing machines it holds that the set
$$\{M | P(M) \}$$
is undecidable.
So my question is really is this give an example of a property $P$ of Turing machines that does not satisfy Rice's theorem and such that
$$\{M | P(M) \}$$ is an undecidable language.
I was thinking about something like this: A Turing machine has property P if the computation history of input $\epsilon$ passes through 3 different states. This property is not language invariant but I cannot prove that it is undecidable...
For those wondering: by language invariant I mean the following:
A property $P$ of Turing machines is called language invariant if
$$L_{M1} = L_{M_2} \Rightarrow P(M_1) = P(M_2).$$
Thanks!

A: Your approach probably works. By that, I mean that your language will indeed be undecidable . . . if we replace "$3$" by a sufficiently large number. Maybe (probably?) $3$ is already large enough, but that would take some work.
The point would be to build for each $n$, a machine $M_n$ which basically (using a fixed number $k$ of states, independent of $n$) checks whether $n$ is in the Halting Problem. If $n$ is not in the Halting Problem, $M_n$ never uses more than $k$-many states. If $n$ is in the Halting Problem, have $M_n$ enter a subroutine where it goes through $k+1$ "dummy" states.
Basically, all we need is for there to be a universal Turing machine with $k$ many states. This is possible for large enough values of $k$; whether $k=3$ depends on exactly how you've set up your Turing machines. I believe under most definitions, 3 is indeed enough, but it would take an argument.

Here's a simpler approach. By the Padding Lemma, we can find a computable set $X$ of machines which each compute the empty language. (Note that of course $X$ doesn't consist of all machines computing the empty language.) Then any infinite subset of $X$ which is not all of $X$ will be non-language-invariant.
So: does $X$ have any non-computable subsets?

A: Here is an even simpler example. Take any non-trivial language-invariant property $P$ of Turing machines! Let $F$ be your favourite Turing machine (just one)! Let $S = \{ M : P(M) \oplus M = F \}$. Then $S$ is undecidable because $\{ M : M \in S \oplus M = F \} = \{ M : P(M) \}$ is undecidable by Rice's theorem. Done!

In general you can replace "$M = F$" by any non-trivial decidable statement. In other words let $S = \{ M : P(M) \oplus Q(M) \}$ where $Q$ is any computable property. Then $Q$ would not be language-invariant by Rice's theorem and hence $S$ also would not be language-invariant. But by the same argument as before, $S$ would be undecidable.

This motivates a more interesting question of whether there is a property of Turing machines that is not decomposable into $P \oplus Q$ where $P$ is a language-invariant property and $Q$ is a computable property. This is not hard to answer. We will start with no commitment for the desired property $I$, and incrementally commit some Turing machines to satisfy $I$ and some to not satisfy $I$, and never change our mind on previous commitments. Go through each computable property $Q$ one by one. We ensure the invariance that we have only made finitely many previous commitments at every step. We choose two Turing machines $A,B$ that are not already involved in previous commitments and either both satisfy $Q$ or both do not satisfy $Q$. This is possible by the invariance. If $A,B$ accept the same language, we commit $I(A)$ and $\neg I(B)$, otherwise we commit $I(A)$ and $I(B)$. In either case $I \oplus Q$ is not language-invariant. At the end of the process, $I$ is an example of the desired kind of property.


text:
Q: How to access variable names dyamically in jstl I am new to jsp and jstl and this may not be exactly possible. I need a way to display multiple shipments based on an order. In later pages I would like to be able to pass a variable to select which shipment information to display.
currently my variables are created like this:
<c:choose>
    <c:when test="${param.order == 1}">
        Param.o_num = <c:out value="${param.order}"/>

        <c:set var="o_buyer" value="Michael S" />
        <c:set var="o_address" value="1234 Frederick St" />
        <c:set var="o_cost" value="$99.98" />
        <c:set var="o_number" value="0000646ASDF" />

        <c:set var="o_shipments" value="3" />

        <c:set var="sh_1_to" value="Colonel Mustard" />
        <c:set var="sh_1_date" value="Wednesday, May 10, 2017" />
        <c:set var="sh_1_address" value="1234 Study Lane" />
        <c:set var="sh_1_city" value="Omaha" />
        <c:set var="sh_1_state" value="NE" />
        <c:set var="sh_1_zip" value="68152" />
        <c:set var="sh_1_num" value="001" />
        <c:set var="sh_1_total" value="$24.99" />
        <c:set var="sh_1_status" value="Preparing Shipment" />
        <c:set var="sh_1_message" value="Its good stuff, please enjoy." />
        <c:set var="sh_1_signature" value="- Michael" />

        <c:set var="sh_2_to" value="Miss Scarlet" />
        <c:set var="sh_2_date" value="Wednesday, April 24, 2017" />
        <c:set var="sh_2_address" value="1234 Library Ave" />
        <c:set var="sh_2_city" value="Omaha" />
        <c:set var="sh_2_state" value="NE" />
        <c:set var="sh_2_zip" value="68102" />
        <c:set var="sh_2_num" value="002" />
        <c:set var="sh_2_total" value="$24.99" />
        <c:set var="sh_2_status" value="Preparing Shipment" />
        <c:set var="sh_2_message" value="Eat Well and Prosper." />
        <c:set var="sh_2_signature" value="- Mike S" />

        <c:set var="sh_3_to" value="Mrs Peacock" />
        <c:set var="sh_3_date" value="Wednesday, April 18, 2017" />
        <c:set var="sh_3_address" value="1234 Kitchen Blvd" />
        <c:set var="sh_3_city" value="Omaha" />
        <c:set var="sh_3_state" value="NE" />
        <c:set var="sh_3_zip" value="68106" />
        <c:set var="sh_3_num" value="003" />
        <c:set var="sh_3_total" value="$24.99" />
        <c:set var="sh_3_status" value="Delivered" />
        <c:set var="sh_3_message" value="Don''t forget to chew." />
        <c:set var="sh_3_signature" value="- Michael S" />

    </c:when>
    <c:when test="${param.order == 2}">...

and i access them by like:
<c:choose>
    <c:when test="${not empty sh_1_to }">

            <a class="os_card <c:out value=" ${sh_1_status= ='Delivered' ? 'os_card_disabled' : '' }" />" title="" href="${shipURL}1">

Send To

${sh_1_to}

Est. Delivery

${sh_1_date}

Total

${sh_1_total}

Number

${o_number}-${sh_1_num}

Status

${sh_1_status}

    </c:when>
    <c:otherwise>
    </c:otherwise>
</c:choose>

is there a way for me to change it to ${shipment.to} where 'shipment' is a variable?


text:
Q: How to use RElasticSearch package to execute a query that runs on ElasticSearch head? I am working on RElasticSearch package. I ran a GET query in ElasticSearch-head on my index which looks like this:
{
  "query": {
     "term": {
      "id": "0a88d2dd43fe985501440bbd6610768f"
    }
  }
}

This ran successfully. I want to know how to specify this query in searchES method of RElasticSearch package. I tried finding answers but there is no proper documentation anywhere. Can anyone please help me out?? Thanks in advance.

A: Never mind. I used the POST method in httr package in R and passed my JSON object as a string parameter. It worked.
Something like :
library(httr)
filter<-'{"query":{"bool":{"must":[{"range":{"createdTime":{"from":"2014-03-07","to":"2014-03-07"}}}]}}}'
POST("//_search?pretty",body=filter)


text:
Q: Destroy previous fragments from layout I have a layout which I populate with two fragments. I have written a service that fetches data online and then repopulate the layout with two fragments . I want to destroy old fragments and then place the new one but this keeps on adding the new fragments in the layout. If I use beginTransaction().replace that only adds one fragment at a time in layout . How can I achieve this thing?
new Handler().post(new Runnable() {
            public void run() {

                Fragment f = getFragmentManager().findFragmentByTag("fragmentNowPlaying");
                if (f != null)
                    transaction.remove(f);

                f = getFragmentManager().findFragmentByTag("fragmentChannel");
                if (f != null)
                    transaction.remove(f);

                FragmentTransaction transaction = fm.beginTransaction();
                FragmentNowPlaying fragmentNowPlaying = new FragmentNowPlaying();
                transaction = fm.beginTransaction().add(R.id.content,fragmentNowPlaying, "fragmentNowPlaying");
                transaction.commitAllowingStateLoss();

                transaction = fm.beginTransaction();
                FragmentChannel fragmentchannel = new FragmentChannel();
                transaction = fm.beginTransaction().add(R.id.content,fragmentchannel, "fragmentChannel");
                transaction.commitAllowingStateLoss();
            }
        });

A: Use two separate FrameLayout containers for each Fragment. This way you can replace() them independently of each other.


text:
Q: Will replacing php coding, in the index.php file with `get_template_part` tags, reduce website performance? My index.php file currently includes content such as:

*

*Latest Products

*Product Testimonials

*Subscribe to us

*Blogs

Rather than have the entire coding for this, placed into my index.php file, I would like to create a template file for each 'section' and then call it in the index.php file, using the get_template_part tag.
So much so, my index.php would then become a file housing a series of get_template_part entries.
Is anyone aware of any issues that this may cause, such as website load speed or any compatibility issues?

A: Since originally posting this question, I have experimented with the layout of the index.php file, where I used Google's PageSpeed Insights and Pingdom to measure any performance changes.
Firstly, I placed the following content into the index.php file:

*

*Latest Products

*Product Testimonials

*Subscribe to us

*Blogs

I then took out the above content and then placed the content into assigned Templates files.  I then entered the appropriate get_template_part tags into the 'index.php' files, as to call each Template file.
Whilst there was a slight reduction in page load speed, it was negligible.  On one occasion, the change in PageSpeed was a reduction of speed of 0.0003s.
Of course, it is up to the site creator on how they want to go about the creation for their website but I feel this is a good trade off, considering it would result in a more organised website.


text:
Q: Add query string to script tag link in asp.net to break Cache Hope someone can help me on this. I manage an ASP.Net website and usually update script files and css files very often. I add current time appended into a single string as a query string parameter (eg: profileImage.jpg?123021) which makes the browser to look for the file without getting it from cache.
How can I do the same thing to all script tags and css links from the server side so that it loads the latest version of the file.
Any help appreciated.
Amila

A: If your asp.net website uses Master Pages, it should be easy to make these changes in the Master Page file.  Look a file with the extension .master.  If you are not sure how to make the specific edit, post the <head> area from the master page markup in a new question.
MSDN Master Pages: http://msdn.microsoft.com/en-us/library/wtxbf3hh(v=vs.100).aspx
If your site does not use master pages, then you'd need to create some server-side logic that affects the <head> section of the page.  Below are some links to related QA's about injecting script and styles from the server side.
ASP.NET: How to (programmatically) attach a <script> tag, containing a link to .js, to <head>?
How to Add script codes before the </body> tag ASP.NET


text:
Q: Download multiple audio files I have trying to download the multiple .mp3 files from a server at  time. One complete audio file is divided into 286 parts. I fetch all the urls of the file and now I want to download 286 files. I search a lot but many library stop downloading when I go back to previous controller and if user minimize the app the downloaded stop. Is there any library which can manage multiple downloads and download didn't stop when user go back to previous controller of minimize the app.
I am using Download Manager library but I can't get my desired. Please give me the solution. I am stuck with that from 3 days . Please tell me the solution . Thanks

A: In my project I'm using AFNetwirking. You can create a singleton object, and here is my method (for example) for downloading files :
- (AFHTTPRequestOperation *)performDownloadWithURLString:(nonnull NSString *)urlString
                                     destinationPath:(NSString *)destinationPath
                                            progress:(void (^)(long long bytesRead, long long totalBytesToRead))progress
                                         apiCallback:(void(^)(BOOL isSuccessful, id object))apiCallback
{

    NSURL *url = [NSURL URLWithString:urlString];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    NSString *fullPath = [[FCFileManager pathForTemporaryDirectory] stringByAppendingPathComponent:[url lastPathComponent]];

    [operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:fullPath append:NO]];

    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead)
     {
         if(progress) {
             progress(totalBytesRead, totalBytesExpectedToRead);
         }
     }];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

            if(destinationPath && [FCFileManager isFileItemAtPath:destinationPath]) {
                NSError *removeError;
                [FCFileManager removeItemAtPath:destinationPath error:&removeError];
            }
            if(destinationPath) {
                [FCFileManager moveItemAtPath:fullPath toPath:destinationPath];
            }

            dispatch_async(dispatch_get_main_queue(), ^{
                if(apiCallback) {
                    apiCallback(YES, destinationPath ?: fullPath);
                }
            });
        });

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSError *removeError;
        [FCFileManager removeItemAtPath:fullPath error:&removeError];

        if(apiCallback) {
            apiCallback(NO, [AZError errorWithNSError:error]);
        }

    }];
    [operation start];
}

Hope it helps you.


text:
Q: Android Studio JDK location I am having an issue with my android studio. Whenever i open it ,it throws an error
"Invalid Project JDK".

I have deleted my previous version of Java and installed a new version. I also tried to change the JDK location directory for new version, but it is not solved. Help in this regard will be appreciated!

A: TRY to reset your Java and Android  Environment variables configurations.
You can input Java and Javac in your cmd to check whether your "Java Path" is  correct. Then input adb in your cmd to check whether your "Android Path" is correct.
Hope this is helpful.


text:
Q: Alterar Cor da string mediante ao retorno do Mysql Tenho o código abaixo, caso a coluna score tiver um campo com "LOW" a cor de apenas o LOW tem que ser (#FFFF00) e se caso o campo for HIGHT, apenas o HIGHT tem que ter a cor (#FF0000):
   <?php
    while($row = $stm->fetch())  {
    $color = $row["score"];

   echo "
"."<input type=checkbox name='check[]' value='[]' >	"."	"."" .$row['quantidade']. "	". "". $row['data'] . "	"."" . $row['ip'] . "	"."" . $row['hostname'] . "	"."" .$row['sender']. "	"."" .$row['subject']."	".""."
" .$row['score']. " <button class='btn btn-danger btn-xs' data-title='Delete' data-toggle='modal' data-target='#delete' </button>

".'' ;
}

  switch($color){

    case 'LOW':
        $color = "#FFFF00";
        break;
    case 'HIGH':
        $color = "#FF0000";
        break;

        return $color;
}

 ?>

O que ocorre que nenhuma cor é alterada no campo que tem estes cases. Poderiam me ajudar onde estou errando?
Grato.

A: Eu consegui observar dois possíveis problemas:
1º Seu Switch deve estar antes do seu echo, tente criar uma função e chamar ela dentro do laço, abaixo um exemple de como você pode estruturar:
<?php
function GetColor($color){
  switch($color){
    case 'LOW':
        $color = "#FFFF00";
        break;
    case 'HIGH':
        $color = "#FF0000";
        break;
    }
    return $color;
}

while($row = $stm->fetch())  {
    $color = $row["score"];

   echo "
"."<input type=checkbox name='check[]' value='[]' >	"."	"."" .
   $row['quantidade']. "	". "".
   $row['data'] . "	"."" .
   $row['ip'] . "	"."" .
   $row['hostname'] . "	"."" .
   $row['sender']. "	"."" .
   $row['subject']."	"."".
   "
" .
   $row['score']. "
	<button class='btn btn-danger btn-xs' data-title='Delete' data-toggle='modal' data-target='#delete' </button>

".'' ;
}
?>

2º Sua atribuição css ao color parece incorreta:
tente assim
color: ".$color.";


text:
Q: Which Demo Weapons count for the Left 4 Heads Achievement The Left 4 Heads achievement is to behead 4 people in 10 seconds. Which of the demo melee weapons count as beheading as per the achievement?
I know that obviously the Eyelander will, since it debuted with the achievement in the first place, but what about the new swords since? The axes?

A: All weapons that can decapitate will work with the achievement, including those which do not buff you based on how many heads you've taken in a life. That means all these:

*

*Eyelander

*Scotsman's Skullcutter

*Horseless Headless Horsemann's Headtaker

*Claidheamh Mòr

*Half-Zatoichi

It does make things easier if you equip weapons that help you run faster, like the Eyelander or the HHHH. I wouldn't use the Skullcutter for it.
Obviously, you have to be a Demoman to get the achievement using the Half-Zatoichi; it won't count if you're a Soldier.

A: From the Obtaining Demoman Achievements page on the official TF2 wiki:

Left 4 Heads
Decapitate 4 players with only 10 seconds between each kill.
Difficulty: Hard
How to obtain: Equip the Eyelander, Scotsman's Skullcutter, Horseless Headless Horsemann's Headtaker, Claidheamh Mòr, or Half-Zatoichi and engage multiple enemies at close range. Pair your melee weapon with the Chargin' Targe in order to reach new targets before the ten seconds expire.


text:
Q: OCMock stub for method's pass-by-reference argument I have a method that I need to stub.  The method is of the form below:
BOOL myMethodWithError:(*__autoreleasing *NSError)error;

So I mocked the object and attempted to return a nil back through 'error'.  I coded it as follows.
id mockMyObject = [OCMockObject mockForClass:[MyObject class]];
BOOL retVal = YES;
NSError *error = nil;
[[[mockMyObject stub] andReturn:OCMOCK_VALUE(retVal)] myMethodWithError:&error];

When the test is run and the mock object is operated, the error reference id appears to change.  So the mock throws an exception:

OCMockObject[MyObject]: expected method invoked:
  myMethodWithError:0xbfffca78

I have tried a number of different ways but each time the pointer value appears to change once the error object is passed to the method which causes the mock object to throw an error.
I simply need to test my business rules against the pass-by-reference value of the argument, but I can't seem to get the mock or test object to cooperate.
Thanks in advance, any help will be greatly appreciated.

A: Apart from the solutions Ben mentions in his answer(I only tested the one based on ignoringNonObjectArgs, and it works fine), I prefer to use [OCMArg anyPointer] with the appropriate cast:
[[[myMock stub] andReturn:something] someMethod:(NSError * __autoreleasing *)[OCMArg anyPointer]];

A: Use ignoringNonObjectArgs
[[[[mock stub] andReturnValue:OCMOCK_VALUE((BOOL){YES})] ignoringNonObjectArgs] myMethodWithError:NULL];

From http://ocmock.org/features/

Arguments that are neither objects nor pointers or selectors cannot be
  ignored using an any placeholder. It is possible, though, to tell the
  mock to ignore all non-object arguments in an invocation:

[[[mock expect] ignoringNonObjectArgs] someMethodWithIntArgument:0]

In this
  case the mock will accept any invocation of someMethodWithIntArgument:
  no matter what argument is actually passed. If the method has object
  arguments as well as non-object arguments, the object arguments can
  still be constrained as usual using the methods on OCMArg.

Bonus Answer
This would also solve your issue:
[[[mock stub] andReturnValue:OCMOCK_VALUE((BOOL){YES})] myMethodWithError:[OCMArg setTo:nil]];


text:
Q: statemodifier halt() not working Following Famo.us University Animation part. The following code didn't halt the translation, instead runs straight to the end. I expected it halted where it is clicked. Am I right?
surface.on('click', function() {
  stateModifier.halt();
  surface.setContent('halted');
});

Thanks

A: The answer is: It will halt the transform, but will complete at the transforms final position
That is why you see the jump from where it is clicked.
Rather than halt the Transform just set the transform to the current Transform position.
Example jsBin
  surface.on('click', function() {
    //stateModifier.halt();
    stateModifier.setTransform(stateModifier.getTransform());
    surface.setContent('Halted');
  });


text:
Q: Picture not loading with htm tag

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0">

The picture Element

<picture>
  <source media="(min-width: 650px)" srcset="img_food.jpg">
  <source media="(min-width: 465px)" srcset="img_car.jpg">

</picture>

I need to know if this is outdated and if you can insert local files

A: Your code references local images. This snippet is a clone of yours -- all I've done is change the images to web-accessible images. So your code is fine. If images are not appearing, it's because they can't be found.

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0">

The picture Element

<picture>
  <source media="(min-width: 650px)" srcset="https://img.traveltriangle.com/blog/wp-content/uploads/2018/12/cover-for-street-food-in-sydney.jpg">
  <source media="(min-width: 465px)" srcset="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/2019-honda-civic-sedan-1558453497.jpg?crop=1xw:0.9997727789138833xh;center,top&resize=480:*">

</picture>


text:
Q: What could be wrong in saving the following animation in Python? I am new in Python and would like to save animations. Here is a minimal working environment:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from numpy import pi

X,Y = np.meshgrid(np.arange(0,2*np.pi,.2),np.arange(0,2*np.pi,.2) )
U = np.cos(X)
V = np.sin(Y)

fig,ax = plt.subplots(1,1)
Q = ax.quiver( X, Y, U, V, pivot='mid', color='r', units='inches')

ax.set_xlim(0, 2*pi)
ax.set_ylim(0, 2*pi)

def update_quiver(num, Q, X, Y):
    U = np.cos(X + num*0.1)
    V = np.sin(Y + num*0.1)
    Q.set_UVC(U,V)
    return Q,

anim = animation.FuncAnimation(fig, update_quiver, fargs=(Q, X, Y),
    interval=10, blit=False)

mywriter = animation.FFMpegWriter()
anim.save('mymovie.mp4',writer=mywriter)

I get the error message:
mywriter = animation.FFMpegWriter()
AttributeError: 'module' object has no attribute 'FFMpegWriter'

Any help will be highly appreciated!


text:
Q: In C#, how to know if a thread is waiting to enter write lock for ReaderWriterLockSlim? I am trying to implement the ReaderWriterLockSlim for a list. I would like each thread to be able to read from the list at once, but only one thread to be permitted to "wait" for the write lock. If a thread attempts to gain control of the write lock while another thread is already writing or waiting to write, I would like it not to wait for the lock. I have found the TryEnterReadLock(Int32) method, but from my understanding, it will only wait until the calling thread can gain control of the write lock or the timeout is reached. I would try this with a timeout of "0", however, I don't think this will work since if other threads possess the read lock, it will timeout before gaining access to the write lock. I know I could use a variable to represent whether or not a thread is writing or waiting to write, but I wanted to know if there is a more professional way of doing this (I'd prefer not to have to create another variable and consequently have to create a mutex lock for it).

A: Move the logic further back, Use TryEnterUpgradeableReadLock on the readers with a 0 timeout, then that one reader becomes your writer waiting for the other readers to finish.
public void YourFunction()
{
    bool enteredUpgLock = false;
    bool enteredWriteLock = false;

    try
    {
        //Preemptively take a upgradeable read lock, only one thread can do this.
        enteredUpgLock = _readerWriterLock.TryEnterUpgradeableReadLock(0);

        try
        {
            //If we don't have the upgradeable lock take a normal read lock.
            if (!enteredUpgLock)
            {
                _readerWriterLock.EnterReadLock();
            }

            DoReadWork();
        }
        finally
        {
            //Release the read lock if we had it.
            if(!enteredUpgLock)
                _readerWriterLock.ExitReadLock();
        }

        try
        {
            if (enteredUpgLock)
            {
                //We held the upgradeable lock, wait forever till we can take it.
                _readerWriterLock.EnterWriteLock();
                enteredWriteLock = true;
            }
            else
            {
                //We did not have the upgrade lock, try to take the write lock but if we can't bail out.
                enteredWriteLock = _readerWriterLock.TryEnterWriteLock(0);
                if(!enteredWriteLock)
                    return;
            }

            DoWriteWork();
        }
        finally
        {
            if(enteredWriteLock)
                _readerWriterLock.ExitWriteLock();
        }
    }
    finally
    {
        //If we had the upgradeable lock, release it.
        if (enteredUpgLock)
        {
            _readerWriterLock.ExitUpgradeableReadLock();
        }
    }
}


text:
Q: How to understand OpenJDK versions and find the newest Java 8 image? I am using 8u151-jdk-alpine3.7 in my docker file. I wanted update to newest Java 8 version.
There are two versions in the image name

*

*8u151 which si version of Java

*alpine3.7 which I can't find definition anywhere

Additionaly there is no clear list of released versions so I could find which version follows 8u151-jdk-alpine3.7.
Question: Would I search newer version of Java for the same Alpine version(3.7) or newer one? What is the diffrence? It's confusing at least.

A: Isn't that Java 8u151 for use on Alpine 3.7?
If you're not changing the Alpine image then presumably you should be looking for something with a larger number than 8u151, with the rest of the name the same.


text:
Q: An errant line on a simple plot Why is there a horizontal line in the following plot? If it were plotted on the Cartesian plane, the horizontal line would be drawn along the positive x-axis. Every command is to draw a semicircle or to color a semicircle.
The figure is composed of 18 semicircles - nine of which are above the x-axis and nine of which are below the x-axis. Every arc from a semicircle above the x-axis should align with an arc below the x-axis. These arcs don't quite align, though.
\documentclass{amsart}

\usepackage[dvipsnames]{xcolor}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}[x=0.25cm,y=0.25cm]

\draw (-9,0) arc (180:0:9);
\path[fill=Purple] (-9,0) arc (180:0:9) -- (9,0) -- (-9,0);
\draw (-9,0) arc (180:0:8);
\path[fill=Orchid] (-9,0) arc (180:0:8) -- (7,0) -- (-9,0);
\draw (-9,0) arc (180:0:7);
\path[fill=blue] (-9,0) arc (180:0:7) -- (5,0) -- (-9,0);
\draw (-9,0) arc (180:0:6);
\path[fill=green] (-9,0) arc (180:0:6) -- (3,0) -- (-9,0);
\draw (-9,0) arc (180:0:5);
\path[fill=yellow] (-9,0) arc (180:0:5) -- (1,0) -- (-9,0);
\draw (-9,0) arc (180:0:4);
\path[fill=orange] (-9,0) arc (180:0:4) -- (-1,0) -- (-9,0);
\draw (-9,0) arc (180:0:3);
\path[fill=RedOrange] (-9,0) arc (180:0:3) -- (-3,0) -- (-9,0);
\draw (-9,0) arc (180:0:2);
\path[fill=Red] (-9,0) arc (180:0:2) -- (-5,0) -- (-9,0);
\draw (-9,0) arc (180:0:1);
\path[fill=Mahogany] (-9,0) arc (180:0:1) -- (-7,0) -- (-9,0);

\draw (-9,0) arc (180:360:9);
\path[fill=Mahogany] (-9,0) arc (180:360:9) -- (18,0) -- (-9,0);
\draw (-7,0) arc (180:360:8);
\path[fill=Red] (-7,0) arc (180:360:8) -- (18,0) -- (-7,0);
\draw (-5,0) arc (180:360:7);
\path[fill=RedOrange] (-5,0) arc (180:360:7) -- (18,0) -- (-5,0);
\draw (-3,0) arc (180:360:6);
\path[fill=orange] (-3,0) arc (180:360:6) -- (18,0) -- (-3,0);
\draw (-1,0) arc (180:360:5);
\path[fill=yellow] (-1,0) arc (180:360:5) -- (18,0) -- (-1,0);
\draw (1,0) arc (180:360:4);
\path[fill=green] (1,0) arc (180:360:4) -- (18,0) -- (1,0);
\draw (3,0) arc (180:360:3);
\path[fill=blue] (3,0) arc (180:360:3) -- (18,0) -- (3,0);
\draw (5,0) arc (180:360:2);
\path[fill=Orchid] (5,0) arc (180:360:2) -- (18,0) -- (5,0);
\draw (7,0) arc (180:360:1);
\path[fill=Purple] (7,0) arc (180:360:1) -- (18,0) -- (7,0);

\end{tikzpicture}

\end{document}

A: See if this code reproduces your figure in the desired form:
\documentclass{amsart}
\usepackage[dvipsnames]{xcolor}
\usepackage{tikz}

\begin{document}
    \begin{tikzpicture}[x=0.25cm,y=0.25cm, very thin]
\draw[fill=Mahogany]    (-9,0) arc (180:0:9) arc (360:180:9);
\draw[fill=Red]         (-9,0) arc (180:0:9) arc (360:180:8) arc (0:180:1);
\draw[fill=RedOrange]   (-9,0) arc (180:0:9) arc (360:180:7) arc (0:180:2);
\draw[fill=orange]      (-9,0) arc (180:0:9) arc (360:180:6) arc (0:180:3);
\draw[fill=yellow]      (-9,0) arc (180:0:9) arc (360:180:5) arc (0:180:4);
\draw[fill=green]       (-9,0) arc (180:0:9) arc (360:180:4) arc (0:180:5);
\draw[fill=blue]        (-9,0) arc (180:0:9) arc (360:180:3) arc (0:180:6);
\draw[fill=Orchid]      (-9,0) arc (180:0:9) arc (360:180:2) arc (0:180:7);
\draw[fill=Purple]      (-9,0) arc (180:0:9) arc (360:180:1) arc (0:180:8);
    \end{tikzpicture}
\end{document}

Note: each shape is drawn with a single closed line filled with a selected color. A very thin line is added around the edges of the shapes, especially in the area where they are very close to each other or even overlapping.


text:
Q: Yii2 - Set safe attributes on scenarios How can I safe my attributes for a massive assignment when I'm using a scenario (in my example 'update' scenario)?
Here is my rules:
public function rules()
{
    return [
        [['user_id', 'type', 'name', 'status'], 'required'],
        [['country_id', 'address', 'name', 'status'], 'safe', 'on' => 'update'],
    ];
}

public function scenarios()
{
    $scenarios = parent::scenarios();
    $scenarios['update'] = ['user_id', 'type', 'name'];
    return $scenarios;
}

When I'm checking the safe attributes in my controller using $model->safeAttributes(), I'm only getting the required attributes that are in the required of the 'update' scenario of the function scenarios().
And of course, the $model->load(Yii::$app->request->post()) function does not retreive other attributes.
How can I put them safe?
Even if I want to add some other rules, I can't find the way!

A: Set the scenario before you load the model:
$model->setScenario('update');
$model->load(Yii::$app->request->post())

A: You need to add them all in scenario
$scenarios['update'] = ['user_id', 'type', 'name', 'country_id', 'address', 'name', 'status'];


text:
Q: How do I get the selected text from a WordEditor Object (in Outlook2010) and Copy it to another Form? i want to Copy selected Text from WordEditor(Body of Outlook Email) to another Form when i searched i found that part of code to Copy to new Word Document by using Microsoft.Office.Interop.Word.Document
Outlook.MailItem mailItem;
Outlook.Inspector inspector = mailItem.GetInspector;

// Obtain the Word.Document object from the Inspector object
Word.Document document = (Word.Document)inspector.WordEditor;

// Copy the selected objects
document.Application.Selection.Copy();

i always get Error with mailItem.GetInspector part ( Object refrence is not set to instance of object )

A: You need to request the active inspector from the Application object. Globals.ThisAddIn.Application.ActiveInspector() will provide you with the currently active inspector reference which you can then request the CurrentItem and convert to a MailItem reference if the item is a MailItem type (could also be a CalendarItem, TaskItem, NoteItem, etc.).

A: for starters you are not using the OutLook.MailItem properly..
use something like this as a test and utilize it and make changes as you see fit to fit your UseCase
public void ShowEmail(string To, string Subject, string Body)
{
    Outlook.Application myOutlook = new Outlook.Application();
    Outlook.NameSpace myNamespace = myOutlook.GetNamespace("MAPI");
    myNamespace.Logon(null, null, null, null);
    Outlook.MAPIFolder outbox = myNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderOutbox);
    Outlook.MailItem mail = (Outlook.MailItem)outbox.Items.Add(Outlook.OlItemType.olMailItem);

    mail.Recipients.Add(To);
    mail.Subject = Subject;
    mail.Body = Body;

    mail.GetInspector.Activate();
}

Go ahead and test it, create a button on your form and in the Click event handler:

private void button1_Click(object sender, EventArgs e)
{
    ShowEmail("youremailOutlookAddress.com", "Hello!", "Hey here's a test Email!");
}

OutLookMailItem how to use Outlook

A: Set the MailItem object to "objExplorer.Selection[1] as Microsoft.Office.Interop.Outlook.MailItem;" where objExplorer = AddIn name.Globals.ThisAddIn.Application.ActiveExplorer();


text:
Q: Filtrar pares em uma tupla no Python "Faça uma função chamada filtra_pares que receba uma tupla com quatro elementos inteiros como parâmetro, e retorne uma nova tupla contendo
apenas os elementos pares da tupla original, na mesma ordem em que se
encontravam."
Eu tentei fazer algo do tipo.
def pares(a,b,c,d):
    nova =()
    if a%2==0 and b%2 ==0 and c%2 ==0 and d%2 == 0:
            novafiltrada = nova+a,b,c,d
            return novafiltrada

Porém da TypeError.

A: O que você está fazendo na primeira linha de código, é pedir 4 elementos, e não uma tupla com quatro elementos.
def filtra_pares(t):
    lista = [] # Aqui se declara uma lista, pois iremos modificá-la no loop, cosia que a tupla não nos permite.
    if type(t) == tuple and len(t) == 4:
        #Se o parâmetro enviado para função, for uma tupla de quatro itens, o procedimento será feito.
         #Senão, um aviso será exibido.
        for i in t:
            #Aqui faremos um loop para cada item na tupla, caso ele não for inteiro um aviso será dado, e aquela lista inicial será limpa, para que quando o loop for parado pelo break, o resultado estar vazio.
            if type(i) != int:
                lista = []
                print('Todos os itens da tuplas devem ser inteiros.')
                break
             elif i%2 == 0:
                 #Se ele for inteiro e par, será adicionado à lista.
                 lista.append(i)
        print(tuple(lista)) #A lista é transformada em tupla e o resultado é exibido quando o loop acabar.
    else:
        print('Apenas será aceito, uma tupla, com quatro itens.')

tupla_inserida = (1,4,2,3)
filtra_pares(tupla_inserida)
#Retorno: (4,2)

O loop mantém a ordem dos elementos, então não precisamos nos preocupar com isso.


text:
Q: When trying to make a bar plot in R, I get one box. How do I get the desired result? I have a data frame read for a table that goes:
           V1           V2            V3            V4 V5
1     4.958077588 -3.265524806 12.2825957502  -9.205571807  1
2     1.203644083 -3.941877984 12.4758708139  -9.919943466  2
3     3.111368916 -4.922094042  7.8249212719  -8.662939867  1

and so on about 2000 times. I need to produce this:
what I need
but when entering this code:
 barplot(nrow(mydata), names = mydata$V5,ylab="count",space=1)

all I get is a literal box. I need a frequency count for V5. How can I get it?

A: If we are looking for frequency count, then use table and then plot on that
tbl <- table(mydata$V5)
barplot(tbl, names = names(tbl),ylab="count",space=1)

Or using ggplot
library(ggplot2)
ggplot(mydata, aes(x= V5)) +
     geom_bar(aes(y = ..count..), fill = 'darkblue') +
     xlab('class') +
     theme_bw()


text:
Q: How can I add an independent controller method with a view for confirming delete? When a resource is to be deleted in Rails' CRUD, it is standard to display a modal/popup to get user's confirmation, then call the controller method destroy. This is done by something like this:
link_to "Delete", resource_path(resource), method: :delete, confirm: "Are you sure?"

Going against this, I want to have the confirmation as an independent view page with a dedicated controller method (let's say confirm_destroy). Then deletion would follow two steps of method calls, in parallel with when a resource is created or updated:

*

*new → create

*edit → update

*confirm_destroy → destroy
I can do this relatively easily, but there is a minor difficulty such that I have to manually define the routes path for confirm_destroy while other paths can be done with a single resource(s) method.
Am I on the wrong track? What is the best way to deal with such case?

A: I think best way is to create new route and new action, because it's custom action. By default resource includes only :destroy


text:
Q: What is the best option to customize Expiration bundle? I do not want to delete documents when they expire, instead I need to move them somewhere (like database for expired documents) as I need to store them for historical purposes. What is the best way to achieve this goal in RavenDB?

*

*is there a way to change expiration bundle behavior?

*should I implement my own bundle?

*should I implement a trigger or other specific entity

*or there is other existing option I am now aware of or do not have enough knowledge to consider it as option (like replication or maybe
documents are not fully deleted in this bundle)?

A: Create your own bundle based on the logic in the expiration bundle.
That is the simplest way to handle this.


text:
Q: how to navigate without contextless I get this error when I open the App.
when I am trying to initialize the router  from authStore get this error
"You are trying to use contextless navigation without
      a GetMaterialApp or Get.key.
      If you are testing your app, you can use:
      [Get.testMode = true], or if you are running your app on
      a physical device or emulator, you must exchange your [MaterialApp]
      for a [GetMaterialApp].
      "

main.dart
@override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      navigatorKey: Get.key,
      smartManagement: SmartManagement.full,
      initialBinding: InitialBinding(),
      debugShowCheckedModeBanner: false,
      title: 'Ponte Delivery',
      initialRoute: Routers.home,
      getPages: Pages.getPages,
      theme: Themes.light,
    );
  }

class InitialBinding implements Bindings {
  @override
  void dependencies() {
    Get.lazyPut<LocalStorage>(() => LocalStorageImpl());
    Get.put<HttpClient>(HttpClientImpl(Dio()), permanent: true);
    Get.put<AuthStore>(AuthStore(Get.find<LocalStorage>()), permanent: true);

  }
}

AuthStore
 @override
  void onInit() {
    ever(isLogged, fireRoute);
    super.onInit();
    token = _storage.read(TOKEN);
    user = _storage.read(USER, construct: (map) => UserModel.fromMap(map));
    if (token == null && user == null) {
      isLogged.value = false;
    }
  }

  fireRoute(logged) {
    print(logged);
    if (!logged) {
      Get.offNamed(Routers.initialRoute);
    }
  }

I am using already GetMaterialApp.
I tried to use debugger and I got error in this Line

      Get.offNamed(Routers.initialRoute);


text:
Q: WKWebView: Remote url accessing local files I'm using Xamarin.iOS but everything is easily translatable to ObjC / Swift.
I have a WKWebView which loads a remote URL (html, js, css) that will then load mp4 videos stored locally within the app. The problem is these videos are not being loaded.
The site uses HTML 5 video tags and I'm setting the local urls by communicating C# with Javascript.
The video paths are something like this: /var/mobile/Containers/Data/Application/F535FA1C-752B-4B46-B237-6781464EE0E5/Documents/../Library/Vimeo/7b2723fa-b0f1-40c5-bc58-d43949273329.mp4.
This is my WKWebView setup:
var userController = new WKUserContentController();
userController.AddScriptMessageHandler(new iOSSiteWrapper(this.ViewModel, () => this.webView), "iOSWrapper");
var configuration = new WKWebViewConfiguration
{
    AllowsInlineMediaPlayback = true,
    UserContentController = userController
};
configuration.Preferences.JavaScriptCanOpenWindowsAutomatically = true;
configuration.Preferences.JavaScriptEnabled = true;
configuration.Preferences.SetValueForKey(NSObject.FromObject(true), new NSString("allowFileAccessFromFileURLs"));
configuration.AllowsInlineMediaPlayback = true;
configuration.AllowsPictureInPictureMediaPlayback = true;
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
    configuration.MediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypes.None;
}
else
{
    configuration.MediaPlaybackRequiresUserAction = false;
}

this.webView = new WKWebView(
    new CoreGraphics.CGRect(),
    configuration)
{
    WeakNavigationDelegate = this
};

// add to view hierarchy...

// this.ViewModel.HtmlContent is a string which contains the html page
this.webView.LoadHtmlString(this.ViewModel.HtmlContent, NSUrl.FromString(Constants.BASE_URL));

I have configured ATS exceptions in the Info.plist file.
Update
I tried loading this simple html string:
var videoToPlay = "file:///var/mobile/Containers/Data/Application/F535FA1C-752B-4B46-B237-6781464EE0E5/Documents/../Library/Vimeo/7b2723fa-b0f1-40c5-bc58-d43949273329.mp4";
var html = $"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<video id=\"video\" type=\"video/mp4\" controls=\"controls\" role=\"presentation\" width=\"305\" height=\"242\"><source id=\"source\" src=\"{videoToPlay}\"></video>
";

this.webView.LoadHtmlString(html, NSUrl.FromString(Constants.BASE_URL));

And the result is the same. The video does not play and I can see this error on the Safari output:

Not allowed to load local resource: file:///var/mobile/Containers/Data/Application/F535FA1C-752B-4B46-B237-6781464EE0E5/Documents/../Library/Vimeo/7b2723fa-b0f1-40c5-bc58-d43949273329.mp4

2nd Update
If I load the html snippet setting the local path as base url, it works:
this.webView.LoadHtmlString(html, NSUrl.FromFilename(videoToPlay));

But as I'm trying to load a remote site, I need the base url to be the remote base url. So a new question would be: is it possible to set two base urls on WKWebView?
Otherwise, do I have any option other than loading the entire site locally?

A: This is what I've done to make it work:
1) Download the html file into the local storage
2) Look for all relative urls in the html file and set the base url on them. I mean something like this: src="myvideo.mp4 --> src="https://myhomeurl.com/myvideo.mp4"
3) Use webView.LoadFileUrl instead of LoadHtmlString (I also changed the second parameter from NSUrl.FromString to NSUrl.FromFilename).


text:
Q: How do i create multiple objects for child classes using parent class constructor(super())? class Noodle {

double lengthInCentimeters;
double widthInCentimeters;
String shape;
String ingredients;
String texture = "brittle";

Noodle(double lenInCent, double wthInCent, String shp, String ingr) {

 this.lengthInCentimeters = lenInCent;
 this.widthInCentimeters = wthInCent;
 this.shape = shp;
 this.ingredients = ingr;

}

public void cook() {

 this.texture = "cooked";

}

public static void main(String[] args) {
 Pho phoChay = new Pho();
 System.out.println(phoChay.shape);

 }
}
class Pho extends Noodle {
Pho(){
 super(30.0,0.64,"flat","rice flour");
}
}

I want to create one more Pho object with different parameters how do I do it?
for eg
A lengthInCentimeters of 20.0.
A widthInCentimeters of 0.85
A shape of "inflated
ingredients of "wheat flour"

A: Just create required args constructor matching super:
public class Pho extends Noodle{

    public Pho(double lenInCent, double wthInCent, String shp, String ingr) {
        super(lenInCent, wthInCent, shp, ingr);
    }
}

So you can create all kinds of noodles you need:
public class Main {

    public static void main(String[] args) {
        Noodle pho = new Pho(30.0,0.64,"flat","rice flour");
        Noodle anotherPho = new Pho(11.0,0.33,"round","bone flour");
    }
}

A: Extend the Noodle class, have a no parameter constructor in the child class that calls the parent super constructor with the desired parameters.
Here is some sample code:
class Pho extends Noodle
{
    public Pho()
    {
        super(20.0, .85, "inflated", "wheat flour");
    }
}


text:
Q: Why does my flutter app keep crashing when loading pdf from the internet? I am building an app in flutter that reads pdf files from the internet. The package I'm using is "advance_pdf_viewer." I have followed everything as instructed in the documentation. But my app always crashes a few seconds after showing the Circular Progress Indicator Widget.
Here's is my code
//@dart=2.9
import 'package:flutter/material.dart';
import 'package:advance_pdf_viewer/advance_pdf_viewer.dart';

class PDFviewerPage extends StatefulWidget {
  const PDFviewerPage({Key key}) : super(key: key);

  @override
  _PDFviewerPageState createState() => _PDFviewerPageState();
}

class _PDFviewerPageState extends State<PDFviewerPage> {
  bool _isLoading = true;
  PDFDocument _document;

  loadDocument() async {
    setState(() {
      _isLoading = true;
    });
    final document = await PDFDocument.fromURL(
        "https://unec.edu.az/application/uploads/2014/12/pdf-sample.pdf");
    setState(() {
      _document = document;
      _isLoading = false;
    });
  }

  @override
  void initState() {
    super.initState();
    loadDocument();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Example'),
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : PDFViewer(document: _document),
    );
  }
}

Also, I have these permissions enabled in my manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

This is the error message returned in my debug console
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: MissingPluginException(No implementation found for method getPage on channel flutter_plugin_pdf_viewer)
What could be the cause of the consistent crashing? And how do I fix it?

A: I had the same issue, the only thing that worked for me so far was using the previous version of the package:
(on pubspec.yaml)
advance_pdf_viewer: 2.0.0

A: Not sure if it is still actual. Here is what I have tried, according to https://github.com/lohanidamodar/pdf_viewer/issues/117#issuecomment-1259538440 temporary solution could be updating pubspec.yaml file with the following changes:
Replace the following line:
advance_pdf_viewer: ^2.0.1

with:
  advance_pdf_viewer:
    git:
      url: https://github.com/lohanidamodar/pdf_viewer.git
      ref: 4e5d96be29de515f1081c0b6897741b8dca84722

Moreover, there is also another solution using https://pub.dev/packages/advance_pdf_viewer_fork package which doesn't have current issue.

A: I actually solved the issue by replacing the package to flutter_pdfview: ^1.2.1


text:
Q: Why won't this semi circle grow? Basically,
I have two semi-circles. One(circle0) is of constant radius and the inner semi-circle(circle1, with gradient) is of variable radius. circle1 has initial value of 1% radius of circle0.
I want to input a value in the target box(0-100) for the new radius of circle1. I have put an interval of 100ms for a 1% step in radius of circle1 to show it growing but it doesn't seem to work.
I am not very good at javascript/jquery but any help is greatly appreciated.
See demo here: https://jsfiddle.net/nilerafter24/ma845o6d/3/
Here is my javascript:
$(document).ready(function() {
    function circle_set(delta) {
        if (!delta) {
            return false;
        } else {
            var e = document.querySelectorAll('circle[id^=circle]');
            var radius0 = parseInt(e[0].getAttribute('r'), 10);
            var radius1 = parseInt(e[1].getAttribute('r'), 10);
            var currentRadius = (delta / 100) * 50;

            if (currentRadius <= radius0) {

                setTimeout(function() {
                    if (radius1 <= currentRadius) {
                        radius1++;
                        e[1].setAttribute('r', String(radius0) + "%");
                    },
                }, 100);
            }
        }
    }

    var inputTargetButton = document.getElementById('executeTarget');
    var inputTargetValue = document.getElementById('setTarget');

    if (inputTargetButton.type == 'button') {
        inputTargetButton.onclick = function() {
            circle_set(inputTargetValue.value)
        }
    }
});

Edit:
Corrected big mistake.Changed radius0 to radius1. Need more coffee.

A: you have to use setInterval for your function, also your condition is incorrect. work this JsFiddle
setInterval(function() {
    if (radius1 <= currentRadius) {
        radius1++;
        e[1].setAttribute('r', String(radius1) + "%");
    }
}, 100);

A: First, what you have is increasing the radius of the larger semicircle, radius0. You want to increase radius1 and apply that to circle1.
Second thing is that setTimeout() will only call the function once. You need to use setInterval() to call the function every 100ms. But, since you don't want it to continue calling after the radius has reached currentRadius, you should clear it at that point using clearInterval():
if (currentRadius <= radius0) {
    var timer = setInterval(function() {
        if (radius1 <= currentRadius) {
            radius1++;
            e[1].setAttribute('r', String(radius1) + "%");
        }
        else {
            clearInterval(timer);
        }
    }, 100);
}

Check out this working fiddle: https://jsfiddle.net/q4ns6q0m/1/

A: From what I tested, in this code:
if (radius0 <= currentRadius) {
   radius0++;
   e[1].setAttribute('r', String(radius0) + "%");
  },
}

the if condition is never satisfied.


text: Q: Using the locally installed JDK for all Bazel operations Normally Bazel downloads Java compilers from the internet and runs them to compile code. I am using Bazel in a restricted environment that doesn't allow running these downloaded binaries. I have an approved JDK v8 and Bazel installed locally. How do I configure Bazel to use this locally installed JDK for everything (running Bazel, compiling code, running tests, etc)?


text:
Q: cant install vis on node red i want to install vis on node-red but when i run npm install node-red-vis i get the following error:
npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.
npm WARN deprecated json3@3.3.2: Please use the native JSON object instead of JSON 3
npm WARN deprecated debug@4.1.1: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (https://github.com/visionmedia/debug/issues/797)
npm ERR! code 1
npm ERR! path C:\Users\Julius\node_modules\node-red-vis
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c node node_modules/iobroker.vis/lib/install.js
npm ERR! node:internal/modules/cjs/loader:936
npm ERR!   throw err;
npm ERR!   ^
npm ERR!
npm ERR! Error: Cannot find module 'C:\Users\Julius\node_modules\node-red-vis\node_modules\iobroker.vis\lib\install.js'
npm ERR!     at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
npm ERR!     at Function.Module._load (node:internal/modules/cjs/loader:778:27)
npm ERR!     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
npm ERR!     at node:internal/main/run_main_module:17:47 {
npm ERR!   code: 'MODULE_NOT_FOUND',
npm ERR!   requireStack: []
npm ERR! }

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Julius\AppData\Local\npm-cache\_logs\2022-07-26T07_05_03_773Z-debug-0.log

System: Windows 11 Pro 22H2
node.js: v16.16.0
complete log:
https://1drv.ms/u/s!ApGMjAYcI9vviXNSvRkENmVYE6IY?e=NOeIwR


text:
Q: How to draw at PictureBox from another Thread? I have a Form and a PictureBox that located on it. I want to draw some kind of a background in this PictureBox (just array of dots that located at specific order) when my PictureBox is updating. Code for drawing works fine, but it's take so much time(cause i'm drawing so many dots) and i can't works normally with that form, cause program is waiting till all the dots will be drawned. So i decide to draw this dots at the separate Thread, like this:
private void flowchartDrawingArea_Paint(object sender, PaintEventArgs e)
{
    Thread thread = new Thread(() => DrawBackground(sender, e));
    thread.Start();
}

private void DrawBackground(object sender, PaintEventArgs e)
{
    GridBackground.GetAreaSize((Control)sender);
    GridBackground.Draw(e);
}

And my drawing class looks like this:
class GridBackground
{
    /*...*/
    public void Draw(PaintEventArgs e)
    {
        int positionWidth = 0;
        int positionHeight = 0;

        while (positionHeight < PanelHeight)
        {
            while (positionWidth < PanelWidth)
            {
                Rectangle rectangle = new Rectangle(positionX, positionY, R, R);
                e.Graphics.FillEllipse(Brushes.White, rectangle);
                e.Graphics.DrawEllipse(new Pen(Color.Gray, 2), rectangle);
                positionWidth += DotInterval;
            }
            positionHeight += DotInterval;
            positionWidth = 0;
        }
    }
}

but i always have a "parameter not valid" exception at "e" at e.Graphics.FillEllipse(Brushes.White, rectangle); string. I read that this happens when trying to do something with form controls from other thread, but i don't know how to solve it in my case.

A: If you just want to defer the drawing to another thread, you can use a back buffer. The basic idea is to do all the rendering to an off-screen Bitmap, and after you're done, let the UI thread draw this back buffer on the actual PictureBox.
There's plenty of optimizations you can do, too. If your code isn't fast enough to render aesthetic features in realtime, that's a problem for a UI, and delegating the rendering to a different thread is just hiding that problem. For example:

*

*Instead of doing FillEllipse and DrawEllipse in a loop, render the ellipse once into a bitmap, and then keep doing DrawImage instead. That's going to be much faster.

*Respect the regions being redrawn in the Paint event handler. You're often asked only for a partial redraw, and you're wasting your CPU always redrawing everything.

*If you need to handle scrolling, try using as much of the existing back buffer as possible. Drawing the backbuffer with an offset will give you the same appearance much cheaper.

*In fact, you can even draw entire rows at once, and multiples of rows. Again, it's much faster to draw three bitmaps than to draw 200 individual ellipses.

A: Is flowchartDrawingArea your pictureBox name?
You can try this code.
Thread thread = new Thread(() => flowchartDrawingArea.BeginInvoke(new Action<object, PaintEventArgs>((o, args) => { DrawBackground(o, args); }), sender, e));
thread.Start();


text:
Q: Rails: How to setup routes that mimic Flickr's URL schema I'd like for my URLs to look like this (similar to how Flickr has theirs set up).
/photos/username
/videos/username
/blogs/username
/photos/username/12345
/videos/username/12345
/blogs/username/12345

Is there a way to set those up as resources in my routes file instead of having to do a bunch of custom routes?
In the case of the /photos/username/12345 URLs...the username isn't necessary but I think makes the URLs more readable.
NOTE: I'm using Rails 2.3.10

A: Just make some regular non-RESTful routes
map.connect ":controller/:username", :action => :index
map.connect ":controller/:username/:id", :action => :show

This will route /photos/shpigford to the index action on PhotosController and put :username => "shpigford" in the params hash. The second line will route a URL with an id, like /videos/edgerunner/35467 to the show action on VideosController and put :username => "edgerunner", :id => "35467" in the params hash.
You may want to constrain these routes a bit, so that they don't accidentally match other similar routes. You may also want to add named routes. A more elaborate setup would be:
map.with_options :controller => /photos|videos|blogs/,
                 :username => /[-a-z0-9]+/,
                 :conditions => { :method => :get } do |route|
  route.user_assets ":controller/:username",     :action => :index
  route.user_asset  ":controller/:username/:id", :action => :show, :id => /\d+/
end

The with_options block applies its options to all the route definitions inside it, so that we don't have to repeat them every time. What this does, in addition to the basic setup above, is;

*

*Makes sure that the first segment is one of the three controllers we have (Otherwise it would happily accept /zombies/fandango and try to execute the index action of a nonexistent ZombiesController to fail miserably)

*Makes sure that the second segment(username) consists only of lowercase ASCII letters, numbers and dash.

*Accepts only HTTP GET requests. POST, PUT and DELETE aren't welcome.

*Defines these routes as named routes so that you can call user_assets_path(:photos,'edgerunner') in your views to render /photos/edgerunner

*Makes sure the third segment(id) digits only, so it does not match /photos/clouds/nimbus


text:
Q: Loaded event before OnApplyTemplate I was under the impression that listening to the Loaded event will make sure that I can access the visual tree at that point. This seems to work fine in most situations and the visual tree is what I expect it to be. However when using a TabControl, controls on hidden tabs do not get their visual tree constructed before the loaded event fires.
Take this simple example:
<Window ...>
    <Grid>
        <TabControl>
            <TabItem Header="Tab 1">
                <my:MyTextBox />
            </TabItem>
            <TabItem Header="Tab 2">
                <my:MyTextBox />
            </TabItem>
        </TabControl>
    </Grid>
</Window>

MyTextBox is a custom component, that just logs out when certain events occur.
public class MyTextBox : TextBox
{
    public MyTextBox()
    {
        Loaded += (s,e) => {
            Console.WriteLine("MyTextBox {0}: Loaded", s.GetHashCode());
            Dispatcher.BeginInvoke(()=>Console.WriteLine("MyTextBox {0}: Loaded BeginInvoke", s.GetHashCode()));
        };
    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        Console.WriteLine("MyTextBox {0}: OnApplyTemplate", this.GetHashCode());
    }
}

And this is the output:
MyTextBox A: OnApplyTemplate
MyTextBox A: Loaded
MyTextBox B: Loaded
MyTextBox A: Loaded BeginInvoke
MyTextBox B: Loaded BeginInvoke
(changing tab to 2)
MyTextBox B: OnApplyTemplate
MyTextBox B: Loaded
MyTextBox B: Loaded BeginInvoke

As you can see, for B, which is on the second tab, OnApplyTemplate is only executed when you switch to its tab, but the loaded event is actually raised before.
The problem is now that my custom component is a look-less component that has its control template set. In the loaded event I now want to go through the visual tree and apply some additional default values, but as the template was not applied yet, the visual tree is empty.
Is there some way, from the outside (i.e. without modifying the component), to make sure that I can iterate through the visual tree as soon as it is loaded?

A: The TabControl does some virtualization under the hood.
You can disable this as per answers in this SO question:
How to preserve control state within tab items in a TabControl


text:
Q: Google Cloud Shell gcloud commands output not pretty printed anymore I was using GCloud Shell a few weeks ago and got pretty printed outputs from gcloud commands, like so:
DISPLAY NAME                            EMAIL                                                 DISABLED
Compute Engine default service account  XXXXXXXXXXXX-compute@developer.gserviceaccount.com    False
sa-xxxxxxxxx                            sa-xxxxxxxxx@my-project.iam.gserviceaccount.com       False

Since a few days, output is not anymore pretty printed:
DISPLAY NAME: Compute Engine default service account
EMAIL: XXXXXXXXXXXX-compute@developer.gserviceaccount.com
DISABLED: False

DISPLAY NAME: sa-xxxxxxxxx
EMAIL: sa-xxxxxxxxx@my-project.iam.gserviceaccount.com
DISABLED: False

I checked embedded gcloud SDK version:
$ gcloud -v
Google Cloud SDK 360.0.0
alpha 2021.10.04
app-engine-go 1.9.71
app-engine-java 1.9.91
app-engine-python 1.9.95
app-engine-python-extras 1.9.95
beta 2021.10.04
bigtable
bq 2.0.71
cbt 0.10.1
cloud-build-local 0.5.2
cloud-datastore-emulator 2.1.0
core 2021.10.04
datalab 20190610
gsutil 5.3
kind 0.7.0
kpt 1.0.0-beta.5
local-extract 1.3.1
minikube 1.23.2
pubsub-emulator 0.5.0
skaffold 1.32.0

I also checked the documentation on output formats, which isn't of any help. Tried several outputs without being able to have a pretty one like before.
I tried installing the SDK 360.0.0 on Cloud Shell, which gives me the pretty output as before…
Anyone else having this issue? Or knowing how to get the pretty print as before (without having to manually install gcloud SDK)?
Edit:
As asked by John Hanley, here is the output of gcloud config list:
[accessibility]
screen_reader = True
[component_manager]
disable_update_check = True
[compute]
gce_metadata_read_timeout_sec = 30
[core]
account = nicolas@mydomain.com
disable_usage_reporting = True
project = my-project
[metrics]
environment = devshell

Your active configuration is: [cloudshell-25102]

Column width as given by tput cols is 267.

A: Thanks to @JohnHanley for the insight of gcloud config list, I compared the configurations between embedded gcloud and the downloaded version, then read some documentation to find that this behavior is only due to an accessibility option which is now set to true by default.
For anyone having this issue, here is the command to get the good ol' pretty print output back:
gcloud config set accessibility/screen_reader false

If you want it to persist between Cloud Shell reboots, add the --installation flag and use sudo.


text:
Q: How to output sound through HDMI adapter (late 2008 Macbook)? Is there a workaround that allows the laptop to send sound to a projector, such as using a different type of adapter?

A: There are Mini DisplayPort / USB to HDMI adaptors. The Mini DisplayPort provides the video and the USB supplies the sound.
For example:
newertechnology
Monoprice
StarTech


text:
Q: How can I remove left UIBarButtonItem's background I tried to remove the background of the left UIBarButtonItem's background.

My image is just the icon with the lines. But there is black background.
My code is:
paneViewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"menuicon"] style:UIBarButtonItemStylePlain target:self action:@selector(navigationPaneBarButtonItemTapped:)];
paneViewController.navigationItem.leftBarButtonItem.tintColor = [UIColor clearColor];

Where am I wrong?
Update:
UIImage *myImage = [UIImage imageNamed:@"menuicon"];
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton setImage:myImage forState:UIControlStateNormal];
myButton.showsTouchWhenHighlighted = YES;
myButton.frame = CGRectMake(0.0, 0.0, myImage.size.width, myImage.size.height);

[myButton addTarget:self action:@selector(navigationPaneBarButtonItemTapped:) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithCustomView:myButton];
paneViewController.navigationItem.leftBarButtonItem = leftBarButton;

That worked for me. Thanks

A: Create the object as a UIButton (do all the usual setup; frame, target, background image... etc) and then call initWithCustomView: on the UIBarButtonItem instead.

A: this works as well:
UIBarButtonItem *navButton = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navbutton.png"]
                                                                  style:UIBarButtonItemStylePlain
                                                                 target:self
                                                                 action:@selector(buttonPressed)] autorelease];

NSArray *buttonArray = [NSArray arrayWithObjects:navButton, nil];

TransparentToolbar *toolbar = [[[TransparentToolbar alloc] initWithFrame:CGRectMake(0.0f, 0.0, 44.0f, 44.0f)] autorelease];
toolbar.items = buttonArray;

UIBarButtonItem *controls = [[[UIBarButtonItem alloc] initWithCustomView:toolbar] autorelease];
self.navigationItem.rightBarButtonItem = controls;


text:
Q: Matching a question mark in .htaccess I'm trying to set up some 301 redirects for old Kayako helpdesk URL's. The old URL's were;
example.com/index.php?/rest_of_url
I've set up rewriting so the URL's are prettier example.com/rest_of_url, and I'm trying to 301 redirect all old URL's to new. I've tried the following but they don't appear to work;
RewriteRule ^index.php?/(.*)?$ /$1 [R=301,L]

RewriteRule ^index.php\?/(.*)?$ /$1 [R=301,L]

RewriteRule ^index.(.*)/(.*)?$ /$2 [R=301,L]

I can't quite figure it out.
EDIT:
Here is the whole .htaccess file
<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{QUERY_STRING} ^/(.*)$
RewriteRule ^index\.php$ /%1? [R=302,L]

RewriteCond $1 !^(admin|api|console|favicon\.ico|robots\.txt|sitemap\.xml|index\.php|tiny_mce_gzip\.php|cron|onsite|staff|rss|setup|visitor|winapp|wallboard|__swift) [NC]
RewriteCond $1 !\.(jpg|jpeg|png|gif|js|css|htm|html)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

RewriteCond $1 !^(favicon\.ico|robots\.txt|sitemap\.xml|index\.php|tiny_mce_gzip\.php|__swift) [NC]
RewriteCond $1 !\.(jpg|jpeg|png|gif|js|css|htm|html)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9]*)/(.*)$ $1/index.php?/$2 [L]
</IfModule>

A: The part after the question mark is not in the RewriteRule url.
You have to use %{QUERY_STRING}:
RewriteCond %{QUERY_STRING} ^/(.*)$
RewriteRule ^index\.php$ /%1? [R=301,L]

%1is the first (.*) in the last RewriteCond.
In your case, without loop, use:
RewriteCond %{THE_REQUEST} \s/+index\.php\?([^\s&]+) [NC]
RewriteRule ^ /%1? [R=302,L,NE]


text:
Q: SQ L - how to select the next latest 10 records from a specified position in a table? I have a table of pdf titles in a MYSQL database and I am trying to load these dynamically onto my website only 10 at a time as the user scrolls down to the bottom of the page.  I am ok with the ajax request but I am stuck on the SQL statement required to capture the next 10 titles from a specified position in the table.
Let us say the last loaded title had an ID of 10.
My SQL attempt:
 SELECT titles FROM pdfLibrary ************ ORDER BY DATE ASC LIMIT 10

I would like some help finishing this SQL statement.

A: You can use LIMIT with an OFFSET, e.g.
SELECT titles
FROM pdfLibrary
ORDER BY DATE ASC
LIMIT 10 OFFSET 10

Programatically, you would replace OFFSET 10 with OFFSET ID, assuming you wanted to use the ID to keep track of where you were in your count.

A: You can use 2 parameters with the Limit for example if you want to get result 10 to 20
SELECT titles FROM pdfLibrary ORDER BY DATE ASC LIMIT 10,20;

this will return you to records of 10 to 20


text:
Q: How to get a js object from a DIV? How can I get the google maps object from my DIV?
This is what I did to set the map:
var map = new google.maps.Map(document.getElementById("map_canvas"),
          mapOptions);

Then I want to get the map to do this:
var marker = new google.maps.Marker({
  position: initialLocation,
  map: document.getElementById("map_canvas"),
  title:"AJAX!"
});

Of course this produces an error.

Uncaught Error: Invalid value for property  : [object HTMLDivElement]

A: I guess if it expects a map object then you need to keep track of that map object so you can use it in other functions. Something like:
var map;

function CreateMap(){
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}

function AddMarker(){
    var marker = new google.maps.Marker({
      position: initialLocation,
      map: map,
      title:"AJAX!"
    });
}


text:
Q: DNS resolution stops working with Apache2.4.7/PHP5.5.9 until restart I have a problem that has just started over the last few days. The server has been running and working great for over two years.
In my PHP application, I connect to S3 and Sendgrid. This week I've started getting the following errors:

Connection could not be established with host smtp.sendgrid.net [php_network_getaddresses: getaddrinfo failed: No address associated with hostname #0]

DNS works fine on the command line and it works in the app after I restart Apache.
I restarted Apache yesterday but we started getting errors again today. Nothing had changed, no restarts or anything. There is nothing in the Apache error log to indicate anything has happened.
Server Details:

*

*Linode 1024 VPS

*Ubuntu 14.04 LTS

*Apache 2.4.7

*PHP 5.5.9


text:
Q: HTML5 video controls dissappears when video start playing I have html5 video player displaying a video on a mobile device. Immediately the video has started playing the controls dissappears and doesn't appear until the video has finished playing. This is my video code
<video height="350px" width="350px" ng-src="{{post.Video}}" controls="controls"></video>

Please how do I make the controls display on the video especially when it is playing?

A: It just needs a little love:
<video height="350px" width="350px" stay-with-me-please="true"></video>

Let us know how that works ;)


text:
Q: Export telerik RadGrid to PDF I have a Telerik RadGrid with NestedViewTemplate, when exporting it to PDF, it results in a corrupted file.
<NestedViewTemplate>

        <%# Eval("Notes") %>

</NestedViewTemplate>

Edit: the same grid but without this column (NestedViewTemplate) works fine and the export results in a well-formatted pdf file

A: I got it!
There is an exception log says:

Invalid XHTML. RadGrid has to render correct XHTML in order to export to PDF.  Parse error:  The 'br' start tag on line 778 position 6734 does not match the end tag of 'span'...

The note contains some HTML tags and the
 tag is not valid XHTML tag, So, I replaced every
 by
, and it works properly now


text:
Q: Pandas Change To_SQL Column Mappings I have a slight problem in regards to pd.to_sql(). My task is to load excel files into a MSSQL database (import wizard is not an option). I've used sqlalchemy along with pandas in the past with success but can't seem to crack this.
from sqlalchemy import create_engine
import pandas as pd

# Parameters for SQL
ServerName = "SERVER_NAME_HERE"
Database = "MY_NAME_HERE"
Driver = "driver=SQL Server Native Client 11.0"

# Create the connection
engine = create_engine('mssql+pyodbc://' + ServerName + '/' + Database + "?" + Driver)

df1=read_excel('MY_PATH_HERE')
# do my manipulations below and make sure the dtypes are correct....

#... end my manipulations
df2.to_sql('Auvi-Q_Evzio_Log', engine, if_exists='append', index=False)

ERROR:
pyodbc.ProgrammingError: ('42S22', "[42S22] [Microsoft][SQL Server Native
Client 11.0][SQL Server]Invalid column name 'Created On'. (207)
(SQLExecDirectW)")

My issue is that the schema of the database is already set up and cannot change it. I have a column in my dataframe Created On, but the column name in the Database is CreatedOn. I have a handful of columns where this issue arises. Is there a way to set the mappings or schema correctly in to_sql? there is a schema parameter in the documentation, but I can't find a valid example.
I could just change the column names of my dataframe to match the scehma, but my interest has been peeked otherwise.

A: I'd try the following approach:
db_tab_cols = pd.read_sql("select * from [Auvi-Q_Evzio_Log] where 1=2", engine) \
                .columns.tolist()

df2.columns = db_tab_cols
df2.to_sql('Auvi-Q_Evzio_Log', engine, if_exists='append', index=False)

PS this solution assumes that df2 has the same order of columns as Auvi-Q_Evzio_Log table


text:
Q: Obter nome em Select Join Vejam a seguinte função:
$id_contratos = array_map(function($item)
{ return $item['id'];}, $result['contratos']);

$empresa = " -- aqui eu preciso recuperar o nome da empresa --";
$view["empresa"] = $empresa;

E a tabela com os seguintes campos:
DROP TABLE IF EXISTS `tbl_devedor_contrato`;
CREATE TABLE IF NOT EXISTS `tbl_devedor_contrato` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`plano` VARCHAR(10) NULL DEFAULT NULL,
`contrato` VARCHAR(60) NOT NULL,
`dt_contrato` DATE NULL DEFAULT NULL,
`dt_expiracao` DATE NULL DEFAULT NULL,
`devedor_id` INT(11) NULL DEFAULT NULL,
`empresa_id` INT(11) NULL DEFAULT NULL,
`importacao_id` INT(11) NULL DEFAULT NULL,
`crud` VARCHAR(2) NULL DEFAULT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 1;

Sabendo que o id da tabela tbl_devedor_contrato é igual a $id_contratos, eu quero recuperar a informação do campo empresa_id desta mesma tabela e tendo a informação deste campo, eu preciso utiliza-lo para fazer um join e obter o nome_fantasia da empresa, referente ao int obtido em empresa_id.
Sei que precisaria fazer primeiro um select e depois um join, mas já tentei e não deu certo.
Abaixo a tabela, para obter o nome_fantasia
DROP TABLE IF EXISTS `tbl_empresa`;
CREATE TABLE IF NOT EXISTS `tbl_empresa` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`cnpj` varchar(20) NOT NULL,
`nome_fantasia` varchar(255) NOT NULL,
`razao_social` varchar(255) NOT NULL,
`cep` varchar(8) DEFAULT NULL,
`logradouro` varchar(160) DEFAULT NULL,
`numero` varchar(20) DEFAULT NULL,
`complemento` varchar(60) DEFAULT NULL,
`bairro` varchar(60) DEFAULT NULL,
`cidade` varchar(60) DEFAULT NULL,
`uf` varchar(2) DEFAULT NULL,
`telefone` varchar(10) DEFAULT NULL,
`email` varchar(160) DEFAULT NULL,
`id_assessoria` INT(11) NOT NULL,
`dt_cadastro` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`dt_atualizacao` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`situacao` TINYINT(1) NULL DEFAULT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
DEFAULT CHARSET = utf8;

Variável de $result['contratos']:
Array
(
[0] => Array
     (
        [id] => 1
        [plano] => 4
        [contrato] => 93642059600
        [dt_contrato] => 2017-11-01
        [dt_expiracao] => 2017-11-30
        [devedor_id] => 1
        [empresa_id] => 1
        [importacao_id] => 0
        [crud] => R
    )
)

A: Para que você consiga fazer isto no codeigniter, basta usar o JOIN na sua função de retorno dos dados, da seguinte maneira:
public function get_devedor_contrato(){
    $this->db->select("tbl_devedor_contrato.*, tbl_empresa.razao_social");
    $this->db->join("tbl_empresa", "tbl_empresa.id=tbl_devedor_contrato.empresa_id");
    return $this->db->get('tbl_devedor_contrato')->result();
}


text:
Q: After Update of R and dplyr running time for dplyr::group_by function increases I was recently running a R script developed under R 3.2.2 version with dplyr 0.5.0 under R 3.5.1 using dplyr 0.7.6. To my surprise the code took approximately 100 times longer to run than usual, which I traced to the use of the group_by function in the following expression where I:
matches=as.data.frame(df %>%
                       group_by(id) %>%
                       filter(living_quarters >= matching_living_quarters,
                              abs(age-matching_age) <= 4,
                              index<matching_index-lag_time,
                              sex==matching_sex) %>%
                       mutate(matched_id=matching_id))

I couldn't find any reason so far why the run time would be so much worse. Did group_by lead to parallel processing in earlier versions or does anybody have an insight why this staight forward use would be processed much slower by the updated version?


text:
Q: SCP not exiting on failure (on latest Ubuntu and Linux Alpine) I am using latest Linux Alpine (3.6) as OS in a docker container (also tested on Ubuntu 16.10 outside of Docker with same result).
I have installed openssh (apk add openssh).
Here is my command :
scp -i $KEY_PATH -P $PORT -o StrictHostKeyChecking=no $USER@$HOST:$FILENAME .

When scp successfully copies a file, it exists with 0 (expected).
When the file is not found, scp says : No such file or directory but does not exits. What can I do to get a proper exit with a non 0 code ? Could it be a problem on the server or network ?


text:
Q: API Java and PHP with URL call To API Java code with PHP, and connect a Java frontend with a PHP backend that will connect to a database, you just call the PHP file's URL in the code, correct?
URL url = new URL("http://10.0.3.2/MYCODE/app/login.php");

String urlParams = "name="+name+"&password="+password;

HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();

A: public String login(String name ,String password) {
StringBuilder sURL = new StringBuilder(100);
        StringBuilder sb1 = new StringBuilder();
        System.out.println("FF:"+pathReader);
        try {
            sURL.append("http://10.0.3.2/MYCODE/app/login.php?");
            sURL.append("name="+name);
            sURL.append("&password="+password);
            InputStream is = new URL(sURL.toString()).openStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            int cp;
            while ((cp = rd.read()) != -1) {
                sb1.append((char) cp);
            }

            }
        catch (Exception me) {
            System.out.println("## Exception :" + me.getMessage());
        }
        sb1.toString();
        }


text:
Q: Materialized view vs table - performance I am quite new to Redshift but have quite some experience in the BI area. I need help from an expert Redshift developer. Here's my situation:
I have an external (S3) database added to Redshift. This will suffer very frequent changes, approx. every 15 minutes. I will run a lot of concurrent queries directly from Qlik Sense against this external DB.
As best practices say that Redshift + Spectrum works best when the smaller table resides in Redshift, I decided to move some calculated dimension tables locally and leave the outer tables in S3. The challenge I have is if it's better suited to use materialized views for this or tables.
I already tested both, with DIST STYLE = ALL and proper SORT KEY and the test show that MVs are faster. I just don't understand why that is. Considering the dimension tables are fairly small (<3mil rows), I have the following questions:

*

*shall we use MVs and refresh them via scheduled task or use table and perform some form of ETL via stored procedure (maybe) to refresh it.

*if table is used: I tried casting the varchar keys (heavily used in joins) to bigint to force encoding to AZ64, but queries perform worse than without casting (where encode=LZO). Is this because in the external DB it's stored as varchar?

*if MV is used: I also tried above casting in the query behind MV, but the encoding says NONE (figured out by checking the table created behind the scene). Moreover, even without casting, most of the key columns used in joins have no encoding. Might it be that this is the reason why MVs are faster than table? And should I not expect the opposite - no encoding = worse performance?

Some more info: in S3, we store in the form of parquet files, with proper partitioning. In Redshift, the tables are sorted against the same columns as S3 partitioning, plus some more columns. And all queries use joins against these columns in the same order and also a filter in the where clause on these columns. So the query is well structured.
Let me know if you need any other details.