text:
Q: What is the remainder when dividing $11^{(345^{678})}$ by 13? So basically I figured out that this problem comes down to the following:
We want to find the answer to $11^{(345^{678})} \ \text{mod} \ 13$.
Then, because $11$ and $13$ are coprime, we know that $11^{\phi(13)} = 1 \
 \text{mod} \ 13$. Because 13 is prime, we know that $\phi(13) = 12$. So
$11^{12x} = 1 \ \text{mod} \  13 $ for any integer x.
Then we need to find how many times 12 fits into $345^{678}$, so $345^{678} \ \text{mod} \ 12 $. However, $345$ and $12$ are not coprime, so we can't use Euler's theorem. This is the part where I don't actually know what to do anymore.
I tried the following: 345 mod 12 = 9 mod 12, so $345^{678} \ \text{mod} \ 12 = 9^{678} \ \text{mod} \ 12$.
We know that $9^2 \ \text{mod} \ 12 = 81 \ \text{mod} \ 12 = 9 \ \text{mod} \ 12$. And we know that $9^4 \ \text{mod} \ 12 = 9^2 \cdot 9^2 \ \text{mod} \ 12 = 9 \ \text{mod} \ 12$. So $9^2$, $9^4$, $9^8$, $9^{16}$, $9^{32}$, $9^{64}$,$9^{128}$, $9^{256}$ and $9^{512}$ are all 9 in mod 12.
So then, $9^{678} \ \text{mod} \ 12  = 9^{512} \cdot 9^{128} \cdot 9^{32} \cdot 9^{4} \cdot 9^2 \ \text{mod} \ 12  = 9^5 \ \text{mod} \ 12  = 9 \ \text{mod} \ 12 $.
Then, going back to the original question, we know that we need to calculate $11^{9} \ \text{mod} \ 13  = 11^8 \cdot 11 \ \text{mod} \ 13$.
Using the same trick as with the 9, I get that $11^{9} \ \text{mod} \ 13  = 8 \ \text{mod} \ 13$.
Is this correct? If not, what am I doing wrong? Is there a better way to attack such problems?
Thanks for reading,
K.

A: Your answer is correct, bur finding the value of $345^{678}\bmod 12$  is too long:
as you observe, it is $9^{678}\bmod 12$. You missed that since $9^2\equiv9\mod13$, we also have (easy induction) $9^n\equiv 9\mod13$ for all $n\ge1$, so
$$11^{345^{678}}\equiv (-2)^9=(-2)^6(-2)^3\equiv (-1)\cdot(-8)=8.$$

A: As $11\equiv-2\pmod{13},$
$11^{(345^{678})}\equiv(-2)^{(345^{678})}\pmod{13}$
Now $(-2)^6\equiv-1\pmod{13}\implies(-2)^{12}\equiv1,$
and $(-2)^{(345^{678})}\equiv(-2)^{(345^{678}\pmod{12})}\pmod{13}$
Now as $345\equiv0\pmod3\implies345^{678}\equiv0\  \ \ \ (1)$
and $345\equiv1\pmod4\implies345^{678}\equiv1\  \ \ \ (2)$
Using $(1),(2)$ by observation, $345^{678}\equiv9\pmod{12}$
$(-2)^{(345^{678}\pmod{12})}\equiv(-2)^9\pmod{13}\equiv?$


text:
Q: Failed to delete files on removable storage I was trying to delete files from local storage on the Android Lollipop by the following line:
new File(path).delete();

Deleting file that resides in Internal storage works fine. But failed to do so on file that is located on external removable storage. I've checked that the file do exists but cannot be overwritten. Moreover, permission has already been granted to the app.

In order to read or write files on the external storage, your app must acquire the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE system permissions.

As stated in the documentation, no luck though.
Googled for available solutions, but doesn't satisfy the problem.

A: You can not delete file on removable media starting from KitKat (API 19). You have to interact with user by means Storage Access Framework, get access object for the file you are going to delete - DocumentFile - and call delete operation on it. You can read this for deep understanding of this nightmare.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using a power transistor upstream of a load (control VCC to a load with a lower control voltage) So I have an interesting challenge. I have an LCD screen from a laptop which I am driving with a control board. The problem is the backlight needs around 19 volts to run while the control board I have is designed for LCD panels with a 5 volt backlight. Everything else runs fine, just not the backlight. I have a 19 volt power supply that I intend to run everything off of (the 5v control board will be powered of a buck converter from this 19v source). The problem is, when the control board is off or in power saving mode, it is supposed to cut power to the backlight, but since I am driving it directly off the 19v power supply, it stays on. To solve this problem I acquired myself a TIP31AG power transistor from the local radio shack (yes they do still exists) assuming that it could be used like a relay, or atleast in the same situations. As you can imagine this turned out not to be the case.
The Problem:

*

*I have a 19v load of an unkown and probably variable current draw and resistance (it has a separate PWM brightness control which probably varies things).

*I have a 5v control wire which can provide a decent amount of current (greater than logic level that is)

*I need to control the VCC into the load (not the ground connection, due to the way the control board works)

*I have a TIP31AG power transistor, and all the tutorials I have looked at have their TIP31 (which is NPN btw) downstream of the load (that is between the load and ground)

Can this be done with my TIP31 or do I need a TIP32 (the PNP variant) and another PNP control diode to control the load on the VCC side?

simulate this circuit – Schematic created using CircuitLab

A: It seems you want to switch the 19 V backlight on/off with a 5 V signal.  This can be done with a NPN power transistor, but not the way you show.  The problem is that you are running it in emitter follower mode.  The output voltage will be the control voltage minus the B-E drop, which is around 700 mV.  In your circuit, the 19 V load will only get about 4.3 V.
To fix this, run the transistor in common emitter mode:

You haven't said how much current the 19 V load requires, nor provided a link to the transistor datasheet, so we can't tell what the base current needs to be.  I arbitrarily chose 10 mA.  If the transistor has a guaranteed gain of 30 in this case, then this supports up to 300 mA load current.  You also haven't said what the current capability of the digital output is, so I can't even say whether this is possible or not.
If the digital output can't supply the load current divided by the transistor gain, then you need a higher gain transistor, or a second transistor to provide more gain.
Another approach would be to replace the NPN transistor with a N channel MOSFET, like the IRLML2502.  In that case, connect the gate directly to the digital output without R1 between.
Added
Argh!  You now say that the 19 V load is connected to ground and you can only switch the high side.  Thanks for the wild goose chase.
Here is something that should work:

Q2 becomes a controlled current sink depending on the digital signal.  When the digital signal is at 0 V, it is off.  R3 is enough to overcome whatever base leakage Q1 might have and make sure it is off.  This turns off power to the high side of the load.
When the digital signal is at 5 V, the base of Q2 will be at about 4.3 V.  R1 is therefore causing about 10 mA to flow, most of which will come from the collector of Q2.  Most of that will come from the base of Q1.  If Q1 has a gain of 30, then it can support up to about 300 mA of load current.
In this case the drive capability of the digital signal is of little concern since Q2 provides additional gain.  Let's say it has a gain of 50, so that means it only requires the digital output to source 200 µA when high.  It would be very unusual for a 5 V digital output to not be able to do that.


text:
Q: Cannot set headers for Express.js app (CORS) No matter what I try to use to set the headers it simply won't work.
The server side needs to send the response headers like this, after accepting the POST request from Frontend.
server.js
app.post('/register', (req, res) => {
   res.set({
       'Content-Type': 'application/json',
       'Access-Control-Allow-Origin': '*'
   });
   res.send('string');
   res.end();
}

The res.set() function was not the only function I tried to use.
I tried with:
res.writeHead(201, {'Access-Control-Allow-Origin': '*'}) - doesn't work
res.setHeader('Access-Control-Allow-Origin', '*') - nope
res.headers() - also doesn't work
It says here that it goes like this: How can I set response header on express.js assets but the answer doesn't work for me.
No matter what I tried, the server just won't respond with the CORS enabled header and I need that header property. What am I doing wrong?

A: Try using the cors module: https://www.npmjs.com/package/cors
var cors = require('cors')

...

app.use(cors())

A:
The Access-Control-Expose-Headers response header indicates which headers can be exposed as part of the response by listing their names.

You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
res.set('Access-Control-Expose-Headers', 'Access-Control-Allow-Origin, <any-other-custom-header>, ...');


text:
Q: Is it possible to get data from a HDD with a missing PCB? I have an old maxtor 3.5" IDE drive that is missing the PCB. I have no idea what happened to it. The drive is nearly 20 years old and has been sitting in a drawer for years.
I recently lost my beloved dog, and wanted to find every picture/video of her that I ever had. I know of some videos that I couldn't find, and I'm hoping maybe they're on that hard drive. Is there any way to get access to it?
I contacted a website that sells replacement PCB's and gave them all the details, and they said they couldn't help. Maybe there's something that can be done though? Here are the details from various labels on the drive:

*

*Model: 91741U4

*HDA: 04A

*PCBA: 05A

*Unique: 13A

*Code: FA570480

*Cylinders: 16383

*Heads: 16

*Sectors: 63J

*Jumper: J50

*Master/Single: On

*Slave: Off

*Serial Number: E406RAYC

*Manufactured 04 November 1999

On the bottom of the drive, underneath where the PCB would be, there's a sticker with a bar code. Under the bar code it says:
EC38HT-2-C M2500DTBS9416C

A: Sorry, but I can't offer much hope.
Your drive is very old but I believe this article is relevant:
https://www.hddzone.com/maxtor_pcb_swap_replacement_guide.html
The article has full information but I will cover the most important parts.
An HDD replacement PCB must be a close match to the original and the numbers that must match depend on the manufacturer. For Maxtor the important number is on the main controller IC, the largest one on the board. You have a big problem here.
Most boards have a small 8 pin ROM chip that contains important drive specific information. Usually this chip must be moved to the replacement board. Another big problem.
Things may be different for your drive but I have an old Maxtor drive from 2003 that is similar to that in the article.
A commercial data recovery service may be able to help but the cost would be very high.

A: You can always go to a hard drive data recovery lab in your area.  Unfortunately, they are never cheap, but they should be able to recover your data.

A: Based on personal experience, I'd say your chances are really slim.  I've tried to replace controller boards on hard drives with another from an identical make and model, and even then I could never get it to work.  (I work in the IT department of a medium-sized company, so I have access to a lot of hard drives.)


text:
Q: Odoo 9 admin screen is empty I installed odoo 9 (see odoo 9 theme installed in addson are missing from app for the exact steps)
I'm following the following guide https://www.odoo.com/documentation/9.0/howtos/themes.html to learn how to create a theme
I was able to create the theme and add a message on the screen (Welcome in our website! like in the tutorial)
and since then
the admin screen is empty
and any admin function either not working or logged me out
how can i debug it?

A: I found the following solution by installing odoo 10
https://www.getopenerp.com/install-odoo-10-on-ubuntu-16-04/
Works smoothly but I had to sudo su postgres before start odd ./odoo-bin
than I could walked-through https://www.odoo.com/documentation/9.0/howtos/themes.html


text:
Q: Is there a way of using relative adress with websockets? Is there some easy way of using relative address with websockets? Something like:
WebSocket.listen "<ws://localhost:8080/api>" Msg ->
   WebSocket.listen "<ws://api>" Msg

Or do I have to create a task to retrieve window.location.host on start and use it to construct the url?


text:
Q: Trying to import Koalas in Spark After pip installing koalas,  I tried to import it using the code below and it returns the error message far below.    Any direction on how to fix this?
import databricks.koalas as ks
Error:
Traceback (most recent call last):
  File "/tmp/zeppelin_pyspark-9015139547840077087.py", line 331, in <module>
    exec(code)
  File "<stdin>", line 9, in <module>
  File "/usr/lib/a-4.2.0-py-3.5.3/lib/python3.5/site-packages/databricks/koalas/__init__.py", line 41, in <module>
    import pyarrow
  File "/usr/lib/a-4.2.0-py-3.5.3/lib/python3.5/site-packages/pyarrow/__init__.py", line 45, in <module>
    import pyarrow.compat as compat
AttributeError: module 'pyarrow' has no attribute 'compat'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/tmp/zeppelin_pyspark-9015139547840077087.py", line 333, in <module>
    raise Exception(traceback.format_exc())
Exception: Traceback (most recent call last):
  File "/tmp/zeppelin_pyspark-9015139547840077087.py", line 331, in <module>
    exec(code)
  File "<stdin>", line 9, in <module>
  File "/usr/lib/a-4.2.0-py-3.5.3/lib/python3.5/site-packages/databricks/koalas/__init__.py", line 41, in <module>
    import pyarrow
  File "/usr/lib/a-4.2.0-py-3.5.3/lib/python3.5/site-packages/pyarrow/__init__.py", line 45, in <module>
    import pyarrow.compat as compat
AttributeError: module 'pyarrow' has no attribute 'compat'


text:
Q: Magento Cron not working For some reason my Cron is not working anymore in my Magento 1.9.3 store.
I tried it by running it manually, but both solutions did not give any error, still zero results in the AOE Scheduler task list. Non of them are running.
I tried:
https://www.domain.com/cron.php

and by SH
sh /path/to/my/magento/root/cron.sh

How can I solve this issue?


text:
Q: toolbarBreak disappears when deleting QToolBar When I execute the following example code, I first create two toolbars with a break between it and then I delete the second toolbar after that. The problem is that the toolbarBreak also disappears when I do that.
When I reinitialize t2, there is no break anymore. Is the toolbarBreak really "gone" here?
To fix this, I need to call addToolBarBreak(); before i reinitialize the toolbar. But do I create a duplicate of the toolbarBreak I had before?
Or should I call removeToolbarBreak(t2) before deleting t2?
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    auto* t1 = new QToolBar(this);
    t1->setMovable(false);
    t1->addAction("Hello t1 Action");
    auto* t2 = new QToolBar(this);
    t2->setMovable(false);
    t2->addAction("Hello t2 Action");

    addToolBar(t1);
    addToolBarBreak();
    addToolBar(t2);

    delete t2;
    t2 = new QToolBar(this);
    t2->setMovable(false);
    t2->addAction("Hello t2 Action");

    // addToolBarBreak(); // fixes the problem
    addToolBar(t2);
}

A: Yes, the Layout takes care of it! I debugged the Qt code myself today.
See here, in QToolBarAreaLayout::takeAt(int *x, int index) the break will be removed.


text:
Q: How to get the name of the property that is bound to datagrid column in wpf? I have a datagrid with almost 30 columns, I need to get the name of the property that is bound to a column. I am using datagrid_selectedcellschanged(sender,selectedeventargs) event of the datagrid.

A: You can do this on selectionChanged,
 private void peopleGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
  {
         var selectedObj= peopleGrid.SelectedItem as YourObject;
         if(selectedObj != null)
         {
         int PersonID   = selectedObj.PersonID;
         }
  }

A: I am not sure What you mean by Name of the property - Column header or Cell Value
If you mean the column header you can get it like this
string selectedColumnHeader = (string)myGrid.SelectedCells[0].Column.Header;

If you mean Cell Value you can get it like this
DataRowView dataRow = (DataRowView)dataGrid1.SelectedItem;
int index = datagrid1.CurrentCell.Column.DisplayIndex;
string cellValue= dataRow.Row.ItemArray[index].ToString();

A: Here is how I managed to resolve the same issue based on a data grid template column and using an editable column.
First is to cast the binding expression of the element being edited.  Next, retrieve the associated property name being displayed in the cell.
<DataGrid Name="dgMaterialSorter" AutoGenerateColumns="False" Grid.Column="1" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
          PreparingCellForEdit="dgMaterialSorter_PreparingCellForEdit"
          CellEditEnding="dgMaterialSorter_CellEditEnding">
    <DataGrid.Columns>
        <DataGridTextColumn Header="" Binding="{Binding MaterialName}"  IsReadOnly="true" Width="Auto" HeaderStyle="{StaticResource GridHdr_Right}" CellStyle="{StaticResource GridCol_Right}"/>
        <DataGridTextColumn Header="Code" Binding="{Binding MaterialCode}"  IsReadOnly="true" Width="Auto" HeaderStyle="{StaticResource GridHdr_Center}" CellStyle="{StaticResource GridCol_Center}" />
        <DataGridTemplateColumn Header="Qty"  HeaderStyle="{StaticResource GridHdr_Center}" CellStyle="{StaticResource GridCol_Center}"  >
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Quantity}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox x:Name="EditTextbox" Text="{Binding Quantity, Mode=TwoWay, UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=True}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellEditingTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>

private void dgMaterialSorter_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    if (e.EditAction == DataGridEditAction.Commit)
    {

        BindingExpression binding = (BindingExpression)e.EditingElement.BindingGroup.BindingExpressions[0];
        string bindingField = binding.ResolvedSourcePropertyName;
        if (bindingField.Equals(nameof(MaterialSorter.Quantity))) { /*DO SOMETHING*/ }
    }
}


text:
Q: Why do consecutive iterates need to be "close" in matrix secant methods? I know the vague idea about how matrix secant methods work:  The essence of the method is still using Newton's method to do the updates, and thus it is doing root finding on $f(x)$ and updating the the $x_k$ iterates by this:
$$x_{k+1} = x_k – J'(x_k)^{-1} J(x_k)$$, where $J(x_k)$ is the jacobian of $f(x)$
then of course the secant method is striving to do what newton's method does, with two modifications:
1) we are trying to find the roots of the gradient, $g(x) = \nabla f(x) = 0 $
2) we take a secant approximation of the Jacobian instead of the jacobian itself:  $M_k (x_{k+1} – x_k) = g(x_{k+1}) – g(x_k)$
Then, the next idea of the matrix secant methods is that consecutive iterates on the approximation of $M_k$ be close to each other, i.e. minimize $ ||M_k – M_{k+1} || $.
For example, in Nocedal and Wright, we have the sentence: "…and a requirement that the difference between successive approximations have low rank."  Why is it that we want consecutive iterates of the secant methods to be "close" to each other in this sense?

A: You asked a lot of questions, and I will attempt to provide an "answer" - the quotes are there since to the best of my knowledge there is no formal proof for the fact that these methods work better than the gradient method, despite their excellent performance in practice.
So first, let's look at (the pure) Newton's method for minimization - we find a descent direction $d_k$ by solving the system $\nabla^2 f(x_k) d_k = -\nabla f(x_k)$, and then compute
$$
x_{k+1} = x_k + d_k = x_k - [\nabla^2 f(x_k)]^{-1} \nabla f(x_k).
$$
First, observe that $d_k$ is indeed a descent direction if and only if $\nabla^2 f(x_k)$ is positive definite. Since $M_k$ attempts to imitate the Hessian, it should also be positive definite. This answers your second question (in the comments).
To answer the rest, I will need to look from another perspective. Observe, that Newton's method is equivalent to
$$
x_{k+1} = \operatorname*{argmin}_x \{ f(x_k) + \nabla f(x_k)^T (x - x_k) + \frac{1}{2} (x - x_k)^T \nabla^2 f(x_k)(x - x_k)  \}
$$
Indeed, when $\nabla^2 f(x_k)$ is positive definite the function inside the braces is convex, and if you compare its gradient w.r.t $x$ to zero, you obtain the Newton update. What is inside the braces is the 2nd order Taylor approximation. So Newton's method essentially assumes that the 2nd order Taylor approximation is a good approximation for the function, which we can minimize instead of minimizing the function itself.
Remember that the error term in the 2nd order approximation includes the 3rd derivatives. If they are small, the approximation is good. Thus, Newton's method works well when the 2nd derivative changes 'slowly' in some sense. And indeed, there are theorems which rely on this slowness to formally prove its convergence: either assume that $\nabla^2 f$ is Lipschitz continuous, or assume that $f$ is self-concordant.
This analysis attempts to intuitively answer your first question - why do we require consecutive $M_k$ to be close to each other - it is to imitate the behavior of the Hessian of such 'good' functions where the Hessian changes slowly.


text:
Q: expectation number shake hands from same country Here is a brainstorm of probability:

For 18 people, 9 from country A and 9 from country B. They sit in a circle and shake hands if the person next to them is from the same country, otherwise they don't shake hands. What's the expectation of total number of handshakes?

I know how to solve when people sit in a line: if two of people are from same country, choose any two of seats for them, the probability of sitting adjacently are
$$P = \dfrac{17\times2}{P^{18}_2}=\dfrac{17\times2}{18\times17}=\dfrac{1}{9}.$$
The possibilities that two of people are from same country are
$$C_2^9\times2=\dfrac{9\times8}{1\times2}\times2=72.$$
Therefore the expectation is
$$E = \dfrac{1}{9}\times72=8.$$
But for the circle case, there are a lot of duplicate case, I don't know how to deal with.

A: The probability a given person shakes hands with the person to their left is $\frac{8}{17}$ (since there are $17$ people who may be sitting to their left, $8$ of whom they would shake hands with). So the expected number of people who shake hands with the person to their left is $18\times 8/17$. This is also the expected number of handshakes, since each handshake involves exactly one person shaking hands with someone to their left.
Incidentally, this also does the line version. In this case you need to look at the probability that the person in a given position shakes hands with the person to their left; this is $8/17$ for every position except the leftmost one (where it is $0$), so you get $17\times 8/17$ in this case.


text:
Q:  file not found I just updated my Xcode to 6.3 and my project which was working fine till xcode 6.2 started giving errors .
Error is <TargetName-Swift.h> file not found ,current path of bridging header is inside subfolder of project ,i.e one level inside .xcodeproj file .
Already tried

*

*Deleting Bridging-Header file and recreating it .

*Changing the path under Swift Compiler- Code generation under build settings

*Also tried to change header search path ,but I think that was already correct .

*Checked for circular reference , but i dont think that can be a problem because it was working fine before updating xcode .
Also somewhere I read it is generated at "$(TARGET_TEMP_DIR)/../$(PROJECT_NAME).build/DerivedSources"
 at this path , but didnot work for me .
****Edit ***
Checked the log files generated it has error like "Opening import file for module 'Swift': Permission denied". Any idea ?? Of course I am super admin in the mac I am using .
Tried degrading Xcode again to 6.2 an everything worked well .
Any help would be great ..!!
Thanks .

A: This is due to build errors. <TargetName-Swift.h> is generated when there are no build errors.
Xcode 6.3 includes swift 1.2 which has some breaking changes compared with earlier swift version (distributed with xcode 6.2).

A: *

*Make sure you have Objective-C Bridging Header set to "TARGET_NAME/Your-Bridging-Header.h";" in the Build Settings

*Open Terminal and run next commands:
cd Project_Folder
sudo chown -R whoami *


text:
Q: Double quotes appear when it should've been single quotes Python 3 I am currently doing exercices from the book "Learn Python the hard way by Zed, Shaw. "
Although the author specified that his book is intended for Python 2.x, I'm managing to convert the syntax from the book to python 3 standards.
One strange thing, though. In an exercise where he's explaining the different uses of %r, the interpreter prints one of the string values with double quotes, whereas the others are printed with a single quote.
I'd like to know the reason, please.
Here's the code :
formatter = " %r %r %r %r"
print (formatter % ( "I had this thing",
   "That you could type up right.",
   "But it didn't sing.",
   "So I said goodnight."))

The code works fine, it's just that in the interpreter, the output reads :

'I had this thing', 'That you could type up right.' "But I didn't sing." 'So I said good night.'

As you can see, the third value gets printed inside double quotes. How come ?
I'm using notepad ++, python 3 and Windows Powhershell.
Thank you

A: "But it didn't sing." as this string contains single quote, it is being printed inside double quote.
Moreover, %r will insert the canonical string representation of the object (i.e. repr(o))
To learn more about repr() read Python3 official documentation: https://docs.python.org/3/library/functions.html#repr


text:
Q: Conditional dot I did some changes to my LoF in order for the page number not to be printed with a dotted leader at the right margin but just with a short gap after the caption. Now I would like to have one dot ending the caption, which in most cases under the figure is supposed to be printed without dot. For that I have somewhat managed to redefine \cftfigureformatpnum to include a dot. But I would actually like the dot to be conditional, for the case that the caption exceptionally does end on a dot (or possibly some other punctuation), similar to how biblatex does.
\documentclass{memoir}
\usepackage{caption}
\usepackage{calc}

%Some formatting of the figure captions
\DeclareCaptionLabelSeparator*{qquad}{\qquad}
\DeclareCaptionStyle{mystyle}%
{font=small,labelfont=sc,textfont=it,format=hang,labelsep=qquad}
\captionsetup{style=mystyle}
\renewcommand*{\figurename}{figure}

%Some formatting of the LoF
\renewcommand\printloftitle[1]{\section*{#1}}
\renewcommand\afterloftitle{\vspace{\baselineskip}{\small\textsc{Figure\quad Caption}\\}}
\setlength{\cftfigurenumwidth}{\widthof{\small{\textsc{Figure\quad}}}}
\renewcommand{\cftfigureleader}{}
\renewcommand{\cftfigureafterpnum}{\cftparfillskip}

%Make a dot before the page number
\makeatletter
\renewcommand*{\cftfigureformatpnum}[1]{%
\cftfigureformatpnumhook{#1}%
\hbox to \@pnumwidth{.\hfil{\cftfigurepagefont #1}}}
\makeatother
\begin{document}

\begin{figure}
\caption{something}
\end{figure}

\begin{figure}
\caption{something a bit longer, longer, longer, longer and longer, and longer, and longer, and longer}
\end{figure}

\begin{figure}
\caption{If I already have a dot it gets ugly.}
\end{figure}

\listoffigures

\end{document}

A: Do \usepackage{amsthm} that has an interesting \@addpunct macro and carry the current value of \spacefactor inside the \hbox:
\usepackage{amsthm}

%Make a dot before the page number
\makeatletter
\renewcommand*{\cftfigureformatpnum}[1]{%
  \edef\savespacefactor{\the\spacefactor}%
  \cftfigureformatpnumhook{#1}%
  \hbox to \@pnumwidth{%
    \spacefactor\savespacefactor\@addpunct{.}%
    \hfil{\cftfigurepagefont #1}}}
\makeatother

However, I'd simplify the macro as
%Make a dot before the page number
\makeatletter
\renewcommand*{\cftfigureformatpnum}[1]{%
  \@addpunct{.}\nolinebreak\hspace{1em}{\cftfigurepagefont #1}%
}
\makeatother

You're interested in a fixed space between the caption text and the page number, not that this space decreases if the page number has more than one digit.
By default, \cftfigureformatpnumhook does nothing.
Note that \@addpunct{.} will add a period only if no punctuation symbol ends the caption text. So you can have question marks, exclamation marks, colons or semicolons and no period will be added.

A: I solved this using the xstring package, which includes a good amount of functionality for working with strings. The IfEndWith and StrGobbleRight commands were particularly useful. After including the package, I redefined the caption function with the following:
%Renew the caption command
\let\oldcaption=\caption
\renewcommand{\caption}[1]{%
  \IfEndWith{#1}{.}{
    \StrGobbleRight{#1}{1}[\output]
    \oldcaption[\output]{\output{}.}
  }{
    \oldcaption{#1}
  }
}

I've updated you MWE to the following:
\documentclass{memoir}
\usepackage{caption}
\usepackage{calc}
\usepackage{xstring}

%Some formatting of the figure captions
\DeclareCaptionLabelSeparator*{qquad}{\qquad}
\DeclareCaptionStyle{mystyle}%
{font=small,labelfont=sc,textfont=it,format=hang,labelsep=qquad}
\captionsetup{style=mystyle}
\renewcommand*{\figurename}{figure}

%Some formatting of the LoF
\renewcommand\printloftitle[1]{\section*{#1}}
\renewcommand\afterloftitle{\vspace{\baselineskip}{\small\textsc{Figure\quad Caption}\\}}
\setlength{\cftfigurenumwidth}{\widthof{\small{\textsc{Figure\quad}}}}
\renewcommand{\cftfigureleader}{}
\renewcommand{\cftfigureafterpnum}{\cftparfillskip}

%Renew the caption command
\let\oldcaption=\caption
\renewcommand{\caption}[1]{%
  \IfEndWith{#1}{.}{
    \StrGobbleRight{#1}{1}[\output]
    \oldcaption[\output]{\output{}.}
  }{
    \oldcaption{#1}
  }
}

%Make a dot before the page number
\makeatletter
\renewcommand*{\cftfigureformatpnum}[1]{%
\cftfigureformatpnumhook{#1}%
\hbox to \@pnumwidth{.\hfil{\cftfigurepagefont #1}}}
\makeatother
\begin{document}

\begin{figure}
\caption{something}
\end{figure}

\begin{figure}
\caption{something a bit longer, longer, longer, longer and longer, and longer, and longer, and longer}
\end{figure}

\begin{figure}
\caption{If I already have a dot it gets ugly.}
\end{figure}

\listoffigures

\end{document}

You'll notice that the extra . is gone where it shouldn't exist.


text:
Q: Flashing Safari I just upgraded to OS X El Capitan and my Safari windows are constantly flashing. I've already re-started my computer, but it's still flashing. It's mostly when something on the page is moving and mainly on constantly moving pages, such as Facebook, Pandora, and Imgur. Is there something I can do to make it stop flashing?

A: Choose Develop → Show Web Inspector (⌥⌘I) and select  Disable paint flashing.


text:
Q: android : post data to webview I am using Webview to send data to exchange mail server . ( http post did not work for mails with large attachments and hence hence trying this method ).
Please see my code below.
If I send data with no encoding at all, sending fails.
If I do as per my code below where I do encoding for the whole data , it still fails.
If i try the commented code , where I store the data as name valuepairs and encode that , mail is received but there is no attachment. So what is the right way to do encoding here? The type of attachment is ContentBody . All other parameters are string.
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,);
            entity.addPart("hidid", new StringBody(hidid));
            entity.addPart("hidchk", new StringBody(hidchk));
            entity.addPart("hidcanary", new StringBody(canary));
           entity.addPart("attach", attachment);
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            entity.writeTo(bytes);
            String fullUrl = baseUrl + "?ae=Dialog&t=Attach&a=Add";
        webView.postUrl(fullUrl, EncodingUtils.getBytes(bytes.toString(),"BASE64"));

          /*  List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("hidid", hidid));
            parameters.add(new BasicNameValuePair("hidchk", hidchk));
            parameters.add(new BasicNameValuePair("hidcanary", canary));
            parameters.add(new BasicNameValuePair("attach", attachment.toString()));
            UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(parameters);
String fullUrl = baseUrl + "?ae=Dialog&t=Attach&a=Add";
   webView.postUrl(fullUrl, EntityUtils.toByteArray(entity1)); */

i see that he Android WebView::postUrl method is harder coded for "application/x-www-form-urlencoded" .

A: Try converting your attachment as
 public static String encodeToBase64(String string)
    {
        String encodedString = "";
        try
        {
            byte[] byteData = null;
            if(Build.VERSION.SDK_INT >= 8) // Build.VERSION_CODES.FROYO --> 8
            {
                byteData = android.util.Base64.encode(string.getBytes(),android.util.Base64.DEFAULT);
            }
            else
            {
                byteData = Base64Utility.encode(string.getBytes(),Base64Utility.DEFAULT);
            }
            encodedString = new String(byteData);
        }
        catch (Exception e)
        {
        }
        return encodedString;
    }

to base64

A: bytes.toString()

creates a String from your bytes. Use toBytesArray() instead, to obtain a byte[]
Then, EncodingUtils encodes using a Charset. BASE64 is not a Charset. UTF-8 is. If you want to Base64-encode your bytes, use android.util.Base64.encode(byte[]);
In your example :
webView.postUrl(fullUrl, Base64.encode(bytes.toByteArray(), Base64.DEFAULT));

A: Per a blog post about using MultipartEntity to post data to a url, you may need to include some additional jar files in your project.  They include the following apache open-source projects:  apache-mime4j, httpclient, httpcore and httpmime.
Once you do that, you should be able to use the following code as an example to post both string & files to a url:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.tumblr.com/api/write");

try {
  MultipartEntity entity = new MultipartEntity();

  entity.addPart("type", new StringBody("photo"));
  entity.addPart("data", new FileBody(image));
  httppost.setEntity(entity);
  HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}


text:
Q: WCF Custom Validator passing parameter and/or find out from which behavior the custom validator is called? when I call the X509CertificateValidator from the web.config:
<serviceBehaviors>
        <behavior name="MyServiceBehaviour">
          [...]
            <clientCertificate>
              <authentication certificateValidationMode="Custom" customCertificateValidatorType="MyX509CertificateValidator, service" />
            </clientCertificate>
           [...]
        </behavior>
</serviceBehaviors>

*

*Is it possible to pass any parameter/data to the MyX509CertificateValidator class?

*Is it possible to find out, from which behavior (in this case MyServiceBehaviour) the MyX509CertificateValidator is called (in case if you have several behaviors in the web.config)?


text:
Q: NVMe ssd: Why is 4k writing faster than reading? I have a Samsung 960 Pro 512 GB SSD on NVMe with PCIe Gen.3x4 running. I use the Samsung NVMe Driver 2.0.0.1607. The SSD is running fine. However, I don't understand why the writing of 4k is faster than the reading of 4k. I am using AS Benchmark:

It is a factor of 3! Is there something wrong (with my system or AS Benchmark) or is this normal?

A: 4k reads are going to be about the hardest thing the drive can do.  They are amongst the smallest block sizes the drive is going to be able to handle, and there's no way for the drive to preload large quantities of data, in fact they are probably quite inefficient if the drive load-ahead logic is intending to read anything larger than 4kb.
"Normal" drive reads are more likely to be larger than 4kb as there are very few files that are that small, and even the page file is likely to be read in large chunks as it would be odd for a program to have "only" 4KB of memory paged out. This means that any preloading that the drive tries to do will actually penalise the drive throughput.
4K reads might pass through the drive buffer, but the "random" part of the test makes them entirely unpredictable. The controller won't know when the drive might need the more usual "large" reads again.
4K writes on the other hand can be buffered, queued, and written out sequentially in an efficient manner.  The drive buffer can do a lot of the catch-and-write work that it was designed for, and the wear leveller might even allocate all those 4K writes to the same drive erase block, occasionally turning what is a 4K "random" write into something closer to a sequential write.
In fact I suspect that this is what is happening in the "4K-64Thrd" writes, the "64-Thrd" is apparently using a large queue depth, thus signalling to the drive that it has a large amount of data to read or write.  This triggers a lot of clustering of writes and so approaches the sequential write speed of the drive.  There is still an overhead to performing a 4K write, but now you are fully exposing the potential of the buffer.  In the Read version of the test the drive controller, now recognising that it is under very constant heavy load, stops preloading data, possibly avoids the buffer and instead switches to a "raw" read mode, again approaching the sequential read speed.
Basically the drive controller can do something to make a 4K write more efficient, especially if a cluster of them arrive at a similar time, while it can't do anything to make a single 4K read more efficient, especially if it is trying to optimise dataflow by pre-loading data into the cache.

A: SSD controller caches writes in the onboard NVRAM, and flushes it to flash media at opportune times. Write latency is thus the cache access latency, typically 20us. Reads, on the contrary, are served off the media, with access time of 120-150us at best.

A: Other answers have already explained why it may be that writing is faster than reading; I would like to add that for this drive this is absolutely normal, as it is confirmed by benchmarks that you can find in reviews.
ArsTecnica's review
ArsTechnica has reviewed the drive, both your version (512 GB) and the 2 TB one:

(This graph is not immediately visible in the review, it's the 5th one in the first gallery, you have to click on it)
The performance of these 2 models is very similar, and their numbers look like yours: the drive can read at 37 MB/s and write at 151 MB/s.
AnandTech's review
AnandTech has also reviewed the drive: they used the 2TB model, averaging the results of tests with a queue depth of 1, 2 and 4. These are the graphs:

The drive reads at 137 MB/s and writes at 437 MB/s. The number are much higher than yours, but it's probably due to the higher queue depths. Anyway the write speed is 3 times the read speed, as in your case.
PC World's review
One more review, by PC World: they have tested the 1 TB version, and the results for 4K are 30 MB/s for reading and 155 MB/s for writing:

The write speed is in line with yours, but here the drive is even slower at reading. The result is that the ratio is five to one, not three to one.
Conclusion
Reviews confirm that for this drive it is normal that the write speed for random 4K is much faster than the read speed: depending on the test, it can even be 5 times faster.
Your drive is fine. There's no reason to believe it is faulty, or that your system has a problem.

A: Expanding on Andrey's answer, you need to look at the overhead involved before the SSD can signal to the computer that the operation is complete.
For a write, the data must merely be written to an internal RAM cache. Later it will be written to flash memory, along with other 4k blocks and metadata needed to check, error correct and locate it.
For a read, the SSD must first locate the data. The location that the computer wants to read is called the logical address, and does not have a direct relationship with the physical location of the data in flash memory. The SSD translates the logical address into a physical one, based on the geometry of the flash memory (the way the cells are arranged), bad block remapping, wear levelling and various other factors. It then has to wait for any other operations to finish before retrieving the data from flash, then checking it and if required re-reading and applying error correction, possibly even re-writing the whole block somewhere else.
While the total time taken by a write operation may be longer than a typical read operation, the time taken for the SSD to report that the operation completed to the extent that it can process further commands is lower. With large blocks the overhead is not the limiting factor, but with many small blocks it starts to limit read/write speed.


text:
Q: Is there convincing evidence of a difference in the population averages? My question is as follows:

Auto Exhaust and Lead Concentration in Blood. Researchers took
  independent random samples from two populations of police officers and
  measured the level of lead concentration in their blood. The sample of
  126 police officers subjected to constant inhalation of automobile
  exhaust fumes in downtown Cairo had an average blood level
  concentration of 29.2 μg/dl and an SD of 7.5 μg/dl; a control sample
  of 50 police officers from the Cairo suburb of Abbasia, with no
  history of exposure, had an average blood level concentration of 18.2
  μg/dl and an SD of 5.8 μg/dl.
  My work is as follows:

Given:
Experimental:
n = 126
μ = 29.2
sd = 7.5
Control:
$n = 50$
$μ = 18.2$
$SD = 5.8$
Null hypothesis: $μ1 = μ2$
Alternative hypothesis: $μ1 ≠ μ2$
$$\left(\frac{(126-1)(7.5)^2 + (50-1)(5.8)^2}{(126+50-2)}\right)^{1/2}=7.06$$
$$SE = 7.06\sqrt{(1/ 126)+(1/50)} = 1.18$$
$$-11/(1.18)= -9.32$$
So this test statistic generates a very small P-value - meaning we can reject the null hypothesis?


text:
Q: How to add object within list view item to new array list myListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.dialog_box);
            dialog.setTitle("Wish List");

            TextView dialogText = (TextView) dialog.findViewById(R.id.dialog_text);
            Button dialogButtonYes = (Button) dialog.findViewById(R.id.button_yes);
            Button dialogButtonNo = (Button) dialog.findViewById(R.id.button_no);

            dialogButtonYes.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    ArrayList<Product> wishList = new ArrayList<Product>();
                    wishList.add() ***// HOW DO I ACCESS THE OBJECT AT THAT ITEM TO ADD IT TO THE WISHLIST***
                }
            });

            dialogButtonNo.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    dialog.dismiss();
                }
            });
        }
    });

I don't know how to insert Object at that specific item click into the array list. How would I go about that?
I have all sorts of Objects saved up in different items through the list view but each item consists of a different object and when the user clicks yes from the dialog box on the specific item, I want to store that object in a new array list once again.
Thank You

A: You should be able to use the position parameter (arg2 in your example) in onItemClick to index into the main list. Then set a final variable to store the Product which can then be added in the dialog if desired:
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    Object o = myList.getItemAtPosition(arg2);
    if (o instanceof Product) {
        final Product selectedProduct = (Product)o;
    }
    // ... Create dialog etc...
}

A: Define the wishlist array outside of the click somewhere in the class
 myListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {

            final Product product = adapter.getItem(arg2);

            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.dialog_box);
            dialog.setTitle("Wish List");

            TextView dialogText = (TextView) dialog.findViewById(R.id.dialog_text);
            Button dialogButtonYes = (Button) dialog.findViewById(R.id.button_yes);
            Button dialogButtonNo = (Button) dialog.findViewById(R.id.button_no);

            dialogButtonYes.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                      addToWishList(product);
                }
            });

            dialogButtonNo.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    dialog.dismiss();
                }
            });
        }
    });

somewhere in your activity or adapter
ArrayList<Product> wishList = new ArrayList<Product>();

have a method like this
public function addToWishList(Product product){
 wishList.add(product);
}


text:
Q: Detecting syntax error in css file and ruby on rails. invalid css I am encountering a problem when trying to push my code up to heroku. I have run:
RAILS_ENV=production bundle exec rake assets:precompile

and got this error:
Sass::SyntaxError: Invalid CSS after "  color: #f19f4d;5": expected "{", was ";"
(sass):916

I understand there is syntax error somewhere in my css yet i have gone through all my files and can not find this line. Can someone please tell me if there is way to locate this line or where it could possibly be. Thank you so much!

A: If you are using Bootstrap, it depends on jQuery so you'll need to make sure to include it in your application stylesheet so for example in app/assets/stylesheets toward the top of the file and before any bootstrap includes or imports you'll need
//*= require jquery-ui

If that's not the problem, thaen precompilation is failing due to some kind of syntax error.  First try to any occurrence of f19f4d in your code by doing a full text search of your code.  If you have a *nix based system you can just try either of these from the terminal,
if you are using git version control
git grep f19f4d

Or just
grep f19f4d

If that doesn't turn up the culprit, than it must be a third party dependency.  You'll need to go through any includes in your css. Check in your layout file.  You should have something like
<%= stylesheet_link_tag "application" %>

So then open the file app/assets/stylesheets/application.scss
You will then need to comment out any includes and add them back one by one until you find which library is causing precompilation to fail.  You will need to do this for every layout and/or stylesheet until you find which one is causing the problem.
At the top of each stylesheet you should have a list of includes like
  @import 'bootstrap';

Or they may look more like this:
//*= require jquery-ui

So to comment them to not load you can just make them like this while you are testing.
// @import 'bootstrap';

// require jquery-ui

You may got other compilation errors if you have a lot of 3rd party stuff all over the place, but you have to find the bug somewhere.


text:
Q: select or fetch value from an array. chef inspec Having an array command port.where{port= /.+/}.ports with result:
[111, 20048, 80, 5556, 5557, 1622, 22, 23, 33080, 5432, 25, 443, 2620, 26365, 2049, 10500, 199, 29460, 7188, 4118, 55755, 35461, 51986, 123, 16515, 161, 646, 659, 13666, 29013, 611, 21460]

I need to select the value match with 2049 and 111 from the array. My code is:
port.where{port= /.+/}.ports.flatten.select {|x| x.to_i  == 111 && x.to_i == 2049}

Required result is to select only array matching values [2049,111].


text:
Q: How to use Chrome dev tools to debug javascript tag added dynamically to a page's head element? I'm trying to use Chrome's dev tools to debug the flow of javascript on a page. I have a 3rd party system that loads javascript that dynamically adds a SCRIPT tag to the HEAD element on the page using some code like:
var head= document.getElementsByTagName("head")[0];
var el = document.createElement('script');
el.type = 'text/javascript';
el.src = 'https://address.com/anotherjsscript.js';
head.appendChild(el);

How can I catch the "anotherjsscript.js" as it is dynamically loaded and debug into that?

A: Although BenG's answer will cover most cases, my case was badly obfuscated with a different filename dynamically served each time.  My solution was to add an event listener for "Script first statement" and then laboriously work through all the other scripts until I hit the one I wanted.

A: Option 1
I just used your code above pointing to jQuery Validation:-
var head= document.getElementsByTagName("head")[0];
var el = document.createElement('script');
el.type = 'text/javascript';
el.src = 'https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.js';
head.appendChild(el);

After letting the page run for the 1st time, you will see the request under the Network Tab, right click on the script and select Open in source panel :-

then add your break point and refresh the page again:-

Which should then get hit.
Option 2
Another option is to create a function like below, which gets the script content, prepend a debugger and set the scripts text to the content:-
function debugScript(url){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", url, false );
    xmlHttp.send( null );
    var script = 'debugger; ' + xmlHttp.responseText;
    var head = document.getElementsByTagName("head")[0];
    var el = document.createElement('script');
    el.type = 'text/javascript';
    el.text = script;
    head.appendChild(el);
}

debugScript('https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.js');

The breakpoint will get hit as long as the developer tools is open.


text:
Q: how to write expression with vb.net in mapwingis (ShapefileCategory.Expression) I would like to give color to the map with new category. to make must make previous expression.  I've tried but still failed. What is wrong ?
Please help me.
 Dim category As MapWinGIS.ShapefileCategory = sf.Categories.Add("Manual")
    Dim ad As String = "Alaska"
    Dim UniqueShape As New MapWinGIS.Shapefile
    UniqueShape = FormMain.AxMapMain.get_GetObject(idx)

    Dim af As String = UniqueShape.Table.Field(1).Name
    Const cote As String = """"

    'failed
    ' category.Expression = "[STATE_NAME] = """ + ad + """"
    'failed
    ' category.Expression = "[STATE_NAME] <> """""
    'failed
    category.Expression = "[" + af + "] = " + ad
    'failed
    category.Expression = "[STATE_NAME] = " & cote & "Alaska" & cote
    'failed
    'category.Expression = "[STATE_NAME] = ""Alaska"""

    Dim utils As New MapWinGIS.Utils
    category.DrawingOptions.FillColor = utils.ColorByName(MapWinGIS.tkMapColor.Magenta)
    sf.Categories.ApplyExpression(0)

    sf.DefaultDrawingOptions.Visible = False
    ' FormMain.AxMapMain.AddLayer(sf, True)
    FormMain.AxMapMain.Redraw()
    FormMain.AxMapMain.Refresh()


text:
Q: Less frequent ticks on the x axis in Pyplot In a python plot, I have used xticks to tell my plot what values to put on the xaxis:
plt.xticks(np.arange(grid_resid.shape[1]),xp_int,rotation="vertical")

Both (np.arange(grid_resid.shape[1]) and xp_int have 1830 values each:
[   0    1    2 ..., 1827 1828 1829]
[ 53293  53294  53295 ...,  55120  55121  55122]
I have realised that I don't need a tick for each of the 1830 values. I instead want a tick only every 100 or so. I'm hoping that there's a simple way to do this.
Any help would be gratefully received. Thank you.

A: xticks, as you see, takes two parameters. The first specifies the location of the ticks, the second the labels.
In your case, the locations happen to be integers that can be used as keys to your labels. Thus you could easily do a tick every 100:
locs = np.arange(grid_resid.shape[1],step=100) # locations
plt.xticks( locs, xp_int[locs], rotation="vertical" )


text:
Q: unique pointer vs raw pointer Trying to understand the unique_pointer vs raw pointer access
#include <iostream>
#include <memory>

int main() {
    int a = 10;
    int *x = &a;
    int *y = &a;
    std::unique_ptr<int> p1 = std::make_unique<int>(a);
    std::cout<<*x<<*p1<<*y<<"\n";
    // prints 101010
    *p1 = 20;
    std::cout<<*x<<*p1<<*y<<"\n";
    // prints 102010
    *x =30;
    std::cout<<*x<<*p1<<*y<<"\n";
    // 302030
    return 0;
}

Output
101010
102010
302030

Program ended with exit code: 0

In the above code x, y,p1 are all pointing to variable a;
so change of value a should have reflected to all the pointers dereferencing .
Please do help me to understand the behaviour I am few of the guys who all are now moving from use of raw pointers to smart pointers.

A: You're wrong, p1 doesn't point to a.
Instead std::make_unique<int>(a) create a brand new int object and initialize it to the current value of a.

To make p1 point to a you need to do
std::unique_ptr<int> p1(&a);

However that brings with it other problems, like p1 taking over the ownership of &a, and attempting to free that memory when p1 is destructed (which is not possible).
You could use the Boost null_deleter to avoid the last problem.
But I recommend that in most situation you should not look at the smart pointers a simple self-deleting pointers, but instead from an ownership perspective.

A: The code below is based on MSVC.
Reason

*

*std::make_unique() let you make new object, not reference the parameter

*

*You can find that the unique_ptr p1 gets a different address
int a = 10;                                         // &a = 0x000000bd7d5dfb74
int* x = &a;                                        // x = 0x000000bd7d5dfb74
int* y = &a;                                        // y = 0x000000bd7d5dfb74

std::unique_ptr<int> p1 = std::make_unique<int>(a); // p1._Mypair._Myval2 = 0x00000288fbbd6ba0
std::cout << *x << *y << *p1 << "\n";

*p1 = 20;
std::cout << *x << *y << *p1 << "\n";

*x = 30;
std::cout << *x << *y << *p1 << "\n";

Solution

*

*As Some programmer dude said, use std::unique_ptr<int> p1(&a);

*

*This results that the unique_ptr indicates the same address
int* a = new int(10);        // a = 0x0000027411117260
int* x = a;                  // x = 0x0000027411117260
int* y = a;                  // y = 0x0000027411117260

std::unique_ptr<int> p1(a);  // p1._Mypair._Myval2 = 0x0000027411117260
std::cout << *x << *y << *p1 << "\n";

*p1 = 20;
std::cout << *x << *y << *p1 << "\n";

*x = 30;
std::cout << *x << *y << *p1 << "\n";

*FYI, as the unique_ptr p1 will free the memory of a, you do not need to free the memory explicitly.


text:
Q: Поменять местами элементы словаря Вопрос может быть не серьезный, но никак не соображу и в сети ничего толкового не найти.
Есть список словарей:
[
{'Цитата': 'Каждый миг наслаждения — это дар богов. ', 'Автор': 'Клод Адриан Гельвеций', 'Ссылка': 'http://forismatic.com/ru/20376e8629/'},
{'Цитата': 'Вместо того, чтобы посвятить себя миру, человек растрачивает себя на дела. ', 'Автор': 'Карлос Кастанеда', 'Ссылка': 'http://forismatic.com/ru/9208878436/'},
{'Цитата': 'Ничего не принимайте близко к сердцу. Немногое на свете долго бывает важным.', 'Автор': 'Эрих Мария Ремарк', 'Ссылка': 'http://forismatic.com/ru/ee22b4e505/'}
]

Подскажите, пожалуйста, как преобразовать словари, чтобы сначала шел автор, затем цитата, затем ссылка.

A: Вообще спрашивается зачем?
Для вывода на экран можно решить в лоб, а для доступа к элементам порядок не важен
Но если очень чешется, то можно сделать так:
data = [
    {'Цитата': 'Каждый миг наслаждения — это дар богов. ', 'Автор': 'Клод Адриан Гельвеций', 'Ссылка': 'http://forismatic.com/ru/20376e8629/'},
    {'Цитата': 'Вместо того, чтобы посвятить себя миру, человек растрачивает себя на дела. ', 'Автор': 'Карлос Кастанеда', 'Ссылка': 'http://forismatic.com/ru/9208878436/'},
    {'Цитата': 'Ничего не принимайте близко к сердцу. Немногое на свете долго бывает важным.', 'Автор': 'Эрих Мария Ремарк', 'Ссылка': 'http://forismatic.com/ru/ee22b4e505/'}
]

data = [{'Автор': obj['Автор'], 'Цитата': obj['Цитата'], 'Ссылка': obj['Ссылка']} for obj in data]

print(*data, sep='\n')

будет выведено:
{'Автор': 'Клод Адриан Гельвеций', 'Цитата': 'Каждый миг наслаждения — это дар богов. ', 'Ссылка': 'http://forismatic.com/ru/20376e8629/'}
{'Автор': 'Карлос Кастанеда', 'Цитата': 'Вместо того, чтобы посвятить себя миру, человек растрачивает себя на дела. ', 'Ссылка': 'http://forismatic.com/ru/9208878436/'}
{'Автор': 'Эрих Мария Ремарк', 'Цитата': 'Ничего не принимайте близко к сердцу. Немногое на свете долго бывает важным.', 'Ссылка': 'http://forismatic.com/ru/ee22b4e505/'}

A: Лучше не полагаться на внутреннее устройство словаря, а просто выводить поля в нужной последовательности:
dict_list =[
{'Цитата': 'Каждый миг наслаждения — это дар богов. ', 'Автор': 'Клод Адриан Гельвеций', 'Ссылка': 'http://forismatic.com/ru/20376e8629/'},
{'Цитата': 'Вместо того, чтобы посвятить себя миру, человек растрачивает себя на дела. ', 'Автор': 'Карлос Кастанеда', 'Ссылка': 'http://forismatic.com/ru/9208878436/'},
{'Цитата': 'Ничего не принимайте близко к сердцу. Немногое на свете долго бывает важным.', 'Автор': 'Эрих Мария Ремарк', 'Ссылка': 'http://forismatic.com/ru/ee22b4e505/'}
]

for d in dict_list:
    for k in ['Автор', 'Цитата', 'Ссылка']:
        print(f'{k}: {d[k]}')
    print()

Результат:
Автор: Клод Адриан Гельвеций
Цитата: Каждый миг наслаждения — это дар богов.
Ссылка: http://forismatic.com/ru/20376e8629/

Автор: Карлос Кастанеда
Цитата: Вместо того, чтобы посвятить себя миру, человек растрачивает себя на дела.
Ссылка: http://forismatic.com/ru/9208878436/

Автор: Эрих Мария Ремарк
Цитата: Ничего не принимайте близко к сердцу. Немногое на свете долго бывает важным.
Ссылка: http://forismatic.com/ru/ee22b4e505/

A: Вы можете заполнять словарь изначально в необходимой последовательности.
Также, не думаю что вам правда нужна определенная последовательность, т.к вы можете получать значения из словаря независимо от последовательностей.

A: Если хочется хранить отсортированный словарь, то используйте OrderedDict из collections. Вот как пример сортировка по алфавиту
from collections import OrderedDict

dict_list = [
{'Цитата': 'Каждый миг наслаждения — это дар богов. ', 'Автор': 'Клод Адриан Гельвеций', 'Ссылка': 'http://forismatic.com/ru/20376e8629/'},
{'Цитата': 'Вместо того, чтобы посвятить себя миру, человек растрачивает себя на дела. ', 'Автор': 'Карлос Кастанеда', 'Ссылка': 'http://forismatic.com/ru/9208878436/'},
{'Цитата': 'Ничего не принимайте близко к сердцу. Немногое на свете долго бывает важным.', 'Автор': 'Эрих Мария Ремарк', 'Ссылка': 'http://forismatic.com/ru/ee22b4e505/'}
]

for i in range(len(dict_list)):
    dict_list[i] = OrderedDict(sorted(dict_list[i].items(), key=lambda a: a[0]))

for i in dict_list:
    print(i, end="\n")

Вывод:
OrderedDict([('Автор', 'Клод Адриан Гельвеций'), ('Ссылка', 'http://forismatic.com/ru/20376e8629/'), ('Цитата', 'Каждый миг наслаждения — это дар богов. ')])
OrderedDict([('Автор', 'Карлос Кастанеда'), ('Ссылка', 'http://forismatic.com/ru/9208878436/'), ('Цитата', 'Вместо того, чтобы посвятить себя миру, человек растрачивает себя на дела. ')])
OrderedDict([('Автор', 'Эрих Мария Ремарк'), ('Ссылка', 'http://forismatic.com/ru/ee22b4e505/'), ('Цитата', 'Ничего не принимайте близко к сердцу. Немногое на свете долго бывает важным.')])


text:
Q: Using WPDB class I want to use the wpdb class on my external page not associated with wordpress.
I tried to include the following on the php file:
// include wordpress functions
include( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
require_wp_db();
global $wpdb;

Now I made a query using $wpdb->query
$product_info_query = $wpdb->query("select p.products_id, p.products_type, p.img_display, p.products_sku, pd.products_name, pd.products_description, p.products_model, p.products_quantity, p.products_image, pd.products_url, p.products_price, p.products_tax_class_id, p.products_date_added, p.products_last_modified, p.products_date_available, p.manufacturers_id, gp.likes from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_GLOBAL_PRODUCTS . " gp where p.products_status = '1' and p.products_id = '" . (int)$_GET['products_id'] . "' and pd.products_id = p.products_id and gp.products_id = p.products_id and pd.language_id = '" . (int)$languages_id . "'");
$product_info = mysql_fetch_array($product_info_query);

However, its not working. It returned a warning:
Warning: mysql_fetch_array() expects parameter 1 to be resource

What seems to be the problem? How to fix this and probably use wpdb class correctly on running queries outside wordpress?

A: You can't mix wpdb with mysql_fetch_array. They are not compatible. You need to use wpdb methods, plus PHP functions like while, foreach, and for. wpdb does not return the references that PHP's mysql functions use. It returns an object, and array, or sometimes a string.
In your case, though, the database part is done. You just want to foreach over the result set.
foreach ($products as $op) {
    // do stuff
}


text:
Q: How to Decrease The Database Table Row Integer value I want to decrease the value of stocks.  I am using a jbutton in java and using this code, but the problem is that it decreasing the all integer i want to decrease one stocks value.
If you have any questions please ask.
 try{
        Class.forName(Driver);
        Connection con = DriverManager.getConnection(url,user,pass);
        String sql = "UPDATE goods SET stocks = stocks - '"+quantPOS.getText()+"'";

        PreparedStatement pst = con.prepareStatement(sql);
        pst.executeUpdate();
         JOptionPane.showMessageDialog(this, "Updated Succesfully");
    }catch(Exception e){
        JOptionPane.showMessageDialog(this, e.getMessage());
    }

A: Okay. Your problem is that it decreasing the all integer but  you want to decrease one stocks value. This is because of your SQL statement.
UPDATE goods SET stocks = stocks - '"+quantPOS.getText()+"'

What above query does is that it will update the stocks value of all rows of Goods table. So, if you want to update only one stock value, you must use WHERE clause and specify that particular row id (using any unique column e.g. primary key column)
UPDATE goods SET stocks = stocks - '"+quantPOS.getText()+"' WHERE row_id=123

A: You need to add a where clause to the SQL statement.
You will also need to convert the text in the text field to a number.
Also, use a PreparedStatement for your SQL. It will make writing the statement easier and is less likely to make SQL syntax mistakes:
int value = stocks - Integer.parseInt( quantPos.getText() );

String sql = "UPDATE Goods SET Stocks = ? WHERE ID = ?";

PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, value );
stmt.setString( 2, theIdHere );
stmt.executeUpdate();

Also, follow conventions when naming tables an columns in a database. These value should start with an upper case character.
    stmt.close();

A: Make a select button in that row and after selecting take all the values of that row in update panel in the particular textboxes and then update it using the update query sql.


text:
Q: What can I do if my USB flash drive / SD-card is write-protected or read-only? When I plug in my USB flash drive (or SD card), it shows up on my computer as write-protected or read-only. I am unable to transfer data to it, nor can I modify or delete any files already stored on it. I also cannot repartition or reformat the drive using GParted or other tools, including Windows Disk Management, DiskPart. The drive does not have a write-protect switch.
Why did this happen and what can I do about it? Is there a way to remove the write protection?

This question comes up often and the answers are usually the same. This post is meant to provide a definitive, canonical answer for this problem.
Feel free to edit the answer to add additional details.
This question was copied from this superuser.com question by bwDraco, and then edited.
(To moderators) This question is thus intended to be a master dupe target. (Jargon of stackexchange.com, meaning to mark other similar questions as a duplicate of this.)

Answer
(TL;DR: Sorry for giving the answer here; a moderator deleted my anwser. I've fixed it following his/her request, but probably it's been missed.)
See the original question and answer in superuser.com.  In short, probably all you can do is retrieve the data and throw away the device.


text:
Q: Mixed order in DidSelectRowAt method I dont understand why my debugger first goes do the bottom of the method, I mean, it ignores Api calls at first, goes to the bottom of the methos, and then goes back to the Api calls.

Like this:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "SecondVC") as? SecondVC

//Method for AlamoFire API call 1 here
APIManager.shared.getDetailsCity(city: indexPath.row){ (details) in
//code for the method
}

//Method2 for AlamoFire API call 2 here
APIManager.shared.getDetailsCountry(country: indexPath.row){ (details) in
//code for the method2
}
self.navigationController?.pushViewController(secondVC!, animated: true)
}

code for the method and code for the method2 is produced after all other things.

Also, sometimes code for the method2 is read before code for the method

A: As Stefan pointed out, the APIManager calls seem to execute the closure asynchronously.
You could do the following:

*

*Create an integer property index in the second view controller

*when the user taps on a cell, instantiate that view controller and set vc.index = indexPath.row before pushing it

In the second view controller, in viewDidLoad:

*

*start a progress indicator

*give the user some info, like "loading data - please wait"

*call the API manager with the index value

In the closures, update the UI (make sure this code runs in the main thread)
After all closures have returned (maybe use a dispatch group), hide the progress indicator


text:
Q: jQuery radio button group check I use this piece of jQuery code to check if a group of radio buttons is checked.
jQuery code :
jQuery(window).load(function() {

    $("#offerteaanvragen").submit(function(event) {
        var className = $('.stap2titel').attr('class');
        if (className == "stap2titel") {

        if (!$("input[name='color']").is(':checked')) {
           event.preventDefault();
           var para = document.createTextNode(" Selecteer een kleur");
           var element = document.getElementById("error_kleur");
           element.appendChild(para);
         }
 });

The top side of the code is to check if I am on the correct page by checking the (h5) title, and if I am in the correct form. Then I check my group of input buttons with the same name. If 1 of them is checked it should skip the code, But it does always say it is not checked.
Here is the how the input looks like:
<input id="color2" class="input_hidden" type="radio" value="color2" name="color">

These are generated by code because the amount of inputs can change on the available colors.
How do I fix this?
PS: This is code that is for IE only.
EDIT: I think it is something with the IF statement. It will always return True. Should I delete the ! in the IF statement and then paste the code in the else statement ? This would cause the if statement to execute the code in the else if checkbox selected == false.


text:
Q: jQuery adding and removing attributes I have a project where we have multiple modals on same page. So the idea is to get the id from the button that is clicked and append that id to the modal. Example is:
Here is my code in plunker: bootstrap modal
 <button class="btn btn-readmore" data-toggle="modal" href="modals/serv-cutting.html" data-target="#vividCutting">read more</button>

 <button class="btn btn-readmore" data-toggle="modal" href="modals/serv-color.html" data-target="#vividColor">read more</button>

then add that id attribute to:

So I have quite a few modals and i came up with this jQuery as if I dont remove the id first, then all the buttons that trigger modals just keep opening the same modal:
$('button.btn-readmore').click(function() {
    var newId = $(this).attr('data-target').slice(1);
    console.log(newId);
    if($('.modal').prop('id', newId)){
        $(this).removeProp('id', newId);
    } else {
        $('.modal').prop('id', newId)
    }
});

I think Im close but need a little advice.

A: Based on your comments on my previous answer and the updates to your question, it looks like you want to re-use the same modal and have it loaded with remote content depending on which button is clicked.
HTML:
<button class="btn btn-readmore" data-toggle="modal" href="modals/serv-color.html" data-target="#modal1">read more 1</button>
<button class="btn btn-readmore" data-toggle="modal" href="modals/serv-cutting.html" data-target="#modal1">read more 2</button>

JavaScript that destroys the modal after it his hidden in order to allow the remote content to be loaded every time it is re-created, courtesy of Twitter bootstrap remote modal shows same content everytime
$('body').on('hidden.bs.modal', '.modal', function () {
    $(this).removeData('bs.modal');
});


text:
Q: Is DynamoDB optimistic locking with one version attribute for each field in an item a valid design pattern? It's common to implement optimistic concurrency control in DynamoDB by giving each item in the database a top-level "version" attribute and only allowing an update of an item to succeed if the current version matches the expected version (see https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.OptimisticLocking.html).
Suppose I want more fine-grained control, so that if user A updates fields 1, 2, and 3 and user B simultaneously updates field 4, 5, and 6, neither user has to retry. Are there known implementations or discussions of DynamoDB optimistic locking in which each attribute has its own version field?

A: What you're trying to do is in principle possible. Limitations:

*

*You will have to write the necessary queries yourself, and will not enjoy support via your SDK.

*It becomes a lot more difficult to track per-field dependencies. You might only want to perform a field update if certain other fields are unmodified.
Examples of potential read-write conflicts
Your example potentially runs into this second limitation. Consider that the two processes/users want to apply a transaction that has a read-set and a write-set. The read-set describes which fields were accessed to determine the output of the transaction, the write-set contains the actual updates.
In your example, if the two processes have an empty read-set, then they do not conflict:

process
read
write

A
{}
{1 → A1, 2 → A2, 3 → A3}

B
{}
{4 → B4, 5 → B5, 6 → B6}

They can be applied in any order and will not conflict. The resulting update will be {1 → A1, 2 → A2, 3 → A3, 4 → B4, 5 → B5, 6 → B6}.
If one process has read elements of the other process's write-set, then they may or may not conflict depending on order:

process
read
write

A
{}
{1 → A1, 2 → A2, 3 → A3}

B
{1}
{4 → B4, 5 → B5, 6 → B6}

*

*If A runs first, then B will fail and the update is {1 → A1, 2 → A2, 3 → A3}.

*If B runs first, then A can run afterwards and the entire update is as in the previous scenario.
Depending on the consistency mode used for the reads (eventual consistency or strong consistency), the transactions might fail to apply even if they don't conflict, because the read-set references stale data.
If both processes have read fields that the other process writes, then either transaction can be applied and the other will fail. For example:

process
read
write

A
{4}
{1 → A1, 2 → A2, 3 → A3}

B
{1}
{4 → B4, 5 → B5, 6 → B6}

Checking field version vs checking old value
On an implementation level, you probably wouldn't add a version attribute for scalar fields. I.e. you would probably not create a document like this:
{
  "field1": "some value",
  "field1version": 1
}

Instead, you would typically assert that the read fields still contain the value that you read. Thus, your update queries would look like the following (showing the last example for process B, in an SQL-like syntax):
UPDATE collection
SET field4 = 'B4', field5 = 'B5', field6 = 'B6'
WHERE field1 = 'old value for field 1'

But a version number is a more generic approach that is safer. For example, it may be relevant to your application if a field was touched at all, even if it later contains the original value again. For example, consider the following sequence of reads R(value, version) and writes W(value, version):
A: R(1, v1)                 R(1, v3)
B:         W(2, v2) W(1, v3)
   ----------------------------------> time

Here, process A reads value 1 from a field. Another process overwrites that field with 2, then again with 1. A later read by process A returns 1 again. For applications that only care about the current value, this approach is sufficient. Other applications may care about how often that field was written, and would not consider those two reads to be equivalent.
Dependency tracking vs actual locks
That said: while thinking about reducing conflicts can be great, sometimes such fine-grained dependency tracking just isn't worth it. This depends very much on your specific data model and on your scale.
Optimistic locking is great because it can give you high throughput – but only if you expect few conflicts, and failures to apply an update can be handled gracefully (such as by re-starting an unit of work).
If you expect a lot of conflicts then using a database that supports actual locks might be preferable (e.g. an RDBMS where you can BEGIN TRANSACTION).


text:
Q: mysql increase value when button is clicked I can't seem to find a way to increase a value stored in a mysql database when a button is clicked.
The button in html (not including styling with css):
Press Me

I've my mysql database all set up and working and I just can't find a way to increase a value in the database everytime this button/link is clicked. You should be able to click this button multiple times without leaving the page.
I've tried using PHP but it will only send the information once the page is loaded which means the button hasn't been clicked, and also I haven't found a way to increase the value on every click.. By the way, this doesn't have to be done with PHP.
<?php
// Connection to database
  $connection=mysqli_connect("localhost","root","","test");
// Check connection
  if (mysqli_connect_errno())
    {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

// Increasing the current value with 1
  mysqli_query($connection,"UPDATE articles SET amount = (amount + 1)
      WHERE id='1'");

  mysqli_close($connection);

  echo "PHP RAN successfully";     ?>

*Also, sorry for my bad English, i'm an Swedish dude :)

A: Include jquery in your page as JS library.
Press Me

server_code_increment.php
<?php
// Connection to database
  $connection=mysqli_connect("localhost","root","","test");
// Check connection
  if (mysqli_connect_errno())
    {
    echo 'NOT_OK';
    //echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

// Increasing the current value with 1
  mysqli_query($connection,"UPDATE articles SET amount = (amount + 1)
      WHERE id='1'");

  mysqli_close($connection);

  echo 'OK';   ?>

Modify as per your need

A: you don't HAVE to use ajax though its probably the prettier way.  this will work with a basic ahref reload page
<a class="button" href="<?php echo $_SERVER['PHP_SELF'];?>&a=increase">Press Me

<?php
if ($_GET['a']=="increase") {
// Connection to database
  $connection=mysqli_connect("localhost","root","","test");
// Check connection
  if (mysqli_connect_errno())
    {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

// Increasing the current value with 1
  mysqli_query($connection,"UPDATE articles SET amount = (amount + 1)
      WHERE id='1'");

  mysqli_close($connection);

  echo "PHP RAN successfully";
}

//echo out the DB value here
echo $db->amount;
?>

A:  Press me

id (its only avariable)
<? php
 $no=$_get['id'];
?>

Select your last inserted amount from db
 eg: $lastamount=mysql_query("select query for last insertdata");
 write
 $no=$lastamount+$no;
 mysqli_query($connection,"UPDATE articles SET amount = $no
  WHERE id='1'");


text:
Q: Problems setting up tomcat with intellij I am trying to figure out how write a simple java program in intellij that uses Apache Tomcat (I'm using Tomcat version 9 in this case). I have been trying to follow this tutorial: https://www.youtube.com/watch?v=ThBw3WBTw9Q&t=249s
I have followed the steps and my program looks like this:

However when I try to run the program and I try to access http://localhost:8080/HelloWebApp_war_exploded/api/hello-world I get a 404 error. I can't figure out the source of this error, what could possibly be causing this problem?


text:
Q: How do I dynamically reference a Record Type ID in a Custom Setting? I am building an application that I hope to sell on the AppExchange. On that application, I am building three custom "new record" buttons on a related list (parent and child objects are both custom objects) -- one for each Record Type on the child object.
I have successfully used URL custom buttons to pass Record Type ID via a URL parameter; however, the URL parameter is the Record Type ID (as opposed to Name), which will change with each organization. Since this will be an AppExchange application, it must be dynamic.
I have decided to create a Custom Setting that holds the Record Type IDs for each Record Type; however, I do not know how to dynamically determine the Record Type IDs within the Custom Setting. I do not believe I can use SOQL or other Apex code to retrieve these dynamically, but I could be wrong.
So my two questions are:
1) What is the best method for determining Record Type IDs dynamically?
2) How do I update a Custom Setting with that ID?
Thanks so much!

A: Check out this Apex Interface: InstallHandler Interface
Should allow you to query for the RecordType Id and insert it into the custom setting when the user installs the managed package.


text:
Q: Using two diodes as a simple power supply backup switch I saw this module as a "battery emergency switch module" for $2 on aliexpress:

which is just a relay energized by the external power supply, and when the external supply is gone, connects the battery to output.
despite a relay could switch higher currents than a same priced diode, it is slow and the chances that the circuit resets are high. also, the relay may stay energized with lower voltages than the nominal supply, while the circuit has turned off because of low voltage.
what could be the problems with a simple circuit like this ?

simulate this circuit – Schematic created using CircuitLab
it is cheaper (for some applications at least) and much faster than the relay. it doesn't have the problem of low voltage mentioned above.

A: The two diode arrangement is used a lot, not only for battery backup but also for other similar purposes (e.g. redundant power supply units).
Simple diodes have a voltage drop that may or may not be acceptable in your use case. The mitigation measures for the voltage drop include:

*

*Using higher supply voltage (voltage drop of ~1V is bad in 5V circuit and becomes way less of a concern in 24V circuit)

*Using Shottky diodes or germanium diodes (they have less voltage drop, like 0.2-0.5V vs 0.7-1.2v for silicon ones)

*Using MOSFET-based "ideal diode" circuits that are more complex and expensive but can go as low as 0.02V drop.

A: I fully understand your concerns that you have about resets etc that may result from slow operation of the relay.
A simple suggestion would be an improvement to the diode solution.
A single pole changeover relay could short out 1 or other diode depending whether the power supply or battery was providing the load. It'll introduce a small change in voltage but overcome the lost power.

A: There are two problems with the two-diode circuit. The first is the voltage drop over the diodes. With standard silicon diodes, there is a typical 0.7 volt drop. So if you use 5 volt power, you'd better be sure your device will function properly on 4.3 volts. You can also use Shockley diodes to reduce the drop.
The second problem, or better, disadvantage is that the 2-diode circuit has no priority. It will pass power from whichever source is higher voltage. If you have a 6 volt battery but a 5 volt external power source, your battery will continue to drain until it drops to less than 5 volts. The relay module has priority. While the external power is applied, the battery is disconnected.


text:
Q: debugging with ansible: How to get stderr and stdout from failing commands to be printed respecting newlines so as to be human readable? If I run a simple ansible playbook, I often get difficult-to-read output from failing tasks, like that below.  Big problems:

*

*the linebreaks within the stdout are printed as \n, not an actual linebreak.  This makes things like python tracebacks very obnoxious to read.

*stdout, stderr, cmd... the json blob being output contains lots of useful things, but since they are all run together on the same line it is
very difficult for a human to parse.
How can I get ansible to print its output in a format that I can read easily, so I can debug?
Here is the yucky output:
$ ansible-playbook playbooks/backUpWebsite.yml

PLAY [localhost]
***************************************************************

TASK [command]
*****************************************************************
fatal: [localhost]: FAILED! => {"changed": true, "cmd": "python -c 'ksjfasdlkjf'", "delta": "0:00:00.037459", "end": "2017-10-03 19:58:50.525257", "failed": true, "rc": 1, "start": "2017-10-03 19:58:50.487798", "stderr": "Traceback (most recent call last):\n  File \"<string>\", line 1, in <module>\nNameError: name 'ksjfasdlkjf' is not defined", "stdout": "", "stdout_lines": [], "warnings": []}
        to retry, use: --limit @<snip>playbooks/backUpWebsite.retry

PLAY RECAP
*********************************************************************
localhost                  : ok=0    changed=0    unreachable=0 failed=1

Here is the script that generated it:
---
- hosts: localhost
  gather_facts: False
  tasks:
      #wrong on purpose!
    - shell: "python -c 'ksjfasdlkjf'"
      register: unobtainable

A: To get ansible to respect linebreaks in output so that you can read the stdout of your failing task, change the stdout_callback to minimal.
In your ansible.cfg, change the stdout_callback option:
stdout_callback=minimal

the 'minimal' output is a bit terse, but it prints output respecting linebreaks so that you can see what is happening:
 $ ansible-playbook playbooks/backUpWebsite.yml
 localhost | FAILED | rc=1 >>
 Traceback (most recent call last):
   File "<string>", line 1, in <module>
 NameError: name 'ksjfasdlkjf' is not defined

         to retry, use: --limit @<snip>/playbooks/backUpWebsite.retry

Other things that I hear can work

*

*You could write your own callback handler for stdout.  People have done this and it seems straightforward to do, but I've never tried it.

Things I tried that don't work:
Three vs.  Use "ansible-playbook  -vvv".  You get a tremendous pile of output, which does include the json nicely linebroken, but the newlines within the stdout output are not printed, so stdout/stderr are still hard to read:
$ ansible-playbook playbooks/backUpWebsite.yml -vvv
Using <snip>/ansible.cfg as config file

PLAYBOOK: backUpWebsite.yml ****************************************************
1 plays in playbooks/backUpWebsite.yml

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
task path: <snip>/playbooks/backUpWebsite.yml:6
Using module file <snip>/ansible/lib/ansible/modules/core/commands/command.py
<127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: <snip>
<127.0.0.1> EXEC /bin/sh -c 'echo ~ && sleep 0'
<127.0.0.1> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo <snip>/.ansible/tmp/ansible-tmp-1507083519.4247632-54588405727205 `" && echo ansible-tmp-1507083519.4247632-54588405727205="` echo <snip>/.ansible/tmp/ansible-tmp-1507083519.4247632-54588405727205 `" ) && sleep 0'
<127.0.0.1> PUT /tmp/tmpumtlourx TO <snip>/.ansible/tmp/ansible-tmp-1507083519.4247632-54588405727205/command.py
<127.0.0.1> EXEC /bin/sh -c 'chmod u+x <snip>/.ansible/tmp/ansible-tmp-1507083519.4247632-54588405727205/ <snip>/.ansible/tmp/ansible-tmp-1507083519.4247632-54588405727205/command.py && sleep 0'
<127.0.0.1> EXEC /bin/sh -c '<snip>/anaconda3/bin/python <snip>/.ansible/tmp/ansible-tmp-1507083519.4247632-54588405727205/command.py; rm -rf "<snip>/.ansible/tmp/ansible-tmp-1507083519.4247632-54588405727205/" > /dev/null 2>&1 && sleep 0'
fatal: [localhost]: FAILED! => {
    "changed": true,
    "cmd": "python -c 'ksjfasdlkjf'",
    "delta": "0:00:00.037657",
    "end": "2017-10-03 20:18:39.843933",
    "failed": true,
    "invocation": {
        "module_args": {
            "_raw_params": "python -c 'ksjfasdlkjf'",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 1,
    "start": "2017-10-03 20:18:39.806276",
    "stderr": "Traceback (most recent call last):\n  File \"<string>\", line 1, in <module>\nNameError: name 'ksjfasdlkjf' is not defined",
    "stdout": "",
    "stdout_lines": [],
    "warnings": []
}
        to retry, use: --limit @<snip>/sys/ansible_readynet/playbooks/backUpWebsite.retry

PLAY RECAP *********************************************************************
localhost                  : ok=0    changed=0    unreachable=0    failed=1

Credit
I posted this issue against ansible on github in hope of persuading people that the ansible defaults are very unhelpful.  jhawkesworth helpfully introduced me to the 'minimal' stdout callback.
I have since found this page in the ansible documentation that mentions this plugin in a very non-prominent way.
IMHO, this secret of getting readable error output from ansible is entirely too well hidden from new users, and I have personally witnessed this sour several people I know on the use of ansible in general.


text:
Q: ngRoute: URL changes, but the view stays the same I don't really know what I'm doing wrong, because the URL changes, but the view stays the same.
app.js:
var app = angular.module('app', [
'ngRoute',
'ui.bootstrap',
'ui.bootstrap-slider',
'angularFileUpload',
'ngTouch',
'ngAnimate',
'r'
]);

app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
    .when('/data', {
        templateUrl: 'html/data/data.html',
        controller: 'RController'
    })
    .otherwise({
        templateUrl: 'html/start/start.html'
    });
}]);

index.jade:
doctype html
html(ng-app='app')
meta(charset='utf-8')
head
    title i-CoDa
    link(rel='shortcut icon', href='./img/icon.ico')
    link(rel="stylesheet", href="./css/main.css")
body(ng-controller='RController')
    div#navigation.navbar.navbar-default.navbar-fixed-top(role='navigation')
        div.container
            div.navbar-header
                button.navbar-toggle.navbar-collapse(aria-expanded='false')
                    span.sr-only Toggle navigation
                    span.icon-bar
                    span.icon-bar
                    span.icon-bar
                a.navbar-brand(href='./index.html')
                    img#logo(src="./img/logo.svg", alt="i-CoDa Logo")
            div.collapse.navbar-collapse.navbar-right
                ng-include(src="'./html/navbar/navbar.html'")
    div#main
        div(ng-view)
    footer.container.col-lg-12

    script(src="./js/dependencies.js")
    script(src="./js/bundle.js")

navbar.jade:
ul.nav.navbar-nav
 li.active
    a(href='#/start.html') Start Page
 li.active
    a(href='#/data.html') Data

The structure of my project looks like this:
|
|_server.R
|_www
  |___html
  |___css
  |___js
  |___index.html

I also looked at similar posts and tried everything, but it didn't work.
Could someone give me a hint?

A: You are doing it in the wrong way. The RController that you are set it on the body is presenting for all of the content inside the body regardless whatever router you will make, while it should be set for the /data route only.
Removing it from the body, or, just set it to another controller such as MasterController (you also have to create it).
Then you create to a route /start (which should have controller + view similars to /data route that you currently have)  for the default option, and you define the otherwise option like this

.otherwise({ redirectTo: '/start' });


text:
Q: connecting windows store application application to localhost I'm trying to connect my windows store application to mysql database hosted on localhost. Data Connection is successful but I can't resolve Mysqlconnection function. I tried to add mysql.data reference but it didn't appear in the options. I tried adding MySql.Data.MySqlClient namespace but it didn't resolve. I have installed mysql visual studio plugin 1.1.1.

A: You'd better use WCF or Web Service to connect with your DataBase. And then make your Windows Store App to reference the WCF or Web Service.
Because your app will be published and installed to many clients. The direct connection client and the database is not advisable.
If you just want to test in your local machine. Here are some articles about this:
MySQL for Windows Store apps
How to: Using MySQL Connector/NET with Windows Store Apps


text:
Q: Chrome ignores CSS print settings on portrait I am trying to control the layout of printing of a HTML element depending on portait or landscape.
Here's what I put in CSS settings.
@media print and (orientation: landscape){
    /* Your code for portrait landscape */

    #reactView{
    /*chrome seems only look at this data*/
    height: 7in !important;
    }

@media print and (orientation: portrait){
    /* Your code for portrait landscape */

    #reactView{
    height: 10in !important;
    }
}

The settings work well on IE, Firefox. But on Chrome the the setting for portrait is not working. On portrait I got 7 inch too.
Is it a bug on Chrome? And is there a workaround? Thanks.
I am on Chrome 60, 64 bit.

A: From my tests orientation:landscape works with IE and FF, but not Chrome. However Chrome works with min-width:600px. The way I combined them below works for all three browsers.
@media print {
    all
    @media (orientation:landscape) and (min-width:600px) {
        landscape
    }
}
@media screen {
    all
    @media (min-width:1006px) {
        landscape
    }
}

A: Have you tried setting a page size in your css?
@page {
  size: letter portrait;
}

See https://www.w3.org/TR/css3-page/ and https://www.w3.org/TR/css-gcpm-3/


text:
Q: Angular & Firebase - Possible to create an auth guard that checks if the user is on a login screen? What I'm using

*

*Angular

*Firebase

What I'm trying to achieve

*

*An Auth Guard that performs a router redirect based on conditions

Where I've got to

*

*I have an auth guard on many of the components that if the users has a bookmark (for example...) to url and navigate to it whilst not logged in, they will be pushed back to the login page.

Question

*

*Is it possible to modify my auth guard so that if the user is logged in, but somehow manages to navigate to 'www.mydomain.com/login' that they are redirected to a specified route?

My Route Guard
I've left my commented out code where I've tried out some logic. The issue here is that if I use the commented out code, if the user isn't logged in, it ends up in a loop of redirecting back to the login page that you're already on.

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';

//testing
import { Observable } from 'rxjs/Observable';
import { AngularFireAuth } from 'angularfire2/auth';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/take';
import 'rxjs/add/operator/do';

@Injectable()

export class AuthGuardService implements CanActivate {

  constructor(
    private authService: AuthService,
    private router: Router,
    private auth: AngularFireAuth
  ) { }

  canActivate(): Observable<boolean> {

    return this.auth.authState
      .take(1)
      .map(authState => !!authState)
      .do(auth => !auth ? this.router.navigate(['/login']) : true);

  }

  // canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
  //   return this.checkLoggedIn(state.url);
  // }

  // checkLoggedIn(url: string) {

  //   if (this.authService.isLoggedIn()) {
  //     console.log("yup, i'm logged in!");
  //     return true;
  //   } else {
  //     this.router.navigate(['/login']);
  //     console.log("nop, i'm not logged in!");
  //     return false;
  //   }
  // }

}

Example of auth guard on a route
Ideally, I'd like some logic in my auth guard which means I can do the same below on the login route

    {
        path: 'folders',
        component: FolderListComponent,
        resolve: { folderListData: FolderListResolver },
        canActivate: [AuthGuardService]
    },

UPDATE
Getting a little closer thanks to @Vega. What happens now:

*

*Login page > sign in > redirected to correct page = Great!

*Navigate to any page apart from login whilst not signed in = redirected back to login page = Great!

*Navigate to login screen whilst signed in = Stuck. It now thinks the user isn't logged in = This needs fixing

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    let newUrl = state.url;
    if (newUrl === "/login") {
      if (this.authService.isLoggedIn()) {
        console.log('Login Page / Signed In');
        return false;
      }
      else {
        console.log('Login Page / Not Signed In');
        return true;
      }
    }
    else {
      if (this.authService.isLoggedIn()) {
        console.log('Other Page / Signed In');
        return true
      } else {
        this.router.navigate(['/login']);
        console.log('Other Page / Not Signed In');
        return false;
      }
    }
  }

A: UPDATE:
This may be not the more elegant way, but it works, and is less code:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    let newUrl = state.url;
    if (newUrl === "/login") {
      if (this.authService.loggedIn()) {
        //this.router.navigate([oldUrl]);
        //logged and routing to /login => go back. this probably need to be improved!
        this.location.back();
        return false
      }
      else {
        //not logged => go /login
        return true
      }
    }
   // here is the 'traditional' part of the guard
    else {
      if (this.authService.loggedIn()) {
        return true
      } else {
        this.router.navigate(['/login']);
        return false;
      }
    }
  }

Old answer:
In main component:
 ngOnInit() {

        if (isPlatformBrowser) {
            this.routerSubscription = this.router.events
                .filter(event => event instanceof NavigationEnd)
                .subscribe(() => {
                    let url = window.location.toString();
                    if (url.indexOf("/login") && loggedIn)
                      //do whatever is necessary
                    }
                    else{
                       this.router.navigate(['login']);
               }
                });
        }
    }

    ngOnDestroy() {
        this.routerSubscription.unsubscribe();
    }

Or something like the following:
{ path: 'login', component: LoginComponent, canActivate: [AnOtherGuard] },

and
in AnOtherGuard
 ....
 canActivate() {
    if (this.authService.loggedIn()) {
      this.location.back(); //or whatever is necessary
      return false;
    }
    else {
      return true;
    }
  }


text:
Q: Combine xml tags into one Is there an easy way to convert xml file tags into one line? my xml file ($xml = simplexml_load_file('http://localhost/locations.xml');)  contains:
<markers>
    <marker>
    <name>Chipotle Minneapolis</name>
    <lat>44.947464</lat>
    <lng>-93.320826</lng>
    <category>Restaurant</category>
    <address>3040 Excelsior Blvd</address>
    <address2></address2>
    <city>Minneapolis</city>
    <state>MN</state>
    <postal>55416</postal>
    <country>US</country>
    <phone>612-922-6662</phone>
    <email>info@chipotle.com</email>
    <web>http://www.chipotle.com</web>
    <hours1>Mon-Sun 11am-10pm</hours1>
    <hours2></hours2>
    <hours3></hours3>
    <featured></featured>
  </marker>
</markers>

convert above code to this format:
<markers><marker name="Chipotle Minneapolis" lat="44.947464" lng="-93.320826" category="Restaurant" address="3040 Excelsior Blvd" address2="" city="Minneapolis" state="MN" postal="55416" country="US" phone="612-922-6662" email="info@chipotle.com" web="http://www.chipotle.com" hours1="Mon-Sun 11am-10pm" hours2="" hours3="" featured="" features="" /></markers>

Thanks

A: Easy job for SimpleXML:
$string = '<markers>...</markers>';

$xml = new SimpleXMLElement($string);

foreach ($xml->marker as $m) {
    foreach ($m->children() as $c) {
        $m->addAttribute($c->getName(), $c);
        $trash[] = $c;
    }
    foreach ($trash as $t) unset($t[0]);
}

echo $xml->asXML();

It will work even if you  have multiple marker elements. Of course, if
you have  only one  then the  outer loop  is not  needed. Note  that the
elements are removed (by unset()) in  a separate iteration not to mess
the main one.

A: Put your xml code in $string variable and use this code:
$xml = new SimpleXMLElement('<markers/>');

$marker = $xml->addChild('marker');

$string = "<markers> ... </markers>";

$string = simplexml_load_string( $string );

foreach( $string->marker->children() as $name => $value )
    $marker->addAttribute( $value->getName(), $value );

echo $xml->asXML();