text:
Q: How could i use an iMac as secondary monitor for a Windows 7 laptop Recently (less than one year ago) i bought an iMac 21,5".
Now i would like to use it as secondary monitor for my laptop. (My laptop runs Windows 7).
Is it possible? (I found conflicting opinions on the web, even on the Apple forum).
What type of cable do I need?
(I will appreciate also a link to the product on some online store: amazon, ebay etc.)
Thank you in advance.
UPDATE:
I tried air display... i'm not satisfied at all...
typical scenario: browser window on the main Windows laptop, dev tools/firebug on the secondary iMac screen.
The mouse goes fast between the 2 screens (GOOD), but when i changed the selected tab nothing happens. I had to drag the dev tools window to the main screen to get an update of the selected tab.
My test is ended here.
I'm still waiting for other answers.
I will prefer an answer that suggest me what kind of cable i've to buy, and where i can find it on the web.

A: In addition to the above, other software solutions are Jinx, who offers a product called ScreenRecycler.  Couple this with a VNC client like TightVNC or JollysFastVNC (from Jinx), you pay once for the main computer, and can use any number (one at a time) of other computers as a remote display.  This software is currently in Beta, and I found that after 5-10 minutes of use, the remote display slowed and became very choppy.  I don't know if this was because my main computer is running OS X 10.11 Beta, but I suspect it is just issues with the ScreenRecycler product.  Also, the VNC Client does not detect the screen resolution of the host (remote) computer, and so does not allow you to take full screen unless it happens to be one of the predefined resolutions.
I found Air Display to work very well with acceptable performance, using 2 laptops (1 Windows, 1 Mac) over WiFi 802.11n.  Mac was primary, Windows was remote monitor.  However, you have to pay for each machine (1 at a time) that you use as a remote monitor - opposite of how ScreenRecycler is licensed.  Air Display also used the host computer's screen resolution nicely, but at times motion became choppy.
Finally, there is MaxiVista - this one is one-way, only uses Mac, Windows or Linux as a remote monitor for Windows.  I have not tested it, as what I wanted to do was use my Mac and extend to external monitors wirelessly, but the hardware is too old to support AirPlay to an Apple TV.  MaxiVista runs from $49.95 to $129.95, which I find to be way too expensive, as the others are around $20.  For the price of MaxiVista, you may as well just buy a physical monitor and skip the network bandwidth utilization and lagginess.

A: Incase anyone is interested, this is a bit late but it could be useful for anyone who searched and finds this page.
I had a 27" 2010 iMac and a pc with a DP (DisplayPort) connection so I just purchased a mDP (Mini DisplayPort) to DP cable from PBTech ($11.50 NZD). I don't know what connections you have on your laptop but all adapters I could find worked from mDP to VGA and not the other way around.
VGA carry analog signals which in terms of quality are one of the worst cables when connecting to an LED or similar screen. It's also probably why there are very little/any VGA to mDP adapters as they would be expensive  and not too many people would purchase them. All sources I searched stated that it was either very difficult or impossible to go from an analog VGA to a digital mDP.
I did find something that should work for DVI but it is a bit pricey. You would need a Dual Link DVI to DP ($150 used - none selling new) and a DP to mDP ($7.53).
According to this Source VGA to DVI is possible but the cables required "are harder to locate and often cost upwards for $100" plus you would still the above DVI to mDP setup
tl:dr?
DP connection:

*

*Upwards of $8 to get a DP to mDP cable
DVI connection:

*

*~$158 to get a DVI -> DP and a DP -> mDP
VGA connection:

*

*If you can find a cable/adapter expect to add on at least $100 on top of what you would pay for a DVI connection

Hope it helps and doesn't empty out your wallet.

A: Thunderbolt-equipped iMacs prior to iMac (Retina 5K, 27-inch, Late 2014) (see this document), like your iMac (Mid 2011), support Target Display mode:

Target Display Mode lets you use your iMac as the external display for
  another, "primary" computer.

Thunderbolt-only solution
NOTE: This won't work for iMac (Retina 5K, 27-inch, Late 2014) and later iMac models as they don't support Target Display Mode.
If you happen to own a laptop with a Thunderbolt port follow these simple steps to extend your display (Thunderbolt to Thunderbolt cable required) (from KB PH4469):

*

*Connect the Thunderbolt cable to the Thunderbolt ports on each computer.

*Make sure the iMac and the primary computer are turned on and awake.

*Press ⌘F2 on the keyboard of the iMac.

(As a side note: Older iMacs with Mini DisplayPort also support Target Display Mode. The steps to configure and enable Target Display mode are very similar.).
A comment on DVI to Thunderbolt adaptors
You can't use Mini DisplayPort to DVI or VGA adaptors:

to connect a computer with a DVI/VGA port to a Thunderbolt display (from this thread):

I can confirm that Mini DisplayPort to DVI converter works ONLY from a
  Mini DisplayPort computer port to a DVI display. The reverse direction
  is not supported by those converters,

There is some hope, though, as the post goes on to say:

but there are other much more
  expensive ones that will convert DVI computer ports to Mini
  DisplayPort display.

The poster is probably refering to a product mentioned earlier in the thread: the Kanex C247D Single-Link DVI to Mini DisplayPort Converter, advertised like this:

Connect a (...) LED Cinema Display to your DVI-equipped
  MacBook Pro, Mac Mini, or PC with this (...) Kanex solution.

However, opinions diverge on whether it will work with a Thunderbolt display at all:

*

*
I am sure that Kanex don't do anything that will help you no matter
  how expensive it may be.

*
As far as I am aware, and I have done a lot of reading about this, you
  can connect an older display to the new Thunderbolt port of a new MAC
  but you CANNOT connect the Thunderbolt display to anything other than
  a MAC with a Thunderbolt port.  The Kanex thing works from a
  Thunderbolt port into an older display, DVI or whatever but you cannot
  convert MAC DVI into Thunderbolt......I think

I've noticed that the LED Cinema Display is listed as a Mini DisplayPort display (from http://support.apple.com/kb/SP502):

so the adaptor may indeed only work with Mini DisplayPort displays, not with Thunderbolt displays, and as far as I can tell, your iMac will act like a Thunderbolt display.
It's up to you to try it, although $129.90 (as of this writing) is a steep price to pay for the Kanex adaptor just to test it.
Software-based solution
If the solutions described above aren't feasible or cost-effective, you can use several software solutions. One is Air Display:

Use your iPad, iPhone, Android, Mac or Windows PC as a second (or
  third) monitor with no messy cables or wires

There is a free trial version here.
Note: Windows 7 Starter edition is not supported.

A: I tried various options (wasted my money on the Avatron Air Display of the accepted response, which doesn't support Windows 10, and no longer supports Windows clients with AirDisplay2 -the latest version supported in Windows- with the current AirDisplay3 currently supported in Macs; AirDisplay can now be considered a Mac-only solution, and pricey).
I found that spacedesk.net does a nice job using the HTML5 client in Mac, or an Android VM in your Mac as a client (probably better performance, haven't tried it yet).

A: Late to the party but I guess this guy's video deserves a spot in the solution here.
Use a second laptop as a second screen for your primary laptop (Windows or Mac)
I believe his solution can be used universally without pulling your hair out for future support, also use it for other purposes like streaming or connecting a camera via HDMI
TLDR: buy a capture card:
USB => 1080 30FPS
USB-C => 4k 60FPS

After hooking up your capture card into your primary computer, connect the USB to the secondary computer and use the camera app on the secondary computer.

*

*your primary computer will recognize the capture card as a secondary screen

*your secondary computer camera app will take the source of the video via USB and display it as a second screen


text:
Q: Howto combine DjangoRestFramework routers for different apps I use Django 2.1 and DRF and a planning a quite larger application with many plugged-in apps. I'd like to have ONE /api URL for the DRF as endpoint, but allow each app to have a special model exposed over the REST endpoint, e.g.:
In the main urls.py:
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

urlpatterns = [
    # ...
    path('api/', include(router.urls)),
    # ...
]

and in foo_app/urls.py:
router = routers.DefaultRouter()
router.register(r'foomodel', FooModelViewSet)

Now, /api/foomodel produces a 404 Error. The foo_model/urls.py gets imported (a print statement there is printed at Django start), and all the other foo_model.urlpattern[path...] are recognized and work fine.
How can I define custom api model endpoints for a central api REST endpoint? I didn't find anything in the documentation.
Thanks in advance.

A: I simply achieved this by extending the router registries.
root urls.py
from ad.urls import router as ad_router

main_router = routers.DefaultRouter()
main_router.registry.extend(ad_router.registry)

ad.urls.py
from .api.urls import router as api_router

router = routers.DefaultRouter()
router.registry.extend(api_router.registry)

ad.api.urls.py
router = routers.DefaultRouter()
router.register(r'ad', AdViewSet)

A: In your main urls.py you would do something like this.
(This is for Django 1.8)
urlpatterns += patterns('',
url(r'^api/', include(patterns('',
    url(r'^foo_app/', include('foo_app.urls')),
    url(r'^bar_app/', include('bar_app.urls')),
    url(r'^test_app/', include('test_app.urls')),
))))

this allows you to access all your endpoints this way
localhost:8000/api/foo_app/<foo_app_endpoint>
localhost:8000/api/bar_app/<bar_app_endpoint>
localhost:8000/api/bar_app/<test_app_endpoint>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Every finite connected space is also path-connected? Let  $X$ be a connected space, if $X$ is finite, then $X$ is a path-connected space? If so, how to prove it? If not, how to give a counterexample?
Thanks in advanced.

A: For $x \in X$, let $U_x := \bigcap \{U \subseteq X : U \text{ open}, x\in U\}$ denote the smallest open set containing $x$.

Lemma. Let $x, y \in X$, then there is a sequence $x_0 = x, x_1, \ldots, x_n= y$ such that for each $i$, either $x_i \in U_{x_{i+1}}$ or $x_{i+1} \in U_{x_i}$.

Proof. For $x \in X$, let $A \subseteq X$ denote the set of points $y\in X$ for which such a sequence exists. We have $x \in A$, and for any $y \in A$, we have $U_y \subseteq A$, hence $A$ is open. If $z \not\in A$, then $U_z \subseteq X \setminus A$, hence $A$ is closed. As $X$ is connected, $A=X$.

Lemma 2. If $x \in U_y$, then there is a path connecting $x$ and $y$.

Proof. Define $w \colon [0,1] \to X$ by $w(t) = x$ for $t < 1$ and $w(1) = y$. Let $U \subseteq X$ open, if $y \not\in U$, then $w^{-1}[U] \in \{\emptyset, [0,1)\}$, hence $w^{-1}[U]$ is open, if $y \in U$, then $U_y \subseteq U$, hence $x \in U$, therefore $w^{-1}[U] = [0,1]$. Therefore $w$ is continuous.

Proposition. $X$ is path-connected.

Proof. Let $x,y \in X$, by Lemma 1 there is a sequence $x_0, \ldots, x_n$ with $x_0 = x$, $x_n = y$, and $x_i \in U_{x_{i+1}}$ or $x_{i+1} \in U_{x_i}$ for all $i$. By Lemma 2, $x_i$ and $x_{i+1}$ are connectable by a path $w_i$.
As this is true for all $i$, $x_0$ and $x_n$ are connected by a path.


text:
Q: Where is the Arch Linux official package source repository? After searching Google and the wiki I can't seem to find it, but only links to the software repositories.

A: Found a link!

*

*Reference Subversion repository

*Browseable Git clone


text:
Q: Using tuples instead of boolean operators Is there a difference (in terms of performance, not readability) between the following ways of evaluating two (or more) conditions linked by and?
a == 1 and b == 2

or
(a,b) == (1,2)

The same for or:
a == 1 or b == 1

or
1 in (a,b)

Which way is preferable? The one using boolean operators or the other one using tuples?

A: These are some timings using python 2.7
In [29]: a = 1

In [30]: b = 2

In [31]: timeit a == 1 and b == 2
10000000 loops, best of 3: 82.2 ns per loop

In [32]: timeit (a,b) == (1,2)
10000000 loops, best of 3: 132 ns per loop

In [33]: timeit 1 in (a,b)
10000000 loops, best of 3: 118 ns per loop

And when the outcome is False:
In [37]: timeit a == 2 and b == 2
10000000 loops, best of 3: 52.2 ns per loop

In [38]: timeit 3 in (a,b)
10000000 loops, best of 3: 151 ns per loop

In [39]: timeit (a,b) == (2,2)
10000000 loops, best of 3: 144 ns per loop

a == 2 and b == 2 is faster as and is a short circuit operator
As per wim's comment using a set will be faster than checking the tuple for membership:
In [55]: timeit 3 in {a,b}
10000000 loops, best of 3: 92.9 ns per loop

A: Yes, there is a logical difference in that that using and/or are short-circuiting.
>>> def return1():
...     return 1
...
>>> def raises():
...     raise Exception('uh oh')
...
>>> a, b = 1, 2
>>> a == return1() or b == raises()
True
>>> b == return1() and a == raises()
False

Note the function which raises exception never gets called.  In both the other examples, we will have an unhandled exception:
>>> a, b == return1(), raises()
# raises Exception
>>> 1 in (return1(), raises())
# raises Exception ..

In the case of literals, this obviously doesn't make any difference to the flow and any performance differences are likely to be negligible.  I prefer the second style in this case.

A: Using and/or operators are almost always better in terms of performance (perhaps not for readability but that's another issue):
1. They avoid having to create tuple objects like you do in other examples which will be more costly in terms of space/time complexity
2. They short-circuit meaning there is a good chance you can avoid executing unnecessary portions of the code.


text:
Q: How can I access inputfields in TYPO3-6.2-backend to fill them with javascript variables? If you use the extension-builder there is no option to generate a button. How can you achieve to create a submit-button?
The function of the clicked button should be to read some filled inputfields and execute a javascript function with the input.
The result of this query should fill other empty input fields. The problem here for me is to identify the inputfields by id or name,
that i can fill them with the result of my query.
How can I acchieve that I can fill some backend inputfields with javascript variables by button click? I use TYPO3 version 6.2. How can I generate a simple submit button for this function?


text:
Q: pg_fetch_all для несуществующих записей Сейчас при запросе к базе данных использую функцию pg_fetch_all для сбора всех данных. Но проблема в том, что если я сделаю запрос по значению, которого в таблице не существует, то функция мне ничего не вернёт. Например, я делаю запрос ... IN ('moscow', 'saint-petersburg', 'khabarovsk'). И функция pg_fetch_all вернёт ассоциативный массив длинной в 3 элемента. Но если в таблице нет записи со значением поля saint-petersburg, то вернётся массив всего из двух записей, где на втором месте будет расположена информация о Хабаровске. А мне важна последовательность. То есть, нужно, чтобы функция не просто пропускала несуществующие записи, а вставляла вместо них пустой массив - array(). Как это сделать?

A: Не совсем уверен в правильности всего запроса целиком но направление точно задаст:
with tmp_data (id,value) as
  (VALUES
    (1,'moscow'),
    (2,'saint-petersburg'),
    (3,'khabarovsk')
  )
Select
  c.*
from
  tmp_data z
  left join cities_data c on z.value = c.page_id
order by tmp_data.id


text:
Q: My React component does not update in the Safari browser Thought everything was going great. Works perfectly in Chrome, FF, Edge, even IE 11!
The parent component holds all the sate. I pass the bets object to the child component which calculates a count to pass to the grandchild component to display.
The parent state 'bets' is an object with the keys as an ID and the value as an object.
The parent state is correctly changing when I interact with the app. Why will only Safari not update when the parent state changes? (on iOS and MacOS)
Parent
class ParentComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            bets: {}
        };
    }
}

Child
getBadgeCount = (league) => {
    const bets = this.props.bets;
    let count = 0;
    Object.keys(bets).map((bet) => bets[bet].event.league === league && count++);
    return count;
};

// ...

<ChildItem count={this.getBadgeCount(league)} />

GrandChild
class GrandChildComponent extends React.Component {
    render() {
        const { count } = this.props;
        return (

                    {count > 0 &&
{count}
}

        );
    }
}

I console.log the count inside the grandchild render and in the componentDidUpdate and it shows the right number. Is there something apple/safari specific with react I am missing?

A: In the case where there are variables being changed based on which you can switch between the styles (opacity: 1 or opacity: 0.99) You can try adding a key to the element which is not being updated in Safari/iOS.

{Count}

I ran into the same problem, this seems to work for now.

A: So I did solve the very bizarre issue after a few days.
What was happening was I guess the engine in the Safari browser was not re-rendering the little badge icon correctly. I would print out the value inside the DOM, OUTSIDE of the styled badge I was using, and the number would update as expected... Leading me to believe the issue was related to styles.
THEN after removing what I thought was the CSS causing the issue, I noticed that it looked like safari was 'partially' updating the value in the badge. It appears to have half re-rendered, and the previous number collides with the new value... Not sure if this is some obscure problem with the render engine?

After adding and removing all the CSS one by one, the issue remained so I decided to trick the browser to 'force' render with a simple calculation inside the grandchild where it was being rendered:
const safariRenderHack = { opacity: count % 2 ? 1 : 0.99 };

{count}

Not a great solution but oh well I guess it's fixed. ha

A: I just run into similar problem.
Safari didn't re-render some texts implemented as:
{someValue}

On 'someValue' field update, reactJS worked fine (element was requested to render) but Safari re-renders only area of new value (shorter than previous). UI glitches :-/
If I done anything to CSS via Developer tools, element has been rendered again and looks fine :-/
After some tries, I luckily used a 'display: block;' style property and it starts to re-rendering absolutely fine. Also 'display: inline-block;' will fix that problem too, if it is needed to be used.

A: I had a similar problem where a center positioned span using flexbox inside a div wasn't updating correctly in Safari.
Restyling this div to use display:block solved this rendering issue so this might be worth looking into if anyone runs into the same problem in the future.
P.S. Looking at the styling code now, making the change was actually a much cleaner solution as it reduced the amount of lines from 4 to 1 but this might not be the case for all scenarios of course.
before:
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;

after: (is a div so display:block is already used)
text-align: center;

A: When using map function , React looks at the keys :
To identify which items have changed, are added, or are removed.
Solution :

*

*Now, As you use map function u must Add Key to the div inside map .

*Use a key variable that is connected to the logic behind clicking , so that when clicking the key , the variable is updated and so React will rerender this grandchild div .
As the following code :

{Count}

PS : I discourage to use Date as a key , because I f u are clicking quickly it glitches , while if u are connecting it with a state with the logic behind clicking , it won't .

A: this may help you:
will-change: transform;

A: I know it may be late but what helped me with Safari not re-rendering reused components was:
will-change: opacity;
You may have to experiment which element in your HTML hierarchy to apply this to.
It makes no sense because no opacity was being changed in my case but it did fix the problem. Thank you, Apple...

A: We also ran into this problem. So, I did a short research about it and got the gist as follows:

*

*It works by providing the unique key to the element(key={new Date()} works bcz unique even with seconds) which is not rerendering properly say a description as text inside it that changes by button or an event.

*So what I got as a gist basically, providing the individual key make new dom element to react during reconcilation process rather than changing same value inside the element so basically that element showing object is made unique instead of changing value inside that dom element so I think safari specific it is as it is holding state of the element rendering dynamically. So after providing the key prop you are basically rendering the unique different element(obviously with different text/object inside it). This basically utilizes here the concept of keys while we render a list in react component.


text:
Q: Unsupported major.minor version 51.0 while executing JSP I am trying to deploy my JSP and java files on the server. But when I try to access the jsp I get the error msg
 javax.servlet.ServletException: java.lang.UnsupportedClassVersionError: com/usct/db/DBConnect : Unsupported major.minor version 51.0

I read a few posts and found out that this is due to difference in Java version on the two different platforms but I am using JAVA 1.7 on my server and my client when I do
java -version

in my jdk/bin it shows that the java version is 1.7.0_10 and
Java SE Runtime Environment (build 1.7.0_10-b18)

Can someone please help me with this issue?
Thank you

A:
... but I am using JAVA 1.7 on my server and my client when I do ...

The most likely explanation is that you are actually using Java 1.6 or earlier ... despite what you think.  In other words, when you run java -version from the command-line, you are getting a different Java installation to the one that is being used to run your web container.
(If you are on a Linux system, you should be able to tell which JVM is being used by running ps -efl and greping for "java" or similar.  Alternatively, use the approach suggested by @dbf.)
It is worth noting that the version of Java on the client is not relevant.  The exception is occurring on the server side.
Reference: How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version
- explains the general problem and solution.

A: java.lang.UnsupportedClassVersionError error occurs due to higher JDK during compile time and lower JDK during runtime.
Java Version     Major Version

 Java 4               48.0
 Java 5               49.0
 Java 6               50.0
 Java 7               51.0

So if you compile your Java source file with javac of JDK 1.7 it will
  create class files with major version 51.0 and if you run those class
  files with Java 1.6 it will throw
  java.lang.unsupportedclassversionerror unsupported major.minor version
  51.0 error

Try Compiling with older JDK or Upgrade the JRE.
More more information visit.

A: I believe  com/usct/db/DBConnect is not a class provided by Java. And hence the reason of your error is not the version of jdk and jre on both your coding and execution environment. It seems the jar you used for the class DBConnect on your client and environment are of different java versions.

A: Try to print System.getProperty("java.version") from your JSP to check what version is actually used by your server.


text:
Q: Peterson's algorithm: Can deadlock occur if in peterson's algo, A process is preempted just after comming out of critical region before setting its flag to false. Then will not be there a deadlock. ??
plz help !

A: No deadlock. That's why we all learn this theoretical algorithm at schools.
note: You can encounter deadlock anywhere if you do something wrong. But it is not caused by a bug or property of this algorithm.

A: This cannot cause deadlock, because there is nothing that is blocking the process which just exited the critical section from proceeding.


text:
Q: XSL Transformation Solution In my mapping project, I have a xsd based on this xml structure for source. Note the capitalized node names and attribute values:
<ROOT>
    <INPUT>
        <NODEA
            ATT1="xxx"
            ATT2="xxx" />
        <NODEB
            ATT1="xxx"
            ATT2="xxx" />
    </INPUT>
</ROOT>

And other xsd based on this xml for target. Note the lowercase names and element values:
<operation>
    <input>
        <nodea>
            <att1>xxx</att1>
            <att2>xxx</att2>
        </nodea>
        <nodeb>
            <att1>xxx</att1>
            <att2>xxx</att2>
        </nodeb>
    </input>
</operation>

How can I get an XSL transformation, grouping by tree nodes, similar like this, with Altova MapForce 2017? Note the node comments and the name of variables:
<xsl:template match="/ROOT">
    <operation>
        <input>
            <xsl:for-each select="INPUT">
                <!-- NODEA -->
                <xsl:for-each select="NODEA">
                    <!-- ATT1 -->
                    <xsl:for-each select="@ATT1">
                        <xsl:variable name="v_ATT1" select="."/>
                        <att1>
                            <xsl:value-of select="string($v_ATT1)"/>
                        </att1>
                    </xsl:for-each>
                    <!-- ATT2 -->
                    <xsl:for-each select="@ATT2">
                        <xsl:variable name="v_ATT2" select="."/>
                        <att2>
                            <xsl:value-of select="string($v_ATT2)"/>
                        </att2>
                    </xsl:for-each>
                </xsl:for-each>
                <!-- NODEB -->
                <xsl:for-each select="NODEB">
                    <!-- ATT1 -->
                    ...
                    <!-- ATT2 -->
                    ...
                </xsl:for-each>
            </xsl:for-each>
        </input>
    </operation>
</xsl:template>

The Altova MapForce creates this different solution:
<xsl:stylesheet ... >
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/">
        <xsl:variable name="var1_initial" select="."/>
        <operation xmlns="...">
            <xsl:attribute ...>
            <input>
                <xsl:for-each select="*[local-name()='ROOT' and namespace-uri()='']">
                    <xsl:variable name="var2_cur" select="."/>
                    <att1>
                        <xsl:value-of select="*[local-name()='INPUT' and namespace-uri()='']/*[local-name()='NODEA' and namespace-uri()='']/@ATT1"/>
                    </att1>
                    ...
                </xsl:for-each>
            </input>
        </operation>
    </xsl:template>
</xsl:stylesheet>

A: If your purpose is to transform the first XML into the second one, then why don't you do simply:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:param name="upper-case" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>
<xsl:param name="lower-case" select="'abcdefghijklmnopqrstuvwxyz'"/>

<xsl:template match="/ROOT">
    <operation>
        <xsl:apply-templates/>
    </operation>
</xsl:template>

<xsl:template match="*">
    <xsl:element name="{translate(name(), $upper-case, $lower-case)}">
        <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
</xsl:template>

<xsl:template match="@*">
    <xsl:element name="{translate(name(), $upper-case, $lower-case)}">
        <xsl:value-of select="."/>
    </xsl:element>
</xsl:template>

</xsl:stylesheet>

There is no grouping involved here - just renaming nodes and converting attributes to elements.


text:
Q: Why does Avg. Page Load Time is Zero on Google Analytics? I have recently connected to GA to track usage and my site view would less than 1000 views per day. I would like to see my site "Avg. Page Load Time" but it is always showing zero. What needs to done to get Avg. Page Load Time ?
I have referred How to set up page speed logging for google analytics in analytics.js but i don't have permission to Modify the GA code in the site. Is there any other option to get Avg. Page Load Time ?
Question:
Please see below that got Avg. Page Load Time for first landing page but remaining pages still 0 and my question is When will get Avg. Page Load Time for remaining pages(Please give me example to any one page) ?

A: The best solution to obtain a statistically significant value (or as much as possible in Google Analytics) is that of the link you entered.
10.000 page views should surely show data even with the default setting (1%).
To understand if the data you will be looking at makes sense, create a custom report with dimension Browser and metrics Avg Page Load Time (sec) and Page Load sample like this:

In this way you see if the sample is low, so the data is not very reliable.
This is the example for your second question (directly from Demo Account of Google Merchandise Store):

About your new screenshot: if you try to create a custom report with Avg. Page Load Time and Page Load Sample you will see that for that pages (with Avg. Page Load Time equals 0) the sample is 0, so the page load time cannot be calculated.


text:
Q: Where I can find the best best step by step training for building LSTM in Keras? Team,
I wonder of anyone has found a good (for dummies :-) documentation for creating LSTM networks in Keras? Specifically about the expected size of the input, layers and output. E.g. Expected input batch shape: (batch_size, timesteps, data_dim). The Keras.io documentation isn't really clear. I'm using the Keras visualization (this is helping me).

A: I have used http://machinelearningmastery.com a lot.
Some examples regarding LSTM networks:
http://machinelearningmastery.com/sequence-classification-lstm-recurrent-neural-networks-python-keras/
http://machinelearningmastery.com/understanding-stateful-lstm-recurrent-neural-networks-python-keras/
Good luck!

A: Basically, a good way to understand the batch size, clases, timesteps and data dim using pandas DataFrames is available in the following question


text:
Q: browser in host can not see vagrant box, portforward does not work I have installed Vagrant in my Window XP, and in my Vagrantfile I have:
Vagrant::Config.run do |config|
  # Setup the box
  config.vm.box = "lucid32"
  config.vm.forward_port 80, 8080
  config.vm.network :hostonly, "192.168.10.200"
end

But I see no sign of my vagrant box when I type "http://192.168.10.200:8080" in browser.
IP address of the virtual box is correct, because from within the vbox, I have:
vagrant@lucid32:~$ ifconfig
....
eth1      Link encap:Ethernet  HWaddr 08:00:27:79:c5:4b
          inet addr:192.168.10.200  Bcast:192.168.10.255  Mask:255.255.255.0

There seem to be no firewall problem because if I type
vagrant@lucid32:~$ curl 'http://google.com'

it works fine.
I have read Vagrant's port forwarding not working
and tried:
vagrant@lucid32:~$ curl 'http://localhost:80'
curl: (7) couldn't connect to host

and also
vagrant@lucid32:~$ curl 'http://localhost:8080'
curl: (7) couldn't connect to host

So, looks like port forward is not working...
If you know what I can do so I can access my vbox from host browser, can you help me?
Thanks in advance

A: If you just started a Vagrant box with this Vagrantfile, there is nothing more than an empty Ubuntu Lucid, which does not run any service yet. So there is nothing served on port 80, this is why there is nothing to see either from inside the box on port 80 or the host machine on 8080.
For you Vagrant machine to provide some services (such as a web server on port 80), you have to do some provisioning. You can do it manually or using Chef or Puppet which are hooked into Vagrant's up process.

A: I had a similar problem. Sometimes using port forwarding for ports below 2000 is a problem. What worked for me is choosing ports that are above 2000. So my vagrantfile now looks like:
config.vm.network :forwarded_port, host: 4500, guest: 9000

Typing localhost:4500 on my host machine now just works fine. It seems like you are on an older version of vagrant than mine, so you can edit your vagrant file to something like
config.vm.forward_port 9000, 4500

Now typing localhost:4500 on your host machine should work fine.
Good luck,


text:
Q: Vertical space before and after align environment I am wondering if it is possible in LaTeX to generally adjust the spacing before and after math in the align environment from amsmath.
From the Mathmode-guide (by Herbert Voss) I gather that \belowdisplayskip and friends should do the job, but manipulating them doesn't yield any visible results.

A: It has a pretty clear effect to me:
\hrule
\begin{align}
f(x)&=x
\end{align}
\hrule
\vskip1cm
\belowdisplayskip=0pt
\hrule
\begin{align}
f(x)&=x
\end{align}
\hrule

Can you provide a minimal working example where it doesn't?


text:
Q: How can I put many script-generated records in PostgreSQL quickly from node.js? The following code, which inserts 200,000 records into PostgreSQL server from node.js, is taking about 17 minutes on my laptop PC, which feels horribly slow.
var pg = require('pg');
var Client = pg.Client;
var async = require('async');

var client = new Client(connectionString);
client.connect();

var rollback = function(client) {
  client.query('ROLLBACK', function() {
    client.end();
    process.kill();
  });
};

client.query('BEGIN',function(err,result){
  if(err){ console.error(err); rollback(client);};
  async.waterfall([
    function(cb){
      client.query('DROP INDEX idx',function(err,result){
        client.query('TRUNCATE TABLE tbl',function(err,result){
          async.forEach(values,function(value,valueNext){
            client.query('INSERT INTO tbl ('
                         + 'col1,'
                         + 'col2) VALUES ($1,$2)',[
                           value,
                           generatedSomething(value)
                         ],function(err){
                           valueNext();
                         });
          },function(err,result){
            if(err){ console.error(err); rollback(client);cb(false);return;};
            client.query('CREATE INDEX idx ON tbl',function(err,result){
              cb(null);
            });
          });
        });
      });
    });
  },
],function(err){
  client.query('COMMIT', client.end.bind(client));
});

There are some strategies I've applied to speed up.

*

*Drop all indices before insertion, create it after all insertion is done ... ok

*Use TRUNCATE TABLE instead of DELETE FROM ... ok

*Use COPY FROM instead of INSERT INTO ... not done

It seems that using COPY FROM instead of INSERT INTO will make effect, but it's used for imported CSV files, not for script-generated values.
So, does it mean that exporting script-generated values to temporary CSV file, and importing values using COPY FROM, is the most effictive way to insert values into PostgreSQL quickly?

A: copyFrom will return a WritableStream that you can append your values to as CSV, like:
var stream = client.copyFrom("COPY tbl (col1, col2) FROM STDIN WITH CSV");
stream.on('close', function() {
  client.query("COMMIT");
});
stream.on('error', rollback);
async.forEach(values, function(value, valueNext) {
  stream.write(value + "," + generatedSomething(value) + "\n");
});
stream.end();

Of course you will need to properly escape your values


text:
Q: How to take a backup and restore a subsite? How to take a backup and restore a sub-site inside a site collection of a SharePoint web application in SharePoint 2010 and 2013?

A: You can take advantage of Granular backup/restore feature in SP 2010. Or you can also use Export/Import command line to take specific subsite backup.
stsadm -o export -url  http://servername:portno/subsitename -filename mysubSiteBackup -includeusersecurity

Reference
Or Else
Powershell, But you have to make sure both web application have same set of features / solutions etc.Follow the below powershell commands.

*

*use export-spweb to export the subsite. export-spweb -identity "http://Subsite url" -path c:\export.cmp

*Now create a blank subsite on target site collection. Use new-spweb powershell. New-SPWeb http://somesite/subweb1

*Finally, you have to run the import-spweb to import the subsite. import-spweb -identity "http://Targetsubsite url" -path "c:\export.cmp"

A: You backup and restore sites using PowerShell (export-spweb or import-spweb).  You can also perform the backup in Central Admin. please refer to the article.
how to prepare to back up and restore SharePoint


text:
Q: How to install software on an offline ubuntu PC? My "online" PC is running windows Good evening everybody!
The "setup":
My "online PC":
Running Win10, I don't want to bother with installing another OS on that machine.
My "offline PC":
Running ubuntu 15.04 32bit. It has never been connected to the internet and I want to keep it that way.
The problem / question
I want to download software on my online windows PC, transfer it to the offline ubuntu PC (with a USB-drive or whatever) and then install it there.
I have only found tutorials and infos for running two ubuntu PCs and "exchanging" software between them, but not really anything for downloading stuff on a windows machine and then installing it on a ubuntu machine.
And like I said, I don't want to set up a second OS on that "online PC".
So, is there a (noob-friendly) way to do this?
(I have almost 0 experience with ubuntu or linux in general, I know that you can use "get-apt" to install software on ubuntu if an internet connection is available, or something like that)
Why?
I only have one PC (a laptop actually) that is connected to the internet, all my other devices are offline, for privacy / security reasons. (I know, I am a bit paranoid, and yes, I know that beeing paranoid and running Win10 is a bit of a contradiction)

A: This will depend greatly on how the software is distributed. If it's a .deb file, then you have a couple of options:

*

*Using a GUI, right-click on the .deb file

*Choose "Package Menu"⇢"Install Package" (it might be named something slightly different. I don't have a 15.04 installation anywhere to confirm with)

If you prefer to use the terminal, then:
sudo dpkg -i whatever.deb

You will want to have the installation media for Ubuntu nearby in the even there are unmet dependencies, as many of the core packages can be found on there.
The other option would be to compile the application from source. Generally the process goes:

*

*Download a file with a .tar.gz or .tar.bz2 extension

*Decompress it

*Check for dependencies with ./configure

*Compile with make

*Install with make install
Hopefully this will give you what you need.


text:
Q: Conditional Expectation of Gaussian Vector with Non Invertible Matrices Suppose $(X, Y)$ is a zero mean Gaussian vector with $X$ and $Y$ both vectors in their own right.  Define $\Sigma_Y = E(YY')$, $\Sigma_{XY} = E(XY')$.  In the case where $\Sigma_Y$ is invertible, we easily see that $$(X - \Sigma_{XY} \Sigma_Y^{-1}Y, Y)$$ is also Gaussian (as a linear transformation of $(X,Y)$) with zero covariance between its two parts (so that they are independent) and thus $$E(X |Y) = \Sigma_{XY} \Sigma_Y^{-1}Y$$
I am very confused however, as to what happens when $\Sigma_Y$ is NOT invertible.  Is $E(X |Y)$ still a linear transformation of $Y$?  If so, what would it be?  Does this somehow involve the Moore-Penrose inverse of $\Sigma_Y$?


text:
Q: How to make trained neural networks with nondeterministic output? I'm trying to figure out how to train a neural network to play a puzzle game, given no prior knowledge of the rules. I've previously used neural networks as classifiers, but they're essentially deterministic once trained. This is fine for action games like Mario, but there's a starting problem with a puzzles or games like go or chess where the initial setup is always the same. If the network's first attempt produces an illegal move, the board won't change, so a deterministic system will just keep trying the same illegal move.
Are there particular methods people use to make such a network try different outputs if the first is rejected? I considered having "number of moves" and/or "number of illegal moves blocked" inputs, to give a sense of time, but presumably there are more sophisticated techniques out there!

A: In your case, you would need to use techniques that come from reinforcement learning such as Deep Q learning. Indeed, these techniques are not deterministic and learn a policy that is not deterministic. The policy will first integrate the rules of the game to eventually choose a strategy that maximises the payoff. Of course, the environment will have to be properly defined for these methods to be effective.


text:
Q: Google charts - graph within a tooltip I currently have a scatter chart that has the html tooltips turned on. According to the API you can use any javascript (and html) in the tooltips. What I would like to do is allow the user to not only hover over a data point and see more information on it, but to also see another graph within the tooltip.

The parts enclosed with {{ }} are simply Django variables and likewise, {% %} are Django logic statements. If anyone has any ideas about how to go about this I'd greatly appreciate it.

A: Solved the problem by using the graph to png technique as suggested by JeremyFaller. My answer involves some Django, but I believe most people will get the general idea for php etc.
I have only included the relevant parts for getting graphs to show up in tooltips. Likewise, there is important information in the comments of the code. Scroll across to you don't miss any.
This first bit is just a default chart (not dynamically created from a DB).

var encoded_img;
var copy_of_data_list;
google.load("visualization", "1", {packages: ["corechart", "table"]});
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
    // Create and populate the data table.
    var data = google.visualization.arrayToDataTable([
        ['x', 'Cats', 'Blanket 1', 'Blanket 2'],
        ['A', 1, 1, 0.5],
        ['B', 2, 0.5, 1],
        ['C', 4, 1, 0.5],
        ['D', 8, 0.5, 1],
        ['E', 7, 1, 0.5],
        ['F', 7, 0.5, 1],
        ['G', 8, 1, 0.5],
        ['H', 4, 0.5, 1],
        ['I', 2, 1, 0.5],
        ['J', 3.5, 0.5, 1],
        ['K', 3, 1, 0.5],
        ['L', 3.5, 0.5, 1],
        ['M', 1, 1, 0.5],
        ['N', 1, 0.5, 1]
    ]);

    // Create and draw the visualization.
    var chart_divB = document.getElementById('chart_divB'); //chart_divB is hidden
    var chartB = new google.visualization.LineChart(chart_divB)
    google.visualization.events.addListener(chartB, 'ready', function () {
        encoded_img = '

'; //Creates the encoded img
    });
    var options = {title: 'Something random and cutsie about cats',
        width: 600,
        height: 400
    };

    chartB.draw(data, options); //Draws it in the hidden div (required for the png trick)
    copy_of_data_list ={{ main_graph_list_of_lists|safe }} //My Django data from a db
    for (var i = 0; i < copy_of_data_list.length; i++) {
        copy_of_data_list[i][2 * i + 2] += encoded_img; //Adds the encoded png image to the correct tooltip columns (most people will just have one, but I have other things going on)
    }
}

This is the second 'proper' chart which is visible and has tooltips.
google.load("visualization", "1", {packages: ["corechart", "table"]});
    google.setOnLoadCallback(drawChart);
    var data;
    function drawChart() {
        data = new google.visualization.DataTable();

        data.addColumn('number', 'X');
        {% for column in num_columns %} //More stuff that is not specifically related to this problem
            data.addColumn('number', 'Y');
            data.addColumn({type: 'string', label: 'Probe Details', role: 'tooltip', 'p': {'html': true}});//It is essential that the tooltip column/s is html enabled
        {% endfor %}
        data.addRows(copy_of_data_list); //The modified data thanks to the last 'chart'

        var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    }

Taking this beyond just one tooltip chart
This technique of using the png encoded images can be used to create different charts for each of the tooltips. By creating N hidden divs, each with their own unique id - a small modification on what I have done above can be used to achieve this. Hint: loop from the getting of the element by ID to the drawing of the chart N times (number of tooltips you have). For each of these hidden divs, with their own unique ids, you can then basically just draw hidden graphs and then convert them to pngs.
Note: if people want a better example, I will make one upon request if they can't get different tooltip charts working.


text:
Q: Force webpage to use a specific font I have created a question mark button using the Arial font.
The CSS looks like this:
.question {
    font: bold 24px Arial;
}

It appears correctly on almost all browsers, as this screenshot shows.

However, newer versions of Android use the Roboto font face instead of Arial. The question mark is now off-center and the wrong width.

My question: is it possible to force the browser to use Arial?

A: You cannot force a device/computer which doesn't have Arial installed to use it. You would have to rely on webfonts to use Arial everywhere.
Also, your syntax is wrong, you should be using the shorthand property font, and not font-family (which is only used to specify the font face and potential fallbacks), like so:
.question {
    font: bold 24px Arial, sans-serif;
}


text:
Q: How can I speed up my Android App testing If have an app release in the playstore and whenever I am working on updates, my testcycles take way too long.
The problem is, if I want to copy my own built apk to my phone, it recognizes it as may apk from the playstore and asks if I want to update it. If I try to update, it stops and says it could not be installed.
So what I have to do is upload my app to google dev console als intern test track and wait until it is there as an update on my phone. This can take nearly an hour. So if I want to test simple stuff, I have to wait nearly an hour to see the results. That is not practicable.
Is there any way to fasten my testing workflow up?
I think I am missing a really simple thing right now.
Currently I am working with some google play game services. Maybe that makes any difference.

A: i think you can create an "RC" version, as long as it maintain the same app package and send the url to download it via email to the testers

A: Ok i found a solution. Not the best, but it is a solution.
I have to delete the app from my phone and then i can install it via ADB or just send the APK via email and install it. That helps to speed things up.
And Bobby Prabowo posted a link to deploygate.com
I will check this out. Maybe that is a better solution.


text:
Q: Python Loops and counter Here's my code;
mood = 0
if mood == 5:
     mood = 4
# I don't want the mood going over four

Here is how the mood increases;
moode = raw_input("how are you").lower()
if 'bad' in moode:
    mood += 1
    print ('You have said that %s times today')%(mood)

The problem is that if you say it 5 times, she replies 'you have said it 5 times' but I don't want mood to go over four?

A: You need to check the value of mood after you increment it.
mood = 0
if 'bad' in moode:
    mood += 1
    if mood > 4:
        mood = 4
    print ('You have said that %s times today')%(name)

or as @arsajii mentioned - don't even both incrementing if it's already 4 or above
mood = 0
if 'bad' in moode:
    if mood < 4:
        mood += 1
    print ('You have said that %s times today')%(name)


text:
Q: Asterisk ODBC: Why is "Last connection attempt: 1970-01-01 01:00:00"? I am using Asterisk 13.23.1 and I have configured ODBC successfully - everything is working fine.
But I wonder why odbc show always shows
Last connection attempt: 1970-01-01 01:00:00
Why is the date never updated?

A: Connection attempt filled by res_odbc only on re-connection.
So that just mean have been connected from first try.


text:
Q: ¿Por que mi menú dinámico no se actualiza al momento de cargarlo con javascript? Estoy creando un menú dinámico, trae los datos correctamente a la pantalla pero no me carga con las funciones de desplegar y contraer el menú, como cargara sin ningún evento. Estoy usando la plantilla Admin LTE 2.
Note lo siguiente:
En la pantalla cuando inspecciono el elemento.

Pero si le doy "ver código fuente de la página" me muestra esto:

Actualización 1:

    function GenerarMenus(id, esSub) {
        var menuGenrado = '';
        if (esSub) {
            menuGenrado = '
';
        }else {
            menuGenrado = '
';
        }
        //Obtengo los menus papas
        ObtenerMenus(id);
        if (menus != undefined) {
            $.each(menus, function (i, v) {
                var subMenu = GenerarMenus(v.id, true);
                if (subMenu.length == 0) {
                    if(v.id_padre == 0){
                        menuGenrado += '
 ' + v.titulo + '';
                    }else{
                        menuGenrado += '
--> ' + v.titulo + '';
                    }
                } else {
                    if(v.id_padre == 0){
                        menuGenrado += '
 ' + v.titulo + '';
                        menuGenrado += subMenu;
                    }else{
                        menuGenrado += '
----> ' + v.titulo + '';
                        menuGenrado += subMenu;
                    }

                }
                menuGenrado += '
';
            });
        }
        menuGenrado += '
'
        if (menuGenrado == '

' || menuGenrado == '

') {
            menuGenrado = '';
        }
        return menuGenrado;
    }

    var menus;
    var todoMenus;
    $(document).ready(function () {
        ObtenerSidebar();
        Contraer();
    });

    function ObtenerSidebar() {
        ObtenerTodoMenu();
        //FIN ATAJOS
        $("#main-nav").append(GenerarMenus(0, false));
    }

    function Contraer(){
        $(".nav-stacked").css("display","none");
        $("#menu").css("display","block");
    }

    function ObtenerTodoMenu() {
        //Genero el menú de ejemplo aqui
        todoMenus = [
                {
                  "id": 1,
                  "id_padre": 0,
                  "icono": "fa fa-dashboard fa-fw",
                  "link": "/",
                  "titulo": "Tablero",
                  "status": true
                },
                {
                  "id": 2,
                  "id_padre": 0,
                  "icono": "fa fa-tasks fa-fw",
                  "link": "#",
                  "titulo": "Procesos",
                  "status": true
                },
                {
                  "id": 3,
                  "id_padre": 2,
                  "icono": "fa fa-list-ol fa-fw",
                  "link": "/lotes",
                  "titulo": "Lotes",
                  "status": true
                },
                {
                  "id": 4,
                  "id_padre": 2,
                  "icono": "fa fa-eraser fa-fw",
                  "link": "/limpieza",
                  "titulo": "Limpieza",
                  "status": true
                },
                {
                  "id": 5,
                  "id_padre": 2,
                  "icono": "fa fa-stop fa-fw",
                  "link": "/paradas",
                  "titulo": "Paradas",
                  "status": true
                },
                {
                  "id": 6,
                  "id_padre": 2,
                  "icono": "fa fa-wrench fa-fw",
                  "link": "#",
                  "titulo": "Mantenimiento",
                  "status": true
                },
                {
                  "id": 7,
                  "id_padre": 6,
                  "icono": "fa fa-file-text fa-fw",
                  "link": "/planes",
                  "titulo": "Planes",
                  "status": true
                },
                {
                  "id": 8,
                  "id_padre": 6,
                  "icono": "fa fa-calendar fa-fw",
                  "link": "/calendario",
                  "titulo": "Calendario",
                  "status": true
                }
        ];
    }

    function ObtenerMenus(id) {
        menus = [];
        $.each(todoMenus, function (i, v) {
            if (v.id_padre == id) {
                menus.push(v);
            }
        });
    }

A: El error es porque en el core del Admin LTE 2 (es decir, en el archivo admin.min.js) se espera que dentro del sidebar:

*

*Solo los li que tienen sub-menu deben tener la clase treeview, es decir, <li class="treeview"....

*Y solo los ul que sean sub-menu deben tener la clase treeview-menu, es decir, <ul class="treeview-menu"...


text:
Q: Is Redis ZADD or ZSCORE atomic? If two Redis clients issue ZADD or ZSCORE commands concurrently, will it have race condition and mess up the set value? If it is not thread-safe, then I will need to protect the commands with a lock, right?
I read the ZSET API reference. Maybe I missed it, but I saw nowhere it mentions the thread-safety of ZSET commands.

A: I found an answer here. Basically Redis is single threaded and all commands will be queued and serialized, so there is no parallel command execution to worry about.


text:
Q: How to push JMX metrics using JMX exporter from Kafka consumer to prometheus How to push JMX metrics using JMX exporter from Kafka consumer to prometheus without making any change in kafka server side

A: Kafka server is not responsible for exposing consumer client metrics, and the JMX exporter is pulled, not pushed, depending on how you've configured the Prometheus server metrics scraper
As for how to get consumer metrics - add the JMX exporter to the JVM args when you run the consumer, just like any other Java client you may be monitoring, then modify your scraper to discover the consumer endpoint(s)

If you literally want to push data to Prometheus, that would require the PushGateway


text:
Q: if $E,F$, two bases are orthonormal then $T$ is unitary.
Let $T:V\to V$ and two bases of $V$: $E = \{v_1, \ldots, v_n \}$ and
  $F = \{T(v_1), \ldots, T(v_n)\}$.
Prove: $E,F$ are orthonormal implies $T$ is unitary.

So basically we want to prove that for every $v\in V$:$$TT^*(v) = 1_v \iff TT^*(v)-1_v(v) = 0 \iff (TT^*-1_v)(v)$$
First of all, it's a well-known fact that $TT^*-1_v$ is conjugate to itself. If we proved that for every $v\in V$: $$\langle TT^*(v)-1_v(v), v\rangle = 0 $$
It would imply that $TT^*-1_v \equiv 0$ and we're done.
So I'm stuck at this point (not sure if even this is the right/optimial way)

A: We can restate this relationship
$$\langle TT^*(v)-1_v(v), v\rangle = 0$$
as
$$\langle Tv, Tv\rangle = \langle v, v \rangle$$
using linearity and the definition of the adjoint.
Expressing the vector $v$ in terms of the given orthonormal basis $e_i$ we see that
\begin{eqnarray*}
\langle Tv, Tv\rangle &=& \langle T\sum v_i e_i, T\sum v_j e_j\rangle \\
&=& \langle \sum v_i T(e_i), \sum v_j T(e_j)\rangle \\
&=& \sum v_i\sum \overline{v_j}\langle  T(e_i),  T(e_j)\rangle \\
&=& \sum v_i\sum \overline{v_j}\delta_{ij} \\
&=& \langle v, v \rangle \\
\end{eqnarray*}


text:
Q: Why the Paperclip cause my WEBrick server collapse frequently? Well, I added Paperclip into my project in Rails 3.1 to handle the images and avatars.
I installed the Paperclip as gem.
In gemfile I wrote:
gem 'paperclip', :git => 'git://github.com/thoughtbot/paperclip.git',
                 :branch => 'rails3'

Well, I actually quite spent some effort and finally get the paperclip working correctly. However, during development, I have found that if I frequently refresh a webpage which has avatars within a short time, the WEBrick could soon collapse and turned down.
The error message is something like:

Ruby interpreter(CUI) 1.9.2p290 [i386-mingw32] has shut down.

My development environment is:
  Ruby 1.9
  Rails 3.1
  WIN7 32bit
Such frequent collapses really cause inconvenience. Does anyone know the solution?


text:
Q: cost of fprintf I am developing an embedded application in C++ for a platform with limited code/data RAM, but rather unlimited RAM for filesystem usage.
While looking for reducing the code size, I realized that excluding fprintf() lines contributed a lot to the size of generated code.
My questions are :
1. Why is the cost of fprintf so high ?
2. If I exclude the fprintf functionality, what would be the alternative to generate log files describing the occurances through the application run ?

A: It takes a reasonable amount of code to provide the full ANSI compliant printf functionality.
Some embedded environments offer several different versions of printf that are considerably smaller, as they only offer selected functionality.
For example, the IAR C/C++ Compiler for MSP430 (PDF), offers Tiny, Small, Large and Full implementations of the printf formatter, with the Tiny version only supporting the basic specifiers (c, d, i, o, p, s, u, X, x, and %) with no support for multibytes, floats, length modifiers, width and precision.
If your environment offers this choice then select the version of printf (and scanf) that matches your needs and be aware of the limitations.
If your environment does not offer this choice then take a look at the various "tiny" alternative printf implementations available (such as this one from Kustaa Nyholm of SpareTimeLabs).

A: I can think of three scenarios:

*

*Each time you remove a fprintf line the code size drops slightly, and when you remove the very last fprint it also drops slightly.

*When you remove the very last fprint the code size drops significantly.

*Every time you remove one instance of fprint the code size drops significantly.

In scenario 1, it isn't fprintf that is the culprit, but rather the string literals that you are passing to it. You need to get these strings out of your code, either by using very short, terse messages, or by storing the strings in a file and referencing them by some form of ID within the code (although this incurs performance hits)
In scenario 2, fprintf is (probably) the main culprit. It is quite a complex function that is capable of formatting all kinds of data types in all kinds of ways - so it takes quite a bit of code space. When you remove the last use of it the linker will eliminate it from the final binaries, making them smaller. Try using std::ofstream instead. If you only ever insert (for example) ints and strings to your output file, then only the code for handling ints and strings is linked in.
Scenario 3 is very unlikely - and would probably indicate that fprintf is being inlined wherever you use it.
Hope this helps

A: In embedded systems, printf can sometimes drag in all the floating point support for format strings like %f.
More intelligent environments will make the floating point options for printf an optional thing.
But even for integers, there's a lot of general purpose code in printf and you may find it's more compact to write your own routines, tailored to your specific needs, like:
outInt (char *buff, int intVal);
outChr (char *buff, char chVal);
outStr (char *buff, char *strVal);

and so on, for writing to buffers, then outBuff (char *buff) for sending it to a file or standard output.

For example, if you control the data being used (no string overflow, 16-bit twos complement integers and such), you can use the following functions:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void outChr (char *buff, char chVal) {
    *buff++ = chVal;
    *buff = '\0';
}

void outStr (char *buff, char *strVal) {
    strcpy (buff, strVal);
}

void outInt (char *buff, int intVal) {
    int divisor = 10000, printing = 0;

    // Special cases.

    if (intVal == -32768) { outStr (buff, "-32768"); return; }
    if (intVal ==      0) { outChr (buff,      '0'); return; }

    // Handle negatives.

    if (intVal < 0) { outChr (buff++, '-'); intVal = -intVal; }

    // Handle non-zero positives <= 32767.

    while (divisor > 0) {
        if ((intVal >= divisor) || printing) {
            outChr (buff++, "0123456789"[intVal/divisor]);
            printing = 1;
        }
        intVal = intVal % divisor;
        divisor /= 10;
    }
}

int main (int argc, char *argv[]) {
    char buff[1000];
    int i;
    for (i = 1; i < argc; i++) {
        outInt (buff, atoi (argv[i]));
        printf ("[%s] -> [%s]\n", argv[i], buff);
    }
    return 0;
}

Running this with:
pax$ tstprg 32767 10000 9999 10 9 1 0 -1 -9 -10 -99 -10000 -32767 -32768

outputs:
[32767] -> [32767]
[10000] -> [10000]
[9999] -> [9999]
[10] -> [10]
[9] -> [9]
[1] -> [1]
[0] -> [0]
[-1] -> [-1]
[-9] -> [-9]
[-10] -> [-10]
[-99] -> [-99]
[-10000] -> [-10000]
[-32767] -> [-32767]
[-32768] -> [-32768]

These functions should be relatively small in size since they're targeted to specific needs rather than the far more general printf family.

A: The answer to your first question depends on the compiler that you are using; you can only get a definitive answer by examining your compiler. As GrahamS pointed out, formatter implementation can be complicated.
Try using fputs instead of fprintf to avoid the formatter.


text:
Q: Modify loadbalanceinfo for RDS Session Collection Does anyone know how to change the loadbalanceinfo string for a RDS Session Host Remote Desktop collection?
Use case: we had a case today where something got corrupted in our RDS collection, and there was little info available on the errors that were being thrown except "delete the collection and recreate it."  Given that we had 70 people unable to work, that was our best option.
That is what I did, but, of course, it had a different loadbalanceinfo string in the RDP file for the new collection.  If we were using RDWeb or RemoteApp deployment to allow access, that's no big deal, but we have a large amount of HP ThinPro Linux thin clients, so it meant changing a test client's connection properties to reflect the new loadbalanceinfo string and then deploying new connections to all of the thin clients so they could connect to the new collection.
Additionally, we had many users who had downloaded the RDP file from RDWeb for the old collection to their desktop or something, and all of those had to be replaced as well.
In the case that this happens again, is there a way to change that string on the new collection so that it matches the old collection's string and no connection replacement is necessary?


text:
Q: Trying to send mail through mailx and postfix, but receiving nothing in inbox I'm trying to set up a type of notification system that will alert me when my website is down using crontab and mailx.  I went ahead and installed mailx on my server and then tried to send a simple test email by doing: mail -s "Testing" myemail.com < /dev/null, but I receive nothing in my inbox.  The only message I see after entering that command is mailx saying that the body is null, which is completely fine for this situation.
I started looking online and noticed that for mailx to work I need to setup an MTA using something like mutt or postfix, but my server is already configured with postfix so I would think that this would have gave me an error upon sending the email.
I really don't know much about mailx or postfix for that matter so it's a little difficult for me to debug this issue when there aren't any errors occurring.  If anyone knows why this would be happening, I would greatly appreciate it.  Thanks!

A: If the message is successfully passed off to postfix, there will be no immediate error.  Check mailq to see if the message is still in the mail queue, and look at /var/log/maillog (or equivalent) for delivery errors.
There could be many reasons why the message is not being delivered.  Two of the most common ones are (a) that your service provider blocks outbound mail connections in order to prevent spam, or (b) your mail provider is blocking connections from your server because it is a potential spam source, e.g. that IP address has been used for spam in the past and is on a blacklist.  You would need to check the logs in order to diagnose.
More generally, why not use a service like UptimeRobot or Hetrix Tools which do this and have a free tier?


text:
Q: How to make a TextArea change its height according to its content? I have a TextArea and I want its height to grow dynamically according to its content : so there is no scrollbar needed. How to achieve that ?

A: Use setGrowByContent(true); on the TextArea.


text:
Q: Switching between Full/Plain HTML view and setting default view I am developing a website that has a plain HTML version for older browsers (I know this is not a good practice, but my employers insisted).
I put a link on the footer of all pages to switch between the views. Then I use a session variable to store whether the user is in the Full Site mode or the Plain Site mode.
However, this session variable does not get destroyed when a user quit the website. Since I want the site to show the Full Site version by default, this is a problem. I don't want the Plain Site mode to be "remembered". But it is not possible to do a destroy_session() on page exit without javascript, and it would be inefficient.
Any ideas on how I can fix this problem?


text:
Q: Django on creating new model store records of existing user and its data I have created a model Customer:
class Customer(models.Model):
    name = models.CharField(max_length=20, db_index=True)
    address = models.CharField(max_length=100, blank=True)
    email = models.EmailField(max_length=100, blank=True)
    users = models.ManyToManyField(User, db_index=True)
    phone = models.IntegerFeild(max_length=100, blank=True)

as well as a new model called XYZ:
class XYZ(models.Model):
        customer = models.OneToOneFieldOneToOneField(Customer, on_delete=models.CASCADE)
        abc = models.CharField(max_length=10, default='x')
        user = models.OneToOneField(User, on_delete=models.CASCADE)

How should I insert data into this XYZ table for an existing Customer, without using manually Insert into the query? Is there any Django query or way to insert the existing customer records in the XYZ table?

A: Here's one way of doing it, As it is unclear how your data from XYZ is stored so I'm assuming static values.
Go into django shell. You can do this by running python manage.py shell
Now import your models
from yourapp.models import Customer, XYZ

Also import your user model
from django.contrib.auth.models import User
fetch the user object you want to add.
user = User.objects.get(username='your_username')

If you want admins you can do this
superusers = User.objects.filter(is_superuser=True) # This will get all the admins of your website. But beware this is a queryset(i.e list of user objects) if there is more than one admin for your site.
now you can create an entry for each of the customer object into your XYZ table.
Finally, depending on your requirement you can run this loop.
for customer in Customer.objects.all():
    XYZ.objects.create(customer=customer, abc="your string", user=user)

A: I think what you should do is these steps:

*

*python manage.py shell

*query all Customer
from path.to.your.models import Customer
customers = Customer.objects.filter(users=

*insert all XYZ
for c in customers:
if c.users.is_admin:
    xyz = XYZ(
        customer=c
        user=c.users
        )
    xyz.save()


text:
Q: NFS mount a directory from server node to client node In one of my assignments on CentOS 7, I am trying to NFS mount /home directory from management node to client node.
I have given the commands I have tried below.
I tried to disable firewall, but it's asking for password which I don't have, and so it didn't work. Then I made changes in the exports file as below, but nothing to my avail. PFB the commands I ran:
[user@node-1 ~]$ ssh -i ~/.ssh/key node-2
Last login: Wed Sep 19 12:56:36 2018 from 192.18.0.3
[user@node-2 ~]$ sudo mount -t nfs 192.18.0.3:/home /home
mount.nfs: access denied by server while mounting 192.18.0.3:/home
[user@node-2 ~]$ exit
logout
Connection to node-2 closed.
[user@node-1 ~]$ systemctl disable firewalld
==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-unit-files ===
Authentication is required to manage system service or unit files.
Authenticating as: Cloud User (user)
Password:
polkit-agent-helper-1: pam_authenticate failed: Authentication failure
==== AUTHENTICATION FAILED ===
Failed to execute operation: Access denied
[user@node-1 ~]$ sudo vi /etc/exports

The changes made in the exports file are as:
/home 192.18.0.*(rw,sync,no_root_squash,no_all_squash)

And then I tried updating the changes but got another error
[user@node-1 ~]$ exportfs -ra
exportfs: could not open /var/lib/nfs/.etab.lock for locking: errno 13
(Permission denied)
exportfs: can't lock /var/lib/nfs/etab for writing

Can anyone help me mount the /home directory from the management server to client server, please?

A: 192.18.0.* is not a valid ip or subnet. Try 192.18.0.0/24 instead.

*

*Note: the  192.18.0.0 - 192.18.194.255 ip range belongs to Oracle Corporation. Don't use it unless you're a worker at oracle.

A: To check what are the allowed IP networks run this command in node-1:
$ showmount -e localhost

or this in node-2
$ showmount -e node-1

You should see the IP networks actually allowed to mount each of the NFS exported directories in node-1.


text:
Q: Identity server 3 Windows authentication not working with current user In my mvc app integrated with identity server 3 with windows login. When i use that login with windows option its asking credentials popup (I attached screen shot.)
when i close the browser and reopen it again its asking. My windows session is not persistence.

*

*My Expected behaviour it should take my current system user session automatically.I am using windows server 2016 OS.

My code :
var metadataAddress = config.FederatedAuthenticationMetaAddress;
            var manager = new SyncConfigurationManager(new ConfigurationManager<WsFederationConfiguration>(metadataAddress));

            var wsFederation = new WsFederationAuthenticationOptions
            {
                AuthenticationType = "windows",
                Caption = "Windows",
                SignInAsAuthenticationType = signInAsType,
                  ConfigurationManager = manager,
                Wtrealm = "urn:idsrv3"
            };

   app.UseWsFederationAuthentication(wsFederation);

A: it is the behavior of a window due to the settings can be changed from internet options
to change it go for internet options--> security tab --> custom level--> scroll down and chose what fits for you like that :

and even you can force an option by AD group policy that what I did sot it greyed out for users
to do it through group policy :
open group policy management from your active directory and make a gpo and then edit and do the following :
The policy value for Computer Configuration -> Administrative Templates -> Windows Components -> Internet Explorer -> Internet Control Panel -> Security Page -> Internet Zone -> "Logon options"


text:
Q: Where should I ask questions about the installation of SSL certificates? I have questions regarding the installation of an SSL certificates, but I wasn't sure what site I should be using to ask these questions.  Should I be using Server Fault, Information Security, Stack Overflow, or another site to assist with this?

A: This is not a programming issue. It is an issue of using/installing a program.
If you want to install it on a server in a business environment, you can ask on Server Fault. Otherwise on Super User.


text:
Q: How to change the UIImage of a UIImageView from a subview? I want to change an image on a view, from a popup dialog of 4-6 icons (imagine like changing your image on a messenger application).
The way I implement this modal popup is by creating a new view at IB, with opacity on the background, and then I load this as a subview:
    IconsViewController *iconsViewController = [[IconsViewController alloc] initWithNibName:@"IconsView" bundle:nil];
[self.view addSubview:iconsViewController.view];

So, when the user touches an icon, I have
- (IBAction)iconIsSelected:(id)sender {
switch ([sender tag]) {
    case 1:
        [(ParentViewController*)[self superview] changeIcon];
        break;
    case 2:
        // same here..
        break;
    default:
        break;
}
[self.view removeFromSuperview];
[self release];

}
The changeIcon just sets the image to a corresponding icon.
As you can guess, this is not working - the changeIcon message never works.
I can't understand what am I doing wrong, any help much appreciated!

A: The superview of a view is a view, not a view controller, yet you cast the superview to be of class ParentViewController. If the view has no superview, it returns nil, and message to nil are no-ops (which explains why you don't crash there).
BTW, that [self release] at the end is highly suspicious.

A: You have a few choices here...
First one is create a property on your IconsViewController of type ParentViewController*, for example:
@property (readwrite,nonatomic,assign) ParentViewController* parentController; // weak reference

To break this down further:

*

*readwrite because we want to be able to access the value via [self parentController] but also change it via [iconsViewController setParentController:self]

*nonatomic because I'm not too worried about threading

*assign to make it a "weak reference" where the parent will not be retained by the child.  If they each retain the other, it could lead to memory leaks later because unless explicitly released you'd end up with a retain circle causing neither object to hit a zero retain count.

When you load from nib, set the property:
IconsViewController *iconsViewController = [[IconsViewController alloc] initWithNibName:@"IconsView" bundle:nil];
iconsViewController.parentController = self;

Then, call to it from inside of iconIsSelected like this:
[[self parentController] changeIcon];

Alternatively, you can create a delegate protocol:
@protocol IconViewSelectedDelegate (NSObject)

- (void) changeIcon;

@end

And use that protocol as a property, instead of the parent view controller type.  This is more abstract, but it keeps the design cleaner.  The parent view controller would then implement that delegate protocol, as one of many others.
Another option is to use NSNotificationCenter and publish/subscribe to events from your dynamic view.  This is the "loosest" coupling between the two objects, but it might be overkill for this scenario.


text:
Q: Convert Arduino Code to STM32 cubeide, I giving paramter setting of LoRa module which is e32 433t20d over the Arduino Nano with ebyte RF setting software. With this code Arduino work as middleman. I want to use same code with stm32. How to make same code over the stm32 nucle board f401RE with Cubeide? It looks very easy but I really new one at cubeide. Please help thanks
Arduino Code:
#include <SoftwareSerial.h>

SoftwareSerial fixSerial(10, 11); // RX, TX

#define M0 7
#define M1 6

void setup() {
  Serial.begin(9600);
  fixSerial.begin(9600);

  pinMode(M0, OUTPUT);
  pinMode(M1, OUTPUT);

  digitalWrite(M0, HIGH);       // E32 Modülleri için Aktif edin
  digitalWrite(M1, HIGH);
}

void loop() {
  if (Serial.available()) {
    fixSerial.write(Serial.read());
  }

  if (fixSerial.available()) {
    Serial.write(fixSerial.read());
  }
}

this is my first try but not succed.
while (1) {

    if (HAL_UART_Receive(&huart1, rx1_data, 1, HAL_MAX_DELAY) == HAL_OK) {
        HAL_UART_Transmit(&huart2, rx1_data, 1, HAL_MAX_DELAY);
    }

    if (HAL_UART_Receive(&huart2, rx2_data, 1, HAL_MAX_DELAY) == HAL_OK) {
        HAL_UART_Transmit(&huart1, rx2_data, 1, HAL_MAX_DELAY);
    }

All code:
/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * Copyright (c) 2023 STMicroelectronics.
 * All rights reserved.
 *
 * This software is licensed under terms that can be found in the LICENSE file
 * in the root directory of this software component.
 * If no LICENSE file comes with this software, it is provided AS-IS.
 *
 ******************************************************************************
 */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include <string.h>

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
UART_HandleTypeDef huart1;
UART_HandleTypeDef huart2;

/* USER CODE BEGIN PV */

uint8_t rx1_data[1];
uint8_t rx2_data[1];

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_USART1_UART_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
 * @brief  The application entry point.
 * @retval int
 */
int main(void) {
    /* USER CODE BEGIN 1 */

    /* USER CODE END 1 */

    /* MCU Configuration--------------------------------------------------------*/

    /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
    HAL_Init();

    /* USER CODE BEGIN Init */

    /* USER CODE END Init */

    /* Configure the system clock */
    SystemClock_Config();

    /* USER CODE BEGIN SysInit */

    /* USER CODE END SysInit */

    /* Initialize all configured peripherals */
    MX_GPIO_Init();
    MX_USART2_UART_Init();
    MX_USART1_UART_Init();
    /* USER CODE BEGIN 2 */

    HAL_GPIO_WritePin(M0_GPIO_Port, M0_Pin, GPIO_PIN_SET);
    HAL_GPIO_WritePin(M1_GPIO_Port, M1_Pin, GPIO_PIN_SET);

    /* USER CODE END 2 */

    /* Infinite loop */
    /* USER CODE BEGIN WHILE */
    while (1) {

        if (HAL_UART_Receive(&huart1, rx1_data, 1, HAL_MAX_DELAY) == HAL_OK) {
            HAL_UART_Transmit(&huart2, rx1_data, 1, HAL_MAX_DELAY);
        }

        if (HAL_UART_Receive(&huart2, rx2_data, 1, HAL_MAX_DELAY) == HAL_OK) {
            HAL_UART_Transmit(&huart1, rx2_data, 1, HAL_MAX_DELAY);
        }
    }
}

/**
 * @brief System Clock Configuration
 * @retval None
 */
void SystemClock_Config(void) {
    RCC_OscInitTypeDef RCC_OscInitStruct = { 0 };
    RCC_ClkInitTypeDef RCC_ClkInitStruct = { 0 };

    /** Configure the main internal regulator output voltage
     */
    __HAL_RCC_PWR_CLK_ENABLE();
    __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2);

    /** Initializes the RCC Oscillators according to the specified parameters
     * in the RCC_OscInitTypeDef structure.
     */
    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
    RCC_OscInitStruct.HSIState = RCC_HSI_ON;
    RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
    RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
    RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
    RCC_OscInitStruct.PLL.PLLM = 16;
    RCC_OscInitStruct.PLL.PLLN = 336;
    RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4;
    RCC_OscInitStruct.PLL.PLLQ = 7;
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
        Error_Handler();
    }

    /** Initializes the CPU, AHB and APB buses clocks
     */
    RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
            | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
    RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
    RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
    RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
    RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) {
        Error_Handler();
    }
}

/**
 * @brief USART1 Initialization Function
 * @param None
 * @retval None
 */
static void MX_USART1_UART_Init(void) {

    /* USER CODE BEGIN USART1_Init 0 */

    /* USER CODE END USART1_Init 0 */

    /* USER CODE BEGIN USART1_Init 1 */

    /* USER CODE END USART1_Init 1 */
    huart1.Instance = USART1;
    huart1.Init.BaudRate = 9600;
    huart1.Init.WordLength = UART_WORDLENGTH_8B;
    huart1.Init.StopBits = UART_STOPBITS_1;
    huart1.Init.Parity = UART_PARITY_NONE;
    huart1.Init.Mode = UART_MODE_TX_RX;
    huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    huart1.Init.OverSampling = UART_OVERSAMPLING_16;
    if (HAL_UART_Init(&huart1) != HAL_OK) {
        Error_Handler();
    }
    /* USER CODE BEGIN USART1_Init 2 */

    /* USER CODE END USART1_Init 2 */

}

/**
 * @brief USART2 Initialization Function
 * @param None
 * @retval None
 */
static void MX_USART2_UART_Init(void) {

    /* USER CODE BEGIN USART2_Init 0 */

    /* USER CODE END USART2_Init 0 */

    /* USER CODE BEGIN USART2_Init 1 */

    /* USER CODE END USART2_Init 1 */
    huart2.Instance = USART2;
    huart2.Init.BaudRate = 9600;
    huart2.Init.WordLength = UART_WORDLENGTH_8B;
    huart2.Init.StopBits = UART_STOPBITS_1;
    huart2.Init.Parity = UART_PARITY_NONE;
    huart2.Init.Mode = UART_MODE_TX_RX;
    huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    huart2.Init.OverSampling = UART_OVERSAMPLING_16;
    if (HAL_UART_Init(&huart2) != HAL_OK) {
        Error_Handler();
    }
    /* USER CODE BEGIN USART2_Init 2 */

    /* USER CODE END USART2_Init 2 */

}

/**
 * @brief GPIO Initialization Function
 * @param None
 * @retval None
 */
static void MX_GPIO_Init(void) {
    GPIO_InitTypeDef GPIO_InitStruct = { 0 };

    /* GPIO Ports Clock Enable */
    __HAL_RCC_GPIOC_CLK_ENABLE();
    __HAL_RCC_GPIOH_CLK_ENABLE();
    __HAL_RCC_GPIOA_CLK_ENABLE();
    __HAL_RCC_GPIOB_CLK_ENABLE();

    /*Configure GPIO pin Output Level */
    HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_RESET);

    /*Configure GPIO pin Output Level */
    HAL_GPIO_WritePin(GPIOB, M1_Pin | M0_Pin, GPIO_PIN_RESET);

    /*Configure GPIO pin : B1_Pin */
    GPIO_InitStruct.Pin = B1_Pin;
    GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);

    /*Configure GPIO pin : LD2_Pin */
    GPIO_InitStruct.Pin = LD2_Pin;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
    HAL_GPIO_Init(LD2_GPIO_Port, &GPIO_InitStruct);

    /*Configure GPIO pins : M1_Pin M0_Pin */
    GPIO_InitStruct.Pin = M1_Pin | M0_Pin;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
 * @brief  This function is executed in case of error occurrence.
 * @retval None
 */
void Error_Handler(void) {
    /* USER CODE BEGIN Error_Handler_Debug */
    /* User can add his own implementation to report the HAL error return state */
    __disable_irq();
    while (1) {
    }
    /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

A: I assume what you're trying to do is some kind of serial bridge so that your STM will receive data from UART1 and send to UART2 and vice versa.
Do you really need it? why not just take some USB -> serial adapter and connect it directly.
Anyway, going back to your code the issue is in your loop, HAL_UART_Receive basically waits until at least 1 byte is available (with HAL_MAX_DELAY) so in your code you just wait first byte from UART1, send it to UART2 and then switch to receiving from UART2. What if 2 or more bytes will come from UART1? Only the first one will be received and you will hang up waiting HAL_UART_Receive on UART2. Hope you get the idea. So what you can do here is:

*

*Use interrupts and setup you code in a way that the data will be expected from both UARTs simultaneously and then re-transmitted as it appears.

*Do something like you do in Arduino example where you first check is data is available and then move on to the next UART. Without hanging up waiting data forever using HAL_UART_Receive with HAL_MAX_DELAY


text:
Q: Theory of Mosfet P channel someone can help me explain why is ~6V at source terminal?

A: After turn on supply on source is 10V, but beetwen source and gate is -10V (gate is invers polarity for source). Transistor go into conduction state but with increase current the voltage on source terminal decrease. Potencial beetwen source and gate decrease and transistor will stop conduction (or better word, current flow decrease). Finaly transistor reach ballance and on source temrinal you get ~6V.
Because gate is always zero polarization of source have matter.

A: On that PMOS you shorted Drain and Gate making a "MOS diode".
A MOS diode will drop a voltage of about
\$V_{ds}= V_t + \sqrt(2I_d/K)\$
For the 2N6845 \$V_t\$ is between -2 V and -4 V, let's say \$V_t\$ is 3 V.
The second term depends on the current which can go quite high in your case due to the low series resistor of 1 ohm and the supply voltage of 10 V
The second term will then also be around 3 V resulting from the 4 A which is flowing.
If you make the 1 ohm resistor much higher in value (like 100 kohm) to make \$I_d\$ very small then you will get roughly: \$V_{ds}= V_t\$


text:
Q: AS3: How to dispatch from the document class? I have a pretty good handle on dispatching from classes other than the Document Class, but what happens when I want to dispatch an event from the Document class and have other classes listen to the document class broadcast?
It seems like there are several ways to approach this (i.e using a Singleton, using composition, using MovieClip(root)) I was just wondering what people find is the "best practice" way to do this?

A: I would do it like this:
in document class:

public function attachEventListener(event:String, callback:Function) {
   addEventListener(e, callback, false, 0, true);
}

If you don't want the other classes to have access to the document class, I would just put
addEventListener(Event.MY_EVENT, someClass.eventListenerFunction, false, 0, true); in the document class.
But obviously there's other ways to do it too. Depends on your preference.

A: Simple: Don't do it.
Why can't you just tell the objects what to do?  The Document Class is at the top of the hierarchy, it should be able to manipulate objects directly.  Objects lower down the hierarchy should dispatch up, but not down.

A: You should pass the document class as a paramenter to the others classes constructors.


text:
Q: applying diffrent color for same td in array

(scope.arrays || []).forEach(function (a) {
    gridTemplate = gridTemplate +
        '
' +
        '   ' + a.name + '	' +
        '   ' + a.address + '	' +
        '   ' + a.phno + '	' +
        '   ' + a.city + '	' +
        '   ' + a.pincode + '	' +
        '     | 	';
        '
';
});

output:
If arrays length is 2, then output will be like this.
name1 address1  phno1  city1  pincode1 | name2 address2 phno2 city2 pincode2
if i assign index value and increment inside loop and set color for even and off index means, colors are overriding.
i want to set different color for each array value. for eg, I want to set pink color for "name1 address1  phno1  city1  pincode1 " and red color for "name2 address2 phno2 city2 pincode2
"

A: You can have second argument as index in forEach. Use Modulo(%) to differentiate odd or even row and apply style accordingly.

var scope = {
  arrays: [
    {name: 'name1', address: 'address1', phno: 'phno1', city: 'city1', pincode: 'pincode1'},
    {name: 'name2', address: 'address2', phno: 'phno2', city: 'city2', pincode: 'pincode2'}
  ]
};

gridTemplate = "";
(scope.arrays || []).forEach(function(a, index) {
  gridTemplate = gridTemplate +
    '
' +
    '   ' + a.name + '	' +
    '   ' + a.address + '	' +
    '   ' + a.phno + '	' +
    '   ' + a.city + '	' +
    '   ' + a.pincode + '	' +
    '    | 	';
  '
';
});

document.getElementById("table").innerHTML = gridTemplate;


text:
Q: Line bundle defined by exceptional divisor; $\mathcal O(E) = \pi^*\mathcal O(-1)$ In Huybrechts book (Cor 2.5.6), it is shown:
Let $X=\mathbb C^{n}$ and $\hat X$ its blow-up at $0$. Then locally $\mathcal O(E) = \pi^*\mathcal O(-1)$, where $\pi: \hat X \to \mathbb P^{n-1}$.
I have trouble understanding the proof:

*

*Its clear, that $\bigcup_{(\ell,z)\in \hat X} \ell$ is a line
bundle. But why is it isomorphic to $\mathcal O(E)$?

*Why does the section $t(\ell,z)=((\ell,z),z)$ vanish with
multiplicity $1$?

*Why does 2. imply $\mathcal O(E) = \pi^*\mathcal O(-1)$?

I think 2. is simply because the function $z$ vanishes with multiplicity $1$ at $0$, but for the rest I have no clue.


text:
Q: Show filters from category & products, show filters relevant filter post selection (and non-relevant from active parent) & product count per filter I posted a similar question on 10 Jan 2020 (see here) but my problem/question has expanded since then and don't want S.O. police on my back ;)
This is the criteria:

*

*There are filter categories and there are filters belong to those categories.

*Each filter displays a count of how many products belong to a filter.

*The number of available filters need to reduce depending on active filter selection to not only those that still apply to the pool of products but those that are also relevant to child filters of other filter categories.

*There is a caveat to the above, if only one filter category has child filters selected then all the sibling filters (filters of the same filter category are to still display) until a filter from another filter category is made active.  Once a filter from another filter category/parent is selected the previous full list can reduce but previously select filters must remain active just show a count of zero if that's the case.

I think I'm really close with the SQL below but it will not correctly update the count of products belonging to each filter upon selection.  The only way I can get it to work is if I change the OR to an AND in the SQL below but this then will not show the other child filters belonging to a filter category that has an active child filter.
I have provided schema and sample data here, along with a fiddle of samehttp://sqlfiddle.com/#!9/afbd4d7/1/0:
CREATE TABLE `store_categories` (
  `categories_id` int(11) NOT NULL AUTO_INCREMENT,
  `parent_id` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`categories_id`),
  KEY `idx_categories_parent_id` (`parent_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `store_products` (
  `products_id` int(11) NOT NULL AUTO_INCREMENT,
  `products_status` tinyint(1) NOT NULL,
  PRIMARY KEY (`products_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `store_products_filters` (
  `pf_id` int(11) NOT NULL AUTO_INCREMENT,
  `pf_name` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL,
  `pf_sort` int(4) DEFAULT '0',
  `pf_to_pfc_id` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`pf_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `store_products_filters_categories` (
  `pfc_id` int(11) NOT NULL AUTO_INCREMENT,
  `pfc_name` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL,
  `pfc_sort` int(4) DEFAULT '0',
  PRIMARY KEY (`pfc_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `store_products_filters_to_products` (
  `pftp_id` int(11) NOT NULL AUTO_INCREMENT,
  `pftp_pf_id` int(11) DEFAULT NULL,
  `pftp_products_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`pftp_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `store_products_to_categories` (
  `products_id` int(11) NOT NULL,
  `categories_id` int(11) NOT NULL,
  PRIMARY KEY (`products_id`,`categories_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

INSERT INTO `store_categories` VALUES ('1', '0');
INSERT INTO `store_categories` VALUES ('2', '1');
INSERT INTO `store_categories` VALUES ('3', '0');
INSERT INTO `store_categories` VALUES ('4', '1');
INSERT INTO `store_categories` VALUES ('5', '0');
INSERT INTO `store_categories` VALUES ('6', '0');
INSERT INTO `store_products` VALUES ('1', '1');
INSERT INTO `store_products` VALUES ('2', '1');
INSERT INTO `store_products` VALUES ('3', '1');
INSERT INTO `store_products` VALUES ('4', '1');
INSERT INTO `store_products` VALUES ('5', '0');
INSERT INTO `store_products_filters` VALUES ('1', 'Small', '0', '1');
INSERT INTO `store_products_filters` VALUES ('2', 'Medium', '0', '1');
INSERT INTO `store_products_filters` VALUES ('3', 'Large', '0', '1');
INSERT INTO `store_products_filters` VALUES ('4', 'Extra Large', '0', '1');
INSERT INTO `store_products_filters` VALUES ('5', 'Circle', '0', '2');
INSERT INTO `store_products_filters` VALUES ('6', 'Square', '0', '2');
INSERT INTO `store_products_filters` VALUES ('7', 'Triangle', '0', '2');
INSERT INTO `store_products_filters` VALUES ('8', 'Red', '5000', '3');
INSERT INTO `store_products_filters` VALUES ('9', 'Blue', '5000', '3');
INSERT INTO `store_products_filters` VALUES ('10', 'Black', '2000', '3');
INSERT INTO `store_products_filters` VALUES ('11', 'Yellow', '5000', '3');
INSERT INTO `store_products_filters_categories` VALUES ('1', 'Size', '300');
INSERT INTO `store_products_filters_categories` VALUES ('2', 'Type', '100');
INSERT INTO `store_products_filters_categories` VALUES ('3', 'Colour', '400');
INSERT INTO `store_products_filters_to_products` VALUES ('1', '1', '1');
INSERT INTO `store_products_filters_to_products` VALUES ('2', '6', '1');
INSERT INTO `store_products_filters_to_products` VALUES ('3', '9', '1');
INSERT INTO `store_products_filters_to_products` VALUES ('4', '1', '2');
INSERT INTO `store_products_filters_to_products` VALUES ('5', '5', '2');
INSERT INTO `store_products_filters_to_products` VALUES ('6', '8', '2');
INSERT INTO `store_products_filters_to_products` VALUES ('7', '2', '3');
INSERT INTO `store_products_filters_to_products` VALUES ('8', '7', '3');
INSERT INTO `store_products_filters_to_products` VALUES ('9', '11', '3');
INSERT INTO `store_products_filters_to_products` VALUES ('10', '3', '4');
INSERT INTO `store_products_filters_to_products` VALUES ('11', '5', '4');
INSERT INTO `store_products_filters_to_products` VALUES ('12', '10', '4');
INSERT INTO `store_products_to_categories` VALUES ('1', '2');
INSERT INTO `store_products_to_categories` VALUES ('2', '2');
INSERT INTO `store_products_to_categories` VALUES ('3', '2');
INSERT INTO `store_products_to_categories` VALUES ('4', '2');
INSERT INTO `store_products_to_categories` VALUES ('5', '2');

There are 3 active filters, Small, Medium and Circle.
There are 2 "Small" sized products
There is 1 "Medium" sized product
There are 2 products that have a "Circle" filter applied to them but only one of those is "Small" and the other is "Large"
With Small, Medium filters applied I would expect/like Circle to show 1 but it shows a count of 2
OR pf.pf_id IN (
        SELECT
            pf_id
        FROM
            store_products_filters
        WHERE
            pf_to_pfc_id IN (1, 2)
    )

My thought so far is to remove the above SQL if filters from more than one filter category are active.
You can see an example of what I'm trying to achieve on this site https://www.ukpos.com/display-stands-frames-and-noticeboards which is powered by Magento.  I'm not sure if the filters are out of the box or a added plugin.
My full SQL below.
SELECT
    pfc.pfc_id,
    pfc.pfc_name,
    pf.pf_id,
    pf.pf_name,
    count(pftp.pftp_pf_id) AS products_in_filter
FROM
    store_products_filters_to_products pftp
LEFT JOIN store_products_filters pf ON pftp.pftp_pf_id = pf.pf_id
LEFT JOIN store_products_filters_categories pfc ON pf.pf_to_pfc_id = pfc_id
WHERE
    pftp_products_id IN (
        SELECT
            ptc.products_id
        FROM
            store_products_to_categories ptc
        LEFT JOIN store_products p ON ptc.products_id = p.products_id
        WHERE
            p.products_status = 1
        AND (
            ptc.categories_id = 1
            OR ptc.categories_id IN (
                SELECT
                    categories_id
                FROM
                    store_categories
                WHERE
                    parent_id = '1'
            )
        )
    )
AND (
    pf.pf_id IN (
        SELECT
            pftp_pf_id
        FROM
            store_products_filters_categories
        WHERE
            pftp_products_id IN (
                SELECT
                    pftp.pftp_products_id
                FROM
                    store_products_filters_to_products pftp
                JOIN store_products_filters pf ON pf.pf_id = pftp.pftp_pf_id
                GROUP BY
                    pftp.pftp_products_id
                HAVING
                    (
                        sum(pf.pf_id = 1) > 0
                        OR sum(pf.pf_id = 2) > 0
                    )
                AND (sum(pf.pf_id = 5) > 0)
            )
    )
    OR pf.pf_id IN (
        SELECT
            pf_id
        FROM
            store_products_filters
        WHERE
            pf_to_pfc_id IN (1, 2)
    )
)
GROUP BY
    pfc.pfc_id,
    pftp.pftp_pf_id
ORDER BY
    pfc.pfc_sort ASC,
    pfc.pfc_name ASC,
    pf.pf_sort ASC,
    pf.pf_name ASC