text:
Q: How to find the smaller of two binary numbers with basically only bitwise logic? is there a simple way to find the smaller of two binary numbers (signed in two's complement format), with only the following operations: bitwise logic, right shift, an add, an equality compare, and a jump if accu is negative?
I need this for an assignment to express some C snippets in a very minimal assembler language.
The only thing I came up with so far is a distinction of 3 cases:

*

*If one number is negative and the other positive we have the solution there.

*If both numbers are positive, add to both minus one and check for the first number to get zero, this is the smaller one.

*If both are negative, make them positive i.e. take the two's complement of both and go to step 2.
But this seems rather extensive for a "simple" less than condition.
Maybe I am just stupid and can't see the obvious solution :)

A: Okay, first of all, you do know this is possible -- those operations are all there really is for bit manipulation.  So what's, first of all, the simplest possible thing?  A loop like this
loop
  Set A to one closer to zero
  Set B one closer to zero
until either A is 0 or B is zero

When you get either A or B to zero, then that one is the smaller.  Observe that this works for either two negatives or two positives.  So now you have a known solution; conveniently, you have an add instruction so you don't need to implement that.
But that's O(n).  What can you do better? (Hint: you should be able to get O(lg n).)
Consider what a right-shift is in  a binary number: it's essentially division by 2.
See if that hint helps any.
Here's an alternate thought: if you have a word-width add, how can you turn an addition into a subtraction?  If you can do that,. you can subtract A from B and see how the difference comes out.


text:
Q: c# search data on gridview error in SQL syntax I am trying to find the data 'surti' in the textbox and I get an error :
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '%'surti%'' at line 1
private void button5_Click(object sender, EventArgs e)
        {
            MySqlConnection cmd;
            cmd = koneksi;
            cmd.Open();
            MySqlCommand sql = new MySqlCommand("Select * from pelanggan where nama_pelanggan like %'" +textBox4.Text+"%'",cmd);
            MySqlDataAdapter ql = new MySqlDataAdapter(sql);
            DataTable tb = new DataTable();
            ql.Fill(tb);
            dataGridView1.DataSource = tb;
        }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change the color theme of Kivy's FileChooser For some reason, the FileChooser Popup comes with a dark theme by default. How can it be changed to a normal/bright theme without manually redefining the appearance of each and every element in the kv style file?
Side note: I don't understand why Kivy comes with dark default colors in the first place, and why there is no easy way to change it. Not even MD themes appear to be convenient, because they require to rewrite all standard classes (e.g. MDRaisedButton instead of Button). But maybe these are topics for another discussion...

A: You can do something like:
Builder.load_string('''
<FileChooserListView>:
    canvas.before:
        Color:
            rgba: 0.5,0,0,1
        Rectangle:
            size: self.size
''')

to add a little color.


text:
Q: Passbook generates PKPass error I add passbook in my app, when the system is iOS6.0 it work correctly.When the system is iOS7.1 it appear an error.

I check the code found that
PKPass *newPass = [[PKPass alloc] initWithData:passData error:&error];

When generate PKPass in iOS6.0 get a correct PKPass,when the system is iOS7.1 get a nil.
The error contain message is that:
Error Domain=PKPassKitErrorDomain Code=1 "The pass cannot be read because it isn't valid." UserInfo=0x175cd2f0 {NSUnderlyingError=0x175c2c10 "more than one field has the key 'phone'. Field keys must be unique.", NSLocalizedDescription=The pass cannot be read because it isn't valid.}
The data of the passbook i get it from server.Code like follow
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.connectionData appendData:data];
}

After get the data write to file,code like follow:
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);
NSString* filePath  = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"pk.pkpass"];

if ([self.connectionData writeToFile:filePath atomically:YES]) {

    if (![PKPassLibrary isPassLibraryAvailable]) {

        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error"
                                                     message:@"PassKit not available"
                                                    delegate:nil
                                           cancelButtonTitle:@"Pitty"
                                           otherButtonTitles:nil];
        [alert show];
        [alert release];

        return;
    }
}

After write to file i want to show it,code like follow:
    NSString* passFile = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES) objectAtIndex:0] stringByAppendingPathComponent:name];

NSString * newPassStr = [[NSString alloc] initWithContentsOfFile:passFile encoding:NSUTF8StringEncoding error:nil];

NSData *passData = [NSData dataWithContentsOfFile:passFile];

NSError* error = nil;
PKPass *newPass = [[PKPass alloc] initWithData:passData error:&error];

Then when i get the PKPass *newPass appear the error in iOS7.1. In iOS6 it's OK.
Anyone can tell me the reason?A lot of thanks.

A: Your error message is telling you everything you need to know.
You have duplicate keys in your pass.json.  Your backFields array and your auxiliaryFields array both contain an item with the key phone.  According to the Passbook Package Format Reference, field keys have to be unique.
I notice that this pass has been generated using Passsource.  You might want to let kudit (the Passsource developer) know because his service should not allow such a pass to be generated.


text:
Q: Show that $(\sum_{k=1}^{n}k^{-1}-\sum_{k=1}^{n}k^{-2})/(\log n)\longrightarrow 1$ as $n\longrightarrow\infty$ As the title of this post, how could I show

$$\dfrac{\sum_{k=1}^{n}k^{-1}-\sum_{k=1}^{n}k^{-2}}{\log n}\longrightarrow 1\ \text{as}\ n\longrightarrow\infty.$$

My attempt is the following:
To make $$\dfrac{\sum_{k=1}^{n}k^{-1}-\sum_{k=1}^{n}k^{-2}}{\log n}\longrightarrow 1,$$ equivalently we can show that as $n\rightarrow\infty$, we have $$1\leq\dfrac{\sum_{k=1}^{n}k^{-1}-\sum_{k=1}^{n}k^{-2}}{\log n}\leq 1,$$  which is the same as $$1\leq\dfrac{\log n}{\sum_{k=1}^{n}k^{-1}-\sum_{k=1}^{n}k^{-2}}\leq 1,$$ so that we want to show firstly, we have $$\sum_{k=1}^{n}k^{-1}-\sum_{k=1}^{n}k^{-2}\leq\log n\leq \sum_{k=1}^{n}k^{-1}-\sum_{k=1}^{n}k^{-2},$$ and $$\sum_{k=1}^{n}k^{-1}-\sum_{k=1}^{n}k^{-2}\longrightarrow 1\ \text{as}\ n\longrightarrow\infty.$$
However, I am not able to show neither of them...
Am I heading to a wrong direction?
Thank you!
Edit 1:
This edit follows the proof from "user284331"
Since $x\mapsto\dfrac{1}{x}$ is decreasing, we have $$\sum_{k=2}^{n}\dfrac{1}{k}\leq\int_{1}^{n}\dfrac{1}{t}dt\leq\sum_{k=1}^{n}\dfrac{1}{k}.$$
Thus, by noting that $\sum_{k=1}^{\infty}\dfrac{1}{k^{2}}<\infty$ and $\int_{1}^{n}\dfrac{1}{t}=\log (n)$, we have
\begin{align*}
\dfrac{\sum_{k=1}^{n}\dfrac{1}{k}-\sum_{k=1}^{n}\dfrac{1}{k^{2}}}{\log n}&\geq\dfrac{\int_{1}^{n}\dfrac{1}{t}-\sum_{k=1}^{n}\dfrac{1}{k^{2}}}{\log n}\\
&=\dfrac{\log(n)-\sum_{k=1}^{n}\dfrac{1}{k^{2}}}{\log n}\\
&=1-\dfrac{\sum_{k=1}^{n}\dfrac{1}{k^{2}}}{\log n}\longrightarrow 1,
\end{align*}
and
\begin{align*}
\dfrac{\sum_{k=1}^{n}\dfrac{1}{k}-\sum_{k=1}^{n}\dfrac{1}{k^{2}}}{\log n}&=\dfrac{1+\sum_{k=2}^{n}\dfrac{1}{k}-\sum_{k=1}^{n}\dfrac{1}{k^{2}}}{\log n}\\
&\leq \dfrac{1+\int_{1}^{n}\dfrac{1}{t}-\sum_{k=1}^{n}\dfrac{1}{k^{2}}}{\log n}\\
&=\dfrac{1+\log(n)}{\log(n)}-\dfrac{\sum_{k=1}^{n}\dfrac{1}{k^{2}}}{\log n}\longrightarrow 1.
\end{align*}

A: Note that
\begin{align*}
\int_{1}^{n}\dfrac{1}{t}dt\leq\sum_{k=1}^{n}\dfrac{1}{k}\\
\sum_{k=2}^{n}\dfrac{1}{k}\leq\int_{1}^{n}\dfrac{1}{t}dt
\end{align*}
and
\begin{align*}
\sum_{n=1}^{\infty}\dfrac{1}{n^{2}}<\infty.
\end{align*}
So
\begin{align*}
\dfrac{\displaystyle\sum_{k=1}^{n}\dfrac{1}{k}-\sum_{k=1}^{n}\dfrac{1}{k^{2}}}{\log n}&\geq\dfrac{\displaystyle\int_{1}^{n}\dfrac{1}{t}dt-\sum_{n=1}^{\infty}\dfrac{1}{n^{2}}}{\log n}\\
&=1-\dfrac{1}{\log n}\sum_{n=1}^{\infty}\dfrac{1}{n^{2}}\\
&\rightarrow 1.
\end{align*}
On the other hand,
\begin{align*}
\dfrac{\displaystyle\sum_{k=1}^{n}\dfrac{1}{k}-\sum_{k=1}^{n}\dfrac{1}{k^{2}}}{\log n}&\leq\dfrac{1+\displaystyle\int_{1}^{n}\dfrac{1}{t}dt-\sum_{k=1}^{n}\dfrac{1}{k^{2}}}{\log n}\\
&=\dfrac{1}{\log n}+1-\dfrac{1}{\log n}\sum_{k=1}^{n}\dfrac{1}{k^{2}}\\
&\rightarrow 1,
\end{align*}
so the result follows by Squeeze Theorem.

A: $\sum_{k\geq 1}\frac{1}{k^2}=\zeta(2)$ is convergent, so its partial sums do not contribute to the value of the limit.
On the other hand the harmonic series is divergent, and by Cesàro-Stolz
$$ \lim_{n\to +\infty}\frac{H_{n}}{\log(n)}=\lim_{n\to +\infty}\frac{H_{n+1}-H_n}{\log(n+1)-\log(n)}=\lim_{n\to +\infty}\frac{\frac{1}{n+1}}{-\log\left(1-\frac{1}{n+1}\right)}=1. $$


text:
Q: HID lagging - dongled keyboard I am new to Ubuntu 19.04, but not new to Ubuntu as a whole. I wiped a 27 inch iMac (Mid 2011) a friend snagged in a college auction, and it's worked just fine as an Ubuntu machine- today I attempted to write using my trusted Microsoft bluetooth touchpad + keyboard. It skips keypresses terribly when I'm writing at length. If I type slowly, it's fine.
First, I changed the batteries in the keyboard. When that didn't fix the problem, I used a different USB port. Next, I checked the Accessibility settings. Then I checked to see if it could 'see' it's RAM- I thought next that the graphics driver was wrong, and it isn't (it's using Radeon BARTS, but CAYMAN also is listed for the Radeon 6970). Next, I tried Googling "Ubuntu 19.04 laggy", and ended up here.
It's a massive improvement over OSX Lion, even with the input lag. And it's all in one case is very sleek on my desk... But if I can't use it for lengthy text, it's useless to me.


text:
Q: Sierra Wireless AirCard 313U (AT&T Momentum 4G) on Ubuntu Linux I'm trying to get a Sierra Wireless AirCard 313U (more specifically, the AT&T Momentum 4G) working under Ubuntu Linux.
I've looked at a number of pages so far:
How to connect internet using AT&T USBConnect Momentum 4G (AC313U) on Ubuntu/Mint?
Can I use a Sierra Wireless Modem on Linux Machines (direct IP modems)?
Setting up a Bigpond NextG wireless connection on Linux
My understanding based on the above is that the Sierra Wireless drivers are already included with non-ancient Linux kernels, and the device should be automatically detected, with some /dev/ttyUSB* device files being created as a result. I don't see these files, however.
dmesg shows a couple lines like
[ 555.877426] usb 2-2: config 1 has an invalid interface number: 7 but max is 5

which appears to suggest that the device is in its software installation mode, rather than modem mode. I'm not sure how to get the device into modem mode; my understanding is the driver is supposed to be doing this anyway.
I've tried plugging in under Ubuntu 12.04 and 10.04.04, with basically the same results (i.e., device not detected). I was able to modprobe sierra and modprobe sierra_net (on 12.04 at least; 10.04.04 didn't seem to have the sierra_net module), so the drivers should be included.
The device did work on a couple Windows 7 machines I tried it on, though a funny thing is that it didn't automatically install its drivers like it was supposed to; I had to go download them from AT&T's website and install them myself.

A: I had an AT&T mobile 3G USB plug-in at my business back before cable-modem internet was available. It was my stand-by for when the DSL went out.
I discovered the easiest way to make it work was to have it plugged into the computer when installing Ubuntu. This was what we did to get internet when going on the road and needing to run peoples' credit cards from our POS app in ubuntu. I recall the Ubuntus we were using on the road were 10.04...?
When it was at work, these were the magic steps used to make it come online... ssh into the firewall ubuntu server (edited: just checked and the firewall is 9.04):
root@wall:~# cat do_this_for_3g.txt
nohup pppd call gsm &

# Then after DSL works, to kill the 3G...
ps aux | grep pppd
# root     18716  0.0  0.0   7528   888 pts/0    R+   12:08   0:00 grep pppd
# root     23021  0.0  0.1  21668  1316 pts/0    S    Mar15   0:00 pppd call gsm

kill 23021

/etc/init.d/networking restart

Notice that gsm_chat is a script in /etc/ppp/peers:
root@wall:/etc/ppp/peers# cat gsm_chat
# Connection script for Sierra Wireless GSM/UMTS modems
# Note: This demo script is setup to work on the Cingular EDGE network
#
SAY 'Starting Sierra Wireless GSM connect script...\n'
SAY '\n'

#######################################
SAY 'Setting the abort string\n'
SAY '\n'
# Abort String ------------------------------
ABORT 'NO DIAL TONE' ABORT 'NO ANSWER' ABORT 'NO CARRIER' ABORT DELAYED

#######################################
SAY 'Initializing modem\n'
# Modem Initialization
'' AT
OK ATZ

#######################################
SAY '\n'
SAY     'Setting APN\n'
# Access Point Name (APN)
# Incorrect APN or CGDCONT can often cause errors in connection.
# Below are a bunch of different popular APNs

#REG:\s1 AT+cgdcont=1,"IP","proxy"
#OK     'AT+CGDCONT=0,"IP","proxy"'
#OK     'AT+CGDCONT=1,"IP","proxy"'
#OK     'AT+CGDCONT=2,"IP","proxy"'
#OK     'AT+CGDCONT=0,"IP","ISP.CINGULAR"'
OK     'AT+CGDCONT=1,"IP","ISP.CINGULAR"'
#OK     'AT+CGDCONT=2,"IP","ISP.CINGULAR"'

#######################################
SAY '\n'
SAY     'Dialing...\n'
# Dial the ISP, this is the common Cingular dial string

OK ATD*99#
CONNECT ''


text:
Q: The MVC action controller generates a url with a token for the user to click on and view the page without logging in I need to send the user a url with a token so that the user can click on that link and view my page without logging in to the system. This user has been created in my system, but has not set a password, I want this user not to see the other pages but only see the page that I allow.
Please help me to come up with a solution in this regard.
Thanks all.

A: Create one table in your database like below

Insert the entry in this table when you send the link to particular user. As an example, Here I inserted two entries for UserId 10 and 12

Make one procedure or function to validate the token against request.
CREATE PROCEDURE sp_ValidateUserIdAndTokenId
    @UserId INT,
    @TokenId varchar(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    IF ISNULL(@UserId,0) <> 0 AND ISNULL(@TokenId,'') <> ''
    BEGIN

        IF EXISTS(SELECT 1 FROM UserToken WHERE UserID = @UserId AND TokenID = @TokenId)
        BEGIN

            Declare @TokenInsertedDateTime AS DateTime
            Declare @IsTokenExpired AS Bit

            SET @TokenInsertedDateTime = (SELECT TokenInserted FROM UserToken WHERE UserID = @UserId AND TokenID = @TokenId)
            -- Here Calculate the token time difference in minutes for one day i.e. 1440 minutes.
            SET @IsTokenExpired = (SELECT CASE WHEN DATEDIFF(MINUTE, @TokenInsertedDateTime, GETDATE()+1) > 1440 THEN 0 ELSE 1 END)

            SELECT @IsTokenExpired

        END
    END
END

Now, When request comes in controller's action at that time you have to make a call the database to identify the Token and User in newly created table and determine the request is valid or not(You can also calculate the interval of time for particular token).
[HttpGet]
[AllowAnonymous]
public ActionResult Add(int userId, string tokenId)
{
   // Determine the request with tokenId and validate your tokenId
   // make the database call of created procedure or function and validate your userid and token here.
   return View();
}


text:
Q: Should we do something about enormous numbers of edits in short times? First of all, dear Antonio Carlos Ribeiro, please don't take it as a personal...
Today, I just looked up the editor parts on Stackoverflow and I saw this user made 543 edits in 24 hours. When I look at his revision history, his edits only include (I look at all revisions on last 27 pages) this:

*

*add laravel tag which questions have already laravel-4 tag.

Looks like all the edits he made are like this. Since his reputation is over 3k, the system does allow this kind of minor editing without any approval. (As we all know, under 2k reputation users need 3 approval for editing).
Does our system need to prevent this number of minor edits?
Or it is okay for everybody since the user has over 3k reputation?


text:
Q: Approximating compactly supported $L^2$ functions with Schwartz functions "from within"? It is well known that the class of Schwartz functions $\mathcal{S}$ in dense in all $L^p$ spaces therefore for each $f \in L^2$ there exists a sequence of Schwartz functions $(f_k)$ such that $\lVert f - f_k \rVert_{L^2} \to 0$ as $k \to \infty$.
If we suppose further that $f$ has compact support can we find a sequence of Schwartz functions $(f_k)$ such that $\lVert f - f_k \rVert_{L^2} \to 0$ as $k \to \infty$ (as above) and additionally $\operatorname{supp}(f_k) \subseteq \operatorname{supp}(f)$ for all $k$?

A: No, this is not possible, even if you define $\text{supp}(f)$ only as an equivalence class (up to a null set). For a counterexample take the characteristic function $f$ of a closed set $E$ of positive measure but without interior points (like that fat Cantor set which Mateusz mentioned).
Indeed, if $f_n$ is a continuous function with $\text{supp}(f_n)\subseteq\text{supp}(f)\cup N=E\cup N$ for some null set $N$, then $f_n=0$, because otherwise $E\cup N$ would have to contain some interval $(a,b)$ which must contain a point from the complement of $E$ and which after shrinking (since $E$ is closed) can thus be assumed to lie completely in the complement of $E$, hence $N\supseteq(a,b)$, a contradiction.


text:
Q: How to make Banshee to play AAC audio streams? I have played MP3 radio with Banshee but I had to use VLC to play AAC streams.
How to make it work with Banshee?

A: I had to install the "GStreamer plugin for aac" in the "Ubuntu Software Center"

A: change the file from aac to m4a, so that music player will treat it as a different type, it works for me in Ubuntu 13.10 with clementine.


text:
Q: Azure WebService can't find one of my assemblies but it's there based on Azure Console I am very new to Azure and WebServices so please bear with me here. Basically, I have a WebService that references 3 different dlls SOCreate.dll, EOTCBase.dll, EOTC_InBuffer.dll, not standard .NET dlls but rather dlls from other projects I have. After I published a WebService on Azure successfully, I am calling my WebService which calls a method in EOTCBase.dll. The method in EOTCBase.dll tries to load an EOTC_InBuffer.dll assembly like so:
Assembly dbAssembly = Assembly.LoadFile(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\EOTC_InBuffer.dll");
but that call fails with an error The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
When I check what files I have on Azure I can see my WebService and a bin folder:

then I go inside the bin folder and can see all 3 dlls in there:

I guess that means that all 3 dlls are published on Azure and are available in bin folder. I tried to google for something similar but wasn't able to find a similar scenario. Could somebody please maybe point what's wrong here or maybe reference a link to some reading materials? Thank you.
P.S. It almost looks like that all those 3 dlls in the same bin folder based on Azure Console output but in fact some of them not in there actually.

A: UPDATE
I mean open kudu on the portal, and manually add the mydll folder as in my screenshot. The specific path of the .dll file is D:\home\site\wwwroot\mydll\a.dll. In this way, if the operation is successful, you don't need to worry about the temporary folder. Copy all the .dll files that will be used to the mydll folder.

PRIVIOUS
You can use dynamic load function to use your .dll file. If this is successful locally, and unsuccessful after deployment, then the problem should be the Azure cloud environment.
    #region Dynamically load .dll
    object obj=null;
    byte[] filesByte;
    Assembly assembly;
    Type type;
    MethodInfo timerInitial;
    MethodInfo timerDispose;
    #endregion

    private void LoadDll()
    {
        try
        {
            filesByte = File.ReadAllBytes(Path.GetDirectoryName(Application.ExecutablePath) + "//EOTC_InBuffer.dll");
            assembly = Assembly.Load(filesByte);
            type = assembly.GetType("EOTC_InBuffer.dll");
            obj = System.Activator.CreateInstance(type);
            timerStart = tp.GetMethod("TimerStart");
            timerStop = tp.GetMethod("TimerStop");
            if (timerStart != null)
            {
                timerStart.Invoke(obj, null);
            }
        }
        catch(Exception)
        {

        }
    }

You are successful in running locally, but deploying to Azure will fail. This problem cannot be dealt with, because we cannot register the .dll in the Azure environment, nor can we read and load these .dll files in the bin folder through code.
I have replied to this question in another post before, and also tried to use the code to deal with this problem but all failed, I hope it will help you.


text:
Q: Why does console in R Studio only allow partial commands? I am trying to advance my R knowledge, but RStudio gets very frustrating: I paste in my work / or re-enact a how-to, but console complains too much; also Ctrl-Enter only works in the text-editor.
After hours of debugging, I had to put a command in piece by piece, and then a random internet search said I should not code in console. I am not coding, I am taking a class and pasting examples; but coding is possible in Console. Now, I have to rethink my whole strategy and take notes in R. Kind of makes me think of applescript or javascript programming where you see the code and only debug in console; but should have been labeled that way...I have been tinkering off and on for a year now. I wish I had a keyboard shortcut/format to paste in console just to test a code: Like \ or +, etc.
Note: I had to define a few variables and enable
    Library(dslabs)
    Library(dplyr) gives group_by, %>%
    Library(purrr) gives map_dbl

accuracy <- map_dbl(cutoff, function(x){
  y_hat <- ifelse(train_set$height > x, "Male", "Female") %>%
    factor(levels = levels(test_set$identifier))
mean(y_hat == train_set$identifier)})

Console says: "Error: unexpected symbol in "accuracy <- map_dbl(cutoff, function(x){ y_hat <- ifelse(train_set$height > x, "Male", "Female") %>% factor(levels = levels(test_set$identifier)) mean"
Turns out > "console" has to run the first part before a logical space/break or {; then give "+" and take the final arguments and } or )
The editor just works right.
Partial answer at https://www.dummies.com:
"To prepare your script to be sourced, you first write the entire script in an editor window. In RStudio, for example, the editor window is in the top-left corner of the screen. Whenever you press Enter in the editor window, the cursor moves to the next line, as in any text editor" (de Vries, and Meys, J. (n.d.) Programming: R: How to Source a Script in R. Dummies: A Wiley Brand. https://www.dummies.com/programming/r/how-to-source-a-script-in-r ).
Why doesn't console tell you to try the editor window, allow customization, or just work without breaking it into steps, such as a nifty library() for console?

A: RStudio is very deliberate. It wants you to write chunks of source code in the top-left window called "Editor." Besides tidyverse or dplyr providing redirect abilities, errors happen because %>% is used to direct output between more than one line of code; and multiple lines cannot be done from console easily.
Yes, console accepts code, but it won't recognize more than a single function. Meaning if it sees ) } or %>% that is the end of the function. And you need a new line. Enter the code up to the %>% and hit enter.
Example:
height %>% #enter

Console will add the + itself.
Keep coding.
After the last ) such as in factor(); console will return to a new line, and "mean," will run by itself.
Remember: %>% points to the next line of code. So RStudio's console needs you to paste in the code piece-by-piece and physically press "enter" or "return" after each %>%
Instructors might not give the code to you in context, which can be frustrating, because a section of code will depend on functions defined earlier to work. Look for instructor notes about different versions of R; or the instructors samples and handouts to get the full context; if not ask the instructor; my instructors code was correct, just not without the tidbits before which were not provided. Once I got those the results were the same and/or more accurate.
In summary:
To make coding easier, build examples in the Editor, like this:
Start a new RMarkdown document using File > New File > R Markdown... and name it.
This opens a new document with author info and simple howto examples as runnable chunks of code
Start taking notes, then start a new line, and type three ``` (called back-tick on the ~ key).
Let editor offset it by typing ```{r, include=TRUE}
```{r, include=TRUE}
cutoff <- seq(61, 70)
accuracy <- map_dbl(cutoff, function(x){
y_hat <- ifelse(train_set$height > x, "Male", "Female") %>%
 factor(levels = levels(test_set$identifier))
mean(y_hat == train_set$identifier)})
```

Now you have a workable chunk of source code. You can Run it in console by clicking the green play button "Run Current Chunk," include=TRUE tells it to draw the tables beneath the code so you can see them yourself.


text:
Q: Xamarin Offline Location How we get Offline location through GPS? How we get Offline location through GPS?
I try but Xam.Plugin.GeoLocator fails in offline mode.

A: At least on iPhone the Flight Mode disables most of the GPS functions. So for Offline Mode as in Flight Mode that is actually the correct behavior. However, if you turn off WiFi Cellular and Bluetooth individually or just have no network available, GPS should be available.
If this does not answer your question, you may want to disclose a bit more info on your usecase, a specific error or even the code sample that seems to fail where it should not.

A: Xaml:
 <Button Text="location"
            TextColor="Black"
            Clicked="Button"/>

    <Label Text="longi"
           TextColor="Gray"
           FontSize="Small"/>
    <Label x:Name="longit"
           FontSize="10"
           TextColor="Orange"/>

    <Label Text="Latitu"
           TextColor="Gray"
           FontSize="Small"/>

    <Label x:Name="latit"
           FontSize="10"
           TextColor="Orange"/>

Code:
 private async void Button(object sender, EventArgs e)
        {
            try
            {
                var locator = CrossGeolocator.Current;
                locator.DesiredAccuracy = 50;
                var post = await locator.GetPositionAsync(TimeSpan.FromSeconds(10));

                longit.Text = post.Longitude.ToString();
                latit.Text = post.Latitude.ToString();
            }
            catch (Exception ex)
            {

                throw ex;
            }

Permissions:
 public override void OnRequestPermissionsResult(int requestCode,
     string[] permissions, Android.Content.PM.Permission[] grantResults)
        {
            Plugin.Permissions.PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode,
                permissions, grantResults);
            base.OnRequestPermissionsResult(requestCode, permissions,
                grantResults);
        }


text:
Q: Controller stops updating value after the value is changed I'm trying to use angular to change the css class of an element when a user inputs data, both after a button click and in real time as the user is typing in data.
HTML:
<input type="text" class="defaultClass" ng-class="{true: 'errorClass',
false:'defaultClass'}[updateInput()]" ng-model="inputOne">

CSS:
.defaultClass {border: 1px solid #ccc;}

.errorClass {border: 1px solid #FF0000;}

After a button is pressed, the controller checks if the model of the element is blank and if so, makes the function return true and therefore changes the css class in the ng-class to show an error.
$scope.calcButton = function (){

if ($scope.inputOne === "" || $scope.inputOne === undefined) {
    $scope.updateInput = function() {
        return true;
    };
} else {
    $scope.updateInput = function() {
        return false;
    };
}

};

Outside of the button click function, I have the following code in the same controller that should be watching the status of $scope.inputOne and returning true or false based upon the status of the input:
$scope.updateInput = function() {
    if ($scope.inputOne === "") {
        return true;
    } else {
        return false;
    }
 };

And it works fine as long as I don't click the button, but once the value is changed by the button press the controller stops checking if the input field is empty or filled.
This is a problem because I want to have the error messages fade away as the user types in data after a button press that threw errors, but I can't change the css by user input at this point.
Why does it do this? How can I ensure that the controller still keeps track of what's going on in the input field after the button click?

A: Try like this
ng-class="{'errorClass' : !inputOne,'defaultClass': inputOne }"

or like this
ng-class="!inputOne ? 'errorClass' : 'defaultClass'"

'',null,NaN,undefined,0 etc considered false in JavaScript.
just check model has value or not.
It'll work through two way binding . don't need method for this to check


text:
Q: Creating an Ethnicity Variable with Multiple Column Names as Variables I have a survey dataset that includes self-reported ethnicity. Participants were allowed to select as many ethnicities as they wanted to. The data structure looks like this:
Hispanic English Indian

1        NA      NA

NA       1       NA

NA       NA      1

NA       1       1

1        1       1

What I want to do is create a new categorical ethnicity variable where the column names take the place of the 1s above. In addition, if someone selected more than one ethnicity, then the categorical ethnicity variable should include both, like this:
Hispanic English Indian Ethnicity

1        NA      NA     Hispanic

NA       1       NA     English

NA       NA      1      Indian

NA       1       1      English_Indian

1        1       1      Hispanic_English_Indian

A: We can use apply to loop over the rows (MARGIN = 1), then paste the names of the row values that are not an NA
df1$Ethnicity <- apply(df1, 1, function(x)
     paste(names(x)[!is.na(x)], collapse= "_"))

-output
 df1
  Hispanic English Indian               Ethnicity
1        1      NA     NA                Hispanic
2       NA       1     NA                 English
3       NA      NA      1                  Indian
4       NA       1      1          English_Indian
5        1       1      1 Hispanic_English_Indian

data
df1 <- structure(list(Hispanic = c(1L, NA, NA, NA, 1L),
English = c(NA,
1L, NA, 1L, 1L), Indian = c(NA, NA, 1L, 1L, 1L)),
 class = "data.frame", row.names = c(NA,
-5L))


text:
Q: ¿Cómo hago que un input acepte solamente un formato (+595)? tengo un form en html, en la cual como uno de los campos es un teléfono, pero solo quiero aceptar el formato +595981123456,
intente hacerlo con el atributo "pattern", pero sigue sin validar,

Teléfono Particular

    <input type="text" class="form-control" name="tel_tt" id="tel_tt" data-toggle="tooltip" data-placement="top" title="Ingrese el número en formato internacional (+595)" placeholder="+595981123456" required="" pattern="[09]|[+595]" >

Alguna sugerencia para solucionarlo,
Desde ya, gracias

A: Ha Upei? Tenes dos opciones:
La primera y la mas simple seria con el pattern html de la siguiente forma
pattern="[+]{1}[595]{3}[0-9]{9}"
La otra opción seria con Javascript, podes descomentar el código en Javascript para poder probarlo. Utilizando slice y eventListener es una forma de solucionar tu problema.
Espero que el código de ejemplo te sirva de guia. Saludos!

let btn = document.getElementById('enviar')

function validarTelefono() {
  let telefonoEl = document.getElementById('tel_tt').value
  let formatoInt = telefonoEl.slice(0,4)
  if (formatoInt === '+595'){
    return true
  }
  return false
}

function checkTelefono(){
  if (validarTelefono()) {
    alert('Telefono ok!')
  } else {
    alert('Problema con formato internacional')
    let telefonoEl = document.getElementById('tel_tt')
    telefonoEl.focus()
  }
}

//btn.addEventListener('click', checkTelefono)
<form>

Teléfono Particular

    <input type="text" class="form-control" name="tel_tt" id="tel_tt" data-toggle="tooltip" data-placement="top" title="Ingrese el número en formato internacional (+595)981123456" placeholder="+595981123456" pattern="[+]{1}[595]{3}[0-9]{9}" required>

<button id="enviar">Enviar</button>
</form>

A: Puedes usar un plugin de jQuery como https://css-tricks.com/input-masking/
Prueba por ejemplo:

Teléfono Particular

        <input type="text" class="form-control" name="tel_tt" id="tel_tt" data-toggle="tooltip" data-placement="top" title="Ingrese el número en formato internacional (+595)" placeholder="+595981123456" required="" pattern="[09]|[+595]" >


text:
Q: Magento preventing two product types in same cart I have a custom attrib... call it.. IsRestricted that each product has assigned to it.  It has a 1 or 0.  I want to check the existing cart to see if it has a restricted item.  If it does and I am attempting to add a non-restricted item to it, I need to post a message saying only restricted OR non-restricted items can be in the cart at the same time.
So if the items in the cart all have a 0 then you can only add new items with a 0 if the items in the cart have a 1 then you can only add items with a 1.
I am on the community version..Magento ver. 1.9.2.1
Does anyone know how I can do this?
Thanks in advance..
-Ken

A: You can extend public function addAction() in ./app/code/core/Mage/Checkout/controllers/CartController.php and iterate through all items in cart:
$_items = $cart->getQuote()->getAllItems();

foreach ($_items as $_item) {
    // ...
    // $_item->getProduct()->getData('IsRestricted');
    // ...
}


text:
Q: what is the difference between framework and bundle in iphone OS? what is the difference between framework and bundle in iphone OS?

A: Frameworks are groups of libraries, headers, et. al. which together make up a unit that you can use when programming. Kind of like a DLL on other platforms, except more than that.
A bundle is a structured folder which contains code and other support files. Frameworks are bundles. So are applications.
These are the same as on Mac OS X, since the iPhone OS is Mac OS X (though a special version of it).
See:  Bundle Structures
And: Frameworks


text:
Q: How to fix 'Ajax form submission' with PHP The code shown below employs the Ajax but there is an indefinite loading bar as if the function never gets called from the controller. How would I go about getting the HTML to successfully initiate this function?
//HTML
<button type="button" data-url="/ajax/controller.php" name="dosubmit" class="wojo button positive">Approve</button>
<input name="ProcessApproval" type="hidden" value="1">

//Function
public function ProcessPOApproval()
      {
        $PID = $_GET['pid'];

        $ApprovalTransactionalData = array(
            'PONum' => "$PID",
            'Step' => "4"
        );
        self::$db->insert("accounting_transact", $ApprovalTransactionalData);
}

//Controller
<?php
 /* == Proccess Project File == */
 if (isset($_POST['ProcessApproval'])):
    if (intval($_POST['ProcessApproval']) == 0 || empty($_POST['ProcessApproval'])):
        die();
    endif;
    ProcessPOApproval();
endif;
?>

     //Ajax
       /* == Master Form == */
       $('body').on('click', 'button[name=dosubmit]', function() {
           posturl = $(this).data('url')

           function showResponse(json) {
               if (json.status == "success") {
                   $(".wojo.form").removeClass("loading").slideUp();
                   $("#msgholder").html(json.message);
               } else {
                   $(".wojo.form").removeClass("loading");
                   $("#msgholder").html(json.message);
               }
           }

           function showLoader() {
               $(".wojo.form").addClass("loading");
           }
           var options = {
               target: "#msgholder",
               beforeSubmit: showLoader,
               success: showResponse,
               type: "post",
               url: SITEURL + posturl,
               dataType: 'json'
           };

           $('#wojo_form').ajaxForm(options).submit();
       });

Below is the HTML with the wojo_form id as requested.
    <form id="wojo_form" name="wojo_form" method="post">

        Submitting Accountant

          <input type="text" value="" disabled="disabled" name="created">

        Next Approval

          <input type="text" value="<?php echo $row->lastlogin;?>" disabled="disabled" name="lastlogin">

        Approval Group

          <input type="text" value="<?php echo $row->lastip;?>" disabled="disabled" name="lastip">

    <button type="button" data-url="/ajax/controller.php" action="" name="dosubmit" class="wojo button">Decline Approval</button>
    <input name="ProcessDecline" type="hidden" value="1">
    <button type="button" data-url="ajax/controller.php" name="dosubmit" class="wojo button positive">Approve</button>
    <input name="ProcessApproval" type="hidden" value="1">
    <button type="button" data-url="/ajax/controller.php" name="dosubmit" class="wojo button info">Add Notes</button>
    <input name="ProcessNotes" type="hidden" value="1">
  </form>

If you need anything additional please let me know.


text:
Q: Pronunciation of the prefix "tri" I know that English pronunciation is rather arbitrary. There are still some "rules" that even with many exceptions are useful for non-natives like me.
I'm puzzled about the pronunciation of the very common prefix "tri", meaning "three".
"Tri" is often pronounced /traɪ/. For example: triangle, trilateral, tripartite, trioxide, triode, triad, trilobites, triglyceride, triennium, tridimensional, trigeminal, tricycle, tricuspid, triceps, triathlon.
But sometimes "tri" is pronounced /trɪ/. For example: trigamous, triplicate, trio, trinity, trilogy, trillion, trigonometry, triplet, triple, triphthong, triploid, triptych.
Finally, it seems that a few words can be pronounced both ways. For example: trimester, tricolor.
I can find no pattern at all. Is there any "rule"? Or can you help me in any way to guess the right pronunciation of a new word with the prefix "tri"?

A: Unfortunately not. As your example words show, you can't apply historical criteria (e.g. 'is it a Greek root') or any obvious phonological decision process ('is it stressed,' 'is there a vowel after it').
The only rule I can think of of is: in chemistry, the pronunciation "tri-" = /traɪ/ is fixed.
I can offer an extension of this rule, which I believe always holds:

*

*In a word "triXYZ", if XYZ is itself a word in English, then you pronounce "tri" as /traɪ/.

As an AE speaker, I can't think of a counterexample, anyway.

A: As you say, tri is most commonly pronounced as /traɪ/. But there are some situations where you can predict that you have to use /trɪ/ based on the spelling or the phonological structure of the word.
There are some consonant clusters that can't start a syllable in English: before these, you have to use /trɪ/. This explains /ˈtrɪf.θɑŋ/ and /ˈtrɪp.tɪk/.
Even though doubled consonants are not actually pronounced any differently from single consonants in spoken English, they generally indicate that the preceding vowel is short. This explains /trɪl.jən/.


text: Q: Omnet++ 5.0: Simulation terminated with exit code: -1073741511" I have just installed Omnet++ 5.0 (on Windows 7) and installed inet with it as well. As soon as I try to run any of the examples, it throws and error "Simulation terminated with exit code: -1073741511". I am not finding any help regarding this error anywhere. Please help.


text:
Q: Login is only supported from http:// or https:// URLs. Please host your page in a web I downloaded a simple html 5 application from the windows mobile services.
I want to use this in a windows phone 8 html5 application and I want to authenticate against google/facebook etc.
I tried to follow the steps with the post here "Azure mobile login problem in PhoneGap app". Inserted the latest Cordova (3.0.0) js file. Perhaps there are more steps I should follow?? there are lots of files to chose from from this download.
When I try to launch this application through the "Emulator WVGA 512MB", I get the following error. "Login is only supported from http:// or https:// URLs. Please host your page in a web"
Can I implement and test the login through the emulator like this? If so what steps do I need to take? I am using Visual studio 2012
I just want to get a simple authentication example to google going in "Windows phone 8 html5" that I can test on my local machine.


text:
Q: How to use "{" symbol in xaml string How can I use { symbol in xaml string? E.g.:
<TextBlock Text="{0}"/>

I can do it starting string with a space symbol:
<TextBlock Text=" {0}"/>

but I'm looking for a better solution.

A: Like this:
<TextBlock Text="{}{0}"/>

The {} at the start tells the parser to not look for markup extensions.
Alternatively, you can specify the data without using an attribute:
<TextBlock>{0}</TextBlock>


text:
Q: How to propagate event from element with higher z-index to elements under excluding click event? I have a component which has markers in it. Marker is a styled div with icon. Markers have click, mouseenter and mouseleave events. When mouse enters tooltip appears. On top of markers I can place other element to cover them. That element has higher z-index. I still want to be able to hover over (mouseenter, mouseleave) over lower z-index elements (markers) while preventing click event on them when they are covered. Is there any solution to pass only few or exclude only some event from propagation on higher z-index element?

A:

<!DOCTYPE html>

HIGH

LOW


text:
Q: Using ReadLine on an inputfile, how do I remove blank lines without it reading it as end of stream? Here's the issue; I'm trying to readline's from a .txt, however there are blank lines inbetween each number, so it's throwing me an error and filling the rest of my array with the default 0's. should I be using trim before parsing?
(this was on a c# final, and my instructor may or may not go over the final answer so I am asking here out of curiosity, my solution was to edit the .txt file so there were no empty lines. lol.)
    private void getScoreButton_Click(object sender, EventArgs e)
    {
        double sum = 0.00;
        double avg = 0.00;
        int numBelowAvg = 0;
        int numAboveAvg = 0;
        const int SIZE = 20;
        StreamReader inputFilesData;
        int i = 0;

        int[] scores = new int[SIZE];

        try
        {
            inputFilesData = File.OpenText("scores.txt");

            while (i < scores.Length && !inputFilesData.EndOfStream)
            {
                scores[i] = int.Parse(inputFilesData.ReadLine());
                i++;
            }
            inputFilesData.Close();

        }
        catch (Exception excep)
        {
            MessageBox.Show(excep.Message);
        }

        for(int j= 0; j <scores.Length; j++)
        {
            scoreListBox.Items.Add(scores[j]);
            sum += scores[j];
        }

        avg = sum / scores.Length;

        for (int j = 0; j < scores.Length; j++)
        {
            if(scores[j]>avg)
            {
                numAboveAvg++;
            }
            else
            {
                numBelowAvg++;
            }
        }

        avgLabel.Text = avg.ToString("N2");
        aboveAvgLabel.Text = numAboveAvg.ToString();
        belowAvgLabel.Text = numBelowAvg.ToString();

    }
}

}

A: You could exclude blank lines using something like:
while (i < scores.Length && !inputFilesData.EndOfStream)
{
    String line = inputFilesData.ReadLine().Trim();
    if (line.Length > 0)
    {
        scores[i] = int.Parse(line);
        i++;
    }
}


text:
Q: Dynamic UITableViewCell not resizing according to the content
Senario A:
If I set the label content in cellForRowAtIndexPath, the cell correctly get resized.
Senario B:
If I change the text content in custom action in cell, the cell sized does not get changed.(I do call setNeedsLayout + layoutIfNeeded)
How to fix this?
EDIT:
1) I have set,
myTableView.estimatedRowHeight = 71.0
myTableView.rowHeight = UITableViewAutomaticDimension
2) I have correctly added auto layout constraints.

A: I was running into this issue, and my problem was that I was constraining the content to self (the UITableViewCell) and not to self.contentView (the contentView OF the cell). Hope this helps someone else who has built their cells all in code!

A: In my case, the cell's custom size was enabled:

A: After you change the text of the cell, just reload that particular cell or simply call mainTableView.reloadData().
To reload that cell-
//indexPath is indexPath of cell you just changed label of
mainTableView.reloadRows(at: indexPath, with: .automatic)

A: In my case, in the same cell I had an imageView in the top left corner with a "center vertically in container" constraint, and a "top space container" constraint.
Obviously to satisfy this two constraint the cell must have an height equal to:
(height of the imageView / 2) + (length of the top space container constraint).
This height is not enough to fit the label text, so my label had only 1 line visible.
After I have deleted the imageView top constraint all went to the right place, in my case i wanted the image to be centered, if the image had to stay in the top left corner I had to take off the "center vertically in container" constraint.
I hope this can help someone.

A: First of all, I don't specifically know what was your action on UITableViewCell. So, I assume I do that in UITableViewCell selection.

The below answer only work on iOS 9 and above

But, for some reason, it failed to do it in iOS 8 until it scroll. So, I will update the answer for iOS 8.
I have seen you have used UITableView's estimatedRowHeight and rowHeight at your project. So,

Please check the following

*

*Make sure UITableView's estimatedRowHeight and rowHeight include inside viewDidLoad()

*Make sure your UILabel lines set to 0

*Make sure there is no constraints about height for your UILabel and let the constraints be like that :

If there are other component also included, make sure only bottom and top space constraints included or top space to container margin and bottom space to container margin.

*Every time that you want to update the cell, you have to reload tableView no matter what your current situation will be.
So, don't say anything yet before you try this sample project, @Rikh answer still work. May be you are going in wrong direction. Here's the solution. Please do as I said steps by steps and let me know if that didn't work out. You might need to share your sample project which is causing.

Sample Demo - DynamicCellDemo

UPDATE for iOS 8 : update the following code for iOS 8 users

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    if #available(iOS 9, *) {
        // do nothing
    } else {
        tblDynamic.reloadData()
    }
}

A: what you can do is set the AutoLayout constraints for the label in present in the cell from all the sides that is from Top, Bottom, Leading and Trailing. Then add the following UITableViewDelegate method to your class.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return 500
}

This will do the job. As now content in table view cell automatically adjusts the height of the cell.

A: Try this if it works:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

     return UITableViewAutomaticDimension

}

 func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {

    return UITableViewAutomaticDimension

}

A: Add the following in your viewDidLoad()
-(void)viewDidLoad{
   [super viewDidLoad];
   tableView.rowHeight = UITableViewAutomaticDimension
   tableView.estimatedRowHeight = 140
}


text:
Q: Leiningen and Clojure dependencies I'm fairly new to clojure but I've been having trouble finding good resources and examples online, so hopefully someone could point me in the right direction. I've started a project with lein, project.clj looks like this:
(defproject scratch "1.0"
  :description ""
  :main scratch.core
  :dependencies [
    [org.clojure/clojure "1.3.0"]
    [org.clojars.jyaan/slick "247.1"]
  ])

and src/scratch/core.clj looks like this:
(ns scratch.core
    (:import org.newdawn.slick))

(defn -main [] (println "hello world"))

As far as I can tell this is right, but when I try to run lein run I get a ClassNotFoundException.
I did a jar tf on the lib/slick-247.1.jar file and confirmed it has a directory structure which would indicate that it has that namespace (org/newdawn/slick/etc...). I'm sure it's a simple mistake but I can't see what it is, does anyone have any ideas?

A: I think the issue is that you are trying to import the whole package, like a "import org.newdawn.slick.*" in Java. In Clojure you cannot do this, but you have to import each class that you want to use.
The shortest that you can get is:
(:import (java.io BufferedReader Bits BufferedWriter))


text:
Q: Limit font face to certain language Is there a magical way that could make font to support certain language and other languages to follow sequence font-family: fonts;

A: Like this?

body {
  font-family: Arial;
}

*[lang=jp] {
  font-family: Meiryo;
}

Hello!

こんにちわ!


text:
Q: traversing singly linked list in Java I have a simple Java question. As shown in the below code:
public static ListNode removeNthFromEnd(ListNode head, int n) {

        ListNode start = new ListNode(0);
        ListNode slow = start, fast = start;
        slow.next = head;

        //Move fast in front so that the gap between slow and fast becomes n
        for(int i=1; i<=n+1; i++)   {
            fast = fast.next;
        }
        //Move fast to the end, maintaining the gap
        while(fast != null) {
            slow = slow.next;
            fast = fast.next;
        }
        //Skip the desired node
        slow.next = slow.next.next;
        return start.next;
    }

Start, fast and slow address the same object. I don't get why  "slow = slow.next;" will not change the start object, but "slow.next = slow.next.next;" will change the start object.

A: slow is a local variable, so changing its value to refer to a new instance of ListNode doesn't affect the original list.
However, if slow refers to a ListNode that belongs to your list, changing slow.next to refer to a new instance changes the state of your list.
It may be clearer if you use a setter to modify the next node :
slow.next = slow.next.next;

would be equivalent to :
slow.setNext(slow.next.next);

So if slow refers to a ListNode that belongs to your list, changing its state is changing the state of your list.


text:
Q: Unhandled exception 0xE0434352 does not get wrapped into a .NET Exception Here's my scenario:

*

*.NET 6.0.11

*Native application, running as a Windows service, calls a .NET 6 assembly via a .NET generated .comhost.dll using COM

*The .NET assembly blocks on System.Net.Sockets.Socket.Receive call

When shutting down the OS, the Receive call gets an unhandled exception:
Unhandled exception at 0x77438642 (KERNELBASE.dll) in myapp.exe.3180.dmp: 0xE0434352 (parameters: 0x80004005, 0x00000000, 0x00000000, 0x00000000, 0x71370000).
The try/catch block cannot handle the exception, i.e. it seems the exception isn't wrapped into a .NET Exception and the catch block below isn't hit:
try
{
    return s.Receive(buffer); // <- the unhandled exception seen in a crash dump
}
catch (Exception ex)
{
    Trace($"Receive error - ex: {ex}");
    throw;
}

This unhandled exception does not result in a HRESULT being returned to the native code and the process crashes. A registered AppDomain.CurrentDomain.UnhandledException does not get triggered.
When the OS runs normally, the internal Receive exceptions are properly wrapped into an Exception, the catch block is hit and a HRESULT is returned to the native code.
I'm colleting the crash dump with WER. This crash gets also logged as Informational in the Application Windows Logs:
Fault bucket 1695090666501866404, type 1
Event Name: APPCRASH
Response: Not available
Cab Id: 0

Problem signature:
P1: myapp.exe
P2: 1.0.0.0
P3: 63984a64
P4: KERNELBASE.dll
P5: 10.0.20348.1249
P6: ac7a852c
P7: e0434352
P8: 00138642
P9:
P10:

The native stack for the exception is:
    KERNELBASE.dll!_RaiseException@16() Unknown
    coreclr.dll!RaiseTheExceptionInternalOnly(Object * throwable, int rethrow=0x00000000, int) Line 2807    C++
    coreclr.dll!IL_Throw(Object * obj=0x021463a0) Line 4119 C++
    System.Net.Sockets.dll!6fb66362()   Unknown
    [Frames below may be incorrect and/or missing, native debugger attempting to walk managed call stack]
    073689cd()  Unknown
    07368801()  Unknown
    0736843d()  Unknown
    073682c8()  Unknown
    coreclr.dll!@COMToCLRDispatchHelper@32()    Unknown
    coreclr.dll!InvokeStub(ComCallMethodDesc * pCMD, unsigned long pManagedTarget=0x021463a0, Object * orThis=0x0213efac, ComMethodFrame * pFrame=0x0191eea8, Thread * pThread=0x00b96d40, unsigned __int64 * pRetValOut=0x0191ee88) Line 197   C++
    [Inline Frame] coreclr.dll!COMToCLRInvokeTarget(unsigned long) Line 342 C++
    [Inline Frame] coreclr.dll!COMToCLRWorkerBody(Thread *) Line 457    C++
    coreclr.dll!COMToCLRWorker(Thread * pThread=0x00b96d40, ComMethodFrame * pFrame=0x0191eea8) Line 560    C++
    01d0d359()  Unknown
    .. the rest of the stack in myapp.exe ...

And the managed stack is:
    KERNELBASE.dll!_RaiseException@16() Unknown
    [Managed to Native Transition]
    System.Net.Sockets.dll!System.Net.Sockets.Socket.Receive(System.Span<byte> buffer) Line 1495    C#
    .. the rest of the stack in myapp.exe ..

Do you have any suggestions on how to proceed with debugging this?
Thank you.


text:
Q: Spacing only works in xeCJK for Chinese and Japanses but not Korean \documentclass{article}
\usepackage{xeCJK}
\setCJKmainfont{Batang}

\CJKspace
\begin{document}

一二三四五

一 二 三 四 五

あいうえお

あ い う え お

일이삼사오

일 이 삼 사 오

\end{document}

I'm trying to write something with some Chinese, Japanese, and Korean in it. As you may know, among the three, Korean is the one that requires spacing between the words, but not the other two. I have the code written as above, and for Chinese and Japanese, the result is as expected, with spaces, but for Korean, the spaces in the last line are ignored.
I've read the other post about putting spaces between Korean words, but it doesn't seem to work for me. So I have no idea what I'm doing wrong.

A: I'm sorry that it is a bug of xeCJK since version 2012/12/07 v3.1.1. We'll fix it soon.
Before we fix it, you could check out the SVN version or temporaly use this quick fix:
\ExplSyntaxOn
\int_step_inline:nnnn { "AC00 } {1} { "D7A3 } { \char_set_catcode_letter:n {#1} }
\ExplSyntaxOff

Update:
In fact it is a bug of XeTeX. I've just reported it. Anyway, we'll still have a patch in xeCJK package.


text:
Q: Bootstrap CSS Navigation overlapping Having a problem with bootstrap Nav bar when displayed on phone. The compressed element kicks in and the two different Nav bars overlap:
Two rows of navigation and both have collapsing menus.
See screen shot from both iPad and iPhone.
Edit:
After example provided:

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Computer Medic

Login

Admin

Database Code

Projects

Bookmarks

Notes

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        Toggle navigation

        </button>

        <a class="navbar-brand" href="<?php echo $home_url; ?>admin/index.php">CM Site Admin

            <li <?php echo $page_title=="Admin Index" ? "class='active'" : ""; ?>>
                <a href="<?php echo $home_url; ?>admin/index.php">Home

            <li <?php
                    echo $page_title=="Users"
                        || $page_title=="Create User"
                        || $page_title=="Update User"
                        || $page_title=="User Search Results"
                        || $page_title=="Change Password"
                        || strip_tags($page_title)=="Users / Edit User"
                        || strip_tags($page_title)=="Users / Create User"
                        ? "class='active'" : ""; ?> >
                <a href="<?php echo $home_url; ?>admin/read_users.php">Users

                      <?php echo $_SESSION['firstname']; ?>

                        <a href="<?php echo $home_url . "admin/update_user.php?id=" . $_SESSION['user_id']; ?>">Edit Profile

                        <a href="<?php echo $home_url . "admin/change_password.php?id=" . $_SESSION['user_id']; ?>">Change Password

<a href="<?php echo $home_url; ?>logout.php">Logout

A: I believe this is what you're trying to do.
You can enclose two individual navbars inside a single .navbar-fixed-top so they maintain individual classes as far as the styling differences while remaining in a fixed position with no overlap: navbar-default and navbar-inverse. Then just make sure each has there own unique data-target for the individual toggles to function.
For example:
data-target="#navbar1" with id="navbar1"
data-target="#navbar2" with id="navbar2"

Also you should use the navbar-right class instead of pull-right. See Navbar Alignment for more info.
Working Example:

body {
  padding-top: 110px;
}
div.navbar {
  margin-bottom: 0;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar1">
          Toggle navigation

        </button>
        Computer Medic

Login

Admin

Database Code

Projects

Bookmarks

Notes

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar2">
          Toggle navigation

        </button>

        CM Site Admin

            Home

            Users

                Edit Profile

                Change Password

Logout

    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
    survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
    software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a
    galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets
    containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's
    standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
    It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the
    printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,
    but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker
    including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled
    it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
    and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since
    the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in
    the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting
    industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic
    typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem
    Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
    publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer
    took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset
    sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's
    standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
    It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the
    printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,
    but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker
    including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled
    it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
    and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since
    the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in
    the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting
    industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic
    typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem
    Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
    publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer
    took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset
    sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's
    standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
    It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the
    printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,
    but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker
    including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled
    it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
    and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since
    the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in
    the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting
    industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic
    typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem
    Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
    publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer
    took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset
    sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's
    standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
    It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the
    printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,
    but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker
    including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled
    it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
    and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since
    the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in
    the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting
    industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic
    typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem
    Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
    It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
    publishing software like Aldus PageMaker including versions of Lorem Ipsum.


text:
Q: .Net 3.5 app on Win PE 4.0 image Assuming a WinPE 4.0 image is setup correctly with the WinPE-NetFx4.cab, WinPE-NetFx4_en-us.cab and prerequisite packages like WMI, should an app built in Visual Studio 2008 for .NET 3.5 execute?  Or, is the app linked to strong name signed 3.5 assemblies such that it will not use the equivalent ones in .NET 4.0?

A: I'm also using WinPE 4.0 and experienced the same issue. Most of my app developed using earlier version of .NET Framework (.NET 3.0 & 3.5) will not execute (execute but nothing show up on screen)
A further investigation was made into the WinPE 4.0 WIM's Windows directory "Windows\Microsoft.NET\Framework" show only signs of version 4 (for my case v4.0.30319) was installed (WinPE-NetFx4.cab).
This concludes Microsoft's WinPE 4.0 only supports .NET Framework 4.
In order to make your app work again, re-compiled them using .NET Framework 4 assemblies.


text:
Q: Angular animation with position fixed to bottom set to 0 I'm trying to perform an enter slide-in animation using angular animation library.
One of the child div is placed at bottom of page using position: fixed, bottom: 0
The problem how ever is that while animation starts the child div starts its position at top and after animation is finished moves down to bottom of page.
Following is the example: Stackblitz.
As you observe is that child Box, Parent Box both end animation at same position, and after that child box moves down.
How to solve this issue so that when animation starts child div is at the bottom of the page.
Because of this animation doesn't look smooth.

A: I played around a bit with your code and got this:
//our root app component
import { Component, NgModule, EventEmitter } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatButtonModule } from '@angular/material';

import { style, animate, animation, animateChild, useAnimation, group, sequence, transition, state, trigger, query as q, stagger } from '@angular/animations';
const query = (s,a,o={optional:true})=>q(s,a,o);

@Component({
  selector: 'my-app',
  template: `

Parent box

Child box

  `,
  animations: [
    trigger('routeChange', [
      transition(':enter', [
        query('@*', [animateChild()]),
        query('.box', [
          style({ transform: 'translateX(-100%)', opacity: 0 }),
          animate('3400ms cubic-bezier(.75,-0.48,.26,1.52)', style({ transform: 'translateX(0)', opacity: 1 }))
        ])
      ]),
    ])
  ],
  styles: [`

    .appContainer {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }

   .child {
     color: green;
     bottom: 0;
     left: center;
     position: fixed;
   }

    .box {
      width: 100px;
      height: 50px;
      background-color: #f0397b;
      margin: 5px;
    }

  `]
})
export class App {

}

@NgModule({
  imports: [ BrowserModule, BrowserAnimationsModule, MatButtonModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule { }

Here is the fork of your code on Stackblitz. I hope it helps :)


text:
Q: Subtract 1 from a large number in PHP I need to subtract 1 from the number 294867828828426241 in PHP. However when I do
$a = 294867828828426241 - 1;

I receive the floating point number 2.94867828828E+17. Which, when resolved by number_format() gives the original number.
How can i get the correct value, please?
This needs to be able to be able work with different numbers.

A: If you have the BCMath extension you can use this:
$a = bcsub('294867828828426241', '1');

echo $a; // 294867828828426240

However, testing on my 64-bit server your code should work correctly. I'm not sure, but you can check to see if increasing the precision directive in your php.ini will make any difference. I have mine set at 14.


text:
Q: Generate XML in C# Using Specific XML Namespace Target XML I am trying to achieve:
<Row><Data ss:Type="String">value</Data></Row>

Output I am currently getting:
<Row xmlns=""><Data Type="Number">0</Data></Row>

I am trying to create that target XML code using the System.Xml library, but the namespace prefix is not showing up when I create new elements. Snippet of the code that is generating the above output:
XmlElement eRow = xDoc.CreateElement("Row");
XmlElement eData = xDoc.CreateElement("Data");
XmlAttribute xAt = xDoc.CreateAttribute("ss", "Type", null);
xAt.Value = "Number";
eData.Attributes.Append(xAt);
eData.InnerText = "0";
eRow.AppendChild(eData);

I am trying to append this XML to a file that already exists. I have loaded the file as
XmlDocument xTemp = new XmlDocument();
xTemp.Load(templatePath);

and there are already namespaces in DocumentElement.Attributes that have already declared the prefix that I want to use: <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">. Essentially, I am trying to get the "ss" prefix to show up before "Type" like in the target I provided above. Additionally, the output is displaying xmlns="" as an attribute in the "Row" tag, something that I never added. I assume these are both issues with the namespace not being declared, but as mentioned above, it should already be declared in the original document that I loaded.
How can I generate the target XML code I want?

A: You have created your attribute xAt without specifying the namespace uri, which is equivalent to empty string namespace uri (see the corresponding MSDN doc here), that is certainly why you get the <Row xmlns="">
Actually you need to specify the exact namespace uri for it to work as you expect it.
Let me illustrate using the namespace uri you have given in your question (Illustration very similar to your initial code but might have a few small differences that you can easily modify).
String namespaceUri = "urn:schemas-microsoft-com:office:spreadsheet";
XmlDocument xDoc = new XmlDocument();

XmlElement workbook = xDoc.CreateElement("ss", "Workbook", namespaceUri);
XmlElement rows = xDoc.CreateElement("Rows");

At this step I can assume that I have an XmlDocument similar to what you have after initially loading your file. My XmlDocument has the workbook node as its DocumentElement, it uses the given prefix and namespace uri.
Now we can create the attribute:
var attribute = xDoc.CreateAttribute("ss", "Type", "urn:schemas-microsoft-com:office:spreadsheet");
attribute.Value = "String";

The namespace uri should be specified correctly otherwise it won't be correctly rendered. When this attribute is used, since the namespace it is refering to is found on the nesting element (workbook), it is not necessary to mention it again here, and the framework will automatically remove the reference to the namespace uri.
Now we can go ahead and create the Row and data elements and add the attribute to the collection of attributes of the Data element.
XmlElement eRow = xDoc.CreateElement("Row");
XmlElement eData = xDoc.CreateElement("Data");

eData.Attributes.Append(attribute);
eData.InnerText = "value";
eRow.AppendChild(eData);

rows.AppendChild(eRow);
workbook.AppendChild(rows);

xDoc.AppendChild(workbook);

We can then display the document, for example with:
Console.WriteLine(xDoc.OuterXml);

Result:
<ss:Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"><Rows><Row><Data ss:Type="String">value</Data></Row></Rows></ss:Workbook>

I hope this helps.


text:
Q: onConfigurationChanged-it's still showing the first layout I have an activity which handles configuration changes. But now i have to change
layout.I tried in onConfigurationChanged callback just to set again the layout and hoping will get the correct layout(land) but it's still showing
the first layout for portrait view ( there two layout(same name) are placed in res/
layout and res/layout-land :)
if I delete android:configChanges="orientation", it works should be, but ı need to handle onConfigurationChanged. What should I do??

A: // In your activity code.
int mCurrentOrientation;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mfo_offers);
    ........
    mCurrentOrientation = getCurrentOrientation();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // You may handle different configuration changes in your activity which configured in your mainfest.xml, you only need to recreate layout when orientation changes.
        if(mCurrentOrientation != newConfig.orientation) {
            recreate(); // This recreate the activity if you can properly restore your activity state.
        }
        ......
}

See Activity.recreate() here: http://developer.android.com/reference/android/app/Activity.html#recreate()

A: If you have your portrait layout main.xml in /res/layout and your landscape layout main.xml in /res/layout-land, and your onConfigurationChanged() looks like this:
    public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            setContentView(R.layout.main);
    ...
    ...
    ...

    }

And in your Manifest you should have android:configChanges="keyboardHidden|orientation"
Then it should work fine, as this does in my app. Is this what you are doing?


text:
Q: what Inputenc should I choose in Texmaker (Win7)? I've written a main.tex document in Kile under Debian and I want to continue writing it in Windows where I've just installed TexMaker (I need to type and hear audio-recordigs, Windows has a better sound system). Both OS have a minimum installation of TeXLive 2013 with few additional packages. When I compile the main file, I get over a dozen errors: in Kile/Debian those were classified as Warnings rather than Errors. Almost all of them say this:

! Package textcomp Error: Symbol \textrightarrow not provided by
  (textcomp) font family ppl in TS1 encoding. (textcomp) Default family
  used instead. See the textcomp package documentation for explanation.
  Type H  for immediate help.

I don't know what encoding to choose or what option to put for \usepackage[???]{inputenc}. Clearly ISO-8859-1 isn't working AND is turning my keyboard crazy (some keys don't corresppond to the symbols above them if Ctrl or Alt keys are also pressed). TexMaker is suggesting UTF-8. I thought adding \PassOptionsToPackage{warn}{textcomp} in the preamble would help compile the file...but to no avail!
Help me please, I need to expedite my work!
MWE:
    \documentclass[a4paper,12pt]{scrartcl}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage[italian]{babel}

\usepackage{amssymb, amsmath, amsfonts, xfrac} %tutto matematica
\usepackage{outlines}
\PassOptionsToPackage{warn}{textcomp}
\usepackage{textcomp}

\begin{document}

\begin{outline}[enumerate]
 \1 What was blah blaha and blah?
 \2[] blah blah \textrightarrow{} lorem ipsum etc.
 \end{outline}

\end{document}

2nd not-so-MWE:
\documentclass[a4paper,12pt]{scrartcl}
\usepackage{enumerate}
\usepackage{outlines}
\usepackage{enumitem}
\setlist[enumerate,2]{label= \roman*)}
\setlist[enumerate,3]{label=\textbf{\alph*})}
\usepackage{siunitx}
\renewcommand{\SIrange}[3]{\lbrack\num{#1}\ {;}\ \num{#2}\rbrack\,\si{#3}}
 \sisetup{range-phrase = \ ;\ ,
          range-units  = brackets,
          list-units   = brackets,
          list-separator = {,\ },
          list-final-separator = {\ e\ }}
\usepackage{listings}% needed by siunitex
\usepackage{mathpazo}% needed by siunitex
%\usepackage{helvet}% needed by siunitex
\usepackage{cancel}
\usepackage{blindtext}
\usepackage{miller}
\usepackage{hyperref}
\hypersetup{pdfstartview=FitH}
\usepackage[italian]{cleveref}

\begin{outline}[enumerate]
 \1 What was blah blaha and blah?
 \2[] blah blah \textrightarrow{} lorem ipsum etc.
 \end{outline}

\end{document}

A: MWE:
\documentclass{article}
\usepackage{textcomp}
\usepackage{mathpazo}
\begin{document}
\textrightarrow
\end{document}

It generates the error:
! Package textcomp Error: Symbol \textrightarrow not provided by
(textcomp)                font family ppl in TS1 encoding.
(textcomp)                Default family used instead.

The problem is independent from package inputenc. The package mainly controls characters with character codes between 127 and 255, not the ASCII characters.
It maps them to LICRs (LaTeX internal character represnetation), e.g. ö becomes \"o.
Package fontenc maps the LICRs to the font encoding slots or replacement code.
The font encoding TS1 is a little special. There are many fonts that do not cover all characters in this encoding. Therefore package textcomp defines encoding subsets that do not define all slots for such fonts. Font ppl (Palatino) has subset 3. It is explained in the .log file:
Package textcomp Info: Sub-encoding information:
(textcomp)               5 = only ISO-Adobe without \textcurrency
(textcomp)               4 = 5 + \texteuro
(textcomp)               3 = 4 + \textohm
(textcomp)               2 = 3 + \textestimated + \textcurrency
(textcomp)               1 = TS1 - \textcircled - \t
(textcomp)               0 = TS1 (full)

The font project TeX Gyre extends the free available URW fonts:

TeX Gyre Pagella is based on URW Palladio L (from Palatino, designed by Hermann Zapf in the 1940s).

The text fonts can be easily replaced by TeX Gyre Pagella with package tgpagella:
\usepackage{mathpazo}
\usepackage{tgpagella}

Package mathpazo is kept for the math fonts, that still use Palatino.
Full example:
\documentclass{article}
\usepackage{textcomp}
\usepackage{mathpazo}
\usepackage{tgpagella}
\begin{document}
\textrightarrow $\rightarrow$
\end{document}

Here the text version comes from TeX Gyre Pagella, the math version from the default Computer Modern fonts.

Example for LuaTeX/XeTeX:
\documentclass{article}
\usepackage{fontspec}
\setmainfont{TeX Gyre Pagella}
\usepackage{unicode-math}
\setmathfont{TeX Gyre Pagella Math}
\begin{document}
  \textrightarrow → $\rightarrow →$
\end{document}

The text and math versions of TeX Gyre Pagella (Math) use a different shape for U+2192 (RIGHTWARDS ARROW).


text:
Q: Sending email on sails with mailgun machine results in 'cannot call method' on sails.machines['...'].sendPlaintextEmail({...} I have a sails project I have hooked up in treeline - after creating an object I want to send an email using the mailgun machine however receive the following error:
/Users/alexlunnon/Workspace/fclp/fclp/api/controllers/OfferController.js:48
   sails.machines['00ba429e-d255-4f44-8efc-af6f5cfa4942_0.3.1'].sendPlaint
                                                                ^
TypeError: Cannot call method 'sendPlaintextEmail' of undefined
at Object.sails.machines._project_1691_0.0.15.create_offer.setEnvironment.exec.success (/Users/alexlunnon/Workspace/fclp/fclp/api/controllers/OfferController.js:48:86)
at afterwards (/Users/alexlunnon/Workspace/fclp/fclp/node_modules/machine/lib/intercept-exit-callbacks.js:131:21)
at voided [as _onTimeout] (/Users/alexlunnon/Workspace/fclp/fclp/node_modules/machine/lib/intercept-exit-callbacks.js:98:20)
at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)

In the controller I can see sails.machines['00ba429e-d255-4f44-8efc-af6f5cfa4942_0.3.1'].sendPlaintextEmail({ is successfully called when an object is created. I can also see under the machines folder 00ba429e-d255-4f44-8efc-af6f5cfa4942_0.3.1 has been synced with machinepack-mailgun from treeline.
Trying to isolate the issue I am able to see that removing all dynamic content from the call to sendPlaintextEmail results in the same error - as does sendHTMLEmail. I am using angular to post the object through to the OfferController.js
Any tips or suggestions to debug this issue?

A: The most likely issue is that some dependencies did not properly install.  The easiest solution is to delete your api/machines folder completely and run treeline lift again to have the system automatically re-install the necessary dependencies.


text:
Q: jQuery: Looping over elements writing their ID attribute to an array? I'm trying find a bunch of <label>s in a form of mine based on an array of elements and their id attribute.
eg. [ input#country , input#other-country ] would be able to find <label for="country"> , <label for="other-country"> and so on…
so far I have this code:
var LOCATION = {};

LOCATION.option = form.find('input[name=location]').toArray();
LOCATION.labels = [
    $.each( LOCATION.option, function(i, input) {
        $('label[for='+input.id+']');
    })
];

When logging out the input.id inside the $.each loop I get the correct value being written out however I can't seem to find a way to write my matched label element from inside the $.each loop into the LOCATION.labels array afterwards.
Does anyone know how to put them into the array? toArray() does not seem to work either…
Thanks for reading.

A: I'd probably use .map():
var LOCATION = {};

LOCATION.option = form.find('input[name=location]').toArray();
LOCATION.labels = $.map( LOCATION.option, function(input) {
  return $('label[for='+input.id+']').get(0);
});

See here for an example of this in action.

A: Try this one out. Not really a one line solution to get directly the array, but I've tested this and it works fine.
var LOCATION = {};
$(function(){
  var form = $("#form"); //sample form
  LOCATION.option = form.find('input[name=location]').toArray();
  LOCATION.labels = [];
  $.each(LOCATION.option, function(i,input) {
    LOCATION.labels.push($('label[for='+input.id+']').get(0));
  });
});

A: You almost had it, just .push() from inside .each()
var LOCATION = {};

LOCATION.option = form.find('input[name=location]').toArray();
LOCATION.labels = [];

$.each( LOCATION.option, function(i, input) {
    LOCATION.labels.push($('label[for='+input.id+']'));
})


text:
Q: Implementing the metropolis-hasting algorithm Over the past few weeks I have been trying to understand MCMC and the Metropolis-Hastings, but I have failed every time I tried to implement it.
So I am trying to use the metropolis-Hastings algorithm to get the Boltzmann distribution from the uniform distribution, but it is not working.
Here is a summary of what I am doing:

*

*I draw a random number form the uniform distribution m.

*I draw another random number form the uniform distribution n.

*I set dU = n-m.

*If dU < 0, I accept dU, set m = n , and repeat.

*If dU > 0, I calculate w = exp(-b*dU), where b is 1/kT, and draw a random number form the uniform distribution r.

*If w > r, I accept dU, set m = n, and repeat.
7 If w < r, I reject dU, set m = m, and repeat.

I am a beginner to this field and to python, so I am not sure if the code  wrong or the algorithm is wrong ( probably both.)
My code is attached below. Thank you.
import random
%matplotlib inline
import numpy as np
import scipy
import matplotlib.pyplot as plt
from scipy import stats
k = 1.38064852 * 10**(-23)
t = 298
b = 1/(t*k)   U = []
m = np.random.uniform(0, 1)
for j in range(100000):
    n = np.random.uniform(0, 1)
    du = n-m
    if du<0:
            U.append(du)
            m = n
    elif du > 0:
            w = np.exp(-b*du)
            r = np.random.uniform(0, 1)
            if w > r:
                    U.append(du)
                    m = n
            else:
                    U.append(du)
                    m = m

A: Your problem are twofold. One is you sample new energy ('n=random()') as dimensionless quantity, which contradicts everything else you're doing (your temperature is in Kelvin, kB is in J/K etc). And second, using values like 1023 and inverse are not good in physical simulations - you'd better be somewhere within 0...1 range and rescale later. Below I made code which works in electron-volts, sample new energy in eV as well, and produced something which resembles the truth.
import numpy as np
import matplotlib.pyplot as plt

kB = 1.0/11600. # eV/K
T  = 300 # K
b  = 1.0/(kB * T) # inverse temperature, eV^-1

np.random.seed(76543217) # for reproducibility

N = 100000
EE = np.empty(N+1) # energy
DE = np.empty(N+1) # delta energy

Ei = 1.0 # initial energy, 1eV
EE[0] = Ei
DE[0] = 0.0
for k in range(N):
    E  = np.random.random()/b # sample energy, in eV
    dE = E - Ei
    if dE < 0.0:
        Ei = E
        EE[k+1] = Ei
        DE[k+1] = dE
    elif dE > 0.0:
        w = np.exp(-b*dE)
        r = np.random.random()
        if w > r:
            Ei = E
            EE[k+1] = Ei
            DE[k+1] = dE
        else:
            EE[k+1] = Ei
            DE[k+1] = 0.0

x = np.linspace(0, N+1, num=N+1)

print(EE[N-30:])
print(np.mean(EE[N-1000:]))
print(np.mean(EE[N-2000:]))

fig, ax = plt.subplots(1, 1)

ax.plot(x[N-1000:], EE[N-1000:], 'r-', lw=5, alpha=0.6, label='Energy')
ax.plot(x[N-1000:], DE[N-1000:], 'go', lw=5, alpha=0.6, label='Delta Energy')
plt.show()

printed are two last mean values for 1000 and 2000 samples, look thermalized to me
0.010188070423940562
0.010666101150488673

and graph for E/dE