text:
Q: How to add number in array (in brackets) on pyspark Here's my dataframe
+--------------------+--------------------+--------------------+--------------------+--------------------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
|                 ifa|           longitude|            latitude|          first_seen|           last_seen|hour_00|hour_01|hour_02|hour_03|hour_04|hour_05|hour_06|hour_07|hour_08|hour_09|hour_10|hour_11|hour_12|hour_13|hour_14|hour_15|hour_16|hour_17|hour_18|hour_19|hour_20|hour_21|hour_22|hour_23|
+--------------------+--------------------+--------------------+--------------------+--------------------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+
|00000000-240f-e42...|          [106.6284]|            [-6.177]|[2021-06-18 02:35...|[2021-06-18 02:35...|    [0]|    [0]|    [0]|    [0]|    [0]|    [0]|    [0]|    [0]|    [0]|    [0]|    [0]|    [0]|    [0]|    [0]|    [0]|    [0]|    [0]|    [0]|    [0]|    [1]|    [0]|    [0]|    [0]|    [0]|
|00045a11-3666-48b...|[103.519611, 103....|[-3.779082, -3.78...|[2021-06-17 18:39...|[2021-06-17 18:44...| [0, 0]| [0, 0]| [0, 0]| [0, 0]| [0, 0]| [0, 0]| [0, 0]| [0, 0]| [0, 0]| [0, 0]| [0, 0]|[55, 0]| [0, 0]| [0, 0]| [0, 0]| [0, 0]| [0, 0]| [0, 0]| [0, 4]| [0, 0]| [0, 0]| [0, 0]| [0, 0]| [0, 0]|
+--------------------+--------------------+--------------------+--------------------+--------------------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+

Here's my code
%%time
A = A.withColumn('Morning', (col('hour_05') + col('hour_06') + col('hour_07')))
A = A.withColumn('Office Hour', (col('hour_08')+ col('hour_09') + col('hour_10') + col('hour_11') + col('hour_12')+ col('hour_13') + col('hour_14') + col('hour_15') + col('hour_16') + col('hour_17')))
#A = A.withColumn('Lunch Time', (col('hour_12')+ col('hour_13')))
A = A.withColumn('After Office', (col('hour_18')+ col('hour_19') + col('hour_20') + col('hour_21') + col('hour_22') + col('hour_23')))
A = A.withColumn('Bed Time', (col('hour_00')+ col('hour_01') + col('hour_02') + col('hour_03') + col('hour_04') + col('hour_22') + col('hour_23')))

Here's the error message
AnalysisException: "cannot resolve '(`hour_05` + `hour_06`)' due to data type mismatch: '(`hour_05` + `hour_06`)' requires (numeric or calendarinterval) type, not array<bigint>;;\n'Project [ifa#1, longitude#24, latitude#25, first_seen#26, last_seen#27, hour_00#28, hour_01#29, hour_02#30, hour_03#31, hour_04#32, hour_05#33, hour_06#34, hour_07#35, hour_08#36, hour_09#37, hour_10#38, hour_11#39, hour_12#40, hour_13#41, hour_14#42, hour_15#43, hour_16#44, hour_17#45, hour_18#46, ... 6 more fields]\n+- Filter isnotnull(hour_00#28)\n   +- Project [ifa#1, gps#7.longitude AS longitude#24, gps#7.latitude AS latitude#25, gps#7.first_seen AS first_seen#26, gps#7.last_seen AS last_seen#27, gps#7.hour_00 AS hour_00#28, gps#7.hour_01 AS hour_01#29, gps#7.hour_02 AS hour_02#30, gps#7.hour_03 AS hour_03#31, gps#7.hour_04 AS hour_04#32, gps#7.hour_05 AS hour_05#33, gps#7.hour_06 AS hour_06#34, gps#7.hour_07 AS hour_07#35, gps#7.hour_08 AS hour_08#36, gps#7.hour_09 AS hour_09#37, gps#7.hour_10 AS hour_10#38, gps#7.hour_11 AS hour_11#39, gps#7.hour_12 AS hour_12#40, gps#7.hour_13 AS hour_13#41, gps#7.hour_14 AS hour_14#42, gps#7.hour_15 AS hour_15#43, gps#7.hour_16 AS hour_16#44, gps#7.hour_17 AS hour_17#45, gps#7.hour_18 AS hour_18#46, ... 5 more fields]\n      +- Relation[id#0,ifa#1,source#2,device#3,app#4,connection#5,geoip_connection#6,gps#7,geoip_location#8,user#9,brq_count#10L,day#11] parquet\n"

A: First you should add elements of each array column before taking sum of array columns.
You can use higher order built-in function aggregate to take sum of elements of an array.
Example:
>>> df = spark.createDataFrame(([1,2],[5,6]),"array<int>").withColumn("c2",array(lit(1)))
>>> df.show()
+------+---+
| value| c2|
+------+---+
|[1, 2]|[1]|
|[5, 6]|[1]|
+------+---+

>>> df.withColumn("array_sum",aggregate("value",lit(0),lambda x,y:x+y)+aggregate("c2",lit(0),lambda x,y:x+y)).show()
+------+---+---------+
| value| c2|array_sum|
+------+---+---------+
|[1, 2]|[1]|        4|
|[5, 6]|[1]|       12|
+------+---+---------+


text:
Q: Usages of "Let" in the cases of 1) Antecedent Assumption, 2) Existential Instantiation, and 3) Labeling A practice problem led me to produce the following statement (the below result is specific to the practice problem):

For any non-empty interval $I$ (open or closed) in $\mathbb R$: $\forall a,b \in I \left[f(a)=f(b) \right]$

It seemed intuitive that I could conclude the function $f$ was constant over the interval $I$. In attempt to be more formal, I constructed the following claim:
$$\forall a,b \in I \left[f(a)=f(b) \right] \rightarrow \exists C \in \mathbb R \text{ s.t. } \forall x \in I \left [f(x)=C \right]$$
For the purpose of my question, I am going to expand the universal statements into their "full" form and use some color coding:
$$\color{blue}{\forall a,b \big( a \in I \land b \in I} \rightarrow f(a)=f(b) \big) \rightarrow \color{red}{\exists C} \in \mathbb R \text{ s.t. } \color{orange}{\forall x \big ( x \in I} \rightarrow f(x)=C \big)$$
Here is how I would prove this statement:

*

*$I$ is a non-empty set and therefore $\exists y \in I$

*$\color{red}{\text{Let }y} \text{ be an arbitrary element of } I$.

*$\color{orange}{\text{Let  }x } \text{ be an arbitrary element of } I$.

*By our $\color{blue}{\text{assumption}}$, we then conclude that $f(x)=f(y)$.

*Let $f(y)$ be represented by the symbol $C$...i.e. $C=f(y)$.

*Therefore, $f(x)=C$.

*$x$ was arbitrary so we can generalize to all $x$ in $I \quad \square$

I have a series of questions about Step 2, Step 3, and Step 5. I very purposely used the same verb  "let" for the three different statements...because I have encountered all such usages of this word. I apologize in advanced if the proper math jargon that is germane to this question is lacking.
Firstly, although Step 2 and Step 3 are both introducing symbols with the same feature of belonging to the non-empty interval $I$, these two steps seem fundamentally different to me. The ability to bring the object $x$ into the argument seems to emerge naturally for proofs involving implications: I am assuming that $x$ is in $I$ - I refer to this as an "Antecedent Assumption" and am unsure if it has a technical name. My impression is that Step 3 does not depend on Step 1.
Conversely, I feel as though Step 2 can only be invoked as a consequence of Step 1. In particular, I believe this is an instance of existential instantiation As the color coding suggests, Step 2 is asserted in order to eventually produce the desired $C$.
Finally, Step 5 seems to be purely a labeling step. I don't believe this step corresponds to either an antecedent assumption or an existential instantiation. In fact, I have no idea what to refer to this step as in technical terms.
If someone could please provide their expertise on the distinction between these three different usages of the word "Let" (and comment on whether or not my initial attempt at describing them is correct), I would greatly appreciate it.

A: The statement you're trying to prove is actually a special case of the following statement, where $A, B$ are sets and $f : A \to B$:
$$\exists a \in A \land \forall x \in A \forall y \in A (f(x) = f(y)) \implies \exists C \in B \forall x \in A (f(x) = C)$$
The semi-formal proof goes as follows:

*

*$\exists a \in A \land \forall x \in A \forall y \in A (f(x) = f(y))$ [assumption]

*$\exists a \in A$ [$\land$-elimination, 1]

*Introduce variable $a \in A$. [assumption]

*$\forall x \in A \forall y \in A (f(x) = f(y))$ [$\land$-elimination, 1]

*$\forall y \in A (f(a) = f(y))$ [$\forall$-elimination, 4, 3]

*Introduce variable $y \in A$. [assumption]

*$f(a) = f(y)$ [$\forall$-elimination, 5, 6]

*$f(y) = f(a)$ [symmetric property of equality]

*$\forall y \in A (f(y) = f(a))$ [$\forall$-introduction, 6-8 - discharge variable $y \in A$]

*$\exists C \in B \forall y \in A (f(y) = C)$ [$\exists$-introduction, 9]

*$\exists C \in B \forall y \in A (f(y) = C)$ [$\exists$-elimination, 2, 3-10, discharge variable $a \in A$]

*$\exists a \in A \land \forall x \in A \forall y \in A (f(x) = f(y)) \implies \exists C \in B \forall y \in A (f(y) = C)$ [$\implies$-introduction, 1-12, discharge assumption $\exists a \in A \land \forall x \in A \forall y \in A (f(x) = f(y))$]

We see that there are two places where we introduce a new variable, on lines 3 and 6. We use the variable introduction on line 6 to prove a universally quantified statement on line 9. We use the variable introduction on line 3 to utilize $\exists$-elimination.
There is a duality here between proving a statement that begins with $\forall$ and utilizing a statement that begins with $\exists$.
Using a more formal sequent calculus might help to clear up the confusion.
The assertion $\Gamma \vdash \phi$ means that in the context $\Gamma$, we can prove $\Phi$. The context includes all variables and their types (though for simplicity we won't include $A, B,$ or $f$ in $\Gamma$). It also includes all assumed statements.
The relevant rules of the sequent calculus are:
$$\begin{array}{c}
\hline
\Gamma, \Phi, \Delta \vdash \Phi
\end{array}$$ (where $\Phi$ is a statement and $\Gamma, \Phi, \Delta$ form a context)
$$\begin{array}{c}
\Gamma \vdash T \in A \\
\hline
\Gamma \vdash f(T) \in B
\end{array}$$
$$\begin{array}{c}
\Gamma \vdash \Phi \land \Psi \\
\hline
\Gamma \vdash \Phi
\end{array}$$
$$\begin{array}{c}
\Gamma \vdash \Phi \land \Psi \\
\hline
\Gamma \vdash \Psi
\end{array}$$
$$\begin{array}{c}
\Gamma, x \in X \vdash P(x) \\
\hline
\Gamma \vdash \forall x \in X (P(x))
\end{array}$$
$$\begin{array}{c}
\Gamma \vdash \forall x \in X P(x) \; \; \; \Gamma \vdash T \in X \\
\hline
\Gamma \vdash P(T)
\end{array}$$
$$\begin{array}{c}
\Gamma, x \in X, Q(x) \vdash P \; \; \; \Gamma \vdash \exists y \in X (Q(y)) \\
\hline
\Gamma \vdash P
\end{array}$$
$$\begin{array}{c}
\Gamma \vdash T \in X \;\;\; \Gamma \vdash P(T) \\
\hline
\Gamma \vdash \exists C \in X (P(C))
\end{array}$$
$$\begin{array}{c}
\Gamma, \Phi \vdash \Psi\\
\hline
\Gamma \vdash \Phi \implies \Psi
\end{array}$$
$$\begin{array}{c}
\Gamma \vdash T_1 \in X \; \; \Gamma \vdash T_2 \in X \; \; \Gamma \vdash T_1 = T_2\\
\hline
\Gamma \vdash T_2 = T_1
\end{array}$$
For brevity, let $\Phi$ abbreviate the statement $\exists a \in A \land \forall x \in A \forall y \in A (f(x) = f(y))$. The very formal proof for you is as follows:

*

*$\Phi \vdash \exists a \in A \land \forall x \in A \forall y \in A (f(x) = f(y))$

*$\Phi \vdash \exists a \in A$ [derived from line 1]

*$\Phi, a \in A, y \in A \vdash a \in A$

*$\Phi, a \in A, y \in A \vdash \exists a \in A \land \forall x \in A \forall y \in A (f(x) = f(y))$

*$\Phi, a \in A, y \in A \vdash \forall x \in A \forall y \in A (f(x) = f(y))$ [line 4]

*$\Phi, a \in A, y \in A \vdash \forall y \in A (f(a) = f(y))$ [lines 3, 5]

*$\Phi, a \in A, y \in A \vdash y \in A$

*$\Phi, a \in A, y \in A \vdash f(a) = f(y)$ [lines 6, 7]

*$\Phi, a \in A, y \in A \vdash f(y) = f(a)$ [line 8]

*$\Phi, a \in A \vdash \forall y \in A (f(y) = f(a))$ [line 9]

*$\Phi, a \in A \vdash a \in A$

*$\Phi, a \in A \vdash f(a) \in B$ [line 11]

*$\Phi, a \in A \vdash \exists C \in B \forall y \in A (f(y) = C)$ [lines 10, 12]

*$\Phi \vdash \exists C \in B \forall y \in A (f(y) = C)$ [lines 2, 13]

*$\vdash \Phi \implies \exists C \in B \forall y \in A (f(y) = C)$ [line 14]

Notice that we discharge the statement $y \in A$ from the context in order to prove the universally quantified statement $\forall y \in A (f(y) = f(a))$.
Notice that we discharge the statement $a \in A$ from the context in order to utilize the already proven $\exists a \in A$ and prove another statement.
Finally, the part where we say "Let $C = f(a)$" in the informal proof is best reflected on line 13, where we use the already proven $\forall y \in A (f(y) = f(a))$ to prove the statement $\exists C \in B \forall y \in A (f(y) = C)$.
These are three distinct uses of the English term "let".

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it normal to have 40% capacity after 1.5 years of charging Li-Ion? I have a laptop computer that spends 99% of its time plugged in. The last time prior to today I used the computer not plugged in was 1.5 years ago.
Today morning, I put the computer to sleep (with its battery capacity at 95%), went to work with the laptop in my bag, and started to use the laptop after 4 hours of sleep not plugged in. I was surprised to see the battery capacity was at 40%!
Then I used the computer plugged in for few hours, put it to sleep, put the computer to my bag, and after 4 hours of sleep in my bag turned it back on. Now battery capacity was at 100%.
So, it appears if you charge a lithium-ion battery for a really long amount of time such as 1.5 years, its actual capacity can be 40% whereas the displayed capacity is at 95%.
My question is: is this normal?
And before you ask, the full charge capacity has went from 46642 mWh to 44084 mWh, i.e. very minimal decrease.

A: Battery gauges often don't work well with aged batteries, so the state of charge you are reading can be pretty inaccurate.
Also, the ideal state of charge for long battery lifetime (obviously not runtime)  is around 50% charge.  If you leave it plugged in all of the time at 100% charge you will reduce the useful life of the battery.
Some laptop manufacturers have a mode that only charges to 50% if you intend to plug it in for long periods.

A: According to battery-testing firm Cadex Electronics, a fully charged lithium-ion battery will lose about 20 percent of its capacity after a year of typical storage. Increase the storage temperature to just above 100 degrees Fahrenheit such as in a hot attic for example and that number increases to 35 percent. So the environment it is stored in is a factor as well.
As John D mentioned leaving the battery at 100% charge will cause it to degrade faster.
Individual Lithium Ion cells should never be discharged below 3volts or charged above 4.2volts.  Ideally they should be stored at 3.7volts to maximize their life.


text: Q: How to compute a distribution? Is this a good forum to ask statistics homeworks? I don't know how to do the following problem in a basic course. I have been given a data of 30 persons gender (0 or 1) and some column "work" which contains real numbers from the range $[0,40]$. Problem asks to determine distributions of those two variables and figure them graphically. But as far as I know, there are many distributions like normal, geometric, chi^2, Weibull so which one I choose? And what kind of figure should I draw?


text:
Q: How to implement idle timeout in Nativescript android application I am building a Finacial application in Nativescript angular. I need some references like if the app is opened and running in the background after the set of some idle timeout it should redirect to the page which we specified. I couldn't get the proper reference in Nativescript can anyone please add a solution for the idle timeout. I have checked Nativescript extended activity but couldn't get properly

A: You should start by reading the documentation. What you need is Lifecycle hooks.
Read : https://docs.nativescript.org/angular/core-concepts/application-lifecycle#use-application-events
applicationOn(suspendEvent, (args: ApplicationEventData) => {
    setTimeout(() => {
        // do what you want after a certain amouont of time
        // don't
    }, 5000);
});

or
applicationOn(resumeEvent, (args: ApplicationEventData) => {
    // compare current datetime with the last datetime saved in suspendEvent event
});

Don't forget your app can be force-closed, so you have to handle this depending on your needs


text: Q: In a Windows service, do global static variables get cleared on "restart"? I have a .NET-based Windows service.  If I "restart" that service, do global static variables get reinitialized?  Is a stop/start sequence different?


text:
Q: sapui5 :- text not shown on ui5 in Dropdown Box The values are loaded from the data source but on ui no text is shown.
var r0c1 = new sap.ui.commons.DropdownBox("r0c1");
var oItemTemplate1 = new sap.ui.core.ListItem();

property binding is done:
oItemTemplate1.bindProperty("text", "{ZtmDockid}");

bind the items:
r0c1.bindItems("/d/results", oItemTemplate1);

Data is properly coming, but on UI its not showing the text.

A: there are two ways to bind data to a control.
First way using bindProperty:
var oItemTemplate1 = new sap.ui.core.ListItem();
oItemTemplate1.bindProperty("text", "value");

(notice: usage of { })

or binding the values when creating the control:
var oItemTemplate1 = new sap.ui.core.ListItem({
    text: "{value}"
});

(you need to use { } to indicate dynamic values)

A: Herrlock is correct, but I wanted to draw out the subtlety - explicit binding with the bind* functions requires no curly braces ... these are only needed for embedded, or implicit binding.
Here's your code with the braces removed from your bindProperty's second parameter, as a runnable snippet.

// Code from question
var r0c1 = new sap.ui.commons.DropdownBox("r0c1");
var oItemTemplate1 = new sap.ui.core.ListItem();

oItemTemplate1.bindProperty("text", "ZtmDockid");
r0c1.bindItems("/d/results", oItemTemplate1);

// Extra code
r0c1
  .setModel(new sap.ui.model.json.JSONModel({
    d : {
      results : [
        { ZtmDockid : "1" },
        { ZtmDockid : "2" },
        { ZtmDockid : "3" }
      ]
    }
  }))
  .placeAt('content');


text:
Q: Wild card routing without using express I just want to know how can we achieve wild card routing in pure http.createServer without using express.
in express we would do something like below
var express = require('express');
var http = require('http');
var app = express();

app.get('/',function(req,red)
{
    res.send("I am foo");
});
app.get('/:id',function(req,res)
{
    res.send("I am Foo with id " + red.params.id);
});

but I wasn't able to find the equivalent in http.createServer
var http = require('http');

//create a server object:

http.createServer(function (req, res) {
 res.writeHead(200, {'Content-Type': 'text/html'});
 var url = req.url;
 if(url ==='/'){
    res.write('i am foo');
    res.end();
 }else if(url ==='/:id'){//
    res.write('I am foo with id');
    res.end();
 }
}).listen(3000, function(){
 console.log("server start at port 3000");
});

one way we could achieve this is using pattern matching but I don't think its a feasible solution.


text:
Q: Get text using Regular Expression I have the sentence as below:
First learning of regular expression.
And I want to extract only First learning and expression by means of regular expressions.
Where would I start/

A: Regular expressions are for pattern matching, which means we'd need to know a pattern that is to be matched.
If you literally just want those strings, you'd just use First learning and expression as your patterns.
As @orique says, this is kind of pointless; you don't need RegEx for that. If you want something more complicated, you'd need to explain what you're trying to match.

A: Regex is not usually used to match literal text like what you're doing, but instead is used to match patterns of text. If you insist on using regex, you'll have to match the trivial expression
(First learning|expression)

A: As already pointed out, it is unusual to match a literal string like you are asking, but more common to match patterns such as several word characters followed by a space character etc...
Here is a pattern to match several word characters (which are a-z, A-Z, 0-9 and _) followed by a space, followed by several more word characters etc... It ends up capturing three groups. The first group will match the first two words, the second part the next to words, and the last part, the fifth word and the preceding space.
$words = "First learning of regular expression.";
preg_match(/(\w+\s\w+)\s(\w+\s\w+)(\s\w+)/, $words, $matches);
$result = matches[1]+matches[3];

I hope this matches your requirement.


text:
Q: best way to backup & restore user data? I am writing an android training app.
It should have a feature enabling the user to backup his results ( string of text ), but I am not sure what would be the best way.
I do not want to set up a dedicated server for that purpose. I already made the app generate a text file and suggest the user to email it to himself.
But what would be the best way of retrieving it? Just tell the user to save it in some Download folder and than select it from the app? In that case the app would need permissions to access storage that might discourage some users...


text:
Q: How to apply deep linking in the mobile controls I'm trying to use mobile controls in a recent extension library.  I've setup the basic structure and it seems to be working.  However when I navigate to a page I don't get a # with the page name applied to the end.  When I hit the back button I DO get a "#home" applied.
How do get the # to apply to the indivudal pages so they will stick if a full refresh is issued from the browser or someone wants to do deep linking?
Thanks!
<xe:singlePageApp id="singlePageApp1"
    selectedPageName="home">
    <xe:appPage id="home" pageName="home">
        <xe:djxmHeading id="djxmHeading0"
            label="My Home Page">
        </xe:djxmHeading>
        <xe:djxmLineItem id="djxmLineItem3" label="Sell Items"
            moveTo="mobilePage1">

        </xe:djxmLineItem>
        <xe:djxmLineItem id="djxmLineItem4" label="Sold Items"
                moveTo="mobilePage2">
            </xe:djxmLineItem>
    </xe:appPage>
    <xe:appPage id="appPage1" pageName="mobilePage1"
        autoCreate="true">
        <xe:djxmHeading id="djxmHeading1" label="Sell an Item"
            moveTo="home" back="Back">
        </xe:djxmHeading>
        <xc:cc_SellItem></xc:cc_SellItem>
    </xe:appPage>
    <xe:appPage id="appPage2" pageName="mobilePage2">
        <xe:djxmHeading id="djxmHeading2" moveTo="home" back="Back"
            label="Sold Items">
        </xe:djxmHeading>

        <xp:panel>List of Sold Items will go here.</xp:panel></xe:appPage>
    </xe:singlePageApp>

A: You just need to add the hash (#) prefix to the page name in the moveTo property:
<xe:djxmLineItem id="djxmLineItem3" label="Sell Items" moveTo="#mobilePage1"></xe:djxmLineItem>
<xe:djxmLineItem id="djxmLineItem4" label="Sold Items" moveTo="#mobilePage2"></xe:djxmLineItem>

Have a look at "The moveTo property" in the XPages Mobile Controls Tutorial.

A: The Extension Library also includes a Dynamic Content component. This component has a useHash property, which refers to the # in the URL. This should allow you to specify which portion of the app is loaded based on the hash value.


text:
Q: Why is my API request not updating variable? I have a function that makes an HTTP request.
I want that function to make the request, change a variable's value inside the subscribe and print the variable to the console.
However, I keep getting the variable's original value whenever I print it.
I debugged my code and I noticed that my function executes two times.
On the first time, the code inside the subscribe is not executed and because of that the console.log(test) prints Output: true.
On the second time, the code inside the subscribe gets executed but the console.log(test) doesn't.
Here is my code:
MyComponent.component.ts
private searchTest(value) {
  let test: boolean = true;
  this.rest.getOrderByNumber(value).subscribe((orderNrData: {}) => {
    if (Object.entries(orderNrData).length !== 0) {
      test = false;
    } else {
      test = false;
    }
  }, error => {
    test = false;
  });
  console.log(`Output: ${test}`);
}

MyComponent.component.html

    <mat-form-field class="search-form-field" appearance="outline" [formGroup]="searchForm">
      <mat-label>Search</mat-label>
      <input matInput class="search-input" id="search-input-id" placeholder="Ex: EU030327" formControlName="inputForm" #searchInput>
    </mat-form-field>

      <button mat-flat-button class="search-btn" color="accent"
        (click)="searchTest(searchInput.value)"></button>

Basically, what I'm trying to achieve is to be able to make an HTTP request and change a variable's value so I can use it on another part of the code (like on an ngIf).

*

*Why do I get this behavior?

*How I can make the rest of the code wait for the HTTP request to be executed?

EDIT:
I have updated my functions to use callbacks, so now I have this:
MyComponent.component.ts
teste: boolean = true;

searchTest(value){
  this.test(this.test1, value, this);
}

test(callback, value, self){
  callback(value, self);
}

test1(value, self){
  self.rest.getOrderByNumber(value).subscribe((orderNrData: {}) => {
    if (Object.entries(orderNrData).length !== 0) {
      self.teste = false;
    } else {
      self.teste = false;
    }
  }, error => {
    self.teste = false;
  });
}

MyComponent.component.html

    <mat-form-field class="search-form-field" appearance="outline" [formGroup]="searchForm">
      <mat-label>Search</mat-label>
      <input matInput class="search-input" id="search-input-id" placeholder="Ex: EU030327" formControlName="inputForm" #searchInput>
    </mat-form-field>

      <button mat-flat-button class="search-btn" color="accent"
        (click)="searchTest(searchInput.value)"></button>

  This is the error!

Now I have another problem... The
 only appears when I press my button twice or if I hover my mouse pointer over a different component (this is a really weird and new behavior for me).
My page has a component with a search input (the one I'm currently in) and a component with a table that shows the data from the HTTP response.
What's the problem with my code?


text:
Q: jQuery: get all elements with text as it's immediate children, including descendants? I would like to grab all elements containing text.
$(*).each(function(){
    if ($(this).nodeType == 3) return $(this).parent();
}).get();

however when there's an element like

somewhere  here now

However using my code it will return
somewhere
 and here and now separately. I would like for it to return
somewhere here now
.
If an element only has text contents, then this is fine

only this

should give me
only this
 as it has no descendants.
What I'm wary about is big containers getting returned like:

some

where

that should give me some and where, and not the wholediv` because there is many whitespaces in between.

A: Try
function get(ct) {
    return $(ct).find('*').filter(function () {
        return $(this).contents().filter(function () {
            return this.nodeType == 3 && $.trim(this.nodeValue) != '';
        }).length != 0
    });
}

Demo: Fiddle


text:
Q: this.stopSelf() does not stop the service sometimes I have following piece of code in onCreate() of a AIDL service
 @Override
 public void onCreate() {
 log("onCreate()");
  if (SystemProperties.getInt(DONT_START,0)==1) {
     // Do not start the service if some system property is set
     log("not starting service");
     this.stopSelf();
     }
 }

This service is "binded to" or started from multiple places. I have logs in all the lifecycle methods.
Sometimes I see that when service is started after this.stopSelf() - I see onStartCommand() getting called - but no onCreate() - which indicates that this onStartCommand() has been called on the already stopped service
The logs during the issue - 1% times when it fails looks like :
onCreate()
not starting service"
onBind() return null since service not started
onStartCommand()
The logs in normal flow in same scenario when issue is not seen - 99% times looks like :
onCreate()
not starting service"
onBind() return null since service not started
onCreate()
onStartCommand()
Other similar issues I looked at :
I see in similar thread StopSelf does not stop my service that it was recommended to use :
android.os.Process.killProcess(android.os.Process.myPid());

Should I be using this too instead of
   this.stopSelf()


text:
Q: Not able to Inject Javascript in Swagger I get a 404 for a JavaScript file that I am trying to inject in my swagger. Following is my swagger config
var thisAssembly = typeof(SwaggerConfig).Assembly;

GlobalConfiguration.Configuration
    .EnableSwagger(c =>
        {
            c.SingleApiVersion("v1", "A title for your API");
        })
    .EnableSwaggerUi(c =>
        {
            c.InjectJavaScript(thisAssembly,"MyApi.Api.SwaggerExtensions.inject.js");
        });

For inject.js build action is set to embedded resource and logical path is correct as my project name is MyApi.Api and the file is in a folder within the project named SwaggerExtensions

A: I spent a lot of time trying to figure out that a method with the same name has a different behavior. The config in Startup.Configure expects a relative path from wwwroot:
public void Configure(IApplicationBuilder app) {
    //
    app.UseSwagger();
    app.UseSwaggerUI(c => {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Salon API v1");
        c.InjectJavascript("/SwaggerExtension.js");
    });
}

Get started with Swashbuckle and ASP.NET Core

A: When using custom resources the resource name should contain the default namespace of your project as described here. In your case the configuration should be:
c.InjectJavaScript(thisAssembly, "AcctMgmt.SwaggerExtensions.inject.js")


text:
Q: Javascript Redirect page to rewrite url not work Javascript Redirect page to rewrite url not work.
i use this code
<script language="JavaScript">window.location = 'test/6/loveyou';</script>

but when test it's will be redirect to
www.example.com/test.php?test_id=6&test_title=loveyou

i want to redirect to
www.example.com/test/6/loveyou

this is my .htaccess
RewriteRule ^test/([^/]*)/([^/]*)$ /test.php?test_id=$1&test_title=$2 [L]


text:
Q: Pandas: Apply a function aware of column type to every column of a data frame Goal
I would like to apply a function that depends on the input column's type to every column in a data frame. Consider the following data frame:
df = pd.DataFrame( [["a",1],["b",2]], columns = ["string","num"] )

I can test for a column's type:
>>> df["num"].dtype
dtype('int64')
>>> df["num"].dtype in ["int64"]
True

And I can apply a function over all columns:
>>> df . apply( lambda column: column.sum() )
string    ab
num        3
dtype: object

But if I make the function depend on the column's type, I get garbage:
>>> df . apply( lambda column:
...             np.nan if not column.dtype in ['float64','float32','int32','int64']
...             else column.sum() )
string   NaN
num      NaN
dtype: float64

Motivation
There are solutions that involve basically dropping the non-numeric columns, but I actually need to retain them. The reason for that is I'm trying to append a row that counts the zeroes in each column to the results of df.describe. Here's an example of a similar function:
def describe_plus(df):
  most_stats = df.describe()
  missing_stat = pd.DataFrame( df.isnull().sum()
                             , columns = ["missing"]
                             ).transpose()
  length_stat = pd.DataFrame( [[len(df) for _ in df.columns]]
                            , index = ["length"]
                            , columns = df.columns )
  return length_stat.append( missing_stat.append( most_stats ) )

Calling that gives you the ordinary output from pd.describe, plus the length and number missing in each column:
>>> describe_plus( df )
              num  string
length   2.000000     2.0
missing  0.000000     0.0
count    2.000000     NaN
mean     1.000000     NaN
std      1.414214     NaN
min      0.000000     NaN
25%      0.500000     NaN
50%      1.000000     NaN
75%      1.500000     NaN
max      2.000000     NaN

In addition to length and missing, I would like to add a third row to describe_plus, which counts the number of zeroes in each column, or provides NaN for columns that are not numbers.
Edit: RafaelC's solution, in this framework
The trick is to discard those non-numeric variables, compute the summary statistics, and then simply append the other statistics (which are defined over every column, even non-numeric ones).
def describe_plus_plus(df):
  nums = df.select_dtypes(include=[np.number])
  zeroes = pd.DataFrame( [nums.apply( lambda col: len( col[col==0] ) /
len(nums) )] )
  return zeroes.append( describe_plus( df ) )

Example of it in action:
>>> df = pd.DataFrame( [[0,0,0,""],[0,0,1,"a"],[0,1,2,"b"]], columns = ["none","1/3","2/3","string"] )
>>> describe_plus_plus( df )
              1/3       2/3  none  string
0        0.666667  0.333333   1.0     NaN
length   3.000000  3.000000   3.0     3.0
missing  0.000000  0.000000   0.0     0.0
count    3.000000  3.000000   3.0     NaN
mean     0.333333  1.000000   0.0     NaN
std      0.577350  1.000000   0.0     NaN
min      0.000000  0.000000   0.0     NaN
25%      0.000000  0.500000   0.0     NaN
50%      0.000000  1.000000   0.0     NaN
75%      0.500000  1.500000   0.0     NaN
max      1.000000  2.000000   0.0     NaN

A: If you have your list of allowed types, just use loc
allowed_types = [np.float64, np.float32,np.int32, np.int64]
mask = df.dtypes.isin(allowed_types)
df.loc[:, mask].sum()

However, a probably better approach is to use select_dtypes, using np.number as parent dtype if you want to select only columns that are numbers.
df.select_dtypes(include=[np.number])

Of course, can change [np.number] to your list of allowed_types if you really need to be specific.


text:
Q: CONCAT is not working in mysql stored procedure DROP PROCEDURE IF EXISTS Cursor_Test;# MySQL returned an empty result set (i.e. zero rows).

DELIMITER $$

CREATE PROCEDURE Cursor_Test()
BEGIN

  DECLARE Project_Number_val VARCHAR( 255 );
  DECLARE Project_List_val VARCHAR(255);

  DECLARE no_more_rows BOOLEAN;
  DECLARE loop_cntr INT DEFAULT 0;
  DECLARE num_rows INT DEFAULT 0;

  DECLARE projects_cur CURSOR FOR
    SELECT Project_Id
    FROM Project_Details;

  DECLARE CONTINUE HANDLER FOR NOT FOUND
    SET no_more_rows = TRUE;

  OPEN projects_cur;
  select FOUND_ROWS() into num_rows;

  the_loop: LOOP

    FETCH  projects_cur
    INTO   Project_Number_val;

    IF no_more_rows THEN
        CLOSE projects_cur;
        LEAVE the_loop;
    END IF;

SET Project_List_val=CONCAT(`Project_Number_val`,'_List')

-
> ---> **Please check am I doing CONCAT correct here?**

Insert Into test (Panel_Id) select Panel_Id from Project_List_val where Project_Number_val='9';

> --->**Is this taking 9_List as table name?**

    SET loop_cntr = loop_cntr + 1;
  END LOOP the_loop;

  select num_rows, loop_cntr;

END $$# MySQL returned an empty result set (i.e. zero rows).

DELIMITER

Any suggestions?
Hi All,
I have a variable in stored procedure named Project_Number and it is of varchar type.
My Requirement is "for each project number query the table project_Number_List get results from list and insert into other table"
Lets say, Project_Number might be like this 22,21,34,43,434
corresponding tables I need to query is something like this 22_List, 21_List,34_List .....
I'm using cursor to loop through the Project_Number but my problem is how to mix the project_number and _list i.e., 22_list to query the table 22_List

A: Try with this :
SET Project_List_val=CONCAT(Project_Number_val,'_List')

A: SET Project_List_val=CONCAT(Project_Number_val,'_List');

Don't put the single quotation For Project_Number_val vairable.

A: you var call is wrong, try this:
 SET Project_List_val = CONCAT(Project_Number_val,'_List')


text:
Q: Visual Studio web testing I come from a world of PHP (Laravel) and have faced no issues with testing the API or webpage like this before. Every time I would make a change I'd simply refresh the page, and it would show me the result of my changed actions.
This does not seem to be the case with my new experience with VS as it seems I have to run F5 or Ctrl+F5 every time I make a simple change to the program. To make things even more annoying, it is always opening a new tab with each program run.
Is this simply the way "VS is", or am I missing something?

A: It doesn't have anything to do with VS. PHP is a script language, it doesn't get compiled before running like c# does. You have to do a build of the project in order for the DLLs to be up-to-date

A: I am going to assume you're using IIS express and ASP.NET.
Right click on Project and then choose View in Browser.
You'll need to do a build though if you make any changes to the C# but not if making changes to CSS/Javascript (excluding things like SASS etc)


text:
Q: Using PHP/HTML to calculate and display inversions of 4-part chords I am writing a PHP application that represents the six strings of the guitar as a series of ranges. In this way, I can add, or subtract to a set of numbers to systematically change an archetypical structure I define.
The ranges are:
//E: 1-15, A: 26-40, D: 51-65, G: 76-90, b: 101-115, e: 126-140

I am having trouble with the code below.
The function
//the key of the key value pair represents its position on the guitar, and the value
//represents a theoretical function. If the inversion is "0", do nothing. If the
//inversion is "1", all notes that have the value of "r" should have their key
//incremented by 4 and their value changed to '3'.

//example: 1=>"r",28=>"5",52=>"7",77=>"3"
function invChange($pattern, $inversion) {
    if ($inversion == 1) {
        foreach ($pattern as $position => $function) {
            if ($function == 'r' ) { $position += 4; $junction = '3'; }
            if ($function == '3' ) { $position += 3; $junction = '5'; }
            if ($function == '5' ) { $position += 4; $junction = '7'; }
            if ($function == '7' ) { $position += 1; $junction = 'r'; }
            $modScale[$position] = $junction;
        }
    }
    if ($inversion == 2) {
        foreach ($pattern as $position => $function) {
            if ($function == 'r' ) { $position += 7; $junction = '5';}
            if ($function == '3' ) { $position += 7; $junction = '7';}
            if ($function == '5' ) { $position += 5; $junction = 'r';}
            if ($function == '7' ) { $position += 5; $junction = '3';}
            $modScale[$position] = $junction;
        }
    }
    if ($inversion == 3) {
        foreach ($pattern as $position => $function) {
            if ($function == 'r' ) { $position += 11; $junction = '7';}
            if ($function == '3' ) { $position += 8; $junction = 'r';}
            if ($function == '5' ) { $position += 9; $junction = '3';}
            if ($function == '7' ) { $position += 8; $junction = '5';}
            $modScale[$position] = $junction;
        }
    }
    return $modScale;
}

As you can see, this is quite repetitive. Just looking at this code makes me think there has got to be a better way. I think what I need is to use an array in an infinite linear fashion:
array("root" => 4, "third" => 3, "fifth" => 4, "seventh" => 1);

Now I need to take any of a predefined $note => $offset pair and jump them across this array by 1, 2, or 3 jumps. For instance, if it starts as a root, and it makes one jump, I need to add 4 to turn it into a "third", and change its value to 'third'. But if it starts as a root and makes two jumps, I need to add 4, add 3, and then change its value to "fifth".

A: TL;DR;
Well.. you can do it with math. Even more, with restrictions you've provided, it can be done with, actually, one function. Quadratic function.
How it's done
All you need to do - is somehow create a math function, which will take your inversion as an argument, and return a certain position by a given "function" (how it's called inside your PHP function). Since you have three values for "inversion", you can done this with quadratic function:

f(x) = ax2 + bx + c

here, you'll need to find coefficients a, b, and c by given x values ($inversion for your case) and function values (values for "position" in each of your "inversion" if blocks).
However, you have four different position switches for each of your "function" (that's inside foreach block) - that's why, actually, you'll have to deal with four quadratic functions.
Now, about junctions. I'm not sure what it is in logical sense, but, certainly, the dependence is obvious: given the array of all possible junctions, value for certain "function" is just junction at position "current" + "inversion". So, if we have junctions array ['r', '3', '5', '7'], then, if inversion is 1 and current is 3, then result would be 5. If inversion is 2, then result would be 7 e t.c.
And the code
Here we go:
function invChangeN($pattern, $inversion)
{
   $junc = ['r', '3', '5', '7'];
   $pos  = [
      'r' => [ 1, 7, 14],
      '3' => [-3, 5, 14],
      '5' => [ 3, 5, 10],
      '7' => [-1, 7, 10]
   ];
   $inversion -= 2;
   $modScale   = [];
   foreach ($pattern as $p => $f)
   {
      $p += ($pos[$f][0]*pow($inversion,2) + $pos[$f][1]*$inversion + $pos[$f][2])/2;
      $j  = $junc[(array_search($f, $junc)+$inversion+2)%count($junc)];
      $modScale[$p] = $j;
   }
   return $modScale;
}

Little about, why are we doing $inversion -= 2. It's just about - to transpose three points from 1, 2 and 3 (original inversion values) to -1, 0 and 1 - with that it's much easier to calculate our a, b and c.
$pos contains arrays of coefficients for quadratic function for each "function" (that is $f inside loop). Due to resolving linear equations system, they all are "half-integers" (so, have a view W/2, so denominator of fraction is 2). That's why I've just multiplied them all to 2 and added division by 2 to position calculation.
Tests
I've done tests of your function and this new "math" analog - with successful results, which are, of course for inversion as 1, 2 and 3, like:
//derived from old function:
array(4) {
  [8]=>
  string(1) "5"
  [33]=>
  string(1) "r"
  [57]=>
  string(1) "3"
  [84]=>
  string(1) "7"
}
//derived from new function:
array(4) {
  [8]=>
  string(1) "5"
  [33]=>
  string(1) "r"
  [57]=>
  string(1) "3"
  [84]=>
  string(1) "7"
}

Results above are for pattern [1=>"r",28=>"5",52=>"7",77=>"3"] and inversion 2


text:
Q: Crash page on Meta directs users to Meta The generic "oops" crash page on Meta directs users to report the issue at meta (optionally). There's a stack overflow joke in here somewhere...
Perhaps meta should replace that text with another site or email (or just remove it).
alt text http://img17.imageshack.us/img17/7690/sometaerror.png

A: The image of the error isn't joke enough for you? get it? The dialog image box?

A: Excellent find!
We should make sure to redirect people to the meta.meta.stackoverflow.com and not just the normal meta.
;)

A: Unless you're crashing when asking a question, then you can report the error on meta.
The joke is pretty good though. :)


text:
Q: Summation and Arithmetic progression problem This is the question which I am referring to

If $S_n=an^2 + bn $ , verify that the series $\sum {t_{n}}$ is arithmetic where $  S_n=\sum_{n=1}^{n}{t_n} $

My try:

*

*first of all I used below equation to calculate ${t_n}$
${t_n} = S_n - S_{n-1} = a (2n-1)-b$

*

*Then I calculated common difference by below equation
$d=t_n-t_{n-1}$

*Then I calculated $t_1$   by putting $n=1$.

*Then I calculated $s_n$ by AP formula and it came out to be
$s_n= an^2-bn$ but for $\sum {t_{n}}$ to be arithmetic $S_n=s_n$
Please mention where am I wrong

A: $t_n=a\{n^2-(n-1)^2\}+b\{n-(n-1)\}=2na-a+b$
$$t_n-t_{n-1}=2na-a+b-\{2(n-1)a-a+b\}=2a$$ which being independent of $n$ is constant


text:
Q: linear equations; method by integrating factors $$y' -y =4te^{2t}$$ find the solution of the given initial value problem $y(0)=1 $
so basically what I found out obviously is that $exp^{\int -1dt}$ gives the integrating factor $e^{-t}$ right?
and then I multiply the whole equation with that so I get
$(y' - y)e^{-t} = 4te^{2t}  e^{-t}$
and now the struggle, I have no idea how to simplify this thing, somehow in the solution manual they somehow get $(e^{-t}y)' = 2te^t$? I mean I see how you get $e^t$ when you multiply $e^{2t} e^{-t}$ but where did that coefficient come from? thanks for any help, tips, trying to learn this stuff for once.

A: i think it may be solved using the general solution  .
Y(h) -->
$m-1=0$  --- > m=1 .
  $y = C$. ( exponential (mx) ) .
  and F(x) -->
  $Yp=A(exp(mx)$  .
  $(y)General solution = Yp + Yh$ . i wish i helped you , thats all i know .

A: You seem to be having a problem with $(e^{-t}y)'$ where in fact it originally was $(y'-y)e^{-t}$
Let's try differentiating $f(y)=e^{-t}y$ with respect to $t$ using the product rule
$$f'(y)= e^{-t}\frac{dy}{dt} + y\frac{d(e^{-t})}{dt}$$
$$= e^{-t}y' + y(-e^{-t})$$
$$=e^{-t}(y'-y)$$
which is exactly what you had.

A: $$
(\mathrm{e}^{-t}y)'=4t\mathrm{e}^t=\big((4t-4)\mathrm{e}^t\big)',
$$
and hence
$$
\mathrm{e}^{-t}y=(4t-4)\mathrm{e}^t+c,
$$
for some $c$ constant, and since $y(0)=1$, we obtain at $t=0$
$$
1=y(0)=-4+c,
$$
and hence $c=5$. Thus
$$
y(t)=(4t-4)\mathrm{e}^{2t}+5\,\mathrm{e}^{t}.
$$


text:
Q: installing php-imap on amazon ec2 linux 2 I need to install php-imap on amazon ec2 linux 2 instance.
All the php stuff is inside amzn2extra-lamp-mariadb10.2-php7.2 but php-imap package is missing.
Any advice ?
Thanks

A: I installed it like this.
I downloaded the php source code of the currently installed version in my Amazon Linux 2
wget http://php.net/get/php-7.2.8.tar.bz2/from/a/mirror

Unpacked it and went into php-7.2.8/ext/imap/
Compiled extension:
phpize
./configure

I got some errors.
Some U8T_CANONICAL stuff so
sudo yum install libc-client-devel

Then libc-client.a not found so created a symlink for it:
cd /usr/lib
sudo ln -s /usr/lib64/libc-client.a

some other imap library error so:
sudo yum install uw-imap-static

I got some other errors so the working configure line was:
./configure --with-kerberos --with-imap-ssl
make

SUCCESS!
cd php-7.2.8/ext/imap/modules
sudo cp imap.so /usr/lib64/php/modules/

Created an ini file to load it:
sudo vi /etc/php.d/30-imap.ini

added to the file this content:
extension=imap

restarted php service (you might need to restart httpd depending on your php installation):
sudo systemctl restart php-fpm

PHPinfo now contains:
imap
IMAP c-Client Version   2007f
SSL Support enabled
Kerberos Support    enabled

A: For those who are facing the U8T_CANONICAL error and can't being able to install the libc-client-devel on Amazon Linux 2 AMI need to do something extra to resolve the U8T_CANONICAL error.
The main problem is that libc-client-devel isn't available so we need to do it in another way.
I found this link while searching for my problem. The solution that is posted here is solid. The following link that i gave is for those who are not being able to install the libc-client-devel will be benifited from the link.
Or you could just copy paste the commands i'm giving below.
1 - sudo yum groupinstall "Development Tools"
2 - sudo amazon-linux-extras install epel
3 - yum install epel-release
4 - sudo yum install libc-client-devel uw-imap-static openssl-devel
5 - sudo ln -s /usr/lib64/libc-client.a /usr/lib
The rest can be followed from respondent.
Again thanks to the person who answered.

A: Same problem here.
I came from debian/ubuntu and i miss a lot of php packages on aws linux2.
I know it's still a candidate and not a final LTS release.  Only worked for a month with this distro and saw a lot of changes and updates. Some php dependencies can be solved with pear or pecl,  but I couldn't get nothing working on php-imap.
php-imap depends on libc-client (maybe that's a problem?)
Here is my solution.

*

*Search for the libc-client rpm that correspond to your version and
install manually.

*Search for the rpm that corresponds to your php installed version. In my case it was 7.2.5**-2** about 2 weeks ago. (today is
7.2.5**-3** ) and isntall manually

CODE

wget https://dl.iuscommunity.org/pub/ius/stable/CentOS/7/x86_64//php72u-imap-7.2.5-2.ius.centos7.x86_64.rpm -P /tmp
wget http://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/l/libc-client-2007f-16.el7.x86_64.rpm -P /tmp

rpm -i /tmp/libc-client-2007f-16.el7.x86_64.rpm
rpm -i /tmp/php72u-imap-7.2.5-2.ius.centos7.x86_64.rpm

If it fails because Failed dependencies:

rpm -ivh /tmp/php72u-imap-7.2.5-2.ius.centos7.x86_64.rpm --nodeps

I dont like this solution, but can't find for now any other solution more  stable and easy. It will be a pain with updates....


text:
Q: Unable autowire SessionFactory[null] into @Transactional bean I have faced very strange issue with autowiring Hibernate SessionFactory bean into my Service.
I'm able to find SessionFactory bean in Spring Context object. So no issues with creating such bean.
But I can not autowire this bean into my service when it is marked with @Transactional annotation. Factory field is null.
Once I remove this annotation - everything works good.
Service Class:
@Service
@Transactional
public class ExampleRunner implements Runnable{

    @Autowired
    SessionFactory sessionFactory;
 ...
}

applicationContext.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <context:property-placeholder location="classpath:application.properties"
                                  ignore-resource-not-found="true" />

    <context:component-scan base-package="org.edu" />
    <context:annotation-config />

    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName"
                  value="${jdbc.driverClassName:org.hsqldb.jdbcDriver}" />
        <property name="url" value="${jdbc.url:jdbc:hsqldb:mem:myAppDb}" />
        <property name="username" value="${jdbc.username:sa}" />
        <property name="password" value="$jdbc.password:}" />
    </bean>

    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="org.edu" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    ${hibernate.dialect:org.hibernate.dialect.HSQLDialect}
                </prop>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto:create-drop}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql:true}</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
    </bean>

    <tx:annotation-driven transaction-manager="txManager"
                          proxy-target-class="true" />

    <bean id="txManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>

Usage:
public static void main(String[] args) {
    Runnable runner =  new ClassPathXmlApplicationContext("applicationContext.xml").getBean(ExampleRunner.class);
    runner.run();
}

Seems like when I make @Transactional as class level annotation Spring creates CGLib proxy bean where SessionFactory field is null.
But when I use @Transational as method level annotation everything works good.
So I just want to understand such behavior.
What have I missed from Spring documentation?
I use Spring 4.1.4.RELEASE.

A: I got your error actually why you getting problem here because you not allowing container to auto-wired bean for you as you using java Main method it will not auto-wired bean that's why you getting error.


text:
Q: UrlHelper class throws null exception in Asp.net mvc I am developing an Asp.net mvc web application. I am doing Unit Test to my application. I am using Moq to mock objects. I am trying to mock Url helper class. I found this link- asp.net mvc: how to mock Url.Content("~")?. Using that class, I can mock UrlHelper class in unit test.
I created a BaseController like this
public class BaseController : Controller
{
    private IUrlHelper _urlHelper;

    public new IUrlHelper Url
    {
        get { return _urlHelper; }
        set { _urlHelper = value; }
    }
}

Here is the IUrlHelper interface/abstraction
public interface IUrlHelper
{
    string Action(string actionName);
    string Action(string actionName, object routeValues);
    string Action(string actionName, string controllerName);
    string Action(string actionName, RouteValueDictionary routeValues);
    string Action(string actionName, string controllerName, object routeValues);
    string Action(string actionName, string controllerName, RouteValueDictionary routeValues);
    string Action(string actionName, string controllerName, object routeValues, string protocol);
    string Action(string actionName, string controllerName, RouteValueDictionary routeValues, string protocol, string hostName);
    string Content(string contentPath);
    string Encode(string url);
    string RouteUrl(object routeValues);
    string RouteUrl(string routeName);
    string RouteUrl(RouteValueDictionary routeValues);
    string RouteUrl(string routeName, object routeValues);
    string RouteUrl(string routeName, RouteValueDictionary routeValues);
    string RouteUrl(string routeName, object routeValues, string protocol);
    string RouteUrl(string routeName, RouteValueDictionary routeValues, string protocol, string hostName);
}

I mock the Url.Content() in the unit test like this
Mock<IUrlHelper> urlHelperMock = new Mock<IUrlHelper>();
urlHelperMock
    .Setup(x => x.Content(It.IsAny<string>()))
    .Returns<string>(x => "~/" + x);// Mock Content method of Url Helper

Test run successfully and working fine. The problem is I cannot use it in real time application. I mean when I run my app and call Url.Content("path"), it throws null exception.
For example
public class ExampleController : BaseController
{
    public string GetPath()
    {
       return Url.Content("~/Path/To/File");
    }
}

Url.Content in this code throws null exception. It is working fine in unit test. How can I fix that code?

A: In this case there really isn't a need to abstract the UrlHelper. Just mock up the helper for the test to do what is required.
For example, assuming
public class ExampleController : Controller {
    public string GetContent() {
       return Url.Content("~/Path/To/File");
    }
}

Here is a test that mocks the UrlHelper using moq to work just like in original example
[TestClass]
public class UrlHelperTest {
    [TestMethod]
    public void MockUrlHelper() {
        //Arrange
        var expectedPath = "~/Path/To/File";
        var expectedContent = "<p>Fake content here<p>";
        var urlHelperMock = new Mock<UrlHelper>();
        urlHelperMock
            .Setup(m => m.Content(expectedPath))
            .Returns(expectedContent)
            .Verifiable();

        var sut = new ExampleController();
        sut.Url = urlHelperMock.Object; //Set mock UrlHelper

        //Act
        var actualContent = sut.GetContent();

        //Assert
        urlHelperMock.Verify();
        Assert.AreEqual(expectedContent, actualContent);
    }
}

So now the test can be performed and also the framework will populate the necessary controller properties in production because technically nothing was changed from the original framework to custom abstractions.


text:
Q: Divide each element in each row of a dataframe by the value in one of the rows in R I would like to standardize a dataframe by the value in one specific column.  In other words, I would like to divide all the values in each row by the value in a specific column.
For example:
The dataframe is
Gene   P1  P2  P3
A1      6   8   2
A2      12  6   3
A3      8   4   8

I would like to divide all the values in each row by the value in that row for column P3.
Gene   P1     P2    P3
A1      6/2   8/2   2/2
A2      12/3  6/3   3/3
A3      8/8   4/8   8/8

The new dataframe would be:
Gene   P1  P2  P3
A1      3   4   1
A2      4   2   1
A3      1   .5  1

Thank you for your help.

A: Using tidyverse functions:
library(tidyverse)
df1 <- read.table(text = "Gene P1 P2 P3
A1 6 8 2
A2 12 6 3
A3 8 4 8", header = TRUE)

df1 %>%
  mutate(across(.cols = -c(Gene), .fns = ~ .x / P3))
# Gene P1  P2 P3
#1   A1  3 4.0  1
#2   A2  4 2.0  1
#3   A3  1 0.5  1

A: You can directly divide the columns -
cols <- 2:3
df[cols] <- df[cols]/df$P3
df

#  Gene P1  P2 P3
#1   A1  3 4.0  2
#2   A2  4 2.0  3
#3   A3  1 0.5  8


text:
Q: Better way to extract elements from a line using perl? I want to extract some elements from each line of a file.
Below is the line:
 #                 1150 Reading location  09ef38 data = 00b5eda4

I would like to extract the address 09ef38 and the data 00b5eda4 from this line.
The way I use is the simple one like below:
while($line = < INFILE >) {

    if ($line =~ /\#\s*(\S+)\s*(\S+)\s*(\S+)\s*(\S+)\s*(\S+)\s*=\s*(\S+)/) {
       $time = $1;
       $address = $4;
       $data = $6;
       printf(OUTFILE "%s,%s,%s \n",$time,$address,$data);
      }
}

I am wondering is there any better idea to do this ? easier and cleaner?
Thanks a lot!
TCGG

A: You could use matching and a list on LHS, something likes this:
echo '# 1150 Reading location 09ef38 data = 00b5eda4' |
  perl -ne '
    $,="\n";
    ($time, $addr, $data) = /#\s+(\w+).*?location\s+(\w+).*?data\s*=\s*(\w+)/;
    print $time, $addr, $data'

Output:
1150
09ef38
00b5eda4

A: Another option is to split the string on whitespace:
my ($time, $addr, $data) = (split / +/, $line)[1, 4, 7];

A: In python the appropriate regex will be like:
'[0-9]+[a-zA-Z ]*([0-9]+[a-z]+[0-9]+)[a-zA-Z ]*= ([0-9a-zA-Z]+)'

But I don't know exactly how to write it in perl. You can search for it. If you need any explanation of this regexp, I can edit this post with more precise description.

A: I find it convenient to just split by one or more whitespaces of any kind, using \s+. This way you won't have any problems if the input string has any tab characters in it instead of spaces.
while($line = <INFILE>)
{
    my ($time, $addr, $data) = (split /\s+/, $line)[1, 4, 7];
}

When splitting by ANY kind of whitespace it's important to note that it'll also split by the newline at the end, so you'll get an empty element at the end of the return. But in most cases, unless you care about the total amount of elements returned, there's no need to care.


text:
Q: Run a function in the background .js file from the popup .html file in a Chrome extension I am trying to write a Chrome extension. You switch between icons by clicking the Chrome extension icon, and the popup.html comes up with a preview of the icon you will set it to by clicking:
<input type="image" src="icon.png" onclick="helloWorld()"></input>

And the function helloWorld() is defined in the background.js file (same directory:
chrome.browserAction.setIcon({
  path : "/iconcat.png"
});

function helloWorld() {
    chrome.browserAction.setIcon({
      path : "/icon.png"
    });
}

(the first thing that is being done is setting it to a cat icon)
I have both icon.png and iconcat.png in the same directory as each other and the .html and .js files.
How can I get the image button to run the helloWorld() function in the .js file by clicking it?

A: *

*By default, inline script won't be executed. You should extract your onclick inline handler and move it to external script like popup.js.

*To call function in background page from popup page, you could take a look at chrome.runtime.getBackgroundPage or chrome.extension.getBackgroundPage.
Sample code looks like:
manifest.json
{
  "name": "Emoji",
  "version": "1.0",
  "manifest_version": 2,
  "description": "Show an Emoji in Chrome!.",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "picker.html"
  },
  "background": {
    "scripts": ["background.js"]
  }
}

picker.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <input id="inputId" type="image" src="icon.png"></input>
    <script src="picker.js"></script>
</body>
</html>

picker.js
document.getElementById("inputId").addEventListener("click", function() {
    chrome.runtime.getBackgroundPage(function(backgroundPage) {
        backgroundPage.helloWorld();
    });
}, false);

background.js
chrome.browserAction.setIcon({
  path : "/iconcat.png"
});

function helloWorld() {
    chrome.browserAction.setIcon({
      path : "/icon.png"
    });
}


text:
Q: Using multiple backgrounds in Android Application Here is a scenario on which i done a lot of research on google but hopeless. the scenario is, i am going to develop a 2D game in which i want to use multiple backgrounds and i want to translate them as they are moving forward, it must look like one background is near and translating/moving fast and the other background is a bit far and translating/moving a little slow. the nearer background have almost full intensity and the farer background have a bit low intensity. you can say they have different transparency levels. the question is, how can i get this task done or is this possible to use multiple backgrounds.
any suggestion will be appreciated.
as an example, see the image of BADLAND game bellow.

A: I think as far as I got your question you want to put two or more images one over another. I mean if you are trying to overlap the multiple backgrounds and asking for it yes it can be done easily.
What you need to do is to use the FrameLayout. as

"FrameLayout represents a simple layout for the user interface of
  Android applications. It is usually used for displaying single Views
  at a specific area on the screen or overlapping its child views."

and then you can implements the animations on them and translate them You can find different types of translation over them.
Here is all about using the frame layout frameLayout1 framelayout2 and for animations and translation here are links. link , link2 , link3


text:
Q: why does my view embedded in UIScrollView scroll only a little? In my UIViewController I put a UIScrollView and attached constraints:

Then I added a view to this scroll view with following constraints:

and positioned it like this:

so as you can see it is quite long. When I run the app I can scroll it just for couple pixels instead of completely to the top of the screen. I want to make it possible to scroll it to the top so that it can cover everything what's under it. So what am I doing wrong here?
========= EDIT
for clarification - I want to achieve an effect that when user opens this screen, 10% of the screen is covered by the view. User can slide up this view and then it covers 90% of the view. And he can slide it down back to the 10%. Can you help me with adjusting constraints so that it looks good on every screen size?

A: Take a UIView inside the UIScrollView.
Set the constraint for scroll view as leading, trailing, top, bottom.
Select UIViewController in the story board and click size inspector then choose freeform then set the view height as bigger.
Then set constraint of UIView is leading , trailing , top , bottom as 0, so that the UIView will be same as ScrollView region. Now set height constraint something bigger so that you can design image view, label 1 and label 2. Then set constraint like the image view : top to UIView, leading , trailing and height.
For label 1: leading, trailing , vertical to UIImageView, height.
For label 2: leading, trailing , vertical to label 1, height and bottom to UIView (Important as based on this content view will be set).

After setting constraint You can select UIViewControl from story board and set the SizeInspector as fixed as it was before.
It will show the screen as you need (Image view, below label 1 and on scrolling label 2)
I have  tested it in my demo project.
Hope it helps


text:
Q: How to format a big number with different bigmarks for thousand and millions (i.e. 1'000,000) in R Some countries use apostrophes "'" as million marks, and commas "," for thousand marks as in 1'234,567. Is there a way to custom format numbers to do so?
I have only found answers that round numbers and add some letters as in 1.3B, or deal with this issue in javascript, which I don't speak.
Format and prettyNum documentation seem to have only a big.mark argument with no option to set different ones within the same number.

A: I would write my own function to do that, check the logic here.
custom_format <- function(number, msep = "'", tsep = ",") {
  number = format(number, scientific = FALSE)

  dplyr::case_when(
    # for millions
    nchar(number) <= 9 & nchar(number) > 6 ~
      stringr::str_replace(
        number,
        "([0-9]+)([0-9]{3})([0-9]{3})$",
        paste0("\\1", msep, "\\2", tsep, "\\3")
      ),
    nchar(number) <= 6 & nchar(number) > 3 ~
      stringr::str_replace(
        number,
        "([0-9])([0-9]{3})$",
        paste0("\\1", tsep, "\\2")
      ),
    nchar(number) <= 3 ~ number,
    # For Thousands
    TRUE ~ number
  )
}

number <- c(10, 1500, 1000, 1000000, 23000, 234000000)
purrr::map_chr(number, custom_format)
#> [1] "10"          "1,500"       "1,000"       "1'000,000"   "23,000"
#> [6] "234'000,000"

Created on 2022-09-29 by the reprex package (v2.0.1)


text:
Q: How to prevent keyboard buffering on droid VNC server I'm going to answer my own question here.
The question is: how do I prevent Droid VNC Server from buffering key events and not sending them to Android's input system until there's a pointer (mouse / gesture / tap etc.) event?
I am using a custom build of Droid VNC Server from Droid VNC Server on GitHub on Android x86.
The problem I was finding is I would type a series of characters on the keyboard in some editable text field but they wouldn't appear until I touched somewhere on the screen (being careful not to let the text field lose focus) thus causing a mouse event.

A: In /jni/vnc/inputMethods/input.c there's a method keyEvent where I added one line of code to flush the key events in 'realtime':
void keyEvent(rfbBool down, rfbKeySym key, rfbClientPtr cl)
{
....
if (key && down)
{
....
}
// Added this to "flush" out key events as they come in achieving real-time
// character input on Android
suinput_write(inputfd, EV_SYN, SYN_REPORT, 0);


text:
Q: Stripe Checkout Loading Indicator Does Not Go Away I am using Stripe's custom integration, I know in their example they are adding an event listener, but in my javascript code I am skipping that, not sure if that is why the loading indicator never goes away when someone closes out of it.
Here is my code:
 var handler = StripeCheckout.configure({
                key: 'tests',
                image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
                locale: 'auto',
                token: function(token) {
                    // You can access the token ID with `token.id`.
                    // Get the token ID to your server-side code for use.

                },

closed: function() {
                // Close Checkout on page navigation:
                closehandler();

            }
        });
        handler.open({
            name: 'Jungle Exchange',
            description: 'Get your Amazon On!',
            amount: amount
        });

        function closehandler() {
            handler.close();
        }

When clicking on the x for the modal, the loading icon does not disappear from the center of the screen and overlays everything. Any thoughts?
Thanks!

A: That seems unexpected! I'd recommend writing into Stripe support with the exact URL with this happened and different things you've tried, as well as any errors in your Web Inspector console.
https://support.stripe.com/email/login


text:
Q: Include \maketitle in table of contents to compile "book" of IEEE articles Background:
I am creating a compilation of multiple IEEE format articles. This compilation will have a single table of contents. Each paper includes a title and \maketitle command. I would like the TOC to include the title of each paper as the primary level, along with all the sections/subsections etc.
    \documentclass[journal]{IEEEtran}

    \begin{document}
    \onecolumn
    \tableofcontents
     \twocolumn

    % Title and Author information  Paper 1
        \title{Title 1}
        \author{Author 1}
        % Make the title area
        \maketitle
       $ Paper Content

    % Title and Author information  Paper 2
        \title{Title 2}
        \author{Author 2}
        % Make the title area
        \maketitle
       $ Paper Content

\end{document}

Should generate a TOC that approximates this:

*

*Title 1
I - Section 1
I-A Subsection 1
I-B Subsection 2
II - Section 2

*Title 2
I - Section 1
I-A Subsection 1
I-B Subsection 2
II - Section 2
Question:
How can I modify the TOC to include titles?
I am open to other suggestions. I realize that the ieeetran or other article/journal classes do not use \chapter or \part commands, but if there was a way to force this operation while not changing the class, I would be interested in such a solution as well.

A: \maketitle is a command, which 'disables' itself right before the end of the macro (well, it is \relaxed then). As such, a further call to this macro will provide nothing. By using a patch command, this \let\maketitle\relax can be catched and a \addcontentsline command injected instead, which will do the ToC entry then.
I further introduced a titlecounter counter, which is automatically refstepped, so that \label should also work. The format of the ToC entry is quite simple at the moment -- change at will.
Mico had an important objection: There should be a \clearpage right at the start of the \maketitle command, which will shipout possible floats from the preceeding article. However, I restricted this behaviour to the 2nd etc. \maketitle.
\documentclass[journal]{IEEEtran}

\usepackage{etoolbox}%
\usepackage{xpatch}
\usepackage{blindtext}

\makeatletter
\newcounter{titlecounter}
\xpretocmd{\maketitle}{\ifnumgreater{\value{titlecounter}}{1}}{\clearpage}{}{} % Well, this is lazy at the end ;-)

\xpatchcmd{\maketitle}{\let\maketitle\relax\let\@maketitle\relax}{\refstepcounter{titlecounter}\addcontentsline{toc}{section}{\protect{\numberline{\thetitlecounter}{\@title~ \@author}}}}{\typeout{Patching was successful}}{\typeout{patching failed}}%
\makeatother
\begin{document}
\onecolumn
\tableofcontents
\twocolumn

% Title and Author information  Paper 1
\title{Title 1}
\author{Author 1}
% Make the title area
\maketitle
\blindtext[10]
%$ Paper Content

% Title and Author information  Paper 2
\title{Title 2}
\author{Author 2}
% Make the title area
\maketitle
\blindtext[20]
%$ Paper Content

\end{document}

Version with level indentation
Use \setlength{\articlesectionindent}{10pt} (or any other appropiate value), in order to get the indentation of levels relative to the title toc entry.
The resetting of sections etc. is done with the command \@addtoreset{section}{titlecounter}, i.e. each time the titlecounter is stepped, the sections are reset (and consecutively the subsections etc. as well)
\documentclass[journal]{IEEEtran}

\usepackage{etoolbox}%
\usepackage{xpatch}
\usepackage{blindtext}
\usepackage{tocloft}%

\newlength{\articlesectionshift}%
\setlength{\articlesectionshift}{10pt}%
\addtolength{\cftsecindent}{\articlesectionshift}%

\makeatletter
\newcounter{titlecounter}
\xpretocmd{\maketitle}{\ifnumgreater{\value{titlecounter}}{1}}{\clearpage}{}{} % Well, this is lazy at the end ;-)
\xpatchcmd{\maketitle}{\let\maketitle\relax\let\@maketitle\relax}{\refstepcounter{titlecounter}\begingroup
  \addtocontents{toc}{\begingroup\addtolength{\cftsecindent}{-\articlesectionshift}}%
  \addcontentsline{toc}{section}{\protect{\numberline{\thetitlecounter}{\@title~ \@author}}}%
  \addtocontents{toc}{\endgroup}}{\typeout{Patching was successful}}{\typeout{patching failed}}%

\@addtoreset{section}{titlecounter}

\makeatother
\begin{document}
\onecolumn
\tableofcontents
\twocolumn

% Title and Author information  Paper 1
\title{Title 1}
\author{Author 1}
% Make the title area
\maketitle

\section{First}
\subsection{First subsection of 1st section}%
\subsection{2nd subsection of 1st section}%
\subsection{3rd subsection of 1st section}%
\subsection{4th subsection of 1st section}%

\blindtext[10]
\section{Two}
\subsection{First subsection of 2nd section}%

% Title and Author information  Paper 2
\title{Title 2}
\author{Author 2}
% Make the title area
\maketitle
\section{First from second paper}
\subsection{First subsection of 2nd section of 2nd article}%

\blindtext[20]

%$ Paper Content

\end{document}

** Warning ** Both versions will fail in conjunction with hyperref package. It's some issue with the \footnotemark command.


text:
Q: phonegap html5 android synchonous Filesystem IO How can I read and write files synchronously, using PhoneGaps Filesystem API?
Is there a an synchronous wrapper available?

A: There is no way to access files synchronously through the provided api. Guessing from the way phonegap is implemented i doubt that you can write a plugin to do this synchronously.

A: Because of the way the Java-to-JavaScript bridge on Android works, it is pretty much impossible to do a synchronous implementation of File IO. This is because each Java object in Android that is bound to the JavaScript environment runs on its own thread.
Use the existing File API available in PhoneGap - but use it asynchronously. Register a callback with it that will notify your app that an IO process is complete.


text:
Q: Xamarin.UITest Screenshot location I've got a problem with Xamarin.UITest, specifically screenshot feature. It is not working as expected.
I'm trying to copy "created" screenshot to another directory, but I get the following error:

Message: System.IO.FileNotFoundException : Could not find file
  'C:\Program Files (x86)\Microsoft Visual
  Studio\2017\Enterprise\Common7\IDE\screenshot-1.png'.

I'm using this piece of code to copy image file:
var screen = app.Screenshot("Welcome screen.");
screen.CopyTo(@"C:\Users\someuser\Desktop\screenshotTest.png");

How to specify first path/location for screenshots, because the original path probably needs admin privileges, that I don't have.

A: Screenshots saved with App.Screenshot() are located in your test project's directory: MyTestProject"\bin\Debug folder where the first screenshot is named screenshot-1.

A: Half solution to the problem: I downgraded NUnit from 3.11.0 to 2.7.0, so it works OK.

A: Use MoveTo() insted of CopyTo().
var screenshot = app.Screenshot($"{DateTime.Now}_{platform}");
screenshot.MoveTo($@"{Destination}\{screenshot.Name}.{screenshot.Extension}");

A: My screenshots are saving to C:\Users\username\AppData\Local\Temp
Try this code
[TearDown]
public void Teardown()
{
   SaveScreenshotIfTestFails();
}

private void SaveScreenshotIfTestFails()
{
   if (TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Failed)
   {
      var testName = TestContext.CurrentContext.Test.Name;
      var filename = $"{testName}.png";
      var file = app.Screenshot(testName);
      var dir = file.DirectoryName;
      File.Delete(dir + "\\" + filename);
      file.MoveTo($"{testName}.png");
   }
}

A: Screenshots are saved to the Current Directory. Change it via Directory.SetCurrentDirectory.


text:
Q: Accessing Models in Partialview I am developing an asp mvc application.  I want to access currently logged in user name in partial view. I have checked most answers available on net.I will explain my scenario
My child action is
  public ActionResult LoggedInUserActions()
    {
        var userId = User.Identity.GetUserId();
        var user = dbcontext.Users.SingleOrDefault(a => a.Id == userId);
        return PartialView("_HelloUser", user);
    }

in layout iam using
@Html.Action("LoggedInUserActions")

My hellouser partial view contains
 @using Microsoft.AspNet.Identity
    @if (Request.IsAuthenticated) {

    using (Html.BeginForm("LogOff", "Account",new{area=""}, FormMethod.Post, new { @class = "navbar-right" }))
    {
                @Html.AntiForgeryToken()

Hello! @Model.?

                    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" style="margin-left:8px">
                        Action

                    </button>

                        @*
My Orders
*@

@Html.ActionLink("My Account", "Index","Home", new { Area="User"},null)

                        @*

*@

<button type="submit" class=" " style="width: 100%;background-color: darkorange">Log Off</button>

            }
            }

My question is how can i access the user details i accessed from action method to this partial view? is this a good method to access currently logged in users first name? Can someone help me?

A: Your partial view must be typed after the model you want. Add a declaration such as:
@model MyClass

and then you will be able to access it through the @Model property.
Another alternative is to use the view bag for sending data. In this case, you need to get hold of the action result and add data to its view bag:
var result = PartialView("_HelloUser", user);
result.ViewData["Key"] = Value;  //do change Key and Value
return result;


text:
Q: Enqueue CDN in WordPress I've had a look at this question
How to enqueue scripts in WordPress from CDN?
But it isn't working.
I'm trying to install this rangeSlider http://ionden.com/a/plugins/ion.rangeSlider/start.html but I can't get it to work.
I've tried to put the CDN in the header, and then follow the steps, but it didn't work.
I've tried to put the CDN in my footer, to no avail, as well as installing with npm.
My functions enqueue script currently looks like this, so I do have jQuery enqueued. I have tried to put ion-range styles and scripts in here.
function chd_scripts() {
    wp_enqueue_script('jquery');
    wp_enqueue_style( 'chd-style', get_stylesheet_uri() );
    wp_enqueue_script( 'chd-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20151215', true );
    wp_enqueue_script( 'chd-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20151215', true );
    wp_register_style( 'ion_range', 'https://cdnjs.cloudflare.com/ajax/libs/ion-rangeslider/2.3.1/css/ion.rangeSlider.min.css' );
    wp_enqueue_style('ion_range');
    wp_register_script( 'ion_js', 'https://cdnjs.cloudflare.com/ajax/libs/ion-rangeslider/2.3.1/js/ion.rangeSlider.min.js', null, null, true );
wp_enqueue_script('ion_js');
    if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
        wp_enqueue_script( 'comment-reply' );
    }
    wp_enqueue_script ('modernizr', get_template_directory_uri() . '/js/modernizr-custom.js');
    wp_enqueue_script ('lazy', get_template_directory_uri() . '/js/jquery.lazyload.min.js');
    wp_enqueue_style ('global', get_template_directory_uri() . '/css/global.css');
    wp_enqueue_script ('scripts', get_template_directory_uri() . '/js/scripts.js');
    wp_localize_script ('scripts', 'js_variables', array ('js_home_url' => home_url(), 'ajaxURL' => admin_url( 'admin-ajax.php' ), ''));
}
add_action( 'wp_enqueue_scripts', 'chd_scripts' );

And have put this on my front page
<input type="text" class="js-range-slider" name="my_range" value="" />

And this in my scripts
$(".js-range-slider").ionRangeSlider({
  type: "double",
  min: 0,
  max: 1000,
  from: 200,
  to: 500,
  grid: true
});

However, my input field is still default.
Any ideas?

A: https://developer.wordpress.org/reference/functions/wp_enqueue_script/
You have to define "jquery" as dependency so that it will be loaded before your cdn dependency


text:
Q: How to stop SwingWorker.doInBackground process immediately? According to Oracle docs SwingWorker.doInBackground does not include any code that might throw InterruptedException". Dunno if I'm right about what I understand, but I noticed that cancelling the doInBackground process prints out the InterruptedException so it'll continue even if an Exception is encountered? Then how can we cancel and stop the process immediately?
So I tried return STATUS; when it is cancelled but still continues. I also tried PROCESS.destroyForcibly() before return but still the same. How to stop it immediately once cancelled?
import ...

public class Test {

    private BackgroundProcess BG_PROCESS;
    private JFileChooser FILE_CHOOSER;
    private JProgressBar PROGRESS_BAR;

    public Test() {
        initComponents();
    }

    ...

    private class BackgroundProcess extends SwingWorker<Integer, String> {

        private int STATUS;

        @Override
        protected Integer doInBackground() throws Exception {

            File[] SELECTED_FILES = FILE_CHOOSER.getSelectedFiles();

            for (int i = 0; i < SELECTED_FILES.length; i++) {

                String file = SELECTED_FILES[i].getAbsolutePath();
                String name = SELECTED_FILES[i].getName();

                String[] command = {"javac", "" +file+ ""};

                try {
                    ProcessBuilder PROCESS_BUILDER = new ProcessBuilder(command);
                    Process PROCESS = PROCESS_BUILDER.start();
                    if (!isCancelled()) {
                        STATUS = PROCESS.waitFor();
                        if (STATUS == 0) {
                            TEXTAREA.append(name+ "Successfully compiled.");
                        } else {
                            TEXTAREA.append(name+ "Failed. (not compiled)");
                        }
                    } else {
                        TEXTAREA.append("Compilation cancelled.");
                        return STATUS;
                    }
                    PROCESS.destroy();
                } catch (IOException | InterruptedException ex) {
                    ex.printStackTrace(System.err);
                }
            }

            return STATUS;
        }
    }

    public static void main(String[] args) {
        new Test();
    }
}

Start BackgroundProcess
JButton START = new JButton("Start");
START.addActionListener(new ActionListener() {
    @Override
    ...

    BG_PROCESS = new BackgroundProcess();
    BG_PROCESS.execute();
    PROGRESS_BAR.setIndeterminate(true);
});

Cancel BackgroundProcess
JButton CANCEL = new JButton("Cancel");
CANCEL.addActionListener(new ActionListener() {
    @Override
    ...

    BG_PROCESS.cancel(true);
    PROGRESS_BAR.setIndeterminate(false);
});


text:
Q: How can I use if else statement instead of try and catch exception in this code  int age=0,maleCount=0,totalNumberOfMembers=0,younger=1000;
   double sum=0;
    String gender,str;
    FileReader fr=null;
    PrintWriter pw = null;

How can I use if and else statement instead of try and catch exception in this code
   // try and catch block to catch exception if file not found
    try
    {
        fr = new FileReader("MyData.txt");
        pw = new PrintWriter("Results.txt");
    }
    catch (FileNotFoundException fe)
    {
        System.out.println("File not found");
    }
    File file = new File("MyData.txt");
    try {
        Scanner sc = new Scanner(file);
        while(sc.hasNextLine()){
            // we just need to use \t as delimiter
            sc.useDelimiter("\t");
           str = sc.next().trim();
           if(!str.isEmpty()){
            age = Integer.parseInt(str);
            sum += age;
           }else{
               break;
           }
            if(age<younger)
                younger = age;
            sc.useDelimiter("\t");
            gender = sc.next().trim();
            if(gender.equals("Male"))
                maleCount++;
            sc.useDelimiter("\n");
            sc.next().trim();
            totalNumberOfMembers++;
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    pw.write("Average age: "+sum/totalNumberOfMembers+"\n");
   pw.flush();
    pw.write("Youngest age: "+younger+"\n");
   pw.flush();
    pw.write("Number of male members: "+maleCount+"\n");
   pw.flush();
}

How can I use if else statement instead of try and catch exception in this code


text:
Q: SSH Restrict User Access When I ssh into the machine as webmaster I ssh into the correct chroot directory var/www/domainname/public_html but I can still access the entire filesystem.
I have changed the home ssh directory of webmaster successfully.   Now I want to restrict webmaster access to the home directory.  I started following this article.  I am failing Step 5: Testing SSH with Chroot Jail because when I ssh from webmaster on my laptop into the main server with webmaster account.  Webmaster can still see the entire filesystem.  Should only see /var/www/domainname/public_html/
When I cat /var/log/secure | egrep webmaster I see successful connections to the server however nothing in relation to the chroot directory. sshd[22528]: Accepted password for webmaster from ip port # ssh2
I added the following lines in /etc/ssh/sshd_config
#define username to apply chroot jail to
Match User webmaster
#specify chroot jail
ChrootDirectory /var/www/domainname/

Here are the file permissions in the directory I want webmaster restricted to.
drwxr-xr-x.   8 root root   4096 Dec 17 19:37 archive
-rwxr-xr-x.   1 root root 964536 Jan 11 11:00 bash
-rwxr-xr-x.   1 root root 964536 Jan 11 11:01 bin
drwxr-xr-x.   2 root root     33 Jan 11 11:04 etc
drwxr-xr-x.   2 root root      6 Jan 11 11:03 lib64
drwxr-xr-x. 237 root root  12288 Dec 22 15:40 node_modules
crw-rw-rw-.   1 root root   1, 3 Jan 11 10:58 null
-rw-r--r--.   1 root root    545 Dec 22 15:56 package.json
-rw-r--r--.   1 root root 111876 Dec 22 15:40 package-lock.json
drwxr-xr-x.  10 root root   4096 Jan  3 15:18 public_html
crw-rw-rw-.   1 root root   1, 8 Jan 11 10:58 random
drwxr-xr-x.   4 root root     27 Dec 30 12:02 src
crw-rw-rw-.   1 root root   5, 0 Jan 11 10:58 tty
crw-rw-rw-.   1 root root   1, 5 Jan 11 10:58 zero


text:
Q: Inserting number in an array How do I add a number(73) into the middle of an array and then move all the numbers from the middle up one so no number is overwriting. Here is my code so far the 73 should go into the middle and the numbers after it should all move over. Can't use an ARRAYLIST.
int midpoint = length/2;
array[midpoint] = 73;

for (int i = midpoint; i<length; i++){
    aNums[i+1] = array[i];
    System.out.print(array[i] + " ");
}

displayArray1(array,length);

A: Use a List, or more specifically an ArrayList:
ArrayList<Integer> list = new ArrayList<>();

// ... put stuff in list

int midpoint = list.size()/2;
list.add(midpoint, 73);

A: You can't add to an array. You first have to create a bigger array.
int[] newArray = new int[array.length + 1];

Then you have to copy the first half of the array
for(int i = 0; i < midpoint; i++) {
    newArray[i] = array[i];
}

Then put the new midpoint in
newArray[midpoint] = 73;

Then copy the other half
for(int i = midpoint + 1; i < array.length; i++) {
    newArray[i+1] = array[i];
}

And then newArray has the new midpoint.
Technically the last three steps could be done in any order, but it is much more readable to do them in that order. Now you can call your display method or really do whatever you want with it.
There is a utility method called arrayCopy that can assist with moving the array elements. You may or may not be permitted to use it. It's a bit wordy with its parameters, but is a bit faster than a typical for-loop at runtime because it leverages native code.
int[] newArray = new int[array.length + 1];
System.arrayCopy(array,0,newArray,0,midpoint);
newArray[midpoint] = 73;
System.arrayCopy(array,midpoint,newArray,midpoint+1,array.length - midpoint);

To explain those calls, the arraycopy uses:
System.arrayCopy(arrayFrom,
                 startPosInArrayFrom,
                 arrayTo,
                 startPosInArrayTo,
                 numElementsToCopy);

A: you are causing yourself a lot more trouble using an array.
use an ArrayList, which is backed by an array
ArrayList l = new ArrayList();

//...fill contents
int index = l.size()/2;
l.add(index, 72);


text:
Q: Node.js child process isn't receiving stdin unless I close the stdin stream I'm building a discord bot that wraps a terraria server in node.js so server users can restart the server and similar actions.  I've managed to finish half the job, but I can't seem to create a command to execute commands on the terraria server.  I've set it to write the command to the stdin of the child process and some basic debugging verifies that it does, but nothing apparently happens.
In the Node.js docs for child process stdin, it says "Note that if a child process waits to read all of its input, the child will not continue until this stream has been closed via end()."  This seems likely to be the problem, as calling the end() function on it does actually send the command as expected.  That said, it seems hard to believe that I'm unable to continuously send commands to stdin without having to close it.
Is this actually the problem, and if so what are my options for solving it?  My code may be found below.
const discordjs = require("discord.js");
const child_process = require("child_process");
const tokens = require("./tokens");

const client = new discordjs.Client();

const terrariaServerPath = "C:\\Program Files (x86)\\Steam\\steamapps\\common\\Terraria\\TerrariaServer.exe"
const terrariaArgs = ['-port', '7777', "-maxplayers", "8", "-world", "test.wld"]

var child = child_process.spawn(terrariaServerPath, terrariaArgs);

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
});
client.on('disconnect', () => {
    client.destroy();
});

client.on('message', msg => {
    if (msg.channel.name === 'terraria') {
        var msgSplit = msg.content.split(" ");
        if (msgSplit[0] === "!restart") {
            child.kill();
            child = child_process.spawn(terrariaServerPath, terrariaArgs);
            registerStdio();
            msg.reply("restarting server")

        }
        if (msgSplit[0] === "!exec") {
            msg.reply(msgSplit[1]);
            child.stdin.write(msgSplit[1] + "\n");
            child.stdin.end();
        }
    }
});

client.login(tokens.discord_token);
var registerStdio = function () {
    child.stdout.on('data', (data) => {
        console.log(`${data}`);
    });

    child.stderr.on('data', (data) => {
        console.error(`${data}`);
    });
}
registerStdio();

A: I was able to solve the problem by using the library node-pty.  As near as I can tell, the problem was that the child process was not reading the stdin itself and I was unable to flush it.  Node-pty creates a virtual terminal object which can be written to instead of stdin.  This object does not buffer writes and so any input is immediately sent to the program.


text:
Q: Selecting by :class or :id in seesaw Here is from the seesaw tutorial:
(def rbs (for [i [:source :doc]]
          (radio :id i :class :type :text (name i))))

(display (border-panel
           :north (horizontal-panel :items rbs)
           :center split
           :vgap 5
           :hgap 5
           :border 5))

(select f [:JRadioButton])
(select f [:.type])
(select f [:#source])

When selecting by :class, a dot was added in :type so we got :.type, and when selecting by id, a # was added so we got :#source, why so?

A: That's just part of the syntax for selectors that let you specify what you want to select.
The docstring for the select function documents the full selector syntax.  I won't copy the entire docstring, but here are some highlights:
[:#id]            ID
[:tag]            "Simple" (not fully-qualified) class name
[:<class-name>]   Fully-qualified class name; also matches subclasses
[:<class-name!>]  Exact class match
[:.<class>]       "Class" match, as set using :class option
[:*]              Everything

Examples of each:
;; Widget with ID box1.
(select root [:#box1])
;; Class Label, e.g. com.myns.Label or org.foo.Label.
(select root [:Label])
;; javax.swing.text.JTextComponent and descendants.
(select root [:<javax.swing.text.JTextComponent>])
;; Only javax.swing.text.JTextComponent
(select root [:<javax.swing.text.JTextComponent!>])
;; Class class1, e.g. (flow-panel :class :class1)
(select root [:.class1])
;; Everything
(select root [:*])

Note also that these can be combined, e.g.
;; Everything under widgets with class javax.swing.text.JTextComponent
;; (or subclasses) and class input.
(select root [:<javax.swing.text.JTextComponent>.input :*])


text:
Q: c# exception not caught I have a method that is a listener for a TCP client which looks like this:
    private static void ProcessClient(
        Object obj)
    {
        ISession session = (ISession)obj;
        NetworkStream networkStream = null;

        try
        {
            DebugUtility.SetThreadName("Worker: {0}", session.Name);
            networkStream = session.TcpClient.GetStream();
            networkStream.ReadTimeout = Config.ReadTimeout;

            // Loop received packets (blocks untill next packet)
            Int32 packetSize;
            Byte[] buffer = new Byte[session.PacketSize];
            while ((packetSize = networkStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                // Get String from packet  bytes
                String packet = Encoding.UTF8.GetString(buffer, 0, packetSize);

                // Check if packet has data
                if (String.IsNullOrEmpty(packet))
                    continue;

                // Log biggest received package
                DebugUtility.CheckMaxPacketSize(session.Name, packet.Length);

                // Handle packet (in new thread)
                Logger.DebugLog("Received: {0}", packet);
                ThreadPool.QueueUserWorkItem(session.HandlePacket, packet);
            }
        }
        catch (ObjectDisposedException) { }
        catch (NotSupportedException) { }
        catch (TimeoutException) { }
        catch (SocketException) { }
        catch (IOException) { }
        catch (Exception ex)
        {
            Logger.LogException(ex);
        }
        finally
        {
            if (networkStream != null)
                networkStream.Close();

            if (session != null)
                session.Disconnect();
        }
    }

This is for a game service but when I check my logs, I occasionally see this error:
System.Int32 Read(Byte[], Int32, Int32): The stream does not support reading.
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at BusinessLayer.Listener.ListenerWorker.ProcessClient(Object obj) in C:\path\ListenerWorker.cs:line 141 Line: 0

That is the above described file and line 141 is
        while ((packetSize = networkStream.Read(buffer,....

Now I have found that NotSupportedException is throwing this error, but why does it go through? Why is it not ignored but does it fall through the normal Exception ex handler?
Edit: Does anyone know how I can invoke this exception? When does it occur? I only see it coming back in my logs to other users, but I don't know when it happens.

A: Because NetworkStream.Read is throwing an InvalidOperationException, not a NotSupportedException (contrary to the documentation). You can confirm this from Reflector:
if (!this.CanRead)
{
    throw new InvalidOperationException(SR.GetString("net_writeonlystream"));
}

A: Never ever ever swallow an exception unless you are 100% sure that you can do something about it and recover from it. Swallowing all exceptions implies that whatever happens  your program can recover and continue. What if it's an OutOfMemoryException or a StackOverflowException, can you program handle those gracefully? Yes log the exception, but for the love of god, rethrow it and let it do its job :)